accented 0.0.1-dev.4 → 1.0.0

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.
Files changed (217) hide show
  1. package/NOTICE +14 -0
  2. package/README.md +71 -0
  3. package/dist/accented.d.ts +28 -7
  4. package/dist/accented.d.ts.map +1 -1
  5. package/dist/accented.js +107 -42
  6. package/dist/accented.js.map +1 -1
  7. package/dist/common/tokens.d.ts +7 -0
  8. package/dist/common/tokens.d.ts.map +1 -0
  9. package/dist/common/tokens.js +8 -0
  10. package/dist/common/tokens.js.map +1 -0
  11. package/dist/constants.d.ts +4 -0
  12. package/dist/constants.d.ts.map +1 -0
  13. package/dist/constants.js +4 -0
  14. package/dist/constants.js.map +1 -0
  15. package/dist/dom-updater.d.ts +1 -6
  16. package/dist/dom-updater.d.ts.map +1 -1
  17. package/dist/dom-updater.js +136 -20
  18. package/dist/dom-updater.js.map +1 -1
  19. package/dist/elements/accented-dialog.d.ts +359 -0
  20. package/dist/elements/accented-dialog.d.ts.map +1 -0
  21. package/dist/elements/accented-dialog.js +377 -0
  22. package/dist/elements/accented-dialog.js.map +1 -0
  23. package/dist/elements/accented-trigger.d.ts +364 -0
  24. package/dist/elements/accented-trigger.d.ts.map +1 -0
  25. package/dist/elements/accented-trigger.js +214 -0
  26. package/dist/elements/accented-trigger.js.map +1 -0
  27. package/dist/fullscreen-listener.d.ts +2 -0
  28. package/dist/fullscreen-listener.d.ts.map +1 -0
  29. package/dist/fullscreen-listener.js +17 -0
  30. package/dist/fullscreen-listener.js.map +1 -0
  31. package/dist/intersection-observer.d.ts +5 -0
  32. package/dist/intersection-observer.d.ts.map +1 -0
  33. package/dist/intersection-observer.js +34 -0
  34. package/dist/intersection-observer.js.map +1 -0
  35. package/dist/log-and-rethrow.d.ts +2 -0
  36. package/dist/log-and-rethrow.d.ts.map +1 -0
  37. package/dist/log-and-rethrow.js +6 -0
  38. package/dist/log-and-rethrow.js.map +1 -0
  39. package/dist/logger.d.ts +2 -0
  40. package/dist/logger.d.ts.map +1 -0
  41. package/dist/logger.js +28 -0
  42. package/dist/logger.js.map +1 -0
  43. package/dist/register-elements.d.ts +2 -0
  44. package/dist/register-elements.d.ts.map +1 -0
  45. package/dist/register-elements.js +20 -0
  46. package/dist/register-elements.js.map +1 -0
  47. package/dist/resize-listener.d.ts +2 -0
  48. package/dist/resize-listener.d.ts.map +1 -0
  49. package/dist/resize-listener.js +17 -0
  50. package/dist/resize-listener.js.map +1 -0
  51. package/dist/scanner.d.ts +3 -0
  52. package/dist/scanner.d.ts.map +1 -0
  53. package/dist/scanner.js +153 -0
  54. package/dist/scanner.js.map +1 -0
  55. package/dist/scroll-listeners.d.ts +2 -0
  56. package/dist/scroll-listeners.d.ts.map +1 -0
  57. package/dist/scroll-listeners.js +37 -0
  58. package/dist/scroll-listeners.js.map +1 -0
  59. package/dist/state.d.ts +7 -0
  60. package/dist/state.d.ts.map +1 -0
  61. package/dist/state.js +16 -0
  62. package/dist/state.js.map +1 -0
  63. package/dist/task-queue.d.ts +5 -6
  64. package/dist/task-queue.d.ts.map +1 -1
  65. package/dist/task-queue.js +30 -25
  66. package/dist/task-queue.js.map +1 -1
  67. package/dist/types.d.ts +227 -0
  68. package/dist/types.d.ts.map +1 -0
  69. package/dist/types.js +2 -0
  70. package/dist/types.js.map +1 -0
  71. package/dist/utils/are-elements-with-issues-equal.d.ts +3 -0
  72. package/dist/utils/are-elements-with-issues-equal.d.ts.map +1 -0
  73. package/dist/utils/are-elements-with-issues-equal.js +5 -0
  74. package/dist/utils/are-elements-with-issues-equal.js.map +1 -0
  75. package/dist/utils/are-issue-sets-equal.d.ts +3 -0
  76. package/dist/utils/are-issue-sets-equal.d.ts.map +1 -0
  77. package/dist/utils/are-issue-sets-equal.js +6 -0
  78. package/dist/utils/are-issue-sets-equal.js.map +1 -0
  79. package/dist/utils/containing-blocks.d.ts +3 -0
  80. package/dist/utils/containing-blocks.d.ts.map +1 -0
  81. package/dist/utils/containing-blocks.js +46 -0
  82. package/dist/utils/containing-blocks.js.map +1 -0
  83. package/dist/utils/contains.d.ts +2 -0
  84. package/dist/utils/contains.d.ts.map +1 -0
  85. package/dist/utils/contains.js +19 -0
  86. package/dist/utils/contains.js.map +1 -0
  87. package/dist/utils/deduplicate-nodes.d.ts +2 -0
  88. package/dist/utils/deduplicate-nodes.d.ts.map +1 -0
  89. package/dist/utils/deduplicate-nodes.js +4 -0
  90. package/dist/utils/deduplicate-nodes.js.map +1 -0
  91. package/dist/utils/deep-merge.d.ts +4 -0
  92. package/dist/utils/deep-merge.d.ts.map +1 -0
  93. package/dist/utils/deep-merge.js +21 -0
  94. package/dist/utils/deep-merge.js.map +1 -0
  95. package/dist/utils/dom-helpers.d.ts +9 -0
  96. package/dist/utils/dom-helpers.d.ts.map +1 -0
  97. package/dist/utils/dom-helpers.js +34 -0
  98. package/dist/utils/dom-helpers.js.map +1 -0
  99. package/dist/utils/ensure-non-empty.d.ts +2 -0
  100. package/dist/utils/ensure-non-empty.d.ts.map +1 -0
  101. package/dist/utils/ensure-non-empty.js +7 -0
  102. package/dist/utils/ensure-non-empty.js.map +1 -0
  103. package/dist/utils/get-element-html.d.ts +2 -0
  104. package/dist/utils/get-element-html.d.ts.map +1 -0
  105. package/dist/utils/get-element-html.js +16 -0
  106. package/dist/utils/get-element-html.js.map +1 -0
  107. package/dist/utils/get-element-position.d.ts +11 -0
  108. package/dist/utils/get-element-position.d.ts.map +1 -0
  109. package/dist/utils/get-element-position.js +70 -0
  110. package/dist/utils/get-element-position.js.map +1 -0
  111. package/dist/utils/get-parent.d.ts +2 -0
  112. package/dist/utils/get-parent.d.ts.map +1 -0
  113. package/dist/utils/get-parent.js +12 -0
  114. package/dist/utils/get-parent.js.map +1 -0
  115. package/dist/utils/get-scan-context.d.ts +3 -0
  116. package/dist/utils/get-scan-context.d.ts.map +1 -0
  117. package/dist/utils/get-scan-context.js +28 -0
  118. package/dist/utils/get-scan-context.js.map +1 -0
  119. package/dist/utils/get-scrollable-ancestors.d.ts +2 -0
  120. package/dist/utils/get-scrollable-ancestors.d.ts.map +1 -0
  121. package/dist/utils/get-scrollable-ancestors.js +19 -0
  122. package/dist/utils/get-scrollable-ancestors.js.map +1 -0
  123. package/dist/utils/is-node-in-scan-context.d.ts +3 -0
  124. package/dist/utils/is-node-in-scan-context.d.ts.map +1 -0
  125. package/dist/utils/is-node-in-scan-context.js +26 -0
  126. package/dist/utils/is-node-in-scan-context.js.map +1 -0
  127. package/dist/utils/is-non-empty.d.ts +2 -0
  128. package/dist/utils/is-non-empty.d.ts.map +1 -0
  129. package/dist/utils/is-non-empty.js +4 -0
  130. package/dist/utils/is-non-empty.js.map +1 -0
  131. package/dist/utils/normalize-context.d.ts +3 -0
  132. package/dist/utils/normalize-context.d.ts.map +1 -0
  133. package/dist/utils/normalize-context.js +59 -0
  134. package/dist/utils/normalize-context.js.map +1 -0
  135. package/dist/utils/recalculate-positions.d.ts +2 -0
  136. package/dist/utils/recalculate-positions.d.ts.map +1 -0
  137. package/dist/utils/recalculate-positions.js +27 -0
  138. package/dist/utils/recalculate-positions.js.map +1 -0
  139. package/dist/utils/recalculate-scrollable-ancestors.d.ts +2 -0
  140. package/dist/utils/recalculate-scrollable-ancestors.d.ts.map +1 -0
  141. package/dist/utils/recalculate-scrollable-ancestors.js +13 -0
  142. package/dist/utils/recalculate-scrollable-ancestors.js.map +1 -0
  143. package/dist/utils/shadow-dom-aware-mutation-observer.d.ts +10 -0
  144. package/dist/utils/shadow-dom-aware-mutation-observer.d.ts.map +1 -0
  145. package/dist/utils/shadow-dom-aware-mutation-observer.js +61 -0
  146. package/dist/utils/shadow-dom-aware-mutation-observer.js.map +1 -0
  147. package/dist/utils/supports-anchor-positioning.d.ts +6 -0
  148. package/dist/utils/supports-anchor-positioning.d.ts.map +1 -0
  149. package/dist/utils/supports-anchor-positioning.js +4 -0
  150. package/dist/utils/supports-anchor-positioning.js.map +1 -0
  151. package/dist/utils/transform-violations.d.ts +4 -0
  152. package/dist/utils/transform-violations.d.ts.map +1 -0
  153. package/dist/utils/transform-violations.js +61 -0
  154. package/dist/utils/transform-violations.js.map +1 -0
  155. package/dist/utils/update-elements-with-issues.d.ts +13 -0
  156. package/dist/utils/update-elements-with-issues.d.ts.map +1 -0
  157. package/dist/utils/update-elements-with-issues.js +96 -0
  158. package/dist/utils/update-elements-with-issues.js.map +1 -0
  159. package/dist/validate-options.d.ts +3 -0
  160. package/dist/validate-options.d.ts.map +1 -0
  161. package/dist/validate-options.js +129 -0
  162. package/dist/validate-options.js.map +1 -0
  163. package/package.json +21 -8
  164. package/src/accented.test.ts +24 -0
  165. package/src/accented.ts +130 -0
  166. package/src/common/tokens.ts +10 -0
  167. package/src/constants.ts +3 -0
  168. package/src/dom-updater.ts +165 -0
  169. package/src/elements/accented-dialog.ts +419 -0
  170. package/src/elements/accented-trigger.ts +251 -0
  171. package/src/fullscreen-listener.ts +21 -0
  172. package/src/intersection-observer.ts +39 -0
  173. package/src/log-and-rethrow.ts +8 -0
  174. package/src/logger.ts +36 -0
  175. package/src/register-elements.ts +21 -0
  176. package/src/resize-listener.ts +21 -0
  177. package/src/scanner.ts +195 -0
  178. package/src/scroll-listeners.ts +45 -0
  179. package/src/state.ts +35 -0
  180. package/src/task-queue.test.ts +136 -0
  181. package/src/task-queue.ts +61 -0
  182. package/src/types.ts +258 -0
  183. package/src/utils/are-elements-with-issues-equal.ts +11 -0
  184. package/src/utils/are-issue-sets-equal.test.ts +53 -0
  185. package/src/utils/are-issue-sets-equal.ts +12 -0
  186. package/src/utils/containing-blocks.ts +60 -0
  187. package/src/utils/contains.test.ts +54 -0
  188. package/src/utils/contains.ts +19 -0
  189. package/src/utils/deduplicate-nodes.ts +3 -0
  190. package/src/utils/deep-merge.test.ts +41 -0
  191. package/src/utils/deep-merge.ts +24 -0
  192. package/src/utils/dom-helpers.ts +42 -0
  193. package/src/utils/ensure-non-empty.ts +6 -0
  194. package/src/utils/get-element-html.ts +15 -0
  195. package/src/utils/get-element-position.ts +89 -0
  196. package/src/utils/get-parent.ts +14 -0
  197. package/src/utils/get-scan-context.test.ts +85 -0
  198. package/src/utils/get-scan-context.ts +36 -0
  199. package/src/utils/get-scrollable-ancestors.ts +22 -0
  200. package/src/utils/is-node-in-scan-context.test.ts +70 -0
  201. package/src/utils/is-node-in-scan-context.ts +29 -0
  202. package/src/utils/is-non-empty.ts +3 -0
  203. package/src/utils/normalize-context.test.ts +105 -0
  204. package/src/utils/normalize-context.ts +65 -0
  205. package/src/utils/recalculate-positions.ts +27 -0
  206. package/src/utils/recalculate-scrollable-ancestors.ts +13 -0
  207. package/src/utils/shadow-dom-aware-mutation-observer.ts +75 -0
  208. package/src/utils/supports-anchor-positioning.ts +7 -0
  209. package/src/utils/transform-violations.test.ts +128 -0
  210. package/src/utils/transform-violations.ts +74 -0
  211. package/src/utils/update-elements-with-issues.test.ts +371 -0
  212. package/src/utils/update-elements-with-issues.ts +144 -0
  213. package/src/validate-options.ts +184 -0
  214. package/dist/utils/issuesToElements.d.ts +0 -3
  215. package/dist/utils/issuesToElements.d.ts.map +0 -1
  216. package/dist/utils/issuesToElements.js +0 -16
  217. package/dist/utils/issuesToElements.js.map +0 -1
