/** * Locates elements by ARIA role and accessible name, computed from tags and * attributes, so a test finds elements the way assistive technology does. * * The same lookups run over a scene's view value, a `TestHost` tree and a * real DOM tree. `role`, `label` and `placeholder` return a `Locator`, so * they combine with `Locator.inside` on the first two. On the DOM, `click`, * `type`, `keydown` and `submit` act as the user would, through real DOM * events, and refuse an inert element. * * Hidden elements (the `hidden` attribute or property, `aria-hidden="true"`, * ``) and their descendants are excluded from role * queries, as are inert elements. `hidden: true` includes both, but does not * make inert elements interactive. * * Inertness comes from `inert` on an element or ancestor, or being outside * the topmost modal. The last open modal in document order is treated as * topmost. DOM modal detection uses `:modal`, including open shadow roots; * some test environments never match it. DOM inertness follows shadow hosts * and slots, but queries do not search inside shadow roots. * * On a structural tree a match is typed `Locator.Node`, since it can be any * node of the tree. On `TestHost`, `root.all(HtmlLocator.role(...))` keeps the * host's node type. On the DOM a match is an `HTMLElement`. * * **Example** (Finding a button by its name) * * ```ts import.meta.vitest * import { HtmlLocator } from "effect/ui/html/testing" * * const tree = { * tag: "form", * children: [ * { tag: "label", attrs: { for: "new" }, children: [{ text: "New todo" }] }, * { tag: "input", attrs: { id: "new" } }, * { tag: "button", attrs: { type: "submit" }, children: [{ text: "Add" }] } * ] * } * * console.log(HtmlLocator.getByRole(tree, "button", { name: "Add" }) === tree.children[2]) // true * console.log(HtmlLocator.nameOf(tree, HtmlLocator.getByRole(tree, "textbox"))) // "New todo" * ``` * * @stability unstable * @since 4.2.0 */ import { matcher, own } from "../../internal/attrs.ts" import * as Locator from "../../testing/Locator.ts" import type { AriaRole } from "../Html.ts" // --------------------------------------------------------------------------- // trees // --------------------------------------------------------------------------- /** One way to read a tree: the structural `Locator.Node` shape or the DOM. */ interface Reader { readonly isElement: (node: N) => boolean readonly tag: (node: N) => string readonly attr: (node: N, name: string) => string | undefined readonly prop: (node: N, name: string) => unknown /** Whether `hidden` or `inert` is set, accounting for property reflection. */ readonly flag: (node: N, name: string) => boolean readonly children: (node: N) => ReadonlyArray /** The text of a text node, or `undefined` for anything else. */ readonly text: (node: N) => string | undefined } const isDom = (node: unknown): node is globalThis.Node => typeof node === "object" && node !== null && typeof (node as { nodeType?: unknown }).nodeType === "number" const domReader: Reader = { isElement: (node) => node.nodeType === 1, tag: (node) => (node as globalThis.Element).localName, // Named form controls can shadow properties and methods, so read attributes through the prototype. attr: (node, name) => node.nodeType === 1 ? (Object.getPrototypeOf(node).getAttribute.call(node, name) ?? undefined) : undefined, prop: (node, name) => (node as any)[name], flag: (node, name) => node.nodeType === 1 && Object.getPrototypeOf(node).hasAttribute.call(node, name), children: (node) => Array.from(node.childNodes), text: (node) => node.nodeType === 3 ? (node as globalThis.Text).data : undefined } const structuralReader: Reader = { isElement: (node) => node.tag !== undefined, tag: (node) => node.tag!, attr: (node, name) => own(node.attrs, name), prop: (node, name) => node.props?.[name], flag: (node, name) => { const prop = node.props?.[name] return prop === undefined ? own(node.attrs, name) !== undefined : !!prop }, children: (node) => node.children ?? [], text: (node) => node.tag === undefined ? node.text : undefined } const readerOf = (node: unknown): Reader => isDom(node) ? domReader : structuralReader // --------------------------------------------------------------------------- // roles // --------------------------------------------------------------------------- /** Elements under which `header` and `footer` lose their landmark role. */ const sectioning: ReadonlySet = new Set([ "article", "aside", "main", "nav", "section" ]) const fixedRoles: Readonly> = { article: "article", aside: "complementary", blockquote: "blockquote", button: "button", caption: "caption", code: "code", datalist: "listbox", dd: "definition", del: "deletion", details: "group", dfn: "term", dialog: "dialog", dt: "term", em: "emphasis", fieldset: "group", figure: "figure", form: "form", h1: "heading", h2: "heading", h3: "heading", h4: "heading", h5: "heading", h6: "heading", hr: "separator", ins: "insertion", li: "listitem", main: "main", menu: "list", meter: "meter", nav: "navigation", ol: "list", optgroup: "group", option: "option", output: "status", p: "paragraph", progress: "progressbar", search: "search", strong: "strong", sub: "subscript", sup: "superscript", table: "table", tbody: "rowgroup", td: "cell", textarea: "textbox", tfoot: "rowgroup", thead: "rowgroup", time: "time", tr: "row", ul: "list" } const inputRole = (type: string, hasList: boolean): AriaRole | undefined => { switch (type) { case "button": case "image": case "reset": case "submit": return "button" case "checkbox": return "checkbox" case "radio": return "radio" case "range": return "slider" case "number": return "spinbutton" case "search": return hasList ? "combobox" : "searchbox" case "": case "email": case "tel": case "text": case "url": return hasList ? "combobox" : "textbox" default: return undefined } } /** Roles whose accessible name comes from their content when nothing else names them. */ const nameFromContent: ReadonlySet = new Set([ "button", "cell", "checkbox", "columnheader", "gridcell", "heading", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch", "tab", "tooltip", "treeitem" ]) // --------------------------------------------------------------------------- // the index of a tree // --------------------------------------------------------------------------- interface Entry { readonly node: N readonly role: string | undefined readonly hidden: boolean readonly inSection: boolean } interface Index { readonly reader: Reader readonly entries: ReadonlyArray> readonly byNode: Map> readonly byId: Map /** Associated labels by control, in document order. */ readonly labels: Map> } /** Whether a `dialog` is open: its `open` property, or its `open` attribute when no property was set. */ const dialogOpen = (reader: Reader, node: N): boolean => { const open = reader.prop(node, "open") return open === undefined ? reader.attr(node, "open") !== undefined : open === true || open === "modal" } /** * Whether a popover is showing: its `popoverOpen` property, set by `.popover`, or `:popover-open` on a DOM * element. A DOM without `:popover-open` reports it closed. */ const popoverOpen = (reader: Reader, node: N): boolean => { const open = reader.prop(node, "popoverOpen") if (open !== undefined || !isDom(node)) return open === true try { return (node as unknown as globalThis.Element).matches(":popover-open") } catch { return false } } /** Whether a dialog or popover is neither open as a dialog nor showing as a popover. */ const notShown = (reader: Reader, node: N): boolean => { const dialog = reader.tag(node) === "dialog" const popover = reader.attr(node, "popover") !== undefined if (!dialog && !popover) return false return !((dialog && dialogOpen(reader, node)) || (popover && popoverOpen(reader, node))) } /** Approximates top-layer order with document order, including open shadow roots. */ const topModal = (reader: Reader, root: N): N | undefined => { let modal: N | undefined const walk = (node: N) => { if ( reader.isElement(node) && reader.tag(node) === "dialog" && dialogState(node) === "modal" ) modal = node const shadow = isDom(node) ? (node as unknown as globalThis.Element).shadowRoot : null if (shadow != null) walk(shadow as N) for (const child of reader.children(node)) walk(child) } walk(root) return modal } const isHidden = (reader: Reader, node: N): boolean => reader.flag(node, "hidden") || reader.attr(node, "aria-hidden") === "true" || (reader.tag(node) === "input" && (reader.attr(node, "type") ?? "").toLowerCase() === "hidden") || reader.tag(node) === "template" || // A closed dialog or a popover that isn't showing isn't rendered, so neither it nor anything in it is // in the accessibility tree. A dialog shown as a popover is rendered, though its `open` is false. notShown(reader, node) const implicitRole = ( reader: Reader, node: N, inSection: boolean ): AriaRole | undefined => { const tag = reader.tag(node) switch (tag) { case "a": case "area": return reader.attr(node, "href") !== undefined ? "link" : undefined case "header": return inSection ? undefined : "banner" case "footer": return inSection ? undefined : "contentinfo" case "img": return reader.attr(node, "alt") === "" ? "presentation" : "img" case "input": return inputRole( (reader.attr(node, "type") ?? "").toLowerCase(), reader.attr(node, "list") !== undefined ) case "select": { const size = Number(reader.attr(node, "size") ?? "1") return reader.attr(node, "multiple") !== undefined || size > 1 ? "listbox" : "combobox" } case "section": return reader.attr(node, "aria-label") !== undefined || reader.attr(node, "aria-labelledby") !== undefined || reader.attr(node, "title") !== undefined ? "region" : undefined case "th": return reader.attr(node, "scope") === "row" ? "rowheader" : "columnheader" default: return fixedRoles[tag] } } const buildIndex = (root: N): Index => { const reader = readerOf(root) as Reader const index: Index = { reader, entries: [], byNode: new Map(), byId: new Map(), labels: new Map() } // Every label in document order, with its first labelable descendant. const labels = new Map() const entries = index.entries as Array> const modal = topModal(reader, root) const walk = ( node: N, hidden: boolean, inert: boolean, open: ReadonlyArray, inSection: boolean ) => { if (!reader.isElement(node)) { // A document, a fragment or a structural wrapper isn't indexed, but what it holds is. if (reader.text(node) === undefined) { for (const child of reader.children(node)) { walk(child, hidden, inert, open, inSection) } } return } const tag = reader.tag(node) // The topmost modal escapes the inertness around it, not its own. const inertHere = reader.flag(node, "inert") || (inert && node !== modal) const isHiddenHere = hidden || isHidden(reader, node) const explicit = reader.attr(node, "role")?.trim().split(/\s+/)[0] const entry: Entry = { node, role: explicit !== undefined && explicit !== "" ? explicit : implicitRole(reader, node, inSection), hidden: isHiddenHere || inertHere, inSection } entries.push(entry) index.byNode.set(node, entry) const id = reader.attr(node, "id") if (id !== undefined && !index.byId.has(id)) index.byId.set(id, node) const isLabel = tag === "label" if (isLabel) labels.set(node, undefined) else if (open.length > 0 && isLabelable(reader, node)) { for (const label of open) { if (labels.get(label) === undefined) labels.set(label, node) } } const childOpen = isLabel ? [...open, node] : open const childSection = inSection || sectioning.has(tag) const host = isDom(node) && (node as unknown as globalThis.Element).shadowRoot != null for (const child of reader.children(node)) { walk( child, isHiddenHere, host ? slottedInert( node as globalThis.Node, child as globalThis.Node, inertHere, modal as globalThis.Node | undefined ) : inertHere, childOpen, childSection ) } } walk(root, false, modal !== undefined, [], false) for (const [label, first] of labels) { const target = reader.attr(label, "for") const control = target === undefined ? first : index.byId.get(target) if (control === undefined || !isLabelable(reader, control)) continue const list = index.labels.get(control) if (list === undefined) index.labels.set(control, [label]) else list.push(label) } return index } // --------------------------------------------------------------------------- // accessible names // --------------------------------------------------------------------------- const normalize = (text: string): string => text.replace(/\s+/g, " ").trim() const phrasing: ReadonlySet = new Set([ "a", "abbr", "b", "bdi", "bdo", "cite", "code", "data", "del", "dfn", "em", "i", "ins", "kbd", "label", "mark", "q", "s", "samp", "small", "span", "strong", "sub", "sup", "time", "u", "var" ]) /** The text an element contributes as content: its text, with hidden parts and controls left out. */ const contentText = ( index: Index, node: N, skip: N | undefined, includeHidden: boolean ): string => { const { reader } = index const text = reader.text(node) if (text !== undefined) return text if (!reader.isElement(node) || node === skip) return "" if (!includeHidden && isHidden(reader, node)) return "" const tag = reader.tag(node) if (tag === "br") return " " if (tag === "img") return reader.attr(node, "alt") ?? "" if (tag === "input" || tag === "select" || tag === "textarea") return "" const label = reader.attr(node, "aria-label") const inner = label !== undefined && label.trim() !== "" ? label : reader.children(node).map((child) => contentText(index, child, skip, includeHidden)).join("") return phrasing.has(tag) ? inner : ` ${inner} ` } const textOfIds = (index: Index, ids: string): string => normalize( ids.trim().split(/\s+/).map((id) => { const node = index.byId.get(id) return node === undefined ? "" : contentText(index, node, undefined, true) }).join(" ") ) const firstChildText = ( index: Index, node: N, tag: string ): string | undefined => { const child = index.reader.children(node).find((c) => index.reader.isElement(c) && index.reader.tag(c) === tag) return child === undefined ? undefined : normalize(contentText(index, child, undefined, false)) } const computeName = (index: Index, entry: Entry): string => { const { reader } = index const node = entry.node const labelledBy = reader.attr(node, "aria-labelledby") if (labelledBy !== undefined && labelledBy.trim() !== "") { const name = textOfIds(index, labelledBy) if (name !== "") return name } const label = reader.attr(node, "aria-label") if (label !== undefined && label.trim() !== "") return normalize(label) const tag = reader.tag(node) const type = (reader.attr(node, "type") ?? "").toLowerCase() if ( tag === "input" && (type === "button" || type === "submit" || type === "reset") ) { const value = reader.attr(node, "value") ?? (reader.prop(node, "value") as string | undefined) if (value !== undefined && value !== "") return normalize(value) return type === "submit" ? "Submit" : type === "reset" ? "Reset" : "" } if (tag === "input" && type === "image") { return normalize(reader.attr(node, "alt") ?? "") } const labels = index.labels.get(node) if (labels !== undefined) { const fromLabels = normalize( labels.map((l) => contentText(index, l, node, false)).join(" ") ) if (fromLabels !== "") return fromLabels } if (tag === "img" || tag === "area") { const alt = reader.attr(node, "alt") if (alt !== undefined && alt.trim() !== "") return normalize(alt) } if (tag === "fieldset") { const legend = firstChildText(index, node, "legend") if (legend !== undefined && legend !== "") return legend } if (tag === "table") { const caption = firstChildText(index, node, "caption") if (caption !== undefined && caption !== "") return caption } if (tag === "figure") { const caption = firstChildText(index, node, "figcaption") if (caption !== undefined && caption !== "") return caption } if (entry.role !== undefined && nameFromContent.has(entry.role)) { const content = normalize(contentText(index, node, undefined, false)) if (content !== "") return content } const title = reader.attr(node, "title") if (title !== undefined && title.trim() !== "") return normalize(title) if (tag === "input" || tag === "textarea") { const placeholder = reader.attr(node, "placeholder") if (placeholder !== undefined) return normalize(placeholder) } return "" } const isChecked = (reader: Reader, node: N): boolean | undefined => { const aria = reader.attr(node, "aria-checked") if (aria !== undefined) return aria === "true" if (reader.tag(node) !== "input") return undefined const prop = reader.prop(node, "checked") if (typeof prop === "boolean") return prop return reader.attr(node, "checked") !== undefined } const levelOf = (reader: Reader, node: N): number | undefined => { const aria = reader.attr(node, "aria-level") if (aria !== undefined) return Number(aria) const match = /^h([1-6])$/.exec(reader.tag(node)) return match === null ? undefined : Number(match[1]) } // --------------------------------------------------------------------------- // queries // --------------------------------------------------------------------------- /** * What a role query matches besides the role. * * **Details** * * `name` matches the accessible name exactly (after collapsing whitespace), * or tests it with a RegExp. `checked` matches a checkbox or radio button's * live state, `expanded` matches an explicit `aria-expanded` attribute * (`"true"` or `"false"`), and `level` a heading's. `hidden: true` includes * hidden and inert elements for inspection; simulated user actions still * refuse inert targets. * * @stability unstable * @category models * @since 4.2.0 */ export interface RoleOptions { readonly name?: string | RegExp | undefined readonly checked?: boolean | undefined readonly expanded?: boolean | undefined readonly level?: number | undefined readonly hidden?: boolean | undefined } const describeOptions = ( role: string, options: RoleOptions | undefined ): string => { const parts = [`role ${JSON.stringify(role)}`] if (options?.name !== undefined) { parts.push( `name ${ typeof options.name === "string" ? JSON.stringify(options.name) : String(options.name) }` ) } for (const key of ["checked", "expanded", "level"] as const) { if (options?.[key] !== undefined) parts.push(`${key} ${options[key]}`) } return parts.join(", ") } const select = ( index: Index, role: string, options: RoleOptions | undefined ): Array => { const out: Array = [] const name = options?.name const nameMatches = name === undefined ? undefined : matcher(typeof name === "string" ? normalize(name) : name) for (const entry of index.entries) { if (entry.role !== role) continue if (entry.hidden && options?.hidden !== true) continue if ( options?.checked !== undefined && isChecked(index.reader, entry.node) !== options.checked ) continue if ( options?.expanded !== undefined && index.reader.attr(entry.node, "aria-expanded") !== `${options.expanded}` ) continue if ( options?.level !== undefined && levelOf(index.reader, entry.node) !== options.level ) continue if (nameMatches !== undefined && !nameMatches(computeName(index, entry))) { continue } out.push(entry.node) } return out } /** * Every element under `root`, `root` included, with role `role` and matching * `options`, in document order. * * @stability unstable * @category queries * @since 4.2.0 */ export const queryAllByRole: { ( root: globalThis.Node, role: AriaRole, options?: RoleOptions ): ReadonlyArray ( root: Locator.Node, role: AriaRole, options?: RoleOptions ): ReadonlyArray } = (root: any, role: AriaRole, options?: RoleOptions): ReadonlyArray => select(buildIndex(root), role, options) /** * The one element under `root` with role `role` and matching `options`. * Throws when there's none or several, listing the roles and names there are. * * @stability unstable * @category queries * @since 4.2.0 */ export const getByRole: { (root: globalThis.Node, role: AriaRole, options?: RoleOptions): HTMLElement (root: Locator.Node, role: AriaRole, options?: RoleOptions): Locator.Node } = (root: any, role: AriaRole, options?: RoleOptions): any => { const index = buildIndex(root) const found = select(index, role, options) if (found.length === 1) return found[0] if (found.length > 1) { throw new Error( `HtmlLocator: ${found.length} elements have ${describeOptions(role, options)}` ) } throw new Error( `HtmlLocator: nothing has ${describeOptions(role, options)}. Roles here:\n${describeIndex(index)}` ) } const describeIndex = (index: Index): string => { const lines = index.entries .filter((entry) => entry.role !== undefined && !entry.hidden) .map((entry) => ` ${entry.role} ${JSON.stringify(computeName(index, entry))}`) return lines.length === 0 ? " (none)" : lines.join("\n") } /** * The role of `node`: its `role` attribute, else the implicit role of its tag * and attributes, else `undefined`. `root` is the tree it's in, which decides * the role of `header` and `footer`. * * @stability unstable * @category getters * @since 4.2.0 */ export const roleOf: { (root: globalThis.Node, node: globalThis.Node): string | undefined (root: Locator.Node, node: Locator.Node): string | undefined } = (root: any, node: any): string | undefined => buildIndex(root).byNode.get(node)?.role /** * The accessible name of `node`, computed within `root`: from * `aria-labelledby`, `aria-label`, its labels, `alt`, a `legend` or `caption`, * its content for roles named by their content, then `title` and * `placeholder`. * * @stability unstable * @category getters * @since 4.2.0 */ export const nameOf: { (root: globalThis.Node, node: globalThis.Node): string (root: Locator.Node, node: Locator.Node): string } = (root: any, node: any): string => { const index = buildIndex(root) const entry = index.byNode.get(node) return entry === undefined ? "" : computeName(index, entry) } /** * A `Locator` for elements with role `role` and matching `options`, to * combine with `Locator.inside` and the other locators. * * @stability unstable * @category locators * @since 4.2.0 */ export const role = ( role: AriaRole, options?: RoleOptions ): Locator.Locator => Locator.make( describeOptions(role, options), (root) => select(buildIndex(root), role, options) ) // --------------------------------------------------------------------------- // acting on the DOM // --------------------------------------------------------------------------- /** * The form fields labelled `text`: by a `