okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
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 { 20key :string ; 21isComposing ?:boolean ; 22keyCode ?:number ; 23} 24 25export interface ImeGuard { 26compositionStart () :void ; 27compositionEnd ( 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. */ 29keyDown ( event :ImeKey , now :number ) :boolean ; 30/** The textarea lost the focus: a conversion that was cut short never sends a compositionend. */ 31reset () :void ; 32} 33 34export function createImeGuard ( windowMs = IME_COMMIT_WINDOW_MS ) :ImeGuard { 35let armedAt :number | null = null ; 36return { 37compositionStart () { 38armedAt = null ; 39}, 40compositionEnd ( now ) { 41armedAt = now ; 42}, 43keyDown ( event , now ) { 44const armed = armedAt ; 45armedAt = null ; // the next key of any kind uses the flag up 46if ( event . isComposing || event . keyCode === 229 ) 47return true ; 48return armed !== null && event . key === 'Enter' && now - armed >= 0 && now - armed <= windowMs ; 49}, 50reset () { 51armedAt = null ; 52}, 53}; 54}