diff --git a/.oxfmtrc.json b/.oxfmtrc.json index fb55ac86..45e46aa3 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -13,6 +13,7 @@ "packages/devtools-frontend/src/**", "packages/devtools-frontend/patches/**", "experiments/**", - "packages/devtools-anywhere/src/cdp-agent/domains/css/user-agent/html.css" + "packages/devtools-anywhere/src/cdp-agent/domains/css/user-agent/html.css", + "packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/**" ] } diff --git a/CHANGELOG.md b/CHANGELOG.md index 300c0919..55090173 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,20 @@ All packages share one version and are released together (see DEV.md, "Releasing to npm"). Each release says first which Chrome its DevTools frontend comes from; the versioning rules are in DEV.md too. Changes are listed under `Unreleased` as they land, and moved under the version when it is released. The Chinese version is [CHANGELOG.zh-CN.md](CHANGELOG.zh-CN.md); the two say the same. -## Unreleased +## 0.5.0 + +Based on Chrome 159 (159.0.8154.13). + +- The DevTools frontend now comes from Chrome 159 (it was Chrome 158), with that version's panels and UI; the browser default styles shown in Styles follow Chrome 159 too. +- The accessibility tree is computed by the project's own code instead of dom-accessibility-api, and follows Chrome much more closely. `accessibility.js` grows from about 29 KB to about 80 KB. + - Roles, names, descriptions, values and properties follow Chrome's rules: all of the about 1,800 cases imported from dom-accessibility-api's tests and from web-platform-tests match Chrome, layout tables, image map areas and CSS counters in generated content included. + - The tree has the nodes Chrome has without a DOM node the page can see: a select's popup and options, a text field's placeholder and inner editor, an input button's text, a color well's swatch, and list markers with their text, in every predefined counter style and in `@counter-style` rules read from the page. A list marker has the backend id of its `::marker`, and `::before` and `::after` those of their pseudo-elements; the other such nodes get ids below 0, which `getChildAXNodes` takes. + - The tree's shape follows Chrome: generic containers, hidden subtrees, white space text, the body, shadow trees and slots, aria-owns, svg and generated content are kept, ignored or left out as Chrome does, and `getFullAXTree` lists the nodes in Chrome's order. The whole-tree comparison with Chrome differs on 29 of 223 groups; what is left, such as localized names and media controls, is listed in the limitations. +- The Accessibility pane refreshes by itself when the page changes: `Accessibility.nodesUpdated` is sent as in Chrome, while the domain is enabled, for the nodes the client was given by `getChildAXNodes` or `getAXNodeAndAncestors`, those changed in one frame in one event. Changes are seen through a mutation observer; style changes it cannot see (the CSSOM, `:hover`, media queries) are sent with the next DOM change (see the limitations). `loadComplete` is not sent, as the agent starts in a loaded page. +- `devtools-anywhere` has no runtime dependencies any more: snapDOM was already built into `dist/snapdom.js` and is now a development dependency, and dom-accessibility-api is gone. +- Frames report the security origin Chrome 159 gives them, in the frame tree and the frame events: a frame on `about:blank` or `srcdoc` has the origin it inherits from the document that created it, and a sandboxed frame without `allow-same-origin` has an opaque origin. +- A Content Security Policy issue raised without a source file, such as by markup a script inserted, no longer points at the document's URL at line -1: it has no source location, as in Chrome. +- A deprecation issue still points at the page's URL, where Chrome 159 points at the script that called the deprecated API: the page is not told where the call was made (see the limitations). ## 0.4.0 @@ -41,7 +54,7 @@ Based on Chrome 158 (158.0.8127.37). Public API, as in `packages/*/etc/*.public.api.md`: unchanged since 0.3.0. - `devtools-anywhere` ships two more files in `dist/`, loaded on first use: `accessibility.js` (exported as `./accessibility.js`, with its source map `accessibility.js.map`) and `chromium-html.css`; self-hosted, serve them with the bundle. `chromium-html.css` is under the LGPL (2.0 or later), the package's only file that is not MIT or BSD; its license ships as `chromium-html.LICENSE.txt`, and leaving both out only drops the user agent stylesheet rules. It depends on `dom-accessibility-api` now. -- The probe grows from 18948 to 27489 bytes minified (raw bytes, not gzip; 25409 before the functions the agent calls on the page were saved with it), mostly for the Animations panel's hooks, the `matchMedia()` hooks, the browser functions saved for them and for the vision deficiency mask, and the functions the agent calls (an internal interface of the probe, not public API). +- The probe grows from 18948 to 27643 bytes minified (raw bytes, not gzip; 25409 before the functions the agent calls on the page were saved with it), mostly for the Animations panel's hooks, the `matchMedia()` hooks, the browser functions saved for them and for the vision deficiency mask, and the functions the agent and the accessibility tree call (an internal interface of the probe, not public API). - In shell mode the Service Worker keeps its `debugger` rewrite record in the Cache API, under `devtools-anywhere-service-worker-rewrites`; it is deleted when a new worker activates, when shell mode ends, and when a page outside shell mode unregisters a left-over shell worker. - The messages between the probe in a cross-origin iframe and its parent gained the internal event `DevtoolsAnywhere.scrollParent`: use the same version of the probe on both sides. diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 70c73d17..aca077a0 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -2,7 +2,20 @@ 所有包使用同一个版本号,一起发布(见 DEV.zh-CN.md 的「发布到 npm」)。每个版本开头先写明它的 DevTools 前端来自哪个版本的 Chrome;版本规则也在 DEV.zh-CN.md 里。改动合入时记在 `Unreleased` 下,发布时挪到对应的版本号下。英文版见 [CHANGELOG.md](CHANGELOG.md),两份内容保持一致。 -## Unreleased +## 0.5.0 + +基于 Chrome 159(159.0.8154.13)。 + +- DevTools 前端改为来自 Chrome 159(原为 Chrome 158),面板和界面随之更新;Styles 里显示的浏览器默认样式也改为 Chrome 159 的。 +- 无障碍树改由项目自己的代码计算,不再使用 dom-accessibility-api,与 Chrome 的一致程度大幅提高。`accessibility.js` 从约 29 KB 增至约 80 KB。 + - 角色、名称、描述、value 和 properties 按 Chrome 的规则计算:从 dom-accessibility-api 的测试和 web-platform-tests 导入的约 1800 条用例全部与 Chrome 一致,包括布局表格、图像热区和生成内容里的 CSS 计数器。 + - 无障碍树补上了 Chrome 有、而页面看不到 DOM 节点的那些节点:select 的弹出层和选项、文本框的占位符和内部编辑区、input 按钮的文字、取色框的色块,以及列表标记和其文字(所有预定义计数样式,以及从页面读取的 `@counter-style` 规则)。列表标记用其 `::marker` 的 backend id,`::before` 和 `::after` 用其伪元素的 backend id;其余这类节点的 id 为负数,`getChildAXNodes` 接受这些 id。 + - 树的形状与 Chrome 一致:generic 容器、隐藏子树、空白文本、body、shadow 树和 slot、aria-owns、svg 和生成内容,都按 Chrome 的方式保留、忽略或略去,`getFullAXTree` 按 Chrome 的顺序列出节点。与 Chrome 的整棵树对照中,223 组里有 29 组不一致;剩下的(如本地化名称和媒体控件)列在限制文档里。 +- 页面变化时 Accessibility 窗格会自己刷新:与 Chrome 一样,在域启用期间,对客户端经 `getChildAXNodes` 或 `getAXNodeAndAncestors` 拿到过的节点发 `Accessibility.nodesUpdated`,同一帧里变化的合成一个事件。变化由 MutationObserver 得知;它看不到的样式变化(CSSOM、`:hover`、媒体查询)在下一次 DOM 变化时发出(见能力边界)。不发 `loadComplete`,因为 agent 在已加载的页面里启动。 +- `devtools-anywhere` 不再有运行时依赖:snapDOM 本来就已打进 `dist/snapdom.js`,改为开发依赖;dom-accessibility-api 已去掉。 +- frame 的安全源(security origin)与 Chrome 159 一致,见于 frame 树和 frame 事件:`about:blank` 或 `srcdoc` 的 frame 继承创建它的文档的源,没有 `allow-same-origin` 的沙箱 frame 是不透明源。 +- 没有源文件的内容安全策略(CSP)问题(例如脚本插入的标记引发的)不再指向文档 URL 的第 -1 行,而是与 Chrome 一样不带源码位置。 +- 弃用问题仍指向页面 URL,而 Chrome 159 指向调用该弃用 API 的脚本:页面无从得知调用发生在哪里(见限制说明)。 ## 0.4.0 @@ -41,7 +54,7 @@ 公开 API(以 `packages/*/etc/*.public.api.md` 为准)与 0.3.0 相比没有变化。 - `devtools-anywhere` 的 `dist/` 新增两个首次使用时才加载的文件:`accessibility.js`(导出为 `./accessibility.js`,附带 source map `accessibility.js.map`)和 `chromium-html.css`;自托管时和 bundle 放在一起。`chromium-html.css` 采用 LGPL(2.0 或更高版本),是包里唯一不属于 MIT 或 BSD 的文件;许可全文随附为 `chromium-html.LICENSE.txt`,两个文件都删掉只会少掉 user agent stylesheet 规则。新增依赖 `dom-accessibility-api`。 -- 探针 minify 后从 18948 字节增到 27489 字节(原始字节,不是 gzip;保存 agent 调用的页面函数之前为 25409 字节),主要是 Animations 面板用的挂钩、`matchMedia()` 的挂钩,为其和色觉缺陷遮罩保存的浏览器原生函数,以及 agent 调用的函数(属于探针的内部接口,不是公开 API)。 +- 探针 minify 后从 18948 字节增到 27643 字节(原始字节,不是 gzip;保存 agent 调用的页面函数之前为 25409 字节),主要是 Animations 面板用的挂钩、`matchMedia()` 的挂钩,为其和色觉缺陷遮罩保存的浏览器原生函数,以及 agent 和无障碍树调用的函数(属于探针的内部接口,不是公开 API)。 - 壳模式下 Service Worker 把 `debugger` 改写记录存在 Cache API 的 `devtools-anywhere-service-worker-rewrites` 里;新 worker 激活时、退出壳模式时,以及不在壳模式的页面注销遗留的壳 worker 时删除。 - 跨域 iframe 里的探针和父页面之间的消息新增内部事件 `DevtoolsAnywhere.scrollParent`:两边请使用同一版本的探针。 diff --git a/DEV.md b/DEV.md index ba27d1e1..d15af1cd 100644 --- a/DEV.md +++ b/DEV.md @@ -32,7 +32,7 @@ Tests that need the DevTools frontend are skipped until it is built (next step). ### Build the DevTools frontend (once) -The frontend is built from the official [devtools-frontend](https://github.com/ChromeDevTools/devtools-frontend) sources with Chromium's tooling. It needs about 3 GB of disk (2 GB checkout without history, 0.3 GB build output, 0.8 GB depot_tools) and a fast connection the first time. +The frontend is built from the official [devtools-frontend](https://github.com/ChromeDevTools/devtools-frontend) sources with Chromium's tooling. It needs about 4 GB of disk (2 GB checkout without history, 1.1 GB emscripten toolchain that upstream's DEPS fetches and the build does not use, 0.3 GB build output, 0.8 GB depot_tools) and a fast connection the first time. ```bash # depot_tools: Chromium's gclient/gn/autoninja (directories ending in .ignore are git-ignored); diff --git a/DEV.zh-CN.md b/DEV.zh-CN.md index c1878810..8cf4a772 100644 --- a/DEV.zh-CN.md +++ b/DEV.zh-CN.md @@ -32,7 +32,7 @@ pnpm test # 构建所有包,然后在真实 Chrome 上跑全部测试 ### 构建 DevTools 前端(只需一次) -前端用 Chromium 的工具链从官方 [devtools-frontend](https://github.com/ChromeDevTools/devtools-frontend) 源码构建。大约需要 3 GB 磁盘(不带历史的源码检出 2 GB,构建输出 0.3 GB,depot_tools 0.8 GB),第一次需要较快的网络。 +前端用 Chromium 的工具链从官方 [devtools-frontend](https://github.com/ChromeDevTools/devtools-frontend) 源码构建。大约需要 4 GB 磁盘(不带历史的源码检出 2 GB,上游 DEPS 拉取而构建用不到的 emscripten 工具链 1.1 GB,构建输出 0.3 GB,depot_tools 0.8 GB),第一次需要较快的网络。 ```bash # depot_tools:Chromium 的 gclient/gn/autoninja(以 .ignore 结尾的目录不会进 git); diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index 98053a11..b2b02ca9 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -10,18 +10,17 @@ devtools-anywhere itself is licensed under the MIT license (see [LICENSE](LICENS | --- | --- | --- | --- | --- | | [es-module-lexer (ported code)](https://github.com/guybedford/es-module-lexer) | 3.0.4 | MIT | Guy Bedford | devtools-anywhere | | [snapDOM (@zumer/snapdom)](https://github.com/zumerlab/snapdom) | 3.3.5 | MIT | ZumerLab | devtools-anywhere | -| [dom-accessibility-api](https://github.com/eps1lon/dom-accessibility-api) | 0.7.1 | MIT | Sebastian Silbermann | devtools-anywhere | -| [Chromium's default style sheet (html.css)](https://chromium.googlesource.com/chromium/src/+/refs/tags/158.0.8127.37/third_party/blink/renderer/core/html/resources/html.css) | Chrome 158.0.8127.37 | LGPL-2.0-or-later | Lars Knoll; Apple Inc. | devtools-anywhere | -| [Chrome DevTools frontend](https://chromium.googlesource.com/devtools/devtools-frontend) | 047c90eca37c7170d826d72245d5df9281989cf3 | BSD-3-Clause | The Chromium Authors | devtools-frontend, devtools-frontend-locales | +| [Chromium's default style sheet (html.css)](https://chromium.googlesource.com/chromium/src/+/refs/tags/159.0.8154.13/third_party/blink/renderer/core/html/resources/html.css) | Chrome 159.0.8154.13 | LGPL-2.0-or-later | Lars Knoll; Apple Inc. | devtools-anywhere | +| [Chrome DevTools frontend](https://chromium.googlesource.com/devtools/devtools-frontend) | 3d48567555b6795967c376050698efe2bf4f0f98 | BSD-3-Clause | The Chromium Authors | devtools-frontend, devtools-frontend-locales | | [acorn (DevTools front_end/third_party/acorn)](https://github.com/acornjs/acorn) | 8.10.0 | MIT | acorn contributors (see its AUTHORS) | devtools-frontend | -| [chromium (DevTools front_end/third_party/chromium)](https://chromium.googlesource.com/devtools/devtools-frontend/+/047c90eca37c7170d826d72245d5df9281989cf3/front_end/third_party/chromium/) | N/A | BSD-3-Clause | The Chromium Authors | devtools-frontend | +| [chromium (DevTools front_end/third_party/chromium)](https://chromium.googlesource.com/devtools/devtools-frontend/+/3d48567555b6795967c376050698efe2bf4f0f98/front_end/third_party/chromium/) | N/A | BSD-3-Clause | The Chromium Authors | devtools-frontend | | [codemirror.next (DevTools front_end/third_party/codemirror.next)](https://github.com/codemirror/CodeMirror.next/) | 0.19.0 | MIT | Marijn Haverbeke and others | devtools-frontend | | [csp_evaluator (DevTools front_end/third_party/csp_evaluator)](https://www.npmjs.com/package/csp_evaluator) | 1.1.1 | Apache-2.0 | not stated in the license text | devtools-frontend | | [diff (DevTools front_end/third_party/diff)](https://github.com/google/diff-match-patch/tree/master/javascript) | 5.60.0 | Apache-2.0 | Google Inc. (diff-match-patch) | devtools-frontend | | [i18n (DevTools front_end/third_party/i18n)](https://github.com/GoogleChrome/lighthouse) | 15dad3944c2754a9e147fef9ef99934169e2ca08 | Apache-2.0 | Google LLC (Lighthouse) | devtools-frontend | | [intl-messageformat (DevTools front_end/third_party/intl-messageformat)](https://github.com/formatjs/formatjs) | 9.8.0 | BSD-3-Clause | Oath Inc. (includes tslib, 0BSD, Microsoft Corporation) | devtools-frontend | | [json5 (DevTools front_end/third_party/json5)](https://github.com/json5/json5) | 2.2.3 | MIT | Aseem Kishore and others | devtools-frontend | -| [legacy-javascript (DevTools front_end/third_party/legacy-javascript)](https://github.com/GoogleChrome/lighthouse/tree/main/core/lib/legacy-javascript) | 0.0.3 | Apache-2.0 | Google LLC (Lighthouse) | devtools-frontend | +| [legacy-javascript (DevTools front_end/third_party/legacy-javascript)](https://github.com/GoogleChrome/lighthouse/tree/main/core/lib/legacy-javascript) | 0.0.4 | Apache-2.0 | Google LLC (Lighthouse) | devtools-frontend | | [lit (DevTools front_end/third_party/lit)](https://github.com/lit/lit) | 2.4.1 | BSD-3-Clause | Google LLC | devtools-frontend | | [marked (DevTools front_end/third_party/marked)](https://github.com/markedjs/marked) | 18.0.4 | BSD-3-Clause, MIT | Christopher Jeffrey / MarkedJS | devtools-frontend | | [source-map-scopes-codec (DevTools front_end/third_party/source-map-scopes-codec)](https://github.com/ChromeDevTools/source-map-scopes-codec) | 2.0.0 | BSD-3-Clause | The Chromium Authors | devtools-frontend | @@ -104,45 +103,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -### dom-accessibility-api - -- Version: 0.7.1 -- License: MIT -- Copyright: Sebastian Silbermann -- Source: https://github.com/eps1lon/dom-accessibility-api -- Included in: devtools-anywhere -- Notes: Bundled as dist/accessibility.js, loaded on demand for the Accessibility domain. - -```text -MIT License - -Copyright (c) 2020 Sebastian Silbermann - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -``` - ### Chromium's default style sheet (html.css) -- Version: Chrome 158.0.8127.37 +- Version: Chrome 159.0.8154.13 - License: LGPL-2.0-or-later - Copyright: Lars Knoll; Apple Inc. -- Source: https://chromium.googlesource.com/chromium/src/+/refs/tags/158.0.8127.37/third_party/blink/renderer/core/html/resources/html.css +- Source: https://chromium.googlesource.com/chromium/src/+/refs/tags/159.0.8154.13/third_party/blink/renderer/core/html/resources/html.css - Included in: devtools-anywhere - Notes: Shipped unmodified as dist/chromium-html.css, with this license as dist/chromium-html.LICENSE.txt; loaded on demand for the Styles pane. It is the only file under this license: deleting both leaves out the user agent stylesheet rules and nothing else. @@ -631,7 +597,7 @@ That's all there is to it! ### Chrome DevTools frontend -- Version: 047c90eca37c7170d826d72245d5df9281989cf3 +- Version: 3d48567555b6795967c376050698efe2bf4f0f98 - License: BSD-3-Clause - Copyright: The Chromium Authors - Source: https://chromium.googlesource.com/devtools/devtools-frontend @@ -706,7 +672,7 @@ THE SOFTWARE. - Version: N/A - License: BSD-3-Clause - Copyright: The Chromium Authors -- Source: https://chromium.googlesource.com/devtools/devtools-frontend/+/047c90eca37c7170d826d72245d5df9281989cf3/front_end/third_party/chromium/ +- Source: https://chromium.googlesource.com/devtools/devtools-frontend/+/3d48567555b6795967c376050698efe2bf4f0f98/front_end/third_party/chromium/ - Included in: devtools-frontend - Notes: Bundled into dist/bundle/ (from third_party/chromium/). @@ -1497,7 +1463,7 @@ SOFTWARE. ### legacy-javascript (DevTools front_end/third_party/legacy-javascript) -- Version: 0.0.3 +- Version: 0.0.4 - License: Apache-2.0 - Copyright: Google LLC (Lighthouse) - Source: https://github.com/GoogleChrome/lighthouse/tree/main/core/lib/legacy-javascript diff --git a/docs/limitations.md b/docs/limitations.md index 1b8f3517..58709c8a 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -427,11 +427,12 @@ Not merged (off, or no probe in it): ## Accessibility tree -The Elements panel's Accessibility pane and `Accessibility.getPartialAXTree`, `getFullAXTree`, `queryAXTree`, `getRootAXNode`, `getChildAXNodes`, `getAXNodeAndAncestors` are computed in the page from the DOM, ARIA attributes and computed styles, compared with Chrome's. Computed by `accessibility.js` (about 29 KB), loaded on first use from next to the bundle: self-hosted, serve it in the same directory. +The Elements panel's Accessibility pane and `Accessibility.getPartialAXTree`, `getFullAXTree`, `queryAXTree`, `getRootAXNode`, `getChildAXNodes`, `getAXNodeAndAncestors` are computed in the page from the DOM, ARIA attributes and computed styles, compared with Chrome's. Computed by `accessibility.js` (about 80 KB), loaded on first use from next to the bundle: self-hosted, serve it in the same directory. - **Chrome**: computes the tree in the browser, with inline text boxes, list markers and nodes of user-agent shadow trees. -- **devtools-anywhere**: no inline text boxes, list markers or nodes of user-agent shadow trees; the default names of inputs (such as "Submit") are in English. -- **Events**: no `loadComplete` or `nodesUpdated` events (to be done: see the [roadmap](roadmap.md#more-that-can-be-filled-in-the-page)). +- **devtools-anywhere**: no inline text boxes. The nodes of user-agent shadow trees (a select's popup and slots, a text field's placeholder and inner editor, an input button's text, a meter's bar (its two generic wrappers and the value inside), a color well's swatch, a details element's slots) and list markers with their text are rebuilt without a DOM node: they have no `backendDOMNodeId` and get ids below 0, kept for the session, except a list marker, which has the backend id of its `::marker` as in Chrome. The default names of inputs (such as "Submit", an image input's too) are in English, where Chrome's are in the browser's language. MathML is not rebuilt node by node: a `math` element's content shows as generic nodes and its own text, where Chrome has MathML roles such as MathMLIdentifier and the text as rendered (an italic identifier "x" as "𝑥"). A meter with role none or presentation has no nodes, where Chrome keeps the generic wrappers of its bar. A details without a summary gets no default summary, as Chrome's has the browser's localized "Details" as its text, which the page cannot know. A video or audio has neither the name Chrome gives it while it cannot play (the browser's localized "Media can't be played.") nor the ignored nodes of its media controls' shadow tree, which change with the browser version and the media's state. A body is kept in the tree, as in Chrome, when it has a click, mousedown or mouseup handler, but only one set through an `on*` property or attribute: listeners added with `addEventListener` cannot be seen from the page, so such a body stays ignored where Chrome keeps it. +- **Left as they are**: the date, time, month and week inputs have no inner nodes, where Chrome has spin buttons named in the browser's language ("Year", "Month", …) and a picker button; a file input has no inner button either. Where `role="none"` or `"presentation"` conflicts with focus or with a parent that requires owned elements, the tree can differ from Chrome's: the specification leaves these cases open and Chrome's result has to be measured case by case. When several elements own one element with `aria-owns`, the first in document order wins; Chrome resolves this in the order it creates its accessibility objects, which can differ on a page that inserts nodes. These are compared with Chrome as whole trees and left where they differ. +- **Events**: `nodesUpdated` is sent as in Chrome, while the domain is enabled, for the nodes the client was given by `getChildAXNodes` or `getAXNodeAndAncestors` whose node changed, those of one frame in one event. A mutation observer sees the changes to the DOM, its attributes and text: a style change from a class or a `style` attribute is seen, but one through the CSSOM, `:hover` and other states, media queries, animations or an image loading is sent with the next DOM change only (the commands always read the current tree). Chrome also sends a changed node's parent whose node is the same; this sends only the nodes that differ. `loadComplete` is not sent: it comes when a document finishes loading, before the agent runs, and not on enable. @@ -449,6 +450,7 @@ The Elements panel's Accessibility pane and `Accessibility.getPartialAXTree`, `g ### Issues panel - **devtools-anywhere**: CSP violations, deprecations, quirks mode and form issues. CSP and deprecations of the top document only; no interventions. +- **Where a deprecated API was called**: the page's URL, where Chrome points at the calling script, line and column. Why: the report a page's `ReportingObserver` gets leaves the source file, line and column empty (null in Chrome 159), and it arrives after the call, so the observer's stack does not show the caller either. - **Low contrast**: none; Chrome has no such check either. - **Cookies, CORS and mixed content**: none. Why: they are the browser's. diff --git a/docs/limitations.zh-CN.md b/docs/limitations.zh-CN.md index 93cf182e..7a3b0388 100644 --- a/docs/limitations.zh-CN.md +++ b/docs/limitations.zh-CN.md @@ -427,11 +427,12 @@ devtools-anywhere 做不到的事,以及有意与 Chrome 不同的行为。接 ## 无障碍树 -Elements 面板的 Accessibility 窗格,以及 `Accessibility.getPartialAXTree`、`getFullAXTree`、`queryAXTree`、`getRootAXNode`、`getChildAXNodes`、`getAXNodeAndAncestors`:在页面里由 DOM、ARIA 属性和计算样式算出,与 Chrome 对照过。由 `accessibility.js`(约 29 KB)计算,首次使用时从 bundle 旁边加载:自托管时要放在同一目录。 +Elements 面板的 Accessibility 窗格,以及 `Accessibility.getPartialAXTree`、`getFullAXTree`、`queryAXTree`、`getRootAXNode`、`getChildAXNodes`、`getAXNodeAndAncestors`:在页面里由 DOM、ARIA 属性和计算样式算出,与 Chrome 对照过。由 `accessibility.js`(约 80 KB)计算,首次使用时从 bundle 旁边加载:自托管时要放在同一目录。 - **Chrome**:在浏览器里计算,含 InlineTextBox、列表标记和 UA shadow 树里的节点。 -- **devtools-anywhere**:没有 InlineTextBox、列表标记和 UA shadow 树里的节点;input 的默认名称(如 "Submit")是英文。 -- **事件**:不发 `loadComplete`、`nodesUpdated` 事件(待做:见[路线图](roadmap.zh-CN.md#其他能在页面里补上的功能))。 +- **devtools-anywhere**:没有 InlineTextBox。UA shadow 树里的节点(select 的弹出层和 slot、文本框的占位符和内部编辑区、input 按钮的文字、meter 的数值条(两层 generic 包装及其中的数值部分)、取色框的色块、details 的 slot)和列表标记及其文字,在没有 DOM 节点的情况下重建:它们没有 `backendDOMNodeId`,id 为负数,在会话内保持不变;列表标记例外,与 Chrome 一样用其 `::marker` 的 backend id。input 的默认名称(如 "Submit",image input 的也是)是英文,Chrome 的则用浏览器语言。MathML 不逐节点重建:`math` 元素的内容显示为 generic 节点和其原文,Chrome 则给出 MathMLIdentifier 等 MathML 角色和渲染后的文字(斜体标识符 "x" 为 "𝑥")。role 为 none 或 presentation 的 meter 没有节点,Chrome 则保留其数值条的 generic 包装。没有 summary 的 details 不生成 Chrome 的默认 summary:它的文字是浏览器语言的「详细信息」,页面拿不到。video 和 audio 没有 Chrome 在媒体无法播放时给的名称(浏览器语言的「无法播放媒体。」),也没有其媒体控件 shadow 树里那些被忽略的节点:它们随浏览器版本和媒体状态而变。body 与 Chrome 一样在有 click、mousedown 或 mouseup 处理函数时保留在树里,但只认经 `on*` 属性或特性设置的:用 `addEventListener` 添加的监听器页面里看不到,这样的 body 在 Chrome 保留时这里仍被忽略。 +- **暂不处理**:日期、时间、月份、星期类输入框没有内部节点,Chrome 则有以浏览器语言命名的 spinbutton(「年」「月」……)和选择器按钮;file 输入框也没有内部按钮。`role="none"` 或 `"presentation"` 与焦点、或与要求特定子元素的父元素冲突时,树可能与 Chrome 不同:规范对这些情形没有定论,Chrome 的结果只能逐个实测。多个元素用 `aria-owns` 拥有同一元素时,按文档顺序第一个生效;Chrome 按创建无障碍对象的顺序决定,动态插入节点的页面上可能不同。这些已与 Chrome 做整棵树对照,不一致处保留现状。 +- **事件**:与 Chrome 一样,在域启用期间,对客户端经 `getChildAXNodes` 或 `getAXNodeAndAncestors` 拿到过、节点又变了的发 `nodesUpdated`,同一帧的合成一个事件。变化由 MutationObserver 观察 DOM、属性和文本得知:class 或 `style` 属性引起的样式变化能看到;经 CSSOM 的修改、`:hover` 等状态、媒体查询、动画或图片加载引起的,要等下一次 DOM 变化才发出(命令总是读当前的树)。Chrome 还会发出变化节点的父节点,即使其节点没变;这里只发确实不同的节点。不发 `loadComplete`:它在文档加载完成时发出,早于 agent 运行,enable 时也不发。 @@ -449,6 +450,7 @@ Elements 面板的 Accessibility 窗格,以及 `Accessibility.getPartialAXTree ### 问题面板 - **devtools-anywhere**:CSP 违规、弃用、怪异模式和表单问题。CSP 和弃用只有顶层文档的;没有干预。 +- **弃用 API 的调用位置**:给的是页面 URL,Chrome 指向调用它的脚本及行列。原因:页面的 `ReportingObserver` 收到的报告里源文件、行、列都是空的(Chrome 159 中为 null),且报告在调用之后才到,观察者回调的调用栈也看不到调用方。 - **低对比度**:没有;Chrome 也已没有这项检查。 - **Cookie、CORS、混合内容**:没有。原因:只有浏览器知道。 diff --git a/docs/roadmap.md b/docs/roadmap.md index 9607da9f..49daddf0 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -27,7 +27,6 @@ All with standard page APIs, matching Chrome. |---|---|---| | Shell mode: blocked URLs, extra headers and offline for images and scripts | Blocked URLs, extra headers, cache disabled and offline apply to the fetch and XHR the probe intercepts only; the document's own request and other subresources are not affected | In shell mode with the Service Worker, apply them to the same-origin requests it handles (images, scripts, style sheets, …) | | Remaining gaps of the persistent overlays | Grid, flex, container query, scroll-snap and isolation overlays are drawn approximately: no grid line labels or area names, no offsets of aligned grids, no right-to-left layouts; flex shows no distribution of free space or gaps; container queries do not mark the queried descendants; no persistent overlay in merged sandboxed iframes | Drawn on the same layer from the computed styles and boxes | -| Accessibility events | `Accessibility.loadComplete` and `nodesUpdated` are not sent: the tree is computed per command, so the pane does not refresh by itself | A `MutationObserver` on the documents, sending the nodes whose properties changed | | `::backdrop` pseudo-elements | The DOM shows no `::backdrop` node under a modal dialog, an open popover or a fullscreen element, and an animation of one names its host element; Chrome shows the pseudo-element (`DOM.pseudoElementAdded`, in the host's `pseudoElements`) and names it | Add `backdrop` to the pseudo-element nodes, present while the host is in the top layer (`:modal`, `:popover-open`, `:fullscreen`). Hard parts: the type list is shared with CSS (matched styles, cascade, computed updates, user agent rules), whose output then changes and needs its own comparison with Chrome; `showPopover()` and fullscreen change no attribute, so the `toggle` and `fullscreenchange` events must be watched | | Default styles of Firefox and Safari | Only Chromium's `html.css` ships: in Firefox or Safari, the user agent stylesheet rules in Styles are Chrome's, not the ones in effect | Load the sheet of the page's engine, with the same matching: Firefox's are in `layout/style/res/` (`html.css`, `forms.css`, `ua.css`, …, MPL-2.0), Safari's is WebKit's `html.css` (LGPL, the same origin as Chromium's). Hard parts: the many `-moz-` internals are dropped by the page's parser, so measure first how many rules are left; with no CDP to compare rule by rule, only each browser's own DevTools by hand or `getComputedStyle` can check them; one version is pinned as an approximation | | Cross-origin `` documents as child targets (not done) | A cross-origin `` is not found: it has no `contentWindow`, and the window among the page's child windows whose `frameElement` it is cannot be read across origins. So its document is not linked (its hello is refused, it is not pinged), and DOM does not show it as a cross-origin frame; Chrome gives it a child target as for an iframe | Tell its window apart by elimination: of the page's child windows, the ones no other owner holds (`contentWindow` of iframes, frames and objects, same-origin embeds) match the remaining embeds in document order. Not done: the page's child windows come in the order the frames were inserted, not in document order, so the match is not reliable | @@ -39,7 +38,7 @@ Lowest priority: matching selectors with namespace prefixes (`svg|a`, `[xlink|hr ## Commands without effect -Settled: a command the page cannot carry out fails with a server error (-32000), "Not supported in the page: " (`cdp-agent/domains/stubs.ts`): Autofill's addresses, background service recording, the service worker commands that need the worker itself (inspecting, starting and stopping workers, `skipWaiting`, delivering push messages and sync events) and forcing updates on page load (turning it off succeeds), auto dark mode, turning focus emulation on (turning it off succeeds), resetting the pinch zoom, bypassing the service worker, interest group and shared storage tracking, remote target locations, the security isolation status (COOP, COEP and CSP are response headers), the browser's feature flags, network throttling (any latency, throughput or packet loss; without them, and offline, it succeeds), and enabling the domains whose events only the browser has: `Autofill`, `Database` (WebSQL), `HeapProfiler`, `Preload`, `Profiler`. The frontend does not log server errors, and its models start the same when these replies fail; the Frames view leaves out the isolation section and the bounce tracking view shows as disabled, as with the made-up answers before. Read commands fail too rather than answer with made-up data, while `CSS.getEnvironmentVariables` reads the env() values the page resolves. A command the page can only partly carry out is judged by its core effect: without it, the command cannot be carried out (focus emulation cannot keep `:focus` styles); with it, it is not done yet (a user agent override cannot change the document's own request, but scripts and later requests see it). A command that can be done in the page but is not yet still succeeds and is listed in the table above, as does enabling a domain whose events the page can give later (`Accessibility`, `Log`); `Animation`, `Audits` and `ServiceWorker` are implemented; `Inspector.enable` succeeds, as it is about the connection itself. +Settled: a command the page cannot carry out fails with a server error (-32000), "Not supported in the page: " (`cdp-agent/domains/stubs.ts`): Autofill's addresses, background service recording, the service worker commands that need the worker itself (inspecting, starting and stopping workers, `skipWaiting`, delivering push messages and sync events) and forcing updates on page load (turning it off succeeds), auto dark mode, turning focus emulation on (turning it off succeeds), resetting the pinch zoom, bypassing the service worker, interest group and shared storage tracking, remote target locations, the security isolation status (COOP, COEP and CSP are response headers), the browser's feature flags, network throttling (any latency, throughput or packet loss; without them, and offline, it succeeds), and enabling the domains whose events only the browser has: `Autofill`, `Database` (WebSQL), `HeapProfiler`, `Preload`, `Profiler`. The frontend does not log server errors, and its models start the same when these replies fail; the Frames view leaves out the isolation section and the bounce tracking view shows as disabled, as with the made-up answers before. Read commands fail too rather than answer with made-up data, while `CSS.getEnvironmentVariables` reads the env() values the page resolves. A command the page can only partly carry out is judged by its core effect: without it, the command cannot be carried out (focus emulation cannot keep `:focus` styles); with it, it is not done yet (a user agent override cannot change the document's own request, but scripts and later requests see it). A command that can be done in the page but is not yet still succeeds and is listed in the table above, as does enabling a domain whose events the page can give later (`Log`); `Accessibility`, `Animation`, `Audits` and `ServiceWorker` are implemented; `Inspector.enable` succeeds, as it is about the connection itself. ## Patches from an older release line diff --git a/docs/roadmap.zh-CN.md b/docs/roadmap.zh-CN.md index 965d82c2..38ef993c 100644 --- a/docs/roadmap.zh-CN.md +++ b/docs/roadmap.zh-CN.md @@ -27,7 +27,6 @@ |---|---|---| | 外壳模式下对图片和脚本屏蔽 URL、附加请求头、离线 | 屏蔽 URL、附加请求头、禁用缓存、离线只对探针拦截的 fetch、XHR 生效;文档本身的请求和其他子资源不受影响 | 外壳模式开启 Service Worker 时,对它经手的同域请求(图片、脚本、样式表等)同样生效 | | 常驻叠加层的剩余差距 | Grid、Flex、容器查询、scroll-snap 和隔离叠加层是近似绘制:没有 grid 线编号和区域名,对齐后的 grid 偏移、从右到左布局没有处理;Flex 不显示剩余空间分布和间距;容器查询不标出被查询的后代;合并的沙箱 iframe 里的节点没有常驻叠加层 | 在同一层里按计算样式和盒子画出来 | -| 无障碍事件 | 不发 `Accessibility.loadComplete` 和 `nodesUpdated`:树在每条命令里现算,窗格不会自己刷新 | 对文档用 `MutationObserver`,发出属性变了的节点 | | `::backdrop` 伪元素 | 模态 dialog、打开的 popover、全屏元素下,DOM 里没有 `::backdrop` 节点,它上面的动画指向宿主元素;Chrome 会显示该伪元素(`DOM.pseudoElementAdded`,并列在宿主的 `pseudoElements` 里),动画也指向它 | 把 `backdrop` 加入伪元素节点,宿主位于顶层(`:modal`、`:popover-open`、`:fullscreen`)时存在。难点:伪元素类型表与 CSS 域共用(匹配样式、层叠、计算样式更新、浏览器默认样式),加入后 CSS 域的输出会变,需另行与 Chrome 对照;`showPopover()` 和全屏不改任何属性,要监听 `toggle` 与 `fullscreenchange` 事件 | | Firefox、Safari 的浏览器默认样式 | 只附带 Chromium 的 `html.css`:页面在 Firefox 或 Safari 里时,Styles 显示的 user agent stylesheet 规则是 Chrome 的,与实际生效的不同 | 按内核加载对应的样式表,匹配逻辑不用改:Firefox 的在 `layout/style/res/`(`html.css`、`forms.css`、`ua.css` 等,MPL-2.0),Safari 用 WebKit 的 `html.css`(LGPL,与 Chromium 同源)。难点:大量 `-moz-` 私有语法会被页面的解析器丢掉,先实测能保留多少规则;没有 CDP 可以逐条对照,只能和各家 DevTools 人工比对或用 `getComputedStyle` 间接校验;只能钉住一个版本作为近似 | | 跨域 `` 文档作为子目标(没做) | 找不到跨域 `` 的窗口:它没有 `contentWindow`,而跨域时读不了子窗口的 `frameElement`。因此其中的文档不会链接(握手被拒、也不被 ping),DOM 里也不当作跨域 frame;Chrome 会像 iframe 一样给它建子目标 | 用排除法认出它的窗口:页面的子窗口里,不属于其他 owner(iframe、frame、object 的 `contentWindow`,同域 embed)的那些,按文档顺序对应剩下的 embed。没做:页面的子窗口按 frame 插入的顺序排列,不是文档顺序,对应不可靠 | @@ -39,7 +38,7 @@ ## 没有效果的命令 -已定:页面做不到的命令返回服务器错误(-32000),信息是「Not supported in the page: <原因>」(`cdp-agent/domains/stubs.ts`):Autofill 的地址、后台服务记录、需要 worker 本身的 Service Worker 命令(调试、启动、停止 worker,`skipWaiting`,投递推送消息和同步事件)、页面加载时强制更新(关闭时返回成功)、自动深色模式、开启焦点模拟(关闭时返回成功)、重置双指缩放、绕过 Service Worker、跟踪兴趣组和共享存储、远程目标地址、安全隔离状态(COOP、COEP、CSP 是响应头)、浏览器的功能开关、网络限速(设了延迟、吞吐量或丢包就算;都不设或只设离线时返回成功),以及启用只有浏览器才有事件的域:`Autofill`、`Database`(WebSQL)、`HeapProfiler`、`Preload`、`Profiler`。前端不记录服务器错误,这些命令失败时它的各个模型照常启动;Frames 视图不显示隔离状态一节,跳出跟踪视图显示为未启用,与之前编造的回答效果相同。读取类命令同样返回失败而不编造数据,`CSS.getEnvironmentVariables` 则读取页面解析出的 env() 值。只能做一部分的,按核心效果判断:核心效果做不到就算做不到(如焦点模拟保不住 `:focus` 样式),否则算还没做(如 UA 覆盖改不了文档自身的请求,但 JS 和之后的请求能读到)。能在页面里做但还没做的命令仍返回成功,列在上面的表里;页面以后能给出事件的域(`Accessibility`、`Log`;`Animation`、`Audits`、`ServiceWorker` 已实现)启用时也返回成功;`Inspector.enable` 管的是连接本身,也返回成功。 +已定:页面做不到的命令返回服务器错误(-32000),信息是「Not supported in the page: <原因>」(`cdp-agent/domains/stubs.ts`):Autofill 的地址、后台服务记录、需要 worker 本身的 Service Worker 命令(调试、启动、停止 worker,`skipWaiting`,投递推送消息和同步事件)、页面加载时强制更新(关闭时返回成功)、自动深色模式、开启焦点模拟(关闭时返回成功)、重置双指缩放、绕过 Service Worker、跟踪兴趣组和共享存储、远程目标地址、安全隔离状态(COOP、COEP、CSP 是响应头)、浏览器的功能开关、网络限速(设了延迟、吞吐量或丢包就算;都不设或只设离线时返回成功),以及启用只有浏览器才有事件的域:`Autofill`、`Database`(WebSQL)、`HeapProfiler`、`Preload`、`Profiler`。前端不记录服务器错误,这些命令失败时它的各个模型照常启动;Frames 视图不显示隔离状态一节,跳出跟踪视图显示为未启用,与之前编造的回答效果相同。读取类命令同样返回失败而不编造数据,`CSS.getEnvironmentVariables` 则读取页面解析出的 env() 值。只能做一部分的,按核心效果判断:核心效果做不到就算做不到(如焦点模拟保不住 `:focus` 样式),否则算还没做(如 UA 覆盖改不了文档自身的请求,但 JS 和之后的请求能读到)。能在页面里做但还没做的命令仍返回成功,列在上面的表里;页面以后能给出事件的域(`Log`;`Accessibility`、`Animation`、`Audits`、`ServiceWorker` 已实现)启用时也返回成功;`Inspector.enable` 管的是连接本身,也返回成功。 ## 从旧版本线发布补丁 diff --git a/package.json b/package.json index dd6b67ad..3043cd94 100644 --- a/package.json +++ b/package.json @@ -5,8 +5,8 @@ "scripts": { "build": "pnpm -r run build", "dev": "pnpm run build && pnpm -r --parallel run dev", - "typecheck": "pnpm run build && pnpm -r run typecheck && tsc -p tsconfig.scripts.json && tsc -p tsconfig.tests.json", - "test": "pnpm run build && node --test --test-concurrency=4 \"tests/**/*.test.ts\" \"packages/*/src/**/*.test.ts\" \"playground/**/*.test.ts\"", + "typecheck": "pnpm run build && pnpm -r run typecheck && tsc -p scripts && tsc -p tests", + "test": "pnpm run build && node --test --test-concurrency=4 --test-timeout=300000 \"tests/**/*.test.ts\" \"packages/*/src/**/*.test.ts\" \"playground/**/*.test.ts\"", "playground": "node playground/server.ts", "remote": "node packages/remote-server/dist/cli.js --port 8790 --host 127.0.0.1 --no-token --public-url http://localhost:8790/", "licenses:update": "node scripts/third-party-licenses.ts", diff --git a/packages/devtools-anywhere/THIRD_PARTY_LICENSES.md b/packages/devtools-anywhere/THIRD_PARTY_LICENSES.md index 308f0d74..34db3b4f 100644 --- a/packages/devtools-anywhere/THIRD_PARTY_LICENSES.md +++ b/packages/devtools-anywhere/THIRD_PARTY_LICENSES.md @@ -8,8 +8,7 @@ This package contains the third-party code below, with its copyright notices and | --- | --- | --- | --- | --- | | [es-module-lexer (ported code)](https://github.com/guybedford/es-module-lexer) | 3.0.4 | MIT | Guy Bedford | devtools-anywhere | | [snapDOM (@zumer/snapdom)](https://github.com/zumerlab/snapdom) | 3.3.5 | MIT | ZumerLab | devtools-anywhere | -| [dom-accessibility-api](https://github.com/eps1lon/dom-accessibility-api) | 0.7.1 | MIT | Sebastian Silbermann | devtools-anywhere | -| [Chromium's default style sheet (html.css)](https://chromium.googlesource.com/chromium/src/+/refs/tags/158.0.8127.37/third_party/blink/renderer/core/html/resources/html.css) | Chrome 158.0.8127.37 | LGPL-2.0-or-later | Lars Knoll; Apple Inc. | devtools-anywhere | +| [Chromium's default style sheet (html.css)](https://chromium.googlesource.com/chromium/src/+/refs/tags/159.0.8154.13/third_party/blink/renderer/core/html/resources/html.css) | Chrome 159.0.8154.13 | LGPL-2.0-or-later | Lars Knoll; Apple Inc. | devtools-anywhere | ### es-module-lexer (ported code) @@ -66,45 +65,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -### dom-accessibility-api - -- Version: 0.7.1 -- License: MIT -- Copyright: Sebastian Silbermann -- Source: https://github.com/eps1lon/dom-accessibility-api -- Included in: devtools-anywhere -- Notes: Bundled as dist/accessibility.js, loaded on demand for the Accessibility domain. - -```text -MIT License - -Copyright (c) 2020 Sebastian Silbermann - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -``` - ### Chromium's default style sheet (html.css) -- Version: Chrome 158.0.8127.37 +- Version: Chrome 159.0.8154.13 - License: LGPL-2.0-or-later - Copyright: Lars Knoll; Apple Inc. -- Source: https://chromium.googlesource.com/chromium/src/+/refs/tags/158.0.8127.37/third_party/blink/renderer/core/html/resources/html.css +- Source: https://chromium.googlesource.com/chromium/src/+/refs/tags/159.0.8154.13/third_party/blink/renderer/core/html/resources/html.css - Included in: devtools-anywhere - Notes: Shipped unmodified as dist/chromium-html.css, with this license as dist/chromium-html.LICENSE.txt; loaded on demand for the Styles pane. It is the only file under this license: deleting both leaves out the user agent stylesheet rules and nothing else. diff --git a/packages/devtools-anywhere/package.json b/packages/devtools-anywhere/package.json index 9674ccee..c116f6e6 100644 --- a/packages/devtools-anywhere/package.json +++ b/packages/devtools-anywhere/package.json @@ -1,6 +1,6 @@ { "name": "devtools-anywhere", - "version": "0.4.0", + "version": "0.5.0", "description": "Real Chrome DevTools inside any web page, with early capture", "keywords": [ "cdp", @@ -44,15 +44,12 @@ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.service-worker.json && tsc -p tsconfig.cdp-agent.json", "dev": "node build.ts --watch" }, - "dependencies": { - "@zumer/snapdom": "^3.3.5", - "dom-accessibility-api": "^0.7.1" - }, "devDependencies": { "@devtools-anywhere/relay-core": "workspace:*", + "@zumer/snapdom": "^3.3.5", "devtools-protocol": "^0.0.1721318", "esbuild": "^0.25.0", "typescript": "^7.0.2" }, - "chrome": "158.0.8127.37" + "chrome": "159.0.8154.13" } diff --git a/packages/devtools-anywhere/src/cdp-agent/core/natives.ts b/packages/devtools-anywhere/src/cdp-agent/core/natives.ts index 1255aaa9..712be0d5 100644 --- a/packages/devtools-anywhere/src/cdp-agent/core/natives.ts +++ b/packages/devtools-anywhere/src/cdp-agent/core/natives.ts @@ -19,8 +19,11 @@ let top: TopNatives | undefined = typeof MutationObserver === 'function' ? captu /** The native function found for each prototype and `part:name` (null: none). */ let nativeCache = new WeakMap>(); -/** Takes the functions the probe saved before the page's code (`probe.natives`, `probe.top`), where it has them. */ -export function useNatives(probe: Probe): void { +/** + * Takes the functions the probe saved before the page's code (`probe.natives`, `probe.top`), where it has them. + * Also how a script loaded later with its own copy of this module (accessibility.js) takes the agent's (`nativesInUse`). + */ +export function useNatives(probe: Pick): void { if (probe.natives) { table = probe.natives; nativeCache = new WeakMap(); @@ -28,6 +31,9 @@ export function useNatives(probe: Probe): void { if (probe.top) top = probe.top; } +/** The functions in use, for a script loaded later to take (`useNatives`) rather than those it would find then. */ +export const nativesInUse = (): Pick => ({ natives: table, top }); + /** The window's functions the agent calls: frames, timers, the clock, the observers and the listeners. */ export function windowOf(): TopNatives { if (!top) throw new TypeError('the window natives are not there: this is not a browser'); diff --git a/packages/devtools-anywhere/src/cdp-agent/core/nodes/nodes.ts b/packages/devtools-anywhere/src/cdp-agent/core/nodes/nodes.ts index 2f4cb6d1..7bfa30b8 100644 --- a/packages/devtools-anywhere/src/cdp-agent/core/nodes/nodes.ts +++ b/packages/devtools-anywhere/src/cdp-agent/core/nodes/nodes.ts @@ -67,7 +67,7 @@ export function closestOwn(node: Node): boolean { /** Pseudo-classes forced on an element (CSS.forcePseudoState); hidden from the client. */ export const FORCE_ATTRIBUTE = 'data-devtools-anywhere-force'; /** - * What forced colors (domains/emulation/forced-colors.ts) does to an element, as tokens: `kept` when it + * What forced colors (domains/emulation/paint/forced-colors.ts) does to an element, as tokens: `kept` when it * keeps its colors (forced-color-adjust: none), `canvas` or `canvas-` when its background is the * canvas, and `no-image` when its generated background images are taken away. Hidden from the client. */ diff --git a/packages/devtools-anywhere/src/cdp-agent/core/nodes/written-attributes.ts b/packages/devtools-anywhere/src/cdp-agent/core/nodes/written-attributes.ts index 1a851eef..e5ee152e 100644 --- a/packages/devtools-anywhere/src/cdp-agent/core/nodes/written-attributes.ts +++ b/packages/devtools-anywhere/src/cdp-agent/core/nodes/written-attributes.ts @@ -3,12 +3,12 @@ import { nativeCall } from '../natives'; /** * An attribute the agent wrote into one of the page's elements (the emulation's rewrites, see - * domains/emulation/rewrite.ts): the value the page gave it, and the value written, as it reads. + * domains/emulation/rewrite/rewrite.ts): the value the page gave it, and the value written, as it reads. */ export interface Written { original: string; applied: string; - /** What the rewrite gave the original, as last written (domains/emulation/rewrite.ts). */ + /** What the rewrite gave the original, as last written (domains/emulation/rewrite/rewrite.ts). */ target: string; /** For a style attribute rewritten from the writes of its block (rewrite.ts, planWritten), not from its text. */ played?: true; diff --git a/packages/devtools-anywhere/src/cdp-agent/core/turn.ts b/packages/devtools-anywhere/src/cdp-agent/core/turn.ts index f406d6ca..6a693fe2 100644 --- a/packages/devtools-anywhere/src/cdp-agent/core/turn.ts +++ b/packages/devtools-anywhere/src/cdp-agent/core/turn.ts @@ -2,8 +2,8 @@ * The turn of the page's script that the agent's writes into the page are made in, and the frames a write waits * for. A page may answer a write of the agent's with a change of its own in the same turn (a mutation observer * that puts back what it had, or adds something for each change it sees), which the agent's observer would answer - * in turn, for ever: the emulation's rewrites of attributes (domains/emulation/rewrite.ts) and its scans of new - * elements (domains/emulation/inject.ts) tell such answers by the turn, and wait for frames before they write + * in turn, for ever: the emulation's rewrites of attributes (domains/emulation/rewrite/rewrite.ts) and its scans of new + * elements (domains/emulation/inject/inject.ts) tell such answers by the turn, and wait for frames before they write * again. * * The frames, timers and clock are the probe's (windowOf), not the page's: a page may replace them (a fake clock, diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/accessibility.conformance.test.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/accessibility.conformance.test.ts deleted file mode 100644 index 37fd7f37..00000000 --- a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/accessibility.conformance.test.ts +++ /dev/null @@ -1,247 +0,0 @@ -import { describe, test } from 'node:test'; -import assert from 'node:assert/strict'; -import type { Protocol } from 'devtools-protocol'; -import { launch, openPage, setUpAndTearDown } from '../../../../test-support/conformance.ts'; -import type { Env, Side, TestPage } from '../../../../test-support/conformance.ts'; - -let env: Env | undefined; -let t: TestPage; - -/** - * Elements of the cases the Accessibility pane shows, each with an id to find it on both sides. - * Left out: what the page cannot see or Chrome gives in the browser's language (an input - * button's default label). - */ -const FIXTURE = ` -
a - - - - - - - - - -
H
c
-
focusable
- - -
SD
-

