keyboard-utils.ts 1.1 KB

123456789101112131415161718192021222324
  1. /**
  2. * Returns true when a keydown event is part of an IME composition
  3. * (Chinese / Japanese / Korean input methods). When the user is
  4. * composing — e.g. typing English letters under a Chinese input
  5. * method to pick a candidate — pressing Enter commits the
  6. * candidate, but the same Enter keydown ALSO bubbles up to the
  7. * input element and gets misread by `if (e.key === "Enter")`
  8. * handlers as a "submit" intent. Result: the message sends
  9. * before the user actually finished typing.
  10. *
  11. * Both signals are required because no single one is reliable:
  12. * - `nativeEvent.isComposing` — W3C standard, true while the
  13. * IME is composing. Cleared by the time the commit-press
  14. * fires in some browsers.
  15. * - `keyCode === 229` — the legacy "IME activity" signal that
  16. * Chromium continues to emit on the commit-press itself,
  17. * after `isComposing` has already flipped back to false.
  18. *
  19. * Use this in every Enter-as-submit handler on a text input so
  20. * IME composition Enter never leaks through as a submit.
  21. */
  22. export function isImeComposing(e: React.KeyboardEvent): boolean {
  23. return e.nativeEvent.isComposing || e.keyCode === 229
  24. }