/* eslint-disable @typescript-eslint/no-explicit-any */ type TemplateFn = (...args: any[]) => HTMLElement; interface ChoicesTemplateContext { _templates: Record; _docRoot?: ParentNode; passedElement?: { element?: HTMLElement }; } const labelTextFor = (ctx: ChoicesTemplateContext): string => { const id = ctx.passedElement?.element?.id; const label = id ? ctx._docRoot?.querySelector(`label[for='${id}']`) : null; return (label?.innerText ?? label?.textContent ?? '').trim(); }; // Choices.js builds its markup in script, so its templates are patched here. export const choicesAccessibilityTemplates = function (this: ChoicesTemplateContext): Record { const defaults = this._templates; return { containerOuter(this: ChoicesTemplateContext, ...args: any[]): HTMLElement { const container = defaults.containerOuter.apply(this, args); // A listbox may not contain the dropdown's own listbox. if (container.getAttribute('role') === 'listbox') { container.setAttribute('role', 'combobox'); container.setAttribute('aria-haspopup', 'listbox'); } return container; }, choiceList(this: ChoicesTemplateContext, ...args: any[]): HTMLElement { const list = defaults.choiceList.apply(this, args); const name = labelTextFor(this); if (name && list.getAttribute('role') === 'listbox') { list.setAttribute('aria-label', name); } return list; }, notice(this: ChoicesTemplateContext, ...args: any[]): HTMLElement { const notice = defaults.notice.apply(this, args); notice.setAttribute('role', 'option'); notice.setAttribute('aria-disabled', 'true'); notice.setAttribute('aria-selected', 'false'); return notice; }, item(this: ChoicesTemplateContext, ...args: any[]): HTMLElement { const item = defaults.item.apply(this, args); // An option may not contain a button. if (item.querySelector('button')) { item.removeAttribute('role'); item.removeAttribute('aria-selected'); } return item; }, itemList(this: ChoicesTemplateContext, ...args: any[]): HTMLElement { const list = defaults.itemList.apply(this, args); if (list.classList.contains('choices__list--multiple')) { list.removeAttribute('role'); } return list; }, }; }; interface DropdownLike { element: HTMLElement; show: () => unknown; hide: () => unknown; } // `aria-expanded` is not allowed on the dropdown `
`; show and hide set it again. export const stripDropdownAriaExpanded = (dropdown: DropdownLike | undefined): void => { if (!dropdown?.element || (dropdown as { _gdsAriaPatched?: boolean })._gdsAriaPatched) { return; } (dropdown as { _gdsAriaPatched?: boolean })._gdsAriaPatched = true; const strip = (): void => dropdown.element.removeAttribute('aria-expanded'); for (const method of ['show', 'hide'] as const) { const original = dropdown[method].bind(dropdown); dropdown[method] = (): unknown => { const result = original(); strip(); return result; }; } strip(); };