@a11y-pulse/browser-adaptor 0.7.0 → 0.9.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.
package/README.md CHANGED
@@ -20,7 +20,7 @@ npm install @a11y-pulse/browser-adaptor
20
20
 
21
21
  | Entry | Contents |
22
22
  | --- | --- |
23
- | `@a11y-pulse/browser-adaptor` | `BrowserAdaptor`, `ElementRef`, `Rect`, `bufferedClip`, `contrastRatio`, `parseOpaqueRgb`, `relativeLuminance` |
23
+ | `@a11y-pulse/browser-adaptor` | `BrowserAdaptor`, `ElementRef`, `Rect`, `bufferedClip`, `captureElementScreenshot`, `contrastRatio`, `parseOpaqueRgb`, `relativeLuminance`, `stashedElementHandle`, `stashedElementSelectors`, `releaseStashedElements`, and the page scripts `captureElementScreenshot` is built on |
24
24
  | `@a11y-pulse/browser-adaptor/puppeteer` | `PuppeteerAdaptor` |
25
25
  | `@a11y-pulse/browser-adaptor/playwright` | `PlaywrightAdaptor` |
26
26
  | `@a11y-pulse/browser-adaptor/dom` | `getSelector`, `truncateHtml` |
@@ -108,6 +108,24 @@ import { getSelector, truncateHtml } from "@a11y-pulse/browser-adaptor/dom";
108
108
 
109
109
  `getSelector` builds a compact selector for an element (intended to run in page context). `truncateHtml` shortens an element's opening tag for display in results.
110
110
 
111
+ A page script that collects many elements in one evaluate can leave them on `window` under a key of its own, then fetch selectors (or, with `stashedElementHandle`, a handle) for only the ones it reports:
112
+
113
+ ```js
114
+ import { releaseStashedElements, stashedElementSelectors } from "@a11y-pulse/browser-adaptor";
115
+
116
+ const records = await adaptor.evaluate(collectScript, "__myAuditElements");
117
+
118
+ try {
119
+ const selectors = await stashedElementSelectors(adaptor, "__myAuditElements", [0, 4]);
120
+ } finally {
121
+ await releaseStashedElements(adaptor, "__myAuditElements");
122
+ }
123
+ ```
124
+
125
+ ## Element screenshots
126
+
127
+ `captureElementScreenshot(adaptor, handle, { clipBuffer, settleDelay })` screenshots an element clipped to its box plus `clipBuffer` padding. It first centres the element in the viewport if the clip would not fit there or something covers the element's centre, then waits `settleDelay` ms. The caller owns `handle`, and restores the scroll position if that matters.
128
+
111
129
  ## License
112
130
 
113
131
  [MIT](./LICENSE.md). Use it however you like, including in commercial and competing products.
