@zerolith/a11y 0.0.0-stage → 0.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +33 -2
- package/dist/announce.d.ts +26 -0
- package/dist/announce.d.ts.map +1 -0
- package/dist/announce.js +58 -0
- package/dist/announce.js.map +1 -0
- package/dist/focus.d.ts +58 -0
- package/dist/focus.d.ts.map +1 -0
- package/dist/focus.js +240 -0
- package/dist/focus.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/media.d.ts +12 -0
- package/dist/media.d.ts.map +1 -0
- package/dist/media.js +32 -0
- package/dist/media.js.map +1 -0
- package/dist/production/announce.js +4 -0
- package/dist/production/announce.js.map +1 -0
- package/dist/production/focus.js +2 -0
- package/dist/production/focus.js.map +1 -0
- package/dist/production/index.js +2 -0
- package/dist/production/index.js.map +1 -0
- package/dist/production/media.js +2 -0
- package/dist/production/media.js.map +1 -0
- package/package.json +50 -5
- package/src/announce.ts +79 -0
- package/src/focus.ts +331 -0
- package/src/index.ts +11 -0
- package/src/media.ts +41 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zerolith/a11y: the accessibility primitives every component library
|
|
3
|
+
* rebuilds, as functions over the DOM. The public surface is assembled here.
|
|
4
|
+
*/
|
|
5
|
+
export type { FocusOrigin, FocusOriginMonitor, FocusTrapOptions, RovingOptions } from "./focus.js";
|
|
6
|
+
export { focusOrigin, focusTrap, focusables, rovingTabindex } from "./focus.js";
|
|
7
|
+
export type { Announcer, Politeness } from "./announce.js";
|
|
8
|
+
export { createAnnouncer, visuallyHidden } from "./announce.js";
|
|
9
|
+
export { forcedColors, mediaQuery, reducedMotion } from "./media.js";
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEhF,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEhE,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAGhF,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEhE,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/media.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media queries as signals, for the preferences a component should follow:
|
|
3
|
+
* forced colors and reduced motion first.
|
|
4
|
+
*/
|
|
5
|
+
import { type ReadableSignal } from "zerolith";
|
|
6
|
+
/** A media query as a signal that follows the query's matches; false wherever `matchMedia` does not exist, such as on the server. */
|
|
7
|
+
export declare function mediaQuery(query: string): ReadableSignal<boolean>;
|
|
8
|
+
/** True while the user agent is in forced colors mode, such as Windows high contrast, where author colors are replaced by system ones. */
|
|
9
|
+
export declare function forcedColors(): ReadableSignal<boolean>;
|
|
10
|
+
/** True while the user has asked for reduced motion. */
|
|
11
|
+
export declare function reducedMotion(): ReadableSignal<boolean>;
|
|
12
|
+
//# sourceMappingURL=media.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"media.d.ts","sourceRoot":"","sources":["../src/media.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,cAAc,EAAU,MAAM,UAAU,CAAC;AAIvD,qIAAqI;AACrI,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,CAAC,OAAO,CAAC,CAmBjE;AAED,0IAA0I;AAC1I,wBAAgB,YAAY,IAAI,cAAc,CAAC,OAAO,CAAC,CAGtD;AAED,wDAAwD;AACxD,wBAAgB,aAAa,IAAI,cAAc,CAAC,OAAO,CAAC,CAGvD"}
|
package/dist/media.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media queries as signals, for the preferences a component should follow:
|
|
3
|
+
* forced colors and reduced motion first.
|
|
4
|
+
*/
|
|
5
|
+
import { signal } from "zerolith";
|
|
6
|
+
const queries = new Map();
|
|
7
|
+
/** A media query as a signal that follows the query's matches; false wherever `matchMedia` does not exist, such as on the server. */
|
|
8
|
+
export function mediaQuery(query) {
|
|
9
|
+
let existing = queries.get(query);
|
|
10
|
+
if (existing === undefined) {
|
|
11
|
+
if (typeof matchMedia === "undefined") {
|
|
12
|
+
existing = signal(false);
|
|
13
|
+
}
|
|
14
|
+
else {
|
|
15
|
+
const list = matchMedia(query);
|
|
16
|
+
const matches = signal(list.matches);
|
|
17
|
+
list.addEventListener("change", (event) => matches.set(event.matches));
|
|
18
|
+
existing = matches;
|
|
19
|
+
}
|
|
20
|
+
queries.set(query, existing);
|
|
21
|
+
}
|
|
22
|
+
return existing;
|
|
23
|
+
}
|
|
24
|
+
/** True while the user agent is in forced colors mode, such as Windows high contrast, where author colors are replaced by system ones. */
|
|
25
|
+
export function forcedColors() {
|
|
26
|
+
return mediaQuery("(forced-colors: active)");
|
|
27
|
+
}
|
|
28
|
+
/** True while the user has asked for reduced motion. */
|
|
29
|
+
export function reducedMotion() {
|
|
30
|
+
return mediaQuery("(prefers-reduced-motion: reduce)");
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=media.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"media.js","sourceRoot":"","sources":["../src/media.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAuB,MAAM,EAAE,MAAM,UAAU,CAAC;AAEvD,MAAM,OAAO,GAAG,IAAI,GAAG,EAAmC,CAAC;AAE3D,qIAAqI;AACrI,MAAM,UAAU,UAAU,CAAC,KAAa;IAEpC,IAAI,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAClC,IAAI,QAAQ,KAAK,SAAS,EAC1B,CAAC;QACG,IAAI,OAAO,UAAU,KAAK,WAAW,EACrC,CAAC;YACG,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC;aAED,CAAC;YACG,MAAM,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;YAC/B,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACrC,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;YACvE,QAAQ,GAAG,OAAO,CAAC;QACvB,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,QAAQ,CAAC;AACpB,CAAC;AAED,0IAA0I;AAC1I,MAAM,UAAU,YAAY;IAExB,OAAO,UAAU,CAAC,yBAAyB,CAAC,CAAC;AACjD,CAAC;AAED,wDAAwD;AACxD,MAAM,UAAU,aAAa;IAEzB,OAAO,UAAU,CAAC,kCAAkC,CAAC,CAAC;AAC1D,CAAC"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{css as e}from"zerolith";export const visuallyHidden=e`
|
|
2
|
+
:scope { position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
3
|
+
`;export function createAnnouncer(e=document){let t=new Map,n=n=>{let r=t.get(n);return r===void 0&&(r=e.createElement(`div`),r.setAttribute(`aria-live`,n),r.setAttribute(`aria-atomic`,`true`),r.setAttribute(`role`,n===`assertive`?`alert`:`status`),r.className=`zl-s ${visuallyHidden.scope}`,r.setAttribute(`style`,`position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;`),e.body.append(r),t.set(n,r)),r};n(`polite`),n(`assertive`);let r=new Map;return{announce(e,t=`polite`){let i=n(t);i.textContent=``,clearTimeout(r.get(t)),r.set(t,setTimeout(()=>{i.textContent=e},0))},dispose(){for(let e of r.values())clearTimeout(e);r.clear();for(let e of t.values())e.remove();t.clear()}}}
|
|
4
|
+
//# sourceMappingURL=announce.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"announce.js","sources":["../../src/announce.ts"],"sourcesContent":["/**\n * The live announcer and the visually hidden style it uses: text for\n * assistive technology that takes no space on screen.\n */\nimport { type Styles, css } from \"zerolith\";\n\n/** The clip pattern that hides an element visually while assistive technology still reads it. */\nexport const visuallyHidden: Styles = css`\n :scope { position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }\n`;\n\n/** How urgently a message is read. */\nexport type Politeness = \"polite\" | \"assertive\";\n\n/** What `createAnnouncer` returns. */\nexport interface Announcer\n{\n /** Queues a message for the live region; `assertive` interrupts what is being read. */\n announce(message: string, politeness?: Politeness): void;\n /** Removes the live regions. */\n dispose(): void;\n}\n\n/**\n * Creates a pair of live regions, one polite and one assertive, appended to\n * the document body at once, so assistive technology knows them before the\n * first message, and hidden visually by inline styles, which hold in any\n * document `doc` names. Each announcement clears the\n * region and writes the message on the next task, so repeating a message\n * is read again.\n */\nexport function createAnnouncer(doc: Document = document): Announcer\n{\n const regions = new Map<Politeness, HTMLElement>();\n const region = (politeness: Politeness): HTMLElement =>\n {\n let element = regions.get(politeness);\n if (element === undefined)\n {\n element = doc.createElement(\"div\");\n element.setAttribute(\"aria-live\", politeness);\n element.setAttribute(\"aria-atomic\", \"true\");\n element.setAttribute(\"role\", politeness === \"assertive\" ? \"alert\" : \"status\");\n element.className = `zl-s ${visuallyHidden.scope}`;\n element.setAttribute(\"style\", \"position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;\");\n doc.body.append(element);\n regions.set(politeness, element);\n }\n return element;\n };\n region(\"polite\");\n region(\"assertive\");\n const timers = new Map<Politeness, ReturnType<typeof setTimeout>>();\n return {\n announce(message: string, politeness: Politeness = \"polite\"): void\n {\n const element = region(politeness);\n element.textContent = \"\";\n clearTimeout(timers.get(politeness));\n timers.set(politeness, setTimeout(() =>\n {\n element.textContent = message;\n }, 0));\n },\n dispose(): void\n {\n for (const timer of timers.values())\n {\n clearTimeout(timer);\n }\n timers.clear();\n for (const element of regions.values())\n {\n element.remove();\n }\n regions.clear();\n }\n };\n}\n"],"names":["regions","region","element","politeness","doc","timers","message","timer"],"mappings":"AAIA,OAAsB,aAAW,WAGjC,OAAO,MAAM,eAAyB,CAAG;;EAwBzC,OAAM,SAAU,gBAAgB,EAAgB,SAAQ,CAEpD,IAAMA,EAAU,IAAI,IACdC,EAAU,GAAuC,CAEnD,IAAIC,EAAUF,EAAQ,IAAIG,CAAU,EAYpC,OAXID,IAAY,SAEZ,EAAUE,EAAI,cAAc,KAAK,EACjCF,EAAQ,aAAa,YAAaC,CAAU,EAC5CD,EAAQ,aAAa,cAAe,MAAM,EAC1CA,EAAQ,aAAa,OAAQC,IAAe,YAAc,QAAU,QAAQ,EAC5E,EAAQ,UAAY,QAAQ,eAAe,QAC3CD,EAAQ,aAAa,QAAS,iJAAiJ,EAC/KE,EAAI,KAAK,OAAOF,CAAO,EACvBF,EAAQ,IAAIG,EAAYD,CAAO,GAE5BA,CACX,EACAD,EAAO,QAAQ,EACfA,EAAO,WAAW,EAClB,IAAMI,EAAS,IAAI,IACnB,MAAO,CACH,SAAS,EAAiB,EAAyB,SAAQ,CAEvD,IAAMH,EAAUD,EAAOE,CAAU,EACjC,EAAQ,YAAc,GACtB,aAAaE,EAAO,IAAIF,CAAU,CAAC,EACnCE,EAAO,IAAIF,EAAY,eAAgB,CAEnC,EAAQ,YAAcG,CAC1B,EAAG,CAAC,CAAC,CACT,EACA,SAAO,CAEH,IAAK,IAAMC,KAASF,EAAO,OAAM,EAE7B,aAAaE,CAAK,EAEtBF,EAAO,MAAK,EACZ,IAAK,IAAMH,KAAWF,EAAQ,OAAM,EAEhCE,EAAQ,OAAM,EAElBF,EAAQ,MAAK,CACjB,CACH,CACL"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{onDispose as e,signal as t}from"zerolith";function n(e){return e.getClientRects().length>0&&e.closest(`[inert]`)===null&&(e.ownerDocument.defaultView??window).getComputedStyle(e).visibility===`visible`}function r(e){return e instanceof HTMLElement?e instanceof HTMLInputElement?![`button`,`checkbox`,`color`,`file`,`hidden`,`image`,`radio`,`range`,`reset`,`submit`].includes(e.type):e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.isContentEditable:!1}export function focusables(e){return[...e.querySelectorAll(`a[href], area[href], button:not(:disabled), input:not(:disabled):not([type=hidden]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"]):not(:disabled), [contenteditable="true"], audio[controls], video[controls], details > summary, iframe`)].filter(n)}const i=[];export function focusTrap(t={}){return n=>{let r=n.ownerDocument,a=r.activeElement instanceof HTMLElement?r.activeElement:null,o=()=>{let e=focusables(n)[0];return e===void 0?(n.hasAttribute(`tabindex`)||n.setAttribute(`tabindex`,`-1`),n):e},s=!1;i.push(n);let c=t.initial,l=()=>{!s&&n.isConnected&&c!==!1&&(typeof c==`string`?n.querySelector(c)??o():c??o()).focus()};c!==!1&&(n.isConnected?l():queueMicrotask(l));let u=e=>{let t=e;if(t.key!==`Tab`||i.at(-1)!==n)return;let a=focusables(n),o=a[0],s=a.at(-1);if(o===void 0||s===void 0){t.preventDefault();return}let c=r.activeElement;t.shiftKey&&(c===o||!n.contains(c))?(t.preventDefault(),s.focus()):t.shiftKey||c!==s&&n.contains(c)||(t.preventDefault(),o.focus())},d=e=>{i.at(-1)===n&&!n.contains(e.target)&&o().focus()};n.addEventListener(`keydown`,u),r.addEventListener(`focusin`,d),e(()=>{s=!0;let e=i.lastIndexOf(n);e!==-1&&i.splice(e,1),n.removeEventListener(`keydown`,u),r.removeEventListener(`focusin`,d),t.restore!==!1&&a!==null&&a.isConnected&&a.focus()})}}export function rovingTabindex(t={}){let i=t.items??`[data-roving], [role="tab"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="option"], [role="radio"], [role="treeitem"], [role="gridcell"]`,a=t.orientation??`both`,o=t.loop!==!1;return t=>{let s=()=>[...t.querySelectorAll(i)],c=()=>s().filter(e=>!e.hasAttribute(`disabled`)&&e.getAttribute(`aria-disabled`)!==`true`),l,u=e=>{let t=c();l=e!==void 0&&t.includes(e)?e:t.find(e=>e.getAttribute(`aria-selected`)===`true`||e.getAttribute(`aria-checked`)===`true`)??t[0];for(let e of s())e.tabIndex=e===l?0:-1},d=(e,t)=>{let r=c().filter(n);if(r.length===0)return;let i=t===`first`?0:t===`last`?r.length-1:r.indexOf(l??r[0])+e;if(i<0||i>=r.length){if(!o)return;i=(i+r.length)%r.length}let a=r[i];a!==void 0&&(u(a),a.focus())},f=e=>{let t=e;if(r(t.target)&&!c().includes(t.target))return;let n=a!==`vertical`,i=a!==`horizontal`;if(t.key===`ArrowRight`&&n||t.key===`ArrowDown`&&i)d(1);else if(t.key===`ArrowLeft`&&n||t.key===`ArrowUp`&&i)d(-1);else if(t.key===`Home`)d(0,`first`);else if(t.key===`End`)d(0,`last`);else return;t.preventDefault()},p=e=>{let n=e.target.closest(i);n!==null&&t.contains(n)&&u(n)};u(void 0);let m=new MutationObserver(()=>u(l));m.observe(t,{childList:!0,subtree:!0}),t.addEventListener(`keydown`,f),t.addEventListener(`focusin`,p),e(()=>{m.disconnect(),t.removeEventListener(`keydown`,f),t.removeEventListener(`focusin`,p)})}}export function focusOrigin(e=document){let n=t(null),r,i,a=e=>{r=e,clearTimeout(i),i=setTimeout(()=>{r=void 0},650)},o=()=>a(`keyboard`),s=e=>a(e.pointerType===`touch`?`touch`:`pointer`),c=()=>{let t=r??`program`;n.set(t),e.documentElement.setAttribute(`data-focus-origin`,t)},l=t=>{t.relatedTarget===null&&(n.set(null),e.documentElement.removeAttribute(`data-focus-origin`))};return e.addEventListener(`keydown`,o,!0),e.addEventListener(`pointerdown`,s,!0),e.addEventListener(`focusin`,c,!0),e.addEventListener(`focusout`,l,!0),{origin:n,dispose(){clearTimeout(i),e.removeEventListener(`keydown`,o,!0),e.removeEventListener(`pointerdown`,s,!0),e.removeEventListener(`focusin`,c,!0),e.removeEventListener(`focusout`,l,!0),e.documentElement.removeAttribute(`data-focus-origin`)}}}
|
|
2
|
+
//# sourceMappingURL=focus.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"focus.js","sources":["../../src/focus.ts"],"sourcesContent":["/**\n * Focus management: the trap a dialog needs, the roving tabindex a composite\n * widget needs, and a monitor that tells keyboard focus from pointer focus.\n * The trap and the roving tabindex are `ref` callbacks, so they attach when\n * the element is created and clean up when its template is removed.\n */\nimport { type ReadableSignal, onDispose, signal } from \"zerolith\";\n\nconst FOCUSABLE = \"a[href], area[href], button:not(:disabled), input:not(:disabled):not([type=hidden]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\\\"-1\\\"]):not(:disabled), [contenteditable=\\\"true\\\"], audio[controls], video[controls], details > summary, iframe\";\n\n/** True when an element is rendered, visible, and outside any `inert` subtree, so it can take focus. */\nfunction reachable(element: Element): boolean\n{\n return element.getClientRects().length > 0 && element.closest(\"[inert]\") === null && (element.ownerDocument.defaultView ?? window).getComputedStyle(element).visibility === \"visible\";\n}\n\n/** True for a control that uses the arrow keys itself: a text field, a list box, or editable text. */\nfunction editsText(target: EventTarget | null): boolean\n{\n if (!(target instanceof HTMLElement))\n {\n return false;\n }\n if (target instanceof HTMLInputElement)\n {\n return ![\"button\", \"checkbox\", \"color\", \"file\", \"hidden\", \"image\", \"radio\", \"range\", \"reset\", \"submit\"].includes(target.type);\n }\n return target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement || target.isContentEditable;\n}\n\n/** The elements inside `root` that take Tab focus, in document order, skipping anything hidden. */\nexport function focusables(root: Element): HTMLElement[]\n{\n return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter(reachable);\n}\n\n/** The elements with an attached focus trap, newest last. Only the newest acts, so a dialog opened from another keeps focus, and removing it hands control back. */\nconst traps: Element[] = [];\n\n/** Options for `focusTrap`. */\nexport interface FocusTrapOptions\n{\n /** What receives focus on attach: a selector inside the element, an element, or false to leave focus alone. Defaults to the first focusable, or the element itself. */\n initial?: string | HTMLElement | false;\n /** Returns focus to the element that had it before the trap attached. Defaults to true. */\n restore?: boolean;\n}\n\n/**\n * A `ref` that keeps Tab and Shift+Tab inside the element, pulls focus back\n * when it lands outside, moves focus in once the element is in the document,\n * and returns it where it came from when the element's template is removed.\n * With traps on several elements, as when a dialog opens a confirmation,\n * only the newest acts until its template is removed.\n */\nexport function focusTrap(options: FocusTrapOptions = {}): (element: Element) => void\n{\n return (element) =>\n {\n const doc = element.ownerDocument;\n const previous = doc.activeElement instanceof HTMLElement ? doc.activeElement : null;\n const fallback = (): HTMLElement =>\n {\n const first = focusables(element)[0];\n if (first !== undefined)\n {\n return first;\n }\n if (!element.hasAttribute(\"tabindex\"))\n {\n element.setAttribute(\"tabindex\", \"-1\");\n }\n return element as HTMLElement;\n };\n let disposed = false;\n traps.push(element);\n const initial = options.initial;\n const focusInitial = (): void =>\n {\n if (disposed || !element.isConnected || initial === false)\n {\n return;\n }\n const target = typeof initial === \"string\" ? element.querySelector<HTMLElement>(initial) ?? fallback() : initial ?? fallback();\n target.focus();\n };\n if (initial !== false)\n {\n if (element.isConnected)\n {\n focusInitial();\n }\n else\n {\n queueMicrotask(focusInitial);\n }\n }\n const onKeydown = (event: Event): void =>\n {\n const key = event as KeyboardEvent;\n if (key.key !== \"Tab\" || traps.at(-1) !== element)\n {\n return;\n }\n const list = focusables(element);\n const first = list[0];\n const last = list.at(-1);\n if (first === undefined || last === undefined)\n {\n key.preventDefault();\n return;\n }\n const active = doc.activeElement;\n if (key.shiftKey && (active === first || !element.contains(active)))\n {\n key.preventDefault();\n last.focus();\n }\n else if (!key.shiftKey && (active === last || !element.contains(active)))\n {\n key.preventDefault();\n first.focus();\n }\n };\n const onFocusIn = (event: Event): void =>\n {\n if (traps.at(-1) === element && !element.contains(event.target as Node))\n {\n fallback().focus();\n }\n };\n element.addEventListener(\"keydown\", onKeydown);\n doc.addEventListener(\"focusin\", onFocusIn);\n onDispose(() =>\n {\n disposed = true;\n const index = traps.lastIndexOf(element);\n if (index !== -1)\n {\n traps.splice(index, 1);\n }\n element.removeEventListener(\"keydown\", onKeydown);\n doc.removeEventListener(\"focusin\", onFocusIn);\n if (options.restore !== false && previous !== null && previous.isConnected)\n {\n previous.focus();\n }\n });\n };\n}\n\n/** Options for `rovingTabindex`. */\nexport interface RovingOptions\n{\n /** The selector of the items. Defaults to the ARIA roles of composite widgets plus `[data-roving]`. */\n items?: string;\n /** Which arrow keys move: `horizontal` (left and right), `vertical` (up and down), or `both`. Defaults to both. */\n orientation?: \"horizontal\" | \"vertical\" | \"both\";\n /** Wraps from the last item to the first and back. Defaults to true. */\n loop?: boolean;\n}\n\nconst ROVING_ITEMS = \"[data-roving], [role=\\\"tab\\\"], [role=\\\"menuitem\\\"], [role=\\\"menuitemcheckbox\\\"], [role=\\\"menuitemradio\\\"], [role=\\\"option\\\"], [role=\\\"radio\\\"], [role=\\\"treeitem\\\"], [role=\\\"gridcell\\\"]\";\n\n/**\n * A `ref` for a composite widget: exactly one item is in the Tab order, the\n * arrow keys, Home, and End move between items, and the item that was\n * selected or checked starts as the current one. Disabled, hidden, and\n * inert items are skipped, as the children of a collapsed tree item are.\n */\nexport function rovingTabindex(options: RovingOptions = {}): (element: Element) => void\n{\n const selector = options.items ?? ROVING_ITEMS;\n const orientation = options.orientation ?? \"both\";\n const loop = options.loop !== false;\n return (element) =>\n {\n const all = (): HTMLElement[] => [...element.querySelectorAll<HTMLElement>(selector)];\n const items = (): HTMLElement[] => all().filter((item) => !item.hasAttribute(\"disabled\") && item.getAttribute(\"aria-disabled\") !== \"true\");\n let current: HTMLElement | undefined;\n const apply = (next: HTMLElement | undefined): void =>\n {\n const list = items();\n current = next !== undefined && list.includes(next) ? next : list.find((item) => item.getAttribute(\"aria-selected\") === \"true\" || item.getAttribute(\"aria-checked\") === \"true\") ?? list[0];\n for (const item of all())\n {\n item.tabIndex = item === current ? 0 : -1;\n }\n };\n const move = (step: number, edge?: \"first\" | \"last\"): void =>\n {\n const list = items().filter(reachable);\n if (list.length === 0)\n {\n return;\n }\n let index = edge === \"first\" ? 0 : edge === \"last\" ? list.length - 1 : list.indexOf(current ?? list[0] as HTMLElement) + step;\n if (index < 0 || index >= list.length)\n {\n if (!loop)\n {\n return;\n }\n index = (index + list.length) % list.length;\n }\n const target = list[index];\n if (target !== undefined)\n {\n apply(target);\n target.focus();\n }\n };\n const onKeydown = (event: Event): void =>\n {\n const key = event as KeyboardEvent;\n if (editsText(key.target) && !items().includes(key.target as HTMLElement))\n {\n return;\n }\n const horizontal = orientation !== \"vertical\";\n const vertical = orientation !== \"horizontal\";\n if ((key.key === \"ArrowRight\" && horizontal) || (key.key === \"ArrowDown\" && vertical))\n {\n move(1);\n }\n else if ((key.key === \"ArrowLeft\" && horizontal) || (key.key === \"ArrowUp\" && vertical))\n {\n move(-1);\n }\n else if (key.key === \"Home\")\n {\n move(0, \"first\");\n }\n else if (key.key === \"End\")\n {\n move(0, \"last\");\n }\n else\n {\n return;\n }\n key.preventDefault();\n };\n const onFocusIn = (event: Event): void =>\n {\n const target = (event.target as Element).closest<HTMLElement>(selector);\n if (target !== null && element.contains(target))\n {\n apply(target);\n }\n };\n apply(undefined);\n const observer = new MutationObserver(() => apply(current));\n observer.observe(element, { childList: true, subtree: true });\n element.addEventListener(\"keydown\", onKeydown);\n element.addEventListener(\"focusin\", onFocusIn);\n onDispose(() =>\n {\n observer.disconnect();\n element.removeEventListener(\"keydown\", onKeydown);\n element.removeEventListener(\"focusin\", onFocusIn);\n });\n };\n}\n\n/** How the element that has focus got it. */\nexport type FocusOrigin = \"keyboard\" | \"pointer\" | \"touch\" | \"program\";\n\n/** What `focusOrigin` returns. */\nexport interface FocusOriginMonitor\n{\n /** The origin of the current focus, or null while nothing in the document has focus. */\n readonly origin: ReadableSignal<FocusOrigin | null>;\n /** Removes the listeners and the attribute. */\n dispose(): void;\n}\n\n/**\n * Watches how focus arrives, the way Angular CDK's focus monitor does: a key\n * pressed before focus moves means keyboard, a pointer pressed means pointer\n * or touch, anything else means program. The origin is a signal and a\n * `data-focus-origin` attribute on the root element, so a stylesheet can\n * show focus rings for keyboard users only: `[data-focus-origin=\"keyboard\"] :focus { outline: ... }`.\n */\nexport function focusOrigin(doc: Document = document): FocusOriginMonitor\n{\n const origin = signal<FocusOrigin | null>(null);\n let last: FocusOrigin | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const remember = (value: FocusOrigin): void =>\n {\n last = value;\n clearTimeout(timer);\n timer = setTimeout(() =>\n {\n last = undefined;\n }, 650);\n };\n const onKeydown = (): void => remember(\"keyboard\");\n const onPointerdown = (event: Event): void => remember((event as PointerEvent).pointerType === \"touch\" ? \"touch\" : \"pointer\");\n const onFocusIn = (): void =>\n {\n const value = last ?? \"program\";\n origin.set(value);\n doc.documentElement.setAttribute(\"data-focus-origin\", value);\n };\n const onFocusOut = (event: Event): void =>\n {\n if ((event as FocusEvent).relatedTarget === null)\n {\n origin.set(null);\n doc.documentElement.removeAttribute(\"data-focus-origin\");\n }\n };\n doc.addEventListener(\"keydown\", onKeydown, true);\n doc.addEventListener(\"pointerdown\", onPointerdown, true);\n doc.addEventListener(\"focusin\", onFocusIn, true);\n doc.addEventListener(\"focusout\", onFocusOut, true);\n return {\n origin,\n dispose(): void\n {\n clearTimeout(timer);\n doc.removeEventListener(\"keydown\", onKeydown, true);\n doc.removeEventListener(\"pointerdown\", onPointerdown, true);\n doc.removeEventListener(\"focusin\", onFocusIn, true);\n doc.removeEventListener(\"focusout\", onFocusOut, true);\n doc.documentElement.removeAttribute(\"data-focus-origin\");\n }\n };\n}\n"],"names":["reachable","element","editsText","target","root","traps","doc","previous","fallback","first","disposed","initial","options","focusInitial","onKeydown","key","event","list","last","active","onFocusIn","onDispose","index","selector","orientation","loop","all","items","item","current","apply","next","move","edge","step","horizontal","vertical","observer","origin","signal","timer","remember","value","onPointerdown","onFocusOut"],"mappings":"AAMA,OAA8B,eAAW,gBAAc,WAKvD,SAASA,EAAU,EAAgB,CAE/B,OAAOC,EAAQ,eAAc,CAAE,CAAC,OAAS,GAAKA,EAAQ,QAAQ,SAAS,IAAM,OAASA,EAAQ,cAAc,aAAe,OAAM,CAAE,iBAAiBA,CAAO,CAAC,CAAC,aAAe,SAChL,CAGA,SAASC,EAAU,EAA0B,CAUzC,OARMC,aAAkB,YAIpBA,aAAkB,iBAEX,CAAC,CAAC,SAAU,WAAY,QAAS,OAAQ,SAAU,QAAS,QAAS,QAAS,QAAS,QAAQ,CAAC,CAAC,SAASA,EAAO,IAAI,EAEzHA,aAAkB,qBAAuBA,aAAkB,mBAAqBA,EAAO,kBANnF,EAOf,CAGA,OAAM,SAAU,WAAW,EAAa,CAEpC,MAAO,CAAC,GAAGC,EAAK,iBAA8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AU,YAAY,EAAgB,SAAQ,CAEhD,IAAMkB,EAASC,EAA2B,IAAI,EAC1CrB,EACAsB,EACEC,EAAY,GAA4B,CAE1C,EAAOC,EACP,aAAaF,CAAK,EAClB,EAAQ,eAAgB,CAEpB,EAAO,MACX,EAAG,GAAG,CACV,EACM1B,MAAwB2B,EAAS,UAAU,EAC3CE,EAAiB,GAAuBF,EAAUzB,EAAuB,cAAgB,QAAU,QAAU,SAAS,EACtHI,MAAuB,CAEzB,IAAMsB,EAAQxB,GAAQ,UACtBoB,EAAO,IAAII,CAAK,EAChBpC,EAAI,gBAAgB,aAAa,oBAAqBoC,CAAK,CAC/D,EACME,EAAc,GAAsB,CAEjC5B,EAAqB,gBAAkB,OAExCsB,EAAO,IAAI,IAAI,EACfhC,EAAI,gBAAgB,gBAAgB,mBAAmB,EAE/D,EAKA,OAJAA,EAAI,iBAAiB,UAAWQ,EAAW,EAAI,EAC/CR,EAAI,iBAAiB,cAAeqC,EAAe,EAAI,EACvDrC,EAAI,iBAAiB,UAAWc,EAAW,EAAI,EAC/Cd,EAAI,iBAAiB,WAAYsC,EAAY,EAAI,EAC1C,CACH,SACA,SAAO,CAEH,aAAaJ,CAAK,EAClBlC,EAAI,oBAAoB,UAAWQ,EAAW,EAAI,EAClDR,EAAI,oBAAoB,cAAeqC,EAAe,EAAI,EAC1DrC,EAAI,oBAAoB,UAAWc,EAAW,EAAI,EAClDd,EAAI,oBAAoB,WAAYsC,EAAY,EAAI,EACpDtC,EAAI,gBAAgB,gBAAgB,mBAAmB,CAC3D,CACH,CACL"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../src/index.ts"],"sourcesContent":["/**\n * @zerolith/a11y: the accessibility primitives every component library\n * rebuilds, as functions over the DOM. The public surface is assembled here.\n */\nexport type { FocusOrigin, FocusOriginMonitor, FocusTrapOptions, RovingOptions } from \"./focus.js\";\nexport { focusOrigin, focusTrap, focusables, rovingTabindex } from \"./focus.js\";\n\nexport type { Announcer, Politeness } from \"./announce.js\";\nexport { createAnnouncer, visuallyHidden } from \"./announce.js\";\n\nexport { forcedColors, mediaQuery, reducedMotion } from \"./media.js\";\n"],"names":[],"mappings":"AAKA,OAAS,YAAa,UAAW,WAAY,mBAAsB,aAGnE,OAAS,gBAAiB,mBAAsB,gBAEhD,OAAS,aAAc,WAAY,kBAAqB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{signal as e}from"zerolith";const t=new Map;export function mediaQuery(n){let r=t.get(n);if(r===void 0){if(typeof matchMedia>`u`)r=e(!1);else{let t=matchMedia(n),i=e(t.matches);t.addEventListener(`change`,e=>i.set(e.matches)),r=i}t.set(n,r)}return r}export function forcedColors(){return mediaQuery(`(forced-colors: active)`)}export function reducedMotion(){return mediaQuery(`(prefers-reduced-motion: reduce)`)}
|
|
2
|
+
//# sourceMappingURL=media.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"media.js","sources":["../../src/media.ts"],"sourcesContent":["/**\n * Media queries as signals, for the preferences a component should follow:\n * forced colors and reduced motion first.\n */\nimport { type ReadableSignal, signal } from \"zerolith\";\n\nconst queries = new Map<string, ReadableSignal<boolean>>();\n\n/** A media query as a signal that follows the query's matches; false wherever `matchMedia` does not exist, such as on the server. */\nexport function mediaQuery(query: string): ReadableSignal<boolean>\n{\n let existing = queries.get(query);\n if (existing === undefined)\n {\n if (typeof matchMedia === \"undefined\")\n {\n existing = signal(false);\n }\n else\n {\n const list = matchMedia(query);\n const matches = signal(list.matches);\n list.addEventListener(\"change\", (event) => matches.set(event.matches));\n existing = matches;\n }\n queries.set(query, existing);\n }\n return existing;\n}\n\n/** True while the user agent is in forced colors mode, such as Windows high contrast, where author colors are replaced by system ones. */\nexport function forcedColors(): ReadableSignal<boolean>\n{\n return mediaQuery(\"(forced-colors: active)\");\n}\n\n/** True while the user has asked for reduced motion. */\nexport function reducedMotion(): ReadableSignal<boolean>\n{\n return mediaQuery(\"(prefers-reduced-motion: reduce)\");\n}\n"],"names":["queries","existing","query","signal","list","matches","event"],"mappings":"AAIA,OAA8B,gBAAc,WAE5C,MAAMA,EAAU,IAAI,IAGpB,OAAM,SAAU,WAAW,EAAa,CAEpC,IAAIC,EAAWD,EAAQ,IAAIE,CAAK,EAChC,GAAID,IAAa,OACjB,CACI,GAAI,OAAO,WAAe,IAEtB,EAAWE,EAAO,EAAK,MAG3B,CACI,IAAMC,EAAO,WAAWF,CAAK,EACvBG,EAAUF,EAAOC,EAAK,OAAO,EACnCA,EAAK,iBAAiB,SAAW,GAAUC,EAAQ,IAAIC,EAAM,OAAO,CAAC,EACrE,EAAWD,CACf,CACAL,EAAQ,IAAIE,EAAOD,CAAQ,CAC/B,CACA,OAAOA,CACX,CAGA,OAAM,SAAU,cAAY,CAExB,OAAO,WAAW,yBAAyB,CAC/C,CAGA,OAAM,SAAU,eAAa,CAEzB,OAAO,WAAW,kCAAkC,CACxD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@zerolith/a11y",
|
|
3
|
+
"version": "0.1.0-alpha.10",
|
|
4
|
+
"description": "Accessibility primitives for zerolith: focus trap, roving tabindex, live announcer, focus origin, visually hidden styles, and media query signals, the pieces every component library rebuilds",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "molexxxx",
|
|
7
|
+
"homepage": "https://zerolith.dev/",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/molexxxx/zerolith.git",
|
|
11
|
+
"directory": "packages/a11y"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/molexxxx/zerolith/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"zerolith",
|
|
18
|
+
"accessibility",
|
|
19
|
+
"a11y",
|
|
20
|
+
"focus-trap",
|
|
21
|
+
"roving-tabindex"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=24.0.0"
|
|
27
|
+
},
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"development": "./dist/index.js",
|
|
32
|
+
"default": "./dist/production/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist",
|
|
38
|
+
"src",
|
|
39
|
+
"LICENSE",
|
|
40
|
+
"README.md"
|
|
41
|
+
],
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsc -p tsconfig.build.json && node ../../scripts/production.ts"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"zerolith": "^0.1.0-alpha.10"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"zerolith": "^0.1.0-alpha.10"
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/announce.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live announcer and the visually hidden style it uses: text for
|
|
3
|
+
* assistive technology that takes no space on screen.
|
|
4
|
+
*/
|
|
5
|
+
import { type Styles, css } from "zerolith";
|
|
6
|
+
|
|
7
|
+
/** The clip pattern that hides an element visually while assistive technology still reads it. */
|
|
8
|
+
export const visuallyHidden: Styles = css`
|
|
9
|
+
:scope { position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
10
|
+
`;
|
|
11
|
+
|
|
12
|
+
/** How urgently a message is read. */
|
|
13
|
+
export type Politeness = "polite" | "assertive";
|
|
14
|
+
|
|
15
|
+
/** What `createAnnouncer` returns. */
|
|
16
|
+
export interface Announcer
|
|
17
|
+
{
|
|
18
|
+
/** Queues a message for the live region; `assertive` interrupts what is being read. */
|
|
19
|
+
announce(message: string, politeness?: Politeness): void;
|
|
20
|
+
/** Removes the live regions. */
|
|
21
|
+
dispose(): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Creates a pair of live regions, one polite and one assertive, appended to
|
|
26
|
+
* the document body at once, so assistive technology knows them before the
|
|
27
|
+
* first message, and hidden visually by inline styles, which hold in any
|
|
28
|
+
* document `doc` names. Each announcement clears the
|
|
29
|
+
* region and writes the message on the next task, so repeating a message
|
|
30
|
+
* is read again.
|
|
31
|
+
*/
|
|
32
|
+
export function createAnnouncer(doc: Document = document): Announcer
|
|
33
|
+
{
|
|
34
|
+
const regions = new Map<Politeness, HTMLElement>();
|
|
35
|
+
const region = (politeness: Politeness): HTMLElement =>
|
|
36
|
+
{
|
|
37
|
+
let element = regions.get(politeness);
|
|
38
|
+
if (element === undefined)
|
|
39
|
+
{
|
|
40
|
+
element = doc.createElement("div");
|
|
41
|
+
element.setAttribute("aria-live", politeness);
|
|
42
|
+
element.setAttribute("aria-atomic", "true");
|
|
43
|
+
element.setAttribute("role", politeness === "assertive" ? "alert" : "status");
|
|
44
|
+
element.className = `zl-s ${visuallyHidden.scope}`;
|
|
45
|
+
element.setAttribute("style", "position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;");
|
|
46
|
+
doc.body.append(element);
|
|
47
|
+
regions.set(politeness, element);
|
|
48
|
+
}
|
|
49
|
+
return element;
|
|
50
|
+
};
|
|
51
|
+
region("polite");
|
|
52
|
+
region("assertive");
|
|
53
|
+
const timers = new Map<Politeness, ReturnType<typeof setTimeout>>();
|
|
54
|
+
return {
|
|
55
|
+
announce(message: string, politeness: Politeness = "polite"): void
|
|
56
|
+
{
|
|
57
|
+
const element = region(politeness);
|
|
58
|
+
element.textContent = "";
|
|
59
|
+
clearTimeout(timers.get(politeness));
|
|
60
|
+
timers.set(politeness, setTimeout(() =>
|
|
61
|
+
{
|
|
62
|
+
element.textContent = message;
|
|
63
|
+
}, 0));
|
|
64
|
+
},
|
|
65
|
+
dispose(): void
|
|
66
|
+
{
|
|
67
|
+
for (const timer of timers.values())
|
|
68
|
+
{
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
}
|
|
71
|
+
timers.clear();
|
|
72
|
+
for (const element of regions.values())
|
|
73
|
+
{
|
|
74
|
+
element.remove();
|
|
75
|
+
}
|
|
76
|
+
regions.clear();
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
package/src/focus.ts
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Focus management: the trap a dialog needs, the roving tabindex a composite
|
|
3
|
+
* widget needs, and a monitor that tells keyboard focus from pointer focus.
|
|
4
|
+
* The trap and the roving tabindex are `ref` callbacks, so they attach when
|
|
5
|
+
* the element is created and clean up when its template is removed.
|
|
6
|
+
*/
|
|
7
|
+
import { type ReadableSignal, onDispose, signal } from "zerolith";
|
|
8
|
+
|
|
9
|
+
const FOCUSABLE = "a[href], area[href], button:not(:disabled), input:not(:disabled):not([type=hidden]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"]):not(:disabled), [contenteditable=\"true\"], audio[controls], video[controls], details > summary, iframe";
|
|
10
|
+
|
|
11
|
+
/** True when an element is rendered, visible, and outside any `inert` subtree, so it can take focus. */
|
|
12
|
+
function reachable(element: Element): boolean
|
|
13
|
+
{
|
|
14
|
+
return element.getClientRects().length > 0 && element.closest("[inert]") === null && (element.ownerDocument.defaultView ?? window).getComputedStyle(element).visibility === "visible";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** True for a control that uses the arrow keys itself: a text field, a list box, or editable text. */
|
|
18
|
+
function editsText(target: EventTarget | null): boolean
|
|
19
|
+
{
|
|
20
|
+
if (!(target instanceof HTMLElement))
|
|
21
|
+
{
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
if (target instanceof HTMLInputElement)
|
|
25
|
+
{
|
|
26
|
+
return !["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"].includes(target.type);
|
|
27
|
+
}
|
|
28
|
+
return target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement || target.isContentEditable;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The elements inside `root` that take Tab focus, in document order, skipping anything hidden. */
|
|
32
|
+
export function focusables(root: Element): HTMLElement[]
|
|
33
|
+
{
|
|
34
|
+
return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter(reachable);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The elements with an attached focus trap, newest last. Only the newest acts, so a dialog opened from another keeps focus, and removing it hands control back. */
|
|
38
|
+
const traps: Element[] = [];
|
|
39
|
+
|
|
40
|
+
/** Options for `focusTrap`. */
|
|
41
|
+
export interface FocusTrapOptions
|
|
42
|
+
{
|
|
43
|
+
/** What receives focus on attach: a selector inside the element, an element, or false to leave focus alone. Defaults to the first focusable, or the element itself. */
|
|
44
|
+
initial?: string | HTMLElement | false;
|
|
45
|
+
/** Returns focus to the element that had it before the trap attached. Defaults to true. */
|
|
46
|
+
restore?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A `ref` that keeps Tab and Shift+Tab inside the element, pulls focus back
|
|
51
|
+
* when it lands outside, moves focus in once the element is in the document,
|
|
52
|
+
* and returns it where it came from when the element's template is removed.
|
|
53
|
+
* With traps on several elements, as when a dialog opens a confirmation,
|
|
54
|
+
* only the newest acts until its template is removed.
|
|
55
|
+
*/
|
|
56
|
+
export function focusTrap(options: FocusTrapOptions = {}): (element: Element) => void
|
|
57
|
+
{
|
|
58
|
+
return (element) =>
|
|
59
|
+
{
|
|
60
|
+
const doc = element.ownerDocument;
|
|
61
|
+
const previous = doc.activeElement instanceof HTMLElement ? doc.activeElement : null;
|
|
62
|
+
const fallback = (): HTMLElement =>
|
|
63
|
+
{
|
|
64
|
+
const first = focusables(element)[0];
|
|
65
|
+
if (first !== undefined)
|
|
66
|
+
{
|
|
67
|
+
return first;
|
|
68
|
+
}
|
|
69
|
+
if (!element.hasAttribute("tabindex"))
|
|
70
|
+
{
|
|
71
|
+
element.setAttribute("tabindex", "-1");
|
|
72
|
+
}
|
|
73
|
+
return element as HTMLElement;
|
|
74
|
+
};
|
|
75
|
+
let disposed = false;
|
|
76
|
+
traps.push(element);
|
|
77
|
+
const initial = options.initial;
|
|
78
|
+
const focusInitial = (): void =>
|
|
79
|
+
{
|
|
80
|
+
if (disposed || !element.isConnected || initial === false)
|
|
81
|
+
{
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const target = typeof initial === "string" ? element.querySelector<HTMLElement>(initial) ?? fallback() : initial ?? fallback();
|
|
85
|
+
target.focus();
|
|
86
|
+
};
|
|
87
|
+
if (initial !== false)
|
|
88
|
+
{
|
|
89
|
+
if (element.isConnected)
|
|
90
|
+
{
|
|
91
|
+
focusInitial();
|
|
92
|
+
}
|
|
93
|
+
else
|
|
94
|
+
{
|
|
95
|
+
queueMicrotask(focusInitial);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const onKeydown = (event: Event): void =>
|
|
99
|
+
{
|
|
100
|
+
const key = event as KeyboardEvent;
|
|
101
|
+
if (key.key !== "Tab" || traps.at(-1) !== element)
|
|
102
|
+
{
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const list = focusables(element);
|
|
106
|
+
const first = list[0];
|
|
107
|
+
const last = list.at(-1);
|
|
108
|
+
if (first === undefined || last === undefined)
|
|
109
|
+
{
|
|
110
|
+
key.preventDefault();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const active = doc.activeElement;
|
|
114
|
+
if (key.shiftKey && (active === first || !element.contains(active)))
|
|
115
|
+
{
|
|
116
|
+
key.preventDefault();
|
|
117
|
+
last.focus();
|
|
118
|
+
}
|
|
119
|
+
else if (!key.shiftKey && (active === last || !element.contains(active)))
|
|
120
|
+
{
|
|
121
|
+
key.preventDefault();
|
|
122
|
+
first.focus();
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const onFocusIn = (event: Event): void =>
|
|
126
|
+
{
|
|
127
|
+
if (traps.at(-1) === element && !element.contains(event.target as Node))
|
|
128
|
+
{
|
|
129
|
+
fallback().focus();
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
element.addEventListener("keydown", onKeydown);
|
|
133
|
+
doc.addEventListener("focusin", onFocusIn);
|
|
134
|
+
onDispose(() =>
|
|
135
|
+
{
|
|
136
|
+
disposed = true;
|
|
137
|
+
const index = traps.lastIndexOf(element);
|
|
138
|
+
if (index !== -1)
|
|
139
|
+
{
|
|
140
|
+
traps.splice(index, 1);
|
|
141
|
+
}
|
|
142
|
+
element.removeEventListener("keydown", onKeydown);
|
|
143
|
+
doc.removeEventListener("focusin", onFocusIn);
|
|
144
|
+
if (options.restore !== false && previous !== null && previous.isConnected)
|
|
145
|
+
{
|
|
146
|
+
previous.focus();
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Options for `rovingTabindex`. */
|
|
153
|
+
export interface RovingOptions
|
|
154
|
+
{
|
|
155
|
+
/** The selector of the items. Defaults to the ARIA roles of composite widgets plus `[data-roving]`. */
|
|
156
|
+
items?: string;
|
|
157
|
+
/** Which arrow keys move: `horizontal` (left and right), `vertical` (up and down), or `both`. Defaults to both. */
|
|
158
|
+
orientation?: "horizontal" | "vertical" | "both";
|
|
159
|
+
/** Wraps from the last item to the first and back. Defaults to true. */
|
|
160
|
+
loop?: boolean;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const ROVING_ITEMS = "[data-roving], [role=\"tab\"], [role=\"menuitem\"], [role=\"menuitemcheckbox\"], [role=\"menuitemradio\"], [role=\"option\"], [role=\"radio\"], [role=\"treeitem\"], [role=\"gridcell\"]";
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* A `ref` for a composite widget: exactly one item is in the Tab order, the
|
|
167
|
+
* arrow keys, Home, and End move between items, and the item that was
|
|
168
|
+
* selected or checked starts as the current one. Disabled, hidden, and
|
|
169
|
+
* inert items are skipped, as the children of a collapsed tree item are.
|
|
170
|
+
*/
|
|
171
|
+
export function rovingTabindex(options: RovingOptions = {}): (element: Element) => void
|
|
172
|
+
{
|
|
173
|
+
const selector = options.items ?? ROVING_ITEMS;
|
|
174
|
+
const orientation = options.orientation ?? "both";
|
|
175
|
+
const loop = options.loop !== false;
|
|
176
|
+
return (element) =>
|
|
177
|
+
{
|
|
178
|
+
const all = (): HTMLElement[] => [...element.querySelectorAll<HTMLElement>(selector)];
|
|
179
|
+
const items = (): HTMLElement[] => all().filter((item) => !item.hasAttribute("disabled") && item.getAttribute("aria-disabled") !== "true");
|
|
180
|
+
let current: HTMLElement | undefined;
|
|
181
|
+
const apply = (next: HTMLElement | undefined): void =>
|
|
182
|
+
{
|
|
183
|
+
const list = items();
|
|
184
|
+
current = next !== undefined && list.includes(next) ? next : list.find((item) => item.getAttribute("aria-selected") === "true" || item.getAttribute("aria-checked") === "true") ?? list[0];
|
|
185
|
+
for (const item of all())
|
|
186
|
+
{
|
|
187
|
+
item.tabIndex = item === current ? 0 : -1;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
const move = (step: number, edge?: "first" | "last"): void =>
|
|
191
|
+
{
|
|
192
|
+
const list = items().filter(reachable);
|
|
193
|
+
if (list.length === 0)
|
|
194
|
+
{
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
let index = edge === "first" ? 0 : edge === "last" ? list.length - 1 : list.indexOf(current ?? list[0] as HTMLElement) + step;
|
|
198
|
+
if (index < 0 || index >= list.length)
|
|
199
|
+
{
|
|
200
|
+
if (!loop)
|
|
201
|
+
{
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
index = (index + list.length) % list.length;
|
|
205
|
+
}
|
|
206
|
+
const target = list[index];
|
|
207
|
+
if (target !== undefined)
|
|
208
|
+
{
|
|
209
|
+
apply(target);
|
|
210
|
+
target.focus();
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
const onKeydown = (event: Event): void =>
|
|
214
|
+
{
|
|
215
|
+
const key = event as KeyboardEvent;
|
|
216
|
+
if (editsText(key.target) && !items().includes(key.target as HTMLElement))
|
|
217
|
+
{
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
const horizontal = orientation !== "vertical";
|
|
221
|
+
const vertical = orientation !== "horizontal";
|
|
222
|
+
if ((key.key === "ArrowRight" && horizontal) || (key.key === "ArrowDown" && vertical))
|
|
223
|
+
{
|
|
224
|
+
move(1);
|
|
225
|
+
}
|
|
226
|
+
else if ((key.key === "ArrowLeft" && horizontal) || (key.key === "ArrowUp" && vertical))
|
|
227
|
+
{
|
|
228
|
+
move(-1);
|
|
229
|
+
}
|
|
230
|
+
else if (key.key === "Home")
|
|
231
|
+
{
|
|
232
|
+
move(0, "first");
|
|
233
|
+
}
|
|
234
|
+
else if (key.key === "End")
|
|
235
|
+
{
|
|
236
|
+
move(0, "last");
|
|
237
|
+
}
|
|
238
|
+
else
|
|
239
|
+
{
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
key.preventDefault();
|
|
243
|
+
};
|
|
244
|
+
const onFocusIn = (event: Event): void =>
|
|
245
|
+
{
|
|
246
|
+
const target = (event.target as Element).closest<HTMLElement>(selector);
|
|
247
|
+
if (target !== null && element.contains(target))
|
|
248
|
+
{
|
|
249
|
+
apply(target);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
apply(undefined);
|
|
253
|
+
const observer = new MutationObserver(() => apply(current));
|
|
254
|
+
observer.observe(element, { childList: true, subtree: true });
|
|
255
|
+
element.addEventListener("keydown", onKeydown);
|
|
256
|
+
element.addEventListener("focusin", onFocusIn);
|
|
257
|
+
onDispose(() =>
|
|
258
|
+
{
|
|
259
|
+
observer.disconnect();
|
|
260
|
+
element.removeEventListener("keydown", onKeydown);
|
|
261
|
+
element.removeEventListener("focusin", onFocusIn);
|
|
262
|
+
});
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** How the element that has focus got it. */
|
|
267
|
+
export type FocusOrigin = "keyboard" | "pointer" | "touch" | "program";
|
|
268
|
+
|
|
269
|
+
/** What `focusOrigin` returns. */
|
|
270
|
+
export interface FocusOriginMonitor
|
|
271
|
+
{
|
|
272
|
+
/** The origin of the current focus, or null while nothing in the document has focus. */
|
|
273
|
+
readonly origin: ReadableSignal<FocusOrigin | null>;
|
|
274
|
+
/** Removes the listeners and the attribute. */
|
|
275
|
+
dispose(): void;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Watches how focus arrives, the way Angular CDK's focus monitor does: a key
|
|
280
|
+
* pressed before focus moves means keyboard, a pointer pressed means pointer
|
|
281
|
+
* or touch, anything else means program. The origin is a signal and a
|
|
282
|
+
* `data-focus-origin` attribute on the root element, so a stylesheet can
|
|
283
|
+
* show focus rings for keyboard users only: `[data-focus-origin="keyboard"] :focus { outline: ... }`.
|
|
284
|
+
*/
|
|
285
|
+
export function focusOrigin(doc: Document = document): FocusOriginMonitor
|
|
286
|
+
{
|
|
287
|
+
const origin = signal<FocusOrigin | null>(null);
|
|
288
|
+
let last: FocusOrigin | undefined;
|
|
289
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
290
|
+
const remember = (value: FocusOrigin): void =>
|
|
291
|
+
{
|
|
292
|
+
last = value;
|
|
293
|
+
clearTimeout(timer);
|
|
294
|
+
timer = setTimeout(() =>
|
|
295
|
+
{
|
|
296
|
+
last = undefined;
|
|
297
|
+
}, 650);
|
|
298
|
+
};
|
|
299
|
+
const onKeydown = (): void => remember("keyboard");
|
|
300
|
+
const onPointerdown = (event: Event): void => remember((event as PointerEvent).pointerType === "touch" ? "touch" : "pointer");
|
|
301
|
+
const onFocusIn = (): void =>
|
|
302
|
+
{
|
|
303
|
+
const value = last ?? "program";
|
|
304
|
+
origin.set(value);
|
|
305
|
+
doc.documentElement.setAttribute("data-focus-origin", value);
|
|
306
|
+
};
|
|
307
|
+
const onFocusOut = (event: Event): void =>
|
|
308
|
+
{
|
|
309
|
+
if ((event as FocusEvent).relatedTarget === null)
|
|
310
|
+
{
|
|
311
|
+
origin.set(null);
|
|
312
|
+
doc.documentElement.removeAttribute("data-focus-origin");
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
doc.addEventListener("keydown", onKeydown, true);
|
|
316
|
+
doc.addEventListener("pointerdown", onPointerdown, true);
|
|
317
|
+
doc.addEventListener("focusin", onFocusIn, true);
|
|
318
|
+
doc.addEventListener("focusout", onFocusOut, true);
|
|
319
|
+
return {
|
|
320
|
+
origin,
|
|
321
|
+
dispose(): void
|
|
322
|
+
{
|
|
323
|
+
clearTimeout(timer);
|
|
324
|
+
doc.removeEventListener("keydown", onKeydown, true);
|
|
325
|
+
doc.removeEventListener("pointerdown", onPointerdown, true);
|
|
326
|
+
doc.removeEventListener("focusin", onFocusIn, true);
|
|
327
|
+
doc.removeEventListener("focusout", onFocusOut, true);
|
|
328
|
+
doc.documentElement.removeAttribute("data-focus-origin");
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
}
|