35 lines
1.4 KiB
TypeScript
35 lines
1.4 KiB
TypeScript
export const KEYBOARD_CONTRACT_SCHEMA_VERSION = 1 as const;
|
|
|
|
export interface KeyboardObservation {
|
|
schemaVersion: typeof KEYBOARD_CONTRACT_SCHEMA_VERSION;
|
|
key: string;
|
|
code: string;
|
|
location: 0 | 1 | 2 | 3;
|
|
shiftKey: boolean;
|
|
ctrlKey: boolean;
|
|
altKey: boolean;
|
|
metaKey: boolean;
|
|
repeat: boolean;
|
|
isComposing: boolean;
|
|
deadKey: boolean;
|
|
}
|
|
|
|
export function observeKeyboardEvent(event: { key?: string; code?: string; location?: number; shiftKey?: boolean; ctrlKey?: boolean; altKey?: boolean; metaKey?: boolean; repeat?: boolean; isComposing?: boolean }): KeyboardObservation {
|
|
if (typeof event.key !== "string" || event.key.length === 0 || event.key.length > 128) throw new Error("KEY_IDENTITY_INVALID");
|
|
if (typeof event.code !== "string" || event.code.length === 0 || event.code.length > 64) throw new Error("KEY_CODE_INVALID");
|
|
if (!Number.isInteger(event.location) || event.location! < 0 || event.location! > 3) throw new Error("KEY_LOCATION_INVALID");
|
|
return {
|
|
schemaVersion: KEYBOARD_CONTRACT_SCHEMA_VERSION,
|
|
key: event.key,
|
|
code: event.code,
|
|
location: event.location as 0 | 1 | 2 | 3,
|
|
shiftKey: Boolean(event.shiftKey),
|
|
ctrlKey: Boolean(event.ctrlKey),
|
|
altKey: Boolean(event.altKey),
|
|
metaKey: Boolean(event.metaKey),
|
|
repeat: Boolean(event.repeat),
|
|
isComposing: Boolean(event.isComposing),
|
|
deadKey: event.key === "Dead",
|
|
};
|
|
}
|