All files shortcuts.ts

100% Statements 41/41
100% Branches 31/31
100% Functions 1/1
100% Lines 41/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67          20x           20x 20x   20x 10x 10x 5x 2x   3x   5x 2x 3x 2x   1x   10x 10x 2x 2x 2x 2x 8x 7x 7x 7x 7x   2x 2x 1x   2x   1x 1x   2x 2x 1x   2x   1x 1x   1x 1x   7x 7x      
import React from 'react';
import { stopPropagation } from './utils';
import { SelectionText } from './SelectionText';
 
export default function shortcuts(e: React.KeyboardEvent<HTMLTextAreaElement>, indentWidth: number = 2) {
  const api = new SelectionText(e.target as HTMLTextAreaElement);
  /**
   * Support of shortcuts for React v16
   * https://github.com/uiwjs/react-textarea-code-editor/issues/128
   * https://blog.saeloun.com/2021/04/23/react-keyboard-event-code.html
   */
  const code = (e.code || e.nativeEvent.code).toLocaleLowerCase();
  const indent = ' '.repeat(indentWidth);
 
  if (code === 'tab') {
    stopPropagation(e);
    if (api.start === api.end) {
      if (e.shiftKey) {
        api.lineStarRemove(indent);
      } else {
        api.insertText(indent).position(api.start + indentWidth, api.end + indentWidth);
      }
    } else if (api.getSelectedValue().indexOf('\n') > -1 && e.shiftKey) {
      api.lineStarRemove(indent);
    } else if (api.getSelectedValue().indexOf('\n') > -1) {
      api.lineStarInstert(indent);
    } else {
      api.insertText(indent).position(api.start + indentWidth, api.end);
    }
    api.notifyChange();
  } else if (code === 'enter') {
    stopPropagation(e);
    const indent = `\n${api.getIndentText()}`;
    api.insertText(indent).position(api.start + indent.length, api.start + indent.length);
    api.notifyChange();
  } else if (code && /^(quote|backquote|bracketleft|digit9|comma)$/.test(code) && api.getSelectedValue()) {
    stopPropagation(e);
    const val = api.getSelectedValue();
    let txt = '';
    switch (code) {
      case 'quote':
        txt = `'${val}'`;
        if (e.shiftKey) {
          txt = `"${val}"`;
        }
        break;
      case 'backquote':
        txt = `\`${val}\``;
        break;
      case 'bracketleft':
        txt = `[${val}]`;
        if (e.shiftKey) {
          txt = `{${val}}`;
        }
        break;
      case 'digit9':
        txt = `(${val})`;
        break;
      case 'comma':
        txt = `<${val}>`;
        break;
    }
    api.insertText(txt);
    api.notifyChange();
  }
}