@@ -0,0 +1,143 @@
1
+ // src/get-selector.ts
2
+ function getSelector(root) {
3
+ const MAX_LENGTH = 128;
4
+ const esc = (value) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(value) : value;
5
+ const tagName = (node2) => node2.nodeType === 1 ? node2.nodeName.toLowerCase() : node2.nodeName.toUpperCase().replace(/^#/, "");
6
+ const rootOf = (element) => {
7
+ const node2 = element.getRootNode?.();
8
+ return node2 && typeof node2.querySelectorAll === "function" ? node2 : null;
9
+ };
10
+ const matchCount = (queryRoot2, selector) => {
11
+ try {
12
+ return queryRoot2.querySelectorAll(selector).length;
13
+ } catch {
14
+ return Number.POSITIVE_INFINITY;
15
+ }
16
+ };
17
+ const safeMatches = (element, selector) => {
18
+ try {
19
+ return typeof element.matches === "function" && element.matches(selector);
20
+ } catch {
21
+ return false;
22
+ }
23
+ };
24
+ const idIsUnique = (element, id) => {
25
+ const queryRoot2 = rootOf(element);
26
+ return queryRoot2 === null || matchCount(queryRoot2, `#${esc(id)}`) === 1;
27
+ };
28
+ const classFeature = (cls) => ({
29
+ feature: `.${esc(cls)}`,
30
+ sharedBy: (sibling) => Array.from(sibling.classList ?? []).includes(cls)
31
+ });
32
+ const rarestFeature = (element, queryRoot2) => {
33
+ const classes = Array.from(element.classList).slice(0, 8);
34
+ if (!queryRoot2) {
35
+ const cls = classes[0];
36
+ return cls === void 0 ? null : classFeature(cls);
37
+ }
38
+ let best = null;
39
+ let bestCount = Number.POSITIVE_INFINITY;
40
+ for (const cls of classes) {
41
+ const candidate = classFeature(cls);
42
+ if (!safeMatches(element, candidate.feature)) {
43
+ continue;
44
+ }
45
+ const count = matchCount(queryRoot2, candidate.feature);
46
+ if (count < bestCount) {
47
+ best = candidate;
48
+ bestCount = count;
49
+ }
50
+ if (count === 1) {
51
+ return best;
52
+ }
53
+ }
54
+ const href = typeof element.getAttribute === "function" ? element.getAttribute("href") : null;
55
+ if (href && href.length <= 100 && !/["\\?]/.test(href)) {
56
+ const feature = `[href="${href}"]`;
57
+ if (safeMatches(element, feature) && matchCount(queryRoot2, feature) < bestCount) {
58
+ return {
59
+ feature,
60
+ sharedBy: (sibling) => typeof sibling.getAttribute === "function" && sibling.getAttribute("href") === href
61
+ };
62
+ }
63
+ }
64
+ return best;
65
+ };
66
+ const positionAmongSiblings = (element, sharedBy) => {
67
+ const siblings = element.parentNode?.children;
68
+ if (!siblings) {
69
+ return { nth: 0, ambiguous: false };
70
+ }
71
+ let nth = 0;
72
+ let count = 0;
73
+ let shared = 0;
74
+ for (const sibling of Array.from(siblings)) {
75
+ if (sibling.nodeName !== element.nodeName) {
76
+ continue;
77
+ }
78
+ count++;
79
+ if (sibling === element) {
80
+ nth = count;
81
+ }
82
+ if (sharedBy(sibling)) {
83
+ shared++;
84
+ }
85
+ }
86
+ return { nth, ambiguous: shared > 1 };
87
+ };
88
+ const segmentFor = (element, queryRoot2) => {
89
+ if (element.id && idIsUnique(element, element.id)) {
90
+ return { segment: `#${esc(element.id)}`, anchored: true };
91
+ }
92
+ const feature = rarestFeature(element, queryRoot2);
93
+ let segment = tagName(element) + (feature === null ? "" : feature.feature);
94
+ const { nth, ambiguous } = positionAmongSiblings(
95
+ element,
96
+ feature === null ? () => true : feature.sharedBy
97
+ );
98
+ if (ambiguous && nth > 0) {
99
+ segment += `:nth-of-type(${nth})`;
100
+ }
101
+ return { segment, anchored: false };
102
+ };
103
+ const degradedSegmentFor = (element) => {
104
+ let segment = tagName(element);
105
+ const { nth, ambiguous } = positionAmongSiblings(element, () => true);
106
+ if (ambiguous && nth > 0) {
107
+ segment += `:nth-of-type(${nth})`;
108
+ }
109
+ return segment;
110
+ };
111
+ const segments = [];
112
+ let node = root;
113
+ const queryRoot = root && root.nodeType === 1 ? rootOf(root) : null;
114
+ try {
115
+ while (node && node.nodeType === 1) {
116
+ const element = node;
117
+ let { segment, anchored } = segmentFor(element, queryRoot);
118
+ const joinedWith = (candidate) => segments.length ? candidate.length + 1 + segments.join(">").length : candidate.length;
119
+ if (joinedWith(segment) > MAX_LENGTH - 1) {
120
+ segment = degradedSegmentFor(element);
121
+ anchored = false;
122
+ if (joinedWith(segment) > MAX_LENGTH - 1) {
123
+ break;
124
+ }
125
+ }
126
+ segments.unshift(segment);
127
+ if (anchored) {
128
+ break;
129
+ }
130
+ if (queryRoot && matchCount(queryRoot, segments.join(">")) === 1) {
131
+ break;
132
+ }
133
+ node = element.parentNode;
134
+ }
135
+ } catch {
136
+ }
137
+ return segments.join(">");
138
+ }
139
+
140
+ export {
141
+ getSelector
142
+ };
143
+ //# sourceMappingURL=chunk-WI4RV7YK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/get-selector.ts"],"sourcesContent":["/**\n * Build a compact, hopefully-unique selector for any given element on the page. This function is\n * serialized and run in the page context, so it must not reference any symbols outside its own\n * scope.\n *\n * Mirrors axe-core's approach: each level contributes the fewest features that discriminate the\n * element (a unique id, the rarest single class, or an :nth-of-type position), and the walk stops\n * as soon as the joined selector matches exactly one element. Selectors stay short because of that\n * early stop, not because of truncation; the length budget is only a backstop.\n */\nexport function getSelector(root: Node | null): string {\n\tconst MAX_LENGTH = 128;\n\n\tconst esc = (value: string): string =>\n\t\ttypeof CSS !== \"undefined\" && typeof CSS.escape === \"function\" ? CSS.escape(value) : value;\n\n\tconst tagName = (node: Node): string =>\n\t\tnode.nodeType === 1\n\t\t\t? node.nodeName.toLowerCase()\n\t\t\t: node.nodeName.toUpperCase().replace(/^#/, \"\");\n\n\t// A querySelectorAll-capable root (Document or ShadowRoot) for the element, used to confirm\n\t// uniqueness and class rarity. Absent on the plain objects used in the serialisation unit tests,\n\t// where we trust ids and walk to the top instead of stopping early.\n\tconst rootOf = (element: Element): ParentNode | null => {\n\t\tconst node = (element as Element & { getRootNode?: () => Node }).getRootNode?.();\n\n\t\treturn node && typeof (node as ParentNode).querySelectorAll === \"function\"\n\t\t\t? (node as ParentNode)\n\t\t\t: null;\n\t};\n\n\tconst matchCount = (queryRoot: ParentNode, selector: string): number => {\n\t\ttry {\n\t\t\treturn queryRoot.querySelectorAll(selector).length;\n\t\t} catch {\n\t\t\t// A selector that fails to parse can't be relied on.\n\t\t\treturn Number.POSITIVE_INFINITY;\n\t\t}\n\t};\n\n\t// A candidate feature is only usable if it actually selects this element; an escaping or engine\n\t// mismatch (e.g. CSS string escapes in an attribute value) could otherwise produce a selector\n\t// that matches nothing. Or a different element entirely.\n\tconst safeMatches = (element: Element, selector: string): boolean => {\n\t\ttry {\n\t\t\treturn typeof element.matches === \"function\" && element.matches(selector);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst idIsUnique = (element: Element, id: string): boolean => {\n\t\tconst queryRoot = rootOf(element);\n\n\t\treturn queryRoot === null || matchCount(queryRoot, `#${esc(id)}`) === 1;\n\t};\n\n\t// A discriminating feature for one level of the selector: its CSS text plus a predicate telling\n\t// whether a sibling would match the same feature (used to decide if an :nth-of-type pin is still\n\t// needed).\n\ttype Feature = {\n\t\tfeature: string;\n\t\tsharedBy: (sibling: Element) => boolean;\n\t};\n\n\tconst classFeature = (cls: string): Feature => ({\n\t\tfeature: `.${esc(cls)}`,\n\t\tsharedBy: (sibling) => Array.from(sibling.classList ?? []).includes(cls),\n\t});\n\n\t// The single feature that narrows the element down the most: the class or href attribute with the\n\t// fewest matches in the root. Hrefs break ties between structurally-identical content blocks,\n\t// where classes and :nth-of-type (which only pins position within one parent) cannot. Without a\n\t// queryable root there is no rarity information, so the first class stands in.\n\tconst rarestFeature = (element: Element, queryRoot: ParentNode | null): Feature | null => {\n\t\tconst classes = Array.from(element.classList).slice(0, 8);\n\n\t\tif (!queryRoot) {\n\t\t\tconst cls = classes[0];\n\n\t\t\treturn cls === undefined ? null : classFeature(cls);\n\t\t}\n\n\t\tlet best: Feature | null = null;\n\t\tlet bestCount = Number.POSITIVE_INFINITY;\n\n\t\tfor (const cls of classes) {\n\t\t\tconst candidate = classFeature(cls);\n\n\t\t\tif (!safeMatches(element, candidate.feature)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst count = matchCount(queryRoot, candidate.feature);\n\n\t\t\tif (count < bestCount) {\n\t\t\t\tbest = candidate;\n\t\t\t\tbestCount = count;\n\t\t\t}\n\n\t\t\tif (count === 1) {\n\t\t\t\treturn best;\n\t\t\t}\n\t\t}\n\n\t\tconst href = typeof element.getAttribute === \"function\" ? element.getAttribute(\"href\") : null;\n\n\t\t// Skip hrefs with characters that change meaning inside a CSS string (quotes, backslashes), and\n\t\t// query strings, which are too volatile across runs to pin a selector to. Fragments (#main)\n\t\t// stay eligible. Skip links make stable discriminators.\n\t\tif (href && href.length <= 100 && !/[\"\\\\?]/.test(href)) {\n\t\t\tconst feature = `[href=\"${href}\"]`;\n\n\t\t\tif (safeMatches(element, feature) && matchCount(queryRoot, feature) < bestCount) {\n\t\t\t\treturn {\n\t\t\t\t\tfeature,\n\t\t\t\t\tsharedBy: (sibling) =>\n\t\t\t\t\t\ttypeof sibling.getAttribute === \"function\" && sibling.getAttribute(\"href\") === href,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t};\n\n\t// The element's 1-based position among same-tag siblings, and whether the chosen feature fails to\n\t// discriminate it from them (so the segment needs an :nth-of-type pin). Siblings are absent on\n\t// the serialisation test nodes. There we skip the pin.\n\tconst positionAmongSiblings = (\n\t\telement: Element,\n\t\tsharedBy: (sibling: Element) => boolean,\n\t): { nth: number; ambiguous: boolean } => {\n\t\tconst siblings = (element.parentNode as ParentNode | null)?.children;\n\n\t\tif (!siblings) {\n\t\t\treturn { nth: 0, ambiguous: false };\n\t\t}\n\n\t\tlet nth = 0;\n\t\tlet count = 0;\n\t\tlet shared = 0;\n\n\t\tfor (const sibling of Array.from(siblings)) {\n\t\t\tif (sibling.nodeName !== element.nodeName) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcount++;\n\n\t\t\tif (sibling === element) {\n\t\t\t\tnth = count;\n\t\t\t}\n\n\t\t\tif (sharedBy(sibling)) {\n\t\t\t\tshared++;\n\t\t\t}\n\t\t}\n\n\t\treturn { nth, ambiguous: shared > 1 };\n\t};\n\n\tconst segmentFor = (\n\t\telement: Element,\n\t\tqueryRoot: ParentNode | null,\n\t): { segment: string; anchored: boolean } => {\n\t\t// Only treat an id as an absolute anchor when it actually resolves to a single element: pages\n\t\t// with duplicate ids would otherwise yield a selector (e.g. \"#dup>a\") that matches several\n\t\t// elements.\n\t\tif (element.id && idIsUnique(element, element.id)) {\n\t\t\treturn { segment: `#${esc(element.id)}`, anchored: true };\n\t\t}\n\n\t\tconst feature = rarestFeature(element, queryRoot);\n\t\tlet segment = tagName(element) + (feature === null ? \"\" : feature.feature);\n\n\t\t// When same-tag siblings share the chosen feature, pin the position so the segment selects\n\t\t// exactly this element rather than all of them.\n\t\tconst { nth, ambiguous } = positionAmongSiblings(\n\t\t\telement,\n\t\t\tfeature === null ? () => true : feature.sharedBy,\n\t\t);\n\n\t\tif (ambiguous && nth > 0) {\n\t\t\tsegment += `:nth-of-type(${nth})`;\n\t\t}\n\n\t\treturn { segment, anchored: false };\n\t};\n\n\t// A minimal segment for when a level's full segment would blow the budget (e.g. an enormous class\n\t// name or a long href): just the tag, pinned by position when same-tag siblings would make the\n\t// bare tag ambiguous.\n\tconst degradedSegmentFor = (element: Element): string => {\n\t\tlet segment = tagName(element);\n\n\t\tconst { nth, ambiguous } = positionAmongSiblings(element, () => true);\n\n\t\tif (ambiguous && nth > 0) {\n\t\t\tsegment += `:nth-of-type(${nth})`;\n\t\t}\n\n\t\treturn segment;\n\t};\n\n\tconst segments: string[] = [];\n\tlet node: Node | null = root;\n\tconst queryRoot = root && root.nodeType === 1 ? rootOf(root as Element) : null;\n\n\ttry {\n\t\t// Walk only element nodes. Stopping at the first non-element parent (the document, or a\n\t\t// ShadowRoot when the target is inside an open shadow root) keeps the selector within its tree\n\t\t// and avoids reading `classList` off a node that has none.\n\t\twhile (node && node.nodeType === 1) {\n\t\t\tconst element = node as Element;\n\t\t\tlet { segment, anchored } = segmentFor(element, queryRoot);\n\n\t\t\t// Keep within the budget (the +1 accounts for the \">\" that would join this segment to the\n\t\t\t// rest). A level whose full segment doesn't fit is degraded to tag + position rather than\n\t\t\t// discarded, so ancestor context is never lost to one long feature.\n\t\t\tconst joinedWith = (candidate: string): number =>\n\t\t\t\tsegments.length ? candidate.length + 1 + segments.join(\">\").length : candidate.length;\n\n\t\t\tif (joinedWith(segment) > MAX_LENGTH - 1) {\n\t\t\t\tsegment = degradedSegmentFor(element);\n\t\t\t\tanchored = false;\n\n\t\t\t\tif (joinedWith(segment) > MAX_LENGTH - 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsegments.unshift(segment);\n\n\t\t\tif (anchored) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Stop as soon as the selector already identifies a single element. This, not truncation, is\n\t\t\t// what keeps selectors short.\n\t\t\tif (queryRoot && matchCount(queryRoot, segments.join(\">\")) === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tnode = element.parentNode;\n\t\t}\n\t} catch {\n\t\t// A malformed node tree must never crash the audit; return what we have.\n\t}\n\n\treturn segments.join(\">\");\n}\n"],"mappings":";AAUO,SAAS,YAAY,MAA2B;AACtD,QAAM,aAAa;AAEnB,QAAM,MAAM,CAAC,UACZ,OAAO,QAAQ,eAAe,OAAO,IAAI,WAAW,aAAa,IAAI,OAAO,KAAK,IAAI;AAEtF,QAAM,UAAU,CAACA,UAChBA,MAAK,aAAa,IACfA,MAAK,SAAS,YAAY,IAC1BA,MAAK,SAAS,YAAY,EAAE,QAAQ,MAAM,EAAE;AAKhD,QAAM,SAAS,CAAC,YAAwC;AACvD,UAAMA,QAAQ,QA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
- const esc = (value) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(value) : value;
5
- const tagName = (node2) => node2.nodeType === 1 ? node2.nodeName.toLowerCase() : node2.nodeName.toUpperCase().replace(/^#/, "");
6
- const rootOf = (element) => {
7
- const node2 = element.getRootNode?.();
8
- return node2 && typeof node2.querySelectorAll === "function" ? node2 : null;
9
- };
10
- const matchCount = (queryRoot2, selector) => {
11
- try {
12
- return queryRoot2.querySelectorAll(selector).length;
13
- } catch {
14
- return Number.POSITIVE_INFINITY;
15
- }
16
- };
17
- const safeMatches = (element, selector) => {
18
- try {
19
- return typeof element.matches === "function" && element.matches(selector);
20
- } catch {
21
- return false;
22
- }
23
- };
24
- const idIsUnique = (element, id) => {
25
- const queryRoot2 = rootOf(element);
26
- return queryRoot2 === null || matchCount(queryRoot2, `#${esc(id)}`) === 1;
27
- };
28
- const classFeature = (cls) => ({
29
- feature: `.${esc(cls)}`,
30
- sharedBy: (sibling) => Array.from(sibling.classList ?? []).includes(cls)
31
- });
32
- const rarestFeature = (element, queryRoot2) => {
33
- const classes = Array.from(element.classList).slice(0, 8);
34
- if (!queryRoot2) {
35
- const cls = classes[0];
36
- return cls === void 0 ? null : classFeature(cls);
37
- }
38
- let best = null;
39
- let bestCount = Number.POSITIVE_INFINITY;
40
- for (const cls of classes) {
41
- const candidate = classFeature(cls);
42
- if (!safeMatches(element, candidate.feature)) {
43
- continue;
44
- }
45
- const count = matchCount(queryRoot2, candidate.feature);
46
- if (count < bestCount) {
47
- best = candidate;
48
- bestCount = count;
49
- }
50
- if (count === 1) {
51
- return best;
52
- }
53
- }
54
- const href = typeof element.getAttribute === "function" ? element.getAttribute("href") : null;
55
- if (href && href.length <= 100 && !/["\\?]/.test(href)) {
56
- const feature = `[href="${href}"]`;
57
- if (safeMatches(element, feature) && matchCount(queryRoot2, feature) < bestCount) {
58
- return {
59
- feature,
60
- sharedBy: (sibling) => typeof sibling.getAttribute === "function" && sibling.getAttribute("href") === href
61
- };
62
- }
63
- }
64
- return best;
65
- };
66
- const positionAmongSiblings = (element, sharedBy) => {
67
- const siblings = element.parentNode?.children;
68
- if (!siblings) {
69
- return { nth: 0, ambiguous: false };
70
- }
71
- let nth = 0;
72
- let count = 0;
73
- let shared = 0;
74
- for (const sibling of Array.from(siblings)) {
75
- if (sibling.nodeName !== element.nodeName) {
76
- continue;
77
- }
78
- count++;
79
- if (sibling === element) {
80
- nth = count;
81
- }
82
- if (sharedBy(sibling)) {
83
- shared++;
84
- }
85
- }
86
- return { nth, ambiguous: shared > 1 };
87
- };
88
- const segmentFor = (element, queryRoot2) => {
89
- if (element.id && idIsUnique(element, element.id)) {
90
- return { segment: `#${esc(element.id)}`, anchored: true };
91
- }
92
- const feature = rarestFeature(element, queryRoot2);
93
- let segment = tagName(element) + (feature === null ? "" : feature.feature);
94
- const { nth, ambiguous } = positionAmongSiblings(
95
- element,
96
- feature === null ? () => true : feature.sharedBy
97
- );
98
- if (ambiguous && nth > 0) {
99
- segment += `:nth-of-type(${nth})`;
100
- }
101
- return { segment, anchored: false };
102
- };
103
- const degradedSegmentFor = (element) => {
104
- let segment = tagName(element);
105
- const { nth, ambiguous } = positionAmongSiblings(element, () => true);
106
- if (ambiguous && nth > 0) {
107
- segment += `:nth-of-type(${nth})`;
108
- }
109
- return segment;
110
- };
111
- const segments = [];
112
- let node = root;
113
- const queryRoot = root && root.nodeType === 1 ? rootOf(root) : null;
114
- try {
115
- while (node && node.nodeType === 1) {
116
- const element = node;
117
- let { segment, anchored } = segmentFor(element, queryRoot);
118
- const joinedWith = (candidate) => segments.length ? candidate.length + 1 + segments.join(">").length : candidate.length;
119
- if (joinedWith(segment) > MAX_LENGTH - 1) {
120
- segment = degradedSegmentFor(element);
121
- anchored = false;
122
- if (joinedWith(segment) > MAX_LENGTH - 1) {
123
- break;
124
- }
125
- }
126
- segments.unshift(segment);
127
- if (anchored) {
128
- break;
129
- }
130
- if (queryRoot && matchCount(queryRoot, segments.join(">")) === 1) {
131
- break;
132
- }
133
- node = element.parentNode;
134
- }
135
- } catch {
136
- }
137
- return segments.join(">");
138
- }
1
+ import {
2
+ getSelector
3
+ } from "./chunk-WI4RV7YK.js";
139
4
 
140
5
  // src/truncate-html.ts
141
6
  var DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 50;
package/dist/dom.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/get-selector.ts","../src/truncate-html.ts"],"sourcesContent":["/**\n * Build a compact, hopefully-unique selector for any given element on the page. This function is\n * serialized and run in the page context, so it must not reference any symbols outside its own\n * scope.\n *\n * Mirrors axe-core's approach: each level contributes the fewest features that discriminate the\n * element (a unique id, the rarest single class, or an :nth-of-type position), and the walk stops\n * as soon as the joined selector matches exactly one element. Selectors stay short because of that\n * early stop, not because of truncation; the length budget is only a backstop.\n */\nexport function getSelector(root: Node | null): string {\n\tconst MAX_LENGTH = 128;\n\n\tconst esc = (value: string): string =>\n\t\ttypeof CSS !== \"undefined\" && typeof CSS.escape === \"function\" ? CSS.escape(value) : value;\n\n\tconst tagName = (node: Node): string =>\n\t\tnode.nodeType === 1\n\t\t\t? node.nodeName.toLowerCase()\n\t\t\t: node.nodeName.toUpperCase().replace(/^#/, \"\");\n\n\t// A querySelectorAll-capable root (Document or ShadowRoot) for the element, used to confirm\n\t// uniqueness and class rarity. Absent on the plain objects used in the serialisation unit tests,\n\t// where we trust ids and walk to the top instead of stopping early.\n\tconst rootOf = (element: Element): ParentNode | null => {\n\t\tconst node = (element as Element & { getRootNode?: () => Node }).getRootNode?.();\n\n\t\treturn node && typeof (node as ParentNode).querySelectorAll === \"function\"\n\t\t\t? (node as ParentNode)\n\t\t\t: null;\n\t};\n\n\tconst matchCount = (queryRoot: ParentNode, selector: string): number => {\n\t\ttry {\n\t\t\treturn queryRoot.querySelectorAll(selector).length;\n\t\t} catch {\n\t\t\t// A selector that fails to parse can't be relied on.\n\t\t\treturn Number.POSITIVE_INFINITY;\n\t\t}\n\t};\n\n\t// A candidate feature is only usable if it actually selects this element; an escaping or engine\n\t// mismatch (e.g. CSS string escapes in an attribute value) could otherwise produce a selector\n\t// that matches nothing. Or a different element entirely.\n\tconst safeMatches = (element: Element, selector: string): boolean => {\n\t\ttry {\n\t\t\treturn typeof element.matches === \"function\" && element.matches(selector);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tconst idIsUnique = (element: Element, id: string): boolean => {\n\t\tconst queryRoot = rootOf(element);\n\n\t\treturn queryRoot === null || matchCount(queryRoot, `#${esc(id)}`) === 1;\n\t};\n\n\t// A discriminating feature for one level of the selector: its CSS text plus a predicate telling\n\t// whether a sibling would match the same feature (used to decide if an :nth-of-type pin is still\n\t// needed).\n\ttype Feature = {\n\t\tfeature: string;\n\t\tsharedBy: (sibling: Element) => boolean;\n\t};\n\n\tconst classFeature = (cls: string): Feature => ({\n\t\tfeature: `.${esc(cls)}`,\n\t\tsharedBy: (sibling) => Array.from(sibling.classList ?? []).includes(cls),\n\t});\n\n\t// The single feature that narrows the element down the most: the class or href attribute with the\n\t// fewest matches in the root. Hrefs break ties between structurally-identical content blocks,\n\t// where classes and :nth-of-type (which only pins position within one parent) cannot. Without a\n\t// queryable root there is no rarity information, so the first class stands in.\n\tconst rarestFeature = (element: Element, queryRoot: ParentNode | null): Feature | null => {\n\t\tconst classes = Array.from(element.classList).slice(0, 8);\n\n\t\tif (!queryRoot) {\n\t\t\tconst cls = classes[0];\n\n\t\t\treturn cls === undefined ? null : classFeature(cls);\n\t\t}\n\n\t\tlet best: Feature | null = null;\n\t\tlet bestCount = Number.POSITIVE_INFINITY;\n\n\t\tfor (const cls of classes) {\n\t\t\tconst candidate = classFeature(cls);\n\n\t\t\tif (!safeMatches(element, candidate.feature)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst count = matchCount(queryRoot, candidate.feature);\n\n\t\t\tif (count < bestCount) {\n\t\t\t\tbest = candidate;\n\t\t\t\tbestCount = count;\n\t\t\t}\n\n\t\t\tif (count === 1) {\n\t\t\t\treturn best;\n\t\t\t}\n\t\t}\n\n\t\tconst href = typeof element.getAttribute === \"function\" ? element.getAttribute(\"href\") : null;\n\n\t\t// Skip hrefs with characters that change meaning inside a CSS string (quotes, backslashes), and\n\t\t// query strings, which are too volatile across runs to pin a selector to. Fragments (#main)\n\t\t// stay eligible. Skip links make stable discriminators.\n\t\tif (href && href.length <= 100 && !/[\"\\\\?]/.test(href)) {\n\t\t\tconst feature = `[href=\"${href}\"]`;\n\n\t\t\tif (safeMatches(element, feature) && matchCount(queryRoot, feature) < bestCount) {\n\t\t\t\treturn {\n\t\t\t\t\tfeature,\n\t\t\t\t\tsharedBy: (sibling) =>\n\t\t\t\t\t\ttypeof sibling.getAttribute === \"function\" && sibling.getAttribute(\"href\") === href,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t};\n\n\t// The element's 1-based position among same-tag siblings, and whether the chosen feature fails to\n\t// discriminate it from them (so the segment needs an :nth-of-type pin). Siblings are absent on\n\t// the serialisation test nodes. There we skip the pin.\n\tconst positionAmongSiblings = (\n\t\telement: Element,\n\t\tsharedBy: (sibling: Element) => boolean,\n\t): { nth: number; ambiguous: boolean } => {\n\t\tconst siblings = (element.parentNode as ParentNode | null)?.children;\n\n\t\tif (!siblings) {\n\t\t\treturn { nth: 0, ambiguous: false };\n\t\t}\n\n\t\tlet nth = 0;\n\t\tlet count = 0;\n\t\tlet shared = 0;\n\n\t\tfor (const sibling of Array.from(siblings)) {\n\t\t\tif (sibling.nodeName !== element.nodeName) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcount++;\n\n\t\t\tif (sibling === element) {\n\t\t\t\tnth = count;\n\t\t\t}\n\n\t\t\tif (sharedBy(sibling)) {\n\t\t\t\tshared++;\n\t\t\t}\n\t\t}\n\n\t\treturn { nth, ambiguous: shared > 1 };\n\t};\n\n\tconst segmentFor = (\n\t\telement: Element,\n\t\tqueryRoot: ParentNode | null,\n\t): { segment: string; anchored: boolean } => {\n\t\t// Only treat an id as an absolute anchor when it actually resolves to a single element: pages\n\t\t// with duplicate ids would otherwise yield a selector (e.g. \"#dup>a\") that matches several\n\t\t// elements.\n\t\tif (element.id && idIsUnique(element, element.id)) {\n\t\t\treturn { segment: `#${esc(element.id)}`, anchored: true };\n\t\t}\n\n\t\tconst feature = rarestFeature(element, queryRoot);\n\t\tlet segment = tagName(element) + (feature === null ? \"\" : feature.feature);\n\n\t\t// When same-tag siblings share the chosen feature, pin the position so the segment selects\n\t\t// exactly this element rather than all of them.\n\t\tconst { nth, ambiguous } = positionAmongSiblings(\n\t\t\telement,\n\t\t\tfeature === null ? () => true : feature.sharedBy,\n\t\t);\n\n\t\tif (ambiguous && nth > 0) {\n\t\t\tsegment += `:nth-of-type(${nth})`;\n\t\t}\n\n\t\treturn { segment, anchored: false };\n\t};\n\n\t// A minimal segment for when a level's full segment would blow the budget (e.g. an enormous class\n\t// name or a long href): just the tag, pinned by position when same-tag siblings would make the\n\t// bare tag ambiguous.\n\tconst degradedSegmentFor = (element: Element): string => {\n\t\tlet segment = tagName(element);\n\n\t\tconst { nth, ambiguous } = positionAmongSiblings(element, () => true);\n\n\t\tif (ambiguous && nth > 0) {\n\t\t\tsegment += `:nth-of-type(${nth})`;\n\t\t}\n\n\t\treturn segment;\n\t};\n\n\tconst segments: string[] = [];\n\tlet node: Node | null = root;\n\tconst queryRoot = root && root.nodeType === 1 ? rootOf(root as Element) : null;\n\n\ttry {\n\t\t// Walk only element nodes. Stopping at the first non-element parent (the document, or a\n\t\t// ShadowRoot when the target is inside an open shadow root) keeps the selector within its tree\n\t\t// and avoids reading `classList` off a node that has none.\n\t\twhile (node && node.nodeType === 1) {\n\t\t\tconst element = node as Element;\n\t\t\tlet { segment, anchored } = segmentFor(element, queryRoot);\n\n\t\t\t// Keep within the budget (the +1 accounts for the \">\" that would join this segment to the\n\t\t\t// rest). A level whose full segment doesn't fit is degraded to tag + position rather than\n\t\t\t// discarded, so ancestor context is never lost to one long feature.\n\t\t\tconst joinedWith = (candidate: string): number =>\n\t\t\t\tsegments.length ? candidate.length + 1 + segments.join(\">\").length : candidate.length;\n\n\t\t\tif (joinedWith(segment) > MAX_LENGTH - 1) {\n\t\t\t\tsegment = degradedSegmentFor(element);\n\t\t\t\tanchored = false;\n\n\t\t\t\tif (joinedWith(segment) > MAX_LENGTH - 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsegments.unshift(segment);\n\n\t\t\tif (anchored) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Stop as soon as the selector already identifies a single element. This, not truncation, is\n\t\t\t// what keeps selectors short.\n\t\t\tif (queryRoot && matchCount(queryRoot, segments.join(\">\")) === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tnode = element.parentNode;\n\t\t}\n\t} catch {\n\t\t// A malformed node tree must never crash the audit; return what we have.\n\t}\n\n\treturn segments.join(\">\");\n}\n","const DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 50;\nconst DEFAULT_MAX_LENGTH = 300;\nconst ELLIPSIS = \"...\";\n\nexport type TruncateHtmlOptions = {\n\tmaxAttributeValueLength?: number;\n\tmaxLength?: number;\n};\n\n/**\n * Given an element's outerHTML, produce a truncated version suitable for display in results. For\n * memory efficiency, pass a shallow outerHTML i.e. `Node.cloneNode(false).outerHTML`.\n */\nexport function truncateHtml(html: string, options: TruncateHtmlOptions = {}): string {\n\tif (!html) {\n\t\treturn \"\";\n\t}\n\n\tconst maxAttributeValueLength =\n\t\toptions.maxAttributeValueLength ?? DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH;\n\tconst maxLength = options.maxLength ?? DEFAULT_MAX_LENGTH;\n\n\t// Keep only the opening tag\n\tconst closingBracket = html.indexOf(\">\");\n\tconst openingTag = closingBracket === -1 ? html : html.slice(0, closingBracket + 1);\n\n\t// Shorten long quoted attribute values, preserving the quote style.\n\tconst trimmed = openingTag.replace(\n\t\t/=([\"'])([\\s\\S]*?)\\1/g,\n\t\t(match, quote: string, value: string) => {\n\t\t\tif (value.length <= maxAttributeValueLength) {\n\t\t\t\treturn match;\n\t\t\t}\n\n\t\t\treturn `=${quote}${value.slice(0, maxAttributeValueLength)}${ELLIPSIS}${quote}`;\n\t\t},\n\t);\n\n\tif (trimmed.length > maxLength) {\n\t\treturn `${trimmed.slice(0, maxLength)}${ELLIPSIS}`;\n\t}\n\n\treturn trimmed;\n}\n"],"mappings":";AAUO,SAAS,YAAY,MAA2B;AACtD,QAAM,aAAa;AAEnB,QAAM,MAAM,CAAC,UACZ,OAAO,QAAQ,eAAe,OAAO,IAAI,WAAW,aAAa,IAAI,OAAO,KAAK,IAAI;AAEtF,QAAM,UAAU,CAACA,UAChBA,MAAK,aAAa,IACfA,MAAK,SAAS,YAAY,IAC1BA,MAAK,SAAS,YAAY,EAAE,QAAQ,MAAM,EAAE;AAKhD,QAAM,SAAS,CAAC,YAAwC;AACvD,UAAMA,QAAQ,QAAmD,cAAc;AAE/E,WAAOA,SAAQ,OAAQA,MAAoB,qBAAqB,aAC5DA,QACD;AAAA,EACJ;AAEA,QAAM,aAAa,CAACC,YAAuB,aAA6B;AACvE,QAAI;AACH,aAAOA,WAAU,iBAAiB,QAAQ,EAAE;AAAA,IAC7C,QAAQ;AAEP,aAAO,OAAO;AAAA,IACf;AAAA,EACD;AAKA,QAAM,cAAc,CAAC,SAAkB,aAA8B;AACpE,QAAI;AACH,aAAO,OAAO,QAAQ,YAAY,cAAc,QAAQ,QAAQ,QAAQ;AAAA,IACzE,QAAQ;AACP,aAAO;AAAA,IACR;AAAA,EACD;AAEA,QAAM,aAAa,CAAC,SAAkB,OAAwB;AAC7D,UAAMA,aAAY,OAAO,OAAO;AAEhC,WAAOA,eAAc,QAAQ,WAAWA,YAAW,IAAI,IAAI,EAAE,CAAC,EAAE,MAAM;AAAA,EACvE;AAUA,QAAM,eAAe,CAAC,SAA0B;AAAA,IAC/C,SAAS,IAAI,IAAI,GAAG,CAAC;AAAA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-html.ts"],"sourcesContent":["const DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 50;\nconst DEFAULT_MAX_LENGTH = 300;\nconst ELLIPSIS = \"...\";\n\nexport type TruncateHtmlOptions = {\n\tmaxAttributeValueLength?: number;\n\tmaxLength?: number;\n};\n\n/**\n * Given an element's outerHTML, produce a truncated version suitable for display in results. For\n * memory efficiency, pass a shallow outerHTML i.e. `Node.cloneNode(false).outerHTML`.\n */\nexport function truncateHtml(html: string, options: TruncateHtmlOptions = {}): string {\n\tif (!html) {\n\t\treturn \"\";\n\t}\n\n\tconst maxAttributeValueLength =\n\t\toptions.maxAttributeValueLength ?? DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH;\n\tconst maxLength = options.maxLength ?? DEFAULT_MAX_LENGTH;\n\n\t// Keep only the opening tag\n\tconst closingBracket = html.indexOf(\">\");\n\tconst openingTag = closingBracket === -1 ? html : html.slice(0, closingBracket + 1);\n\n\t// Shorten long quoted attribute values, preserving the quote style.\n\tconst trimmed = openingTag.replace(\n\t\t/=([\"'])([\\s\\S]*?)\\1/g,\n\t\t(match, quote: string, value: string) => {\n\t\t\tif (value.length <= maxAttributeValueLength) {\n\t\t\t\treturn match;\n\t\t\t}\n\n\t\t\treturn `=${quote}${value.slice(0, maxAttributeValueLength)}${ELLIPSIS}${quote}`;\n\t\t},\n\t);\n\n\tif (trimmed.length > maxLength) {\n\t\treturn `${trimmed.slice(0, maxLength)}${ELLIPSIS}`;\n\t}\n\n\treturn trimmed;\n}\n"],"mappings":";;;;;AAAA,IAAM,qCAAqC;AAC3C,IAAM,qBAAqB;AAC3B,IAAM,WAAW;AAWV,SAAS,aAAa,MAAc,UAA+B,CAAC,GAAW;AACrF,MAAI,CAAC,MAAM;AACV,WAAO;AAAA,EACR;AAEA,QAAM,0BACL,QAAQ,2BAA2B;AACpC,QAAM,YAAY,QAAQ,aAAa;AAGvC,QAAM,iBAAiB,KAAK,QAAQ,GAAG;AACvC,QAAM,aAAa,mBAAmB,KAAK,OAAO,KAAK,MAAM,GAAG,iBAAiB,CAAC;AAGlF,QAAM,UAAU,WAAW;AAAA,IAC1B;AAAA,IACA,CAAC,OAAO,OAAe,UAAkB;AACxC,UAAI,MAAM,UAAU,yBAAyB;AAC5C,eAAO;AAAA,MACR;AAEA,aAAO,IAAI,KAAK,GAAG,MAAM,MAAM,GAAG,uBAAuB,CAAC,GAAG,QAAQ,GAAG,KAAK;AAAA,IAC9E;AAAA,EACD;AAEA,MAAI,QAAQ,SAAS,WAAW;AAC/B,WAAO,GAAG,QAAQ,MAAM,GAAG,SAAS,CAAC,GAAG,QAAQ;AAAA,EACjD;AAEA,SAAO;AACR;","names":[]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * IMPORTANT: The `*Script` functions in this file are serialized and injected into the audited page,
3
+ * so they must not reference any symbols outside their own scope.
4
+ */
5
+ import type { BrowserAdaptor, ElementRef, Rect } from "./adaptor";
6
+ export declare function pageDimensionsScript(): {
7
+ width: number;
8
+ height: number;
9
+ };
10
+ export declare function elementRectScript(el: Element | null): Rect;
11
+ /**
12
+ * Whether the element should be centred in the viewport before its screenshots are taken: either
13
+ * something unrelated covers its centre, or its screenshot clip (its box padded by `buffer`, cut
14
+ * off at the document edges like bufferedClip) reaches past an edge of the viewport. A capture only
15
+ * shows what is inside the viewport, so such a clip would lose an indicator drawn in the padding. A
16
+ * clip larger than the viewport does not count, since scrolling cannot fit it anyway.
17
+ */
18
+ export declare function needsCentringScript(el: Element | null, buffer: number): boolean;
19
+ /**
20
+ * Scroll the window so the element sits at the vertical centre of the viewport and is inside it
21
+ * horizontally with `buffer` to spare, instantly so a screenshot taken immediately afterwards isn't
22
+ * captured mid-animation. Scrolls the window directly rather than via scrollIntoView(): Chromium
23
+ * moves the sequential focus navigation starting point to the element passed to scrollIntoView(),
24
+ * so when focus cannot be handed back afterwards (a closed shadow host) the next Tab would re-enter
25
+ * the same element instead of moving on.
26
+ */
27
+ export declare function scrollToCenterScript(el: Element | null, buffer?: number): void;
28
+ export type ElementScreenshotOptions = {
29
+ /** Padding around the element's box. */
30
+ clipBuffer: number;
31
+ /** How long to wait (ms) after scrolling for the page to settle. */
32
+ settleDelay: number;
33
+ };
34
+ /**
35
+ * Screenshot the element `handle` refers to, clipped to its box plus `clipBuffer` padding, first
36
+ * centring it in the viewport when its clip would not fit or something covers it. The caller owns
37
+ * `handle`.
38
+ */
39
+ export declare function captureElementScreenshot(adaptor: Pick<BrowserAdaptor, "evaluate" | "screenshotClip" | "screenshotClipScale">, handle: ElementRef, options: ElementScreenshotOptions): Promise<Uint8Array>;
package/dist/index.d.ts CHANGED
@@ -2,3 +2,5 @@ export type { BrowserAdaptor, ElementRef, KeyName, Rect } from "./adaptor";
2
2
  export { bufferedClip } from "./clip";
3
3
  export type { Rgb } from "./contrast";
4
4
  export { contrastRatio, parseOpaqueRgb, relativeLuminance } from "./contrast";
5
+ export { captureElementScreenshot, type ElementScreenshotOptions, elementRectScript, needsCentringScript, pageDimensionsScript, scrollToCenterScript, } from "./element-screenshot";
6
+ export { releaseStashedElements, stashedElementHandle, stashedElementSelectors, } from "./stashed-elements";
package/dist/index.js CHANGED
@@ -1,3 +1,7 @@
1
+ import {
2
+ getSelector
3
+ } from "./chunk-WI4RV7YK.js";
4
+
1
5
  // src/clip.ts
2
6
  function bufferedClip(rect, pageWidth, pageHeight, buffer) {
3
7
  const left = Math.max(0, Math.min(buffer, rect.x));
@@ -36,10 +40,128 @@ function contrastRatio(a, b) {
36
40
  const lb = relativeLuminance(b);
37
41
  return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
38
42
  }
43
+
44
+ // src/element-screenshot.ts
45
+ function pageDimensionsScript() {
46
+ return {
47
+ width: document.documentElement.scrollWidth,
48
+ height: document.documentElement.scrollHeight
49
+ };
50
+ }
51
+ function elementRectScript(el) {
52
+ if (!el) {
53
+ return { x: 0, y: 0, width: 0, height: 0 };
54
+ }
55
+ const rect = el.getBoundingClientRect();
56
+ return {
57
+ x: rect.left + window.scrollX,
58
+ y: rect.top + window.scrollY,
59
+ width: rect.width,
60
+ height: rect.height
61
+ };
62
+ }
63
+ function needsCentringScript(el, buffer) {
64
+ if (!el) {
65
+ return false;
66
+ }
67
+ const rect = el.getBoundingClientRect();
68
+ const viewport = document.scrollingElement ?? document.documentElement;
69
+ const viewportWidth = viewport.clientWidth;
70
+ const viewportHeight = viewport.clientHeight;
71
+ const x = Math.min(Math.max(rect.left + rect.width / 2, 0), viewportWidth - 1);
72
+ const y = Math.min(Math.max(rect.top + rect.height / 2, 0), viewportHeight - 1);
73
+ let hit = document.elementFromPoint(x, y);
74
+ while (hit?.shadowRoot) {
75
+ const inner = hit.shadowRoot.elementFromPoint(x, y);
76
+ if (!inner || inner === hit) {
77
+ break;
78
+ }
79
+ hit = inner;
80
+ }
81
+ if (hit && hit !== el && !el.contains(hit) && !hit.contains(el)) {
82
+ return true;
83
+ }
84
+ const docLeft = -window.scrollX;
85
+ const docTop = -window.scrollY;
86
+ const left = Math.max(rect.left - buffer, docLeft);
87
+ const top = Math.max(rect.top - buffer, docTop);
88
+ const right = Math.min(rect.right + buffer, docLeft + document.documentElement.scrollWidth);
89
+ const bottom = Math.min(rect.bottom + buffer, docTop + document.documentElement.scrollHeight);
90
+ if (right - left > viewportWidth || bottom - top > viewportHeight) {
91
+ return false;
92
+ }
93
+ return left < 0 || top < 0 || right > viewportWidth || bottom > viewportHeight;
94
+ }
95
+ function scrollToCenterScript(el, buffer = 0) {
96
+ if (!el) {
97
+ return;
98
+ }
99
+ const rect = el.getBoundingClientRect();
100
+ const viewport = document.scrollingElement ?? document.documentElement;
101
+ const viewportWidth = viewport.clientWidth;
102
+ const top = rect.top + rect.height / 2 - viewport.clientHeight / 2;
103
+ let left = 0;
104
+ if (rect.left - buffer < 0) {
105
+ left = rect.left - buffer;
106
+ } else if (rect.right + buffer > viewportWidth) {
107
+ left = Math.min(rect.right + buffer - viewportWidth, rect.left - buffer);
108
+ }
109
+ window.scrollBy({ top, left, behavior: "instant" });
110
+ }
111
+ async function captureElementScreenshot(adaptor, handle, options) {
112
+ if (await adaptor.evaluate(needsCentringScript, handle, options.clipBuffer)) {
113
+ await adaptor.evaluate(scrollToCenterScript, handle, options.clipBuffer);
114
+ await new Promise((resolve) => setTimeout(resolve, options.settleDelay));
115
+ }
116
+ const { width: pageWidth, height: pageHeight } = await adaptor.evaluate(pageDimensionsScript);
117
+ const rect = await adaptor.evaluate(elementRectScript, handle);
118
+ const clip = bufferedClip(rect, pageWidth, pageHeight, options.clipBuffer);
119
+ return adaptor.screenshotClip(clip, adaptor.screenshotClipScale ?? 1);
120
+ }
121
+
122
+ // src/stashed-elements.ts
123
+ function pickStashedScript(stashKey, index) {
124
+ const stash = window[stashKey];
125
+ window.__a11yPulsePickedElement = Array.isArray(stash) ? stash[index] ?? null : null;
126
+ }
127
+ function pickedElementScript() {
128
+ return window.__a11yPulsePickedElement ?? null;
129
+ }
130
+ function releaseStashScript(stashKey) {
131
+ delete window[stashKey];
132
+ delete window.__a11yPulsePickedElement;
133
+ }
134
+ async function stashedElementHandle(adaptor, stashKey, index) {
135
+ await adaptor.evaluate(pickStashedScript, stashKey, index);
136
+ return adaptor.evaluateHandle(pickedElementScript);
137
+ }
138
+ async function stashedElementSelectors(adaptor, stashKey, indices) {
139
+ const selectors = [];
140
+ for (const index of indices) {
141
+ const handle = await stashedElementHandle(adaptor, stashKey, index);
142
+ try {
143
+ selectors.push(await adaptor.evaluate(getSelector, handle));
144
+ } finally {
145
+ await adaptor.disposeRef(handle);
146
+ }
147
+ }
148
+ return selectors;
149
+ }
150
+ async function releaseStashedElements(adaptor, stashKey) {
151
+ await adaptor.evaluate(releaseStashScript, stashKey);
152
+ }
39
153
  export {
40
154
  bufferedClip,
155
+ captureElementScreenshot,
41
156
  contrastRatio,
157
+ elementRectScript,
158
+ needsCentringScript,
159
+ pageDimensionsScript,
42
160
  parseOpaqueRgb,
43
- relativeLuminance
161
+ relativeLuminance,
162
+ releaseStashedElements,
163
+ scrollToCenterScript,
164
+ stashedElementHandle,
165
+ stashedElementSelectors
44
166
  };
45
167
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/clip.ts","../src/contrast.ts"],"sourcesContent":["import type { Rect } from \"./adaptor\";\n\n/**\n * A screenshot clip framing `rect` with up to `buffer` pixels of padding on each side, shrunk where\n * the page edges leave less room. The padding allows for indicators drawn just outside the element\n * box (outlines, shadows) and for anti-aliasing.\n */\nexport function bufferedClip(\n\trect: Rect,\n\tpageWidth: number,\n\tpageHeight: number,\n\tbuffer: number,\n): Rect {\n\tconst left = Math.max(0, Math.min(buffer, rect.x));\n\tconst top = Math.max(0, Math.min(buffer, rect.y));\n\tconst right = Math.max(0, Math.min(buffer, pageWidth - rect.x - rect.width));\n\tconst bottom = Math.max(0, Math.min(buffer, pageHeight - rect.y - rect.height));\n\n\t// Clamp to non-negative origins: an element positioned partially off the top or left of the\n\t// document has a negative page-relative rect, and Puppeteer rejects a screenshot clip with\n\t// negative x/y.\n\treturn {\n\t\tx: Math.max(0, rect.x - left),\n\t\ty: Math.max(0, rect.y - top),\n\t\twidth: rect.width + left + right,\n\t\theight: rect.height + top + bottom,\n\t};\n}\n","export type Rgb = readonly [number, number, number];\n\n// Computed colours serialise as `rgb()` or `rgba()` with comma separators for sRGB values. Colours\n// authored in other spaces (oklch, display-p3) keep their own notation and are not parsed.\nconst RGB_PATTERN = /^rgba?\\(\\s*([\\d.]+),\\s*([\\d.]+),\\s*([\\d.]+)(?:,\\s*([\\d.]+))?\\s*\\)$/;\n\n/**\n * Parse a computed `rgb()` or `rgba()` colour, or return null when it is translucent or in another\n * notation.\n */\nexport function parseOpaqueRgb(value: string): Rgb | null {\n\tconst match = RGB_PATTERN.exec(value.trim());\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tif (match[4] !== undefined && Number(match[4]) < 1) {\n\t\treturn null;\n\t}\n\n\treturn [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\nfunction linearise(channel: number): number {\n\tconst c = channel / 255;\n\n\treturn c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n}\n\n/**\n * The WCAG relative luminance of an sRGB colour, from 0 (black) to 1 (white).\n */\nexport function relativeLuminance([r, g, b]: Rgb): number {\n\treturn 0.2126 * linearise(r) + 0.7152 * linearise(g) + 0.0722 * linearise(b);\n}\n\n/**\n * The WCAG contrast ratio between two colours, from 1 to 21.\n */\nexport function contrastRatio(a: Rgb, b: Rgb): number {\n\tconst la = relativeLuminance(a);\n\tconst lb = relativeLuminance(b);\n\n\treturn (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n"],"mappings":";AAOO,SAAS,aACf,MACA,WACA,YACA,QACO;AACP,QAAM,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,KAAK,CAAC,CAAC;AACjD,QAAM,MAAM,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,KAAK,CAAC,CAAC;AAChD,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,YAAY,KAAK,IAAI,KAAK,KAAK,CAAC;AAC3E,QAAM,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,aAAa,KAAK,IAAI,KAAK,MAAM,CAAC;AAK9E,SAAO;AAAA,IACN,GAAG,KAAK,IAAI,GAAG,KAAK,IAAI,IAAI;AAAA,IAC5B,GAAG,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG;AAAA,IAC3B,OAAO,KAAK,QAAQ,OAAO;AAAA,IAC3B,QAAQ,KAAK,SAAS,MAAM;AAAA,EAC7B;AACD;;;ACvBA,IAAM,cAAc;AAMb,SAAS,eAAe,OAA2B;AACzD,QAAM,QAAQ,YAAY,KAAK,MAAM,KAAK,CAAC;AAE3C,MAAI,CAAC,OAAO;AACX,WAAO;AAAA,EACR;AAEA,MAAI,MAAM,CAAC,MAAM,UAAa,OAAO,MAAM,CAAC,CAAC,IAAI,GAAG;AACnD,WAAO;AAAA,EACR;AAEA,SAAO,CAAC,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,CAAC;AAC7D;AAEA,SAAS,UAAU,SAAyB;AAC3C,QAAM,IAAI,UAAU;AAEpB,SAAO,KAAK,UAAU,IAAI,UAAU,IAAI,SAAS,UAAU;AAC5D;AAKO,SAAS,kBAAkB,CAAC,GAAG,GAAG,CAAC,GAAgB;AACzD,SAAO,SAAS,UAAU,CAAC,IAAI,SAAS,UAAU,CAAC,IAAI,SAAS,UAAU,CAAC;AAC5E;AAKO,SAAS,cAAc,GAAQ,GAAgB;AACrD,QAAM,KAAK,kBAAkB,CAAC;AAC9B,QAAM,KAAK,kBAAkB,CAAC;AAE9B,UAAQ,KAAK,IAAI,IAAI,EAAE,IAAI,SAAS,KAAK,IAAI,IAAI,EAAE,IAAI;AACxD;","names":[]}
1
+ {"version":3,"sources":["../src/clip.ts","../src/contrast.ts","../src/element-screenshot.ts","../src/stashed-elements.ts"],"sourcesContent":["import type { Rect } from \"./adaptor\";\n\n/**\n * A screenshot clip framing `rect` with up to `buffer` pixels of padding on each side, shrunk where\n * the page edges leave less room. The padding allows for indicators drawn just outside the element\n * box (outlines, shadows) and for anti-aliasing.\n */\nexport function bufferedClip(\n\trect: Rect,\n\tpageWidth: number,\n\tpageHeight: number,\n\tbuffer: number,\n): Rect {\n\tconst left = Math.max(0, Math.min(buffer, rect.x));\n\tconst top = Math.max(0, Math.min(buffer, rect.y));\n\tconst right = Math.max(0, Math.min(buffer, pageWidth - rect.x - rect.width));\n\tconst bottom = Math.max(0, Math.min(buffer, pageHeight - rect.y - rect.height));\n\n\t// Clamp to non-negative origins: an element positioned partially off the top or left of the\n\t// document has a negative page-relative rect, and Puppeteer rejects a screenshot clip with\n\t// negative x/y.\n\treturn {\n\t\tx: Math.max(0, rect.x - left),\n\t\ty: Math.max(0, rect.y - top),\n\t\twidth: rect.width + left + right,\n\t\theight: rect.height + top + bottom,\n\t};\n}\n","export type Rgb = readonly [number, number, number];\n\n// Computed colours serialise as `rgb()` or `rgba()` with comma separators for sRGB values. Colours\n// authored in other spaces (oklch, display-p3) keep their own notation and are not parsed.\nconst RGB_PATTERN = /^rgba?\\(\\s*([\\d.]+),\\s*([\\d.]+),\\s*([\\d.]+)(?:,\\s*([\\d.]+))?\\s*\\)$/;\n\n/**\n * Parse a computed `rgb()` or `rgba()` colour, or return null when it is translucent or in another\n * notation.\n */\nexport function parseOpaqueRgb(value: string): Rgb | null {\n\tconst match = RGB_PATTERN.exec(value.trim());\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tif (match[4] !== undefined && Number(match[4]) < 1) {\n\t\treturn null;\n\t}\n\n\treturn [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\nfunction linearise(channel: number): number {\n\tconst c = channel / 255;\n\n\treturn c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n}\n\n/**\n * The WCAG relative luminance of an sRGB colour, from 0 (black) to 1 (white).\n */\nexport function relativeLuminance([r, g, b]: Rgb): number {\n\treturn 0.2126 * linearise(r) + 0.7152 * linearise(g) + 0.0722 * linearise(b);\n}\n\n/**\n * The WCAG contrast ratio between two colours, from 1 to 21.\n */\nexport function contrastRatio(a: Rgb, b: Rgb): number {\n\tconst la = relativeLuminance(a);\n\tconst lb = relativeLuminance(b);\n\n\treturn (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n","/**\n * IMPORTANT: The `*Script` functions in this file are serialized and injected into the audited page,\n * so they must not reference any symbols outside their own scope.\n */\n\nimport type { BrowserAdaptor, ElementRef, Rect } from \"./adaptor\";\nimport { bufferedClip } from \"./clip\";\n\nexport function pageDimensionsScript(): { width: number; height: number } {\n\treturn {\n\t\twidth: document.documentElement.scrollWidth,\n\t\theight: document.documentElement.scrollHeight,\n\t};\n}\n\nexport function elementRectScript(el: Element | null): Rect {\n\tif (!el) {\n\t\treturn { x: 0, y: 0, width: 0, height: 0 };\n\t}\n\n\tconst rect = el.getBoundingClientRect();\n\n\treturn {\n\t\tx: rect.left + window.scrollX,\n\t\ty: rect.top + window.scrollY,\n\t\twidth: rect.width,\n\t\theight: rect.height,\n\t};\n}\n\n/**\n * Whether the element should be centred in the viewport before its screenshots are taken: either\n * something unrelated covers its centre, or its screenshot clip (its box padded by `buffer`, cut\n * off at the document edges like bufferedClip) reaches past an edge of the viewport. A capture only\n * shows what is inside the viewport, so such a clip would lose an indicator drawn in the padding. A\n * clip larger than the viewport does not count, since scrolling cannot fit it anyway.\n */\nexport function needsCentringScript(el: Element | null, buffer: number): boolean {\n\tif (!el) {\n\t\treturn false;\n\t}\n\n\tconst rect = el.getBoundingClientRect();\n\t// In quirks mode the viewport's size is on <body>, and <html> measures the whole document.\n\tconst viewport = document.scrollingElement ?? document.documentElement;\n\tconst viewportWidth = viewport.clientWidth;\n\tconst viewportHeight = viewport.clientHeight;\n\n\tconst x = Math.min(Math.max(rect.left + rect.width / 2, 0), viewportWidth - 1);\n\tconst y = Math.min(Math.max(rect.top + rect.height / 2, 0), viewportHeight - 1);\n\n\tlet hit = document.elementFromPoint(x, y);\n\n\twhile (hit?.shadowRoot) {\n\t\tconst inner = hit.shadowRoot.elementFromPoint(x, y);\n\n\t\tif (!inner || inner === hit) {\n\t\t\tbreak;\n\t\t}\n\n\t\thit = inner;\n\t}\n\n\tif (hit && hit !== el && !el.contains(hit) && !hit.contains(el)) {\n\t\treturn true;\n\t}\n\n\tconst docLeft = -window.scrollX;\n\tconst docTop = -window.scrollY;\n\tconst left = Math.max(rect.left - buffer, docLeft);\n\tconst top = Math.max(rect.top - buffer, docTop);\n\tconst right = Math.min(rect.right + buffer, docLeft + document.documentElement.scrollWidth);\n\tconst bottom = Math.min(rect.bottom + buffer, docTop + document.documentElement.scrollHeight);\n\n\tif (right - left > viewportWidth || bottom - top > viewportHeight) {\n\t\treturn false;\n\t}\n\n\treturn left < 0 || top < 0 || right > viewportWidth || bottom > viewportHeight;\n}\n\n/**\n * Scroll the window so the element sits at the vertical centre of the viewport and is inside it\n * horizontally with `buffer` to spare, instantly so a screenshot taken immediately afterwards isn't\n * captured mid-animation. Scrolls the window directly rather than via scrollIntoView(): Chromium\n * moves the sequential focus navigation starting point to the element passed to scrollIntoView(),\n * so when focus cannot be handed back afterwards (a closed shadow host) the next Tab would re-enter\n * the same element instead of moving on.\n */\nexport function scrollToCenterScript(el: Element | null, buffer = 0): void {\n\tif (!el) {\n\t\treturn;\n\t}\n\n\tconst rect = el.getBoundingClientRect();\n\t// In quirks mode the viewport's size is on <body>, and <html> measures the whole document.\n\tconst viewport = document.scrollingElement ?? document.documentElement;\n\tconst viewportWidth = viewport.clientWidth;\n\tconst top = rect.top + rect.height / 2 - viewport.clientHeight / 2;\n\tlet left = 0;\n\n\tif (rect.left - buffer < 0) {\n\t\tleft = rect.left - buffer;\n\t} else if (rect.right + buffer > viewportWidth) {\n\t\tleft = Math.min(rect.right + buffer - viewportWidth, rect.left - buffer);\n\t}\n\n\twindow.scrollBy({ top, left, behavior: \"instant\" });\n}\n\nexport type ElementScreenshotOptions = {\n\t/** Padding around the element's box. */\n\tclipBuffer: number;\n\t/** How long to wait (ms) after scrolling for the page to settle. */\n\tsettleDelay: number;\n};\n\n/**\n * Screenshot the element `handle` refers to, clipped to its box plus `clipBuffer` padding, first\n * centring it in the viewport when its clip would not fit or something covers it. The caller owns\n * `handle`.\n */\nexport async function captureElementScreenshot(\n\tadaptor: Pick<BrowserAdaptor, \"evaluate\" | \"screenshotClip\" | \"screenshotClipScale\">,\n\thandle: ElementRef,\n\toptions: ElementScreenshotOptions,\n): Promise<Uint8Array> {\n\tif (await adaptor.evaluate(needsCentringScript, handle, options.clipBuffer)) {\n\t\tawait adaptor.evaluate(scrollToCenterScript, handle, options.clipBuffer);\n\t\tawait new Promise((resolve) => setTimeout(resolve, options.settleDelay));\n\t}\n\n\tconst { width: pageWidth, height: pageHeight } = await adaptor.evaluate(pageDimensionsScript);\n\tconst rect = await adaptor.evaluate(elementRectScript, handle);\n\tconst clip = bufferedClip(rect, pageWidth, pageHeight, options.clipBuffer);\n\n\treturn adaptor.screenshotClip(clip, adaptor.screenshotClipScale ?? 1);\n}\n","import type { BrowserAdaptor, ElementRef } from \"./adaptor\";\nimport { getSelector } from \"./get-selector\";\n\ntype PickWindow = Window & { __a11yPulsePickedElement?: Element | null };\n\nfunction pickStashedScript(stashKey: string, index: number): void {\n\tconst stash = (window as unknown as Record<string, unknown>)[stashKey];\n\n\t(window as PickWindow).__a11yPulsePickedElement = Array.isArray(stash)\n\t\t? (stash[index] ?? null)\n\t\t: null;\n}\n\nfunction pickedElementScript(): Element | null {\n\treturn (window as PickWindow).__a11yPulsePickedElement ?? null;\n}\n\nfunction releaseStashScript(stashKey: string): void {\n\tdelete (window as unknown as Record<string, unknown>)[stashKey];\n\tdelete (window as PickWindow).__a11yPulsePickedElement;\n}\n\n/**\n * Return a handle to the element at `index` of the array a page script left on `window[stashKey]`.\n * The caller owns the handle.\n */\nexport async function stashedElementHandle(\n\tadaptor: BrowserAdaptor,\n\tstashKey: string,\n\tindex: number,\n): Promise<ElementRef> {\n\tawait adaptor.evaluate(pickStashedScript, stashKey, index);\n\n\treturn adaptor.evaluateHandle(pickedElementScript);\n}\n\n/**\n * Return a selector (see getSelector) for each element at `indices` of the array a page script\n * left on `window[stashKey]`.\n */\nexport async function stashedElementSelectors(\n\tadaptor: BrowserAdaptor,\n\tstashKey: string,\n\tindices: readonly number[],\n): Promise<string[]> {\n\tconst selectors: string[] = [];\n\n\tfor (const index of indices) {\n\t\tconst handle = await stashedElementHandle(adaptor, stashKey, index);\n\n\t\ttry {\n\t\t\tselectors.push(await adaptor.evaluate(getSelector, handle));\n\t\t} finally {\n\t\t\tawait adaptor.disposeRef(handle);\n\t\t}\n\t}\n\n\treturn selectors;\n}\n\n/**\n * Remove the array on `window[stashKey]` from the page.\n */\nexport async function releaseStashedElements(\n\tadaptor: BrowserAd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+ /**
3
+ * Return a handle to the element at `index` of the array a page script left on `window[stashKey]`.
4
+ * The caller owns the handle.
5
+ */
6
+ export declare function stashedElementHandle(adaptor: BrowserAdaptor, stashKey: string, index: number): Promise<ElementRef>;
7
+ /**
8
+ * Return a selector (see getSelector) for each element at `indices` of the array a page script
9
+ * left on `window[stashKey]`.
10
+ */
11
+ export declare function stashedElementSelectors(adaptor: BrowserAdaptor, stashKey: string, indices: readonly number[]): Promise<string[]>;
12
+ /**
13
+ * Remove the array on `window[stashKey]` from the page.
14
+ */
15
+ export declare function releaseStashedElements(adaptor: BrowserAdaptor, stashKey: string): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a11y-pulse/browser-adaptor",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Shared browser adaptor primitives and DOM helpers for A11y Pulse accessibility audits.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -77,7 +77,7 @@
77
77
  }
78
78
  },
79
79
  "devDependencies": {
80
- "happy-dom": "^21.0.1",
80
+ "happy-dom": "^21.0.3",
81
81
  "playwright-core": "^1.64.1",
82
82
  "puppeteer": "^25.14.0"
83
83
  }