diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx
index 5f9f28f1..8c31b7f2 100644
--- a/src/client/FileTree.tsx
+++ b/src/client/FileTree.tsx
@@ -53,7 +53,7 @@ import { api, archiveBuild, archiveDownloadUrl, archiveStatus, downloadUrl, type
import { FS_TREES_MAX_PATHS } from '../fs-batch.ts'
import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx'
import { IconUploadOutline16, IconVscode16 } from './icons.tsx'
-import { isImeComposition } from './ime-guard.ts'
+import { isLikelyImeKey } from './ime-guard.ts'
import { useSubmenuFlip } from './menu-flip.ts'
import type { OpenInApp, OpenInAppEntry } from './open-in-app.ts'
import type { OpenWithTarget } from './open-with.ts'
@@ -1512,8 +1512,12 @@ export function FileTree(props: {
/** The inline rename editor replacing one row (dirs and files alike):
* same indent/icon/height for a seamless swap, Enter/blur commits,
- * Escape cancels, IME composition keys never reach the handlers (the
- * shared isImeComposition guard). */
+ * Escape cancels. Composition keys must not commit the name; this handler
+ * is a NON-intercepting early return (no stopPropagation), so it asks the
+ * conservative isLikelyImeKey — the document capture guard only swallows
+ * keys inside a live composition window by design (bare legacy 229
+ * keydowns pass it, #833), which is right for the guard and not enough
+ * here. */
const renderRenameRow = (entry: FsEntry, depth: number): ReactNode => (
prev === null ? prev : { ...prev, value: event.target.value })
}}
onKeyDown={(event) => {
- if (isImeComposition(event)) return
+ if (isLikelyImeKey(event)) return
if (event.key === 'Enter') {
event.preventDefault()
commitRename(entry.path, renaming?.value ?? '')
@@ -1549,7 +1553,7 @@ export function FileTree(props: {
/** The inline new-folder editor at the top of one level: the same
* interaction contract as the rename editor (Enter commits, Escape
- * cancels, blur commits, IME guarded). */
+ * cancels, blur commits, conservatively IME-guarded). */
const renderNewFolderRow = (dir: string, depth: number): ReactNode => (
{dirRowIcon(dir, true)}
@@ -1564,7 +1568,7 @@ export function FileTree(props: {
setNewFolder(prev => prev === null ? prev : { ...prev, value: event.target.value })
}}
onKeyDown={(event) => {
- if (isImeComposition(event)) return
+ if (isLikelyImeKey(event)) return
if (event.key === 'Enter') {
event.preventDefault()
commitNewFolder(dir, newFolder?.value ?? '')
diff --git a/src/client/ime-guard.ts b/src/client/ime-guard.ts
index 9cfdca81..53a340d3 100644
--- a/src/client/ime-guard.ts
+++ b/src/client/ime-guard.ts
@@ -20,16 +20,70 @@
* composition keys. The browser's native IME processing is untouched:
* stopPropagation only silences page JS, not the default action.
*
- * The composition signal follows the DSH core convention (InputBar's IME
- * guard, issue #535): `isComposing` for modern engines, keyCode 229 as the
- * legacy signal engines emit without isComposing.
+ * TWO predicates, deliberately different, because the two kinds of call site
+ * pay different prices for a false positive:
+ *
+ * - `isImeComposition` — the capture guard's decision (narrow). A false
+ * positive here costs `stopPropagation()`: the key is swallowed for EVERY
+ * downstream listener, page-wide. Trusting a bare legacy 229 outside a
+ * composition window did exactly that to layout-switcher utilities (#833,
+ * see below), so 229 only counts while a composition is live.
+ * - `isLikelyImeKey` — the conservative disjunction
+ * `isComposing || keyCode === 229`, for NON-intercepting callers that use
+ * the answer as an early return (FileTree's rename / new-folder commit
+ * handlers). A false positive there costs one skipped key while a false
+ * negative commits a half-composed name, so the over-approximation wins.
+ *
+ * The conservative shape is also what DSH core itself uses, but only because
+ * no core call site stops propagation: `QuestionComposer` (ui-user-questions)
+ * has no composition tracking at all — just `isComposing || keyCode === 229` —
+ * and `InputBar` (ui-conversation, issue #535) ORs a live composition ref
+ * with the bare 229. This module is the one place where the wider rule is
+ * wrong, which is why the narrow decision lives behind its own name here.
+ *
+ * The legacy 229 signal is only trusted by the capture guard while (or right
+ * after) a real composition is running. Legacy engines (Safari) emit 229
+ * keydowns with `isComposing === false` *during* a composition, and that
+ * context is what distinguishes them from synthetic 229 keydowns emitted
+ * outside any IME — layout-switcher utilities (e.g. KeyRay's layout swap)
+ * send a keydown carrying the whole converted word as a multi-character
+ * unicode string, Chromium reports it as keyCode 229 / isComposing=false, and
+ * swallowing it made the backspaces land while the replacement text never
+ * did: the word silently disappeared instead of being rewritten.
*/
-/** The pure decision: is this keyboard event part of an IME composition?
- * `isComposing` is optional on the input: React's synthetic KeyboardEvent
- * type does not declare it (the DOM event always carries it), and the
- * keyCode 229 fallback covers exactly those callers. */
-export function isImeComposition(event: { isComposing?: boolean; keyCode: number }): boolean {
+/** Live composition context, tracked by the guard's composition listeners. */
+let guardComposing = false
+/** Grace window (ms) after compositionend that still counts as composition,
+ * covering legacy engines' closing 229 keydown with isComposing === false. */
+const GUARD_COMPOSITION_END_GRACE_MS = 50
+let guardComposingUntil = 0
+
+function imeCompositionLive(): boolean {
+ return guardComposing || Date.now() < guardComposingUntil
+}
+
+/** The key-event shape both predicates accept. `isComposing` is optional:
+ * React's synthetic KeyboardEvent type does not declare it (the DOM event
+ * always carries it). */
+type ImeKeyEvent = { isComposing?: boolean; keyCode: number }
+
+/** The CAPTURE guard's decision: is this keyboard event part of an IME
+ * composition? NOT a pure function of its argument — it consults the
+ * guard's module-level composition state (above) to scope the legacy 229
+ * signal. Never reuse it as a generic "is IME" helper: see the module doc
+ * for why non-intercepting callers want `isLikelyImeKey` instead. */
+export function isImeComposition(event: ImeKeyEvent): boolean {
+ if (event.isComposing === true) return true
+ if (event.keyCode !== 229) return false
+ return imeCompositionLive()
+}
+
+/** The CONSERVATIVE decision, for non-intercepting callers where misreading a
+ * composition key costs more than ignoring an ordinary one: a bare 229 counts
+ * even outside a composition window. Pure — reads no module state, so it
+ * answers the same before, during and after a composition. */
+export function isLikelyImeKey(event: ImeKeyEvent): boolean {
return event.isComposing === true || event.keyCode === 229
}
@@ -41,10 +95,23 @@ export function registerImeGuard(): () => void {
const onKey = (event: KeyboardEvent): void => {
if (isImeComposition(event)) event.stopPropagation()
}
+ const onCompositionStart = (): void => {
+ guardComposing = true
+ }
+ const onCompositionEnd = (): void => {
+ guardComposing = false
+ guardComposingUntil = Date.now() + GUARD_COMPOSITION_END_GRACE_MS
+ }
document.addEventListener('keydown', onKey, true)
document.addEventListener('keyup', onKey, true)
+ document.addEventListener('compositionstart', onCompositionStart, true)
+ document.addEventListener('compositionend', onCompositionEnd, true)
return () => {
document.removeEventListener('keydown', onKey, true)
document.removeEventListener('keyup', onKey, true)
+ document.removeEventListener('compositionstart', onCompositionStart, true)
+ document.removeEventListener('compositionend', onCompositionEnd, true)
+ guardComposing = false
+ guardComposingUntil = 0
}
}
diff --git a/tests/ime-guard.spec.ts b/tests/ime-guard.spec.ts
index 43758e20..f695000e 100644
--- a/tests/ime-guard.spec.ts
+++ b/tests/ime-guard.spec.ts
@@ -3,10 +3,15 @@
* IME-composition guard tests.
*
* The guard registers document CAPTURE-phase keydown/keyup listeners that
- * stopPropagation() while an input method is composing (isComposing or the
- * legacy keyCode 229). These tests pin:
+ * stopPropagation() while an input method is composing (isComposing, or the
+ * legacy keyCode 229 *inside a live composition context* — bare synthetic
+ * 229 keydowns from layout-switcher utilities must pass through). These tests
+ * pin:
*
- * 1. the pure decision (`isImeComposition`);
+ * 1. the decision predicates — the capture guard's narrow `isImeComposition`
+ * (NOT a pure function: it reads the guard's module-level composition
+ * state) and the conservative `isLikelyImeKey` that non-intercepting
+ * callers use;
* 2. the native-listener path — a bubble listener on `document` and a
* target-phase listener on the input must NOT see composition keys, but
* must see every other key;
@@ -15,18 +20,22 @@
* document-capture listener wins the ordering race against React's
* delegation (the mechanism that inlined third-party UI, e.g. Univer's
* InputNumber, uses to hijack ArrowUp/ArrowDown);
- * 4. the disposer restores normal flow (HMR-safe).
+ * 4. the disposer restores normal flow (HMR-safe);
+ * 5. the FileTree shape — a commit handler that early-returns on the
+ * conservative predicate must not commit a rename on a bare 229 Enter,
+ * even though the capture guard's predicate deliberately says "not IME"
+ * for that same event.
*
* Events are dispatched on a deep element (an `` in `document.body`)
* exactly like the browser does, so capture-phase blocking behaves like in
* production — dispatching on `document` itself would run all listeners in
* the target phase where stopPropagation does not stop same-node listeners.
*/
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
-import { isImeComposition, registerImeGuard } from '../src/client/ime-guard.ts'
+import { isImeComposition, isLikelyImeKey, registerImeGuard } from '../src/client/ime-guard.ts'
/** Build a KeyboardEvent the way jsdom allows: keyCode/isComposing via defineProperty. */
function keyEvent(
@@ -48,11 +57,15 @@ describe('isImeComposition', () => {
expect(isImeComposition({ isComposing: true, keyCode: 0 })).toBe(true)
})
- it('treats keyCode 229 as composition (legacy engines without isComposing)', () => {
- expect(isImeComposition({ isComposing: false, keyCode: 229 })).toBe(true)
+ it('treats keyCode 229 as composition only inside a live composition context', () => {
+ // No composition events were dispatched, so no composition is live: a bare
+ // synthetic 229 (layout-switcher utilities emit these) must NOT count.
+ expect(isImeComposition({ isComposing: false, keyCode: 229 })).toBe(false)
})
- it('treats both signals together as composition', () => {
+ it('short-circuits on isComposing even when a 229 keyCode rides along', () => {
+ // The isComposing branch returns before the composition-context lookup, so
+ // this is true for the same reason as the isComposing-only case above.
expect(isImeComposition({ isComposing: true, keyCode: 229 })).toBe(true)
})
@@ -62,6 +75,47 @@ describe('isImeComposition', () => {
})
})
+describe('isLikelyImeKey — the conservative predicate', () => {
+ it('treats isComposing as composition', () => {
+ expect(isLikelyImeKey({ isComposing: true, keyCode: 0 })).toBe(true)
+ })
+
+ it('trusts a bare keyCode 229 with no composition context at all', () => {
+ // This is the whole difference from isImeComposition, and the reason the
+ // two names exist: no composition event was ever dispatched here.
+ expect(isLikelyImeKey({ isComposing: false, keyCode: 229 })).toBe(true)
+ })
+
+ it('lets ordinary keys through', () => {
+ expect(isLikelyImeKey({ isComposing: false, keyCode: 40 })).toBe(false)
+ expect(isLikelyImeKey({ isComposing: false, keyCode: 13 })).toBe(false)
+ expect(isLikelyImeKey({ isComposing: false, keyCode: 0 })).toBe(false)
+ })
+
+ it('a FileTree-shaped commit handler ignores a bare 229 Enter (rename / new folder)', () => {
+ let commits = 0
+ // The shape of FileTree's rename / new-folder onKeyDown: a NON-intercepting
+ // early return, so a false positive costs one skipped key while a false
+ // negative commits a half-composed name. This case guards THAT call site's
+ // semantics, not the capture guard's — the guardian of the document-wide
+ // stopPropagation is the `isImeComposition` suite above.
+ const onKeyDown = (event: { key: string; isComposing?: boolean; keyCode: number }): void => {
+ if (isLikelyImeKey(event)) return
+ if (event.key === 'Enter') commits += 1
+ }
+ // Legacy engines report the IME-confirming Enter as keyCode 229 with
+ // isComposing === false; outside a composition window the capture guard's
+ // predicate answers false for it by design (#833), so a handler that read
+ // its safety from there would commit the rename.
+ expect(isImeComposition({ isComposing: false, keyCode: 229 })).toBe(false)
+ onKeyDown({ key: 'Enter', isComposing: false, keyCode: 229 })
+ expect(commits).toBe(0)
+ // A real Enter still commits: the guard must not swallow ordinary typing.
+ onKeyDown({ key: 'Enter', isComposing: false, keyCode: 13 })
+ expect(commits).toBe(1)
+ })
+})
+
describe('registerImeGuard — native listeners', () => {
let input: HTMLInputElement
let dispose: (() => void) | undefined
@@ -108,12 +162,46 @@ describe('registerImeGuard — native listeners', () => {
expect(seen).toEqual([])
})
- it('blocks composition keys signalled by keyCode 229 only', () => {
+ it('blocks a keyCode 229 keydown inside a live composition (legacy engines emit 229 with isComposing=false)', () => {
dispose = registerImeGuard()
- input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', keyCode: 229 }))
+ document.dispatchEvent(new Event('compositionstart'))
+ input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', isComposing: false, keyCode: 229 }))
expect(seen).toEqual([])
})
+ it('keeps blocking a keyCode 229 keydown right after compositionend (legacy closing keydown)', () => {
+ vi.useFakeTimers()
+ try {
+ dispose = registerImeGuard()
+ document.dispatchEvent(new Event('compositionstart'))
+ document.dispatchEvent(new Event('compositionend'))
+ input.dispatchEvent(keyEvent('keydown', { key: 'a', isComposing: false, keyCode: 229 }))
+ expect(seen).toEqual([])
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('lets a bare synthetic keyCode 229 keydown through when no composition ever started (KeyRay regression)', () => {
+ dispose = registerImeGuard()
+ input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', isComposing: false, keyCode: 229 }))
+ expect(seen).toEqual(['input:keydown', 'document:keydown'])
+ })
+
+ it('lets a keyCode 229 keydown through after the post-compositionend grace window expires', () => {
+ vi.useFakeTimers()
+ try {
+ dispose = registerImeGuard()
+ document.dispatchEvent(new Event('compositionstart'))
+ document.dispatchEvent(new Event('compositionend'))
+ vi.advanceTimersByTime(51)
+ input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', isComposing: false, keyCode: 229 }))
+ expect(seen).toEqual(['input:keydown', 'document:keydown'])
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it('still blocks after the composition signal is gone (guard is per-event)', () => {
dispose = registerImeGuard()
input.dispatchEvent(keyEvent('keydown', { key: 'ArrowDown', isComposing: true }))