///
import type { Suggestions } from '../../types';
import type { TextareaState, WebInputSession } from './WebInputSession';
export type InputHooks = {
// True when the key ran an editor command, so the browser must not act on it.
keyDown(e: KeyboardEvent): boolean;
// The selected text for the clipboard, deleted first for a cut. Null leaves the event to the browser.
clipboard(cut: boolean): string | null;
focusChanged(focused: boolean): void;
changed(): void;
// An undo or redo from the browser or an iOS gesture, run on the core's history.
history(undo: boolean): void;
};
const SUGGESTION_ATTRIBUTES: [string, string, string][] = [
['autocomplete', 'on', 'off'],
['autocorrect', 'on', 'off'],
['autocapitalize', 'sentences', 'off'],
['spellcheck', 'true', 'false'],
];
// The hidden textarea the keyboard types into, wired to a WebInputSession.
export class InputHost {
readonly textarea: HTMLTextAreaElement;
// iOS reports the selection as 0,0 for a moment after focus, so selection changes wait a frame.
private settling = false;
private settleTimer: ReturnType | undefined;
private readonly listeners: [EventTarget, string, EventListener][] = [];
constructor(
root: HTMLElement,
private readonly session: WebInputSession,
private readonly hooks: InputHooks,
) {
const ta = document.createElement('textarea');
// 16px keeps iOS from zooming the page on focus.
ta.style.cssText =
'position:absolute;left:0;top:0;width:2px;height:1px;padding:0;border:0;margin:0;opacity:0;' +
'resize:none;overflow:hidden;white-space:pre;font-size:16px;line-height:1;color:transparent;' +
'background:transparent;caret-color:transparent;outline:none;pointer-events:none;';
this.textarea = ta;
this.setSuggestions('off');
root.append(ta);
this.on(ta, 'beforeinput', (e) => {
const type = (e as InputEvent).inputType;
if (type === 'historyUndo' || type === 'historyRedo') {
e.preventDefault();
this.hooks.history(type === 'historyUndo');
return;
}
this.session.beforeInput(this.state());
});
this.on(ta, 'input', (e) => {
const ie = e as InputEvent;
this.write(
this.session.input(
{ inputType: ie.inputType ?? '', data: ie.data ?? null, isComposing: !!ie.isComposing },
this.state(),
),
);
this.hooks.changed();
});
this.on(ta, 'compositionstart', () => {
this.session.compositionStart(this.state());
this.hooks.changed();
});
this.on(ta, 'compositionend', () => {
this.session.compositionEnd();
this.hooks.changed();
// A browser may still send the composition's last input after this event, so the window moves a task later.
clearTimeout(this.settleTimer);
this.settleTimer = setTimeout(() => {
this.settleTimer = undefined;
this.write(this.session.settle(this.state()));
this.hooks.changed();
}, 0);
});
this.on(ta, 'copy', (e) => this.clip(e as ClipboardEvent, false));
this.on(ta, 'cut', (e) => this.clip(e as ClipboardEvent, true));
this.on(ta, 'keydown', (e) => {
if (this.hooks.keyDown(e as KeyboardEvent)) e.preventDefault();
});
this.on(ta, 'focus', () => {
this.settling = true;
requestAnimationFrame(() => {
this.settling = false;
});
this.hooks.focusChanged(true);
});
this.on(ta, 'blur', () => {
this.session.finishComposition();
this.hooks.focusChanged(false);
});
this.on(document, 'selectionchange', () => {
if (this.settling || document.activeElement !== ta) return;
this.write(this.session.selectionChange(this.state()));
this.hooks.changed();
});
}
get focused(): boolean {
return document.activeElement === this.textarea;
}
state(): TextareaState {
const ta = this.textarea;
return { value: ta.value, start: ta.selectionStart, end: ta.selectionEnd };
}
write(state: TextareaState | null): void {
if (!state) return;
const ta = this.textarea;
if (ta.value !== state.value) ta.value = state.value;
if (ta.selectionStart !== state.start || ta.selectionEnd !== state.end)
ta.setSelectionRange(state.start, state.end);
}
// Keeps the textarea at the caret, so the keyboard's candidate window opens there.
place(x: number, y: number): void {
const s = this.textarea.style;
const left = `${Math.round(x)}px`;
const top = `${Math.round(y)}px`;
// An unchanged write still invalidates the page's layout.
if (s.left !== left) s.left = left;
if (s.top !== top) s.top = top;
}
focus(): void {
this.write(this.session.sync());
this.textarea.focus({ preventScroll: true });
}
blur(): void {
this.textarea.blur();
}
setSuggestions(suggestions: Suggestions): void {
for (const [name, on, off] of SUGGESTION_ATTRIBUTES)
this.textarea.setAttribute(name, suggestions === 'on' ? on : off);
}
// A read only textarea brings no keyboard on a phone, while selection still works.
setReadOnly(readOnly: boolean): void {
this.textarea.readOnly = readOnly;
}
destroy(): void {
clearTimeout(this.settleTimer);
for (const [target, type, fn] of this.listeners) target.removeEventListener(type, fn);
this.textarea.remove();
}
// The textarea holds only a window, so the clipboard takes the editor's whole selection.
private clip(e: ClipboardEvent, cut: boolean): void {
const text = this.hooks.clipboard(cut);
if (text === null || !e.clipboardData) return;
e.clipboardData.setData('text/plain', text);
e.preventDefault();
}
private on(target: EventTarget, type: string, fn: EventListener): void {
target.addEventListener(type, fn);
this.listeners.push([target, type, fn]);
}
}