okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
2.5 KiB54 linesraw
1/**
2 * The Enter that commits an IME conversion must not also send the message (#5071, Japanese input on macOS).
3 *
4 * The browsers disagree on the order of the events when Enter commits a conversion:
5 *   Chrome, Edge (WebView2), Firefox:  keydown(Enter, keyCode 229, isComposing true)  ->  compositionend
6 *   Safari (WKWebView):                compositionend  ->  keydown(Enter, keyCode 229, isComposing FALSE)
7 *   WebKitGTK (IBus), as reported:     compositionend  ->  keydown(Enter, keyCode 13, isComposing false)
8 * `isComposing` alone only covers the first. The rule here covers all three:
9 *   1. a key event that says it is composing (isComposing) or that is the IME's own (keyCode 229) belongs to the IME;
10 *   2. the first Enter right after a compositionend, in the same tick (a few milliseconds), is the one that committed;
11 *   3. every other key is the person's. A second Enter after the conversion is committed sends, exactly once.
12 * The flag of rule 2 is armed by compositionend, used up by the next key whatever it is, and expires on its own, so it can never leave
13 * the composer unable to send. Times are the events' own `timeStamp`s (one clock).
14 */
15
16/** How long after a compositionend an Enter still counts as the one that committed. The three engines deliver it in the same tick. */
17export const IME_COMMIT_WINDOW_MS = 50;
18
19export interface ImeKey {
20    key: string;
21    isComposing?: boolean;
22    keyCode?: number;
23}
24
25export interface ImeGuard {
26    compositionStart(): void;
27    compositionEnd(now: number): void;
28    /** True when this keydown belongs to the IME: the composer must neither send nor run a menu or shortcut action for it. */
29    keyDown(event: ImeKey, now: number): boolean;
30    /** The textarea lost the focus: a conversion that was cut short never sends a compositionend. */
31    reset(): void;
32}
33
34export function createImeGuard(windowMs = IME_COMMIT_WINDOW_MS): ImeGuard {
35    let armedAt: number | null = null;
36    return {
37        compositionStart() {
38            armedAt = null;
39        },
40        compositionEnd(now) {
41            armedAt = now;
42        },
43        keyDown(event, now) {
44            const armed = armedAt;
45            armedAt = null;                     // the next key of any kind uses the flag up
46            if (event.isComposing || event.keyCode === 229)
47                return true;
48            return armed !== null && event.key === 'Enter' && now - armed >= 0 && now - armed <= windowMs;
49        },
50        reset() {
51            armedAt = null;
52        },
53    };
54}