@@ -0,0 +1,39 @@
1
+ import { logAndRethrow } from './log-and-rethrow.js';
2
+ import { extendedElementsWithIssues } from './state.js';
3
+ import { getElementPosition } from './utils/get-element-position.js';
4
+ import { supportsAnchorPositioning } from './utils/supports-anchor-positioning.js';
5
+
6
+ export function setupIntersectionObserver() {
7
+ const intersectionObserver = new IntersectionObserver(
8
+ (entries) => {
9
+ try {
10
+ for (const entry of entries) {
11
+ const extendedElementWithIssues = extendedElementsWithIssues.value.find(
12
+ (el) => el.element === entry.target,
13
+ );
14
+ if (extendedElementWithIssues) {
15
+ // We initially treated setting visibility in the intersection observer
16
+ // as a fallback option for browsers that don't support `position-visibility`,
17
+ // but then we realized that this `position-visibility` actually works
18
+ // in an unexpected way when the container has `overflow: visible`.
19
+ // So now we always set visibility in the intersection observer.
20
+ extendedElementWithIssues.visible.value = entry.isIntersecting;
21
+ if (entry.isIntersecting && !supportsAnchorPositioning(window)) {
22
+ extendedElementWithIssues.position.value = getElementPosition(entry.target, window);
23
+ }
24
+ }
25
+ }
26
+ } catch (error) {
27
+ logAndRethrow(error);
28
+ }
29
+ },
30
+ { threshold: 0 },
31
+ );
32
+
33
+ return {
34
+ intersectionObserver,
35
+ disconnect: () => {
36
+ intersectionObserver.disconnect();
37
+ },
38
+ };
39
+ }
@@ -0,0 +1,8 @@
1
+ import { issuesUrl } from './constants.js';
2
+
3
+ export function logAndRethrow(error: unknown) {
4
+ console.error(
5
+ `Accented threw an error (see below). Try updating your browser to the latest version. If you’re still seeing the error, file an issue at ${issuesUrl}.`,
6
+ );
7
+ throw error;
8
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { effect } from '@preact/signals-core';
2
+ import { accentedUrl } from './constants.js';
3
+ import { elementsWithIssues, enabled } from './state.js';
4
+ import type { ElementWithIssues } from './types.ts';
5
+
6
+ function filterPropsForOutput(elements: Array<ElementWithIssues>) {
7
+ return elements.map(({ element, issues }) => ({ element, issues }));
8
+ }
9
+
10
+ export function createLogger() {
11
+ let firstRun = true;
12
+
13
+ return effect(() => {
14
+ if (!enabled.value) {
15
+ return;
16
+ }
17
+
18
+ const elementCount = elementsWithIssues.value.length;
19
+ if (elementCount > 0) {
20
+ const issueCount = elementsWithIssues.value.reduce(
21
+ (acc, { issues }) => acc + issues.length,
22
+ 0,
23
+ );
24
+ console.log(
25
+ `${issueCount} accessibility issue${issueCount === 1 ? '' : 's'} found in ${elementCount} element${issueCount === 1 ? '' : 's'} (Accented, ${accentedUrl}):\n`,
26
+ filterPropsForOutput(elementsWithIssues.value),
27
+ );
28
+ } else {
29
+ if (firstRun) {
30
+ firstRun = false;
31
+ } else {
32
+ console.log(`No accessibility issues found (Accented, ${accentedUrl}).`);
33
+ }
34
+ }
35
+ });
36
+ }
@@ -0,0 +1,21 @@
1
+ import { getAccentedDialog } from './elements/accented-dialog.js';
2
+ import { getAccentedTrigger } from './elements/accented-trigger.js';
3
+
4
+ export function registerElements(name: string): void {
5
+ const elements = [
6
+ {
7
+ elementName: `${name}-trigger`,
8
+ Component: getAccentedTrigger(name),
9
+ },
10
+ {
11
+ elementName: `${name}-dialog`,
12
+ Component: getAccentedDialog(),
13
+ },
14
+ ];
15
+
16
+ for (const { elementName, Component } of elements) {
17
+ if (!customElements.get(elementName)) {
18
+ customElements.define(elementName, Component);
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,21 @@
1
+ import { logAndRethrow } from './log-and-rethrow.js';
2
+ import { recalculatePositions } from './utils/recalculate-positions.js';
3
+
4
+ export function setupResizeListener() {
5
+ const abortController = new AbortController();
6
+ window.addEventListener(
7
+ 'resize',
8
+ () => {
9
+ try {
10
+ recalculatePositions();
11
+ } catch (error) {
12
+ logAndRethrow(error);
13
+ }
14
+ },
15
+ { signal: abortController.signal },
16
+ );
17
+
18
+ return () => {
19
+ abortController.abort();
20
+ };
21
+ }
package/src/scanner.ts ADDED
@@ -0,0 +1,195 @@
1
+ import axe from 'axe-core';
2
+ import { getAccentedElementNames, issuesUrl } from './constants.js';
3
+ import { logAndRethrow } from './log-and-rethrow.js';
4
+ import { elementsWithIssues, enabled, extendedElementsWithIssues } from './state.js';
5
+ import { TaskQueue } from './task-queue.js';
6
+ import type { AxeOptions, Callback, Context, Throttle } from './types.ts';
7
+ import { getScanContext } from './utils/get-scan-context.js';
8
+ import { recalculatePositions } from './utils/recalculate-positions.js';
9
+ import { recalculateScrollableAncestors } from './utils/recalculate-scrollable-ancestors.js';
10
+ import { createShadowDOMAwareMutationObserver } from './utils/shadow-dom-aware-mutation-observer.js';
11
+ import { supportsAnchorPositioning } from './utils/supports-anchor-positioning.js';
12
+ import { updateElementsWithIssues } from './utils/update-elements-with-issues.js';
13
+
14
+ export function createScanner(
15
+ name: string,
16
+ context: Context,
17
+ axeOptions: AxeOptions,
18
+ throttle: Required<Throttle>,
19
+ callback: Callback,
20
+ ) {
21
+ const axeRunningWindowProp = `__${name}_axe_running__`;
22
+ const win = window as unknown as Record<string, boolean>;
23
+ const taskQueue = new TaskQueue<Node>(async (nodes) => {
24
+ // We may see errors coming from axe-core when Accented is toggled off and on in qiuck succession,
25
+ // which I've seen happen with hot reloading of a React application.
26
+ // This window property serves as a circuit breaker for that particular case.
27
+ if (win[axeRunningWindowProp]) {
28
+ return;
29
+ }
30
+
31
+ try {
32
+ performance.mark('scan-start');
33
+
34
+ win[axeRunningWindowProp] = true;
35
+
36
+ const scanContext = getScanContext(nodes, context);
37
+
38
+ let result: axe.AxeResults | undefined;
39
+
40
+ try {
41
+ result = await axe.run(scanContext, {
42
+ /**
43
+ * By default, axe-core doesn't include element refs
44
+ * in the violations array,
45
+ * and we need those element refs.
46
+ */
47
+ elementRef: true,
48
+
49
+ /**
50
+ * Although axe-core can perform iframe scanning, I haven't succeeded in it,
51
+ * and the docs suggest that the axe-core script should be explicitly included
52
+ * in each of the iframed documents anyway.
53
+ * It seems preferable to disallow iframe scanning and not report issues in elements within iframes
54
+ * in the case that such issues are for some reason reported by axe-core.
55
+ * A consumer of Accented can instead scan the iframed document by calling Accented initialization from that document.
56
+ */
57
+ iframes: false,
58
+
59
+ /**
60
+ * The `preload` docs are not clear to me,
61
+ * but when it's set to `true` by default,
62
+ * axe-core tries to fetch cross-origin CSS,
63
+ * which fails in the absence of CORS headers.
64
+ * I'm not sure why axe-core needs to preload
65
+ * those resources in the first place,
66
+ * so disabling it seems to be the safe option.
67
+ */
68
+ preload: false,
69
+
70
+ /**
71
+ * We're only interested in violations,
72
+ * not in passes or incomplete results.
73
+ */
74
+ resultTypes: ['violations'],
75
+
76
+ ...axeOptions,
77
+ });
78
+ } catch (error) {
79
+ console.error(
80
+ `Accented: axe-core (the accessibility testing engine) threw an error. Check the \`axeOptions\` property (https://www.accented.dev/api#axeoptions) that you’re passing to Accented. If you still think it’s a bug in Accented, file an issue at ${issuesUrl}.\n`,
81
+ error,
82
+ );
83
+ }
84
+ win[axeRunningWindowProp] = false;
85
+
86
+ const scanMeasure = performance.measure('scan', 'scan-start');
87
+ const scanDuration = Math.round(scanMeasure.duration);
88
+
89
+ if (!enabled.value || !result) {
90
+ return;
91
+ }
92
+
93
+ performance.mark('dom-update-start');
94
+
95
+ updateElementsWithIssues({
96
+ extendedElementsWithIssues,
97
+ scanContext,
98
+ violations: result.violations,
99
+ win: window,
100
+ name,
101
+ });
102
+
103
+ const domUpdateMeasure = performance.measure('dom-update', 'dom-update-start');
104
+ const domUpdateDuration = Math.round(domUpdateMeasure.duration);
105
+
106
+ callback({
107
+ // Assuming that the {include, exclude} shape of the context object will be used less often
108
+ // than other variants, we'll output just the `include` array in case nothing is excluded
109
+ // in the scan.
110
+ scanContext: scanContext.exclude.length > 0 ? scanContext : scanContext.include,
111
+ elementsWithIssues: elementsWithIssues.value,
112
+ performance: {
113
+ totalBlockingTime: scanDuration + domUpdateDuration,
114
+ scan: scanDuration,
115
+ domUpdate: domUpdateDuration,
116
+ },
117
+ });
118
+ } catch (error) {
119
+ win[axeRunningWindowProp] = false;
120
+ logAndRethrow(error);
121
+ }
122
+ }, throttle);
123
+
124
+ taskQueue.add(document);
125
+
126
+ const accentedElementNames = getAccentedElementNames(name);
127
+ const mutationObserver = createShadowDOMAwareMutationObserver(name, (mutationList) => {
128
+ try {
129
+ // We're not interested in mutations that are caused exclusively by the custom elements
130
+ // introduced by Accented.
131
+ const listWithoutAccentedElements = mutationList.filter((mutationRecord) => {
132
+ const onlyAccentedElementsAddedOrRemoved =
133
+ mutationRecord.type === 'childList' &&
134
+ [...mutationRecord.addedNodes].every((node) =>
135
+ accentedElementNames.includes(node.nodeName.toLowerCase()),
136
+ ) &&
137
+ [...mutationRecord.removedNodes].every((node) =>
138
+ accentedElementNames.includes(node.nodeName.toLowerCase()),
139
+ );
140
+ const accentedElementChanged =
141
+ mutationRecord.type === 'attributes' &&
142
+ accentedElementNames.includes(mutationRecord.target.nodeName.toLowerCase());
143
+ return !(onlyAccentedElementsAddedOrRemoved || accentedElementChanged);
144
+ });
145
+
146
+ if (listWithoutAccentedElements.length !== 0 && !supportsAnchorPositioning(window)) {
147
+ // Something has changed in the DOM, so we need to realign all triggers with respective elements.
148
+ recalculatePositions();
149
+
150
+ // Elements' scrollable ancestors only change when styles change
151
+ // (specifically when the `display` prop on one of the ancestors changes),
152
+ // so a good place to recalculate the scrollable ancestors for elements is here.
153
+ // In future, we could further optimize this by only recalculating scrollable ancestors for elements that have changed.
154
+ recalculateScrollableAncestors();
155
+ }
156
+
157
+ // Exclude all mutations on elements that got the accented attribute added or removed.
158
+ // If we simply exclude all mutations where attributeName = `data-${name}`,
159
+ // we may miss other mutations on those same elements caused by Accented,
160
+ // leading to extra runs of the mutation observer.
161
+ const elementsWithAccentedAttributeChanges = listWithoutAccentedElements.reduce(
162
+ (nodes, mutationRecord) => {
163
+ if (
164
+ mutationRecord.type === 'attributes' &&
165
+ mutationRecord.attributeName === `data-${name}`
166
+ ) {
167
+ nodes.add(mutationRecord.target);
168
+ }
169
+ return nodes;
170
+ },
171
+ new Set<Node>(),
172
+ );
173
+
174
+ const filteredMutationList = listWithoutAccentedElements.filter((mutationRecord) => {
175
+ return !elementsWithAccentedAttributeChanges.has(mutationRecord.target);
176
+ });
177
+
178
+ const nodes = filteredMutationList.map((mutationRecord) => mutationRecord.target);
179
+ taskQueue.addMultiple(nodes);
180
+ } catch (error) {
181
+ logAndRethrow(error);
182
+ }
183
+ });
184
+
185
+ mutationObserver.observe(document, {
186
+ subtree: true,
187
+ childList: true,
188
+ attributes: true,
189
+ characterData: true,
190
+ });
191
+
192
+ return () => {
193
+ mutationObserver.disconnect();
194
+ };
195
+ }
@@ -0,0 +1,45 @@
1
+ import { effect } from '@preact/signals-core';
2
+ import { logAndRethrow } from './log-and-rethrow.js';
3
+ import { scrollableAncestors } from './state.js';
4
+ import { recalculatePositions } from './utils/recalculate-positions.js';
5
+
6
+ export function setupScrollListeners() {
7
+ const documentAbortController = new AbortController();
8
+ document.addEventListener(
9
+ 'scroll',
10
+ () => {
11
+ try {
12
+ recalculatePositions();
13
+ } catch (error) {
14
+ logAndRethrow(error);
15
+ }
16
+ },
17
+ { signal: documentAbortController.signal },
18
+ );
19
+
20
+ const disposeOfEffect = effect(() => {
21
+ // TODO: optimize performance, issue #81
22
+ const elementAbortController = new AbortController();
23
+ for (const scrollableAncestor of scrollableAncestors.value) {
24
+ scrollableAncestor.addEventListener(
25
+ 'scroll',
26
+ () => {
27
+ try {
28
+ recalculatePositions();
29
+ } catch (error) {
30
+ logAndRethrow(error);
31
+ }
32
+ },
33
+ { signal: elementAbortController.signal },
34
+ );
35
+ }
36
+ return () => {
37
+ elementAbortController.abort();
38
+ };
39
+ });
40
+
41
+ return () => {
42
+ documentAbortController.abort();
43
+ disposeOfEffect();
44
+ };
45
+ }
package/src/state.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { computed, signal } from '@preact/signals-core';
2
+
3
+ import type { ElementWithIssues, ExtendedElementWithIssues } from './types.ts';
4
+
5
+ export const enabled = signal(false);
6
+
7
+ export const extendedElementsWithIssues = signal<Array<ExtendedElementWithIssues>>([]);
8
+
9
+ export const elementsWithIssues = computed<Array<ElementWithIssues>>(() =>
10
+ extendedElementsWithIssues.value.map((extendedElementWithIssues) => ({
11
+ element: extendedElementWithIssues.element,
12
+ rootNode: extendedElementWithIssues.rootNode,
13
+ issues: extendedElementWithIssues.issues.value,
14
+ })),
15
+ );
16
+
17
+ export const rootNodes = computed<Set<Node>>(
18
+ () =>
19
+ new Set(
20
+ (enabled.value ? [document as Node] : []).concat(
21
+ ...extendedElementsWithIssues.value.map(
22
+ (extendedElementWithIssues) => extendedElementWithIssues.rootNode,
23
+ ),
24
+ ),
25
+ ),
26
+ );
27
+
28
+ export const scrollableAncestors = computed<Set<Element>>(() =>
29
+ extendedElementsWithIssues.value.reduce((scrollableAncestors, extendedElementWithIssues) => {
30
+ for (const scrollableAncestor of extendedElementWithIssues.scrollableAncestors.value) {
31
+ scrollableAncestors.add(scrollableAncestor);
32
+ }
33
+ return scrollableAncestors;
34
+ }, new Set<Element>()),
35
+ );
@@ -0,0 +1,136 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mock, suite, test } from 'node:test';
3
+
4
+ import { TaskQueue } from './task-queue';
5
+
6
+ const wait = (duration: number) => new Promise((resolve) => setTimeout(resolve, duration));
7
+
8
+ const createAsyncCallback = (duration: number) =>
9
+ mock.fn(() => new Promise((resolve) => setTimeout(resolve, duration)));
10
+
11
+ suite('TaskQueue', () => {
12
+ test('callback is not called after a TaskQueue is created, even after a timeout', async () => {
13
+ const asyncCallback = createAsyncCallback(0);
14
+ new TaskQueue(asyncCallback, { wait: 50, leading: true });
15
+ await wait(100);
16
+ assert.equal(asyncCallback.mock.callCount(), 0);
17
+ });
18
+
19
+ test('callback is not called if addMultiple is called with an empty array', async () => {
20
+ const asyncCallback = createAsyncCallback(0);
21
+ const taskQueue = new TaskQueue(asyncCallback, { wait: 50, leading: true });
22
+ taskQueue.addMultiple([]);
23
+ await wait(100);
24
+ assert.equal(asyncCallback.mock.callCount(), 0);
25
+ });
26
+
27
+ test('callback is called once if multiple items are added before the first delay has elapsed', async () => {
28
+ const asyncCallback = createAsyncCallback(0);
29
+ const taskQueue = new TaskQueue<string>(asyncCallback, { wait: 100, leading: false });
30
+ taskQueue.add('one');
31
+ // Adding the second item synchronously
32
+ taskQueue.add('two');
33
+ await wait(50);
34
+ // Adding the third item asynchronously
35
+ taskQueue.add('three');
36
+ assert.equal(asyncCallback.mock.callCount(), 0);
37
+ await wait(100);
38
+ assert.equal(asyncCallback.mock.callCount(), 1);
39
+ });
40
+
41
+ test('callback is called according to expected schedule', async () => {
42
+ const asyncCallback = createAsyncCallback(100);
43
+ const taskQueue = new TaskQueue<string>(asyncCallback, { wait: 100, leading: false });
44
+
45
+ // 0 ms: Add "one"
46
+ taskQueue.add('one');
47
+
48
+ await wait(50);
49
+
50
+ // 50 ms: First measurement, callback not called
51
+ assert.equal(asyncCallback.mock.callCount(), 0);
52
+
53
+ // 100 ms: Callback called for the first time
54
+ // 200 ms: First callback completes
55
+
56
+ await wait(200);
57
+
58
+ // 250 ms: Second measurement, callback called once
59
+ assert.equal(asyncCallback.mock.callCount(), 1);
60
+
61
+ // 250 ms: Add "two"
62
+ taskQueue.add('two');
63
+
64
+ // 350 ms: Callback called for the second time
65
+
66
+ await wait(150);
67
+
68
+ // 400 ms: Third measurement, callback called twice
69
+ assert.equal(asyncCallback.mock.callCount(), 2);
70
+ });
71
+
72
+ test('callback is called according to expected schedule when second task is added before the first callback completes', async () => {
73
+ const asyncCallback = createAsyncCallback(100);
74
+ const taskQueue = new TaskQueue<string>(asyncCallback, { wait: 100, leading: false });
75
+
76
+ // 0 ms: Add "one"
77
+ taskQueue.add('one');
78
+
79
+ await wait(50);
80
+
81
+ // 50 ms: First measurement, callback not called
82
+ assert.equal(asyncCallback.mock.callCount(), 0);
83
+
84
+ // 100 ms: Callback called for the first time
85
+
86
+ await wait(100);
87
+
88
+ // 150 ms: Second measurement, callback called once
89
+ assert.equal(asyncCallback.mock.callCount(), 1);
90
+
91
+ // 150 ms: Add "two"
92
+ taskQueue.add('two');
93
+
94
+ // 200 ms: First callback completes
95
+
96
+ await wait(100);
97
+
98
+ // 250 ms: Third measurement, callback still called only once
99
+ assert.equal(asyncCallback.mock.callCount(), 1);
100
+
101
+ // 300 ms: Callback called for the second time
102
+
103
+ await wait(100);
104
+
105
+ // 350 ms: Fourth measurement, callback called twice
106
+ assert.equal(asyncCallback.mock.callCount(), 2);
107
+ });
108
+
109
+ test('callback is called according to expected schedule with leading: true', async () => {
110
+ const asyncCallback = createAsyncCallback(100);
111
+ const taskQueue = new TaskQueue<string>(asyncCallback, { wait: 100, leading: true });
112
+
113
+ // 0 ms: Add "one"
114
+ taskQueue.add('one');
115
+
116
+ await wait(50);
117
+
118
+ // 50 ms: Add "two"
119
+ taskQueue.add('two');
120
+
121
+ // 50 ms: First measurement, callback called
122
+ assert.equal(asyncCallback.mock.callCount(), 1);
123
+
124
+ // 100 ms: First callback completes
125
+
126
+ await wait(100);
127
+
128
+ // 150 ms: Second measurement, callback still called once
129
+ assert.equal(asyncCallback.mock.callCount(), 1);
130
+
131
+ await wait(100);
132
+
133
+ // 250 ms: Third measurement, callback called twice
134
+ assert.equal(asyncCallback.mock.callCount(), 2);
135
+ });
136
+ });
@@ -0,0 +1,61 @@
1
+ import type { Throttle } from './types.ts';
2
+
3
+ type TaskCallback<T> = (items: Array<T>) => void;
4
+
5
+ export class TaskQueue<T> {
6
+ #throttle: Throttle;
7
+ #asyncCallback: TaskCallback<T> | null = null;
8
+
9
+ #items = new Set<T>();
10
+ #inRunLoop = false;
11
+
12
+ constructor(asyncCallback: TaskCallback<T>, throttle: Required<Throttle>) {
13
+ this.#asyncCallback = asyncCallback;
14
+ this.#throttle = throttle;
15
+ }
16
+
17
+ async #preRun() {
18
+ if (this.#inRunLoop) {
19
+ return;
20
+ }
21
+ this.#inRunLoop = true;
22
+
23
+ if (!this.#throttle.leading) {
24
+ await new Promise((resolve) => setTimeout(resolve, this.#throttle.wait));
25
+ }
26
+
27
+ await this.#run();
28
+ }
29
+
30
+ async #run() {
31
+ if (this.#items.size === 0) {
32
+ this.#inRunLoop = false;
33
+ return;
34
+ }
35
+
36
+ const items = Array.from(this.#items);
37
+
38
+ this.#items.clear();
39
+
40
+ if (this.#asyncCallback) {
41
+ await this.#asyncCallback(items);
42
+ }
43
+
44
+ await new Promise((resolve) => setTimeout(resolve, this.#throttle.wait));
45
+
46
+ await this.#run();
47
+ }
48
+
49
+ addMultiple(items: Array<T>) {
50
+ for (const item of items) {
51
+ this.#items.add(item);
52
+ }
53
+ if (this.#items.size > 0) {
54
+ this.#preRun();
55
+ }
56
+ }
57
+
58
+ add(item: T) {
59
+ this.addMultiple([item]);
60
+ }
61
+ }