@zerolith/a11y 0.0.0-stage → 0.1.0-alpha.2

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @zerolith/a11y
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The accessibility primitives every component library rebuilds, as plain functions over the DOM with no dependency beyond `zerolith`.
4
+
5
+ ```ts
6
+ import { html } from "zerolith";
7
+ import { createAnnouncer, focusTrap, rovingTabindex, visuallyHidden } from "@zerolith/a11y";
8
+
9
+ html`<div role="dialog" aria-modal="true" ref=${focusTrap()}>...</div>`;
10
+ html`<div role="tablist" ref=${rovingTabindex({ orientation: "horizontal" })}>...</div>`;
11
+ html`<span class=${visuallyHidden}>Opens in a new window</span>`;
12
+ createAnnouncer().announce("Saved");
13
+ ```
14
+
15
+ - `focusTrap` keeps Tab inside an element, moves focus in on attach, and returns it on removal.
16
+ - `rovingTabindex` makes one item of a composite widget tabbable and moves between items with the arrow keys, Home, and End.
17
+ - `createAnnouncer` speaks messages through a live region.
18
+ - `focusOrigin` tells keyboard focus from pointer focus, as a signal and as a `data-focus-origin` attribute on the root element for styling.
19
+ - `visuallyHidden` is the clip pattern for text meant for assistive technology only.
20
+ - `mediaQuery`, `forcedColors`, and `reducedMotion` are media queries as signals.
21
+
22
+ The guide is on the [docs site](https://molexxxx.github.io/zerolith/guide/accessibility/).
23
+
24
+ Status: alpha. Install with `npm install @zerolith/a11y@alpha`; the API may change before 1.0.
25
+
26
+ ## License
27
+
28
+ Apache-2.0. See `LICENSE`.
@@ -0,0 +1,24 @@
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 } from "zerolith";
6
+ /** The clip pattern that hides an element visually while assistive technology still reads it. */
7
+ export declare const visuallyHidden: Styles;
8
+ /** How urgently a message is read. */
9
+ export type Politeness = "polite" | "assertive";
10
+ /** What `createAnnouncer` returns. */
11
+ export interface Announcer {
12
+ /** Queues a message for the live region; `assertive` interrupts what is being read. */
13
+ announce(message: string, politeness?: Politeness): void;
14
+ /** Removes the live regions. */
15
+ dispose(): void;
16
+ }
17
+ /**
18
+ * Creates a pair of live regions, one polite and one assertive, appended to
19
+ * the document body and hidden visually. Each announcement clears the
20
+ * region and writes the message on the next task, so repeating a message
21
+ * is read again.
22
+ */
23
+ export declare function createAnnouncer(doc?: Document): Announcer;
24
+ //# sourceMappingURL=announce.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"announce.d.ts","sourceRoot":"","sources":["../src/announce.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,MAAM,EAAO,MAAM,UAAU,CAAC;AAE5C,iGAAiG;AACjG,eAAO,MAAM,cAAc,EAAE,MAE5B,CAAC;AAEF,sCAAsC;AACtC,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEhD,sCAAsC;AACtC,MAAM,WAAW,SAAS;IAEtB,uFAAuF;IACvF,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;IACzD,gCAAgC;IAChC,OAAO,IAAI,IAAI,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,GAAE,QAAmB,GAAG,SAAS,CAwCnE"}
@@ -0,0 +1,50 @@
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 { css } from "zerolith";
6
+ /** The clip pattern that hides an element visually while assistive technology still reads it. */
7
+ export const visuallyHidden = css `
8
+ :scope { position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
9
+ `;
10
+ /**
11
+ * Creates a pair of live regions, one polite and one assertive, appended to
12
+ * the document body and hidden visually. Each announcement clears the
13
+ * region and writes the message on the next task, so repeating a message
14
+ * is read again.
15
+ */
16
+ export function createAnnouncer(doc = document) {
17
+ const regions = new Map();
18
+ const region = (politeness) => {
19
+ let element = regions.get(politeness);
20
+ if (element === undefined) {
21
+ element = doc.createElement("div");
22
+ element.setAttribute("aria-live", politeness);
23
+ element.setAttribute("aria-atomic", "true");
24
+ element.setAttribute("role", politeness === "assertive" ? "alert" : "status");
25
+ element.className = `zl-s ${visuallyHidden.scope}`;
26
+ doc.body.append(element);
27
+ regions.set(politeness, element);
28
+ }
29
+ return element;
30
+ };
31
+ let timer;
32
+ return {
33
+ announce(message, politeness = "polite") {
34
+ const element = region(politeness);
35
+ element.textContent = "";
36
+ clearTimeout(timer);
37
+ timer = setTimeout(() => {
38
+ element.textContent = message;
39
+ }, 0);
40
+ },
41
+ dispose() {
42
+ clearTimeout(timer);
43
+ for (const element of regions.values()) {
44
+ element.remove();
45
+ }
46
+ regions.clear();
47
+ }
48
+ };
49
+ }
50
+ //# sourceMappingURL=announce.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"announce.js","sourceRoot":"","sources":["../src/announce.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAe,GAAG,EAAE,MAAM,UAAU,CAAC;AAE5C,iGAAiG;AACjG,MAAM,CAAC,MAAM,cAAc,GAAW,GAAG,CAAA;;CAExC,CAAC;AAcF;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,GAAG,GAAa,QAAQ;IAEpD,MAAM,OAAO,GAAG,IAAI,GAAG,EAA2B,CAAC;IACnD,MAAM,MAAM,GAAG,CAAC,UAAsB,EAAe,EAAE;QAEnD,IAAI,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACtC,IAAI,OAAO,KAAK,SAA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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 } from "zerolith";
8
+ /** The elements inside `root` that take Tab focus, in document order, skipping anything hidden. */
9
+ export declare function focusables(root: Element): HTMLElement[];
10
+ /** Options for `focusTrap`. */
11
+ export interface FocusTrapOptions {
12
+ /** 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. */
13
+ initial?: string | HTMLElement | false;
14
+ /** Returns focus to the element that had it before the trap attached. Defaults to true. */
15
+ restore?: boolean;
16
+ }
17
+ /**
18
+ * A `ref` that keeps Tab and Shift+Tab inside the element, pulls focus back
19
+ * when it lands outside, moves focus in once the element is in the document,
20
+ * and returns it where it came from when the element's template is removed.
21
+ */
22
+ export declare function focusTrap(options?: FocusTrapOptions): (element: Element) => void;
23
+ /** Options for `rovingTabindex`. */
24
+ export interface RovingOptions {
25
+ /** The selector of the items. Defaults to the ARIA roles of composite widgets plus `[data-roving]`. */
26
+ items?: string;
27
+ /** Which arrow keys move: `horizontal` (left and right), `vertical` (up and down), or `both`. Defaults to both. */
28
+ orientation?: "horizontal" | "vertical" | "both";
29
+ /** Wraps from the last item to the first and back. Defaults to true. */
30
+ loop?: boolean;
31
+ }
32
+ /**
33
+ * A `ref` for a composite widget: exactly one item is in the Tab order, the
34
+ * arrow keys, Home, and End move between items, and the item that was
35
+ * selected or checked starts as the current one.
36
+ */
37
+ export declare function rovingTabindex(options?: RovingOptions): (element: Element) => void;
38
+ /** How the element that has focus got it. */
39
+ export type FocusOrigin = "keyboard" | "pointer" | "touch" | "program";
40
+ /** What `focusOrigin` returns. */
41
+ export interface FocusOriginMonitor {
42
+ /** The origin of the current focus, or null while nothing in the document has focus. */
43
+ readonly origin: ReadableSignal<FocusOrigin | null>;
44
+ /** Removes the listeners and the attribute. */
45
+ dispose(): void;
46
+ }
47
+ /**
48
+ * Watches how focus arrives, the way Angular CDK's focus monitor does: a key
49
+ * pressed before focus moves means keyboard, a pointer pressed means pointer
50
+ * or touch, anything else means program. The origin is a signal and a
51
+ * `data-focus-origin` attribute on the root element, so a stylesheet can
52
+ * show focus rings for keyboard users only: `[data-focus-origin="keyboard"] :focus { outline: ... }`.
53
+ */
54
+ export declare function focusOrigin(doc?: Document): FocusOriginMonitor;
55
+ //# sourceMappingURL=focus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focus.d.ts","sourceRoot":"","sources":["../src/focus.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,KAAK,cAAc,EAAqB,MAAM,UAAU,CAAC;AAIlE,mGAAmG;AACnG,wBAAgB,UAAU,CAAC,IAAI,EAAE,OAAO,GAAG,WAAW,EAAE,CAGvD;AAED,+BAA+B;AAC/B,MAAM,WAAW,gBAAgB;IAE7B,uKAAuK;IACvK,OAAO,CAAC,EAAE,MAAM,GAAG,WAAW,GAAG,KAAK,CAAC;IACvC,2FAA2F;IAC3F,OAAO,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAwFpF;AAED,oCAAoC;AACpC,MAAM,WAAW,aAAa;IAE1B,uGAAuG;IACvG,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,mHAAmH;IACnH,WAAW,CAAC,EAAE,YAAY,GAAG,UAAU,GAAG,MAAM,CAAC;IACjD,wEAAwE;IACxE,IAAI,CAAC,EAAE,OAAO,CAAC;CAClB;AAID;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,aAAkB,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAwFtF;AAED,6CAA6C;AAC7C,MAAM,MAAM,WAAW,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAAC;AAEvE,kCAAkC;AAClC,MAAM,WAAW,kBAAkB;IAE/B,wFAAwF;IACxF,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IACpD,+CAA+C;IAC/C,OAAO,IAAI,IAAI,CAAC;CACnB;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,GAAG,GAAE,QAAmB,GAAG,kBAAkB,CA8CxE"}
package/dist/focus.js ADDED
@@ -0,0 +1,212 @@
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 { onDispose, signal } from "zerolith";
8
+ 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\"]), [contenteditable=\"true\"], audio[controls], video[controls], details > summary, iframe";
9
+ /** The elements inside `root` that take Tab focus, in document order, skipping anything hidden. */
10
+ export function focusables(root) {
11
+ return [...root.querySelectorAll(FOCUSABLE)].filter((element) => element.getClientRects().length > 0 && element.closest("[inert]") === null);
12
+ }
13
+ /**
14
+ * A `ref` that keeps Tab and Shift+Tab inside the element, pulls focus back
15
+ * when it lands outside, moves focus in once the element is in the document,
16
+ * and returns it where it came from when the element's template is removed.
17
+ */
18
+ export function focusTrap(options = {}) {
19
+ return (element) => {
20
+ const doc = element.ownerDocument;
21
+ const previous = doc.activeElement instanceof HTMLElement ? doc.activeElement : null;
22
+ const fallback = () => {
23
+ const first = focusables(element)[0];
24
+ if (first !== undefined) {
25
+ return first;
26
+ }
27
+ if (!element.hasAttribute("tabindex")) {
28
+ element.setAttribute("tabindex", "-1");
29
+ }
30
+ return element;
31
+ };
32
+ let disposed = false;
33
+ const initial = options.initial;
34
+ const focusInitial = () => {
35
+ if (disposed || !element.isConnected || initial === false) {
36
+ return;
37
+ }
38
+ const target = typeof initial === "string" ? element.querySelector(initial) ?? fallback() : initial ?? fallback();
39
+ target.focus();
40
+ };
41
+ if (initial !== false) {
42
+ if (element.isConnected) {
43
+ focusInitial();
44
+ }
45
+ else {
46
+ queueMicrotask(focusInitial);
47
+ }
48
+ }
49
+ const onKeydown = (event) => {
50
+ const key = event;
51
+ if (key.key !== "Tab") {
52
+ return;
53
+ }
54
+ const list = focusables(element);
55
+ const first = list[0];
56
+ const last = list.at(-1);
57
+ if (first === undefined || last === undefined) {
58
+ key.preventDefault();
59
+ return;
60
+ }
61
+ const active = doc.activeElement;
62
+ if (key.shiftKey && (active === first || !element.contains(active))) {
63
+ key.preventDefault();
64
+ last.focus();
65
+ }
66
+ else if (!key.shiftKey && (active === last || !element.contains(active))) {
67
+ key.preventDefault();
68
+ first.focus();
69
+ }
70
+ };
71
+ const onFocusIn = (event) => {
72
+ if (!element.contains(event.target)) {
73
+ fallback().focus();
74
+ }
75
+ };
76
+ element.addEventListener("keydown", onKeydown);
77
+ doc.addEventListener("focusin", onFocusIn);
78
+ onDispose(() => {
79
+ disposed = true;
80
+ element.removeEventListener("keydown", onKeydown);
81
+ doc.removeEventListener("focusin", onFocusIn);
82
+ if (options.restore !== false && previous !== null && previous.isConnected) {
83
+ previous.focus();
84
+ }
85
+ });
86
+ };
87
+ }
88
+ const ROVING_ITEMS = "[data-roving], [role=\"tab\"], [role=\"menuitem\"], [role=\"menuitemcheckbox\"], [role=\"menuitemradio\"], [role=\"option\"], [role=\"radio\"], [role=\"treeitem\"], [role=\"gridcell\"]";
89
+ /**
90
+ * A `ref` for a composite widget: exactly one item is in the Tab order, the
91
+ * arrow keys, Home, and End move between items, and the item that was
92
+ * selected or checked starts as the current one.
93
+ */
94
+ export function rovingTabindex(options = {}) {
95
+ const selector = options.items ?? ROVING_ITEMS;
96
+ const orientation = options.orientation ?? "both";
97
+ const loop = options.loop !== false;
98
+ return (element) => {
99
+ const items = () => [...element.querySelectorAll(selector)].filter((item) => !item.hasAttribute("disabled") && item.getAttribute("aria-disabled") !== "true");
100
+ let current;
101
+ const apply = (next) => {
102
+ const list = items();
103
+ current = next !== undefined && list.includes(next) ? next : list.find((item) => item.getAttribute("aria-selected") === "true" || item.getAttribute("aria-checked") === "true") ?? list[0];
104
+ for (const item of list) {
105
+ item.tabIndex = item === current ? 0 : -1;
106
+ }
107
+ };
108
+ const move = (step, edge) => {
109
+ const list = items();
110
+ if (list.length === 0) {
111
+ return;
112
+ }
113
+ let index = edge === "first" ? 0 : edge === "last" ? list.length - 1 : list.indexOf(current ?? list[0]) + step;
114
+ if (index < 0 || index >= list.length) {
115
+ if (!loop) {
116
+ return;
117
+ }
118
+ index = (index + list.length) % list.length;
119
+ }
120
+ const target = list[index];
121
+ if (target !== undefined) {
122
+ apply(target);
123
+ target.focus();
124
+ }
125
+ };
126
+ const onKeydown = (event) => {
127
+ const key = event;
128
+ const horizontal = orientation !== "vertical";
129
+ const vertical = orientation !== "horizontal";
130
+ if ((key.key === "ArrowRight" && horizontal) || (key.key === "ArrowDown" && vertical)) {
131
+ move(1);
132
+ }
133
+ else if ((key.key === "ArrowLeft" && horizontal) || (key.key === "ArrowUp" && vertical)) {
134
+ move(-1);
135
+ }
136
+ else if (key.key === "Home") {
137
+ move(0, "first");
138
+ }
139
+ else if (key.key === "End") {
140
+ move(0, "last");
141
+ }
142
+ else {
143
+ return;
144
+ }
145
+ key.preventDefault();
146
+ };
147
+ const onFocusIn = (event) => {
148
+ const target = event.target.closest(selector);
149
+ if (target !== null && element.contains(target)) {
150
+ apply(target);
151
+ }
152
+ };
153
+ apply(undefined);
154
+ const observer = new MutationObserver(() => apply(current));
155
+ observer.observe(element, { childList: true, subtree: true });
156
+ element.addEventListener("keydown", onKeydown);
157
+ element.addEventListener("focusin", onFocusIn);
158
+ onDispose(() => {
159
+ observer.disconnect();
160
+ element.removeEventListener("keydown", onKeydown);
161
+ element.removeEventListener("focusin", onFocusIn);
162
+ });
163
+ };
164
+ }
165
+ /**
166
+ * Watches how focus arrives, the way Angular CDK's focus monitor does: a key
167
+ * pressed before focus moves means keyboard, a pointer pressed means pointer
168
+ * or touch, anything else means program. The origin is a signal and a
169
+ * `data-focus-origin` attribute on the root element, so a stylesheet can
170
+ * show focus rings for keyboard users only: `[data-focus-origin="keyboard"] :focus { outline: ... }`.
171
+ */
172
+ export function focusOrigin(doc = document) {
173
+ const origin = signal(null);
174
+ let last;
175
+ let timer;
176
+ const remember = (value) => {
177
+ last = value;
178
+ clearTimeout(timer);
179
+ timer = setTimeout(() => {
180
+ last = undefined;
181
+ }, 650);
182
+ };
183
+ const onKeydown = () => remember("keyboard");
184
+ const onPointerdown = (event) => remember(event.pointerType === "touch" ? "touch" : "pointer");
185
+ const onFocusIn = () => {
186
+ const value = last ?? "program";
187
+ origin.set(value);
188
+ doc.documentElement.setAttribute("data-focus-origin", value);
189
+ };
190
+ const onFocusOut = (event) => {
191
+ if (event.relatedTarget === null) {
192
+ origin.set(null);
193
+ doc.documentElement.removeAttribute("data-focus-origin");
194
+ }
195
+ };
196
+ doc.addEventListener("keydown", onKeydown, true);
197
+ doc.addEventListener("pointerdown", onPointerdown, true);
198
+ doc.addEventListener("focusin", onFocusIn, true);
199
+ doc.addEventListener("focusout", onFocusOut, true);
200
+ return {
201
+ origin,
202
+ dispose() {
203
+ clearTimeout(timer);
204
+ doc.removeEventListener("keydown", onKeydown, true);
205
+ doc.removeEventListener("pointerdown", onPointerdown, true);
206
+ doc.removeEventListener("focusin", onFocusIn, true);
207
+ doc.removeEventListener("focusout", onFocusOut, true);
208
+ doc.documentElement.removeAttribute("data-focus-origin");
209
+ }
210
+ };
211
+ }
212
+ //# sourceMappingURL=focus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focus.js","sourceRoot":"","sources":["../src/focus.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAuB,SAAS,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElE,MAAM,SAAS,GAAG,qQAAqQ,CAAC;AAExR,mGAAmG;AAC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,mBAAmB,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;YACpD,GAAG,CAAC,mBAAmB,CAAC,aAAa,EAAE,aAAa,EAAE,IAAI,CAAC,CAAC;YAC5D,GAAG,CAAC,mBAAmB,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;YACpD,GAAG,CAAC,mBAAmB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,CAAC,CAAC;YACtD,GAAG,CAAC,eAAe,CAAC,eAAe,CAAC,mBAAmB,CAAC,CAAC;QAC7D,CAAC;KACJ,CAAC;AACN,CAAC"}
@@ -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,4 @@
1
+ export { focusOrigin, focusTrap, focusables, rovingTabindex } from "./focus.js";
2
+ export { createAnnouncer, visuallyHidden } from "./announce.js";
3
+ export { forcedColors, mediaQuery, reducedMotion } from "./media.js";
4
+ //# sourceMappingURL=index.js.map
@@ -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"}
@@ -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"}
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
- "name": "@zerolith/a11y",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@zerolith/a11y",
3
+ "version": "0.1.0-alpha.2",
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://github.com/molexxxx/zerolith#readme",
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
+ "default": "./dist/index.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "src",
38
+ "LICENSE",
39
+ "README.md"
40
+ ],
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.build.json"
43
+ },
44
+ "peerDependencies": {
45
+ "zerolith": "^0.1.0-alpha.2"
46
+ },
47
+ "devDependencies": {
48
+ "zerolith": "^0.1.0-alpha.2"
49
+ }
50
+ }
@@ -0,0 +1,70 @@
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 and hidden visually. Each announcement clears the
27
+ * region and writes the message on the next task, so repeating a message
28
+ * is read again.
29
+ */
30
+ export function createAnnouncer(doc: Document = document): Announcer
31
+ {
32
+ const regions = new Map<Politeness, HTMLElement>();
33
+ const region = (politeness: Politeness): HTMLElement =>
34
+ {
35
+ let element = regions.get(politeness);
36
+ if (element === undefined)
37
+ {
38
+ element = doc.createElement("div");
39
+ element.setAttribute("aria-live", politeness);
40
+ element.setAttribute("aria-atomic", "true");
41
+ element.setAttribute("role", politeness === "assertive" ? "alert" : "status");
42
+ element.className = `zl-s ${visuallyHidden.scope}`;
43
+ doc.body.append(element);
44
+ regions.set(politeness, element);
45
+ }
46
+ return element;
47
+ };
48
+ let timer: ReturnType<typeof setTimeout> | undefined;
49
+ return {
50
+ announce(message: string, politeness: Politeness = "polite"): void
51
+ {
52
+ const element = region(politeness);
53
+ element.textContent = "";
54
+ clearTimeout(timer);
55
+ timer = setTimeout(() =>
56
+ {
57
+ element.textContent = message;
58
+ }, 0);
59
+ },
60
+ dispose(): void
61
+ {
62
+ clearTimeout(timer);
63
+ for (const element of regions.values())
64
+ {
65
+ element.remove();
66
+ }
67
+ regions.clear();
68
+ }
69
+ };
70
+ }
package/src/focus.ts ADDED
@@ -0,0 +1,294 @@
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\"]), [contenteditable=\"true\"], audio[controls], video[controls], details > summary, iframe";
10
+
11
+ /** The elements inside `root` that take Tab focus, in document order, skipping anything hidden. */
12
+ export function focusables(root: Element): HTMLElement[]
13
+ {
14
+ return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((element) => element.getClientRects().length > 0 && element.closest("[inert]") === null);
15
+ }
16
+
17
+ /** Options for `focusTrap`. */
18
+ export interface FocusTrapOptions
19
+ {
20
+ /** 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. */
21
+ initial?: string | HTMLElement | false;
22
+ /** Returns focus to the element that had it before the trap attached. Defaults to true. */
23
+ restore?: boolean;
24
+ }
25
+
26
+ /**
27
+ * A `ref` that keeps Tab and Shift+Tab inside the element, pulls focus back
28
+ * when it lands outside, moves focus in once the element is in the document,
29
+ * and returns it where it came from when the element's template is removed.
30
+ */
31
+ export function focusTrap(options: FocusTrapOptions = {}): (element: Element) => void
32
+ {
33
+ return (element) =>
34
+ {
35
+ const doc = element.ownerDocument;
36
+ const previous = doc.activeElement instanceof HTMLElement ? doc.activeElement : null;
37
+ const fallback = (): HTMLElement =>
38
+ {
39
+ const first = focusables(element)[0];
40
+ if (first !== undefined)
41
+ {
42
+ return first;
43
+ }
44
+ if (!element.hasAttribute("tabindex"))
45
+ {
46
+ element.setAttribute("tabindex", "-1");
47
+ }
48
+ return element as HTMLElement;
49
+ };
50
+ let disposed = false;
51
+ const initial = options.initial;
52
+ const focusInitial = (): void =>
53
+ {
54
+ if (disposed || !element.isConnected || initial === false)
55
+ {
56
+ return;
57
+ }
58
+ const target = typeof initial === "string" ? element.querySelector<HTMLElement>(initial) ?? fallback() : initial ?? fallback();
59
+ target.focus();
60
+ };
61
+ if (initial !== false)
62
+ {
63
+ if (element.isConnected)
64
+ {
65
+ focusInitial();
66
+ }
67
+ else
68
+ {
69
+ queueMicrotask(focusInitial);
70
+ }
71
+ }
72
+ const onKeydown = (event: Event): void =>
73
+ {
74
+ const key = event as KeyboardEvent;
75
+ if (key.key !== "Tab")
76
+ {
77
+ return;
78
+ }
79
+ const list = focusables(element);
80
+ const first = list[0];
81
+ const last = list.at(-1);
82
+ if (first === undefined || last === undefined)
83
+ {
84
+ key.preventDefault();
85
+ return;
86
+ }
87
+ const active = doc.activeElement;
88
+ if (key.shiftKey && (active === first || !element.contains(active)))
89
+ {
90
+ key.preventDefault();
91
+ last.focus();
92
+ }
93
+ else if (!key.shiftKey && (active === last || !element.contains(active)))
94
+ {
95
+ key.preventDefault();
96
+ first.focus();
97
+ }
98
+ };
99
+ const onFocusIn = (event: Event): void =>
100
+ {
101
+ if (!element.contains(event.target as Node))
102
+ {
103
+ fallback().focus();
104
+ }
105
+ };
106
+ element.addEventListener("keydown", onKeydown);
107
+ doc.addEventListener("focusin", onFocusIn);
108
+ onDispose(() =>
109
+ {
110
+ disposed = true;
111
+ element.removeEventListener("keydown", onKeydown);
112
+ doc.removeEventListener("focusin", onFocusIn);
113
+ if (options.restore !== false && previous !== null && previous.isConnected)
114
+ {
115
+ previous.focus();
116
+ }
117
+ });
118
+ };
119
+ }
120
+
121
+ /** Options for `rovingTabindex`. */
122
+ export interface RovingOptions
123
+ {
124
+ /** The selector of the items. Defaults to the ARIA roles of composite widgets plus `[data-roving]`. */
125
+ items?: string;
126
+ /** Which arrow keys move: `horizontal` (left and right), `vertical` (up and down), or `both`. Defaults to both. */
127
+ orientation?: "horizontal" | "vertical" | "both";
128
+ /** Wraps from the last item to the first and back. Defaults to true. */
129
+ loop?: boolean;
130
+ }
131
+
132
+ const ROVING_ITEMS = "[data-roving], [role=\"tab\"], [role=\"menuitem\"], [role=\"menuitemcheckbox\"], [role=\"menuitemradio\"], [role=\"option\"], [role=\"radio\"], [role=\"treeitem\"], [role=\"gridcell\"]";
133
+
134
+ /**
135
+ * A `ref` for a composite widget: exactly one item is in the Tab order, the
136
+ * arrow keys, Home, and End move between items, and the item that was
137
+ * selected or checked starts as the current one.
138
+ */
139
+ export function rovingTabindex(options: RovingOptions = {}): (element: Element) => void
140
+ {
141
+ const selector = options.items ?? ROVING_ITEMS;
142
+ const orientation = options.orientation ?? "both";
143
+ const loop = options.loop !== false;
144
+ return (element) =>
145
+ {
146
+ const items = (): HTMLElement[] => [...element.querySelectorAll<HTMLElement>(selector)].filter((item) => !item.hasAttribute("disabled") && item.getAttribute("aria-disabled") !== "true");
147
+ let current: HTMLElement | undefined;
148
+ const apply = (next: HTMLElement | undefined): void =>
149
+ {
150
+ const list = items();
151
+ current = next !== undefined && list.includes(next) ? next : list.find((item) => item.getAttribute("aria-selected") === "true" || item.getAttribute("aria-checked") === "true") ?? list[0];
152
+ for (const item of list)
153
+ {
154
+ item.tabIndex = item === current ? 0 : -1;
155
+ }
156
+ };
157
+ const move = (step: number, edge?: "first" | "last"): void =>
158
+ {
159
+ const list = items();
160
+ if (list.length === 0)
161
+ {
162
+ return;
163
+ }
164
+ let index = edge === "first" ? 0 : edge === "last" ? list.length - 1 : list.indexOf(current ?? list[0] as HTMLElement) + step;
165
+ if (index < 0 || index >= list.length)
166
+ {
167
+ if (!loop)
168
+ {
169
+ return;
170
+ }
171
+ index = (index + list.length) % list.length;
172
+ }
173
+ const target = list[index];
174
+ if (target !== undefined)
175
+ {
176
+ apply(target);
177
+ target.focus();
178
+ }
179
+ };
180
+ const onKeydown = (event: Event): void =>
181
+ {
182
+ const key = event as KeyboardEvent;
183
+ const horizontal = orientation !== "vertical";
184
+ const vertical = orientation !== "horizontal";
185
+ if ((key.key === "ArrowRight" && horizontal) || (key.key === "ArrowDown" && vertical))
186
+ {
187
+ move(1);
188
+ }
189
+ else if ((key.key === "ArrowLeft" && horizontal) || (key.key === "ArrowUp" && vertical))
190
+ {
191
+ move(-1);
192
+ }
193
+ else if (key.key === "Home")
194
+ {
195
+ move(0, "first");
196
+ }
197
+ else if (key.key === "End")
198
+ {
199
+ move(0, "last");
200
+ }
201
+ else
202
+ {
203
+ return;
204
+ }
205
+ key.preventDefault();
206
+ };
207
+ const onFocusIn = (event: Event): void =>
208
+ {
209
+ const target = (event.target as Element).closest<HTMLElement>(selector);
210
+ if (target !== null && element.contains(target))
211
+ {
212
+ apply(target);
213
+ }
214
+ };
215
+ apply(undefined);
216
+ const observer = new MutationObserver(() => apply(current));
217
+ observer.observe(element, { childList: true, subtree: true });
218
+ element.addEventListener("keydown", onKeydown);
219
+ element.addEventListener("focusin", onFocusIn);
220
+ onDispose(() =>
221
+ {
222
+ observer.disconnect();
223
+ element.removeEventListener("keydown", onKeydown);
224
+ element.removeEventListener("focusin", onFocusIn);
225
+ });
226
+ };
227
+ }
228
+
229
+ /** How the element that has focus got it. */
230
+ export type FocusOrigin = "keyboard" | "pointer" | "touch" | "program";
231
+
232
+ /** What `focusOrigin` returns. */
233
+ export interface FocusOriginMonitor
234
+ {
235
+ /** The origin of the current focus, or null while nothing in the document has focus. */
236
+ readonly origin: ReadableSignal<FocusOrigin | null>;
237
+ /** Removes the listeners and the attribute. */
238
+ dispose(): void;
239
+ }
240
+
241
+ /**
242
+ * Watches how focus arrives, the way Angular CDK's focus monitor does: a key
243
+ * pressed before focus moves means keyboard, a pointer pressed means pointer
244
+ * or touch, anything else means program. The origin is a signal and a
245
+ * `data-focus-origin` attribute on the root element, so a stylesheet can
246
+ * show focus rings for keyboard users only: `[data-focus-origin="keyboard"] :focus { outline: ... }`.
247
+ */
248
+ export function focusOrigin(doc: Document = document): FocusOriginMonitor
249
+ {
250
+ const origin = signal<FocusOrigin | null>(null);
251
+ let last: FocusOrigin | undefined;
252
+ let timer: ReturnType<typeof setTimeout> | undefined;
253
+ const remember = (value: FocusOrigin): void =>
254
+ {
255
+ last = value;
256
+ clearTimeout(timer);
257
+ timer = setTimeout(() =>
258
+ {
259
+ last = undefined;
260
+ }, 650);
261
+ };
262
+ const onKeydown = (): void => remember("keyboard");
263
+ const onPointerdown = (event: Event): void => remember((event as PointerEvent).pointerType === "touch" ? "touch" : "pointer");
264
+ const onFocusIn = (): void =>
265
+ {
266
+ const value = last ?? "program";
267
+ origin.set(value);
268
+ doc.documentElement.setAttribute("data-focus-origin", value);
269
+ };
270
+ const onFocusOut = (event: Event): void =>
271
+ {
272
+ if ((event as FocusEvent).relatedTarget === null)
273
+ {
274
+ origin.set(null);
275
+ doc.documentElement.removeAttribute("data-focus-origin");
276
+ }
277
+ };
278
+ doc.addEventListener("keydown", onKeydown, true);
279
+ doc.addEventListener("pointerdown", onPointerdown, true);
280
+ doc.addEventListener("focusin", onFocusIn, true);
281
+ doc.addEventListener("focusout", onFocusOut, true);
282
+ return {
283
+ origin,
284
+ dispose(): void
285
+ {
286
+ clearTimeout(timer);
287
+ doc.removeEventListener("keydown", onKeydown, true);
288
+ doc.removeEventListener("pointerdown", onPointerdown, true);
289
+ doc.removeEventListener("focusin", onFocusIn, true);
290
+ doc.removeEventListener("focusout", onFocusOut, true);
291
+ doc.documentElement.removeAttribute("data-focus-origin");
292
+ }
293
+ };
294
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
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
+
8
+ export type { Announcer, Politeness } from "./announce.js";
9
+ export { createAnnouncer, visuallyHidden } from "./announce.js";
10
+
11
+ export { forcedColors, mediaQuery, reducedMotion } from "./media.js";
package/src/media.ts ADDED
@@ -0,0 +1,41 @@
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, signal } from "zerolith";
6
+
7
+ const queries = new Map<string, ReadableSignal<boolean>>();
8
+
9
+ /** A media query as a signal that follows the query's matches; false wherever `matchMedia` does not exist, such as on the server. */
10
+ export function mediaQuery(query: string): ReadableSignal<boolean>
11
+ {
12
+ let existing = queries.get(query);
13
+ if (existing === undefined)
14
+ {
15
+ if (typeof matchMedia === "undefined")
16
+ {
17
+ existing = signal(false);
18
+ }
19
+ else
20
+ {
21
+ const list = matchMedia(query);
22
+ const matches = signal(list.matches);
23
+ list.addEventListener("change", (event) => matches.set(event.matches));
24
+ existing = matches;
25
+ }
26
+ queries.set(query, existing);
27
+ }
28
+ return existing;
29
+ }
30
+
31
+ /** True while the user agent is in forced colors mode, such as Windows high contrast, where author colors are replaced by system ones. */
32
+ export function forcedColors(): ReadableSignal<boolean>
33
+ {
34
+ return mediaQuery("(forced-colors: active)");
35
+ }
36
+
37
+ /** True while the user has asked for reduced motion. */
38
+ export function reducedMotion(): ReadableSignal<boolean>
39
+ {
40
+ return mediaQuery("(prefers-reduced-motion: reduce)");
41
+ }