# All files / src/user-event/type parseKeys.ts

100% Statements 20/20
100% Branches 14/14
100% Functions 2/2
100% Lines 20/20

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
    424x

    26x

    26x
    26x
    72x
    71x
    2x

    69x
    69x

    23x

    72x
    1x

    71x
    11x
    11x
    1x

    10x

    60x
    1x

    59x

     const knownKeys = new Set(['Enter', 'Backspace']);

    export function parseKeys(text: string) {
      const result = [];

      let remainingText = text;
      while (remainingText) {
        const [token, rest] = getNextToken(remainingText);
        if (token.length > 1 && !knownKeys.has(token)) {
          throw new Error(`Unknown key "${token}" in "${text}"`);
        }

        result.push(token);
        remainingText = rest;
      }

      return result;
    }

    function getNextToken(text: string) {
      // Detect `{{` => escaped `{`
      if (text[0] === '{' && text[1] === '{') {
        return ['{', text.slice(2)];
      }

      // Detect `{key}` => special key
      if (text[0] === '{') {
        const endIndex = text.indexOf('}');
        if (endIndex === -1) {
          throw new Error(`Invalid key sequence "${text}"`);
        }

        return [text.slice(1, endIndex), text.slice(endIndex + 1)];
      }

      if (text[0] === '\n') {
        return ['Enter', text.slice(1)];
      }

      return [text[0], text.slice(1)];
    }