One

-

Para bold

- - -no href - -Svg t -
owner
ownee -
-
Site
-
art head
art foot
-
foot
- -
H
-
- - - - - -
-
  1. a
    • b
-
-
Panel
- -
edit
-

lvl

-
rh
- -logo -
S
-tt -
RB
- -
-
T
D
-
q
-
Leg
-
f
Cap
-
Cap
A
Rv
-`; - -setUpAndTearDown( - async () => { - env = await launch(); - t = await openPage(env, []); - await t.page.evaluate( - (html, base) => { - document.title = 'AX'; - document.body.innerHTML = html; - // The fixture's own focus would differ between the sides' runs. - if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); - window.__session = window.DevtoolsAnywhere.createCdpSession({ - loadAccessibility: () => import(base + '/packages/devtools-anywhere/dist/accessibility.js'), - }); - }, - FIXTURE, - env.baseUrl - ); - // Chrome's whole-tree commands need the domain enabled. - await Promise.all([t.ours.send('Accessibility.enable'), t.chrome.send('Accessibility.enable')]); - }, - () => env?.close() -); - -/** The DOM node id of `#id` on one side. */ -async function nodeIdOf(side: Side, id: string) { - const { root } = await side.send('DOM.getDocument', { depth: 0 }); - return (await side.send('DOM.querySelector', { nodeId: root.nodeId, selector: `#${id}` })).nodeId; -} - -/** Ids and links between nodes differ between the sides; Chrome's internal role numbers are its own. */ -function comparable(node: Protocol.Accessibility.AXNode) { - return JSON.parse( - JSON.stringify(node, (key, value: unknown) => - ['nodeId', 'parentId', 'childIds', 'backendDOMNodeId', 'chromeRole', 'frameId'].includes(key) ? undefined : value - ) - ) as unknown; -} - -/** The node and its relatives as roles and names: what the page cannot see (inline text boxes) left out. */ -function outline(nodes: Protocol.Accessibility.AXNode[]) { - return nodes - .filter(n => n.role?.value !== 'InlineTextBox') - .map(n => `${String(n.role?.value)}${n.name ? `:${String(n.name.value)}` : ''}`); -} - -const ids = [...FIXTURE.matchAll(/ id=(\w+)/g)].map(m => m[1] ?? ''); - -describe('Accessibility.getPartialAXTree', () => { - for (const id of ids) - test(`#${id}: role, name and its sources, description, value, properties`, async () => { - const [ours, chrome] = await Promise.all( - [t.ours, t.chrome].map(async side => - side.send('Accessibility.getPartialAXTree', { nodeId: await nodeIdOf(side, id), fetchRelatives: false }) - ) - ); - assert.ok(ours && chrome); - assert.deepEqual(ours.nodes.map(comparable), chrome.nodes.map(comparable)); - }); - - test('fetchRelatives: the children, through ignored ones, and the ancestors', async () => { - for (const id of ['nv', 'ul', 'tb', 'th1', 'h1', 'pp', 'own', 'ownee', 'pr', 'sp', 'dp']) { - const [ours, chrome] = await Promise.all( - [t.ours, t.chrome].map(async side => - side.send('Accessibility.getPartialAXTree', { nodeId: await nodeIdOf(side, id), fetchRelatives: true }) - ) - ); - assert.ok(ours && chrome); - // Chrome's list markers have no DOM node. - const nodes = (r: typeof ours) => outline(r.nodes).filter(s => !s.startsWith('ListMarker')); - assert.deepEqual(nodes(ours), nodes(chrome), `#${id}`); - } - }); - - test('the root is the document, named after its title', async () => { - const [ours, chrome] = await Promise.all( - [t.ours, t.chrome].map(async side => - side.send('Accessibility.getPartialAXTree', { nodeId: await nodeIdOf(side, 'root'), fetchRelatives: true }) - ) - ); - assert.ok(ours && chrome); - const root = (r: typeof ours) => r.nodes.find(n => n.role?.value === 'RootWebArea'); - const [a, b] = [root(ours), root(chrome)]; - assert.ok(a && b); - // The URL and focus are each side's page's. - const props = (n: Protocol.Accessibility.AXNode) => - (n.properties ?? []).filter(p => p.name !== 'focused' && p.name !== 'url'); - assert.deepEqual(comparable({ ...a, properties: props(a) }), comparable({ ...b, properties: props(b) })); - }); -}); - -test('without accessibility.js the commands fail', async () => { - await assert.rejects( - t.page.evaluate(async () => { - const plain = window.DevtoolsAnywhere.createCdpSession(); - const { root } = (await plain.call('DOM.getDocument', {})) as { root: { nodeId: number } }; - await plain.call('Accessibility.getPartialAXTree', { nodeId: root.nodeId }); - }), - /Not supported in the page/ - ); -}); - -/** Roles and names of a list of nodes, without those the page cannot see. */ -const visible = (nodes: Protocol.Accessibility.AXNode[]) => - outline(nodes).filter(s => !/^(ListMarker|MenuListPopup)/.test(s)); - -describe('the whole tree', () => { - test('queryAXTree finds nodes by role and name in a subtree', async () => { - const queries = [ - { role: 'button' }, - { accessibleName: 'One' }, - { role: 'textbox', accessibleName: 'Type' }, - { role: 'heading' }, - { role: 'none' }, - ]; - for (const query of queries) { - const [ours, chrome] = await Promise.all( - [t.ours, t.chrome].map(async side => - side.send('Accessibility.queryAXTree', { nodeId: await nodeIdOf(side, 'root'), ...query }) - ) - ); - assert.ok(ours && chrome); - assert.deepEqual(ours.nodes.map(comparable), chrome.nodes.map(comparable), JSON.stringify(query)); - } - }); - - test('getAXNodeAndAncestors', async () => { - for (const id of ['th1', 'ownee', 'bb']) { - const [ours, chrome] = await Promise.all( - [t.ours, t.chrome].map(async side => - side.send('Accessibility.getAXNodeAndAncestors', { nodeId: await nodeIdOf(side, id) }) - ) - ); - assert.ok(ours && chrome); - assert.deepEqual(outline(ours.nodes), outline(chrome.nodes), `#${id}`); - } - }); - - test('getRootAXNode and getChildAXNodes walk down to a node', async () => { - const walk = async (side: Side) => { - const { node: root } = await side.send('Accessibility.getRootAXNode', {}); - const seen = [outline([root])]; - // Down the first child each time, from the document to the fixture's first text. - let id = root.nodeId; - for (let i = 0; i < 5; i++) { - const { nodes } = await side.send('Accessibility.getChildAXNodes', { id }); - seen.push(visible(nodes)); - const next = nodes[0]; - if (!next) break; - id = next.nodeId; - } - return seen; - }; - const [ours, chrome] = await Promise.all([walk(t.ours), walk(t.chrome)]); - assert.deepEqual(ours, chrome); - }); - - test('getFullAXTree: the nodes the page can see, breadth first', async () => { - const [ours, chrome] = await Promise.all( - [t.ours, t.chrome].map(side => side.send('Accessibility.getFullAXTree', { depth: 1 })) - ); - assert.ok(ours && chrome); - assert.deepEqual(visible(ours.nodes), visible(chrome.nodes)); - }); -}); - -test('the vision deficiency mask is not in the accessibility tree', async () => { - const count = async () => (await t.ours.send('Accessibility.getFullAXTree', {})).nodes.length; - const plain = await count(); - await t.ours.send('Emulation.setEmulatedVisionDeficiency', { type: 'achromatopsia' }); - try { - assert.equal(await count(), plain); - } finally { - await t.ours.send('Emulation.setEmulatedVisionDeficiency', { type: 'none' }); - } -}); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/accessibility.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/accessibility.ts index f313c872..f3cc0cab 100644 --- a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/accessibility.ts +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/accessibility.ts @@ -1,9 +1,13 @@ import type { Protocol } from 'devtools-protocol'; +import { disconnect, nativesInUse, newObserver, observe } from '../../core/natives'; +import { afterFrames } from '../../core/turn'; import { CdpError } from '../../core/session'; import type { Context } from '../../core/context'; import { documentOf, isNode } from '../../core/realm'; import { resolveNode } from '../dom/dom'; +import { PseudoElement } from '../../core/nodes/nodes'; import type { AccessibilityModule, AXTree } from './ax-node'; +import type { AXRef } from './tree/ax-virtual'; /** * Loads accessibility.js (ax-node.ts), which computes the tree: it is large, and only the @@ -11,15 +15,45 @@ import type { AccessibilityModule, AXTree } from './ax-node'; */ export type AccessibilityLoader = () => Promise; +/** What may change the tree: the DOM, its attributes (class and style too) and its text. */ +const OBSERVED: MutationObserverInit = { + attributes: true, + childList: true, + subtree: true, + characterData: true, +}; + /** * The Accessibility domain: the tree computed in the page from the DOM, ARIA attributes and the - * implicit roles (ax-tree.ts, ax-name.ts), as Chrome's getPartialAXTree gives it to the - * Accessibility pane. Chrome's inline text boxes and the nodes of user-agent shadow trees (a - * text field's inner editor, a select's popup) are not in it: the page cannot see them. + * implicit roles (ax-role.ts, ax-name.ts), as Chrome's getPartialAXTree gives it to the + * Accessibility pane. Chrome's inline text boxes are not in it. The nodes of user-agent shadow + * trees (a select's popup), which the page cannot see, are redone without a DOM node + * (ax-virtual.ts): each gets a negative id, kept for the session, apart from the backend ids. So + * are list markers (ax-marker.ts), but a marker has its ::marker pseudo-element's backend id, as in + * Chrome; its text children get negative ids. + * + * Events, as Chrome 158 sends them: `nodesUpdated` only while enabled, and only for the nodes the + * client was given by getChildAXNodes or getAXNodeAndAncestors (the Accessibility pane's + * commands; getPartialAXTree, getFullAXTree, getRootAXNode and queryAXTree mark none), each as a + * whole AXNode, those changed in one frame in one event. `loadComplete` comes when a document + * finishes loading, which the agent, started in a loaded page, never sees: it is not sent, and + * not on enable either, as Chrome does not. A node without a DOM node is not watched. */ export function registerAccessibility(ctx: Context, load: AccessibilityLoader | undefined) { const { session, nodes, frames } = ctx; let module: Promise | null = null; + /** The ids of the nodes without a DOM node, by their host's backend id and key, and back. */ + const virtualIds = new Map(); + const virtualKeys = new Map(); + const virtualIdOf = (hostId: number, key: string) => { + let id = virtualIds.get(`${hostId}:${key}`); + if (id === undefined) { + id = -1 - virtualIds.size; + virtualIds.set(`${hostId}:${key}`, id); + virtualKeys.set(id, { hostId, key }); + } + return id; + }; /** * The tree of a frame's document (the page's or a same-origin iframe's), over its current DOM: * computed again by each command, as the DOM changes between them. @@ -27,27 +61,141 @@ export function registerAccessibility(ctx: Context, load: AccessibilityLoader | const tree = async (doc: Document): Promise => { if (!load) throw new CdpError('Not supported in the page: the accessibility tree is not configured'); // A failed load is not kept, so that the next command loads again. - const m = await (module ??= load().catch((e: unknown) => { - module = null; - throw e; - })); - return m.createAXTree(doc, node => nodes.backendIdOf(node), frames.ofNode(doc).id); + const m = await (module ??= load().then( + loaded => { + loaded.useNatives(nativesInUse()); + return loaded; + }, + (e: unknown) => { + module = null; + throw e; + } + )); + return m.createAXTree( + doc, + node => nodes.backendIdOf(node), + frames.ofNode(doc).id, + virtualIdOf, + (host, type) => nodes.backendIdOf(nodes.pseudoOf(host, type)) + ); }; + /** + * While enabled, the nodes the client was given that nodesUpdated reports, with the AXNode last + * given for each (as JSON): a node is sent again when its AXNode differs. + */ + let enabled = false; + const known = new Map(); + let observer: MutationObserver | null = null; + /** A frame is awaited for changes; the flush of earlier ones may still be computing. */ + let scheduled = false; + + /** Records the nodes given to the client, and watches the trees they are in. */ + function remember(given: [AXRef, Protocol.Accessibility.AXNode][]) { + if (!enabled) return; + for (const [node, axNode] of given) { + // A node without a DOM node is built again with each tree: it is not watched. + if (!isNode(node)) continue; + known.set(node, JSON.stringify(axNode)); + // The document, or the shadow root the node is in: a document's observer does not see into + // shadow trees. A change in a shadow tree whose own nodes the client was not given (a + // slotted element's host's tree) is seen with the next change in an observed one. + observer ??= newObserver(changed); + observe(observer, node.getRootNode(), OBSERVED); + } + } + + /** + * After a change, the next frame computes the tree again and sends the known nodes whose AXNode + * differs, in one event, as Chrome sends the nodes changed in a frame. Chrome sends those its + * tree marks dirty, which may include a node's parent whose AXNode is the same (when a child's + * role changes, say); this sends only those that differ. + * + * The observer sees the DOM only: a style change from an attribute (a class, `style`) or a + * stylesheet added or edited as text is seen, but not one from the CSSOM (insertRule, a + * declaration set on a sheet's rule), :hover, :focus and other states, media queries + * (resizing), animations or transitions, nor an image loading. Those are sent with the next DOM + * change; the commands always compute the tree from the current DOM and styles. + */ + function changed() { + if (scheduled) return; + scheduled = true; + afterFrames(1, () => { + scheduled = false; + void flush(); + }); + } + + async function flush() { + try { + const byDoc = new Map(); + for (const node of known.keys()) { + // A node gone from its document is not sent: its parent's children tell it. + if (!node.isConnected) { + known.delete(node); + continue; + } + const doc = documentOf(node); + byDoc.set(doc, [...(byDoc.get(doc) ?? []), node]); + } + const out: Protocol.Accessibility.AXNode[] = []; + for (const [doc, list] of byDoc) { + const ax = await tree(doc); + if (!enabled) return; + for (const node of list) { + // A node now left out of the tree (display: none) is not sent, as in Chrome; it is sent + // again when it comes back. + if (!ax.inTree(node) || !known.has(node)) continue; + const axNode = ax.node(node); + const json = JSON.stringify(axNode); + if (json === known.get(node)) continue; + known.set(node, json); + out.push(axNode); + } + } + if (out.length && enabled) + session.emit('Accessibility.nodesUpdated', { + nodes: out, + } satisfies Protocol.Accessibility.NodesUpdatedEvent); + } catch { + // The tree could not be loaded: the commands report it. + } + } + + function stop() { + enabled = false; + known.clear(); + if (observer) disconnect(observer); + observer = null; + } + + session.onReset(stop); + session.register('Accessibility', { - // Nothing to stop: the tree is computed per command (enable is a no-op in stubs.ts). - disable: () => ({}), + // Events start with the nodes the client is given from now on. + enable: () => { + enabled = true; + return {}; + }, + disable: () => { + stop(); + return {}; + }, async getPartialAXTree( params: Protocol.Accessibility.GetPartialAXTreeRequest ): Promise { - const node = resolveNode(ctx, params); - const ax = await tree(documentOf(node)); + const { node, ax } = await target(params); const out = [ax.node(node)]; if (params.fetchRelatives ?? true) { // Like Chrome: the node's children, then its ancestors up to the root. - if (ax.inTree(node)) out.push(...childrenOf(ax, node)); + if (ax.inTree(node)) out.push(...childrenOf(ax, node).map(([, axNode]) => axNode)); + const first = out.length; for (let p = ax.parent(node); p; p = ax.parent(p)) out.push(ax.node(p)); + // A node out of the tree is listed among its parent's children here, as Chrome does. + const up = out[first]; + const self = out[0] as Protocol.Accessibility.AXNode; + if (up && !up.childIds?.includes(self.nodeId)) up.childIds = [...(up.childIds ?? []), self.nodeId]; } return { nodes: out }; }, @@ -57,20 +205,24 @@ export function registerAccessibility(ctx: Context, load: AccessibilityLoader | ): Promise { const doc = documentOfFrame(params.frameId); const ax = await tree(doc); - // Breadth first, as Chrome lists them. `depth` counts the nodes that are not ignored above a - // node, as in Chrome: the root's children are at 1, and so are those of an ignored body. - const max = params.depth ?? Infinity; - const out: Protocol.Accessibility.AXNode[] = []; - let level: { node: Node; depth: number }[] = [{ node: doc, depth: 0 }]; - while (level.length) { - const next: typeof level = []; - for (const { node, depth } of level) { - const axNode = ax.node(node); + // In Chrome's order (WalkAXNodesToDepth in inspector_accessibility_agent.cc): breadth first + // over the nodes that are not ignored, from the root; each one's children are listed depth + // first, going down through the ignored ones, before the next node of the queue is taken. + // Chrome also goes down through a node without a DOM node; ours (a control's shadow parts) + // have one in Chrome, and its own (a marker's text in a roled list) have no children here. + // `depth` counts the nodes that are not ignored, the root at 1: those below the last level + // are not taken from the queue, but the ignored nodes under its nodes are still listed. + const max = params.depth ?? -1; + const out: Protocol.Accessibility.AXNode[] = [ax.node(doc)]; + const queue: { node: AXRef; depth: number }[] = [{ node: doc, depth: 1 }]; + for (const { node, depth } of queue) { + const stack = [...ax.children(node)].reverse(); + for (let child = stack.pop(); child; child = stack.pop()) { + const axNode = ax.node(child); out.push(axNode); - const childDepth = axNode.ignored ? depth : depth + 1; - if (childDepth <= max) for (const child of ax.children(node)) next.push({ node: child, depth: childDepth }); + if (axNode.ignored) stack.push(...[...ax.children(child)].reverse()); + else if (max === -1 || depth < max) queue.push({ node: child, depth: depth + 1 }); } - level = next; } return { nodes: out }; }, @@ -85,20 +237,37 @@ export function registerAccessibility(ctx: Context, load: AccessibilityLoader | async getChildAXNodes( params: Protocol.Accessibility.GetChildAXNodesRequest ): Promise { - const node = nodes.getByBackendId(Number(params.id)); - if (!isNode(node)) throw new CdpError('Invalid ID'); - const ax = await tree(documentOf(node)); - return { nodes: childrenOf(ax, node) }; + // A node without a DOM node by its id below 0, a list marker or generated content by its + // pseudo-element's backend id. + const id = Number(params.id); + const virtual = virtualKeys.get(id); + const found = nodes.getByBackendId(virtual ? virtual.hostId : id); + const pseudo = pseudoKey(found); + const host = pseudo && found instanceof PseudoElement ? found.host : found; + if (!isNode(host)) throw new CdpError('Invalid ID'); + const ax = await tree(documentOf(host)); + const node = virtual || pseudo ? ax.virtual(host, virtual ? virtual.key : (pseudo ?? '')) : host; + // A pseudo-element the tree has no node for has no children, as Chrome's ignored node. + if (!node) { + if (pseudo) return { nodes: [] }; + throw new CdpError('Invalid ID'); + } + const given: [AXRef, Protocol.Accessibility.AXNode][] = []; + childrenOf(ax, node, given); + remember(given); + return { nodes: given.map(([, axNode]) => axNode) }; }, async getAXNodeAndAncestors( params: Protocol.Accessibility.GetAXNodeAndAncestorsRequest ): Promise { - const node = resolveNode(ctx, params); - const ax = await tree(documentOf(node)); - const out = [ax.node(node)]; - for (let p = ax.parent(node); p; p = ax.parent(p)) out.push(ax.node(p)); - return { nodes: out }; + const { node, ax } = await target(params); + const given: [AXRef, Protocol.Accessibility.AXNode][] = [[node, ax.node(node)]]; + // A node Chrome has no parent for (a closed details' content) comes alone. + if (given[0]?.[1].parentId !== undefined) + for (let p = ax.parent(node); p; p = ax.parent(p)) given.push([p, ax.node(p)]); + remember(given); + return { nodes: given.map(([, axNode]) => axNode) }; }, async queryAXTree( @@ -106,14 +275,12 @@ export function registerAccessibility(ctx: Context, load: AccessibilityLoader | ): Promise { const root = resolveNode(ctx, params); const ax = await tree(documentOf(root)); - // The nodes in the root's subtree that match, in tree order: ignored ones too, as in Chrome. + // The nodes in the root's subtree that match, in tree order: ignored ones too, with their own + // role and name, as in Chrome. const out: Protocol.Accessibility.AXNode[] = []; - const visit = (node: Node) => { - const axNode = ax.node(node); - // An ignored element's role is none here, not the role Chrome matches against. - const roleKnown = !axNode.ignored || axNode.role?.value !== 'none'; + const visit = (node: AXRef) => { + const axNode = ax.node(node, true); if ( - roleKnown && (params.role === undefined || axNode.role?.value === params.role) && (params.accessibleName === undefined || axNode.name?.value === params.accessibleName) ) @@ -127,16 +294,46 @@ export function registerAccessibility(ctx: Context, load: AccessibilityLoader | }); /** A node's children as Chrome lists them: through ignored ones, down to those not ignored. */ - function childrenOf(ax: AXTree, parent: Node): Protocol.Accessibility.AXNode[] { - const out: Protocol.Accessibility.AXNode[] = []; + function childrenOf( + ax: AXTree, + parent: AXRef, + out: [AXRef, Protocol.Accessibility.AXNode][] = [] + ): [AXRef, Protocol.Accessibility.AXNode][] { for (const child of ax.children(parent)) { const axChild = ax.node(child); - out.push(axChild); - if (axChild.ignored) out.push(...childrenOf(ax, child)); + out.push([child, axChild]); + if (axChild.ignored) childrenOf(ax, child, out); } return out; } + /** + * The node a command refers to and its tree: a DOM node, or a ::marker pseudo-element for its list + * marker's node (its host's when the tree has no marker for it, where Chrome has an ignored node). + */ + async function target(params: { + nodeId?: number; + backendNodeId?: number; + objectId?: string; + }): Promise<{ node: AXRef; ax: AXTree }> { + const { nodeId, backendNodeId } = params; + const ref = nodeId ? nodes.get(nodeId) : backendNodeId ? nodes.getByBackendId(backendNodeId) : null; + const pseudo = pseudoKey(ref); + if (pseudo && ref instanceof PseudoElement) { + const ax = await tree(documentOf(ref.host)); + return { node: ax.virtual(ref.host, pseudo) ?? ref.host, ax }; + } + const node = resolveNode(ctx, params); + return { node, ax: await tree(documentOf(node)) }; + } + + /** The key of a pseudo-element's node in the tree: a ::marker, ::before or ::after. */ + function pseudoKey(ref: unknown): 'marker' | 'before' | 'after' | null { + if (!(ref instanceof PseudoElement)) return null; + const type = ref.pseudoType; + return type === 'marker' || type === 'before' || type === 'after' ? type : null; + } + /** The document of a frame, the top one by default. */ function documentOfFrame(frameId: string | undefined): Document { const frame = frameId === undefined ? frames.top : frames.byId(frameId); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-dom.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-dom.ts new file mode 100644 index 00000000..281197d8 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-dom.ts @@ -0,0 +1,133 @@ +// The DOM as the accessibility tree reads it: attributes, queries and the flattened tree, read +// through the browser's own functions. Part of accessibility.js (ax-node.ts). +// +// The DOM is read through the browser's own functions (core/natives.ts), not those on the page's +// prototypes: a page that replaced `getAttribute` or `querySelectorAll` would otherwise see the +// tree being built, could change what it finds, or make it throw. +import { isDocument, isElement, isHtml, isShadowRoot, isText, styleOf } from '../../core/realm'; +import { nativeCall, nativeGet } from '../../core/natives'; +import { type IgnoredReason } from './tree/ax-ignored'; + +/** An element's attribute, or null (`getAttribute`). */ +export const attr = (el: Element, name: string) => nativeCall(el, 'getAttribute', name); + +/** Whether an element has an attribute (`hasAttribute`). */ +export const hasAttr = (el: Element, name: string) => nativeCall(el, 'hasAttribute', name); + +/** The names of an element's attributes (`getAttributeNames`). */ +export const attrNames = (el: Element) => nativeCall(el, 'getAttributeNames'); + +/** The first element under `scope` that matches `selector` (`querySelector`). */ +export const query = (scope: ParentNode, selector: string) => + nativeCall(scope, 'querySelector', selector); + +/** The elements under `scope` that match `selector` (`querySelectorAll`). */ +export const queryAll = (scope: ParentNode, selector: string): Element[] => [ + ...nativeCall>(scope, 'querySelectorAll', selector), +]; + +/** The closest inclusive ancestor of `el` that matches `selector` (`closest`). */ +export const closest = (el: Element, selector: string) => nativeCall(el, 'closest', selector); + +/** Whether `el` matches `selector` (`matches`). */ +export const matches = (el: Element, selector: string) => nativeCall(el, 'matches', selector); + +/** The element of a document or shadow root with an id (`getElementById`). */ +export const byId = (root: Document | DocumentFragment, id: string) => + nativeCall(root, 'getElementById', id); + +/** A node's root (`getRootNode`). */ +export const rootOf = (node: Node) => nativeCall(node, 'getRootNode'); + +/** An element's border box (`getBoundingClientRect`). */ +export const rectOf = (el: Element) => nativeCall(el, 'getBoundingClientRect'); + +/** A node's `textContent`. */ +export const textOf = (node: Node) => nativeGet(node, 'textContent'); + +/** An HTML element's `innerText`. */ +export const innerTextOf = (el: HTMLElement) => nativeGet(el, 'innerText'); + +/** The document or shadow root a node is in, where its ids resolve; null when detached. */ +export function scopeOf(node: Node): Document | ShadowRoot | null { + const root = rootOf(node); + return isDocument(root) || isShadowRoot(root) ? root : null; +} + +/** A select shown as a drop-down (Chrome's MenuListSelect), not as a list box. */ +export const isMenuList = (el: Element | null): boolean => isHtml(el, 'select') && !el.multiple && el.size <= 1; + +/** Whether an element has focus, in a document that has it. */ +export const isFocused = (el: Element) => el === el.ownerDocument.activeElement && el.ownerDocument.hasFocus(); + +/** The words of a space-separated list. */ +export const words = (list: string) => list.split(' '); + +/** A space-separated list as a set. */ +export const wordSet = (list: string) => new Set(words(list)); + +/** A table from groups of words, "value key key …": each key to its group's value. */ +export function groupTable(groups: string[]): Record { + const table: Record = {}; + for (const group of groups) { + const [value = '', ...keys] = words(group); + for (const key of keys) table[key] = value; + } + return table; +} + +/** + * The outermost closed details a node is in the content of (not in its summary): Chrome makes no + * node for it, as the content is not slotted while closed. Its first summary child is shown. + */ +export function closedDetailsOf(node: Node): HTMLDetailsElement | null { + let found: HTMLDetailsElement | null = null; + for (let child = node, p = domParent(node); p; child = p, p = domParent(p)) + if ( + isHtml(p, 'details') && + !nativeGet(p, 'open') && + child !== domChildren(p).find(c => isHtml(c, 'summary')) + ) + found = p; + return found; +} + +/** + * Why an element is not shown, if it is not: `display: none` on it or an ancestor (no box), or + * `visibility: hidden` (a box, not painted). + */ +export function hiddenReason(el: Element): IgnoredReason | null { + if (!el.isConnected) return 'notRendered'; + for (let n: Node | null = el; n && isElement(n); n = domParent(n)) + if (styleOf(n).display === 'none') return 'notRendered'; + const visibility = styleOf(el).visibility; + return visibility === 'hidden' || visibility === 'collapse' ? 'notVisible' : null; +} + +/** The children of a node as the tree sees them: shadow trees and slots flattened. */ +export function domChildren(node: Node): Node[] { + if (isElement(node)) { + if (node.shadowRoot) return [...node.shadowRoot.childNodes]; + if (isHtml(node, 'slot')) { + const assigned = node.assignedNodes(); + if (assigned.length) return assigned; + } + } + return [...node.childNodes]; +} + +/** Whether an element is inert: it or one of its ancestors in the tree has the inert attribute. */ +export function inInert(el: Element): boolean { + for (let n: Node | null = el; n && isElement(n); n = domParent(n)) if (hasAttr(n, 'inert')) return true; + return false; +} + +/** The parent of a node as the tree sees it: the slot it is assigned to, the host of a shadow root. */ +export function domParent(node: Node): Node | null { + if (isElement(node) || isText(node)) { + const slot = node.assignedSlot; + if (slot) return slot; + } + const parent = node.parentNode; + return isShadowRoot(parent) ? parent.host : parent; +} diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-name.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-name.ts deleted file mode 100644 index d2fb9213..00000000 --- a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-name.ts +++ /dev/null @@ -1,231 +0,0 @@ -// An element's accessible name with the list of where it could come from (`AXValue.sources`), which -// the Accessibility pane shows, and its description. Part of accessibility.js (ax-node.ts). -// -// The name and the description themselves are dom-accessibility-api's (accname 1.2); the sources, -// which only Chrome lists, follow the order and the fields Chrome gives each role. -import type { Protocol } from 'devtools-protocol'; -import { computeAccessibleDescription, computeAccessibleName } from 'dom-accessibility-api'; -import { isDocument, isElement, isHtml, isHtmlElement, isShadowRoot, isText, styleOf } from '../../core/realm'; -import { isFocusable, renderedText } from './ax-tree'; - -type AXValueSource = Protocol.Accessibility.AXValueSource; -type AXRelatedNode = Protocol.Accessibility.AXRelatedNode; - -/** The backend node id of a DOM node, from the agent. */ -export type IdOf = (node: Node) => number; - -/** Roles whose name can come from their content (accname 1.2, plus Chrome's). */ -const NAME_FROM_CONTENTS = new Set([ - 'button', - 'cell', - 'checkbox', - 'columnheader', - 'gridcell', - 'heading', - 'link', - 'menuitem', - 'menuitemcheckbox', - 'menuitemradio', - 'option', - 'radio', - 'rowheader', - 'switch', - 'tab', - 'tooltip', - 'treeitem', - 'DisclosureTriangle', - 'term', -]); - -/** Roles that list no `title` source in Chrome: an element that is only a container of text. */ -const NO_TITLE = new Set(['generic', 'paragraph', 'term', 'definition', 'caption']); - -const computed = (value: string): Protocol.Accessibility.AXValue => ({ type: 'computedString', value }); - -/** White space collapsed and trimmed, as names are. */ -const flat = (text: string) => text.replace(/\s+/g, ' ').trim(); - -/** The text of a related element (a label, an aria-labelledby target): its name from content. */ -function textOf(el: Element): string { - return flat(computeAccessibleName(el, { hidden: true })) || collapsedContentsOf(el); -} - -/** The text of an element's content, for the `contents` source. */ -export function contentsOf(el: Element): string { - return flat(collapsedContentsOf(el)); -} - -/** An element's content text with white space collapsed but not trimmed, as Chrome gives a label's text. */ -function collapsedContentsOf(el: Element): string { - let out = ''; - for (const child of el.childNodes) { - if (isText(child)) out += renderedText(child); - else if (isElement(child)) { - const style = styleOf(child); - if (style.display === 'none' || style.visibility === 'hidden') continue; - const label = child.getAttribute('aria-label')?.trim(); - const text = label || (isHtml(child, 'img') ? (child.alt ?? '') : contentsOf(child)); - out += style.display.startsWith('inline') ? text : ` ${text} `; - } - } - return out.replace(/\s+/g, ' ').replace(/^ /, ''); -} - -/** A form control, which labels name. */ -const isLabelable = (el: Element): el is HTMLElement & { labels: NodeListOf } => - (isHtml(el, 'input') && el.type !== 'hidden') || - isHtml(el, 'button') || - isHtml(el, 'select') || - isHtml(el, 'textarea') || - isHtml(el, 'meter') || - isHtml(el, 'progress') || - isHtml(el, 'output'); - -const isTextField = (el: Element) => - isHtml(el, 'textarea') || (isHtml(el, 'input') && /^(text|search|email|url|tel|password|number|)$/.test(el.type)); - -/** One source, with its value when it has a non-empty one. */ -function source(fields: AXValueSource, value: string): AXValueSource { - return value ? { ...fields, value: computed(value) } : fields; -} - -/** A source read from an attribute, with the attribute's value when present. */ -function attributeSource(el: Element, attribute: string, type: AXValueSource['type'] = 'attribute'): AXValueSource { - const raw = el.getAttribute(attribute); - if (raw === null) return { type, attribute }; - return source({ type, attribute, attributeValue: { type: 'string', value: raw } }, flat(raw)); -} - -/** A related element as name sources list it: its id, and its text. */ -function relatedNode(el: Element, idOf: IdOf): AXRelatedNode { - return { backendDOMNodeId: idOf(el), ...(el.id && { idref: el.id }), text: textOf(el) }; -} - -/** A source naming the element after a related element of its own (a caption, a legend). */ -function nativeSource( - nativeSource: Protocol.Accessibility.AXValueNativeSourceType, - el: Element | null, - idOf: IdOf -): AXValueSource { - if (!el) return { type: 'relatedElement', nativeSource }; - const related = relatedNode(el, idOf); - return source( - { type: 'relatedElement', nativeSource, nativeSourceValue: { type: 'nodeList', relatedNodes: [related] } }, - flat(related.text ?? '') - ); -} - -/** The default label of an input button, which Chrome gives in the browser's language. */ -const BUTTON_LABELS: Record = { submit: 'Submit', reset: 'Reset' }; - -/** The sources of an element's name, in Chrome's order for its role. */ -function sourcesOf(el: Element, role: string, idOf: IdOf): AXValueSource[] { - const sources: AXValueSource[] = []; - // aria-labelledby: the named elements' texts, in order. - const idrefs = el.getAttribute('aria-labelledby'); - if (idrefs === null) sources.push({ type: 'relatedElement', attribute: 'aria-labelledby' }); - else { - const related: AXRelatedNode[] = []; - const root = el.getRootNode(); - for (const idref of idrefs.trim().split(/\s+/).filter(Boolean)) { - const target = isDocument(root) || isShadowRoot(root) ? root.getElementById(idref) : null; - if (target) related.push({ backendDOMNodeId: idOf(target), idref, text: textOf(target) }); - } - sources.push( - source( - { - type: 'relatedElement', - attribute: 'aria-labelledby', - attributeValue: { type: 'idrefList', value: idrefs, relatedNodes: related }, - }, - flat(related.map(r => r.text).join(' ')) - ) - ); - } - sources.push(attributeSource(el, 'aria-label')); - if (isLabelable(el)) { - const labels = [...el.labels]; - if (!labels.length) sources.push({ type: 'relatedElement', nativeSource: 'label' }); - else { - const related = labels.map(label => relatedNode(label, idOf)); - const explicit = labels.some(label => label.htmlFor); - sources.push( - source( - { - type: 'relatedElement', - nativeSource: explicit ? 'labelfor' : 'labelwrapped', - nativeSourceValue: { type: 'nodeList', relatedNodes: related }, - }, - flat(related.map(r => r.text).join(' ')) - ) - ); - } - } - if (isHtml(el, 'img') || isHtml(el, 'area')) sources.push(attributeSource(el, 'alt')); - if (isHtml(el, 'table')) { - sources.push(nativeSource('tablecaption', el.caption, idOf)); - sources.push(attributeSource(el, 'summary')); - } - if (isHtml(el, 'fieldset')) sources.push(nativeSource('legend', el.querySelector(':scope > legend'), idOf)); - const inputButton = isHtml(el, 'input') && /^(submit|reset|button)$/.test(el.type); - if (inputButton) sources.push(attributeSource(el, 'value')); - if (inputButton) sources.push(source({ type: 'contents' }, el.value || BUTTON_LABELS[el.type] || '')); - else if (NAME_FROM_CONTENTS.has(role)) sources.push(source({ type: 'contents' }, contentsOf(el))); - if (isHtmlElement(el) && el.isContentEditable && !isTextField(el)) - sources.push(attributeSource(el, 'aria-placeholder', 'placeholder')); - if (isTextField(el)) { - sources.push(attributeSource(el, 'title')); - sources.push(attributeSource(el, 'placeholder', 'placeholder')); - sources.push(attributeSource(el, 'aria-placeholder', 'placeholder')); - } - if (el.localName === 'svg' && el.namespaceURI === 'http://www.w3.org/2000/svg') { - const title = el.querySelector(':scope > title'); - sources.push(source({ type: 'relatedElement', nativeSource: 'title' }, title ? flat(title.textContent ?? '') : '')); - } - if (!NO_TITLE.has(role) || el.localName === 'section' || isFocusable(el)) sources.push(attributeSource(el, 'title')); - return sources; -} - -/** Marks the sources after the first with a value as superseded; returns that value. */ -function settle(sources: AXValueSource[]): string { - let found = ''; - for (const s of sources) { - if (found) s.superseded = true; - else if (typeof s.value?.value === 'string' && s.value.value) found = s.value.value; - } - return found; -} - -/** An element's name and description (absent when empty). */ -export function nameOf( - el: Element, - role: string, - idOf: IdOf -): { name: Protocol.Accessibility.AXValue; description?: Protocol.Accessibility.AXValue } { - const sources = sourcesOf(el, role, idOf); - const winner = settle(sources); - const name = winner; - const description = flat(computeAccessibleDescription(el)); - return { - name: { ...computed(name), sources }, - ...(description && description !== name && { description: computed(description) }), - }; -} - -/** The document's name: aria-label on the root element, or the title. */ -export function documentNameOf(doc: Document): Protocol.Accessibility.AXValue { - const sources: AXValueSource[] = [ - { type: 'relatedElement', attribute: 'aria-labelledby' }, - { type: 'attribute', attribute: 'aria-label' }, - // Chrome lists aria-label a second time, always superseded. - { type: 'attribute', attribute: 'aria-label', superseded: true }, - source({ type: 'relatedElement', nativeSource: 'title' }, flat(doc.title)), - ]; - return { ...computed(flat(doc.title)), sources }; -} - -/** A text node's name, its rendered text. */ -export function textNameOf(text: Text): Protocol.Accessibility.AXValue { - const value = renderedText(text); - return { ...computed(value), sources: [{ type: 'contents', value: computed(value) }] }; -} diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-node.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-node.ts index 73d1028e..8f1a823c 100644 --- a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-node.ts +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-node.ts @@ -1,9 +1,47 @@ // Entry of accessibility.js, which the Accessibility domain loads on first use (accessibility.ts): // it turns the DOM into CDP AXNodes. Kept out of the bundle like snapDOM, for its size. import type { Protocol } from 'devtools-protocol'; -import { documentNameOf, nameOf, textNameOf, type IdOf } from './ax-name'; -import { INTERNAL_ROLES, TreeShape, isFocusable, roleOf } from './ax-tree'; -import { isDocument, isElement, isHtml, isHtmlElement, isShadowRoot, isText } from '../../core/realm'; +import { + contentsText, + documentNameOf, + inputButtonText, + isNativeTextField, + nameOf, + simplifyName, + targetsOf, + textNameOf, + type IdOf, +} from './name/ax-name'; +import { inDisplayNone } from './name/ax-text'; +import { markerText, type MarkerText } from './marker/ax-marker'; +import { generatedContent, preservesSpace, pseudoHidden, type GeneratedPseudo } from './name/ax-generated'; +import { + attr, + byId, + closedDetailsOf, + groupTable, + hasAttr, + inInert, + innerTextOf, + isFocused, + isMenuList, + matches, + query, + scopeOf, + textOf, +} from './ax-dom'; +import { type Inclusion } from './tree/ax-ignored'; +import { isFocusable, isInternalRole, isRedundantLabel, isSvgLink, roleOf } from './ax-role'; +import { meterOf } from './tree/ax-generic'; +import { TreeShape } from './tree/ax-tree'; +import { isElement, isHtml, isHtmlElement, isText, styleOf } from '../../core/realm'; +import type { Probe } from '../../probe/types'; +import { isVirtual, VirtualNode, type AXRef } from './tree/ax-virtual'; + +// This script has its own copy of core/natives.ts, which found the page's functions when it loaded, on +// demand: the agent gives it those it uses instead (accessibility.ts). +export { useNatives } from '../../core/natives'; +import { nativeGet } from '../../core/natives'; type AXNode = Protocol.Accessibility.AXNode; type AXProperty = Protocol.Accessibility.AXProperty; @@ -12,49 +50,85 @@ type AXPropertyName = Protocol.Accessibility.AXPropertyName; /** The accessibility tree of a document, as CDP AXNodes. */ export interface AXTree { - /** The AXNode of a DOM node: in the tree, or one ignored with why not. */ - node(node: Node): AXNode; - /** The closest node in the tree above a DOM node. */ - parent(node: Node): Node | null; - /** The DOM nodes of a node's children in the tree. */ - children(node: Node): Node[]; - /** Whether a DOM node has a node in the tree. */ - inTree(node: Node): boolean; + /** + * The AXNode of a DOM node: in the tree, or one ignored with why not. `queried`: an ignored node + * keeps its role and name, as queryAXTree gives it in Chrome. + */ + node(node: AXRef, queried?: boolean): AXNode; + /** The closest node in the tree above a node. */ + parent(node: AXRef): AXRef | null; + /** The nodes of a node's children in the tree. */ + children(node: AXRef): AXRef[]; + /** Whether a node is in the tree. */ + inTree(node: AXRef): boolean; + /** + * A node without a DOM node (ax-virtual.ts), by its host and key: `marker` for an element's list + * marker, which has the backend id of its ::marker; `before` and `after` for its generated + * content, with the backend ids of its ::before and ::after. + */ + virtual(host: Node, key: string): AXRef | null; } +/** The backend id of an element's pseudo-element. */ +export type PseudoIdOf = (host: Element, type: 'marker' | 'before' | 'after') => number; + +/** The id of a node without a DOM node, by its host's id and its key: negative, unlike backend ids. */ +export type VirtualIdOf = (hostId: number, key: string) => number; + /** What accessibility.js exports. */ export interface AccessibilityModule { - createAXTree(doc: Document, idOf: IdOf, frameId: string): AXTree; + /** `pseudoIdOf`: the backend id of an element's ::marker, ::before or ::after pseudo-element. */ + createAXTree(doc: Document, idOf: IdOf, frameId: string, virtualIdOf: VirtualIdOf, pseudoIdOf: PseudoIdOf): AXTree; + /** Takes the agent's native functions (`nativesInUse`), past the page's wrappers. */ + useNatives(natives: Pick): void; } const bool = (name: AXPropertyName, value: boolean, type: AXValue['type'] = 'booleanOrUndefined'): AXProperty => ({ name, value: { type, value }, }); +/** A property that is true or false (never undefined). */ +const flag = (name: AXPropertyName, value: boolean) => bool(name, value, 'boolean'); +/** A token property. */ +const token = (name: AXPropertyName, value: string) => prop(name, 'token', value); const prop = (name: AXPropertyName, type: AXValue['type'], value: unknown): AXProperty => ({ name, value: { type, value }, }); -/** A tristate ARIA attribute ("true", "false", "mixed"), if set. */ -const tristate = (value: string | null) => (value === 'true' || value === 'false' || value === 'mixed' ? value : null); - -const isNativeControl = (el: Element) => - isHtml(el, 'input') || isHtml(el, 'button') || isHtml(el, 'select') || isHtml(el, 'textarea'); - /** The idrefs of an attribute, with the nodes they name. */ function idrefList(el: Element, name: AXPropertyName, idOf: IdOf): AXProperty | null { - const value = el.getAttribute(`aria-${name}`); + const value = attr(el, `aria-${name}`); if (value === null) return null; - const root = el.getRootNode(); + const root = scopeOf(el); const relatedNodes: Protocol.Accessibility.AXRelatedNode[] = []; for (const idref of value.trim().split(/\s+/).filter(Boolean)) { - const target = isDocument(root) || isShadowRoot(root) ? root.getElementById(idref) : null; + const target = root && byId(root, idref); if (target) relatedNodes.push({ backendDOMNodeId: idOf(target), idref }); } return { name, value: { type: 'idrefList', value, relatedNodes } }; } +/** + * Whether aria-owns takes none of its targets: Chrome leaves out ids that name no element, targets + * that are not rendered or carry aria-hidden themselves (one inside an aria-hidden subtree is still + * taken) or sit in a meter, and those visibility: hidden or inert, which it moves but ignores; and drops the relation + * when none is left. + */ +function ownsNothing(el: Element): boolean { + return ( + !!scopeOf(el) && + targetsOf(el, 'aria-owns').every( + t => + inDisplayNone(t) || + attr(t, 'aria-hidden') === 'true' || + !!meterOf(t) || + /^(hidden|collapse)$/.test(styleOf(t).visibility) || + inInert(t) + ) + ); +} + /** The nesting level of a list item: how many lists hold it. */ function listLevel(el: Element): number { let level = 0; @@ -62,150 +136,786 @@ function listLevel(el: Element): number { return Math.max(level, 1); } +/** A tristate ARIA attribute ("true", "false", "mixed"), if set. */ +const tristate = (value: string | null) => (value === 'true' || value === 'false' || value === 'mixed' ? value : null); + +/** A true/false ARIA attribute, if set to either. */ +const ariaBool = (el: Element, name: string) => { + const value = attr(el, name)?.trim().toLowerCase(); + return value === 'true' ? true : value === 'false' ? false : null; +}; + +/** A number ARIA attribute, if set to one. */ +const ariaNumber = (el: Element, name: string) => { + const value = attr(el, name); + if (value === null || !value.trim()) return null; + const n = Number(value); + return Number.isFinite(n) ? n : null; +}; + +/** Form-associated (listed) elements: those Chrome checks the validity of. */ +const isListed = (el: Element) => + isHtmlElement(el) && /^(input|button|select|textarea|fieldset|output|object)$/.test(el.localName); + +/** Input types whose control is a text field (Chrome's atomic text field). */ +const TEXT_INPUT = /^(text|search|email|url|tel|password)$/; + +/** An input or textarea that edits text. */ +const isTextField = (el: Element): el is HTMLInputElement | HTMLTextAreaElement => + isHtml(el, 'textarea') || (isHtml(el, 'input') && TEXT_INPUT.test(el.type)); + +/** The kind of combobox, as Chrome tells them apart: a select, a text field, or anything else. */ +function comboboxKind(el: Element, role: string): 'select' | 'textField' | 'button' | null { + if (role !== 'combobox') return null; + if (isMenuList(el)) return 'select'; + return isTextField(el) ? 'textField' : 'button'; +} + +/** The roles Chrome gives a range (valuemin, valuemax, valuetext and a number value). */ +function isRange(el: Element, role: string): boolean { + if (/^(meter|progressbar|scrollbar|slider|spinbutton)$/.test(role)) return true; + // A separator is a splitter, with a range, only when focusable (not by contenteditable). + return role === 'separator' && isFocusable(el) && !(isHtmlElement(el) && el.isContentEditable); +} + +/** Whether an input is Chrome's native slider or spin button, whose range comes from the input. */ +const isNativeRange = (el: Element): el is HTMLInputElement => + isHtml(el, 'input') && (el.type === 'range' || el.type === 'number'); + +/** A range's minimum and maximum, as Chrome gives them (0 when it has none). */ +function rangeBounds(el: Element, role: string): { min: number | null; max: number | null } { + const implicit = role === 'spinbutton' ? null : 0; + const min = ariaNumber(el, 'aria-valuemin'); + const max = ariaNumber(el, 'aria-valuemax'); + if (isHtml(el, 'meter')) return { min: min ?? el.min, max: max ?? el.max }; + return { min: min ?? implicit, max: max ?? (implicit === null ? null : 100) }; +} + +/** An ARIA range's current value, aria-valuenow or the default ARIA gives its role. */ +function rangeValue(el: Element, role: string): number | null { + const { min, max } = rangeBounds(el, role); + const now = ariaNumber(el, 'aria-valuenow'); + if (now !== null) { + if (min !== null && now < min) return min; + if (max !== null && now > max) return max; + return now; + } + if (isHtml(el, 'meter')) return el.value; + if (role === 'scrollbar' || role === 'slider') return min !== null && max !== null ? (min + max) / 2 : 50; + return role === 'separator' ? 50 : role === 'meter' ? (min ?? 0) : role === 'spinbutton' ? 0 : null; +} + +/** A password's value masked as Chrome shows it, with the field's -webkit-text-security. */ +function masked(el: HTMLInputElement, value: string): string { + const security = ( + styleOf(el) as CSSStyleDeclaration & { + webkitTextSecurity?: string; + } + ).webkitTextSecurity; + const mask = security === 'circle' ? '◦' : security === 'square' ? '■' : security === 'none' ? '' : '•'; + return mask ? mask.repeat(value.length) : value; +} + +/** Input types whose value Chrome does not give (it would be "on" or the button's label). */ +const VALUELESS_INPUT = /^(button|checkbox|image|radio|reset|submit|file|hidden)$/; + /** An element's value (`AXNode.value`), for the roles Chrome gives one. */ function valueOf(el: Element, role: string): AXValue | undefined { - if (isHtml(el, 'input') && (el.type === 'range' || el.type === 'number')) + if (isNativeRange(el)) return Number.isNaN(el.valueAsNumber) ? undefined : { type: 'number', value: el.valueAsNumber }; - if (isHtml(el, 'progress') && el.hasAttribute('value')) return { type: 'number', value: el.value }; - if ((isHtml(el, 'input') || isHtml(el, 'textarea')) && /^(textbox|searchbox)$/.test(role) && el.value) - return { type: 'string', value: el.value }; - if (isHtml(el, 'select') && role === 'combobox') { + if (isHtml(el, 'progress')) return hasAttr(el, 'value') ? { type: 'number', value: el.value } : undefined; + if (isRange(el, role)) { + const value = rangeValue(el, role); + return value === null ? undefined : { type: 'number', value }; + } + const text = textValueOf(el, role); + return text ? { type: 'string', value: text } : undefined; +} + +/** The text value of a control (Chrome's GetValueForControl), or of an editable element. */ +function textValueOf(el: Element, role: string): string { + if (isHtml(el, 'select')) { + if (!isMenuList(el)) return ''; const option = el.selectedOptions[0]; - return { type: 'string', value: option ? option.text.trim() : '' }; + return option ? (attr(option, 'aria-label') ?? option.label.trim()) : ''; + } + if (isHtml(el, 'textarea')) return el.value; + if (isHtml(el, 'input')) { + if (VALUELESS_INPUT.test(el.type)) return ''; + return el.type === 'password' ? masked(el, el.value) : el.value; } - if (isEditingHost(el) && el.textContent) return { type: 'string', value: el.textContent }; - return undefined; + // A focusable ARIA combobox (Chrome's ComboBoxMenuButton) shows its content as its value. + if (comboboxKind(el, role) === 'button') return isFocusable(el) ? contentsText(el) : ''; + // An editing host's text as shown, its line breaks kept. + if (isEditingHost(el)) return innerTextOf(el as HTMLElement); + if (role === 'textbox' || role === 'searchbox') return textOf(el) ?? ''; + return ''; } /** An element with contenteditable on it (not inherited). */ const isEditingHost = (el: Element) => isHtmlElement(el) && el.isContentEditable && !(el.parentElement?.isContentEditable ?? false); +/** What content in an editing host edits: plain text under contenteditable=plaintext-only. */ +function editableKind(el: Element | null): 'richtext' | 'plaintext' | null { + if (!isHtmlElement(el) || !el.isContentEditable) return null; + let host: HTMLElement = el; + while (host.parentElement?.isContentEditable) host = host.parentElement; + return attr(host, 'contenteditable')?.trim().toLowerCase() === 'plaintext-only' ? 'plaintext' : 'richtext'; +} + /** aria-haspopup's popup, `true` meaning a menu. */ function hasPopup(el: Element): string | null { - const value = el.getAttribute('aria-haspopup'); + const value = attr(el, 'aria-haspopup'); if (value === 'true') return 'menu'; return value && /^(menu|listbox|tree|grid|dialog)$/.test(value) ? value : null; } -/** An element's properties, in Chrome's order. */ -function propertiesOf(el: Element, role: string, idOf: IdOf, nameSources: AXValue['sources']): AXProperty[] { - const out: AXProperty[] = []; - const disabled = el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true'; - if (disabled) out.push(bool('disabled', true, 'boolean')); - const invalid = el.getAttribute('aria-invalid'); - if (isNativeControl(el) || isHtml(el, 'fieldset') || invalid !== null) - out.push(prop('invalid', 'token', invalid && invalid !== 'false' ? invalid : 'false')); - if (isFocusable(el)) out.push(bool('focusable', true)); - if (el === el.ownerDocument.activeElement && el.ownerDocument.hasFocus()) out.push(bool('focused', true)); - const field = (isHtml(el, 'input') || isHtml(el, 'textarea')) && /^(textbox|searchbox|spinbutton)$/.test(role); - const readOnly = field && el.readOnly; - if (field) out.push(prop('editable', 'token', 'plaintext')); - else if (isEditingHost(el)) out.push(prop('editable', 'token', 'richtext')); - if ((field && !readOnly && !disabled) || (isHtml(el, 'input') && el.type === 'range') || isHtml(el, 'hr')) - out.push(bool('settable', true)); - if (isHtml(el, 'select') && role === 'combobox') { - out.push(prop('hasPopup', 'token', 'menu')); - out.push(bool('expanded', false)); - } else { - const popup = hasPopup(el); - if (popup) out.push(prop('hasPopup', 'token', popup)); +/** Whether a native control's value is valid, as Chrome tells (AXNodeObject::IsValidFormControl). */ +function isValidControl(el: Element): boolean { + const control = el as HTMLInputElement; + if (!control.validity) return true; + if (control.validity.customError) return false; + if (!control.willValidate || control.validity.valid) return true; + // An empty required text field is not reported invalid: it is already said to be required. + return isTextField(el) && el.required && !el.value; +} + +/** + * Roles that take aria-orientation, with the orientation ARIA gives them by default, as + * "orientation role role …"; combobox, radiogroup and treegrid take it with no default. + */ +const ORIENTATION = groupTable([ + 'vertical listbox menu scrollbar tree', + 'horizontal menubar separator slider tablist toolbar', +]); + +/** An element's orientation, explicit or the role's default. */ +function orientationOf(el: Element, role: string): string | null { + const explicit = attr(el, 'aria-orientation')?.trim().toLowerCase(); + const valid = explicit === 'horizontal' || explicit === 'vertical' ? explicit : null; + if (/^(combobox|radiogroup|treegrid)$/.test(role)) return valid; + return role in ORIENTATION ? (valid ?? ORIENTATION[role] ?? null) : null; +} + +/** Roles whose items Chrome says are selected or not even without aria-selected. */ +const SELECT_ITEM = /^(option|tab|treeitem)$/; +/** The widgets that hold such items. */ +const CONTAINER_WIDGET = /^(listbox|tablist|tree|treegrid|grid|combobox|menu|menubar)$/; + +/** The selected state Chrome gives an option, tab or tree item, if any. */ +function selectedOf(el: Element, role: string): boolean | null { + const explicit = ariaBool(el, 'aria-selected'); + if (explicit !== null) return explicit; + if (isHtml(el, 'option')) return el.selected; + if (!SELECT_ITEM.test(role)) return null; + if (isFocused(el)) return true; + let container: Element | null = el.parentElement; + while (container && !CONTAINER_WIDGET.test(roleOf(container))) container = container.parentElement; + if (container) { + const multiple = ariaBool(container, 'aria-multiselectable') ?? (isHtml(container, 'select') && container.multiple); + if (multiple || query(container, '[aria-checked]')) return null; } - if (role === 'DisclosureTriangle' && isHtml(el.parentElement, 'details')) - out.push(bool('expanded', el.parentElement.open)); - else if (!isHtml(el, 'select')) { - const expanded = el.getAttribute('aria-expanded'); - if (expanded === 'true' || expanded === 'false') out.push(bool('expanded', expanded === 'true')); + return false; +} + +/** The nesting level Chrome gives an element (aria-level, or counted for some roles). */ +function levelOf(el: Element, role: string): number | null { + const ariaLevel = Number(attr(el, 'aria-level')); + if (Number.isInteger(ariaLevel) && ariaLevel > 0) return ariaLevel; + // A heading without a level is at level 2, as in Chrome. + if (/^h[1-6]$/.test(el.localName)) return Number(el.localName[1]); + if (role === 'heading') return 2; + if (role === 'listitem') return listLevel(el); + if (role === 'treeitem') { + let level = 1; + for (let p = el.parentElement; p; p = p.parentElement) { + const r = roleOf(p); + if (r === 'group') level++; + else if (r === 'tree') break; + } + return level; } - if (field && role === 'textbox') { - out.push(bool('multiline', isHtml(el, 'textarea'), 'boolean')); - out.push(bool('readonly', readOnly, 'boolean')); + return null; +} + +/** Roles with a readonly state (Chrome's RoleAllowsReadonly). */ +const READONLY_ROLE = /^(grid|gridcell|textbox|columnheader|rowheader|treegrid)$/; +/** Roles with a required state (Chrome's RoleAllowsRequired; combobox but not select). */ +const REQUIRED_ROLE = /^(gridcell|listbox|radiogroup|spinbutton|textbox|tree|columnheader|rowheader|treegrid)$/; +/** Roles whose readonly comes from aria-readonly (ui::IsReadOnlySupported and grid cells). */ +const ARIA_READONLY_ROLE = + /^(checkbox|ColorWell|combobox|Date|DateTime|grid|gridcell|InputTime|listbox|menuitemcheckbox|menuitemradio|radio|radiogroup|searchbox|slider|spinbutton|switch|textbox|treegrid)$/; +/** Roles whose value can be set (Chrome's CanSetValueAttribute). */ +const SETTABLE_ROLE = /^(ColorWell|Date|DateTime|InputTime|scrollbar|searchbox|slider|spinbutton|separator|textbox)$/; + +/** Whether an element is read-only, natively or by aria-readonly (Chrome's Restriction). */ +function isReadOnly(el: Element, role: string): boolean { + // A text field or a number field (ax-name's native text fields). + if (isNativeTextField(el) && el.readOnly) return true; + const contentEditable = hasAttr(el, 'contenteditable'); + const explicit = ariaBool(el, 'aria-readonly'); + if (!contentEditable && explicit !== null && ARIA_READONLY_ROLE.test(role)) return explicit; + if (/^(gridcell|columnheader|rowheader)$/.test(role)) { + const grid = el.parentElement?.parentElement; + const gridRole = grid ? roleOf(grid) : null; + if (grid && (gridRole === 'grid' || gridRole === 'treegrid')) return ariaBool(grid, 'aria-readonly') === true; } - if (field && role !== 'searchbox') out.push(bool('required', el.required, 'boolean')); - if (role === 'columnheader' || role === 'rowheader') { - out.push(bool('readonly', false, 'boolean')); - out.push(bool('required', false, 'boolean')); + return false; +} + +/** The politeness of the live regions by role (ARIA's implicit aria-live), as "politeness role role …". */ +const IMPLICIT_LIVE = groupTable(['assertive alert', 'polite status log', 'off marquee timer']); + +/** Live region properties of a live region's root: its politeness, atomic and relevant. */ +function liveRegion(el: Element, role: string): AXProperty[] { + const live = attr(el, 'aria-live')?.trim().toLowerCase() || IMPLICIT_LIVE[role]; + if (!live || live === 'off') return []; + // Of the live regions by role, alert and status are atomic. + const atomic = ariaBool(el, 'aria-atomic') ?? (role === 'alert' || role === 'status'); + const relevant = attr(el, 'aria-relevant')?.trim() || 'additions text'; + return [token('live', live), flag('atomic', atomic), prop('relevant', 'tokenList', relevant)]; +} + +/** An element's properties, in Chrome's order (inspector_type_builder_helper.cc). */ +function propertiesOf(el: Element, role: string, idOf: IdOf, nameSources: AXValue['sources']): AXProperty[] { + const out: AXProperty[] = liveRegion(el, role); + const combobox = comboboxKind(el, role); + // Global states. + // An object element that shows no content (no plugin, no frame) is disabled. + const emptyObject = isHtml(el, 'object') && !el.contentWindow; + // A disabled optgroup is not said to be disabled: its options are. + const disabled = + (matches(el, ':disabled') && !isHtml(el, 'optgroup')) || attr(el, 'aria-disabled') === 'true' || emptyObject; + if (disabled) out.push(flag('disabled', true)); + const invalid = attr(el, 'aria-invalid'); + if (invalid && invalid !== 'false') out.push(token('invalid', invalid)); + else if (isListed(el)) out.push(token('invalid', invalid === null && !isValidControl(el) ? 'true' : 'false')); + else if (invalid !== null) out.push(token('invalid', 'false')); + if (isFocusable(el) || (isHtml(el, 'dialog') && el.open)) out.push(bool('focusable', true)); + if (isFocused(el)) out.push(bool('focused', true)); + const field = isTextField(el) || isNativeRange(el); + const editableField = field && (/^(textbox|searchbox|spinbutton)$/.test(role) || combobox === 'textField'); + const readOnly = isReadOnly(el, role); + if (editableField) out.push(token('editable', 'plaintext')); + else if (editableKind(el)) + // The host and the elements in it; Chrome says a line break edits plain text, whatever the host. + out.push(token('editable', isHtml(el, 'br') ? 'plaintext' : (editableKind(el) ?? 'richtext'))); + const settable = SETTABLE_ROLE.test(role) || combobox === 'textField'; + if (settable && !disabled && !readOnly) out.push(bool('settable', true)); + // A text field's datalist completes it. + if (combobox === 'textField' && isHtml(el, 'input') && el.list) out.push(token('autocomplete', 'list')); + // Widget properties. + if (combobox === 'select') out.push(token('hasPopup', 'menu')); + else { + const popup = hasPopup(el) ?? (combobox ? 'listbox' : null); + if (popup) out.push(token('hasPopup', popup)); } - if (role === 'tablist' || role === 'listbox' || role === 'grid' || role === 'tree') - out.push(bool('multiselectable', el.getAttribute('aria-multiselectable') === 'true', 'boolean')); - if (role === 'tablist' || role === 'separator' || (isHtml(el, 'input') && el.type === 'range')) - out.push(prop('orientation', 'token', el.getAttribute('aria-orientation') ?? 'horizontal')); - if (isHtml(el, 'input') && (el.type === 'range' || el.type === 'number')) { - const max = el.type === 'range' ? 100 : 0; - out.push(prop('valuemin', 'number', Number(el.min || 0))); - out.push(prop('valuemax', 'number', Number(el.max || max))); - out.push(prop('valuetext', 'string', el.value)); + const level = levelOf(el, role); + if (level !== null) out.push(prop('level', 'integer', level)); + if (/^(tablist|listbox|grid|tree|treegrid)$/.test(role)) { + const multiple = ariaBool(el, 'aria-multiselectable') ?? (isHtml(el, 'select') && el.multiple); + out.push(flag('multiselectable', multiple)); } - if (isHtml(el, 'progress')) { - out.push(prop('valuemin', 'number', 0)); - out.push(prop('valuemax', 'number', el.max)); - out.push(prop('valuetext', 'string', '')); + const orientation = isNativeRange(el) && el.type === 'range' ? 'horizontal' : orientationOf(el, role); + if (orientation) out.push(token('orientation', orientation)); + if (role === 'textbox') + out.push(flag('multiline', isHtml(el, 'textarea') || (ariaBool(el, 'aria-multiline') ?? isEditingHost(el)))); + if (READONLY_ROLE.test(role)) out.push(flag('readonly', readOnly)); + if (REQUIRED_ROLE.test(role) || combobox === 'textField' || combobox === 'button') { + const native = (isTextField(el) || isNativeRange(el) || isHtml(el, 'select')) && el.required; + out.push(flag('required', native || attr(el, 'aria-required') === 'true')); } - if (isHtml(el, 'input') && (el.type === 'checkbox' || el.type === 'radio')) + const range = (min: number, max: number, text: string) => + out.push(prop('valuemin', 'number', min), prop('valuemax', 'number', max), prop('valuetext', 'string', text)); + if (isNativeRange(el)) range(Number(el.min || 0), Number(el.max || (el.type === 'range' ? 100 : 0)), el.value); + else if (isHtml(el, 'progress')) range(0, el.max, ''); + else if (isRange(el, role)) { + const { min, max } = rangeBounds(el, role); + // Chrome gives an ARIA range no valuetext, whatever aria-valuetext says. + range(min ?? 0, max ?? 0, ''); + } + // Widget states. + const pressed = role === 'button' ? tristate(attr(el, 'aria-pressed')) : null; + if (pressed) out.push(prop('pressed', 'tristate', pressed)); + else if (isHtml(el, 'input') && (el.type === 'checkbox' || el.type === 'radio')) out.push(prop('checked', 'tristate', el.indeterminate ? 'mixed' : String(el.checked))); else if (/^(checkbox|radio|switch|menuitemcheckbox|menuitemradio)$/.test(role)) - out.push(prop('checked', 'tristate', tristate(el.getAttribute('aria-checked')) ?? 'false')); - if (isHtml(el, 'option')) out.push(bool('selected', el.selected)); - else if (el.getAttribute('aria-selected') === 'true' || el.getAttribute('aria-selected') === 'false') - out.push(bool('selected', el.getAttribute('aria-selected') === 'true')); - // A heading without a level is at level 2, as in Chrome. - const level = /^h[1-6]$/.test(el.localName) - ? Number(el.localName[1]) - : role === 'heading' - ? 2 - : role === 'listitem' - ? listLevel(el) - : null; - const ariaLevel = Number(el.getAttribute('aria-level')); - if (ariaLevel > 0) out.push(prop('level', 'integer', ariaLevel)); - else if (level !== null) out.push(prop('level', 'integer', level)); - if (role === 'link' && (isHtml(el, 'a') || isHtml(el, 'area'))) out.push(prop('url', 'string', el.href)); - if (role === 'image' && isHtml(el, 'img') && el.src) out.push(prop('url', 'string', el.src)); - for (const name of ['describedby', 'owns', 'controls', 'flowto', 'details'] as const) { + out.push(prop('checked', 'tristate', tristate(attr(el, 'aria-checked')) ?? 'false')); + if (combobox === 'select') out.push(bool('expanded', false)); + else if (role === 'DisclosureTriangle' && isHtml(el.parentElement, 'details')) + out.push(bool('expanded', el.parentElement.open)); + else if (!isHtml(el, 'select')) { + const expanded = attr(el, 'aria-expanded'); + if (expanded === 'true' || expanded === 'false') out.push(bool('expanded', expanded === 'true')); + } + const selected = selectedOf(el, role); + // A disabled option is not said to be selected or not. + if (selected !== null && !(disabled && isHtml(el, 'option'))) out.push(bool('selected', selected)); + if (role === 'dialog' || role === 'alertdialog') + out.push(flag('modal', ariaBool(el, 'aria-modal') ?? (isHtml(el, 'dialog') && matches(el, ':modal')))); + // Relationships, then sparse attributes. + for (const name of ['describedby', 'owns'] as const) { + const list = idrefList(el, name, idOf); + if (list && !(name === 'describedby' && !list.value.relatedNodes?.length) && !(name === 'owns' && ownsNothing(el))) + out.push(list); + } + const url = urlOf(el, role); + if (url) out.push(prop('url', 'string', url)); + const active = activeDescendant(el); + if (active) + out.push({ + name: 'activedescendant', + value: { + type: 'idref', + relatedNodes: [ + { + backendDOMNodeId: idOf(active), + ...(active.id && { idref: active.id }), + }, + ], + }, + }); + for (const name of ['controls', 'details', 'flowto'] as const) { const list = idrefList(el, name, idOf); if (list) out.push(list); } // labelledby: the nodes of the source that named it, aria-labelledby's or the labels'. const named = nameSources?.find(s => s.value && !s.superseded); const related = named?.attributeValue?.relatedNodes ?? named?.nativeSourceValue?.relatedNodes; - if (related) out.push({ name: 'labelledby', value: { type: 'nodeList', relatedNodes: related } }); + if (related) + out.push({ + name: 'labelledby', + value: { type: 'nodeList', relatedNodes: related }, + }); return out; } +/** The active descendant: a list box select's selected option, or aria-activedescendant's target. */ +function activeDescendant(el: Element): Element | null { + if (isHtml(el, 'select')) { + if (isMenuList(el)) return null; + const selected = el.selectedOptions; + return selected[selected.length - 1] ?? null; + } + const idref = attr(el, 'aria-activedescendant')?.trim(); + const scope = idref ? scopeOf(el) : null; + return (idref && scope && byId(scope, idref)) || null; +} + +/** The url Chrome gives a link (its href) or an image (the source it shows). */ +function urlOf(el: Element, role: string): string | null { + if (role === 'link' && (isHtml(el, 'a') || isHtml(el, 'area'))) return el.href; + if (role === 'link' && isSvgLink(el)) return new URL(attr(el, 'href') ?? '', el.baseURI).href; + if (role === 'image' && isHtml(el, 'img')) return el.currentSrc.trim() || null; + // An image input gives its image's address. + if (isHtml(el, 'input') && el.type === 'image') return el.src || null; + return null; +} + /** A role as CDP gives it: ARIA roles as `role`, Chrome's own as `internalRole`. */ const roleValue = (role: string): AXValue => ({ - type: INTERNAL_ROLES.has(role) ? 'internalRole' : 'role', + type: isInternalRole(role) ? 'internalRole' : 'role', value: role, }); -export function createAXTree(doc: Document, idOf: IdOf, frameId: string): AXTree { - const shape = new TreeShape(doc); - const id = (node: Node) => String(idOf(node)); - const links = (node: Node, base: AXNode): AXNode => { - const parent = shape.parent(node); +/** An ignored node's role and name, without their sources, as Chrome's queryAXTree gives them. */ +function ignoredAsQueried(node: Text | Element, reason: string): Pick { + const role = isText(node) ? 'StaticText' : roleOf(node); + // A list box's hidden option has no text laid out to name it. + const name = + isHtml(node, 'option') && reason === 'notRendered' + ? { value: '' } + : isText(node) + ? textNameOf(node) + : nameOf(node, role, () => 0).name; + return { role: roleValue(role), name: { type: 'computedString', value: name.value } }; +} + +/** A node without a DOM node, as Chrome gives those of the user-agent shadow trees. */ +function virtualNode(node: VirtualNode, queried: boolean | undefined): Omit { + const inclusion = node.inclusion; + if (inclusion.kind !== 'included') + return { + ignored: true, + ignoredReasons: + inclusion.kind === 'ignored' && inclusion.noReason + ? [] + : [{ name: inclusion.reason, value: { type: 'boolean', value: true } }], + // queryAXTree gives the generic elements they are. + role: { type: 'role', value: queried ? node.role : 'none' }, + ...(queried && { name: { type: 'computedString', value: '' } }), + }; + const editable = node.editable ? [token('editable', 'plaintext')] : []; + if (node.role === 'StaticText' || node.role === 'LineBreak') + return { + ignored: false, + role: roleValue(node.role), + name: { + type: 'computedString', + value: node.text, + sources: [{ type: 'contents', value: { type: 'computedString', value: node.text } }], + }, + properties: editable, + }; + // A details' slot lists no sources, as a slot cannot be named. + if (isHtml(node.host, 'details')) + return { ignored: false, role: roleValue(node.role), name: { type: 'computedString', value: '' }, properties: [] }; + const sources: Protocol.Accessibility.AXValueSource[] = [ + { type: 'relatedElement', attribute: 'aria-labelledby' }, + { type: 'attribute', attribute: 'aria-label' }, + ]; + if (node.role === 'MenuListPopup') sources.push({ type: 'attribute', attribute: 'title' }); + return { + ignored: false, + role: roleValue(node.role), + name: { type: 'computedString', value: '', sources }, + properties: editable, + }; +} + +/** The text a text field or input button shows (ax-virtual.ts). */ +const fieldText = (el: Element) => + isHtml(el, 'input') && /^(submit|reset|button)$/.test(el.type) ? inputButtonText(el) : textValueOf(el, roleOf(el)); + +/** An element's list marker in the tree: its text, its node, and why it is ignored. */ +interface Marker { + text: MarkerText; + /** Key `marker`, with one StaticText child per run of its text, keys `marker:0`, `marker:1`… */ + node: VirtualNode; + /** The reason of an ignored marker: in a summary, or in a list item hidden or not visible. */ + ignoredBy: 'presentationalRole' | 'ariaHiddenSubtree' | 'notVisible' | null; + /** + * A list item of a native list given another role (`
  • `): Chrome makes its + * marker an ignored node of no role, whose text children are StaticText nodes in the tree. + */ + textOnly: boolean; +} + +/** Whether an element is a list item of a ul, ol or menu with a role attribute other than list. */ +const inRoledList = (el: Element) => + el.localName === 'li' && + /^(ul|ol|menu)$/.test(el.parentElement?.localName ?? '') && + // Chrome compares the role attribute as written, as for the item's own inclusion (ax-tree.ts). + !/^(|list|directory)$/.test((el.parentElement && attr(el.parentElement, 'role')) ?? ''); + +const PRESENTATIONAL: Inclusion = { kind: 'ignored', reason: 'presentationalRole' }; + +/** Whether a node is a list marker or one of its children (ax-marker.ts). */ +const isMarker = (node: AXRef): node is VirtualNode => isVirtual(node) && /^marker\b/.test(node.key); +/** Whether a node is a ::before or ::after or one of their children (ax-generated.ts). */ +const isGenerated = (node: AXRef): node is VirtualNode => isVirtual(node) && /^(before|after)\b/.test(node.key); +/** The pseudo-element nodes, which have the backend ids of their pseudo-elements. */ +const PSEUDO_KEYS = new Set(['marker', 'before', 'after']); +const UNINTERESTING: Inclusion = { kind: 'ignored', reason: 'uninteresting' }; + +export function createAXTree( + doc: Document, + idOf: IdOf, + frameId: string, + virtualIdOf: VirtualIdOf, + pseudoIdOf: PseudoIdOf +): AXTree { + const shape = new TreeShape(doc, fieldText); + // The markers' nodes, made once per tree. + const markers = new Map(); + const markerOf = (host: Element): Marker | null => { + let marker = markers.get(host); + if (marker !== undefined) return marker; + const inclusion = shape.inclusion(host); + const text = shape.inTree(host) ? markerText(host) : null; + // A list item aria-hidden or not visible keeps its marker ignored and empty; not one aria-hidden + // by an ancestor. + const hidden = inclusion.kind === 'ignored' && /^(ariaHidden|notVisible)/.test(inclusion.reason); + if (!text || (inclusion.kind === 'ignored' && inclusion.reason === 'ariaHiddenSubtree')) marker = null; + else { + const textOnly = !hidden && !text.alt && inRoledList(host); + const ignoredBy = hidden + ? inclusion.reason === 'notVisible' + ? 'notVisible' + : 'ariaHiddenSubtree' + : textOnly || roleOf(host) === 'DisclosureTriangle' + ? 'presentationalRole' + : null; + const parts = (hidden || text.alt ? [] : text.parts).map((part, i) => { + // A quote: an ignored node over a StaticText of its text, as Chrome lays it out apart. + if (text.quotes[i]) { + const quoted = new VirtualNode(host, `marker:${i}:0`, 'StaticText', { kind: 'included' }); + quoted.text = part; + const quote = new VirtualNode(host, `marker:${i}`, 'none', UNINTERESTING, [quoted]); + quoted.parent = quote; + return quote; + } + const child = new VirtualNode( + host, + `marker:${i}`, + 'StaticText', + textOnly ? { kind: 'included' } : PRESENTATIONAL + ); + child.text = part; + return child; + }); + const node = new VirtualNode( + host, + 'marker', + text.alt ? 'StaticText' : 'ListMarker', + ignoredBy ? { kind: 'ignored', reason: ignoredBy } : { kind: 'included' }, + parts + ); + for (const part of parts) part.parent = node; + marker = { text, node, ignoredBy, textOnly }; + } + markers.set(host, marker); + return marker; + }; + // The nodes of the ::before and ::after pseudo-elements, made once per tree. + const generated = new Map(); + const generatedOf = (host: Element, pseudo: GeneratedPseudo): VirtualNode | null => { + const key = pseudo.slice(2); + const known = generated.get(`${idOf(host)}:${key}`); + if (known !== undefined) return known; + let node: VirtualNode | null = null; + const inclusion = shape.inclusion(host); + const hidden = inclusion.kind === 'ignored' && /^(ariaHidden|notVisible|notRendered)/.test(inclusion.reason); + // A table part kept alone keeps a pseudo-element's node too, ignored and empty, but where it + // has no box. + const alone = inclusion.kind === 'ignored' && shape.inTree(host) && shape.keptAlone(host); + const content = shape.inTree(host) && (alone || !hidden) ? generatedContent(host, pseudo) : null; + if (alone) { + // Hidden as what is under its host: an aria-hidden host is its aria-hidden root. + if (content && inclusion.reason !== 'notRendered') + node = new VirtualNode( + host, + key, + 'none', + inclusion.reason === 'ariaHiddenElement' + ? { kind: 'ignored', reason: 'ariaHiddenSubtree', hiddenRoot: host } + : { ...inclusion } + ); + } else if (content && 'alt' in content) { + node = new VirtualNode(host, key, 'StaticText', { kind: 'included' }); + node.text = content.alt; + } else if (content && pseudoHidden(host, pseudo)) + node = new VirtualNode(host, key, 'none', { kind: 'ignored', reason: 'notVisible' }); + else if (content) { + // A label that only repeats its checkbox's or radio's name has its inline text ignored, as + // its own text is. + const textInclusion: Inclusion = + content.box === 'inline' && isRedundantLabel(host) + ? { kind: 'ignored', reason: 'presentationalRole' } + : { kind: 'included' }; + const parts = content.parts.map((part, i) => { + if (part.kind === 'image') return new VirtualNode(host, `${key}:${i}`, 'image', { kind: 'included' }); + const text = new VirtualNode( + host, + `${key}:${i}${part.kind === 'quote' ? ':0' : ''}`, + 'StaticText', + textInclusion + ); + text.text = part.text; + // Its name has the runs of preserved white space collapsed, as Chrome's names do. + if (preservesSpace(host, pseudo)) text.name = simplifyName(part.text); + if (part.kind !== 'quote') return text; + const quote = new VirtualNode(host, `${key}:${i}`, 'none', UNINTERESTING, [text]); + text.parent = quote; + return quote; + }); + const wrap = (role: string, inclusion: Inclusion, k: string, raw: VirtualNode[]) => { + const box = new VirtualNode(host, k, role, inclusion, raw); + for (const part of raw) part.parent = box; + return box; + }; + node = + content.box === 'inline' + ? wrap('none', UNINTERESTING, key, parts) + : content.box === 'block' + ? wrap('generic', { kind: 'included' }, key, parts) + : wrap('none', UNINTERESTING, key, [wrap('generic', { kind: 'included' }, `${key}:item`, parts)]); + } + generated.set(`${idOf(host)}:${key}`, node); + return node; + }; + // A marker has its ::marker's backend id, as in Chrome, and the node of a ::before or ::after its + // pseudo-element's; the other nodes without a DOM node get ids below 0, kept for the session + // (accessibility.ts). + const id = (node: AXRef) => + String( + !isVirtual(node) + ? idOf(node) + : PSEUDO_KEYS.has(node.key) + ? pseudoIdOf(node.host, node.key as 'marker' | 'before' | 'after') + : virtualIdOf(idOf(node.host), node.key) + ); + const children = (node: AXRef): AXRef[] => { + if (isMarker(node) || isGenerated(node)) return node.raw; + const own = shape.children(node); + if (!isElement(node)) return own; + const marker = markerOf(node); + const before = generatedOf(node, '::before'); + const after = generatedOf(node, '::after'); + // What aria-owns moves here comes after the ::after, as in Chrome. + const moved = shape.ownedBy(node); + const inPlace = moved.length ? own.filter(c => !moved.includes(c as Element)) : own; + const movedIn = moved.length ? own.filter(c => moved.includes(c as Element)) : []; + return [ + ...(marker ? [marker.node] : []), + ...(before ? [before] : []), + ...inPlace, + ...(after ? [after] : []), + ...movedIn, + ]; + }; + const parent = (node: AXRef): AXRef | null => + isMarker(node) || isGenerated(node) ? node.parent : shape.parent(node); + const links = (node: AXRef, base: AXNode): AXNode => { + const up = parent(node); return { ...base, - ...(parent && { parentId: id(parent) }), - childIds: shape.children(node).map(id), - backendDOMNodeId: idOf(node), + ...(up && { parentId: id(up) }), + childIds: children(node).map(id), + // Chrome's nodes of the shadow trees have one; the page cannot see theirs. + ...(!isVirtual(node) + ? { backendDOMNodeId: idOf(node) } + : PSEUDO_KEYS.has(node.key) && { backendDOMNodeId: Number(id(node)) }), }; }; + /** + * The AXNode of a marker or of one of its text children, which Chrome ignores as presentational. + * `queried`: an ignored one keeps its role and name, as for DOM nodes. + */ + const markerNode = (node: VirtualNode, queried?: boolean): AXNode => { + const marker = markerOf(node.host) as Marker; + const as = (role: string, value: string) => + queried + ? { role: roleValue(role), name: { type: 'computedString' as const, value } } + : { role: roleValue('none') }; + // The text of a marker in a roled list, and a quote and its text: as generated content's. + if (node !== marker.node && node.inclusion !== PRESENTATIONAL) return generatedNode(node); + if (node !== marker.node) + return links(node, { + nodeId: id(node), + ignored: true, + ignoredReasons: [{ name: 'presentationalRole', value: { type: 'boolean', value: true } }], + ...as('StaticText', node.text), + }); + if (marker.ignoredBy) { + const value: AXValue = + marker.ignoredBy === 'ariaHiddenSubtree' + ? { + type: 'idref', + relatedNodes: [{ backendDOMNodeId: idOf(node.host), ...(node.host.id && { idref: node.host.id }) }], + } + : { type: 'boolean', value: true }; + return links(node, { + nodeId: id(node), + ignored: true, + ignoredReasons: [{ name: marker.ignoredBy, value }], + ...(marker.textOnly ? { role: roleValue('none') } : as('ListMarker', marker.text.name)), + }); + } + const value = marker.text.name; + return links(node, { + nodeId: id(node), + ignored: false, + role: roleValue(node.role), + name: { + type: 'computedString', + value, + sources: [{ type: marker.text.alt ? 'implicit' : 'contents', value: { type: 'computedString', value } }], + }, + properties: [], + }); + }; + /** The AXNode of a ::before or ::after or of one of its children (ax-generated.ts). */ + const generatedNode = (node: VirtualNode): AXNode => { + if (node.inclusion.kind === 'ignored') { + const root = node.inclusion.reason === 'ariaHiddenSubtree' ? node.inclusion.hiddenRoot : undefined; + return links(node, { + nodeId: id(node), + ignored: true, + ignoredReasons: [ + { + name: node.inclusion.reason, + value: root + ? { type: 'idref', relatedNodes: [{ backendDOMNodeId: idOf(root), ...(root.id && { idref: root.id }) }] } + : { type: 'boolean', value: true }, + }, + ], + role: roleValue('none'), + }); + } + const text = node.role === 'StaticText'; + const alt = node.key === 'before' || node.key === 'after'; + return links(node, { + nodeId: id(node), + ignored: false, + role: roleValue(node.role), + name: { + type: 'computedString', + value: node.name ?? node.text, + ...(text + ? { sources: [{ type: alt ? 'implicit' : 'contents', value: { type: 'computedString', value: node.text } }] } + : node.role === 'generic' && { + sources: [ + { type: 'relatedElement', attribute: 'aria-labelledby' }, + { type: 'attribute', attribute: 'aria-label' }, + ], + }), + }, + properties: [], + }); + }; return { - parent: node => shape.parent(node), - children: node => shape.children(node), - inTree: node => shape.inTree(node), - node(node) { + parent, + children, + inTree: node => isMarker(node) || isGenerated(node) || shape.inTree(node), + virtual(host, key) { + if (!isElement(host)) return null; + const pseudo = /^(before|after)\b/.exec(key)?.[0]; + if (pseudo) { + const top = generatedOf(host, `::${pseudo}` as GeneratedPseudo); + if (!top || key === pseudo) return top; + const find = (nodes: AXRef[]): AXRef | null => { + for (const c of nodes) { + const found = isVirtual(c) ? (c.key === key ? c : find(c.raw)) : null; + if (found) return found; + } + return null; + }; + return find(top.raw); + } + if (!/^marker\b/.test(key)) return shape.virtual(host, key); + const marker = markerOf(host)?.node; + if (key === 'marker' || !marker) return marker ?? null; + const all = marker.raw.flatMap(c => (isVirtual(c) ? [c, ...c.raw] : [])); + return all.find(c => isVirtual(c) && c.key === key) ?? null; + }, + node(node, queried) { + if (isMarker(node)) return markerNode(node, queried); + if (isGenerated(node)) return generatedNode(node); + if (isVirtual(node)) return links(node, { nodeId: id(node), ...virtualNode(node, queried) }); + // Chrome has no node for a closed details' content: it answers with an unlinked one, id 0. + if (node !== shape.doc && closedDetailsOf(node)) + return { + nodeId: '0', + ignored: true, + ignoredReasons: [{ name: 'notRendered', value: { type: 'boolean', value: true } }], + role: { type: 'role', value: 'none' }, + backendDOMNodeId: idOf(node), + }; const inclusion = shape.inclusion(node); if (inclusion.kind !== 'included') { - const relatedNodes = - inclusion.kind === 'ignored' && inclusion.hiddenRoot && inclusion.reason === 'ariaHiddenSubtree' - ? [ - { - backendDOMNodeId: idOf(inclusion.hiddenRoot), - ...(inclusion.hiddenRoot.id && { idref: inclusion.hiddenRoot.id }), - }, - ] - : undefined; + // Chrome points at the node behind the reason: the aria-hidden root, or the control a + // label only repeats the name of. + const related = + inclusion.hiddenRoot && inclusion.reason === 'ariaHiddenSubtree' + ? inclusion.hiddenRoot + : inclusion.reason === 'labelFor' && isElement(node) + ? nativeGet(node, 'control') + : null; + const relatedNodes = related + ? [{ backendDOMNodeId: idOf(related), ...(related.id && { idref: related.id }) }] + : undefined; const reason: AXProperty = { name: inclusion.reason, value: relatedNodes ? { type: 'idref', relatedNodes } : { type: 'boolean', value: true }, @@ -213,8 +923,11 @@ export function createAXTree(doc: Document, idOf: IdOf, frameId: string): AXTree return links(node, { nodeId: id(node), ignored: true, - ignoredReasons: [reason], - role: { type: 'role', value: 'none' }, + // Chrome gives some ignored nodes no reason (a ruby's annotation, folded into the ruby). + ignoredReasons: inclusion.kind === 'ignored' && inclusion.noReason ? [] : [reason], + ...(queried && (isText(node) || isElement(node)) + ? ignoredAsQueried(node, inclusion.reason) + : { role: { type: 'role', value: 'none' } }), }); } if (node === doc) { @@ -233,13 +946,14 @@ export function createAXTree(doc: Document, idOf: IdOf, frameId: string): AXTree frameId, }; } + const editable = isText(node) && editableKind(node.parentElement); if (isText(node)) return links(node, { nodeId: id(node), ignored: false, role: roleValue('StaticText'), name: textNameOf(node), - properties: [], + properties: editable ? [token('editable', editable)] : [], }); if (!isElement(node)) throw new Error('not an element'); const role = roleOf(node); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-role.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-role.ts new file mode 100644 index 00000000..c356a58d --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-role.ts @@ -0,0 +1,492 @@ +// The role Chrome gives an element: its role attribute checked in context, or the implicit role +// of its tag, type and place (tables, sections, svg). Part of accessibility.js (ax-node.ts). +import { isElement, isHtml, isHtmlElement, isText, styleOf } from '../../core/realm'; +import { nativeGet } from '../../core/natives'; +import { inDisplayNone } from './name/ax-text'; +import { + attr, + attrNames, + byId, + closest, + domChildren, + domParent, + groupTable, + hasAttr, + hiddenReason, + isMenuList, + matches, + query, + queryAll, + rectOf, + scopeOf, + textOf, + words, +} from './ax-dom'; +import { excluded, ignored, INCLUDED, type Inclusion, lifted } from './tree/ax-ignored'; +import { ownersOf } from './tree/ax-owns'; + +/** Whether a role is one of Chrome's own, not an ARIA role (reported as `internalRole`). */ +export const isInternalRole = (role: string) => /^[A-Z]/.test(role); + +/** SVG shapes: graphics-symbol in Chrome. */ +const SVG_SHAPES = new Set('circle ellipse line path polygon polyline rect'.split(' ')); + +export const SVG_NS = 'http://www.w3.org/2000/svg'; + +/** SVG elements that draw nothing themselves, left out with what they hold. */ +const SVG_UNDRAWN = new Set( + 'clipPath desc filter linearGradient marker mask metadata pattern radialGradient script style symbol title'.split(' ') +); + +/** An svg link. */ +export const isSvgLink = (el: Element) => el.namespaceURI === SVG_NS && el.localName === 'a'; + +/** Whether an element is in an svg, under its root. */ +export const inSvg = (el: Element) => (el.parentNode as Element | null)?.namespaceURI === SVG_NS; + +/** + * How an element in an svg without a role takes part, as in Chrome: text and links are kept; a + * shape, image, use, group or inner svg only when it names or describes itself (aria, a title or + * desc child) or takes focus, its children in its place otherwise; foreignObject is presentational; + * the other elements give their children. + */ +export function svgInclusion(el: Element): Inclusion { + if (SVG_UNDRAWN.has(el.localName)) return excluded('notRendered'); + if (el.localName === 'foreignObject') return ignored('presentationalRole'); + if (el.localName === 'text' || el.localName === 'a') return INCLUDED; + if (!/^(circle|ellipse|line|path|polygon|polyline|rect|image|use|g|svg)$/.test(el.localName)) + return lifted('uninteresting'); + const interesting = + hasAuthorName(el) || + hasAttr(el, 'aria-describedby') || + hasAttr(el, 'tabindex') || + !!query(el, ':scope > title, :scope > desc'); + return interesting ? INCLUDED : lifted('uninteresting'); +} + +/** Whether a root svg holds anything Chrome keeps: it is then an SvgRoot, an image otherwise. */ +function hasSvgContent(svg: Element): boolean { + return queryAll(svg, '*').some(el => { + for (let p: Element | null = el; p && p !== svg; p = p.parentElement) + if (SVG_UNDRAWN.has(p.localName)) return false; + if (el.namespaceURI !== SVG_NS) return true; + return !!explicitRole(el) || svgInclusion(el).kind !== 'lifted'; + }); +} + +/** + * Whether an aside, header or footer is inside a section of the page, which makes an aside without + * a name no landmark, and a header or footer a section's (as in Chrome): an ancestor whose role is + * article, complementary or navigation (by tag or role attribute), or a section without a role + * attribute; for a header or footer (`main`), one whose role is main too. A region by role does + * not count, nor what a role attribute makes something else or presentational. + */ +function inSectionOf(el: Element, main: boolean): boolean { + for (let p = el.parentElement; p; p = p.parentElement) { + const explicit = explicitRole(p); + if (explicit === 'none') continue; + const role = explicit ?? implicitRole(p); + if (role === 'article' || role === 'complementary' || role === 'navigation') return true; + if (main && role === 'main') return true; + if (p.localName === 'section' && !explicit) return true; + } + return false; +} + +/** The ARIA roles Chrome knows (abstract roles are not among them). */ +const ARIA_ROLES = new Set( + 'alert alertdialog application article banner blockquote button caption cell checkbox code columnheader combobox comment complementary contentinfo definition deletion dialog directory document emphasis feed figure form generic graphics-document graphics-object graphics-symbol grid gridcell group heading image img insertion link list listbox listitem log main mark marquee math menu menubar menuitem menuitemcheckbox menuitemradio meter navigation none note option paragraph presentation progressbar radio radiogroup region row rowgroup rowheader scrollbar search searchbox sectionfooter sectionheader separator slider spinbutton status strong subscript suggestion superscript switch tab table tablist tabpanel term textbox time timer toolbar tooltip tree treegrid treeitem'.split( + ' ' + ) +); +const DOC_ROLE = + /^doc-(abstract|acknowledgments|afterword|appendix|backlink|biblioentry|bibliography|biblioref|chapter|colophon|conclusion|cover|credit|credits|dedication|endnotes?|epigraph|epilogue|errata|example|footnote|foreword|glossary|glossref|index|introduction|noteref|notice|pagebreak|pagefooter|pageheader|pagelist|part|preface|prologue|pullquote|qna|subtitle|tip|toc)$/; + +/** ARIA attributes any element takes: with one, Chrome keeps the element's role over none. */ +const GLOBAL_ARIA = + /^aria-(atomic|busy|controls|current|describedby|description|details|dropeffect|flowto|grabbed|keyshortcuts|label|labelledby|live|owns|relevant|roledescription)$/; + +/** + * Whether an element has a name from its author: aria-labelledby (to some text), aria-label, or a + * title attribute, even an empty one (Chrome's IsNameFromAuthorAttribute). + */ +export function hasAuthorName(el: Element): boolean { + if (attr(el, 'aria-label')?.trim() || hasAttr(el, 'title')) return true; + const root = scopeOf(el); + return (attr(el, 'aria-labelledby') ?? '').split(/[ \t\n\r\f]+/).some(id => { + const target = id && root ? byId(root, id) : null; + return !!target && !!textOf(target)?.trim(); + }); +} + +/** + * The role from the role attribute: its first token that is a role Chrome knows (in any case), + * with region and form only when named; `none` for both presentational roles, unless the element + * is focusable or has a global ARIA attribute. Null when no token applies. + */ +export function explicitRole(el: Element): string | null { + for (const token of roleTokens(el)) { + if ((token === 'region' || token === 'form') && !hasAuthorName(el)) continue; + if (isOrphaned(el, token)) continue; + if (token === 'none' || token === 'presentation') + return isFocusable(el) || attrNames(el).some(n => GLOBAL_ARIA.test(n)) ? null : 'none'; + return token === 'img' ? 'image' : token === 'directory' ? 'list' : token; + } + return null; +} + +/** The tokens of an element's role attribute that are roles Chrome knows (in any case), in order. */ +const roleTokens = (el: Element) => + (attr(el, 'role') ?? '') + .toLowerCase() + .split(/[ \t\n\r\f]+/) + .filter(token => ARIA_ROLES.has(token) || DOC_ROLE.test(token)); + +/** The first role Chrome knows in an element's role attribute, without context checks. */ +const rawRole = (el: Element): string | null => roleTokens(el)[0] ?? null; + +/** For the roles that need one, the container roles (and tags) that give them their context. */ +const REQUIRED_CONTEXT: Record = { + listitem: { + roles: ['list', 'directory', 'group'], + tags: ['ul', 'ol', 'menu'], + }, + option: { roles: ['listbox', 'group'], tags: ['select'] }, + treeitem: { roles: ['tree', 'group'], tags: [] }, +}; + +/** + * Whether an ARIA role that needs a container lacks one (Chrome's HasRequiredParentContext): up the + * tree, past presentational elements and plain div/span/slot/custom elements (and, for a treeitem, + * other treeitems), the first other element must be a container for it. An aria-owns owner counts + * when it is one. + */ +function isOrphaned(el: Element, role: string): boolean { + const context = REQUIRED_CONTEXT[role]; + if (!context) return false; + const isContainer = (parent: Element, parentRole: string | null) => + context.tags.includes(parent.localName) || (!!parentRole && context.roles.includes(parentRole)); + const scope = el.id && scopeOf(el); + const owner = scope && ownersOf(scope).get(el); + if (owner && isContainer(owner, roleOf(owner))) return false; + for (let n = domParent(el); n; n = domParent(n)) { + if (!isElement(n)) continue; + const parentRole = rawRole(n); + if (isContainer(n, parentRole)) return false; + if (role === 'treeitem' && parentRole === 'treeitem') continue; + if (parentRole === 'none' || parentRole === 'presentation') continue; + const generic = /^(div|span|slot)$/.test(n.localName) || n.localName.includes('-'); + if (!attr(n, 'role') && generic) continue; + break; + } + return true; +} + +/** Whether an element takes keyboard focus: in the tab order or focusable by script. */ +export function isFocusable(el: Element): boolean { + // An option stays focusable in a disabled select, not when it or its group is disabled. + if (isHtml(el, 'option')) + return !hasAttr(el, 'disabled') && !(isHtml(el.parentElement, 'optgroup') && hasAttr(el.parentElement, 'disabled')); + if (matches(el, ':disabled')) return false; + // Without a box (display: contents), Chrome does not focus it. + if (styleOf(el).display === 'contents') return false; + if (hasAttr(el, 'tabindex')) return true; + if (isHtml(el, 'a') || isHtml(el, 'area') || isSvgLink(el)) return hasAttr(el, 'href'); + if (isHtml(el, 'input')) return el.type !== 'hidden'; + // The editing host, not the elements in it. + if (isHtmlElement(el) && el.isContentEditable && !(el.parentElement?.isContentEditable ?? false)) return true; + return (isHtmlElement(el) && /^(button|select|textarea|option)$/.test(el.localName)) || isSummary(el); +} + +/** A details element's summary: Chrome's DisclosureTriangle. */ +const isSummary = (el: Element) => + el.localName === 'summary' && + el.parentElement?.localName === 'details' && + query(el.parentElement, ':scope > summary') === el; + +/** + * Roles that only depend on the tag name (Blink's AXNodeObject::NativeRoleIgnoringAria), as + * "role tag tag …". + */ +const TAG_ROLES = groupTable([ + 'group address details fieldset hgroup optgroup', + 'LineBreak br', + 'listbox datalist', + 'definition dd', + 'deletion del s', + 'term dfn dt', + 'list dir menu ol ul', + 'DescriptionList dl', + 'emphasis em', + 'EmbeddedObject embed', + 'heading h1 h2 h3 h4 h5 h6', + 'separator hr', + 'image img svg', + 'insertion ins', + 'LabelText label', + 'listitem li', + 'MathMLMath math', + 'navigation nav', + 'PluginObject object', + 'status output', + 'paragraph p', + 'progressbar progress', + 'subscript sub', + 'superscript sup', + 'textbox textarea', +]); +// Tags whose role is named after them: ARIA roles, and Chrome's own roles, capitalized. +for (const tag of words( + 'article blockquote button caption code dialog figure form main mark meter option search strong table time' +)) + TAG_ROLES[tag] = tag; +for (const tag of words('abbr audio canvas figcaption iframe legend ruby video')) + TAG_ROLES[tag] = tag[0]?.toUpperCase() + tag.slice(1); + +/** The roles of inputs by their type, as "role type type …"; other types are text fields. */ +const INPUT_ROLES = groupTable([ + 'button button submit reset image file', + 'checkbox checkbox', + 'radio radio', + 'slider range', + 'spinbutton number', + 'ColorWell color', + 'Date date', + 'DateTime datetime-local month week', + 'InputTime time', +]); + +/** An input's role, by its type. */ +const inputRole = (el: HTMLInputElement): string => + INPUT_ROLES[el.type] ?? (el.list ? 'combobox' : el.type === 'search' ? 'searchbox' : 'textbox'); + +const TABLE_LIKE = /^(table|grid|treegrid|LayoutTable)$/; + +/** + * The closest ancestor that counts within a table (Chrome's GetDOMTableAXAncestor): group, + * generic and rowgroup ones are passed over. + */ +function tableAncestor(el: Element): Element | null { + for (let p = el.parentElement; p; p = p.parentElement) if (!/^(group|generic|rowgroup)$/.test(roleOf(p))) return p; + return null; +} + +/** Data table answers, kept for one synchronous pass over the tree. */ +let dataTables: WeakMap | null = null; + +/** Whether a table holds data rather than layout (Chrome's IsDataTable), cached for the current pass. */ +function isDataTable(table: Element): boolean { + if (!dataTables) { + dataTables = new WeakMap(); + queueMicrotask(() => (dataTables = null)); + } + let data = dataTables.get(table); + if (data === undefined) dataTables.set(table, (data = decideDataTable(table))); + return data; +} + +/** + * Chrome's heuristic: a table is for data with a role, in editable content, with a caption, summary, + * thead, tfoot, rules or col, with 20 rows or more, with a th or a cell with headers, abbr, axis or + * scope, with empty-cells: hide, or when half its sized cells have borders, or backgrounds of their + * own with cell spacing, or its first rows alternate colours. + */ +function decideDataTable(table: Element): boolean { + if (!isHtml(table, 'table')) return false; + if (inDisplayNone(table)) return true; + if (hasAttr(table, 'role') || table.isContentEditable) return true; + if (attr(table, 'summary') || table.tHead || table.tFoot || table.caption || attr(table, 'rules')) return true; + if (query(table, ':scope > col, :scope > colgroup')) return true; + const rows = table.rows; + if (rows.length >= 20) return true; + if (!rows.length) return false; + if (rows.length === 1 && rows[0]?.cells.length === 1) return false; + const tableStyle = styleOf(table); + const tableBackground = tableStyle.backgroundColor; + const [h = '0', v = h] = tableStyle.borderSpacing.split(' '); + const spacing = parseFloat(h) > 0 && parseFloat(v) > 0; + let valid = 0; + let bordered = 0; + let backgrounds = 0; + const sides = [0, 0, 0, 0]; + const rowColors: string[] = []; + for (const [r, row] of [...rows].entries()) { + for (const cell of row.cells) { + if (cell.localName === 'th') return true; + if (['headers', 'abbr', 'axis', 'scope'].some(a => attr(cell, a))) return true; + const style = styleOf(cell); + if (inDisplayNone(cell) || !/^(table-cell|block|flow-root|inline-block|list-item|flex|grid)$/.test(style.display)) + continue; + const box = rectOf(cell); + if (box.width < 1 || box.height < 1) continue; + valid++; + if (style.emptyCells === 'hide') return true; + const widths = [style.borderTopWidth, style.borderRightWidth, style.borderBottomWidth, style.borderLeftWidth].map( + w => parseFloat(w) > 0 + ); + if ((widths[0] && widths[2]) || (widths[1] && widths[3])) bordered++; + widths.forEach((w, i) => w && (sides[i] = (sides[i] ?? 0) + 1)); + const color = style.backgroundColor; + if (spacing && color !== tableBackground && !isTransparent(color)) backgrounds++; + if (bordered >= 10 || backgrounds >= 10) return true; + if (r < 5 && r === rowColors.length && styleOf(row).display === 'table-row') + rowColors.push(styleOf(row).backgroundColor); + } + } + if (valid <= 1) return false; + const needed = Math.floor(valid / 2); + if (bordered >= needed || sides.some(n => n >= needed) || backgrounds >= needed) return true; + if (rowColors.length > 2) return rowColors.every((c, k) => (k % 2 ? c !== rowColors[0] : c === rowColors[0])); + return false; +} + +/** A computed colour with no alpha. */ +const isTransparent = (color: string) => color === 'transparent' || /^rgba\(.*,\s*0\)$/.test(color); + +/** The role an element has without a role attribute. */ +export function implicitRole(el: Element): string { + if (el.namespaceURI === SVG_NS) { + if (SVG_SHAPES.has(el.localName)) return 'graphics-symbol'; + if (el.localName === 'g' || el.localName === 'foreignObject' || (el.localName === 'svg' && inSvg(el))) + return 'group'; + if (el.localName === 'svg') return hasSvgContent(el) ? 'SvgRoot' : 'image'; + } + switch (el.localName) { + case 'th': + case 'td': + // The cells of a presentational table are plain containers. + const table = closest(el, 'table'); + if (table && explicitRole(table) === 'none') return 'generic'; + } + switch (el.localName) { + case 'table': + return isDataTable(el) ? 'table' : 'LayoutTable'; + case 'thead': + case 'tbody': + case 'tfoot': { + const table = tableAncestor(el); + const role = table ? roleOf(table) : ''; + return TABLE_LIKE.test(role) && role !== 'LayoutTable' ? 'rowgroup' : 'generic'; + } + case 'tr': { + const table = tableAncestor(el); + const role = table ? roleOf(table) : ''; + if (!TABLE_LIKE.test(role)) return 'generic'; + return role === 'LayoutTable' ? 'LayoutTableRow' : 'row'; + } + } + if (el.localName === 'th' || el.localName === 'td') { + const row = tableAncestor(el); + const rowRole = row ? roleOf(row) : ''; + const table = row && tableAncestor(row); + if (!/^(row|LayoutTableRow)$/.test(rowRole) || !table || !TABLE_LIKE.test(roleOf(table))) return 'generic'; + if (rowRole === 'LayoutTableRow') return 'LayoutTableCell'; + } + switch (el.localName) { + case 'th': { + const scope = attr(el, 'scope'); + if (scope === 'row' || scope === 'rowgroup') return 'rowheader'; + if (scope === 'col' || scope === 'colgroup') return 'columnheader'; + return el.parentElement && query(el.parentElement, ':scope > td') ? 'rowheader' : 'columnheader'; + } + case 'td': + const grid = closest(el, 'table'); + return grid && /^(grid|treegrid)$/.test(explicitRole(grid) ?? '') ? 'gridcell' : 'cell'; + case 'input': + if (isHtml(el, 'input')) return inputRole(el); + break; + case 'summary': + // Any summary child of a details, as in Chrome's tree; only the first opens it (isSummary). + return el.parentElement?.localName === 'details' ? 'DisclosureTriangle' : 'generic'; + case 'section': + return hasAuthorName(el) ? 'region' : 'generic'; + case 'aside': + return inSectionOf(el, false) && !hasAuthorName(el) ? 'generic' : 'complementary'; + case 'header': + case 'footer': { + const inSection = inSectionOf(el, true); + if (inSection) return el.localName === 'header' ? 'sectionheader' : 'sectionfooter'; + return el.localName === 'header' ? 'banner' : 'contentinfo'; + } + case 'a': + return hasAttr(el, 'href') ? 'link' : 'generic'; + case 'area': + // An image map's area without a link is text in Chrome. + return hasAttr(el, 'href') ? 'link' : imageOf(el) ? 'StaticText' : 'generic'; + case 'select': + if (isHtml(el, 'select')) return isMenuList(el) ? 'combobox' : 'listbox'; + } + const role = TAG_ROLES[el.localName]; + if (role) return role; + // A generic element that can be dragged or takes autofocus is a group in Chrome. + // Not with a role attribute, even one with no role Chrome knows. + if (attr(el, 'role')?.trim()) return 'generic'; + // So is one shown as a list item a list item, marker or not. + if (isListItemBox(el)) return 'listitem'; + return hasAttr(el, 'draggable') || hasAttr(el, 'autofocus') ? 'group' : 'generic'; +} + +/** Whether an element is shown as a list item (`display: list-item`, inline or not). */ +export const isListItemBox = (el: Element) => /\blist-item\b/.test(styleOf(el).display); + +/** + * Whether an element shows a list marker (ax-marker.ts): a list item whose ::marker has content, + * its own or that of list-style-type; list-style-image alone makes none in the tree. + */ +export function generatesMarker(el: Element): boolean { + if (!isListItemBox(el)) return false; + const content = styleOf(el, '::marker').content; + return content !== 'none' && (content !== 'normal' || styleOf(el).listStyleType !== 'none'); +} + +/** The role Chrome gives an element: an ARIA role, or one of its own (isInternalRole). */ +export function roleOf(el: Element): string { + const explicit = explicitRole(el); + return explicit && explicit !== 'none' ? explicit : implicitRole(el); +} + +/** + * Whether a label only repeats the name of the checkbox or radio it labels, which Chrome ignores + * (labelFor) with its text: the input is rendered and visible, named by its labels (no aria-label + * or aria-labelledby), and the label holds only text besides the input (comments do not count), with no role, name of its + * own or click handler attribute. A handler added by addEventListener cannot be seen. The text of + * its ::before and ::after is ignored too (ax-node.ts). + */ +export function isRedundantLabel(el: Element): boolean { + if (!isHtml(el, 'label') || explicitRole(el)) return false; + const control = nativeGet(el, 'control'); + if ( + !isHtml(control, 'input') || + !/^(checkbox|radio)$/.test(nativeGet(control, 'type')) || + hiddenReason(control) + ) + return false; + if (hasAttr(control, 'aria-label') || hasAttr(control, 'aria-labelledby')) return false; + if (['aria-label', 'aria-labelledby', 'title', 'onclick'].some(n => hasAttr(el, n))) return false; + // Comments and other nodes that are neither text nor elements show nothing, so they do not count. + return domChildren(el).every(c => isText(c) || c === control || !isElement(c)); +} + +/** + * The image an area belongs to: the first rendered img whose usemap names the area's map. Chrome + * puts the areas under that image, though the map itself is not rendered. + */ +export function imageOf(area: Element): Element | null { + const map = closest(area, 'map'); + const name = (map && attr(map, 'name')) || map?.id; + if (!map || !name) return null; + const root = scopeOf(map); + if (!root) return null; + for (const img of queryAll(root, 'img[usemap]')) + if (attr(img, 'usemap') === `#${name}`) return hiddenReason(img) === 'notRendered' ? null : img; + return null; +} + +/** An image's map areas, in order. */ +export function areasOf(img: Element): Element[] { + const name = attr(img, 'usemap')?.replace(/^#/, ''); + const root = scopeOf(img); + if (!name || !root) return []; + const map = queryAll(root, 'map').find(m => (attr(m, 'name') || m.id) === name); + return map ? queryAll(map, 'area').filter(area => imageOf(area) === img) : []; +} diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-tree.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-tree.ts deleted file mode 100644 index bcb63f33..00000000 --- a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/ax-tree.ts +++ /dev/null @@ -1,302 +0,0 @@ -// The shape of the accessibility tree: which DOM nodes are in it, with which role, and in which -// order. Part of accessibility.js, loaded on demand (ax-node.ts). -// -// Blink builds its tree from the layout tree (third_party/blink/renderer/modules/accessibility/), -// which a page cannot read: these rules redo the common cases from the DOM and computed styles, -// checked against Chrome's getFullAXTree (accessibility.conformance.test.ts). The role mapping -// starts from dom-accessibility-api's getRole (HTML-AAM) and adds Chrome's own choices. -import { getRole } from 'dom-accessibility-api'; -import { isElement, isHtml, isHtmlElement, isShadowRoot, isText, styleOf } from '../../core/realm'; - -/** Chrome's roles that are not ARIA roles, reported as `internalRole`. */ -export const INTERNAL_ROLES = new Set([ - 'RootWebArea', - 'StaticText', - 'LabelText', - 'DisclosureTriangle', - 'DescriptionList', - 'Legend', - 'Figcaption', -]); - -/** Why a node in the tree is ignored (CDP `AXPropertyName`). */ -export type IgnoredReason = - | 'uninteresting' - | 'ariaHiddenElement' - | 'ariaHiddenSubtree' - | 'notRendered' - | 'notVisible' - | 'presentationalRole' - | 'emptyAlt'; - -/** - * How a DOM node takes part in the tree: `included`, ignored but kept (`reason`), left out with its - * children taking its place (`lifted`), or left out with its subtree (`excluded`). - */ -export type Inclusion = - | { kind: 'included' } - | { kind: 'ignored'; reason: IgnoredReason; hiddenRoot?: Element } - | { kind: 'lifted'; reason: IgnoredReason } - | { kind: 'excluded'; reason: IgnoredReason }; - -/** Elements whose text and children the page does not show as content: replaced by their value or a popup. */ -const OPAQUE = new Set( - 'script style template noscript title head textarea select option input img br wbr iframe object embed video audio canvas svg'.split( - ' ' - ) -); - -/** Sectioning elements, inside which `header` and `footer` are no landmarks. */ -const SECTIONING = 'article, aside, main, nav, section'; - -/** The first token of `role` that is a role, or null. */ -function explicitRole(el: Element): string | null { - const value = el.getAttribute('role')?.trim(); - return value ? (value.split(/\s+/)[0] ?? null) : null; -} - -/** Whether an element takes keyboard focus: in the tab order or focusable by script. */ -export function isFocusable(el: Element): boolean { - if (el.matches(':disabled')) return false; - if (el.hasAttribute('tabindex')) return true; - if (isHtml(el, 'a') || isHtml(el, 'area')) return el.hasAttribute('href'); - if (isHtml(el, 'input')) return el.type !== 'hidden'; - if (isHtmlElement(el) && el.isContentEditable) return true; - return ( - isHtml(el, 'button') || isHtml(el, 'select') || isHtml(el, 'textarea') || isHtml(el, 'option') || isSummary(el) - ); -} - -/** A details element's summary: Chrome's DisclosureTriangle. */ -const isSummary = (el: Element) => - el.localName === 'summary' && - el.parentElement?.localName === 'details' && - el.parentElement.querySelector(':scope > summary') === el; - -/** The role Chrome gives an element: an ARIA role, or one of INTERNAL_ROLES. */ -export function roleOf(el: Element): string { - const explicit = explicitRole(el); - if (explicit === 'img') return 'image'; - if (explicit && explicit !== 'none' && explicit !== 'presentation') return explicit; - switch (el.localName) { - case 'dl': - return 'DescriptionList'; - case 'legend': - return 'Legend'; - case 'figcaption': - return 'Figcaption'; - case 'blockquote': - return 'blockquote'; - case 'caption': - return 'caption'; - case 'th': { - const scope = el.getAttribute('scope'); - if (scope === 'row' || scope === 'rowgroup') return 'rowheader'; - if (scope === 'col' || scope === 'colgroup') return 'columnheader'; - return el.parentElement?.querySelector(':scope > td') ? 'rowheader' : 'columnheader'; - } - case 'input': - // dom-accessibility-api has no role for a password field; Chrome makes it a text box. - if (isHtml(el, 'input') && el.type === 'password') return 'textbox'; - break; - case 'label': - return 'LabelText'; - case 'summary': - return isSummary(el) ? 'DisclosureTriangle' : 'generic'; - case 'details': - return 'group'; - case 'section': - return el.hasAttribute('aria-label') || el.hasAttribute('aria-labelledby') || el.hasAttribute('title') - ? 'region' - : 'generic'; - case 'header': - case 'footer': { - const inSection = el.parentElement?.closest(SECTIONING); - if (inSection) return el.localName === 'header' ? 'sectionheader' : 'sectionfooter'; - return el.localName === 'header' ? 'banner' : 'contentinfo'; - } - case 'p': - return 'paragraph'; - case 'a': - return el.hasAttribute('href') ? 'link' : 'generic'; - case 'svg': - return 'image'; - case 'select': - if (isHtml(el, 'select')) return el.multiple || el.size > 1 ? 'listbox' : 'combobox'; - } - const role = getRole(el); - if (role === 'img') return 'image'; - return role && role !== 'presentation' && role !== 'none' ? role : 'generic'; -} - -/** - * Why an element is not shown, if it is not: `display: none` on it or an ancestor (no box), or - * `visibility: hidden` (a box, not painted). - */ -function hiddenReason(el: Element): IgnoredReason | null { - if (!el.isConnected) return 'notRendered'; - for (let n: Node | null = el; n && isElement(n); n = domParent(n)) - if (styleOf(n).display === 'none') return 'notRendered'; - const visibility = styleOf(el).visibility; - return visibility === 'hidden' || visibility === 'collapse' ? 'notVisible' : null; -} - -/** The children of a node as the tree sees them: shadow trees and slots flattened. */ -export function domChildren(node: Node): Node[] { - if (isElement(node)) { - if (node.shadowRoot) return [...node.shadowRoot.childNodes]; - if (isHtml(node, 'slot')) { - const assigned = node.assignedNodes(); - if (assigned.length) return assigned; - } - } - return [...node.childNodes]; -} - -/** The parent of a node as the tree sees it: the slot it is assigned to, the host of a shadow root. */ -export function domParent(node: Node): Node | null { - if (isElement(node) || isText(node)) { - const slot = node.assignedSlot; - if (slot) return slot; - } - const parent = node.parentNode; - return isShadowRoot(parent) ? parent.host : parent; -} - -/** The element a text node's rendering depends on. */ -const displayOf = (node: Node | null) => (node && isElement(node) ? styleOf(node).display : ''); - -/** - * Whether a whitespace-only text node shows: Chrome keeps it as StaticText " " between two inline - * boxes, as it shows as a space there. - */ -function isRenderedSpace(text: Text, inTree: (node: Node) => boolean): boolean { - let prev = text.previousSibling; - while (prev && isText(prev) && !prev.data.trim()) prev = prev.previousSibling; - let next = text.nextSibling; - while (next && isText(next) && !next.data.trim()) next = next.nextSibling; - // Not next to an inline-block (a button, a field), nor to an element left out of the tree: - // Chrome drops the space there. - const inline = (node: Node | null) => !!node && (isText(node) || (displayOf(node) === 'inline' && inTree(node))); - return inline(prev) && inline(next); -} - -/** A text node's text as rendered: white space collapsed, and trimmed at the edges of its block. */ -export function renderedText(text: Text): string { - let value = text.data.replace(/[ \t\n\r\f]+/g, ' '); - if (!value.trim()) return ' '; - const inline = (node: Node | null) => - !!node && (isText(node) ? !!node.data.trim() : displayOf(node).startsWith('inline')); - if (!inline(text.previousSibling)) value = value.replace(/^ /, ''); - if (!inline(text.nextSibling)) value = value.replace(/ $/, ''); - return value; -} - -/** The tree's structure over one document, with aria-owns resolved. */ -export class TreeShape { - /** Elements moved by aria-owns, to their owner. */ - private owner = new Map(); - private owned = new Map(); - readonly doc: Document; - - constructor(doc: Document) { - this.doc = doc; - for (const el of doc.querySelectorAll('[aria-owns]')) { - const ids = el.getAttribute('aria-owns')?.trim().split(/\s+/) ?? []; - const list: Element[] = []; - for (const id of ids) { - const target = doc.getElementById(id); - // An element owned twice stays with its first owner; one cannot own its ancestor. - if (!target || this.owner.has(target) || target.contains(el)) continue; - this.owner.set(target, el); - list.push(target); - } - if (list.length) this.owned.set(el, list); - } - } - - /** How a node takes part in the tree (Inclusion). */ - inclusion(node: Node): Inclusion { - if (node === this.doc) return { kind: 'included' }; - if (isText(node)) { - const parent = domParent(node); - if (!parent || (isElement(parent) && (OPAQUE.has(parent.localName) || hiddenReason(parent)))) - return { kind: 'excluded', reason: 'notRendered' }; - if (!node.data.trim() && !isRenderedSpace(node, n => this.inTree(n))) - return { kind: 'excluded', reason: 'uninteresting' }; - const hidden = this.hiddenRoot(node); - return hidden ? { kind: 'ignored', reason: 'ariaHiddenSubtree', hiddenRoot: hidden } : { kind: 'included' }; - } - if (!isElement(node)) return { kind: 'excluded', reason: 'uninteresting' }; - if (node.closest('[data-devtools-anywhere]')) return { kind: 'excluded', reason: 'notRendered' }; - const hiddenBy = hiddenReason(node); - if (hiddenBy) return { kind: 'excluded', reason: hiddenBy }; - const hidden = this.hiddenRoot(node); - // Chrome leaves the aria-hidden element out and keeps what it hides, ignored. - if (hidden === node) return { kind: 'lifted', reason: 'ariaHiddenElement' }; - if (hidden) return { kind: 'ignored', reason: 'ariaHiddenSubtree', hiddenRoot: hidden }; - if (node === this.doc.documentElement || node === this.doc.body) - return { kind: 'ignored', reason: 'uninteresting' }; - // An implicit or plain tbody; thead and tfoot are row groups. - if (node.localName === 'tbody' && !node.hasAttribute('role')) return { kind: 'ignored', reason: 'uninteresting' }; - const explicit = explicitRole(node); - if (node.localName === 'img' && node.getAttribute('alt') === '' && !explicit) - return { kind: 'lifted', reason: 'emptyAlt' }; - if ((explicit === 'none' || explicit === 'presentation') && !isFocusable(node)) - return { kind: 'lifted', reason: 'presentationalRole' }; - return { kind: 'included' }; - } - - /** The element with aria-hidden="true" that hides a node, if any. */ - private hiddenRoot(node: Node): Element | null { - for (let n: Node | null = node; n && n !== this.doc; n = domParent(n)) - if (isElement(n) && n.getAttribute('aria-hidden') === 'true') return n; - return null; - } - - /** Whether a node is in the tree (included or ignored). */ - inTree(node: Node): boolean { - const kind = this.inclusion(node).kind; - return kind === 'included' || kind === 'ignored'; - } - - /** The nodes in the tree under a node, in order: lifted nodes give their own. */ - children(node: Node): Node[] { - const out: Node[] = []; - const visit = (child: Node) => { - if (isElement(child) && this.owner.has(child)) return; - const inclusion = this.inclusion(child); - if (inclusion.kind === 'excluded') return; - if (inclusion.kind === 'lifted') { - for (const c of this.ownChildren(child)) visit(c); - return; - } - out.push(child); - }; - for (const child of this.ownChildren(node)) visit(child); - if (isElement(node)) - for (const el of this.owned.get(node) ?? []) if (this.inclusion(el).kind !== 'excluded') out.push(el); - return out; - } - - /** A node's DOM children, none for the elements whose content the tree replaces. */ - private ownChildren(node: Node): Node[] { - if (isElement(node) && OPAQUE.has(node.localName)) return []; - if ( - isElement(node) && - /^(checkbox|radio|slider|image|img|progressbar|separator|scrollbar|textbox)$/.test(roleOf(node)) && - node.localName !== 'div' - ) - return []; - return domChildren(node); - } - - /** The closest node in the tree above a node: its aria-owns owner, or its DOM ancestor. */ - parent(node: Node): Node | null { - if (node === this.doc) return null; - let n: Node | null = isElement(node) ? (this.owner.get(node) ?? domParent(node)) : domParent(node); - while (n && n !== this.doc && !this.inTree(n)) - n = isElement(n) ? (this.owner.get(n) ?? domParent(n)) : domParent(n); - return n; - } -} diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-events.conformance.test.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-events.conformance.test.ts new file mode 100644 index 00000000..fd682da6 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-events.conformance.test.ts @@ -0,0 +1,216 @@ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import type { Protocol } from 'devtools-protocol'; +import type { CDPSession } from 'puppeteer-core'; +import { launch, setUpAndTearDown } from '../../../../../test-support/conformance.ts'; +import type { Env, TestPage } from '../../../../../test-support/conformance.ts'; +import { openAxPage, setBody } from '../../../../../test-support/accessibility.ts'; + +let env: Env | undefined; +let t: TestPage; +/** A Chrome session of its own, whose nodesUpdated events are kept in `chromeEvents`. */ +let chrome: CDPSession; +const chromeEvents: Protocol.Accessibility.NodesUpdatedEvent[] = []; + +const FIXTURE = `

    text

    dd

    ee

    `; + +setUpAndTearDown( + async () => { + env = await launch(); + t = await openAxPage(env); + // openAxPage's session does not keep its events. + await t.page.evaluate(() => { + window.__ours = []; + window.__session.onMessage(m => { + const msg: { method?: string; params: unknown } = JSON.parse(m); + if (msg.method) window.__ours.push({ method: msg.method, params: msg.params }); + }); + }); + chrome = await t.page.createCDPSession(); + chrome.on('Accessibility.nodesUpdated', e => chromeEvents.push(e)); + await chrome.send('DOM.getDocument', { depth: -1 }); + }, + () => env?.close() +); + +const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + +/** The backend node id of `#id` on our side and on Chrome's (the same page, the same ids). */ +async function backendIds(id: string): Promise<{ ours: number; chrome: number }> { + const ours = async () => { + const { root } = await t.ours.send('DOM.getDocument', { depth: 0 }); + const { nodeId } = await t.ours.send('DOM.querySelector', { + nodeId: root.nodeId, + selector: `#${id}`, + }); + return (await t.ours.send('DOM.describeNode', { nodeId })).node.backendNodeId; + }; + const theirs = async () => { + const { root } = await chrome.send('DOM.getDocument', { depth: 0 }); + const { nodeId } = await chrome.send('DOM.querySelector', { + nodeId: root.nodeId, + selector: `#${id}`, + }); + return (await chrome.send('DOM.describeNode', { nodeId })).node.backendNodeId; + }; + return { ours: await ours(), chrome: await theirs() }; +} + +/** + * Both sides give the client `#b` and its ancestors, and `#a`'s children: the nodes nodesUpdated + * then reports (the Accessibility pane's commands). + */ +async function giveNodes() { + const b = await backendIds('b'); + await t.ours.send('Accessibility.getAXNodeAndAncestors', { + backendNodeId: b.ours, + }); + await chrome.send('Accessibility.getAXNodeAndAncestors', { + backendNodeId: b.chrome, + }); + const a = await backendIds('a'); + await t.ours.send('Accessibility.getChildAXNodes', { id: String(a.ours) }); + const ax = await chrome.send('Accessibility.getPartialAXTree', { + backendNodeId: a.chrome, + fetchRelatives: false, + }); + await chrome.send('Accessibility.getChildAXNodes', { + id: ax.nodes[0]?.nodeId ?? '', + }); +} + +async function fresh() { + await setBody(t, FIXTURE); + await Promise.all([t.ours.send('Accessibility.enable'), chrome.send('Accessibility.enable')]); + await giveNodes(); + await sleep(200); + await clear(); +} + +async function clear() { + chromeEvents.length = 0; + await t.ours.clear(); +} + +/** Runs `change` in the page and gives the nodes each side reported, as `role:name`, after a while. */ +async function after(change: string): Promise<{ ours: string[][]; chrome: string[][] }> { + await clear(); + await t.page.evaluate(change); + await sleep(400); + const label = (e: Protocol.Accessibility.NodesUpdatedEvent) => + e.nodes.map(n => `${String(n.role?.value)}:${String(n.name?.value ?? '')}`); + const ours = (await t.ours.events('Accessibility.nodesUpdated')).map(label); + return { ours, chrome: chromeEvents.map(label) }; +} + +/** Our nodes are among Chrome's, which may add a parent whose AXNode did not change. */ +function assertAmong(ours: string[][], chrome: string[][], expected: string) { + assert.ok(ours.flat().includes(expected), `ours: ${JSON.stringify(ours)}`); + assert.ok(chrome.flat().includes(expected), `chrome: ${JSON.stringify(chrome)}`); + for (const node of ours.flat()) assert.ok(chrome.flat().includes(node), `${node} not in ${JSON.stringify(chrome)}`); +} + +describe('Accessibility.nodesUpdated', () => { + test('a node given to the client is sent when its name changes', async () => { + await fresh(); + const { ours, chrome } = await after(`document.getElementById('b').setAttribute('aria-label', 'X')`); + assert.deepEqual(ours, [['button:X']]); + assertAmong(ours, chrome, 'button:X'); + }); + + test("a parent is sent when its children change, with the new child's id", async () => { + await fresh(); + const { ours, chrome } = await after( + `document.getElementById('a').append(Object.assign(document.createElement('h2'), { textContent: 'H' }))` + ); + assertAmong(ours, chrome, 'generic:'); + const [event] = await t.ours.events('Accessibility.nodesUpdated'); + assert.equal(event?.nodes[0]?.childIds?.length, 4); + }); + + test('a role change is sent', async () => { + await fresh(); + const { ours, chrome } = await after( + `const a = document.getElementById('a'); a.setAttribute('aria-label', 'Z'); a.setAttribute('role', 'region')` + ); + assertAmong(ours, chrome, 'region:Z'); + }); + + test('a class that hides a node is seen: its parent is sent, not the node', async () => { + await fresh(); + const { ours, chrome } = await after( + `document.head.insertAdjacentHTML('beforeend', ''); + document.getElementById('b').className = 'h'` + ); + assertAmong(ours, chrome, 'generic:'); + assert.ok(!ours.flat().some(n => n.startsWith('button'))); + assert.ok(!chrome.flat().some(n => n.startsWith('button'))); + }); + + test('the changes of one task come in one event', async () => { + await fresh(); + const { ours } = await after(`const b = document.getElementById('b'); + b.setAttribute('aria-label', 'L1'); b.setAttribute('aria-label', 'L2')`); + assert.deepEqual(ours, [['button:L2']]); + }); + + test('a child given by getChildAXNodes is sent', async () => { + await fresh(); + const { ours, chrome } = await after(`const d = document.getElementById('d'); + d.setAttribute('role', 'note'); d.setAttribute('aria-label', 'Y')`); + assertAmong(ours, chrome, 'note:Y'); + }); + + test('a node not given to the client is not sent', async () => { + await fresh(); + const { ours, chrome } = await after(`const e = document.getElementById('e'); + e.setAttribute('role', 'note'); e.setAttribute('aria-label', 'Y')`); + assert.deepEqual(ours, []); + assert.deepEqual(chrome, []); + }); + + test('getFullAXTree gives no node that is sent', async () => { + await setBody(t, FIXTURE); + await Promise.all([t.ours.send('Accessibility.disable'), chrome.send('Accessibility.disable')]); + await Promise.all([t.ours.send('Accessibility.enable'), chrome.send('Accessibility.enable')]); + await Promise.all([t.ours.send('Accessibility.getFullAXTree'), chrome.send('Accessibility.getFullAXTree')]); + const { ours, chrome: theirs } = await after(`document.getElementById('b').setAttribute('aria-label', 'F')`); + assert.deepEqual(ours, []); + assert.deepEqual(theirs, []); + }); + + test('nothing is sent after disable, nor for the nodes given before it once enabled again', async () => { + await fresh(); + await Promise.all([t.ours.send('Accessibility.disable'), chrome.send('Accessibility.disable')]); + let r = await after(`document.getElementById('b').setAttribute('aria-label', 'D')`); + assert.deepEqual(r, { ours: [], chrome: [] }); + await Promise.all([t.ours.send('Accessibility.enable'), chrome.send('Accessibility.enable')]); + r = await after(`document.getElementById('b').setAttribute('aria-label', 'E')`); + assert.deepEqual(r, { ours: [], chrome: [] }); + }); + + test('a command right after a change gives the new tree', async () => { + await fresh(); + const b = await backendIds('b'); + const name = async () => { + const { nodes } = await t.ours.send('Accessibility.getPartialAXTree', { + backendNodeId: b.ours, + fetchRelatives: false, + }); + return nodes[0]?.name?.value; + }; + for (const label of ['N1', 'N2']) { + await t.page.evaluate(l => document.getElementById('b')?.setAttribute('aria-label', l), label); + assert.equal(await name(), label); + } + // A style change the observer does not see (the CSSOM) still shows in the next command. + await t.page.evaluate(() => document.head.appendChild(document.createElement('style'))); + await sleep(100); + await t.page.evaluate(() => [...document.styleSheets].at(-1)?.insertRule('#b { display: none }')); + const { nodes } = await t.ours.send('Accessibility.getPartialAXTree', { + backendNodeId: b.ours, + fetchRelatives: false, + }); + assert.equal(nodes[0]?.ignored, true); + }); +}); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-manual.conformance.test.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-manual.conformance.test.ts new file mode 100644 index 00000000..b8a86862 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-manual.conformance.test.ts @@ -0,0 +1,18 @@ +// Names and descriptions of web-platform-tests' manual accname tests and dom-accessibility-api's +// description tests, compared with real Chrome one element at a time. The input HTML is in +// cases/manual.html, imported from dom-accessibility-api (commit +// a1828981f407b6cd6dc9d7b1046a618af93d0270; MIT License, Copyright (c) 2020 Sebastian Silbermann) +// and web-platform-tests (commit 73abd6299d0100763f0dfab7d30947282f626021; The 3-Clause BSD +// License, Copyright © web-platform-tests contributors). The expected values are Chrome's, not theirs. +// The licenses in full: cases/LICENSES. +import { MANUAL_SETUPS, describeCases, readCases } from '../../../../../test-support/accessibility.ts'; + +/** Cases that differ from Chrome on the current implementation, by what differs. */ +const TODO: Record = {}; + +describeCases(readCases(new URL('cases/manual.html', import.meta.url)), { + todo: TODO, + setups: MANUAL_SETUPS, + // An image input's default label is the browser's localized "Submit". + localized: ['devtools-anywhere image input names'], +}); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-names-by-element.conformance.test.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-names-by-element.conformance.test.ts new file mode 100644 index 00000000..54440e40 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-names-by-element.conformance.test.ts @@ -0,0 +1,699 @@ +// Accessible names by element, after web-platform-tests' html-aam/accname-computation-by-element +// (commit 73abd6299d0100763f0dfab7d30947282f626021; The 3-Clause BSD License, Copyright © +// web-platform-tests contributors): each file's testConfig, and its pages built anew the way +// html-aam/scripts/html-aam-accname-utils.js builds them (buildNameComputationTest), compared with +// real Chrome one element at a time. The expected values are Chrome's, not WPT's. +// The licenses in full: cases/LICENSES. +import { describeCases } from '../../../../../test-support/accessibility.ts'; +import type { CaseGroup } from '../../../../../test-support/accessibility.ts'; + +interface Properties { + descendants?: string[]; + ancestors?: string[]; + attrs?: string[]; + specialContext?: 'area' | 'ruby' | 'rp' | 'rt'; +} +interface Config { + elements: Record; + nameSources: string[]; +} + +/** Each WPT file's testConfigs, in the order the file builds them (keys it ignores left out). */ +const CONFIGS: Record = { + a: [ + { + elements: { + a: { + attrs: ['href'], + }, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from subtree', + 'from title', + 'to be empty', + ], + }, + ], + area: [ + { + elements: { + area: { + attrs: ['href'], + specialContext: 'area', + }, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from alt', + 'from empty alt', + 'from title', + 'to be empty', + ], + }, + ], + button: [ + { + elements: { + button: {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from 2 labels', + 'from 1 label', + 'from encapsulating label', + 'from subtree', + 'from title', + 'to be empty', + ], + }, + ], + fieldset: [ + { + elements: { + fieldset: {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from first legend', + 'from title', + 'to be empty', + ], + }, + ], + figure: [ + { + elements: { + figure: {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from title', + 'to be empty', + ], + }, + ], + iframe: [ + { + elements: { + iframe: {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from title', + 'to be empty', + ], + }, + ], + img: [ + { + elements: { + img: { + attrs: ['img src'], + }, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from alt', + 'from empty alt', + 'from title', + 'from ancestor figure figcaption', + 'to be empty', + ], + }, + ], + 'input-button-submit-reset': [ + { + elements: { + 'input[type="button"]': {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from 2 labels', + 'from 1 label', + 'from encapsulating label', + 'from value', + 'from title', + 'to be empty', + ], + }, + { + elements: { + 'input[type="submit"]': {}, + 'input[type="reset"]': {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from 2 labels', + 'from 1 label', + 'from encapsulating label', + 'from value', + ], + }, + ], + 'input-image': [ + { + elements: { + 'input[type="image"]': { + attrs: ['img src'], + }, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from 2 labels', + 'from 1 label', + 'from encapsulating label', + 'from alt', + 'from empty alt', + 'from title', + ], + }, + ], + 'inputs-with-placeholders': [ + { + elements: { + 'input[type="email"]': { + attrs: ['value'], + }, + 'input[type="number"]': { + attrs: ['value'], + }, + 'input[type="password"]': { + attrs: ['value'], + }, + 'input[type="search"]': { + attrs: ['value'], + }, + 'input[type="tel"]': { + attrs: ['value'], + }, + 'input[type="text"]': { + attrs: ['value'], + }, + 'input[type="url"]': { + attrs: ['value'], + }, + textarea: { + descendants: ['textNode'], + }, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from 2 labels', + 'from 1 label', + 'from encapsulating label', + 'from title', + 'from placeholder', + 'from aria-placeholder', + 'to be empty', + ], + }, + ], + 'other-form-elements': [ + { + elements: { + 'input[type="checkbox"]': {}, + 'input[type="radio"]': {}, + select: { + descendants: ['option', 'textNode'], + }, + 'input[type="color"]': {}, + 'input[type="date"]': {}, + 'input[type="datetime-local"]': {}, + 'input[type="file"]': {}, + 'input[type="month"]': {}, + 'input[type="range"]': {}, + 'input[type="time"]': {}, + 'input[type="week"]': {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from 2 labels', + 'from 1 label', + 'from title', + 'to be empty', + ], + }, + { + elements: { + optgroup: {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from label attribute', + 'from title', + 'to be empty', + ], + }, + ], + output: [ + { + elements: { + output: {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from 2 labels', + 'from 1 label', + 'from title', + 'to be empty', + ], + }, + ], + 'phrasing-elements': [ + { + elements: { + dfn: { + descendants: ['textNode'], + }, + ruby: { + specialContext: 'ruby', + }, + hr: {}, + abbr: { + descendants: ['textNode'], + }, + b: { + descendants: ['textNode'], + }, + bdi: { + descendants: ['textNode'], + }, + bdo: { + descendants: ['textNode'], + }, + br: {}, + cite: { + descendants: ['textNode'], + }, + code: { + descendants: ['textNode'], + }, + em: { + descendants: ['textNode'], + }, + i: { + descendants: ['textNode'], + }, + kbd: { + descendants: ['textNode'], + }, + mark: { + descendants: ['textNode'], + }, + q: { + descendants: ['textNode'], + }, + rp: { + specialContext: 'rp', + }, + rt: { + specialContext: 'rt', + }, + s: { + descendants: ['textNode'], + }, + samp: { + descendants: ['textNode'], + }, + small: { + descendants: ['textNode'], + }, + strong: { + descendants: ['textNode'], + }, + sub: { + descendants: ['textNode'], + }, + sup: { + descendants: ['textNode'], + }, + time: { + descendants: ['textNode'], + }, + u: { + descendants: ['textNode'], + }, + var: { + descendants: ['textNode'], + }, + wbr: {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from title', + 'to be empty', + ], + }, + ], + 'section-and-grouping-elements': [ + { + elements: { + header: {}, + nav: {}, + search: {}, + form: {}, + main: {}, + section: {}, + article: {}, + aside: {}, + footer: {}, + hgroup: {}, + dialog: {}, + address: {}, + application: {}, + audio: {}, + video: {}, + ul: {}, + ol: {}, + dl: {}, + meter: {}, + progress: {}, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from title', + 'to be empty', + ], + }, + ], + summary: [ + { + elements: { + summary: { + ancestors: ['details'], + }, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from subtree', + 'from title', + ], + }, + ], + table: [ + { + elements: { + table: { + descendants: ['tbody', 'tr', 'td', 'textNode'], + }, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from first caption', + 'from title', + 'to be empty', + ], + }, + ], + 'tr-td-th.tentative': [ + { + elements: { + tr: { + ancestors: ['table', 'tbody'], + descendants: ['td', 'textNode'], + }, + th: { + ancestors: ['table', 'thead', 'tr'], + descendants: ['textNode'], + }, + td: { + ancestors: ['table', 'tbody', 'tr'], + descendants: ['textNode'], + }, + thead: { + ancestors: ['table'], + descendants: ['tr', 'th', 'textNode'], + }, + tbody: { + ancestors: ['table'], + descendants: ['tr', 'td', 'textNode'], + }, + tfoot: { + ancestors: ['table'], + descendants: ['tr', 'td', 'textNode'], + }, + }, + nameSources: [ + 'from 2 aria-labelledby refs', + 'from 1 aria-labelledby ref', + 'from aria-label', + 'from title', + 'to be empty', + ], + }, + ], +}; + +/** + * Builds a WPT file's page into the body, as buildNameComputationTests does: for each element, + * one case per name source, each with all the sources from it on. Runs in the page. + */ +function build(configs: Config[], prefix: string) { + const nameValues: Record = { + 'from 1 aria-labelledby ref': 'aria-labelledby ref element #1 text contents', + 'from 2 aria-labelledby refs': 'aria-labelledby ref element #2 text contents', + 'from aria-label': 'aria-label attribute value', + 'from 1 label': 'associated label #1 text contents', + 'from 2 labels': 'associated label #2 text contents', + 'from subtree': 'subtree text contents', + 'from encapsulating label': 'encapsulating label text contents', + 'from first legend': 'legend text contents', + 'from first caption': 'caption text contents', + 'from value': 'value attribute value', + 'from label attribute': 'label attribute value', + 'from alt': 'alt attribute value', + 'from empty alt': '', + 'from title': 'title attribute value', + 'from placeholder': 'placeholder attribute value', + 'from aria-placeholder': 'aria-placeholder attribute value', + 'from ancestor figure figcaption': 'ancestor figure figcaption text contents', + }; + // A 50×50 PNG, so that the images have a size. + const img = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAMAAAAp4XiDAAAAP1BMVEWqAKoAAACrAKuqAKqrAKuvAK+vAK+nAKepAKmsAKyrAKutAK2oAKixALGqAKqqAKqqAKqqAKqqAKqqAKqqAKqx+4SNAAAAFHRSTlMzAL9gQBAgIKCfKxQZBu/fr4BwUHCcwvYAAAEASURBVEjHvdbLEoMgDAVQbkKg9f3I/39rpdiZutHAgrtywZkxESEOxTmJCLwqA6SK9PgCXqoeUCWAVR3kQvZpRbwnETzzHyFd8BhS+iNxG4fO3aYLI8cfYQronSE9Au1fMisnYTGbTnIQYRqdMVhWybVEKxlyLS6gs5IOwR9EFc4cqNYRZjvJqwGUEKCOEJUQojYda1a+9yXEt9sw77edpNVtOlbxYm06VvEp23SsTfkVP3Kb8iuOvnYbpuyycLn8wUpCLl/WBVYyEksik269TQysMw6CnaL1Eo/EiaQEHuPTqDBgC5eBhPCY5TKQ8MzPY8867SfJEbh74iGCkxTnA3SZDugOkmV1AAAAAElFTkSuQmCC'; + const voids = new Set([ + 'AREA', + 'BASE', + 'BR', + 'COL', + 'EMBED', + 'HR', + 'IMG', + 'INPUT', + 'LINK', + 'META', + 'PARAM', + 'SOURCE', + 'TRACK', + 'WBR', + ]); + let testId = 0; + const parts: string[] = []; + + const special = (elTest: HTMLElement, context: string, id: number): HTMLElement | null => { + const text = (parent: Node, tag: string, value: string) => + parent.appendChild(document.createElement(tag)).appendChild(document.createTextNode(value)); + if (context === 'area') { + const map = document.createElement('map'); + const image = document.createElement('img'); + map.setAttribute('name', `map-${id}`); + map.appendChild(elTest); + image.setAttribute('usemap', `#map-${id}`); + image.src = img; + elTest.setAttribute('alt', 'Mapped image alt attribute value'); + elTest.setAttribute('shape', 'rect'); + elTest.setAttribute('coords', '0,0,20,20'); + const div = document.createElement('div'); + div.append(map, image); + return div; + } + if (context === 'ruby') { + elTest.appendChild(document.createTextNode('ruby text node contents')); + text(elTest, 'rp', 'rp #1'); + text(elTest, 'rt', 'rt'); + text(elTest, 'rp', 'rp #2'); + return null; + } + const ruby = document.createElement('ruby'); + ruby.appendChild(document.createTextNode('ruby text node contents')); + if (context === 'rp') { + ruby.appendChild(elTest); + elTest.appendChild(document.createTextNode('rp #1')); + text(ruby, 'rt', 'rt'); + } else { + text(ruby, 'rp', 'rp #1'); + ruby.appendChild(elTest); + elTest.appendChild(document.createTextNode('rt')); + } + text(ruby, 'rp', 'rp #2'); + return ruby; + }; + + const one = (selector: string, nameSources: string[], properties: Properties) => { + const id = ++testId; + const [, element = '', attrName, attrValue] = /^(\w+)(?:\[(\w+)="([\w-]+)"\])?$/.exec(selector) ?? []; + const expSource = nameSources[0]; + let preamble = `

    ${selector} expecting name ${expSource}

    `; + const elTest = document.createElement(element); + if (attrName) elTest.setAttribute(attrName, attrValue ?? ''); + elTest.id = `${prefix}-el-${id}`; + elTest.className = 'ex-label'; + if (properties.attrs?.includes('value')) elTest.setAttribute('value', `${element} value attribute value`); + if (properties.attrs?.includes('href')) elTest.setAttribute('href', '#'); + if (properties.attrs?.includes('img src')) elTest.setAttribute('src', img); + let elReturn: HTMLElement | null = null; + if (properties.ancestors) + elReturn = properties.ancestors.reduceRight((descendant, tag) => { + const ancestor = document.createElement(tag); + ancestor.appendChild(descendant); + return ancestor; + }, elTest); + if (properties.descendants) { + let tagPrevious = element; + properties.descendants.reduce((ancestor, tag) => { + const descendant = + tag === 'textNode' + ? document.createTextNode(`${tagPrevious} text node contents`) + : document.createElement(tag); + ancestor.appendChild(descendant); + tagPrevious = tag; + return descendant; + }, elTest); + } + if (properties.specialContext) elReturn = special(elTest, properties.specialContext, id); + elReturn ??= elTest; + + if (expSource === 'from ancestor figure figcaption') { + const figure = document.createElement('figure'); + const figcaption = document.createElement('figcaption'); + figcaption.textContent = nameValues[expSource] ?? ''; + figure.append(elReturn, figcaption); + elReturn = figure; + } + if (expSource === 'from encapsulating label') { + const label = document.createElement('label'); + label.append(nameValues[expSource] ?? '', elReturn); + elReturn = label; + } + if (nameSources.includes('from 1 label')) + preamble += ``; + if (nameSources.includes('from 2 labels')) + preamble += ``; + if (nameSources.includes('from 1 aria-labelledby ref')) { + preamble += `

    ${nameValues['from 1 aria-labelledby ref']}

    `; + elTest.setAttribute('aria-labelledby', `${elTest.id}-label-1`); + } + if (nameSources.includes('from 2 aria-labelledby refs')) { + preamble += `

    ${nameValues['from 2 aria-labelledby refs']}

    `; + elTest.setAttribute('aria-labelledby', `${elTest.id}-label-1 ${elTest.id}-label-2`); + } + if (nameSources.includes('from subtree')) + elTest.appendChild(document.createTextNode(`${element} ${nameValues['from subtree']}`)); + for (const source of ['from first legend', 'from first caption']) + if (nameSources.includes(source)) { + const child = source.replace('from first ', ''); + elTest.insertAdjacentHTML('afterbegin', `<${child}>Duplicate ${nameValues[source]}`); + elTest.insertAdjacentHTML('afterbegin', `<${child}>${nameValues[source]}`); + } + for (const source of [ + 'from aria-label', + 'from aria-placeholder', + 'from value', + 'from alt', + 'from title', + 'from placeholder', + 'from label attribute', + ]) + if (nameSources.includes(source)) { + const attr = source.replace('from ', '').replace(' attribute', ''); + elTest.setAttribute( + attr, + source === 'from alt' ? (nameValues[source] ?? '') : `${element} ${nameValues[source]}` + ); + } + if (expSource === 'from empty alt') elTest.setAttribute('alt', ''); + if (!elTest.hasChildNodes() && !voids.has(elTest.nodeName)) { + const image = document.createElement('img'); + image.src = img; + elTest.appendChild(image); + } + parts.push(preamble + elReturn.outerHTML); + }; + + for (const config of configs) + for (const [selector, properties] of Object.entries(config.elements)) + for (let i = 0; i < config.nameSources.length; i++) one(selector, config.nameSources.slice(i), properties); + document.body.insertAdjacentHTML('beforeend', `

    ${prefix}

    ` + parts.join('')); +} + +/** + * Cases whose node Chrome gives text in the browser's language: the default name of an image + * input, the file input's button and label, the video's "cannot play" message. + */ +const LOCALIZED = new Set([ + ...Array.from({ length: 9 }, (_, i) => `input-image-el-${i + 1}`), + ...Array.from({ length: 7 }, (_, i) => `other-form-elements-el-${i + 43}`), + ...Array.from({ length: 5 }, (_, i) => `section-and-grouping-elements-el-${i + 71}`), +]); + +const groups: CaseGroup[] = Object.entries(CONFIGS).map(([file, configs]) => { + const ids: string[] = []; + for (const config of configs) + for (const _ of Object.keys(config.elements)) + for (const __ of config.nameSources) ids.push(`${file}-el-${ids.length + 1}`); + return { + name: `wpt html-aam/accname-computation-by-element/${file}.html`, + html: '', + ids: ids.filter(id => !LOCALIZED.has(id)), + }; +}); + +/** Cases that differ from Chrome on the current implementation, by what differs. */ +const TODO = {}; + +describeCases(groups, { + todo: TODO, + setups: Object.fromEntries( + Object.entries(CONFIGS).map(([file, configs]) => [ + `wpt html-aam/accname-computation-by-element/${file}.html`, + `(${build.toString()})(${JSON.stringify(configs)}, ${JSON.stringify(file)})`, + ]) + ), +}); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-names.conformance.test.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-names.conformance.test.ts new file mode 100644 index 00000000..82d5997c --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-names.conformance.test.ts @@ -0,0 +1,47 @@ +// Accessible names (accname), compared with real Chrome one element at a time. The input HTML is +// in cases/names.html, imported from dom-accessibility-api (commit +// a1828981f407b6cd6dc9d7b1046a618af93d0270; MIT License, Copyright (c) 2020 Sebastian Silbermann) +// and web-platform-tests (commit 73abd6299d0100763f0dfab7d30947282f626021; The 3-Clause BSD +// License, Copyright © web-platform-tests contributors). The expected values are Chrome's, not theirs. +// The licenses in full: cases/LICENSES. +import { describeCases, readCases } from '../../../../../test-support/accessibility.ts'; + +/** Cases that differ from Chrome on the current implementation, by what differs. */ +const TODO = {}; + +describeCases(readCases(new URL('cases/names.html', import.meta.url)), { + todo: TODO, + // What the cases' scripts did, written anew. + setups: { + 'dom-accessibility-api script and shadow roots': () => { + // Adjacent text nodes are joined without a space. + const h1 = document.getElementById('lib-A19'); + for (const text of ['Hello ', 'Jill', '!']) h1?.appendChild(document.createTextNode(text)); + }, + 'wpt accname/name/shadowdom/basic.html': () => { + const shadow = (id: string, html: string) => { + const root = document.getElementById(id)?.attachShadow({ mode: 'open' }); + if (root) root.innerHTML = html; + }; + shadow('host1', 'foo'); + shadow('host2', '
    '); + }, + 'wpt accname/name/shadowdom/slot.html': () => { + const shadow = (id: string, html: string) => { + const root = document.getElementById(id)?.attachShadow({ mode: 'open' }); + if (root) root.innerHTML = html; + }; + shadow('host1', 'foo bar'); + shadow('host2', 'foo default bar'); + shadow('host3', 'foo bar'); + shadow('host4', 'foo default bar'); + }, + 'wpt accname/name/comp_name_from_content_alt_counter_invalidation.html': () => { + // The counter changes after a first layout. + void document.documentElement.offsetTop; + const rule = document.body.querySelector('style')?.sheet?.cssRules[0]; + if (rule instanceof CSSStyleRule) rule.style.setProperty('counter-set', 'cnt 228'); + void document.documentElement.offsetTop; + }, + }, +}); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-roles.conformance.test.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-roles.conformance.test.ts new file mode 100644 index 00000000..d8d8f081 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-roles.conformance.test.ts @@ -0,0 +1,13 @@ +// Roles (and the states the library's isInaccessible and isDisabled read), compared with real +// Chrome one element at a time. The input HTML is in cases/roles.html, imported from +// dom-accessibility-api (commit a1828981f407b6cd6dc9d7b1046a618af93d0270; MIT License, +// Copyright (c) 2020 Sebastian Silbermann) and web-platform-tests (commit +// 73abd6299d0100763f0dfab7d30947282f626021; The 3-Clause BSD License, Copyright © +// web-platform-tests contributors). The expected values are Chrome's, not theirs. +// The licenses in full: cases/LICENSES. +import { describeCases, readCases } from '../../../../../test-support/accessibility.ts'; + +/** Cases that differ from Chrome on the current implementation, by what differs. */ +const TODO = {}; + +describeCases(readCases(new URL('cases/roles.html', import.meta.url)), { todo: TODO }); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-tree.conformance.test.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-tree.conformance.test.ts new file mode 100644 index 00000000..5aa3ba84 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility-tree.conformance.test.ts @@ -0,0 +1,131 @@ +// The whole tree (Accessibility.getFullAXTree) of every case group, compared with real Chrome: +// roles, names, which nodes are ignored and how they nest. The per-element tests compare a node's +// fields; these compare the shape around them. Inline text boxes are left out on both sides: the +// page cannot see them, so we will not make them, and their text stays as their StaticText +// parent's name. Set AX_TREE_REPORT= to append each +// differing group's lines only one side has, by kind, and both outlines to the file as JSON lines. +import { appendFileSync } from 'node:fs'; +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { launch, setUpAndTearDown } from '../../../../../test-support/conformance.ts'; +import type { Env, TestPage } from '../../../../../test-support/conformance.ts'; +import { + MANUAL_SETUPS, + fullTree, + listedTree, + openAxPage, + readCases, + setBody, + treeDiff, + treeDiffKind, +} from '../../../../../test-support/accessibility.ts'; + +// Known differences that stay: a details without a summary has Chrome's default summary, whose +// text is the browser's localized "Details", which the page cannot know; a video or audio has +// Chrome's name for media that cannot play, also localized, and the ignored nodes of its media +// controls, which change with the browser version and the media's state (docs/limitations.md). +/** Groups ("file: group") whose tree differs from Chrome's on the current implementation, by what differs. */ +const TODO: Record = { + 'other nodes differ': [ + 'roles: dom-accessibility-api roles', + 'names: wpt accname/name/comp_label.html', + 'manual: wpt accname/manual/name_test_case_548-manual.html', + 'names: dom-accessibility-api names', + 'roles: wpt html-aam/optgroup-role.tentative.html', + 'roles: wpt wai-aria/role/role_none_conflict_resolution.tentative.html', + 'roles: wpt wai-aria/role/role_none_conflict_resolution_spec_ambiguities.tentative.html', + 'names: wpt html-aam/summary.html', + 'manual: wpt accname/manual/name_test_case_544-manual.html', + 'manual: wpt accname/manual/name_test_case_546-manual.html', + 'manual: wpt accname/manual/name_test_case_547-manual.html', + 'manual: wpt accname/manual/name_test_case_549-manual.html', + 'manual: wpt accname/manual/name_test_case_550-manual.html', + 'manual: wpt accname/manual/name_test_case_551-manual.html', + 'manual: wpt accname/manual/name_test_case_552-manual.html', + 'manual: wpt accname/manual/name_test_case_553-manual.html', + 'manual: wpt accname/manual/name_test_case_556-manual.html', + 'manual: wpt accname/manual/name_test_case_558-manual.html', + 'manual: wpt accname/manual/name_test_case_559-manual.html', + 'manual: wpt accname/manual/name_test_case_560-manual.html', + 'manual: wpt accname/manual/name_test_case_561-manual.html', + 'manual: wpt accname/manual/name_test_case_562-manual.html', + 'manual: wpt accname/manual/name_test_case_563-manual.html', + 'manual: wpt accname/manual/name_test_case_564-manual.html', + 'manual: wpt accname/manual/name_test_case_565-manual.html', + 'manual: wpt accname/manual/name_test_case_566-manual.html', + 'manual: wpt accname/manual/name_test_case_604-manual.html', + ], + 'input inner nodes differ; other nodes differ': ['names: wpt accname/name/comp_embedded_control.html'], + 'input inner nodes differ': ['names: wpt accname/name/comp_host_language_label.html'], +}; + +/** Groups whose listed nodes differ from Chrome's though their tree does not, by what differs. */ +const LISTED_TODO = new Map(Object.entries({})); + +let env: Env | undefined; +let t: TestPage; +setUpAndTearDown( + async () => { + env = await launch(); + t = await openAxPage(env); + }, + () => env?.close() +); + +const todo = new Map(); +for (const [reason, groups] of Object.entries(TODO)) for (const group of groups) todo.set(group, reason); + +const files: [string, Record void) | string>][] = [ + ['roles', {}], + ['names', {}], + ['manual', MANUAL_SETUPS], +]; +for (const [file, setups] of files) + describe(file, () => { + for (const group of readCases(new URL(`cases/${file}.html`, import.meta.url))) { + const key = `${file}: ${group.name}`; + test(group.name, { todo: todo.get(key) ?? LISTED_TODO.get(key) }, async () => { + await setBody(t, group.html); + const setup = setups[group.name]; + if (setup) await t.page.evaluate(setup); + const [ours, chrome] = await Promise.all([fullTree(t.ours), fullTree(t.chrome)]); + const report = process.env['AX_TREE_REPORT']; + if (report) { + const diff = treeDiff(ours, chrome); + if (diff.length) + appendFileSync( + report, + JSON.stringify({ + group: key, + diff: diff.map(d => ({ + side: d.side, + kind: treeDiffKind(d.line), + line: d.line.text, + parent: d.line.ancestors.at(-1), + })), + ours: ours.map(l => l.text), + chrome: chrome.map(l => l.text), + }) + '\n' + ); + } + assert.deepEqual( + ours.map(l => l.text), + chrome.map(l => l.text) + ); + // Then the nodes as getFullAXTree lists them, in Chrome's order, with the pseudo-elements + // whose backend ids list markers and generated content carry. In the same test: setting a + // group's body again changes how Chrome breaks aria-owns cycles. + // Asked again while they differ: Chrome may still be settling a node (a summary's generic + // was seen to turn ignored between two calls on a busy runner), while ours does not change. + for (let attempt = 1; ; attempt++) { + const [listedOurs, listedChrome] = await Promise.all([listedTree(t.ours, true), listedTree(t.chrome, false)]); + if (attempt < 3 && JSON.stringify(listedOurs) !== JSON.stringify(listedChrome)) { + await new Promise(r => setTimeout(r, 200)); + continue; + } + assert.deepEqual(listedOurs, listedChrome, 'listed order and pseudo-element ids'); + break; + } + }); + } + }); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility.conformance.test.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility.conformance.test.ts new file mode 100644 index 00000000..5317e8e9 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/accessibility.conformance.test.ts @@ -0,0 +1,425 @@ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; +import type { Protocol } from 'devtools-protocol'; +import { launch, setUpAndTearDown } from '../../../../../test-support/conformance.ts'; +import type { Env, Side, TestPage } from '../../../../../test-support/conformance.ts'; +import { comparable, nodeIdOf, openAxPage, outline } from '../../../../../test-support/accessibility.ts'; + +let env: Env | undefined; +let t: TestPage; + +/** + * Elements of the cases the Accessibility pane shows, each with an id to find it on both sides. + * Left out: what the page cannot see or Chrome gives in the browser's language (an input + * button's default label). + */ +const FIXTURE = ` +
    a + + + + + + + + + +
    H
    c
    +
    focusable
    + + +
    SD
    +

    One

    +

    Para bold

    + + +no href + +Svg t +
    owner
    ownee +
    A
    B
    +
    C
    D
    +
    +
    Site
    +
    art head
    art foot
    +
    foot
    + +
    H
    +
    + + + + + +
    +
    1. a
      • b
    +
    +
    Panel
    + +
    edit
    +

    lvl

    +
    rh
    + +logo +
    S
    +tt +
    RB
    + +
    +
    T
    D
    +
    q
    +
    Leg
    +
    f
    Cap
    +
    Cap
    A
    Rv
    +`; + +setUpAndTearDown( + async () => { + env = await launch(); + t = await openAxPage(env, FIXTURE); + }, + () => env?.close() +); + +const ids = [...FIXTURE.matchAll(/ id=(\w+)/g)].map(m => m[1] ?? ''); + +describe('Accessibility.getPartialAXTree', () => { + for (const id of ids) + test(`#${id}: role, name and its sources, description, value, properties`, async () => { + const [ours, chrome] = await Promise.all( + [t.ours, t.chrome].map(async side => + side.send('Accessibility.getPartialAXTree', { nodeId: await nodeIdOf(side, id), fetchRelatives: false }) + ) + ); + assert.ok(ours && chrome); + assert.deepEqual(ours.nodes.map(comparable), chrome.nodes.map(comparable)); + }); + + test('fetchRelatives: the children, through ignored ones, and the ancestors', async () => { + for (const id of [ + 'nv', + 'ul', + 'tb', + 'th1', + 'h1', + 'pp', + 'own', + 'ownee', + 'cy1', + 'cy2', + 'cy3', + 'cy4', + 'cy5', + 'pr', + 'sp', + 'dp', + ]) { + const [ours, chrome] = await Promise.all( + [t.ours, t.chrome].map(async side => + side.send('Accessibility.getPartialAXTree', { nodeId: await nodeIdOf(side, id), fetchRelatives: true }) + ) + ); + assert.ok(ours && chrome); + assert.deepEqual(outline(ours.nodes), outline(chrome.nodes), `#${id}`); + } + }); + + test('the root is the document, named after its title', async () => { + const [ours, chrome] = await Promise.all( + [t.ours, t.chrome].map(async side => + side.send('Accessibility.getPartialAXTree', { nodeId: await nodeIdOf(side, 'root'), fetchRelatives: true }) + ) + ); + assert.ok(ours && chrome); + const root = (r: typeof ours) => r.nodes.find(n => n.role?.value === 'RootWebArea'); + const [a, b] = [root(ours), root(chrome)]; + assert.ok(a && b); + // The URL and focus are each side's page's. + const props = (n: Protocol.Accessibility.AXNode) => + (n.properties ?? []).filter(p => p.name !== 'focused' && p.name !== 'url'); + assert.deepEqual(comparable({ ...a, properties: props(a) }), comparable({ ...b, properties: props(b) })); + }); +}); + +test('without accessibility.js the commands fail', async () => { + await assert.rejects( + t.page.evaluate(async () => { + const plain = window.DevtoolsAnywhere.createCdpSession(); + const { root } = (await plain.call('DOM.getDocument', {})) as { root: { nodeId: number } }; + await plain.call('Accessibility.getPartialAXTree', { nodeId: root.nodeId }); + }), + /Not supported in the page/ + ); +}); + +describe('the whole tree', () => { + test('queryAXTree finds nodes by role and name in a subtree', async () => { + const queries = [ + { role: 'button' }, + { accessibleName: 'One' }, + { role: 'textbox', accessibleName: 'Type' }, + { role: 'heading' }, + { role: 'none' }, + // Ignored nodes come with their own role and name: those aria-hidden hides; display:none, + // visibility:hidden and role=presentation leave theirs out of the tree. + { role: 'paragraph' }, + { accessibleName: 'hidden' }, + { accessibleName: 'none' }, + { accessibleName: 'vh' }, + { accessibleName: 'pres' }, + ]; + for (const query of queries) { + const [ours, chrome] = await Promise.all( + [t.ours, t.chrome].map(async side => + side.send('Accessibility.queryAXTree', { nodeId: await nodeIdOf(side, 'root'), ...query }) + ) + ); + assert.ok(ours && chrome); + assert.deepEqual(ours.nodes.map(comparable), chrome.nodes.map(comparable), JSON.stringify(query)); + } + }); + + test('getAXNodeAndAncestors', async () => { + for (const id of ['th1', 'ownee', 'bb']) { + const [ours, chrome] = await Promise.all( + [t.ours, t.chrome].map(async side => + side.send('Accessibility.getAXNodeAndAncestors', { nodeId: await nodeIdOf(side, id) }) + ) + ); + assert.ok(ours && chrome); + assert.deepEqual(outline(ours.nodes), outline(chrome.nodes), `#${id}`); + } + }); + + test('parentId and childIds agree, as in Chrome, in and out of a closed details', async () => { + // Each node as its role, whether ignored and its links, by place in the list: ids differ. + const links = (nodes: Protocol.Accessibility.AXNode[]) => { + const at = (id: string | undefined) => (id === undefined ? undefined : nodes.findIndex(n => n.nodeId === id)); + return nodes.map(n => ({ + role: n.role?.value, + ignored: n.ignored, + parent: at(n.parentId), + children: n.childIds?.map(at).filter(i => i !== -1), + })); + }; + // Added for this test only: a closed details changes how Chrome breaks the fixture's + // aria-owns cycles. + await t.page.evaluate(() => + document.body.insertAdjacentHTML( + 'beforeend', + '
    S

    TU

    ' + ) + ); + for (const id of ['dcp', 'dcb', 'dcs', 'su']) { + const [ours, chrome] = await Promise.all( + [t.ours, t.chrome].map(async side => { + const nodeId = await nodeIdOf(side, id); + const partial = await side.send('Accessibility.getPartialAXTree', { nodeId, fetchRelatives: true }); + const ancestors = await side.send('Accessibility.getAXNodeAndAncestors', { nodeId }); + return { partial: partial.nodes, ancestors: ancestors.nodes }; + }) + ); + assert.ok(ours && chrome); + for (const nodes of [ours.partial, ours.ancestors]) + for (const node of nodes) { + const parent = nodes.find(n => n.nodeId === node.parentId); + if (parent) + assert.ok(parent.childIds?.includes(node.nodeId), `#${id}: ${node.nodeId} not among its parent's children`); + } + assert.deepEqual(links(ours.partial), links(chrome.partial), `#${id} getPartialAXTree`); + assert.deepEqual(links(ours.ancestors), links(chrome.ancestors), `#${id} getAXNodeAndAncestors`); + } + await t.page.evaluate(() => document.getElementById('dc')?.remove()); + }); + + test('getRootAXNode and getChildAXNodes walk down to a node', async () => { + const walk = async (side: Side) => { + const { node: root } = await side.send('Accessibility.getRootAXNode', {}); + const seen = [outline([root])]; + // Down the first child each time, from the document to the fixture's first text. + let id = root.nodeId; + for (let i = 0; i < 5; i++) { + const { nodes } = await side.send('Accessibility.getChildAXNodes', { id }); + seen.push(outline(nodes)); + const next = nodes[0]; + if (!next) break; + id = next.nodeId; + } + return seen; + }; + const [ours, chrome] = await Promise.all([walk(t.ours), walk(t.chrome)]); + assert.deepEqual(ours, chrome); + }); + + test('getFullAXTree: the nodes the page can see, breadth first', async () => { + const [ours, chrome] = await Promise.all( + [t.ours, t.chrome].map(side => side.send('Accessibility.getFullAXTree', { depth: 1 })) + ); + assert.ok(ours && chrome); + assert.deepEqual(outline(ours.nodes), outline(chrome.nodes)); + }); +}); + +test('the vision deficiency mask is not in the accessibility tree', async () => { + const count = async () => (await t.ours.send('Accessibility.getFullAXTree', {})).nodes.length; + const plain = await count(); + await t.ours.send('Emulation.setEmulatedVisionDeficiency', { type: 'achromatopsia' }); + try { + assert.equal(await count(), plain); + } finally { + await t.ours.send('Emulation.setEmulatedVisionDeficiency', { type: 'none' }); + } +}); + +test('DOM methods the page replaced do not change the tree', async () => { + const full = async () => (await t.ours.send('Accessibility.getFullAXTree', {})).nodes.map(comparable); + const top = (side: Side) => side.send('Accessibility.getFullAXTree', { depth: 1 }); + const before = await full(); + // Replaces the methods and getters the tree reads with ones that lie or throw, keeping the originals. + await t.page.evaluate(() => { + const saved: [object, string, PropertyDescriptor][] = []; + const replace = (proto: object, name: string, desc: PropertyDescriptor) => { + const original = Object.getOwnPropertyDescriptor(proto, name); + if (original) saved.push([proto, name, original]); + Object.defineProperty(proto, name, { ...desc, configurable: true }); + }; + const fail = () => { + throw new Error('replaced by the page'); + }; + replace(Element.prototype, 'getAttribute', { value: () => 'button' }); + replace(Element.prototype, 'hasAttribute', { value: () => true }); + for (const name of [ + 'querySelector', + 'querySelectorAll', + 'closest', + 'matches', + 'getBoundingClientRect', + 'getAttributeNames', + ]) + replace(Element.prototype, name, { value: fail }); + for (const name of ['querySelector', 'querySelectorAll', 'getElementById']) + replace(Document.prototype, name, { value: fail }); + replace(DocumentFragment.prototype, 'getElementById', { value: fail }); + replace(Node.prototype, 'getRootNode', { value: fail }); + replace(Node.prototype, 'textContent', { get: () => 'lie' }); + replace(HTMLElement.prototype, 'innerText', { get: fail }); + replace(Element.prototype, 'attributes', { get: fail }); + (window as unknown as { __restoreDom: () => void }).__restoreDom = () => { + for (const [proto, name, desc] of saved) Object.defineProperty(proto, name, desc); + }; + }); + try { + assert.deepEqual(await full(), before); + const [ours, chrome] = await Promise.all([top(t.ours), top(t.chrome)]); + assert.deepEqual(outline(ours.nodes), outline(chrome.nodes)); + } finally { + await t.page.evaluate(() => (window as unknown as { __restoreDom: () => void }).__restoreDom()); + } +}); + +/** + * The nodes Chrome has under a control from its user-agent shadow tree, which the page cannot + * see (ax-virtual.ts): each control's subtree walked down by getChildAXNodes, its nodes whole, + * its ancestors and children by getPartialAXTree, and queryAXTree over the controls. + */ +describe('control internals', () => { + /** A node's relatives, and its subtree in depth-first order through getChildAXNodes. */ + const subtree = async (side: Side, id: string) => { + const nodeId = await nodeIdOf(side, id); + const partial = await side.send('Accessibility.getPartialAXTree', { nodeId, fetchRelatives: true }); + const out: unknown[] = []; + const walk = async (node: Protocol.Accessibility.AXNode, depth: number) => { + if (node.role?.value === 'InlineTextBox') return; + out.push({ depth, node: comparable(node) }); + for (const child of (await side.send('Accessibility.getChildAXNodes', { id: node.nodeId })).nodes) + if (child.parentId === node.nodeId) await walk(child, depth + 1); + }; + const [self] = partial.nodes; + assert.ok(self); + await walk(self, 0); + return { partial: outline(partial.nodes), subtree: out }; + }; + /** Compares the subtrees of `ids`, then the nodes of `roles` queryAXTree finds under #controls. */ + const compare = async (html: string, ids: string[], roles: string[]) => { + assert.ok(env); + const page = await openAxPage(env, `
    ${html}
    `); + try { + for (const id of ids) { + const [ours, chrome] = await Promise.all([subtree(page.ours, id), subtree(page.chrome, id)]); + assert.deepEqual(ours, chrome, `#${id}`); + } + for (const role of roles) { + const [ours, chrome] = await Promise.all( + [page.ours, page.chrome].map(async side => + side.send('Accessibility.queryAXTree', { nodeId: await nodeIdOf(side, 'controls'), role }) + ) + ); + assert.ok(ours && chrome); + assert.deepEqual(ours.nodes.map(comparable), chrome.nodes.map(comparable), `queryAXTree ${role}`); + } + } finally { + await page.page.close(); + } + }; + + test('select: options in a drop-down popup, in a list box slot, in groups', () => + compare( + ` + + + + + +`, + ['se1', 'se2', 'se2g', 'se3', 'se4', 'se5', 'se6', 'se7'], + ['option', 'group', 'MenuListPopup', 'generic'] + )); + + // Left out: date and time fields, file and image inputs, whose nodes Chrome names in the + // browser's language. + test('text fields: placeholder, wrappers, inner editor and its text; other inputs; contenteditable', () => + compare( + ` + + + + + + + + + +
    edit bold
    +
    line1
    line2
    tb
    +
    pt
    `, + Array.from({ length: 35 }, (_, i) => `tf${i + 1}`), + ['generic', 'StaticText', 'LineBreak', 'textbox', 'combobox'] + )); + + test('svg: title and desc name and describe, never nodes; image or SvgRoot; the elements kept', () => + compare( + `
    T1D1
    +
    T2
    +
    T3D3
    +
    GTTxtTTATlink
    +
    OnlyD
    +
    RTRD
    +
    xMixed
    +
    RootR
    +
    +
    hello world
    +

    fo

    +
    GR
    +
    inner
    +
    spaced title
    +
    dd
    +
    +
    in defs
    `, + Array.from({ length: 17 }, (_, i) => `sv${i + 1}`).concat('sv4t', 'sv4a', 'sv6r'), + ['image', 'SvgRoot', 'graphics-symbol', 'group', 'link', 'StaticText'] + )); +}); diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/LICENSES b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/LICENSES new file mode 100644 index 00000000..78696189 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/LICENSES @@ -0,0 +1,67 @@ +The input HTML in this directory, and the test files that build cases after +the same sources (../accessibility-*.conformance.test.ts), is taken from the +projects below. These files are only part of the repository's tests: they are +not in any build output or published package. + +================================================================================ +dom-accessibility-api +https://github.com/eps1lon/dom-accessibility-api +commit a1828981f407b6cd6dc9d7b1046a618af93d0270 +================================================================================ + +MIT License + +Copyright (c) 2020 Sebastian Silbermann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +================================================================================ +web-platform-tests +https://github.com/web-platform-tests/wpt +commit 73abd6299d0100763f0dfab7d30947282f626021 +================================================================================ + +# The 3-Clause BSD License + +Copyright © web-platform-tests contributors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/manual.html b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/manual.html new file mode 100644 index 00000000..35de7545 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/manual.html @@ -0,0 +1,1067 @@ + + +
    testfoo
    +
    testfoo
    + +
    +
    testfoo
    + +
    + +
    + English +
    + + + +
    +
    + + My name is +
    + + Zambino + + the weird. + (QED) + + + + + + + + +
    Where
    in
    the world
    are my marbles?
    +
    +
    + +United States + +a + +
    + +
    +
    foo
    + +
    + +
    + + +
    + +
    + + +test +
    foo
    + +test + + +test + foo + +test + + +test + +test +
    foo
    + +
    +
    Description
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + My name is +
    + + Zambino + + the weird. + (QED) + + + + + + + + +
    Where
    in
    the world
    are my marbles?
    +
    + + + + + + + +
    + + My name is +
    + + Zambino + + the weird. + (QED) + + + + + + + + +
    Where
    in
    the world
    are my marbles?
    +
    + + +
    + + + + + +
    + + +

    + Country of origin: + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Rich's button
    + + +
    Rich's button
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + a + + + + + + +
    foo
    + bar + +
    foo
    + +
    foo
    + bar + +
    foo
    + bar + baz + +
    Div with text
    + +
    foo
    + +
    +
    + +
    foo
    + bar + +ABC + +foo +

    bar

    + + +

    foo

    + +ABC + + + + +

    foo

    +

    bar

    +

    baz

    + + +
    foo
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    A
    B
    + +
    C
    D
    + +
    • a
    +
    • b
    +
    • c
    +
    • d
    +
    • e
    +
    f
    +
    g
    +
    h
    + +
    + + + +
    1. a
      1. b
    +
    +
    +
    +
    +
    +
    +
    +
    1. a
    1. a
    2. c
    +
    1. a
    2. b
    +
    +
    1. a
      1. b
    +
    +
    +
    +
    +
    +
    +
    +
    1. a
    +
    1. a
    2. b
    + + +
    + + + +
    +
    +
    +
    +
    1. disc
    2. cjk
    3. pad
    4. range
    5. negative
    + + +
    1. a
    2. b
      1. nested
    3. block
    +
    1. a
    2. b
    3. c
    4. d
    +
    • disc
    • circle
    • square
    • open
    • closed
    • string
    • empty string
    • inside
    • none
    • image
    • image, no type
    • unknown style
    +
    1. a
    2. b
    3. c
    4. d
    5. e
    6. f
    7. g
    8. h
    9. i
    10. j
    11. k
    +
    1. string
    2. strings
    3. counter
    4. counter and strings
    5. empty
    6. none
    7. alternative text
    +
    a div
    a span
    no marker

    a paragraph

    inline, draggable
    +
    • none
    • presentation, no marker
    • button
    • generic
    • hidden
    +
    • quotes
    • counter style rule
    +
    1. empty alternative text
    2. after
    + +
    +
    +
    +

    a + b

    c

    d e

    +

    a

    b + c

    d
    +

    a

    b
    c
    +
    +
    + + +

    slash in a string

    alternative text

    escaped quote and slash in a string

    slash without spaces

    slash in an attribute and in the alternative text

    + + +
    + + +
    xy
    x y
    y

    text

    y z
    y w
    y v
    y
    w
    y z
    xy
    y
    link
    alpha beta
    + +

    plain body

    + +

    body with aria-label

    + +

    body with an id

    + +

    body with a title

    + +

    editable body

    + +

    body with an onclick handler

    + +

    body with an onclick property

    + +

    body with lang and a data attribute

    + +
    S

    content

    text
    +
    S

    content

    text
    +

    before

    S1S2text
    +
    +
    • list
    • menu
    1. navigation
    • none
    • option
    +
    a b
    c
    d
    e f h i
    +
    inline only

    block child

    plain spanspan with lang

    positioned

    inline-block

    contents

    with an id

    inline-flex

    positioned span

    +
    +

    gone

    gone

    shown again

    label text
    + +
    Sab
    + +
    + +
    +
    j

    n

    +
    +
    + +
    text not shown
    +
    + +
    50% x
    + +
    + + +
    a
    d
    h
    v
    i
    x
    q
    again
    nested
    +
    c
    h
    b
    d
    f
    h
    d
    +
    a
    f
    +
    a
    i
    v
    s
    +
    Tx
    +
    a
    b
    c
    d
    ef
    + +

    x

    x

    not visible

    x

    inert

    x

    x

    +
    treasure

    reflection

    reflection

    vampinert owner

    vampnot visible

    vamp
    no box

    +

    xy

    pq
    + +
    x
    y
    + + +

    vr

    vr

    r

    r

    r

    + + +
    ref
    + +
    GoGo
    + +
    + +
    Foo
    Bar baz
    + +
    h
    f
    h
    + +
    h
    f
    h
    h
    h
    h
    + +
    f h
    + +
    Sab
    Stbe
    Sa
    d
    St
    Sa
    d
    Sa
    + +

    ac

    ac
    ac
    ac
    ac
    ac
    ac

    ac

    • ac
    ac
    ac
    x y
    + +
    abt

    at

    at
    t
    at
    t
    + +
    t
    b
    +
    t
    +
    u
    + +
    +
    +
    +
    Sc
    +
    Sc
    +
    bt
    +
    bt
    +
    bt
    +
    Sc
    bt
    +
    bt
    +
    bt
    +
    bt
    +
    bt
    +
    bt
    + +
    +
    btu
    + +
    i
    Cap
    Cap
    diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/names.html b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/names.html new file mode 100644 index 00000000..61007085 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/names.html @@ -0,0 +1,2688 @@ + + +
    greek alpha
    +
    +
    greek gamma
    +
    greek delta
    +
    greek zeta
    +
  • +
  • greek theta
  • +
  • greek iota
  • +
    +
    +
    +
    greeklambda
    +
    greek mu
    +
    greek nu
    +
    +
    +
  • greek pi
  • +
    +
    +
    a table
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    I reference my name
    +
    I reference my name
    I'm prohibited a name
    +
    hello
    +
    foo
    +
    the logo
    +

    Lorem ipsum

    +
    +
    +
    +
    +
    +

    Country of origin:

    +
    +
    +
    +
    +
    +
    +
    an image
    +
    +
    greek rho
    +
    greek rho
    +
    greek rho
    +
    greek rho
    +
    greek rho
    +
    +
    +
    +
    +
    +
    +
    named?
    +
    named?
    +
    named?
    +
    named?
    +
    named?
    +
    named?
    +
    named?
    +
    +
    named?
    +
    named?
    +
    named?
    +
    named?
    +
    named?
    + +

    +
    +
    Custom name
    +
    +
    Custom name
    + +
    + + + + + + +

    Accname tests for assorted combinations of aria-owns, aria-hidden, and host language hiding techniques

    + + + +

    is aria-hidden="true".

    +

    Bold text with a yellow background is the target of another element’s aria-owns.

    + +

    A button using aria-owns to specify its label

    + + +

    A link using aria-owns to concatenate extra text

    + + World Wide Web Consortium + + + +

    Ignore aria-owns when on an element that is hidden from all users

    +

    + + treasure +

    + +

    Computed name of parent heading persists when aria-owns fails to relocate its contents

    +

    + + + sand +

    +

    + + a pearl +

    + +

    Computed name of parent heading excludes content relocated by aria-owns

    +

    + + The dog that caught the + +

    +

    + Speeding + car +

    + +

    Ignore aria-owns when on an element with aria-hidden

    +

    + + reflection +

    + +

    Ignore aria-owns when it targets an element that is hidden from all users

    + + World Wide Web Consortium + +
    + + +
    + +

    Ignore aria-owns when it targets an element with an ancestor that is hidden from all users

    + + World Wide Web Consortium + + + +

    aria-hidden remains in effect on an element after it is relocated using aria-owns

    + + World Wide Web Consortium + +
    + + +
    + +

    Tests the #comp_embedded_control portions of the AccName Name Computation algorithm.

    + + + +

    + + + +

    + + + +

    + + + +

    + +

    + +

    + + + + + +

    + + + + +

    + +

    + +

    + +

    + +

    + +

    + + + + + + + + +

    + + + + +

    + + + + +

    + +

    Tests the #comp_hidden_not_referenced portions of the AccName Name Computation algorithm.

    + + + + + + + + + + visible to all users, + + + + + + +

    + visible to all users, + + hidden from all users, + un-hidden for all users + +

    + +

    Input with hidden label

    + + + +

    Table with hidden caption

    + + +
    + +

    Fieldset with hidden legend

    +
    + +
    + + + + + + + + + + + + +

    AccName: Host Language Label Tests

    +

    Tests the #comp_host_language_label portions of the AccName Name Computation algorithm.

    + +

    HTML input with value, alt, etc.

    + + + + + + +

    HTML input label/for

    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +

    HTML input label encapsulation

    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + + + + +

    HTML select

    + + + +
    + +
    + + + + +

    HTML img/picture

    + + +image label + + + picture label + + + + +  +
+ +  ++foo bar +foo
+bar +foo   bar +foo bar + +

    HTML fieldset/legend

    +
    + fieldset legend label +
    +
    + + +

    HTML table/caption

    + + + + +
    table caption label
    abc
    123
    + + + +

    HTML input with multiple label/for

    + + + + + + + + + + + + + + +

    HTML input with label with role none

    +

    HTML input label/for

    + + +

    HTML label encapsulation

    + + + +

    HTML input with role="none" and label associated (presentational roles conflict resolution)

    +

    HTML input label/for

    + + +

    HTML label encapsulation

    + + +

    HTML input with role="none" and label with role none (presentational roles conflict resolution)

    +

    HTML input label/for

    + + +

    HTML label encapsulation

    + + +

    SVG wrapping title with role="none"

    + + + circle + + + +

    HTML fieldset wrapping legend with role="none"

    +
    legend
    + +

    HTML table wrapping caption with role="none"

    + + + + + + + + + + +
    caption
    th1th2
    td1td2
    + +

    AccName: Label Tests

    +

    Tests the #comp_label portions of the AccName Name Computation algorithm.

    + + + + + +

    Elements with roles that support aria-label use

    + + + +
    x
    +
    x
    +
    x
    + + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + + + +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    +
    x
    +
    x
    + + + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    + + + +
    x
    +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    + + +
    x
    +
    x
    +
    x
    + +

    HTML elements that support aria-label

    + + +x +
    x
    + +
    x
    + +
    + + + + +
    x
    +
    x
    +
    +
    x
    +
    x
    +
    x
    +
    x
    +
    x
    +

    x

    +

    x

    +

    x

    +

    x

    +
    x
    +
    x
    +
    + + + + + +
  • x
  • +
    x
    +x +x + +
      x
    +
    x
    + + + + + + + + + + + + + + + + + + + + + +
    xx
    xx
    xx
    + +
      x
    + +

    Name computation precedence tests

    + + + + + + + + + + +x +label + + + + +alt + + + + + + + + + + + + + + +

    x

    + + + + + + +

    Empty/whitespace aria-label tests

    + + + +x + + +x + + + + + + + + + +

    Tests that the non-standard (misspelled) attribute name aria-labeledby is not supported.

    + +

    Tests for aria-labeledby

    + +
    +

    first heading

    +

    text inside div group

    +
    + +
    +

    + first heading

    +

    text inside div group

    +
    + +
    +

    + first heading

    +

    text inside div group

    +
    + +

    Tests the #comp_labelledby portions of the AccName Name Computation algorithm.

    + + +

    Tests for aria-labelledby

    + +
    +

    first heading

    +

    text inside div group

    +
    + +
    +

    + first heading

    +

    text inside div group

    +
    + + + + + + +

    Tests for aria-labeledby (non-standard spelling)

    + +first label +second label + +

    Tests for precedence: aria-labelledby vs. aria-labeledby (non-standard spelling)

    + + +x + +
    x
    + +x + +
    x
    + +

    Tests for name precedence with aria-labeledby (non-standard spelling)

    + + + +

    + + link1 + + + link2 + image + + + link3 + +

    + + + +

    Tests hidden node name computation as part of the #comp_labelledby portion of the AccName Name Computation algorithm.

    + + + +

    Testing with display:none

    + + + + + + + + + + foo + + + + + + + + + foo + + + + + + + +

    Testing with visibility:hidden

    + + + + + + + + + + foo + + + + + + + + + foo + + + + + + + +

    Testing with visibility:collapse

    + + + + foo + bar + + + + + foo + + bar + baz + + + + + + foo + + bar + baz + + + + + + foo + bar + baz + + + + + foo + bar + baz + + + + + foo + bar + baz + + +

    Testing with aria-hidden

    + + + + + + + + + + foo + + + + + + +

    Testing with hidden attribute

    + + + + + + + + + + foo + + + + + + + + + foo + + + + + + + + +

    Tests the #comp_name_from_content portions of the AccName Name Computation algorithm.

    + +

    This series of tests exercises the button, heading, and link elements, because each have different characteristics worthy of testing in each of the name computation algorithm scenarios:

    +
      +
    • button is a leaf node with sub-level elements presentational.
    • +
    • heading is block level, and can contain sub-level interactives like links.
    • +
    • link (a[href]) is an interactive inline element that can include non-presentational descendants.
    • +
    + +

    ARIA roles, inline

    +label
    +label
    +label
    +
    + +

    ARIA roles, block

    +
    label
    +
    label
    +
    label
    +
    + +

    simple

    +
    +

    label

    +label
    +
    + +

    alt counter with ::before

    +
    +

    label

    +label
    +
    + +

    multiple alt counters with varying increments

    +
    +

    alpha beta gamma

    +alpha beta gamma
    +
    + +

    simple with ::before

    +
    +

    label

    +label
    +
    + +

    simple with ::after

    +
    +

    label

    +label
    +
    + +

    simple with ::before and ::after

    +
    +

    label

    +label
    +
    + +

    no space joiners ::before and ::after

    +
    +

    label

    +label
    +
    + +

    Arabic right-to-left (RTL) with ::before and ::after

    +
    +
    +

    اسم

    + اسم
    +
    +
    + +

    Alternative Text for CSS content (previously `alt:`) in pseudo-elements

    +

    rendered text should be "before label after"

    +

    accessibility label should be "alt-before label alt-after"

    +
    +

    label

    +label
    +
    + +

    Mixed Alternative Text (attr() and strings) for CSS content (previously `alt:`) in pseudo-elements

    +

    rendered text should be "before label after"

    +

    accessibility label should be "start alt-before end label start alt-after end"

    +
    +

    label

    +label
    +
    + +

    Empty alternative text for CSS content in pseudo-elements when applied to primitive appearance form controls

    +

    +

    + +

    simple w/ for each child

    +
    +

    one two three

    +one two three
    +
    + +

    simple for each child with image

    +
    +

    one two three

    +one two three
    +
    + + +

    simple for each child with extra nesting containing image

    +
    +

    one two three four

    +one two three four
    +
    + +

    heading with nested button with nested image

    +

    + heading + + heading +

    + +

    heading with nested link with nested image

    +

    + heading + + link + image + link + + heading +

    + +

    heading with nested link with nested image using aria-label

    +

    + heading + + ignored link text + ignored image alt + ignored link text + + heading +

    + +

    heading with nested link with nested image using aria-labelledby

    +

    + heading + + ignored link text + image + ignored link text + + heading +

    + +

    heading with two nested links referencing image using aria-labelledby

    +

    + + link1 + + + link2 + image + + + link3 + +

    + + + + + +

    simple w/ for each child (w/o spaces and display:inline)

    +
    +

    onetwothree

    +onetwothree
    +
    + +

    simple w/ for each child (w/o spaces and display:block)

    +
    +

    onetwothree

    +onetwothree
    +
    + +

    simple w/ for each child (w/o spaces and display:inline block)

    +
    +

    onetwothree

    +onetwothree
    +
    + +

    Call us

    +

    Call us

    +

    Call us

    +

    Call us

    + + + + + + +

    heading which visually transforms びょういん (hospital) to + びよういん (beauty parlor) using CSS + text-transform:full-size-kana

    +

    びょういんのかんじゃサービス

    + + + + +

    Elements with implicit button, heading, link roles containing element with + implicit term role

    + +

    this is an example

    +this is an example + +

    Elements with implicit button, heading, link roles containing element with + explicit term role

    + +

    this is an example

    +this is an example + +

    Elements with explicit button, heading, link roles containing element with + implicit term role

    +
    this is an example
    +
    this is an example
    +
    this is an example
    + +

    Elements with explicit button, heading, link roles containing element with + explicit term role

    +
    this is an example
    +
    this is an example
    +
    this is an example
    + + + +

    Tests the #comp_name_from_content portions of the AccName Name Computation algorithm.

    + +

    This series of tests exercises the button, heading, and link elements, because each have different characteristics worthy of testing in each of the name computation algorithm scenarios:

    +
      +
    • button is a leaf node with sub-level elements presentational.
    • +
    • heading is block level, and can contain sub-level interactives like links.
    • +
    • link (a[href]) is an interactive inline element that can include non-presentational descendants.
    • +
    + +

    alt counter with ::before

    +
    +

    label

    +label
    +
    + + +

    Each element below is named from its contents. In the first group its contents are the single character "x", and +text in a following sibling belongs to that sibling and must not be part of the name.

    + + + +
    x
    should not be in the name + +
    x
    +
    should not be in the name
    + +
    x
    should not be in the name + +
    x
    should not be in the name + +

    In the second group the contents are "x" and "y" in different boxes, such as the items of a flex container, and +both are part of the name.

    + +
    x
    y
    + +
    x y
    + +
    x y
    + +
    x should not be in the namey
    + +
    x y
    + +
    x y
    + +

    In the third group the element is a shadow host, so its contents are those of its shadow tree, where a slot stands +for the nodes assigned to it or else its fallback content.

    + +
    y
    + +
    + +
    should not be in the name
    + +

    Tests the #comp_name_from_heading portions of the AccName Name Computation algorithm.

    +

    Includes tentative "name from heading" diff.

    + + +
    +

    alertdialog role heading contents

    +

    More alertdialog content.

    +
    + +
    +

    article role heading contents

    +

    More article content.

    +
    + + + +
    +
    +

    Not this one

    +
    +

    nor this one

    +

    Nor this content.

    +
    + + + +

    dialog heading contents

    +

    More dialog content.

    +
    + + + + +
    +
    +

    article role simple DFS

    +
    +

    Not this one

    +

    More article content.

    +
    + + + + + +

    Tests the #comp_name_from_content_pseudo_element_marker portions of the AccName Name Computation algorithm.

    + +
      +
    • the Blue Sky
    • +
    • might be announced as “asterisk”
    • +
    • from Osaka to Kobe
    • +
    • that looks like a radish
    • +
    • Dodged a bullet
    • +
    + +
      +
    1. does not simply walk into Mordor
    2. +
    3. to tango
    4. +
    5. winner!
    6. +
    7. brings good luck
    8. +
    9. Puppy paws
    10. +
    + + + + + + + + + + + + + + + + + + + + + +

    Tests the #comp_text_node portions of the AccName Name Computation algorithm.

    + + + +

    text/element/text nodes, no space

    +buttonlabel +
    headinglabel
    + +

    headinglabel

    +linklabel +
    + +

    text/comment/text nodes, no space

    + + + buttonlabel + +
    + headinglabel +
    + +

    + headinglabel +

    + + linklabel + +
    + +

    text/comment/text nodes, with space

    + + button + + label + +
    + heading + + label +
    + +

    + heading + + label +

    + + link + + label + +
    + +

    text node, with tab char

    +button label +
    heading label
    + +

    heading label

    +link label +
    + +

    text node, with non-breaking space

    +button label +
    heading label
    + +

    heading label

    +link label +
    + +

    text node, with extra non-breaking space

    +button   label +
    heading   label
    + +

    heading   label

    +link   label +
    + +

    text node, with leading/trailing non-breaking space

    + button label  +
     heading label 
    + +

     heading label 

    + link label  +
    + +

    text node, with mixed space and non-breaking space

    +button   label +
    heading   label
    + +

    heading   label

    +link   label +
    + +

    text nodes, with deeply nested space

    + +button label + +
    +heading label +
    + +

    +heading label +

    + +link label + +
    + +

    text nodes, with single line break

    +button +label +
    heading +label
    + +

    heading +label

    +link +label +
    + +

    Tests the #comp_tooltip portions of the AccName Name Computation algorithm.

    + + + +contents +
    contents
    + +alt +alt + + + + + + + + + + + + + + + + + + + + + + +WPT + + + + + +
    + contents + details +
    + + + + + +

    Tests the tentative #comp_tooltip portions of the AccName Name Computation algorithm.

    + + + + +

    Tests the basic shadow DOM portions of the AccName Name Computation algorithm, coming in ARIA #167.

    + + + + + + + +

    Tests the shadow DOM slots portions of the AccName Name Computation algorithm, coming in ARIA #167.

    + + + + + + + + + + + + + +

    Tests the accName for elements defined in HTML-AAM: Accessible Name Computations By HTML Element. + These tests are meant to show whether an element returns a name per the naming mechanism used. See wpt: accname for expanded accName testing.

    + + + + +

    figure element

    +
    + x +
    y
    +
    + +
    + x +
    y
    +
    + +
    + x +
    y
    +
    + +
    + x +
    figcaption text
    +
    + +
    + x +
    y
    +
    + +
    + +
    figcaption
    +
    + +
    + +
    figcaption
    +
    + + +
    + + other content +
    figcaption
    +
    + + + +
    labelledby
    + +

    Accname tests for hidden elements that would otherwise provide names to an associated element

    +

    These tests are a complement to w3c/html-aam#533.

    + +

    Input with hidden label

    + + + +

    Table with hidden caption

    + + +
    + +

    Table with two captions, the first hidden

    + + + +
    Visible caption
    + +

    Fieldset with hidden legend

    +
    + +
    + +

    Fieldset with two legends, the first hidden

    +
    + + Visible legend +
    + +

    Tests the accName for elements defined in HTML-AAM: Accessible Name Computations By HTML Element. + These tests are meant to show whether an element returns a name per the naming mechanism used. See wpt: accname for expanded accName testing.

    + + + + + +

    address element

    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + +
    x
    +
    x
    + + + +

    aside element

    + + + + + + + + + + + + + +

    blockquote element

    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + +
    x
    +
    x
    + + + +

    details element

    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + +
    x
    +
    x
    + + +

    figure element

    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + +
    x
    +
    x
    + + +

    footer element

    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + +
    x
    +
    x
    + + +

    form element

    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + +
    x
    +
    x
    + + +

    hgroup element

    +

    x

    y

    + +

    x

    y

    +

    x

    y

    +

    x

    y

    + +

    x

    y

    +

    x

    y

    + +

    x

    y

    +

    x

    y

    + + +

    hr element

    +
    + +
    +
    +
    + +
    +
    + +
    +
    + + +

    ol element

    +
    1. x
    + +
    1. x
    +
    1. x
    +
    1. x
    + +
    1. x
    +
    1. x
    + +
    1. x
    +
    1. x
    + + +

    main element

    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + +
    x
    +
    x
    + + +

    menu element

    +
  • x
  • + +
  • x
  • +
  • x
  • +
  • x
  • + +
  • x
  • +
  • x
  • + +
  • x
  • +
  • x
  • + + +

    nav element

    + + + + + + + + + + + + + +

    search element

    +x + +x +x +x + +x +x + +x +x + + +

    section element

    +
    x
    + +
    x
    +
    x
    +
    x
    + +
    x
    +
    x
    + +
    x
    +
    x
    + + +

    ul element

    +
    • x
    + +
    • x
    +
    • x
    +
    • x
    + +
    • x
    +
    • x
    + +
    • x
    +
    • x
    + + + +
    labelledby
    + +

    Summary Element - HTML-AAM Contextual-Specific Role Verification Tests

    +

    Tests contextual computedrole mappings for summary defined in + summary (HTML spec) + and HTML-AAM summary mapping +

    + + + +

    x + +
    +
      +
    1. x
    2. +
    3. x
    4. +
    + x + x +
    + +
    +
    + x +
    +

    Other content

    +
    + + + + + + + + + + + + diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/roles.html b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/roles.html new file mode 100644 index 00000000..51517b35 --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/conformance/cases/roles.html @@ -0,0 +1,1765 @@ + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    +

    +

    +

    +
    +
    +
    +
    +
    +
    text
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
      +
      +
      +
      +

      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
        +
        +

        +

        +
        +
        +
        +
        +
        +
        +

        t

        c

        +

        t

        c

        +
        +
        +
        +
        +
        +
        v
        +
        +
        +
        +
        +
        +
        +
        +
        +
        d
        + +
        + +

        Tests contextual computed role mappings defined in HTML AAM, where the returned computed role is expected to change based on the context. Most test names correspond to a unique ID defined in the spec.

        + +

        These should remain in alphabetical order.

        + + +
        x
        +
        x
        +
        x
        +
        x
        +
        x
        +
        x
        +
        x
        +
        x
        + + +
        labelledby
        +
        +
        + + + x + x + +x + +

        Tentative test for the expected role mappings of the obsolete dir element. + The computedrole mappings are defined in HTML-AAM.

        + +

        Merge the outcome of this test into roles.html in the appropriate alphabetical order, when it is no longer considered tentative:

        + +
      • x
      • x
      • + +

        HTML-AAM tests for invalidly nested heading elements

        +

        Equivalent ARIA patterns tested in /wai-aria/heading/invalid-nesting.tentative.html.

        + +

        Accessible names and roles

        +
        + + +

        +

        Invalid h2

        + + +

        +

        Invalid h3

        + + +
        +
        Invalid h6
        + + +

        Chocolate +

        Peanut butter

        + + +

        No heading ancestors

        +
        + +

        One +

        Two +

        Three

        + + + +

        Tentative test for the expected role mappings of the img element to ensure + it is exposed with the correct role when the src, srcset, both or neither + attributes are specified.

        +

        The computedrole mappings are defined in HTML-AAM.

        + +

        Merge the outcome of this test into roles.html in the appropriate alphabetical order, when it is no longer considered tentative:

        + + + + + +

        Image role:

        +x + + + + + + + + + + + +x +x + + + + + + + + + + + + + +

        Presentation / None / Generic role

        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

        Tests contextual computed role mappings defined in HTML-AAM, where the returned computed role is expected to change based on the context. Most test names correspond to a unique ID defined in the spec.

        + +

        These should remain in alphabetical order.

        + + + +x +x + + + +
        + +
        + + +
        +
        +
        + + +
        + + + +
        + + + + + + + + +
        + + + +
        x
        + + + + +
        x
        + + + + + + + + + + + + + +
        x
        +
        x
        +
        x
        +
        x
        +
        x
        +
        x
        +
        x
        +
        x
        + + +
        labelledby
        +
        +
        + + + + + +
        +
        x
        +
        + +
        +
        x
        +
        + +

        Tests ONLY the generic mappings defined in HTML-AAM. Most test names correspond to a unique ID defined in the spec.

        + +

        These should remain in alphabetical order by tagname.

        + + + +x +x +x +x +
        x
        + + +x +
        x
        +x +x + +x +x +x + +

        Tests contextual computedrole mappings for the LI element defined in HTML-AAM, +where the returned computed role is expected to change based on whether the LI element is an accessibility child of a list element, or not.

        + + +

      • x
      • + +
          +
        • x
        • +
        + +
          +
          +
        • x
        • +
          +
        + + +
          +
        • x
        • + + +
          +
        • x
        • +
          + +

          Tests minimum computedrole mappings defined in HTML-AAM ([HTML-AAM Issue #454](https://github.com/w3c/html-aam/pull/454)), where the returned computed role for generic elements is expected to change based on the generic elements having attributes that would require the element no longer be generic, and potentially ignored by browsers. Most test names correspond to a unique ID defined in the spec.

          + + +

          Baseline div, role=generic
          + +
          div with autofocus attribute.
          +
          div with explicit role=generic and autofocus attribute.
          +
          div with explicit role=none and autofocus attribute.
          + +
          div with draggable attribute.
          +
          div with explicit role=generic and draggable attribute.
          +
          div with explicit role=none and draggable attribute.
          + + +
          div with popover attribute, role=group
          + +
          div with draggable attribute and errant role attribute value.
          + + +
          unnamed section with draggable attribute.
          + + + + +
          div with explicit role=article and draggable attribute.
          + + +
          article element with draggable attribute.
          +
          named section with draggable attribute.
          + + + cite element with draggable attribute. + +

          Tests the computedrole mappings defined in HTML-AAM. Most test names correspond to a unique ID defined in the spec.

          + +

          These should remain in alphabetical order, and include all HTML tagnames. If a tag is not tested here, include a pointer to the file where it is tested, such as: <!-- caption -> ./table-roles.html -->

          + + + + +
          x
          + +
          x
          + + + + + + + +
          x
          + + + + + + +x + + + + + + +
          +
          x
          + +
          x
          +
          + +x +
          xx
          +x + +x + + + + + +
          + +
          x
          +
          x
          +
          + +x + +
          x
          + +
          x
          x
          + +
          + + + +

          x

          +

          x

          +

          x

          +

          x

          +
          x
          +
          x
          + + + + +

          x

          +
          + + + +x + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +x + + + + + + +
          • x
          • x
          +
          1. x
          2. x
          + + +
          x
          + +x + +
        • x
        • + +x + + + +
          1. x
          2. x
          + + + + + + +x +

          x

          + + + +x + + + + +x + + +x + + + + + + + + + + + +x + +x + +x + + + + + + + + + + + + + + +
          • x
          • x
          + + + + +

          Tests the computedrole mappings defined in HTML-AAM. Most test names correspond to a unique ID defined in the spec.

          + +

          These should remain in alphabetical order, and include all HTML tagnames. If a tag is not tested here, include a pointer to the file where it is tested, such as: <!-- caption -> ./table-roles.html -->

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          abc
          123
          456
          xyz
          + +

          Tests the computedrole mappings for the table-related roles defined in HTML-AAM. Most test names correspond to unique ID defined in the spec.

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          caption
          abc
          123
          456
          xyz
          + +

          WAI-ARIA tests for invalidly nested heading elements

          +

          Equivalent native patterns tested in /html-aam/heading/invalid-nesting.html.

          + +

          Accessible names and roles

          +
          + +
          +
          Invalid div[role=heading][aria-level=2]
          +
          + +
          +
          Invalid div[role=heading][aria-level=3]
          +
          + +
          +
          Invalid div[role=heading][aria-level=6]
          +
          + +
          Chocolate +
          Peanut butter
          +
          + +

          ARIA heading impostors

          +
          + + + +

          Biscuits + Gravy +

          + +

          Tests Abstract Roles and related 9.1 Roles - handling author errors

          + + + + + + + + + + + + + + +

          Tests button and related roles.

          + +
          +
          +
          +
          +
          +
          +
          +
          +
          +
          + +

          Verifies Required Accessibility Parent Roles from 5.2.7 Required Accessibility Parent Role

          +

          Also verifies Allowed Accessibility Child Roles from 5.2.6 Allowed Accessibility Child Roles

          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          x
          + + + +
          +
          x
          +
          +
          +
          x
          +
          + + +
          +
          +
          x
          +
          + + + + +

          Tests 8.1 Role Attribute role token list selection and 9.1 Roles - handling author errors.

          + + + + + + +
          x
          + + +
          x
          + + + x + + + + + + +
          x
          + + + + + + + +
          x
          + + + +
          x
          +
          x
          +
          x
          + + +
          x
          + + +
          x
          +
          x
          +
          x
          + +
          x
          +
          x
          +
          x
          + +
          x
          + +

          Verifies 9.1 Roles - handling author errors and the form role.

          + + + + + + + + +

          Tests generic.

          + +

          x

          + +

          Tests grid and related roles.

          + + + +
          +
          + x + x +
          +
          + x + x +
          +
          + +
          +
          +
          + x + x + x +
          +
          +
          +
          + x + x + x +
          +
          +
          + +

          Tests invalid ARIA roles from 9.1 Roles - handling author errors.

          + + + + + + + + + + + + +x +x +x +
          x
          +
          x
          +
          x
          + + + + + + + + + + + + +x +x +x +x +x +x +x +x + + + x + x + x + x + x + x + x + + +x +x +x +x +x +x +x + + +
          x
          +
          x
          +
          x
          +
          x
          + + + + + + + + + + + + + +x +x +x +x + + + + + + + + +
          x
          +
          x
          +
          x
          +
          x
          + + +x +x + + +x +x +x +x + + + + + + + +x +x +x + +

          Tests list and related roles.

          + +
          +
          x
          +
          x
          +
          + +

          Tests listbox and related roles.

          + +
          +
          x
          +
          + x + x +
          +
          x
          +
          + +
            +
          • + x +
          • +
          • + x +
          • +
          + + + + +

          Tests menu and related roles.

          + + + + + +

          Tests region and related roles, as well as the "name from author" rule in 9.1 Roles - handling author errors.

          + + + + + + + +

          Verifies conflict resolution requirements for the ARIA none and presentation roles.

          + + +

          x

          + + +

          x

          +

          x

          + + +

          x

          +

          x

          +

          x

          + + +

          Sample Content

          + + + +

          Non-focusable ARIA role="button" nesting non-focusable ARIA role="button" (no presentational roles conflict resolution, since inner button is not focusable)

          +
          + outer button + Inner button +
          + + +

          Focusable ARIA role="button" nesting non-focusable ARIA role="button" (no presentational roles conflict resolution, since inner button is not focusable)

          +
          + outer button + Inner button +
          + + +

          Non-focusable ARIA role="button" nesting focusable ARIA role="button" (presentational roles conflict resolution arise, since inner button is focusable)

          +
          + outer button + Inner button +
          + + +

          Focusable ARIA role="button" nesting focusable ARIA role="button" (presentational roles conflict resolution arise, since inner button is focusable)

          +
          + outer button + Inner button +
          + + +

          HTML button nesting HTML button

          +
          + +
          + + +

          HTML input with role="none" (presentational roles conflict resolution)

          + + + + +

          HTML input with role="none" and disabled (presentational roles conflict resolution does not apply due to disabled attr)

          + + + +

          HTML input with role="none" and readonly (presentational roles conflict resolution)

          + + + +

          HTML input with role="none", disabled and readonly (presentational roles conflict resolution does not apply due to disabled attr)

          + + + + + +

          Presentational role inherited with global

          + + +
            +
          • a
          • +
          • b
          • +
          • c
          • +
          + + + + + + + + +
          a
          + + + + + + + + + + + + + + + + + + +
          col 1col 2
          cell 1cell 2
          cell 3cell 4
          + +

          Tests synonym roles image/img and none/presentation via Core-AAM Computed Role.

          + + + +
          x
          + + +
          x
          + + + +
          • x
          +
          • x
          +
          x
          + +

          Tests tab and related roles.

          + + +
          + +
          +
          + + +
          + + +
          +
          +
          + + +
          + + + +
          +
          +
          +
          + + +
          + + +
          +
          Tab one's stuff
          +
          Tab two's stuff
          + + +
          + + +
          +
          Tab one's stuff
          +
          Tab one's stuff
          + + +
          + +
          + + +
            +
          • + +
          • +
          • + +
          • +
          +
          Tab one's stuff
          +
          Tab two's stuff
          + + +
            +
          • + +
          • +
          • + +
          • +
          +
          Tab one's stuff
          +
          Tab two's stuff
          + +

          Tests table and related roles.

          + + + + + + + + + + + + + + + + + + + + + + + + + + +
          +
          x
          +
          + +

          x

          + + +
          +
          +
          + x + x +
          +
          +
          +
          + x + x +
          +
          +
          + + x + + +
          +
          +
          + x + x + x +
          +
          +
          +
          + x + x + x +
          +
          +
          + + +
          +
          +
          + x +
          +
          +
          +
          + x +
          +
          +
          + + +
          +
          +
          + x + x +
          +
          +
          +
          + x + x +
          +
          +
          + + +
          +
          +
          + x + x + x +
          +
          +
          +
          + x + x + x + x +
          +
          +
          + + +
          +
          + x + x +
          +
          + x + x +
          +
          + + + + +

          Tests tree and related roles.

          + +
            +
          • + x +
              +
            • x
            • +
            • x
            • +
            +
          • +
          • x
          • +
          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          xxx
          xxx
          diff --git a/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/marker/ax-counter-style.ts b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/marker/ax-counter-style.ts new file mode 100644 index 00000000..48d0679f --- /dev/null +++ b/packages/devtools-anywhere/src/cdp-agent/domains/accessibility/marker/ax-counter-style.ts @@ -0,0 +1,348 @@ +// Counter styles of @counter-style rules (CSS Counter Styles 3), read from the document's style +// sheets (CSSCounterStyleRule): a counter's text by the rule's system, symbols, additive-symbols, +// range, pad, negative and fallback, and a list marker's prefix and suffix. Part of +// accessibility.js (ax-counter.ts). +import { markerSuffix, unescape } from './ax-counter'; + +/** A @counter-style rule's descriptors, as the CSSOM gives them ("" when not set). */ +interface CounterStyleRule { + name: string; + system: string; + symbols: string; + additiveSymbols: string; + negative: string; + prefix: string; + suffix: string; + range: string; + pad: string; + fallback: string; +} + +/** The names a rule cannot take: these keep their predefined styles. */ +const RESERVED = /^(decimal|disc|square|circle|disclosure-open|disclosure-closed|none|inherit|initial|unset)$/; + +/** The rules of each document by name, kept while one command works on the tree. */ +const cache = new WeakMap>(); + +/** + * A cascade layer: its sublayers in layer order. A rule's rank is the indexes of its layers + * among their siblings, ended by Infinity: the rules of no sublayer win over those of the + * sublayers, and the unlayered rules ([Infinity]) over all layered ones. + */ +interface Layer { + children: Map; +} + +/** The layer `name` (dotted, as `@layer a.b`) under `parent`, made when new, with its rank prefix. */ +function layerOf(parent: { layer: Layer; rank: number[] }, name: string): { layer: Layer; rank: number[] } { + let current = parent; + for (const part of name.split('.')) { + const { children } = current.layer; + let child = children.get(part); + if (!child) children.set(part, (child = { children: new Map() })); + current = { + layer: child, + rank: [...current.rank, [...children.keys()].indexOf(part)], + }; + } + return current; +} + +function laterRank(a: number[], b: number[]): boolean { + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const x = a[i] ?? -1; + const y = b[i] ?? -1; + if (x !== y) return x > y; + } + return true; +} + +type Ranked = Map; + +/** Whether a media query list matches in the document's window ("" and "all" do). */ +function mediaMatches(doc: Document, media: MediaList | null | undefined): boolean { + const text = media?.mediaText ?? ''; + if (!text || text === 'all') return true; + return doc.defaultView?.matchMedia(text).matches ?? true; +} + +/** Whether a supports condition holds in the document's window. */ +const supports = (doc: Document, condition: string) => doc.defaultView?.CSS.supports(condition) ?? true; + +let anonymous = 0; + +function collect(doc: Document, rules: CSSRuleList, out: Ranked, scope: { layer: Layer; rank: number[] }): void { + const add = (rule: CounterStyleRule, at: { layer: Layer; rank: number[] }) => { + const rank = [...at.rank, Infinity]; + const old = out.get(rule.name); + if (!old || laterRank(rank, old.rank)) out.set(rule.name, { rule, rank }); + }; + // By the rules' type numbers, as the rules may be of another realm. + for (const rule of rules) { + try { + if (rule.type === 11) { + add(rule as unknown as CounterStyleRule, scope); + } else if (rule.type === 3) { + // @import: its sheet, when its media and supports() conditions hold, in its layer. + const r = rule as CSSImportRule & { supportsText?: string | null }; + if (!r.styleSheet || !mediaMatches(doc, r.media)) continue; + if (r.supportsText && !supports(doc, r.supportsText)) continue; + const at = + r.layerName === null || r.layerName === undefined ? scope : layerOf(scope, r.layerName || `\0${anonymous++}`); + collect(doc, r.styleSheet.cssRules, out, at); + } else if (rule.type === 4) { + const r = rule as CSSMediaRule; + if (mediaMatches(doc, r.media)) collect(doc, r.cssRules, out, scope); + } else if (rule.type === 12) { + const r = rule as CSSSupportsRule; + if (supports(doc, r.conditionText)) collect(doc, r.cssRules, out, scope); + } else if ('nameList' in rule) { + // @layer a, b;: the order of the layers. + for (const name of (rule as CSSLayerStatementRule).nameList) layerOf(scope, name); + } else if ('cssRules' in rule) { + const name = + 'name' in rule && rule.constructor.name === 'CSSLayerBlockRule' ? (rule as CSSLayerBlockRule).name : null; + const at = name === null ? scope : layerOf(scope, name || `\0${anonymous++}`); + collect(doc, (rule as CSSGroupingRule).cssRules, out, at); + } + } catch { + // Not readable. + } + } +} + +/** The @counter-style rule named `name` in a document that wins the cascade. */ +function ruleOf(doc: Document, name: string): CounterStyleRule | undefined { + if (RESERVED.test(name)) return undefined; + let rules = cache.get(doc); + if (!rules) { + const ranked: Ranked = new Map(); + const root = { layer: { children: new Map() }, rank: [] }; + for (const sheet of [...doc.styleSheets, ...(doc.adoptedStyleSheets ?? [])]) { + // A disabled sheet, or one of a or