accented 0.0.0-20250124142030 → 0.0.0-20250303013509

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 (129) hide show
  1. package/README.md +55 -3
  2. package/dist/accented.d.ts +3 -1
  3. package/dist/accented.d.ts.map +1 -1
  4. package/dist/accented.js +69 -50
  5. package/dist/accented.js.map +1 -1
  6. package/dist/constants.d.ts +3 -0
  7. package/dist/constants.d.ts.map +1 -0
  8. package/dist/constants.js +3 -0
  9. package/dist/constants.js.map +1 -0
  10. package/dist/dom-updater.d.ts +1 -1
  11. package/dist/dom-updater.d.ts.map +1 -1
  12. package/dist/dom-updater.js +26 -19
  13. package/dist/dom-updater.js.map +1 -1
  14. package/dist/elements/{accented-container.d.ts → accented-dialog.d.ts} +10 -4
  15. package/dist/elements/accented-dialog.d.ts.map +1 -0
  16. package/dist/elements/accented-dialog.js +371 -0
  17. package/dist/elements/accented-dialog.js.map +1 -0
  18. package/dist/elements/accented-trigger.d.ts +361 -0
  19. package/dist/elements/accented-trigger.d.ts.map +1 -0
  20. package/dist/elements/accented-trigger.js +188 -0
  21. package/dist/elements/accented-trigger.js.map +1 -0
  22. package/dist/intersection-observer.d.ts +5 -0
  23. package/dist/intersection-observer.d.ts.map +1 -0
  24. package/dist/intersection-observer.js +28 -0
  25. package/dist/intersection-observer.js.map +1 -0
  26. package/dist/log-and-rethrow.d.ts +2 -0
  27. package/dist/log-and-rethrow.d.ts.map +1 -0
  28. package/dist/log-and-rethrow.js +7 -0
  29. package/dist/log-and-rethrow.js.map +1 -0
  30. package/dist/logger.d.ts.map +1 -1
  31. package/dist/logger.js +10 -5
  32. package/dist/logger.js.map +1 -1
  33. package/dist/register-elements.d.ts +2 -0
  34. package/dist/register-elements.d.ts.map +1 -0
  35. package/dist/register-elements.js +21 -0
  36. package/dist/register-elements.js.map +1 -0
  37. package/dist/resize-listener.d.ts +2 -0
  38. package/dist/resize-listener.d.ts.map +1 -0
  39. package/dist/resize-listener.js +18 -0
  40. package/dist/resize-listener.js.map +1 -0
  41. package/dist/scanner.d.ts +2 -2
  42. package/dist/scanner.d.ts.map +1 -1
  43. package/dist/scanner.js +97 -33
  44. package/dist/scanner.js.map +1 -1
  45. package/dist/scroll-listeners.d.ts +2 -0
  46. package/dist/scroll-listeners.d.ts.map +1 -0
  47. package/dist/scroll-listeners.js +38 -0
  48. package/dist/scroll-listeners.js.map +1 -0
  49. package/dist/state.d.ts +1 -0
  50. package/dist/state.d.ts.map +1 -1
  51. package/dist/state.js +6 -0
  52. package/dist/state.js.map +1 -1
  53. package/dist/types.d.ts +71 -18
  54. package/dist/types.d.ts.map +1 -1
  55. package/dist/types.js +1 -0
  56. package/dist/types.js.map +1 -1
  57. package/dist/utils/deep-merge.js +1 -1
  58. package/dist/utils/deep-merge.js.map +1 -1
  59. package/dist/utils/get-element-html.d.ts +2 -0
  60. package/dist/utils/get-element-html.d.ts.map +1 -0
  61. package/dist/utils/get-element-html.js +14 -0
  62. package/dist/utils/get-element-html.js.map +1 -0
  63. package/dist/utils/get-element-position.d.ts +3 -0
  64. package/dist/utils/get-element-position.d.ts.map +1 -0
  65. package/dist/utils/get-element-position.js +58 -0
  66. package/dist/utils/get-element-position.js.map +1 -0
  67. package/dist/utils/get-scrollable-ancestors.d.ts +2 -0
  68. package/dist/utils/get-scrollable-ancestors.d.ts.map +1 -0
  69. package/dist/utils/get-scrollable-ancestors.js +15 -0
  70. package/dist/utils/get-scrollable-ancestors.js.map +1 -0
  71. package/dist/utils/is-html-element.d.ts +2 -0
  72. package/dist/utils/is-html-element.d.ts.map +1 -0
  73. package/dist/utils/is-html-element.js +7 -0
  74. package/dist/utils/is-html-element.js.map +1 -0
  75. package/dist/utils/recalculate-positions.d.ts +2 -0
  76. package/dist/utils/recalculate-positions.d.ts.map +1 -0
  77. package/dist/utils/recalculate-positions.js +27 -0
  78. package/dist/utils/recalculate-positions.js.map +1 -0
  79. package/dist/utils/recalculate-scrollable-ancestors.d.ts +2 -0
  80. package/dist/utils/recalculate-scrollable-ancestors.d.ts.map +1 -0
  81. package/dist/utils/recalculate-scrollable-ancestors.js +13 -0
  82. package/dist/utils/recalculate-scrollable-ancestors.js.map +1 -0
  83. package/dist/utils/supports-anchor-positioning.d.ts +6 -0
  84. package/dist/utils/supports-anchor-positioning.d.ts.map +1 -0
  85. package/dist/utils/supports-anchor-positioning.js +4 -0
  86. package/dist/utils/supports-anchor-positioning.js.map +1 -0
  87. package/dist/utils/transform-violations.d.ts.map +1 -1
  88. package/dist/utils/transform-violations.js +9 -0
  89. package/dist/utils/transform-violations.js.map +1 -1
  90. package/dist/utils/update-elements-with-issues.d.ts +3 -1
  91. package/dist/utils/update-elements-with-issues.d.ts.map +1 -1
  92. package/dist/utils/update-elements-with-issues.js +25 -7
  93. package/dist/utils/update-elements-with-issues.js.map +1 -1
  94. package/dist/validate-options.d.ts +3 -0
  95. package/dist/validate-options.d.ts.map +1 -0
  96. package/dist/validate-options.js +42 -0
  97. package/dist/validate-options.js.map +1 -0
  98. package/package.json +2 -1
  99. package/src/accented.ts +78 -58
  100. package/src/constants.ts +2 -0
  101. package/src/dom-updater.ts +26 -18
  102. package/src/elements/accented-dialog.ts +394 -0
  103. package/src/elements/accented-trigger.ts +214 -0
  104. package/src/intersection-observer.ts +28 -0
  105. package/src/log-and-rethrow.ts +9 -0
  106. package/src/logger.ts +11 -6
  107. package/src/register-elements.ts +21 -0
  108. package/src/resize-listener.ts +17 -0
  109. package/src/scanner.ts +108 -37
  110. package/src/scroll-listeners.ts +37 -0
  111. package/src/state.ts +12 -0
  112. package/src/types.ts +78 -19
  113. package/src/utils/deep-merge.test.ts +7 -0
  114. package/src/utils/deep-merge.ts +1 -1
  115. package/src/utils/get-element-html.ts +13 -0
  116. package/src/utils/get-element-position.ts +59 -0
  117. package/src/utils/get-scrollable-ancestors.ts +14 -0
  118. package/src/utils/is-html-element.ts +6 -0
  119. package/src/utils/recalculate-positions.ts +27 -0
  120. package/src/utils/recalculate-scrollable-ancestors.ts +13 -0
  121. package/src/utils/supports-anchor-positioning.ts +7 -0
  122. package/src/utils/transform-violations.ts +12 -1
  123. package/src/utils/update-elements-with-issues.test.ts +91 -16
  124. package/src/utils/update-elements-with-issues.ts +40 -20
  125. package/src/validate-options.ts +44 -0
  126. package/dist/elements/accented-container.d.ts.map +0 -1
  127. package/dist/elements/accented-container.js +0 -131
  128. package/dist/elements/accented-container.js.map +0 -1
  129. package/src/elements/accented-container.ts +0 -147
