All files / virtual-keyboard/src/engine applyKey.ts

96.22% Statements 51/53
94.11% Branches 48/51
100% Functions 3/3
100% Lines 44/44

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184                                                                                  192x 192x               15x 15x   15x 1x 1x   14x                                                   96x 96x 96x 96x 96x 96x 96x   96x                 96x     96x             5x     91x 2x 1x                   89x 3x     86x 17x   1x 1x                 16x 15x 15x 15x                       69x 62x 3x 59x   69x   68x   68x 4x   64x 3x     61x 61x                  
import { buildKeyEvent } from "./resolveLayout";
import type {
  KeyboardModifiers,
  ResolvedKey,
  VirtualKeyEvent,
} from "../types";
 
/** A caret/selection-aware editing snapshot. */
export interface EditState {
  value: string;
  selectionStart: number;
  selectionEnd: number;
}
 
/** Behavior options that constrain an edit. */
export interface ApplyKeyOptions {
  /** Maximum length of the value; inserts that would exceed it are ignored. */
  maxLength?: number;
  /** Return `false` to reject an insertion. Receives the inserted text and the candidate value. */
  keyFilter?: (key: string, nextValue: string) => boolean;
  /** When true, Enter fires a submit instead of inserting a newline. */
  submitOnEnter?: boolean;
}
 
/** The result of applying a key to an {@link EditState}. */
export interface ApplyKeyResult {
  /** The value after the edit (unchanged when `changed` is false). */
  value: string;
  /** Caret/selection start after the edit. */
  selectionStart: number;
  /** Caret/selection end after the edit. */
  selectionEnd: number;
  /** Whether the value actually changed. */
  changed: boolean;
  /** Set when Enter fired as a submit (`submitOnEnter`). */
  submit: boolean;
  /** The synthetic event describing this press. */
  event: VirtualKeyEvent;
}
 
function clamp(n: number, min: number, max: number): number {
  Iif (Number.isNaN(n)) return min;
  return Math.max(min, Math.min(max, n));
}
 
/**
 * The number of UTF-16 code units to delete for a single "backspace" ending at
 * `index`. Removes a full surrogate pair (e.g. an emoji) as one unit.
 */
function backspaceUnits(value: string, index: number): number {
  Iif (index <= 0) return 0;
  const prev = value.charCodeAt(index - 1);
  // Low surrogate preceded by a high surrogate → delete both.
  if (prev >= 0xdc00 && prev <= 0xdfff && index >= 2) {
    const prev2 = value.charCodeAt(index - 2);
    Eif (prev2 >= 0xd800 && prev2 <= 0xdbff) return 2;
  }
  return 1;
}
 
/**
 * Apply a resolved key press to an editing snapshot, returning the next value
 * and caret position. Pure and DOM-free, so it is trivially unit-testable and
 * SSR-safe.
 *
 * Handles character insertion (respecting `maxLength` / `keyFilter`), Space,
 * Tab, Enter (newline or submit), Backspace (deletes the selection, else the
 * char before the caret), and Clear. Modifier / layout-switch / hide actions
 * are no-ops here (the hook handles those) and return `changed: false`.
 *
 * @example
 * ```ts
 * const key = resolveKey({ key: "a" }, mods);
 * applyKey(key, { value: "bc", selectionStart: 1, selectionEnd: 1 }, mods);
 * // → { value: "bac", selectionStart: 2, selectionEnd: 2, changed: true, ... }
 * ```
 */
export function applyKey(
  key: ResolvedKey,
  state: EditState,
  modifiers: KeyboardModifiers,
  options: ApplyKeyOptions = {}
): ApplyKeyResult {
  const event = buildKeyEvent(key, modifiers);
  const { value } = state;
  const len = value.length;
  const start = clamp(state.selectionStart, 0, len);
  const end = clamp(state.selectionEnd, start, len);
  const before = value.slice(0, start);
  const afterSelection = value.slice(end);
 
  const noChange: ApplyKeyResult = {
    value,
    selectionStart: start,
    selectionEnd: end,
    changed: false,
    submit: false,
    event,
  };
 
  const action = key.action;
 
  // Modifier / structural actions do not touch the value here.
  if (
    action === "shift" ||
    action === "capslock" ||
    action === "layer" ||
    action === "layout-switch" ||
    action === "hide"
  ) {
    return noChange;
  }
 
  if (action === "clear") {
    if (value === "") return noChange;
    return {
      value: "",
      selectionStart: 0,
      selectionEnd: 0,
      changed: true,
      submit: false,
      event,
    };
  }
 
  if (action === "enter" && options.submitOnEnter) {
    return { ...noChange, submit: true };
  }
 
  if (action === "backspace") {
    if (start !== end) {
      // Delete the active selection.
      const next = before + afterSelection;
      return {
        value: next,
        selectionStart: start,
        selectionEnd: start,
        changed: true,
        submit: false,
        event,
      };
    }
    if (start === 0) return noChange;
    const units = backspaceUnits(value, start);
    const caret = start - units;
    return {
      value: value.slice(0, caret) + afterSelection,
      selectionStart: caret,
      selectionEnd: caret,
      changed: true,
      submit: false,
      event,
    };
  }
 
  // Everything else inserts text: char keys, Space, Tab, Enter (newline).
  let text: string;
  if (action === "space") text = " ";
  else if (action === "tab") text = "\t";
  else if (action === "enter") text = "\n";
  else text = key.effectiveValue;
 
  if (text === "") return noChange;
 
  const candidate = before + text + afterSelection;
 
  if (options.maxLength !== undefined && candidate.length > options.maxLength) {
    return noChange;
  }
  if (options.keyFilter && !options.keyFilter(text, candidate)) {
    return noChange;
  }
 
  const caret = start + text.length;
  return {
    value: candidate,
    selectionStart: caret,
    selectionEnd: caret,
    changed: true,
    submit: false,
    event,
  };
}