import { ACTIVATION_KEYS, CARET_KEYS, COMBOBOX_KEYS, ENTER_KEYS, GRID_KEYS, HORIZONTAL_KEYS, INPUT_KEYS, MENU_KEYS, NAVIGATION_KEYS, RADIO_KEYS, SPACE_KEYS, SPIN_KEYS, TYPEAHEAD, VERTICAL_KEYS, } from './_constants' import { codeToLogicalKey } from './_keyboard-event' import { normalizeKeyName } from './constants' import type { Target } from './hotkey.types' // Nodes and windows can come from another frame (a same-origin iframe or a // popup window), whose DOM classes differ from this window's. These helpers // check `nodeType`, `localName`, and properties instead of using `instanceof`, // which is false for every object from another frame. function isElement(node: unknown): node is Element { return (node as Node | null)?.nodeType === 1 // Node.ELEMENT_NODE } /** Whether a target is a document or window, which receive every key press in their document. */ export function isDocumentLevel(target: Target): target is Document | Window { return 'document' in target || target.nodeType === 9 // Node.DOCUMENT_NODE } /** Returns the document a listener target belongs to, in any frame. */ export function getTargetDocument(target: Target): Document { // A document has no owner document return 'document' in target ? target.document : (target.ownerDocument ?? target) } // Focus /** The focused element, looking inside open shadow roots. */ function getDeepActiveElement(doc: Document): Element | null { let active = doc.activeElement while (active?.shadowRoot?.activeElement) { active = active.shadowRoot.activeElement } return active } /** The next node a key event bubbles to: a slot, a shadow host, or the parent. */ function composedParent(node: Node): Node | null { return ( (node as Element).assignedSlot ?? node.parentNode ?? // A shadow root has no parent node; continue from its host. ((node as Partial).host || null) ) } /** * Whether key presses reach a listener on `target` right now. Document and * window listeners receive every key press in their document. An element * receives them only while focus is inside it, including inside a shadow * root it contains or on content slotted into it. */ export function targetHasFocus(target: Target): boolean { if (isDocumentLevel(target)) return true for ( let node: Node | null = getDeepActiveElement(target.ownerDocument); node; node = composedParent(node) ) { if (node === target) return true } return false } // What blocks a key function getRole(element: Element): string | undefined { return element.getAttribute('role')?.trim().split(/\s+/)[0] } /** * Checks if an element is a text field that hotkeys should not type over: * - text-entry `` types (text, number, date, and similar) that aren't read-only * - `