@@ -0,0 +1,28 @@
1
+ import logAndRethrow from './log-and-rethrow.js';
2
+ import { extendedElementsWithIssues } from './state.js';
3
+ import getElementPosition from './utils/get-element-position.js';
4
+
5
+ export default function setupIntersectionObserver() {
6
+ const intersectionObserver = new IntersectionObserver((entries) => {
7
+ try {
8
+ for (const entry of entries) {
9
+ const extendedElementWithIssues = extendedElementsWithIssues.value.find(el => el.element === entry.target);
10
+ if (extendedElementWithIssues) {
11
+ extendedElementWithIssues.visible.value = entry.isIntersecting;
12
+ if (entry.isIntersecting) {
13
+ extendedElementWithIssues.position.value = getElementPosition(entry.target, window);
14
+ }
15
+ }
16
+ }
17
+ } catch (error) {
18
+ logAndRethrow(error);
19
+ }
20
+ }, { threshold: 0 });
21
+
22
+ return {
23
+ intersectionObserver,
24
+ disconnect: () => {
25
+ intersectionObserver.disconnect();
26
+ }
27
+ };
28
+ }
@@ -0,0 +1,9 @@
1
+ import { issuesUrl } from './constants.js';
2
+
3
+ export default function logAndRethrow(error: unknown) {
4
+ console.error(
5
+ `Accented threw an error (see below). Try updating your browser to the latest version. ` +
6
+ `If you’re still seeing the error, file an issue at ${issuesUrl}.`
7
+ );
8
+ throw error;
9
+ }
package/src/logger.ts CHANGED
@@ -1,20 +1,25 @@
1
1
  import { effect } from '@preact/signals-core';
2
- import { elementsWithIssues } from './state.js';
3
-
4
- const accentedUrl = 'https://www.npmjs.com/package/accented';
2
+ import { elementsWithIssues, enabled } from './state.js';
3
+ import { accentedUrl } from './constants.js';
5
4
 
6
5
  export default function createLogger() {
7
6
 
8
7
  let firstRun = true;
9
8
 
10
9
  return effect(() => {
11
- if (elementsWithIssues.value.length > 0) {
12
- console.log(`Elements with accessibility issues, identified by Accented (${accentedUrl}):\n`, elementsWithIssues.value);
10
+ if (!enabled.value) {
11
+ return;
12
+ }
13
+
14
+ const elementCount = elementsWithIssues.value.length;
15
+ if (elementCount > 0) {
16
+ const issueCount = elementsWithIssues.value.reduce((acc, { issues }) => acc + issues.length, 0);
17
+ console.log(`${issueCount} accessibility issue${issueCount === 1 ? '' : 's'} found in ${elementCount} element${issueCount === 1 ? '' : 's'} (Accented, ${accentedUrl}):\n`, elementsWithIssues.value);
13
18
  } else {
14
19
  if (firstRun) {
15
20
  firstRun = false;
16
21
  } else {
17
- console.log(`No elements with accessibility issues identified by Accented (${accentedUrl}).`);
22
+ console.log(`No accessibility issues found (Accented, ${accentedUrl}).`);
18
23
  }
19
24
  }
20
25
  });
@@ -0,0 +1,21 @@
1
+ import getAccentedTrigger from './elements/accented-trigger.js';
2
+ import getAccentedDialog from './elements/accented-dialog.js';
3
+
4
+ export default 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,17 @@
1
+ import logAndRethrow from './log-and-rethrow.js';
2
+ import recalculatePositions from './utils/recalculate-positions.js';
3
+
4
+ export default function setupResizeListener() {
5
+ const abortController = new AbortController();
6
+ window.addEventListener('resize', () => {
7
+ try {
8
+ recalculatePositions();
9
+ } catch (error) {
10
+ logAndRethrow(error);
11
+ }
12
+ }, { signal: abortController.signal });
13
+
14
+ return () => {
15
+ abortController.abort();
16
+ };
17
+ };
package/src/scanner.ts CHANGED
@@ -1,60 +1,131 @@
1
1
  import axe from 'axe-core';
2
2
  import TaskQueue from './task-queue.js';
3
3
  import { elementsWithIssues, enabled, extendedElementsWithIssues } from './state.js';
4
- import type { Throttle, Callback } from './types';
4
+ import type { AxeOptions, Throttle, Callback, AxeContext } from './types';
5
5
  import updateElementsWithIssues from './utils/update-elements-with-issues.js';
6
+ import recalculatePositions from './utils/recalculate-positions.js';
7
+ import recalculateScrollableAncestors from './utils/recalculate-scrollable-ancestors.js';
8
+ import supportsAnchorPositioning from './utils/supports-anchor-positioning.js';
9
+ import { issuesUrl } from './constants.js';
10
+ import logAndRethrow from './log-and-rethrow.js';
6
11
 
7
- export default function createScanner(name: string, throttle: Required<Throttle>, callback: Callback) {
12
+ export default function createScanner(name: string, axeContext: AxeContext, axeOptions: AxeOptions, throttle: Required<Throttle>, callback: Callback) {
13
+ const axeRunningWindowProp = `__${name}_axe_running__`;
14
+ const win: Record<string, any> = window;
8
15
  const taskQueue = new TaskQueue<Node>(async () => {
9
- performance.mark('axe-start');
10
- const result = await axe.run({
11
- elementRef: true,
12
- // Although axe-core can perform iframe scanning, I haven't succeeded in it,
13
- // and the docs suggest that the axe-core script should be explicitly included
14
- // in each of the iframed documents anyway.
15
- // It seems preferable to disallow iframe scanning and not report issues in elements within iframes
16
- // in the case that such issues are for some reason reported by axe-core.
17
- // A consumer of Accented can instead scan the iframed document by calling Accented initialization from that document.
18
- iframes: false
19
- });
20
-
21
- const axeMeasure = performance.measure('axe', 'axe-start');
22
-
23
- if (!enabled.value) {
16
+ // We may see errors coming from axe-core when Accented is toggled off and on in qiuck succession,
17
+ // which I've seen happen with hot reloading of a React application.
18
+ // This window property serves as a circuit breaker for that particular case.
19
+ if (win[axeRunningWindowProp]) {
24
20
  return;
25
21
  }
26
22
 
27
- updateElementsWithIssues(extendedElementsWithIssues, result.violations, window, name);
23
+ try {
28
24
 
29
- callback({
30
- elementsWithIssues: elementsWithIssues.value,
31
- scanDuration: Math.round(axeMeasure.duration)
32
- });
25
+ performance.mark('axe-start');
26
+
27
+ win[axeRunningWindowProp] = true;
28
+
29
+ let result;
30
+
31
+ try {
32
+ // TODO (https://github.com/pomerantsev/accented/issues/102):
33
+ // only run Axe on what's changed, not on the whole axeContext
34
+ result = await axe.run(axeContext, {
35
+ elementRef: true,
36
+ // Although axe-core can perform iframe scanning, I haven't succeeded in it,
37
+ // and the docs suggest that the axe-core script should be explicitly included
38
+ // in each of the iframed documents anyway.
39
+ // It seems preferable to disallow iframe scanning and not report issues in elements within iframes
40
+ // in the case that such issues are for some reason reported by axe-core.
41
+ // A consumer of Accented can instead scan the iframed document by calling Accented initialization from that document.
42
+ iframes: false,
43
+ resultTypes: ['violations'],
44
+ ...axeOptions
45
+ });
46
+ } catch (error) {
47
+ console.error(
48
+ 'Accented: axe-core (the accessibility testing engine) threw an error. ' +
49
+ 'Check the `axeOptions` property that you’re passing to Accented. ' +
50
+ `If you still think it’s a bug in Accented, file an issue at ${issuesUrl}.\n`,
51
+ error
52
+ );
53
+ result = { violations: [] };
54
+ }
55
+ win[axeRunningWindowProp] = false;
56
+
57
+ const axeMeasure = performance.measure('axe', 'axe-start');
58
+
59
+ if (!enabled.value) {
60
+ return;
61
+ }
62
+
63
+ updateElementsWithIssues(extendedElementsWithIssues, result.violations, window, name);
64
+
65
+ callback({
66
+ elementsWithIssues: elementsWithIssues.value,
67
+ scanDuration: Math.round(axeMeasure.duration)
68
+ });
69
+ } catch (error) {
70
+ win[axeRunningWindowProp] = false;
71
+ logAndRethrow(error);
72
+ }
33
73
  }, throttle);
34
74
 
75
+ // TODO (https://github.com/pomerantsev/accented/issues/102):
76
+ // limit to what's in axeContext,
77
+ // if that's an element or array of elements (not a selector).
35
78
  taskQueue.add(document);
36
79
 
80
+ const accentedElementNames = [`${name}-trigger`, `${name}-dialog`];
37
81
  const mutationObserver = new MutationObserver(mutationList => {
38
- const listWithoutAccentedContainers = mutationList.filter(mutationRecord => {
39
- return !(mutationRecord.type === 'childList' &&
40
- [...mutationRecord.addedNodes].every(node => node.nodeName === `${name}-container`.toUpperCase()) &&
41
- [...mutationRecord.removedNodes].every(node => node.nodeName === `${name}-container`.toUpperCase()));
42
- });
43
-
44
- const elementsWithAccentedAttributeChanges = listWithoutAccentedContainers.reduce((nodes, mutationRecord) => {
45
- if (mutationRecord.type === 'attributes' && mutationRecord.attributeName === `data-${name}`) {
46
- nodes.add(mutationRecord.target);
82
+ try {
83
+ // We're not interested in mutations that are caused exclusively by the custom elements
84
+ // introduced by Accented.
85
+ const listWithoutAccentedElements = mutationList.filter(mutationRecord => {
86
+ const onlyAccentedElementsAddedOrRemoved = mutationRecord.type === 'childList' &&
87
+ [...mutationRecord.addedNodes].every(node => accentedElementNames.includes(node.nodeName.toLowerCase())) &&
88
+ [...mutationRecord.removedNodes].every(node => accentedElementNames.includes(node.nodeName.toLowerCase()));
89
+ const accentedElementChanged = mutationRecord.type === 'attributes' &&
90
+ accentedElementNames.includes(mutationRecord.target.nodeName.toLowerCase());
91
+ return !(onlyAccentedElementsAddedOrRemoved || accentedElementChanged);
92
+ });
93
+
94
+ if (listWithoutAccentedElements.length !== 0 && !supportsAnchorPositioning(window)) {
95
+ // Something has changed in the DOM, so we need to realign all triggers with respective elements.
96
+ recalculatePositions();
97
+
98
+ // Elements' scrollable ancestors only change when styles change
99
+ // (specifically when the `display` prop on one of the ancestors changes),
100
+ // so a good place to recalculate the scrollable ancestors for elements is here.
101
+ // In future, we could further optimize this by only recalculating scrollable ancestors for elements that have changed.
102
+ recalculateScrollableAncestors();
47
103
  }
48
- return nodes;
49
- }, new Set<Node>());
50
104
 
51
- const filteredMutationList = listWithoutAccentedContainers.filter(mutationRecord => {
52
- return !elementsWithAccentedAttributeChanges.has(mutationRecord.target);
53
- });
105
+ // Exclude all mutations on elements that got the accented attribute added or removed.
106
+ // If we simply exclude all mutations where attributeName = `data-${name}`,
107
+ // we may miss other mutations on those same elements caused by Accented,
108
+ // leading to extra runs of the mutation observer.
109
+ const elementsWithAccentedAttributeChanges = listWithoutAccentedElements.reduce((nodes, mutationRecord) => {
110
+ if (mutationRecord.type === 'attributes' && mutationRecord.attributeName === `data-${name}`) {
111
+ nodes.add(mutationRecord.target);
112
+ }
113
+ return nodes;
114
+ }, new Set<Node>());
115
+
116
+ const filteredMutationList = listWithoutAccentedElements.filter(mutationRecord => {
117
+ return !elementsWithAccentedAttributeChanges.has(mutationRecord.target);
118
+ });
54
119
 
55
- taskQueue.addMultiple(filteredMutationList.map(mutationRecord => mutationRecord.target));
120
+ taskQueue.addMultiple(filteredMutationList.map(mutationRecord => mutationRecord.target));
121
+ } catch (error) {
122
+ logAndRethrow(error);
123
+ }
56
124
  });
57
125
 
126
+ // TODO (https://github.com/pomerantsev/accented/issues/102):
127
+ // possibly limit the observer to what's in axeContext,
128
+ // if that's an element or array of elements (not a selector).
58
129
  mutationObserver.observe(document, {
59
130
  subtree: true,
60
131
  childList: true,
@@ -0,0 +1,37 @@
1
+ import { effect } from '@preact/signals-core';
2
+ import recalculatePositions from './utils/recalculate-positions.js';
3
+ import { scrollableAncestors } from './state.js';
4
+ import logAndRethrow from './log-and-rethrow.js';
5
+
6
+ export default function setupScrollListeners() {
7
+ const documentAbortController = new AbortController();
8
+ document.addEventListener('scroll', () => {
9
+ try {
10
+ recalculatePositions();
11
+ } catch (error) {
12
+ logAndRethrow(error);
13
+ }
14
+ }, { signal: documentAbortController.signal });
15
+
16
+ const disposeOfEffect = effect(() => {
17
+ // TODO: optimize performance, issue #81
18
+ const elementAbortController = new AbortController();
19
+ for (const scrollableAncestor of scrollableAncestors.value) {
20
+ scrollableAncestor.addEventListener('scroll', () => {
21
+ try {
22
+ recalculatePositions();
23
+ } catch (error) {
24
+ logAndRethrow(error);
25
+ }
26
+ }, { signal: elementAbortController.signal });
27
+ }
28
+ return () => {
29
+ elementAbortController.abort();
30
+ }
31
+ });
32
+
33
+ return () => {
34
+ documentAbortController.abort();
35
+ disposeOfEffect();
36
+ };
37
+ };
package/src/state.ts CHANGED
@@ -10,3 +10,15 @@ export const elementsWithIssues = computed<Array<ElementWithIssues>>(() => exten
10
10
  element: extendedElementWithIssues.element,
11
11
  issues: extendedElementWithIssues.issues.value
12
12
  })));
13
+
14
+ export const scrollableAncestors = computed<Set<HTMLElement>>(() =>
15
+ extendedElementsWithIssues.value.reduce(
16
+ (scrollableAncestors, extendedElementWithIssues) => {
17
+ for (const scrollableAncestor of extendedElementWithIssues.scrollableAncestors.value) {
18
+ scrollableAncestors.add(scrollableAncestor);
19
+ }
20
+ return scrollableAncestors;
21
+ },
22
+ new Set<HTMLElement>()
23
+ )
24
+ );
package/src/types.ts CHANGED
@@ -1,29 +1,40 @@
1
1
  import type axe from 'axe-core';
2
2
  import type { Signal } from '@preact/signals-core';
3
- import type { AccentedContainer } from './elements/accented-container';
4
-
5
- export type DeepRequired<T> = T extends object ? {
6
- [P in keyof T]-? : DeepRequired<T[P]>
7
- } : T;
3
+ import type { AccentedTrigger } from './elements/accented-trigger';
8
4
 
9
5
  export type Throttle = {
10
6
  /**
11
7
  * The minimal time between scans.
12
8
  *
13
- * Default: 1000.
9
+ * Default: `1000`.
14
10
  * */
15
11
  wait?: number,
16
12
 
17
13
  /**
18
14
  * When to run the scan on Accented initialization or on a mutation.
19
15
  *
20
- * If true, the scan will run immediately. If false, the scan will run after the first throttle delay.
16
+ * If `true`, the scan will run immediately. If `false`, the scan will run after the first throttle delay.
21
17
  *
22
- * Default: true.
18
+ * Default: `true`.
23
19
  * */
24
20
  leading?: boolean
25
21
  }
26
22
 
23
+ export type Output = {
24
+ /**
25
+ * Whether to output the issues to the console.
26
+ *
27
+ * Default: `true`.
28
+ * */
29
+ console?: boolean
30
+ }
31
+
32
+ export type AxeContext = axe.ElementContext;
33
+
34
+ export const allowedAxeOptions = ['rules', 'runOnly'] as const;
35
+
36
+ export type AxeOptions = Pick<axe.RunOptions, typeof allowedAxeOptions[number]>;
37
+
27
38
  type CallbackParams = {
28
39
  /**
29
40
  * The most current array of elements with issues.
@@ -40,23 +51,61 @@ export type Callback = (params: CallbackParams) => void;
40
51
 
41
52
  export type AccentedOptions = {
42
53
 
54
+ /**
55
+ * The `context` parameter for `axe.run()`.
56
+ *
57
+ * Determines what element(s) to scan for accessibility issues.
58
+ *
59
+ * Accepts a variety of shapes:
60
+ * * an element reference;
61
+ * * a selector;
62
+ * * a `NodeList`;
63
+ * * an include / exclude object;
64
+ * * and more.
65
+ *
66
+ * See documentation: https://www.deque.com/axe/core-documentation/api-documentation/#context-parameter
67
+ *
68
+ * Default: `document`.
69
+ */
70
+ axeContext?: AxeContext,
71
+
72
+ /**
73
+ * The `options` parameter for `axe.run()`.
74
+ *
75
+ * Accented only supports two keys of the `options` object:
76
+ * * `rules`;
77
+ * * `runOnly`.
78
+ *
79
+ * Both properties are optional, and both control
80
+ * which accessibility rules your page is tested against.
81
+ *
82
+ * See documentation: https://www.deque.com/axe/core-documentation/api-documentation/#options-parameter
83
+ *
84
+ * Default: `{}`.
85
+ */
86
+ axeOptions?: AxeOptions,
87
+
43
88
  /**
44
89
  * The character sequence that’s used in various elements, attributes and stylesheets that Accented adds to the page.
45
- * * The data attribute that’s added to elements with issues (default: "data-accented").
46
- * * The custom element that encapsulates the button and dialog attached to each element with issues (default: "accented-container").
47
- * * The CSS cascade layer containing page-wide Accented-specific styles (default: "accented").
48
- * * The prefix for some of the CSS custom properties used by Accented (default: "--accented-").
90
+ * * The data attribute that’s added to elements with issues (default: `data-accented`).
91
+ * * The custom elements for the button and the dialog that get created for each element with issues
92
+ * (default: `accented-trigger`, `accented-dialog`).
93
+ * * The CSS cascade layer containing page-wide Accented-specific styles (default: `accented`).
94
+ * * The prefix for some of the CSS custom properties used by Accented (default: `--accented-`).
95
+ * * The window property that’s used to prevent multiple axe-core scans from running simultaneously
96
+ * (default: `__accented_axe_running__`).
49
97
  *
50
- * Default: "accented".
98
+ * Only lowercase alphanumeric characters and dashes (-) are allowed in the name,
99
+ * and it must start with a lowercase letter.
100
+ *
101
+ * Default: `accented`.
51
102
  */
52
103
  name?: string,
53
104
 
54
105
  /**
55
- * Whether to output the issues to the console.
56
- *
57
- * Default: true.
106
+ * Output options object.
58
107
  * */
59
- outputToConsole?: boolean,
108
+ output?: Output,
60
109
 
61
110
  /**
62
111
  * Scan throttling options object.
@@ -66,7 +115,7 @@ export type AccentedOptions = {
66
115
  /**
67
116
  * A callback that will be called after each scan.
68
117
  *
69
- * Default: () => {}.
118
+ * Default: `() => {}`.
70
119
  * */
71
120
  callback?: Callback
72
121
  };
@@ -77,6 +126,13 @@ export type AccentedOptions = {
77
126
  */
78
127
  export type DisableAccented = () => void;
79
128
 
129
+ export type Position = {
130
+ left: number,
131
+ top: number,
132
+ width: number,
133
+ height: number
134
+ };
135
+
80
136
  export type Issue = {
81
137
  id: string,
82
138
  title: string,
@@ -92,6 +148,9 @@ export type ElementWithIssues = {
92
148
 
93
149
  export type ExtendedElementWithIssues = Omit<ElementWithIssues, 'issues'> & {
94
150
  issues: Signal<ElementWithIssues['issues']>,
95
- accentedContainer: AccentedContainer,
151
+ visible: Signal<boolean>,
152
+ trigger: AccentedTrigger,
153
+ position: Signal<Position>,
154
+ scrollableAncestors: Signal<Set<HTMLElement>>
96
155
  id: number
97
156
  };
@@ -24,4 +24,11 @@ suite('deepMerge', () => {
24
24
  const result = deepMerge(target, source);
25
25
  assert.deepEqual(result, { a: null });
26
26
  });
27
+
28
+ test('doesn’t turn arrays into objects', () => {
29
+ const target = { a: [1, 2, 3] };
30
+ const source = { a: [4, 5] };
31
+ const result = deepMerge(target, source);
32
+ assert.deepEqual(result, { a: [4, 5] });
33
+ });
27
34
  });
@@ -3,7 +3,7 @@ type AnyObject = Record<string, any>;
3
3
  export default function deepMerge(target: AnyObject, source: AnyObject): AnyObject {
4
4
  const output = {...target};
5
5
  for (const key of Object.keys(source)) {
6
- if (typeof source[key] === 'object' && source[key] !== null) {
6
+ if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key])) {
7
7
  if (!(key in target)) {
8
8
  output[key] = source[key];
9
9
  } else {
@@ -0,0 +1,13 @@
1
+ export default function getElementHtml(element: Element) {
2
+ const outerHtml = element.outerHTML;
3
+ const innerHtml = element.innerHTML;
4
+ if (!innerHtml) {
5
+ return outerHtml;
6
+ }
7
+ const index = outerHtml.indexOf(innerHtml);
8
+ if (index === -1) {
9
+ // This shouldn't be happening, but if it does, we can just return the outer HTML.
10
+ return outerHtml;
11
+ }
12
+ return outerHtml.slice(0, index) + '…' + outerHtml.slice(index + innerHtml.length);
13
+ }
@@ -0,0 +1,59 @@
1
+ import type { Position } from '../types';
2
+ import isHtmlElement from './is-html-element.js';
3
+
4
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_display/Containing_block#identifying_the_containing_block
5
+ function isContainingBlock(element: Element, win: Window): boolean {
6
+ const style = win.getComputedStyle(element);
7
+ const { transform, perspective } = style;
8
+ // TODO: https://github.com/pomerantsev/accented/issues/119
9
+ // Support other types of containing blocks
10
+ return transform !== 'none'
11
+ || perspective !== 'none';
12
+ }
13
+
14
+ function getNonInitialContainingBlock(element: Element, win: Window): Element | null {
15
+ let currentElement: Element | null = element;
16
+ while (currentElement?.parentElement) {
17
+ currentElement = currentElement.parentElement;
18
+ if (isContainingBlock(currentElement, win)) {
19
+ return currentElement;
20
+ }
21
+ }
22
+ return null;
23
+ }
24
+
25
+ export default function getElementPosition(element: Element, win: Window): Position {
26
+ const nonInitialContainingBlock = getNonInitialContainingBlock(element, win);
27
+ // If an element has an ancestor whose transform is not 'none',
28
+ // fixed positioning works differently.
29
+ // https://achrafkassioui.com/blog/position-fixed-and-CSS-transforms/
30
+ if (nonInitialContainingBlock) {
31
+ if (isHtmlElement(element)) {
32
+ const width = element.offsetWidth;
33
+ const height = element.offsetHeight;
34
+ let left = element.offsetLeft;
35
+ let top = element.offsetTop;
36
+ let currentElement = element.offsetParent as HTMLElement | null;
37
+ // Non-initial containing block may not be an offset parent, we have to account for that as well.
38
+ while (currentElement && currentElement !== nonInitialContainingBlock) {
39
+ left += currentElement.offsetLeft;
40
+ top += currentElement.offsetTop;
41
+ currentElement = currentElement.offsetParent as HTMLElement | null;
42
+ }
43
+ return { top, left, width, height };
44
+ } else {
45
+ // TODO: https://github.com/pomerantsev/accented/issues/116
46
+ // This is half-baked. It works incorrectly with scaled / rotated elements with issues.
47
+ const elementRect = element.getBoundingClientRect();
48
+ const nonInitialContainingBlockRect = nonInitialContainingBlock.getBoundingClientRect();
49
+ return {
50
+ top: elementRect.top - nonInitialContainingBlockRect.top,
51
+ height: elementRect.height,
52
+ left: elementRect.left - nonInitialContainingBlockRect.left,
53
+ width: elementRect.width
54
+ };
55
+ }
56
+ } else {
57
+ return element.getBoundingClientRect();
58
+ }
59
+ }
@@ -0,0 +1,14 @@
1
+ const scrollableOverflowValues = new Set(['auto', 'scroll', 'hidden']);
2
+
3
+ export default function getScrollableAncestors (element: HTMLElement, win: Window) {
4
+ let currentElement = element;
5
+ let scrollableAncestors = new Set<HTMLElement>();
6
+ while (currentElement.parentElement) {
7
+ currentElement = currentElement.parentElement;
8
+ const computedStyle = win.getComputedStyle(currentElement);
9
+ if (scrollableOverflowValues.has(computedStyle.overflowX) || scrollableOverflowValues.has(computedStyle.overflowY)) {
10
+ scrollableAncestors.add(currentElement);
11
+ }
12
+ }
13
+ return scrollableAncestors;
14
+ };
@@ -0,0 +1,6 @@
1
+ export default function isHtmlElement(element: Element): element is HTMLElement {
2
+ // We can't use instanceof because it may not work across contexts
3
+ // (such as when an element is moved from an iframe).
4
+ // This heuristic seems to be the most robust and fastest that I could think of.
5
+ return element.constructor.name.startsWith('HTML');
6
+ }
@@ -0,0 +1,27 @@
1
+ import { batch } from '@preact/signals-core';
2
+ import { extendedElementsWithIssues } from '../state.js';
3
+ import getElementPosition from './get-element-position.js';
4
+ import logAndRethrow from '../log-and-rethrow.js';
5
+
6
+ let frameRequested = false;
7
+
8
+ export default function recalculatePositions() {
9
+ if (frameRequested) {
10
+ return;
11
+ }
12
+ frameRequested = true;
13
+ window.requestAnimationFrame(() => {
14
+ try {
15
+ frameRequested = false;
16
+ batch(() => {
17
+ extendedElementsWithIssues.value.forEach(({ element, position, visible }) => {
18
+ if (visible.value && element.isConnected) {
19
+ position.value = getElementPosition(element, window);
20
+ }
21
+ });
22
+ });
23
+ } catch (error) {
24
+ logAndRethrow(error);
25
+ }
26
+ });
27
+ }
@@ -0,0 +1,13 @@
1
+ import { batch } from '@preact/signals-core';
2
+ import { extendedElementsWithIssues } from '../state.js';
3
+ import getScrollableAncestors from './get-scrollable-ancestors.js';
4
+
5
+ export default function recalculateScrollableAncestors() {
6
+ batch(() => {
7
+ extendedElementsWithIssues.value.forEach(({ element, scrollableAncestors }) => {
8
+ if (element.isConnected) {
9
+ scrollableAncestors.value = getScrollableAncestors(element, window);
10
+ }
11
+ });
12
+ });
13
+ }
@@ -0,0 +1,7 @@
1
+ type WindowWithCSS = Window & {
2
+ CSS: typeof CSS
3
+ }
4
+
5
+ export default function supportsAnchorPositioning(win: WindowWithCSS) {
6
+ return win.CSS.supports('anchor-name: --foo') && win.CSS.supports('position-anchor: --foo');
7
+ }