diff --git a/.claude/marathon.toml b/.claude/marathon.toml index f776fa4..2157ba8 100644 --- a/.claude/marathon.toml +++ b/.claude/marathon.toml @@ -6,7 +6,8 @@ currency = "mise run currency" [remote] platform = "github" publish = "gh pr create" -merge = "gh pr checks --watch && gh pr merge --merge --delete-branch" +checks = "gh pr checks --watch" +merge = "gh pr merge --merge --delete-branch" ci = ''' sha=$(git rev-parse HEAD) for _ in $(seq 30); do diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aea5dee..bdb91fc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: steps: - uses: actions/checkout@v7.0.1 - - uses: jdx/mise-action@v5.2.10 + - uses: jdx/mise-action@v5.3.0 - name: mise run install run: mise run install diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 15c8c53..d93605e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -59,7 +59,7 @@ jobs: exit 1 fi - - uses: jdx/mise-action@v5.2.10 + - uses: jdx/mise-action@v5.3.0 - name: mise run install run: mise run install diff --git a/CHANGELOG.md b/CHANGELOG.md index b12307b..948cb4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,40 @@ All notable changes to `@standards-lab/web-components` are documented here. The [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.2.0] - 2026-11-22 + +### Removed + +- **Breaking:** `./json.js`, with no re-export: import `formatJson` and `tryFormatJson` from the + foundation's `format.js`. + +### Changed + +- **Breaking:** the foundation peer is `@standards-lab/web-foundation` at `^0.4.0`, up from + `^0.3.0`, and `@standards-lab/web-icons` at `^0.1.0` is a second peer, whose glyphs the + components import by package name; a consumer declares both beside the components. +- **Breaking:** the components read the foundation's `--color-accent` and `--color-primary`, which + replace `--accent-color` and `--interaction-color`; a page that set the old names sets the new. +- **Breaking:** each shadow root adopts the foundation's utilities, glyph-button, dialog, and motion + sheets where it uses them, and `sl-settings` its meta and structure sheets, in place of the + components' own rules for the same, so the foundation's classes style the components' internals. + The chat thread's streaming dot and the stage timeline's running ring are spans carrying the + foundation's motion classes, no longer pseudo-elements. +- **Breaking:** `sl-drawer`'s Close is a glyph button showing web-icons' x-16; the `close` slot's + text, "Close" by default, is its name and its hint on hover and keyboard focus, no longer its + visible text. +- The repository's tooling takes marathon 0.23.0 and mise-action v5.3.0. + +### Added + +- `./settings.js`: `sl-settings`, the reader's theme and keyboard settings, applied and stored at + once. +- `./shortcuts.js`: `sl-shortcuts`, the keyboard shortcuts of the dialog that holds it, as a + plain-text table. +- `sl-drawer`'s `modal` attribute, which keeps the drawer modal at every width. +- The Settings and Help pattern, S and ? opening dialogs that hold `sl-settings` and + `sl-shortcuts`, in the README and the demo, with specimen pages for both. + ## [0.1.0] - 2026-11-18 ### Added @@ -39,4 +73,5 @@ All notable changes to `@standards-lab/web-components` are documented here. The - Releases by tag: each `v` tag marks a pack commit whose tree is the pack, the build included, and whose one parent is main's merge commit; its GitHub release carries the tarball. +[0.2.0]: https://github.com/standards-lab/web-components/releases/tag/v0.2.0 [0.1.0]: https://github.com/standards-lab/web-components/releases/tag/v0.1.0 diff --git a/README.md b/README.md index ebf110e..2d21e26 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,12 @@ # web-components -The Lit components of the standards-lab web client stack: twelve elements with a shadow root that -applications compose, their sheets, a Markdown renderer, and a JSON formatter. It is ES modules -with their type declarations and stylesheets, built on -[`@standards-lab/web-foundation`](https://github.com/standards-lab/web-foundation), which it takes -as a peer, and is released by git tag. A component takes properties and attributes, sends events, +The Lit components of the standards-lab web client stack: fourteen elements with a shadow root +that applications compose, their sheets, and a Markdown renderer. It is ES modules with their type +declarations and stylesheets, built on +[`@standards-lab/web-foundation`](https://github.com/standards-lab/web-foundation) with the glyphs +of [`@standards-lab/web-icons`](https://github.com/standards-lab/web-icons), which it takes as +peers, and is released by git tag. A component takes properties and attributes, sends events, and may hold its own UI state; it holds no services, fetches no data, and binds no key. ## Install @@ -16,19 +17,19 @@ Each release is a tag, `v`, of package as `pnpm pack` builds it: `package.json`, this README, the LICENSE, and `dist/`, the build. The build lives only in the tag's tree, so the tag installs with no build step, and its manifest has no scripts. It depends on lit 3.3.3 and marked 18.2.1, and takes the foundation as a peer at -`^0.3.0`: a consumer declares the foundation beside the components, and the one copy serves both, -so a restyle of the foundation's sheets by package name reaches the components' shadow roots too. -Install both by their tags: +`^0.4.0` and the icons at `^0.1.0`: a consumer declares each beside the components, so the page +and the components share one copy of each, and a restyle of the foundation's sheets by package +name reaches the components' shadow roots too. Install all three by their tags: ``` -pnpm add github:standards-lab/web-components#v0.1.0 github:standards-lab/web-foundation#v0.3.0 -bun add github:standards-lab/web-components#v0.1.0 github:standards-lab/web-foundation#v0.3.0 -npm install --allow-git=root github:standards-lab/web-components#v0.1.0 github:standards-lab/web-foundation#v0.3.0 +pnpm add github:standards-lab/web-components#v0.2.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 +bun add github:standards-lab/web-components#v0.2.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 +npm install --allow-git=root github:standards-lab/web-components#v0.2.0 github:standards-lab/web-foundation#v0.4.0 github:standards-lab/web-icons#v0.1.0 ``` npm 12 refuses git dependencies unless `--allow-git` allows them; `root` allows the ones the -project itself declares, which both packages are. Without the foundation declared, the install -fails. Each GitHub release also carries the tarball. +project itself declares, which all three packages are. Leaving either peer undeclared fails the +install. Each GitHub release also carries the tarball. ### Safari @@ -40,8 +41,9 @@ package keeps the standard syntax, with no pack-time rewrite. The package is `@standards-lab/web-components`. Each module defines its element when it is imported, and the element's shadow root adopts the foundation's reset and elements sheets, then -its own layout-only sheet. The modules import `lit` and the foundation by package name and their -sheets as CSS module scripts, so a page reaches them through an import map or a bundler, and links +the foundation's meta, structure, utilities, glyph-button, dialog, and motion sheets where it uses +them, then its own layout-only sheet. The modules import `lit`, the foundation, and the icons by +package name and their sheets as CSS module scripts, so a page reaches them through an import map or a bundler, and links the foundation's `page.css`: ```html @@ -56,9 +58,11 @@ the foundation's `page.css`: - `./entry.js`: `sl-entry`, one directory or file of a document hierarchy, as a button. - `./pagination.js`: `sl-pagination`, a page of entries between its summary and its controls. - `./drawer.js`: `sl-drawer`, its children docked inline on a wide viewport, in a modal drawer - below. + below, or in the modal drawer at every width with `modal`. +- `./shortcuts.js`: `sl-shortcuts`, the keyboard shortcuts of the dialog that holds it, as a table. +- `./settings.js`: `sl-settings`, the reader's theme and keyboard settings, applied and stored at + once. - `./markdown.js`: `markdown(source)`, a Markdown string as a Lit template of plain elements. -- `./json.js`: `formatJson(text)`, valid JSON text re-indented from its own tokens. - `./artifact-viewer.js`: `sl-artifact-viewer`, one artifact's content by its content type. - `./event-log.js`: `sl-event-log`, events as a log in the order given. - `./search-results.js`: `sl-search-results`, a search's matches under a status line. @@ -72,12 +76,105 @@ the foundation's `page.css`: [docs/components.md](https://github.com/standards-lab/web-components/blob/main/docs/components.md) documents each module in full, and its demo and specimen pages. +### Settings and Help + +The components bind no key, so the page binds S and ? itself, as `demo/components.html` does. Two +glyph buttons in the header's `.header-actions` open the dialogs with `command="show-modal"`, and +the foundation's `keys.js` binds each to its key through `data-keys`. Help is a `.dialog-fit` +dialog holding `sl-shortcuts`, and Settings is a `.dialog-wide` dialog holding `sl-settings`; each +has a `.dialog-header` whose Close shows the Esc hint. Close and Escape close either dialog with no +script, and focus returns to the element that held it. The page links the foundation's +`glyph-button.css`, `dialog.css`, and `layout.css` after its entry, and web-icons' `iconFill()` +fills the glyphs' markers: + +```html +
+ App +
+ + + + +
+
+ +
+

Keyboard shortcuts

+ + +
+ +
+ +
+

Settings

+ + +
+ +
+ +``` + +The Help heading takes focus as its dialog opens; the Settings heading doesn't, so `sl-settings` +focuses its first row. `demo/settings.html` and `demo/shortcuts.html` carry the pattern too. + ## Development Tasks run through [mise](https://mise.jdx.dev): ``` -mise run install # the pinned tools, and node_modules with the foundation and the tooling at their tags; reads the network +mise run install # the pinned tools, and node_modules with the foundation, the icons, and the tooling at their tags; reads the network mise run check # lint, lint-context, lint-references, types, build, and both test tiers; reads no network mise run build # src/ into dist/ mise run demo # serve the components demo page and the specimen pages on dist/ @@ -91,11 +188,12 @@ mise run screenshots --scheme dark # only the scheme named, light or dark mise run screenshots --output browser # a gallery of the captures, opened in the browser; directory keeps the files mise run screenshots --dir # write the captures into the directory named, with any of the above mise run screenshots --keep # keep the terminal output's captures, with any of the above -mise run currency # report every tool, package, and action pin, the foundation's and the tooling's tags, and the foundation's peer range, behind its latest; a held pin with its reason +mise run currency # report every tool, package, and action pin, the foundation's, the icons', and the tooling's tags, and both peer ranges, behind its latest; a held pin with its reason ``` `mise run screenshots` captures each specimen page light and dark, in vertical tiles at most -1200px tall, and the drawer's in its viewport at each of its four states. It runs the +1200px tall; it captures the drawer's page in its viewport at each of its six states, and the +settings and shortcuts pages again with their dialogs open. It runs the `web-screenshots` bin of [web-tooling](https://github.com/standards-lab/web-tooling), the devDependency the browser tier's driver and server also come from, over the capture description `scripts/screenshots.config.ts`; `mise run screenshots -- --help` lists the flags with the pages diff --git a/STANDARDS.md b/STANDARDS.md index 9091834..940075f 100644 --- a/STANDARDS.md +++ b/STANDARDS.md @@ -42,7 +42,7 @@ The architecture pages that apply, in the architecture repository: ## Package - The package is `@standards-lab/web-components`, the components layer of the web client stack, - built on `@standards-lab/web-foundation`, its one peer. + built on `@standards-lab/web-foundation` and `@standards-lab/web-icons`, its two peers. - lit and marked are each pinned exactly, and only the Markdown module imports marked (`test/unit/marked.test.ts` enforces it). - `dist/` lives only in a release tag's tree, the pack, never on a branch. diff --git a/context/README.md b/context/README.md index 9e730ba..0879b1c 100644 --- a/context/README.md +++ b/context/README.md @@ -1,7 +1,7 @@ # web-components context web-components is the set of Lit elements with a shadow root that applications compose, built on -web-foundation as a peer. A component takes properties and attributes, sends events, and may hold +web-foundation and web-icons as peers. A component takes properties and attributes, sends events, and may hold its own UI state; it holds no services, fetches no data, holds no application state, and never imports the SDK. An application's internal element becomes a component once a second application needs it. @@ -19,14 +19,16 @@ line; the workflows and CHANGELOG.md name theirs, web-foundation's at ceaab61. T line have their provenance here: - `package.json` is adapted from spike-html-apps-components (10dde51): package.json. It is renamed - `@standards-lab/web-components` at 0.1.0, takes `@standards-lab/web-foundation` as its peer, - and replaces the spike's foundation and tooling devDependencies with web-foundation's and - web-tooling's release tags; it pins marked and typescript-eslint exactly. + `@standards-lab/web-components` at 0.1.0, takes `@standards-lab/web-foundation` and + `@standards-lab/web-icons` as its peers, and replaces the spike's foundation and tooling + devDependencies with web-foundation's and web-tooling's release tags, adds web-icons' release + tag, and pins marked and typescript-eslint exactly. - `.prettierrc.json` is from spike-html-apps-components (10dde51): .prettierrc.json. - `LICENSE` is from spike-html-apps-components (10dde51): LICENSE, unchanged. - `pnpm-lock.yaml` is generated, not copied. -- `test/unit/marked.test.ts`, `test/browser/themes.test.ts`, and - `test/browser/support/profiles.ts` are written here, with no source. +- `test/unit/marked.test.ts`, `test/browser/themes.test.ts`, + `test/browser/shortcut-dialogs.test.ts`, `test/browser/support/profiles.ts`, and + `demo/glyphs.js` are written here, with no source. - `CLAUDE.md`, `.claude/`, and this directory are marathon's working files, written here. ## Capability map @@ -37,3 +39,6 @@ line have their provenance here: list](../docs/components.md#inspection). - **Controls** (built): [the status badge, entry, pagination, and drawer](../docs/components.md#controls). +- **Settings and Help** (built): [the reader's settings and the keyboard shortcuts + list](../docs/components.md#controls), and [the page pattern that opens + them](../README.md#settings-and-help). diff --git a/demo/components.html b/demo/components.html index f98f775..36d8e55 100644 --- a/demo/components.html +++ b/demo/components.html @@ -5,7 +5,11 @@ components + + + + + + + - + +
+ web-components +
+ + + + +
+

Components

The shadow-root pagination, entry, and status badge, on Zen, regular, and mono. Each root adopts the foundation's reset and elements sheets, then its own layout.

+

+ Press ? or S, or the header's buttons, for the Help and Settings + dialogs; Close, or Esc, closes either. +

Status badges

@@ -99,5 +149,43 @@

Events

    + +
    +

    Keyboard shortcuts

    + + +
    + +
    + +
    +

    Settings

    + + +
    + +
    diff --git a/demo/demo.css b/demo/demo.css index 49a78c8..b811470 100644 --- a/demo/demo.css +++ b/demo/demo.css @@ -10,6 +10,16 @@ padding-block: var(--space-l) var(--space-2xl); } + body > header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2xs) var(--space-s); + inline-size: min(100% - 2 * var(--space-m), 80rem); + margin-inline: auto; + padding-block: var(--space-s); + } + main > section { margin-block-start: var(--space-xl); } diff --git a/demo/drawer.html b/demo/drawer.html index 4ade080..24cecd5 100644 --- a/demo/drawer.html +++ b/demo/drawer.html @@ -18,7 +18,8 @@ "@lit/reactive-element": "/deps/@lit/reactive-element/reactive-element.js", "@lit/reactive-element/": "/deps/@lit/reactive-element/", "marked": "/deps/marked/lib/marked.esm.js", - "@standards-lab/web-foundation/": "/deps/@standards-lab/web-foundation/dist/" + "@standards-lab/web-foundation/": "/deps/@standards-lab/web-foundation/dist/", + "@standards-lab/web-icons/octicon/x-16": "/deps/@standards-lab/web-icons/dist/octicon/x-16.js" } } @@ -26,12 +27,15 @@ import "@standards-lab/web-foundation/register-full.js"; import "../dist/drawer.js"; - const drawer = document.querySelector("sl-drawer"); - document.querySelector("#open-documents").addEventListener("click", () => drawer.show()); - const expanded = () => - document.querySelector("#open-documents").setAttribute("aria-expanded", String(drawer.open)); - drawer.addEventListener("open", expanded); - drawer.addEventListener("close", expanded); + for (const [opener, drawer] of [ + ["#open-documents", "#documents"], + ["#open-outline", "#outline"], + ].map((ids) => ids.map((id) => document.querySelector(id)))) { + opener.addEventListener("click", () => drawer.show()); + const expanded = () => opener.setAttribute("aria-expanded", String(drawer.open)); + drawer.addEventListener("open", expanded); + drawer.addEventListener("close", expanded); + } @@ -39,7 +43,8 @@

    Drawer

    sl-drawer, docked beside the content at 48rem and wider, and below it a - modal drawer over the whole viewport, sliding in from the inline-start edge. + modal drawer over the whole viewport, sliding in from the inline-start edge. The Outline + drawer is modal, a modal drawer at every width.

    @@ -65,6 +70,9 @@

    Drawer

    Documents

    quarterly-report.md

    +

    Revenue in the three regions grew 4% over the quarter, led by the north, where the new @@ -81,6 +89,13 @@

    quarterly-report.md

    + + + diff --git a/demo/glyphs.js b/demo/glyphs.js new file mode 100644 index 0000000..08a5497 --- /dev/null +++ b/demo/glyphs.js @@ -0,0 +1,15 @@ +// The demo pages' glyphs: each empty marker, ``, replaced as the +// module loads by the web-icons module's svg, as web-icons' iconFill() fills a Vite page's markers +// at build. The page's import map names each icon's module: question-16, gear-16, and x-16. + +import gear from "@standards-lab/web-icons/octicon/gear-16"; +import question from "@standards-lab/web-icons/octicon/question-16"; +import x from "@standards-lab/web-icons/octicon/x-16"; + +const icons = { "octicon/gear-16": gear, "octicon/question-16": question, "octicon/x-16": x }; + +for (const marker of document.querySelectorAll("svg[data-icon]")) { + const template = document.createElement("template"); + template.innerHTML = icons[marker.dataset.icon]; + marker.replaceWith(template.content); +} diff --git a/demo/settings.html b/demo/settings.html new file mode 100644 index 0000000..124d29b --- /dev/null +++ b/demo/settings.html @@ -0,0 +1,145 @@ + + + + + + settings specimen + + + + + + + + + + + + +
    + web-components +
    + + + + +
    +
    +
    +

    Settings

    +

    + sl-settings, the reader's theme and keyboard settings, applied and stored at + once. Press S, or the header's Settings button, for it in the Settings dialog, + .dialog-wide; Close, or Esc, closes it. +

    + +
    +

    States

    +
    +
    + +
    +

    States at 20rem

    +
    +
    + +
    +

    Focus visible

    +

    The settings' first row, reached by the keyboard.

    + +
    +
    +
    + +
    +

    Keyboard shortcuts

    + + +
    + +
    + +
    +

    Settings

    + + +
    + +
    + + diff --git a/demo/shortcuts.html b/demo/shortcuts.html new file mode 100644 index 0000000..61510f3 --- /dev/null +++ b/demo/shortcuts.html @@ -0,0 +1,149 @@ + + + + + + shortcuts specimen + + + + + + + + + + + + +
    + web-components +
    + + + + +
    +
    +
    +

    Shortcuts

    +

    + sl-shortcuts, the keyboard shortcuts of the dialog that holds it, as a table. + Press ?, or the header's Help button, for it in the Help dialog, + .dialog-fit; Close, or Esc, closes it. +

    + +
    +

    Bindings

    +

    The page's own bindings, besides the header's ? and S.

    +

    + + + Back to the top +

    +
    + +
    +

    States

    +
    +
    + +
    +

    States at 20rem

    +
    +
    +
    + +
    +

    Keyboard shortcuts

    + + +
    + +
    + +
    +

    Settings

    + + +
    + +
    + + diff --git a/docs/components.md b/docs/components.md index 40ba50d..7c00ea9 100644 --- a/docs/components.md +++ b/docs/components.md @@ -32,15 +32,41 @@ the tests measure as they do. closed until `show()`, `toggle()`, or `open` opens it, `open` in the markup as the page loads too, covering the viewport and sliding in from the inline-start edge; docked, `open` in the markup is reverted to false. Its header holds `label` as an `h2` that names the dialog, staying - in view while the content scrolls, and a Close button named "Close" and the label, its text - replaceable through the `close` slot for a translation. As it opens, focus lands on its heading, + in view while the content scrolls, and a Close button, a glyph button showing web-icons' x-16, + named "Close" and the label, a name it shows as a hint on hover and keyboard focus; the `close` + slot replaces "Close" for a translation. As it opens, focus lands on its heading, `tabindex="-1"` and `autofocus`, not on the Close button; the heading shows no focus outline and is out of the Tab order, so Tab from it reaches the Close button. The Close button, Escape, `close()`, or `toggle()` closes it, and focus returns to what opened it. It dispatches `open` and `close` as the modal drawer opens and closes, never as the viewport crosses `dock`, which swaps only the wrapper, so the slotted content is never moved, disconnected, or re-created: an open drawer docks, and docked content becomes a closed drawer. It slides only when the reader - allows motion. Its mode is the custom state `docked` or `drawer`, which a page may style. + allows motion. `modal`, a reflected boolean, makes it the modal dialog at every width, ignoring + `dock`; setting or removing it is a switch too, so it closes an open drawer silently. Its mode is + the custom state `docked` or `drawer`, which a page may style. +- `./shortcuts.js`: `sl-shortcuts`, the page's keyboard shortcuts for a help dialog, as a plain-text + table of Keys and Action: exactly what the foundation's `bindings(dialog)` gives for the dialog + that holds it, `bindings(null)` outside one, in its order, each key in a `kbd` as the keys + grammar labels it, and each action the binding's registered label or its element's name. A row + the reader's setting turns off, character keys alone while character keys are off, carries the + word "off" after its keys and the class `off`. The screen-reader note, `NOTE`, follows the + table. It reads the bindings again as it connects, as its dialog opens, and at each `change` in + the document and each `storage` event. Nothing in it takes focus; it binds no key, runs no + binding, holds no setting, and renders no `[data-keys-list]`. +- `./settings.js`: `sl-settings`, the reader's settings for a Settings dialog: the theme's color, + scheme, space, and type rows, the registry's profile names and `SCHEMES`, each a ◀ value ▶ radio + group checked at what applies to the root, with an inert preview card beside them where the + element's own width fits both and below them where it doesn't, and the keys module's + character-key switch, `SWITCH_LABEL`, and wait between presses, `WAIT_LABEL`, one of `WAITS`. A + click on a row's arrow steps it, wrapping; on a row, H and L step it, J and K or the down and up + arrows move between rows, stopping at the ends, and the left and right arrows cycle its radios + natively; these keys stay inside its rows, and it binds no page key. Every change is applied to + the root and stored at once, through the foundation's preferences module, or the keys module's + `changeSettings`, with no Save and no Cancel, and fires a bubbling, composed `change` at the + host. It reads both settings again as it connects, as its dialog opens, and at each `change` in + the document and each `storage` event; as its dialog opens it focuses the first row's checked + radio, unless an element in the dialog has `autofocus`. Its shadow root adopts the foundation's + meta and structure sheets too, for the preview card's blue button and field. ## Rendering @@ -48,13 +74,6 @@ the tests measure as they do. marked's lexer: raw HTML shows as text, an image as its alt text, and a link is an anchor only to an http, https, or mailto URL or a relative one. It is the one module that imports marked, which an import map then maps too. -- `./json.js`: `formatJson(text)`, valid JSON text re-indented from its own tokens, two spaces an - indent: its keys in their order, duplicates included, its number literals, and its strings with - their escapes as written, only the whitespace between tokens changed. Containers to `MAX_DEPTH`, - 64, deep are indented; one that would open deeper is kept as written on the line where it opens, - so the output's length stays linear in the text's at any depth. It never decides whether - the text is valid; its caller does, as the artifact viewer and the chat thread do with - `JSON.parse`. ## Inspection @@ -63,9 +82,9 @@ the tests measure as they do. and content type that `no-header` (`noHeader`) leaves out, for a page whose own header shows them. Every state, its content or its loading, error, invalid JSON, unsupported, or empty note, is in a region named ` content`, header or not. Valid JSON is formatted from its own - tokens by `./json.js`, never parsed and printed again, so it shows its own keys, their order, - and its numbers; JSON that doesn't parse shows as text under a note. `viewOf(contentType)` gives - a type's `view` and the `content` it takes, `text` or `blob`, so a consumer knows what to + tokens by the foundation's `format.js`, never parsed and printed again, so it shows its own + keys, their order, and its numbers; JSON that doesn't parse shows as text under a note. + `viewOf(contentType)` gives a type's `view` and the `content` it takes, `text` or `blob`, so a consumer knows what to fetch. A text view is always safe, never a URL and never a document, so the viewer shows text whenever the content is text: "can't be shown" is left for bytes that aren't. The `content-type` decides the view, never a Blob's own type, and the Blob's bytes are shown as @@ -124,7 +143,7 @@ the tests measure as they do. labelled, and a streaming reply re-rendered in place; with `verbose`, reasoning, function calls, and their outputs too, each collapsed in a native details, a reasoning item's summary on its line and its content inside, and a call's arguments and its output that are valid JSON - formatted from their own tokens by `./json.js`. A thread its consumer holds + formatted from their own tokens by the foundation's `format.js`. A thread its consumer holds to a height scrolls inside, opening at its end and following the newest item only from its end or on a user's message; unheld, it is as tall as its content and follows nothing, so a consumer that wants it followed holds it. It exports its item types and sends no event. It imports @@ -155,15 +174,19 @@ the tests measure as they do. ## Demo `demo/components.html` puts the status badge, the entry, and the pagination on one page, with its -import map. Each component has a specimen page, `demo/.html`, for `status-badge`, `entry`, -`pagination`, `artifact-viewer`, `chat-thread`, `composer`, `upload-dropzone`, `stage-timeline`, -`event-log`, `search-results`, `document-list`, and `drawer`. A specimen page shows every state of -its component, labelled, then again in a section 20rem wide, and, for a component that holds a -control, one instance reached by the keyboard to show its focus ring: the screenshot script focuses -the focus section's `[data-focus-start]` mark, which takes focus only by script, then presses Tab as -many times as the mark's value says, so `:focus-visible` matches. A page whose component draws its -own frame drops the dashed one, so a capture shows the component's frame alone. The drawer's mode is -the viewport's, so its page is an app's frame instead, its states the page's at two widths: docked -at 1280px, and closed, open, and open right to left at 480px. The specimen pages link the +import map, and the [Settings and Help pattern](../README.md#settings-and-help) in its header, which +the settings and shortcuts pages carry too. `demo/glyphs.js` fills the pages' web-icons markers. +Each component has a specimen page, `demo/.html`, for `status-badge`, `entry`, `pagination`, +`artifact-viewer`, `chat-thread`, `composer`, `upload-dropzone`, `stage-timeline`, `event-log`, +`search-results`, `document-list`, `drawer`, `settings`, and `shortcuts`. A specimen page shows +every state of its component, labelled, then again in a section 20rem wide, and, for a component +that holds a control, one instance reached by the keyboard to show its focus ring: the screenshot +script focuses the focus section's `[data-focus-start]` mark, which takes focus only by script, then +presses Tab as many times as the mark's value says, so `:focus-visible` matches. A page whose +component draws its own frame drops the dashed one, so a capture shows the component's frame alone. +The drawer's mode is the viewport's, so its page is an app's frame instead, its states the page's at +two widths: docked at 1280px, and closed, open, and open right to left at 480px. Its Outline drawer +is `modal`, and its captures open it at 1280px, then reach its Close by Tab. The settings and +shortcuts captures add each page's dialog, opened by its key. The specimen pages link the foundation's `page-full.css` and import its `register-full.js`, so a profile applies by its attribute on the root. diff --git a/docs/development.md b/docs/development.md index 3de6d13..8ab1e50 100644 --- a/docs/development.md +++ b/docs/development.md @@ -8,8 +8,8 @@ workflows. `mise.toml` pins every tool the tasks run, and no task installs a missing one: `task.run_auto_install` is off, and `mise run install` is the one task that reads the network. -The foundation is a peer, which the repository's devDependency installs at its tag, so -`scripts/preflight.sh` looks for it in `node_modules` beside lit and marked. +The foundation and the icons are peers, which the repository's devDependencies install at their +tags, so `scripts/preflight.sh` looks for each in `node_modules` beside lit and marked. Chrome for Testing publishes no checksums, so each chrome-headless-shell bump takes the sha256 and size from the download by hand. mise caches a download by its checksum, so a version bumped without @@ -37,9 +37,9 @@ build ships. `types:test` doesn't: the tests import nothing from `dist/`. ## pnpm -`pnpm-workspace.yaml` lists no packages: the repository is one package. The foundation, a peer, and -the tooling, each a `github:` devDependency installed at its release tag, need no setting there: -pnpm guards only a git dependency below the top level (`blockExoticSubdeps`). +`pnpm-workspace.yaml` lists no packages: the repository is one package. The peers, the foundation +and the icons, and the tooling are each a `github:` devDependency installed at its release tag, and +need no setting there: pnpm guards only a git dependency below the top level (`blockExoticSubdeps`). - `allowBuilds` refuses unrs-resolver's postinstall. unrs-resolver, under eslint-plugin-import-x and eslint-import-resolver-typescript, fetches its native binding when the optional dependency @@ -52,10 +52,10 @@ pnpm guards only a git dependency below the top level (`blockExoticSubdeps`). ## Currency `scripts/currency.sh` reads mise's outdated report at the error log level: mise warns on every run -that a GitHub release has no assets. A `github:` devDependency, the foundation or the tooling, is -pinned to its repository's release tag, which the registry doesn't hold, so it is compared with that -repository's latest release. A peer, the foundation, is declared by a caret range, which must admit -that latest release so a consumer can declare it beside the components, by the release test's own +that a GitHub release has no assets. A `github:` devDependency, the foundation, the icons, or the +tooling, is pinned to its repository's release tag, which the registry doesn't hold, so it is +compared with that repository's latest release. A peer, the foundation or the icons, is declared by +a caret range, which must admit that latest release so a consumer can declare it beside the components, by the release test's own rule, `caretAdmits`. typescript is held to the newest version typescript-eslint's peer range accepts. A pin held back from its latest is named, with its reason, in `mise.toml`'s `HOLDS` list, in the format `scripts/currency.sh` gives. Each action a workflow uses is compared with its @@ -94,8 +94,8 @@ The layer's import rules: - The rule judges the file an import resolves to, never the specifier's text, and `no-unresolved` fails a specifier that names no file, so no import passes by naming none. - `no-extraneous-dependencies` judges an import against `package.json`: a package name it doesn't - declare in dependencies or peerDependencies, where the foundation is (a devDependency alone ships - nothing, and `includeInternal` holds the package's own name, which resolves inside it, to the + declare in dependencies or peerDependencies, where the foundation and the icons are (a + devDependency alone ships nothing, and `includeInternal` holds the package's own name, which resolves inside it, to the same), in every import form (`includeTypes`). `no-relative-packages` refuses a relative path that reaches another package's files. diff --git a/docs/internals.md b/docs/internals.md index 8849d85..2c3afef 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -22,10 +22,10 @@ each sheet is laid out as it is. up to two pixels between, more where a device pixel is more than a CSS one, and within one CSS pixel the follow would stop by itself at a zoom of 0.9 or 1.1. A browser without `currentCSSZoom` is taken as unzoomed. -- Valid JSON is shown by `formatJson()` from its own tokens: `JSON.parse` decides validity alone and - its value is thrown away, since printing it would move integer-like keys first, rewrite numbers, - and drop duplicate keys. Text whose formatting would pass the longest string, a `RangeError`, - shows as it is. +- Valid JSON is shown by the foundation's `tryFormatJson()`, formatted from its own tokens: + `JSON.parse` decides validity alone and its value is thrown away, since printing it would move + integer-like keys first, rewrite numbers, and drop duplicate keys. Text whose formatting would + pass the longest string, a `RangeError`, shows as it is. ## Artifact viewer diff --git a/docs/layout.md b/docs/layout.md index a4c2223..2975bf7 100644 --- a/docs/layout.md +++ b/docs/layout.md @@ -8,11 +8,16 @@ layout each one promises. - Each component adopts its sheet into its shadow root after the foundation's `baseline/reset.css` and `baseline/elements.css`, which give the native controls, the pre, the rendered Markdown, the - details and summary, and the focus outline their look. The sheet is unlayered, so it sits above - both, and it gives a native control no look of its own beyond its layout. + details and summary, and the focus outline their look. Between those and its own, it adopts the + foundation's sheets whose classes it uses: `utilities.css` (every component but the status + badge), `glyph-button.css` (the drawer's Close), `dialog.css` (the drawer's header row), + `motion.css` (the drawer's slide, the dropzone's drag-over change, the chat thread's pulse, and + the stage timeline's ring), and `meta.css` and `structure.css` (the settings' preview card). Its + own sheet is unlayered, so it sits above all of them, and it gives a native control no look of + its own beyond its layout. - A sheet reads only the foundation's baseline tokens, which a shadow root inherits from the page's - entry. A component in progress takes `--accent-color`, the foundation's hook for what is current - or in progress, falling back to `--magenta`; an interaction takes `--interaction-color`, falling + entry. A component in progress takes `--color-accent`, the foundation's hook for what is current + or in progress, falling back to `--magenta`; an interaction takes `--color-primary`, falling back to `--blue`. - A component that draws one frame around content that scrolls (the artifact viewer, the event log, the chat thread) makes it a flex child of a flex-column host with `min-block-size: 0`, so a @@ -160,9 +165,8 @@ layout each one promises. - The field and the control are siblings in a row, each its own native frame, never one inside another; the control sits at the row's block end, beside the field's last line. - The field's bound is eight lines inside its padding and border; past it the field scrolls. -- The elements sheet styles a disabled button but not a disabled field, so the composer gives its - disabled field the first elevated surface, a divider's border, and text a tier quieter, still - apart from the placeholder's `--fg-3`. +- A disabled field takes the elements sheet's disabled look: the first elevated surface, a + divider's border, and text a tier quieter, still apart from the placeholder's `--fg-3`. ## Pagination diff --git a/docs/release.md b/docs/release.md index 0ac3b8e..e84915a 100644 --- a/docs/release.md +++ b/docs/release.md @@ -36,7 +36,7 @@ the tag's tree to the pack, file for file; and creates the GitHub release from t - **CI** runs the check on each pull request to main and each push to it. `mise run install` first installs every pin `mise.toml` names, the chrome-headless-shell the browser tier runs in - included, and `node_modules`, the foundation and the tooling at their release tags. + included, and `node_modules`, the foundation, the icons, and the tooling at their release tags. - **Release** checks out every branch and tag, so the pack commit's parent and main are both at hand. The parent must be main's merge commit, so it has two parents of its own. The tagged tree must be the tarball's `package/`, file for file. The release action releases the tag its `ref` @@ -46,10 +46,11 @@ the tag's tree to the pack, file for file; and creates the GitHub release from t ## Dependencies `test/unit/release.ts` holds every release to its dependencies. lit and marked are its two -dependencies, each at one version, never a range. The foundation is a peer, by a caret range on its -versions, never a git spec, so a consumer declares it from whichever source; the -[README](../README.md#install) says why it is a peer. The repository's own install of it is a -devDependency at one release tag on GitHub, never a range, a branch, a commit, or a `#semver:` spec, +dependencies, each at one version, never a range. The foundation and the icons, +`@standards-lab/web-icons`, are its two peers, each by a caret range on its versions, never a git +spec, so a consumer declares each from whichever source; the [README](../README.md#install) says +why each is a peer. The repository's own install of each is a devDependency at one +release tag on its own GitHub repository, never a range, a branch, a commit, or a `#semver:` spec, which bun fails, and a tag the peer range admits: the same leftmost nonzero part and no lower, so `^0.1.0` admits 0.1.x only. Which version, range, and tag is `package.json`'s, and `mise run currency` reports each behind its latest. The packed manifest carries no scripts, since diff --git a/docs/testing.md b/docs/testing.md index 8b497d6..6ac6260 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -15,8 +15,8 @@ the behavior and layout each one holds to. the browser tier, `mise run demo`, and the screenshots description all serve, so the list is kept once. Of the served packages, lit's own dependencies (lit-html, lit-element, and `@lit/reactive-element`) sit beside it in pnpm's store and the server brings them with it; the - foundation is the install the components' `dist/` imports by name, reached as a consumer reaches - it. + foundation and the icons are the installs the components' `dist/` imports by name, reached as a + consumer reaches them. - `test/browser/support/types.js` is run by no page: tsc checks it with the in-page modules against the same `dist/`, so a declaration that narrows what a consumer may write fails `types:browser`. @@ -52,8 +52,11 @@ the behavior and layout each one holds to. out: it links only the lean entry, so it shows one profile. - Text in a fully transparent color shows nothing, as a hidden mark does, so it takes no color token. -- The stage timeline holds no control, so the focus ring cases skip it; a case pins that it renders - nothing focusable, so a control it gains must get a ring case. +- The stage timeline and the shortcuts list hold no control, so the focus ring cases skip their + pages; a case pins that each renders nothing focusable, so a control one gains must get a ring + case. +- `shortcut-dialogs.test.ts` runs on the demo pages that carry the Settings and Help pattern, so + the README's markup is held to working with the components. ## Components @@ -91,13 +94,6 @@ the behavior and layout each one holds to. and drop the first duplicate, so these values show the output comes from the text's own tokens. - `test/browser/support/deep.ts` writes out the formatter's output for deep nesting rather than reading it from `formatJson`, so a test that compares a view with it checks the formatter too. -- The depth-65 case puts an opening brace in a key, an escaped quote before closing brackets, and an - escaped backslash before a string's real end, then at depth 64 a string holding the brackets that - would close it. A bracket count any of these fools ends the kept container early or late. -- The 20,000-deep case bounds the output at the text's length plus 4·64·64 characters: the 64 - formatted levels each add a line break and at most 128 spaces at their opening and closing - brackets, and the levels below are kept as written. Indenting every level would take some 800 - million spaces. ## Artifact viewer diff --git a/eslint.config.js b/eslint.config.js index 1fe35cf..2dbf608 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -34,11 +34,13 @@ const cssImports = [ ]; const foundation = "@standards-lab/web-foundation"; -/** The layer table cut to the components: their sources, which may import themselves and three - * packages by name, lit, marked, and the foundation, which the manifest declares, the foundation as - * a peer; the foundation is reached only through its install, as a consumer reaches it. */ +const icons = "@standards-lab/web-icons"; +/** The layer table cut to the components: their sources, which may import themselves and four + * packages by name, lit, marked, the foundation, and the icons, which the manifest declares, the + * foundation and the icons as peers; each peer is reached only through its install, as a consumer + * reaches it. */ export const layers = [ - { name: "components", path: "src", may: ["components", "lit", "marked", foundation] }, + { name: "components", path: "src", may: ["components", "lit", "marked", foundation, icons] }, ]; const elements = layers.map(({ name, path }) => ({ diff --git a/mise.toml b/mise.toml index 4b780c5..132e598 100644 --- a/mise.toml +++ b/mise.toml @@ -4,13 +4,8 @@ [settings] task.run_auto_install = false -[env] -HOLDS = ''' -@standards-lab/web-foundation v0.3.0: v0.4.0 renames --accent-color and --interaction-color and changes adopted element rules; v1.client.stack's components-settings takes it with its design review -''' - [tools] -"github:standards-lab/claude-plugins" = { version = "0.22.0", version_prefix = "marathon/v" } +"github:standards-lab/claude-plugins" = { version = "0.23.0", version_prefix = "marathon/v" } actionlint = "1.7.12" node = "26.13.1" pnpm = "12.21.0" @@ -110,6 +105,6 @@ raw = true run = "BROWSER_EXECUTABLE=$(mise which chrome-headless-shell) pnpm exec web-screenshots scripts/screenshots.config.ts" [tasks.currency] -description = "Report every mise tool, package.json pin, action pin, the foundation's and the tooling's tags, and the foundation's peer range behind its latest, a held pin with its reason, exiting nonzero if any isn't held; reads the network" +description = "Report every mise tool, package.json pin, action pin, the foundation's, the icons', and the tooling's tags, and the foundation's and the icons' peer ranges behind their latest, a held pin with its reason, exiting nonzero if any isn't held; reads the network" run = "scripts/currency.sh" quiet = true diff --git a/package.json b/package.json index 543d9c9..4d32410 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@standards-lab/web-components", - "version": "0.1.0", + "version": "0.2.0", "license": "Apache-2.0", "type": "module", "files": [ @@ -18,12 +18,14 @@ "marked": "18.2.1" }, "peerDependencies": { - "@standards-lab/web-foundation": "^0.3.0" + "@standards-lab/web-foundation": "^0.4.0", + "@standards-lab/web-icons": "^0.1.0" }, "devDependencies": { "@eslint-community/eslint-plugin-eslint-comments": "4.8.1", "@eslint/js": "10.0.1", - "@standards-lab/web-foundation": "github:standards-lab/web-foundation#v0.3.0", + "@standards-lab/web-foundation": "github:standards-lab/web-foundation#v0.4.0", + "@standards-lab/web-icons": "github:standards-lab/web-icons#v0.1.0", "@standards-lab/web-tooling": "github:standards-lab/web-tooling#v0.1.0", "@types/node": "26.6.6", "eslint": "10.15.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e3b0859..44f6e50 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -22,8 +22,11 @@ importers: specifier: 10.0.1 version: 10.0.1(eslint@10.15.0(supports-color@7.2.0)) '@standards-lab/web-foundation': - specifier: github:standards-lab/web-foundation#v0.3.0 - version: https://codeload.github.com/standards-lab/web-foundation/tar.gz/f8b3edc0dc658cfff64ec4eb60b5dd7019798b0b + specifier: github:standards-lab/web-foundation#v0.4.0 + version: https://codeload.github.com/standards-lab/web-foundation/tar.gz/67b3b6cd1a60dc4ce420039a2b584961f68d201f + '@standards-lab/web-icons': + specifier: github:standards-lab/web-icons#v0.1.0 + version: https://codeload.github.com/standards-lab/web-icons/tar.gz/499927708dcf386e0cff3de7ba84a10eaf19fa1a '@standards-lab/web-tooling': specifier: github:standards-lab/web-tooling#v0.1.0 version: https://codeload.github.com/standards-lab/web-tooling/tar.gz/24363f36750fe287250ac8b48310b6e02f22f794 @@ -158,9 +161,18 @@ packages: '@lit/reactive-element@2.1.2': resolution: {integrity: sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==} - '@standards-lab/web-foundation@https://codeload.github.com/standards-lab/web-foundation/tar.gz/f8b3edc0dc658cfff64ec4eb60b5dd7019798b0b': - resolution: {gitHosted: true, integrity: sha512-yOEDzhuWiRQt9+0KTv3hj4GOqGOx6uvQQLi7es9GqR+gENMp2nM+LZ/fp1vNYP3VktDeyXIxTLjyjLGysYTtWA==, tarball: https://codeload.github.com/standards-lab/web-foundation/tar.gz/f8b3edc0dc658cfff64ec4eb60b5dd7019798b0b} - version: 0.3.0 + '@standards-lab/web-foundation@https://codeload.github.com/standards-lab/web-foundation/tar.gz/67b3b6cd1a60dc4ce420039a2b584961f68d201f': + resolution: {gitHosted: true, integrity: sha512-XHEQUH+IRxncWqdaNLgRFjpF6f4Jc9WJWTh/7weKEbrjbha2nDgfj+pdwsKITbcuXOqqgqc2Dyx1lr/q7nlQsg==, tarball: https://codeload.github.com/standards-lab/web-foundation/tar.gz/67b3b6cd1a60dc4ce420039a2b584961f68d201f} + version: 0.4.0 + + '@standards-lab/web-icons@https://codeload.github.com/standards-lab/web-icons/tar.gz/499927708dcf386e0cff3de7ba84a10eaf19fa1a': + resolution: {gitHosted: true, integrity: sha512-oiiC6Qi9kuhp3arxvQt3zi4Y98DhRmIYGP2cA/W3TF4MyHYTWlFCGZ0wWIvmaK4NDTqsLdc5xfemPZin+ZP+dg==, tarball: https://codeload.github.com/standards-lab/web-icons/tar.gz/499927708dcf386e0cff3de7ba84a10eaf19fa1a} + version: 0.1.0 + peerDependencies: + vite: ^8.3.8 + peerDependenciesMeta: + vite: + optional: true '@standards-lab/web-tooling@https://codeload.github.com/standards-lab/web-tooling/tar.gz/24363f36750fe287250ac8b48310b6e02f22f794': resolution: {gitHosted: true, integrity: sha512-D+0nTntEPlGCsjg82qXCVPb0INy38/uyiEbYbewQ+gq7pGSMMd9Mw1BDL2/VbuIQMI17cxXRKnnPZDrvP9eAyg==, tarball: https://codeload.github.com/standards-lab/web-tooling/tar.gz/24363f36750fe287250ac8b48310b6e02f22f794} @@ -938,7 +950,9 @@ snapshots: dependencies: '@lit-labs/ssr-dom-shim': 1.6.0 - '@standards-lab/web-foundation@https://codeload.github.com/standards-lab/web-foundation/tar.gz/f8b3edc0dc658cfff64ec4eb60b5dd7019798b0b': {} + '@standards-lab/web-foundation@https://codeload.github.com/standards-lab/web-foundation/tar.gz/67b3b6cd1a60dc4ce420039a2b584961f68d201f': {} + + '@standards-lab/web-icons@https://codeload.github.com/standards-lab/web-icons/tar.gz/499927708dcf386e0cff3de7ba84a10eaf19fa1a': {} '@standards-lab/web-tooling@https://codeload.github.com/standards-lab/web-tooling/tar.gz/24363f36750fe287250ac8b48310b6e02f22f794': {} diff --git a/scripts/demo.js b/scripts/demo.js index 8873e81..cc66dea 100644 --- a/scripts/demo.js +++ b/scripts/demo.js @@ -22,6 +22,8 @@ for (const page of [ "search-results", "document-list", "drawer", + "settings", + "shortcuts", ]) { console.log(`${server.origin}/demo/${page}.html`); } diff --git a/scripts/preflight.sh b/scripts/preflight.sh index b8281e7..0ccd145 100755 --- a/scripts/preflight.sh +++ b/scripts/preflight.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Fails naming mise run install when a tool a task needs is missing: the node_modules tooling, the -# dependencies the build reads, lit, marked, and the foundation at its tag, and with `browser`, the -# pinned chrome-headless-shell. +# dependencies the build reads, lit, marked, and the foundation and the icons at their tags, and +# with `browser`, the pinned chrome-headless-shell. # See docs/development.md # Adapted from spike-html-apps-components (10dde51): scripts/preflight.sh, on web-foundation. set -euo pipefail @@ -20,6 +20,8 @@ require_node_modules() { [[ -f node_modules/marked/package.json ]] || fail "marked (dependencies)" [[ -f node_modules/@standards-lab/web-foundation/package.json ]] || fail "@standards-lab/web-foundation (devDependencies)" + [[ -f node_modules/@standards-lab/web-icons/package.json ]] || + fail "@standards-lab/web-icons (devDependencies)" } require_browser_at_pin() { diff --git a/scripts/screenshots.config.ts b/scripts/screenshots.config.ts index 88df0d6..9b65cbb 100644 --- a/scripts/screenshots.config.ts +++ b/scripts/screenshots.config.ts @@ -1,8 +1,11 @@ // The capture description web-tooling's web-screenshots bin reads for mise run screenshots: each -// specimen page under demo/, whole in tiles, and the drawer's page in its viewport at a wide and a -// narrow width in four states; the palette, space, and type facets at the foundation's defaults; -// --all's profiles; each page's registered profiles; and the repository served as the browser tier -// serves it. +// specimen page under demo/, whole in tiles; the drawer's page in its viewport at a wide and a +// narrow width in four states, and its modal drawer open at the wide width, then with its Close +// reached by Tab and its hint shown; the settings' page whole, then with the Settings dialog opened +// by S, wide and narrow, focus in its rows; the shortcuts' page whole, then with the Help dialog +// opened by ?, its Close reached by Tab and its hint shown; the palette, space, and type facets at +// the foundation's defaults; --all's profiles; each page's registered profiles; and the repository +// served as the browser tier serves it. // Adapted from spike-html-apps-components (10dde51): scripts/screenshots.config.ts, on web-tooling. import type { @@ -33,6 +36,64 @@ const openedByEnter = })()`); }; +const tabToHint: Step = async (page) => { + const key = { key: "Tab", code: "Tab", windowsVirtualKeyCode: 9 }; + await page.cdp("Input.dispatchKeyEvent", { type: "keyDown", ...key }); + await page.cdp("Input.dispatchKeyEvent", { type: "keyUp", ...key }); + await page.evaluate(`(async () => { + let active = document.activeElement; + while (active.shadowRoot?.activeElement) active = active.shadowRoot.activeElement; + const hint = active.getRootNode().getElementById(active.getAttribute("interestfor")); + while (!hint.matches(":popover-open")) { + await new Promise((resolve) => requestAnimationFrame(resolve)); + } + await Promise.all(hint.getAnimations().map((a) => a.finished)); + })()`); +}; + +const modalOpened = + (then?: Step): Step => + async (page) => { + await page.cdp("Emulation.setFocusEmulationEnabled", { enabled: true }); + await page.evaluate(`(async () => { + const drawer = document.querySelector("#outline"); + document.querySelector("#open-outline").click(); + await drawer.updateComplete; + const dialog = drawer.shadowRoot.querySelector("dialog"); + await Promise.all(dialog.getAnimations({ subtree: true }).map((a) => a.finished)); + })()`); + await then?.(page); + }; + +const pressed = + (key: "s" | "?", dialog: string, then?: Step): Step => + async (page) => { + await page.cdp("Emulation.setFocusEmulationEnabled", { enabled: true }); + const press = + key === "s" + ? { key: "s", code: "KeyS", windowsVirtualKeyCode: 83 } + : { key: "?", code: "Slash", windowsVirtualKeyCode: 191, modifiers: 8 }; + await page.cdp("Input.dispatchKeyEvent", { + type: "keyDown", + ...press, + text: key, + unmodifiedText: key, + }); + await page.cdp("Input.dispatchKeyEvent", { type: "keyUp", ...press }); + await page.evaluate(`(async () => { + const dialog = document.querySelector("${dialog}"); + while (!dialog.open) await new Promise((resolve) => requestAnimationFrame(resolve)); + const hosts = dialog.querySelectorAll("sl-settings, sl-shortcuts"); + await Promise.all([...hosts].map((host) => host.updateComplete)); + const settled = () => { + const active = document.activeElement; + return dialog.contains(active) && (!active.shadowRoot || active.shadowRoot.activeElement); + }; + while (!settled()) await new Promise((resolve) => requestAnimationFrame(resolve)); + })()`); + await then?.(page); + }; + const drawerStates: DescribedState[] = [ { name: "drawer-docked", @@ -60,6 +121,51 @@ const drawerStates: DescribedState[] = [ full: false, open: openedByEnter("rtl"), }, + { + name: "drawer-modal", + caption: "the modal drawer, open at 1280px", + viewport: docked, + full: false, + open: modalOpened(), + }, + { + name: "drawer-modal-close", + caption: "the modal drawer, open at 1280px, its Close reached by Tab, its hint shown", + viewport: docked, + full: false, + open: modalOpened(tabToHint), + }, +]; + +const narrow = { width: 390, height: 844 }; + +const settingsStates: DescribedState[] = [ + { name: "settings", caption: "the settings", full: true }, + { + name: "settings-dialog", + caption: "the Settings dialog, opened by S", + viewport: docked, + full: false, + open: pressed("s", "#settings"), + }, + { + name: "settings-dialog-narrow", + caption: "the Settings dialog at 390px, opened by S", + viewport: narrow, + full: false, + open: pressed("s", "#settings"), + }, +]; + +const shortcutsStates: DescribedState[] = [ + { name: "shortcuts", caption: "the shortcuts", full: true }, + { + name: "shortcuts-dialog", + caption: "the Help dialog, opened by ?, then Tab to its Close, its hint shown", + viewport: docked, + full: false, + open: pressed("?", "#help", tabToHint), + }, ]; const pages: DescribedPage[] = ( @@ -78,12 +184,26 @@ const pages: DescribedPage[] = ( ] satisfies [name: string, caption: string][] ) .map(([name, caption]): DescribedPage => ({ name, caption, path: `demo/${name}.html` })) - .concat({ - name: "drawer", - caption: "the drawer", - path: "demo/drawer.html", - states: drawerStates, - }); + .concat( + { + name: "drawer", + caption: "the drawer", + path: "demo/drawer.html", + states: drawerStates, + }, + { + name: "settings", + caption: "the settings", + path: "demo/settings.html", + states: settingsStates, + }, + { + name: "shortcuts", + caption: "the shortcuts", + path: "demo/shortcuts.html", + states: shortcutsStates, + }, + ); const REGISTRY = `(() => { const store = globalThis[Symbol.for("web-foundation.registry")] ?? {}; diff --git a/src/artifact-viewer.css b/src/artifact-viewer.css index ae50689..f73dcd5 100644 --- a/src/artifact-viewer.css +++ b/src/artifact-viewer.css @@ -1,9 +1,11 @@ /* From spike-html-apps-components (10dde51): src/artifact-viewer.css. */ /* - * The artifact viewer's shadow-root sheet: a header of the name and content type over one - * frame that holds a note, the scrolling region, or a native view. - * Unlayered, above the foundation's reset and elements sheets; it reads only the baseline tokens. + * The artifact viewer's shadow-root sheet: a header of the name and content type, on the + * utilities' head row, over one frame that holds a note, the utilities' scrolling frame as the + * region, or a native view. + * Unlayered, above the foundation's reset, elements, and utilities sheets; it reads only the + * baseline tokens. * See docs/layout.md */ @@ -13,26 +15,13 @@ } .header { flex: none; - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: var(--space-3xs) var(--space-xs); margin-block-end: var(--space-2xs); - min-inline-size: 0; overflow-wrap: anywhere; } .name { - flex: 1 1 16ch; - max-inline-size: max-content; - min-inline-size: 0; font-size: var(--text-s); font-weight: 600; } -.type { - margin-inline-start: auto; - font-size: var(--text-s); - color: var(--fg-2); -} .frame { flex: 1 1 auto; display: flex; @@ -42,11 +31,6 @@ border-radius: var(--radius-sm); } .body { - flex: 1 1 auto; - display: grid; - grid-template-columns: minmax(0, 1fr); - min-block-size: 0; - overflow: auto; margin: 0; padding: 0; border: 0; @@ -87,10 +71,6 @@ .error > .label { color: var(--red); } -.detail { - font-size: var(--text-s); - color: var(--fg-2); -} .download { justify-self: start; } diff --git a/src/artifact-viewer.ts b/src/artifact-viewer.ts index c3fd4b1..3e4eca6 100644 --- a/src/artifact-viewer.ts +++ b/src/artifact-viewer.ts @@ -10,8 +10,9 @@ import { html, LitElement, nothing, type PropertyDeclarations, type PropertyValu import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define } from "@standards-lab/web-foundation/dom.js"; -import { formatJson } from "./json.ts"; +import { type FormattedJson, tryFormatJson } from "@standards-lab/web-foundation/format.js"; import { markdown } from "./markdown.ts"; import styles from "./artifact-viewer.css" with { type: "css" }; @@ -128,30 +129,15 @@ async function textOf(blob: Blob): Promise { } } -type Json = { ok: true; text: string } | { ok: false; reason: string }; - -function pretty(content: string): Json { - try { - JSON.parse(content); - } catch (error) { - return { ok: false, reason: error instanceof Error ? error.message : String(error) }; - } - try { - return { ok: true, text: formatJson(content) }; - } catch { - return { ok: true, text: content }; - } -} - /** * Shows one artifact: a header of its name and content type over its content, or, with * `noHeader`, its content alone, for a page that already shows the name and type in a header of * its own. Markdown renders through `markdown()`; valid JSON is formatted from its own tokens by - * `formatJson()`, two spaces an indent, so its keys, their order, duplicates, numbers, and - * strings show as written, never parsed and printed again; and other text, text/html, XML, and - * SVG's source included, is shown as it is, never as a page and from no URL. JSON that doesn't - * parse shows its raw text under a note saying so, and empty content a note saying so. Long - * content scrolls inside the viewer, in a region the keyboard reaches. + * the foundation's `formatJson()`, two spaces an indent, so its keys, their order, duplicates, + * numbers, and strings show as written, never parsed and printed again; and other text, + * text/html, XML, and SVG's source included, is shown as it is, never as a page and from no URL. + * JSON that doesn't parse shows its raw text under a note saying so, and empty content a note + * saying so. Long content scrolls inside the viewer, in a region the keyboard reaches. * * A PDF, an image, audio, or video shows from a Blob, natively: a PDF in an iframe, the browser's * own viewer, as tall as the viewer allows; an image no wider than the viewer and never past its @@ -170,7 +156,7 @@ function pretty(content: string): Json { * native element. Display-only: it sends no event. */ export class ArtifactViewer extends LitElement { - static styles = [reset, elements, styles]; + static styles = [reset, elements, utilities, styles]; static properties = { name: { type: String }, @@ -197,7 +183,7 @@ export class ArtifactViewer extends LitElement { /** Leaves out the header, so the content shows alone; its region keeps its name. */ declare noHeader: boolean; - #json: Json | null = null; + #json: FormattedJson | null = null; #url = ""; #blob: Blob | null = null; #type = ""; @@ -229,7 +215,7 @@ export class ArtifactViewer extends LitElement { if (changed.has("content") || changed.has("contentType")) { const text = typeof this.content === "string" ? this.content : ""; const { view } = viewOf(this.contentType); - this.#json = view === "json" ? pretty(text) : null; + this.#json = view === "json" ? tryFormatJson(text) : null; if (view === "unknown" && this.content instanceof Blob) this.#readBlob(this.content); } this.#sync(); @@ -286,11 +272,11 @@ export class ArtifactViewer extends LitElement { #region(content: unknown, markdownView = false, describedBy: string | typeof nothing = nothing) { return markdownView - ? html`
    + ? html`
    ${content}
    ` : html`
           ${label}
    -      ${detail === nothing ? nothing : html`${detail}`} ${action}
    +      ${detail === nothing ? nothing : html`${detail}`} ${action}
         

    `; } @@ -352,7 +338,7 @@ export class ArtifactViewer extends LitElement { case "markdown": return html`
    ${this.#region(markdown(content), true)}
    `; case "json": { - const json = this.#json ?? pretty(content); + const json = this.#json ?? tryFormatJson(content); if (json.ok) return html`
    ${this.#region(json.text)}
    `; return html`
    ${this.#note("invalid", "Invalid JSON, shown as text.", json.reason)} @@ -392,9 +378,9 @@ export class ArtifactViewer extends LitElement { render() { const header = !this.noHeader && (this.name || this.contentType) - ? html`
    - ${this.name ? html`${this.name}` : nothing} - ${this.contentType ? html`${this.contentType}` : nothing} + ? html`
    + ${this.name ? html`${this.name}` : nothing} + ${this.contentType ? html`${this.contentType}` : nothing}
    ` : nothing; return html`${header}${this.#frame()}`; diff --git a/src/chat-thread.css b/src/chat-thread.css index 30ea720..9321907 100644 --- a/src/chat-thread.css +++ b/src/chat-thread.css @@ -1,9 +1,11 @@ /* From spike-html-apps-components (10dde51): src/chat-thread.css. */ /* - * The chat thread's shadow-root sheet: one frame that scrolls the list of items, each message's - * place and label row, a verbose item's line, a refusal's mark, and the streaming indicator. - * Unlayered, above the foundation's reset and elements sheets; it reads only the baseline tokens. + * The chat thread's shadow-root sheet: the utilities' scrolling frame around the bare list of + * items, each message's place and label row, a verbose item's line, a refusal's mark, and the + * streaming indicator's dot, which the motion sheet's pulse runs. + * Unlayered, above the foundation's reset, elements, utilities, and motion sheets; it reads only + * the baseline tokens. * See docs/layout.md */ @@ -12,12 +14,6 @@ flex-direction: column; } .frame { - flex: 1 1 auto; - display: grid; - grid-template-columns: minmax(0, 1fr); - align-content: start; - min-block-size: 0; - overflow: auto; border: var(--line-s) solid var(--border); border-radius: var(--radius-sm); } @@ -27,11 +23,9 @@ gap: var(--space-s); margin: 0; padding: var(--space-s); - list-style: none; } .thread > .item { min-inline-size: 0; - margin: 0; } .thread > .user { align-self: flex-end; @@ -48,8 +42,6 @@ align-items: baseline; gap: var(--space-3xs) var(--space-xs); font-family: var(--font-ui); - font-size: var(--text-s); - color: var(--fg-2); } .message > .meta { display: flex; @@ -61,8 +53,6 @@ summary, .line { font-family: var(--font-ui); - font-size: var(--text-s); - color: var(--fg-2); } .gutter { display: inline list-item; @@ -83,17 +73,8 @@ summary, font-weight: 600; } .kind, -.name, -.id, .status { display: inline-block; - white-space: nowrap; -} -.name, -.id { - max-inline-size: 100%; - white-space: normal; - overflow-wrap: anywhere; } .id { color: var(--fg-3); @@ -124,25 +105,14 @@ summary, .refusal > .label { color: var(--orange); } -.status.in_progress::before { - content: ""; +.status > .dot { display: inline-block; margin-inline-end: var(--space-3xs); vertical-align: 0.1em; inline-size: 0.5em; block-size: 0.5em; border-radius: var(--radius-full); - background-color: var(--accent-color, var(--magenta)); -} -@media (prefers-reduced-motion: no-preference) { - .status.in_progress::before { - animation: pulse 1.4s ease-in-out infinite; - } -} -@keyframes pulse { - 50% { - opacity: 0.25; - } + background-color: var(--color-accent, var(--magenta)); } .status.incomplete { color: var(--orange); @@ -160,7 +130,3 @@ summary, padding: var(--space-xs) var(--space-s); color: var(--fg-2); } -.empty { - font-size: var(--text-s); - color: var(--fg-2); -} diff --git a/src/chat-thread.ts b/src/chat-thread.ts index cdeef2d..31e4177 100644 --- a/src/chat-thread.ts +++ b/src/chat-thread.ts @@ -18,8 +18,10 @@ import { repeat } from "lit/directives/repeat.js"; import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import motion from "@standards-lab/web-foundation/motion.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define } from "@standards-lab/web-foundation/dom.js"; -import { formatJson } from "./json.ts"; +import { tryFormatJson } from "@standards-lab/web-foundation/format.js"; import { markdown } from "./markdown.ts"; import styles from "./chat-thread.css" with { type: "css" }; @@ -101,12 +103,8 @@ export interface FunctionCallOutputItem { export type ThreadItem = MessageItem | ReasoningItem | FunctionCallItem | FunctionCallOutputItem; function pretty(text: string): string { - try { - JSON.parse(text); - return formatJson(text); - } catch { - return text; - } + const json = tryFormatJson(text); + return json.ok ? json.text : text; } const STATUS_LABELS: Partial> = { @@ -157,7 +155,7 @@ function end(frame: HTMLElement) { * holds it to a height. */ export class ChatThread extends LitElement { - static styles = [reset, elements, styles]; + static styles = [reset, elements, utilities, motion, styles]; static properties = { items: { attribute: false }, @@ -252,7 +250,11 @@ export class ChatThread extends LitElement { #status(status: ItemStatus | undefined) { const label = status ? STATUS_LABELS[status] : undefined; if (!label) return nothing; - return html`${label}`; + const dot = + status === "in_progress" + ? html`` + : nothing; + return html`${dot}${label}`; } #message(item: MessageItem) { @@ -275,14 +277,14 @@ export class ChatThread extends LitElement { class="message ${item.role}" aria-busy=${item.status === "in_progress" ? "true" : nothing} > -
    ${role}${this.#status(item.status)}
    +
    ${role}${this.#status(item.status)}
    ${parts}
    `; } #line(item: ThreadItem, kind: string, names: TemplateResult[], described: TemplateResult[]) { const status = this.#status(item.status); - const parts = [html`${kind}`, ...names]; + const parts = [html`${kind}`, ...names]; if (status !== nothing) parts.push(status); parts.push(...described); return parts.map((part, index) => (index ? html` ${part}` : part)); @@ -296,7 +298,7 @@ export class ChatThread extends LitElement { described: TemplateResult[] = [], ) { return html`
    - ${this.#line(item, kind, names, described)} + ${this.#line(item, kind, names, described)}
    ${body}
    `; } @@ -314,7 +316,7 @@ export class ChatThread extends LitElement { if (summary && !thought) { const gutter = html``; const line = this.#line(item, "Reasoning", [], described); - return html`

    ${gutter}${line}

    `; + return html`

    ${gutter}${line}

    `; } return this.#details( item, @@ -322,7 +324,7 @@ export class ChatThread extends LitElement { [], thought ? content.map((part) => html`

    ${part.text}

    `) - : html`

    No reasoning text.

    `, + : html`

    No reasoning text.

    `, described, ); } @@ -332,8 +334,13 @@ export class ChatThread extends LitElement { return this.#details( item, "Function call", - [html`${item.name}`, html`${item.call_id}`], - args.trim() ? html`
    ${pretty(args)}
    ` : html`

    No arguments.

    `, + [ + html`${item.name}`, + html`${item.call_id}`, + ], + args.trim() + ? html`
    ${pretty(args)}
    ` + : html`

    No arguments.

    `, ); } @@ -349,10 +356,12 @@ export class ChatThread extends LitElement { item, "Function output", [ - ...(name ? [html`${name}`] : []), - html`${item.call_id}`, + ...(name ? [html`${name}`] : []), + html`${item.call_id}`, ], - output.trim() ? html`
    ${pretty(output)}
    ` : html`

    No output.

    `, + output.trim() + ? html`
    ${pretty(output)}
    ` + : html`

    No output.

    `, ); } @@ -381,10 +390,10 @@ export class ChatThread extends LitElement { return; } }); - return html`
    + return html`
    ${ shown.length - ? html`
      + ? html`
        ${repeat( shown, ({ key }) => key, diff --git a/src/composer.css b/src/composer.css index 98e0d20..8c6c792 100644 --- a/src/composer.css +++ b/src/composer.css @@ -2,22 +2,15 @@ /* * The composer's shadow-root sheet: the row of the growing field and its send or stop control, - * and the visually hidden label. - * Unlayered, above the foundation's reset and elements sheets; it reads only the baseline tokens. + * the action stacking both its names on the utilities' alternatives. + * Unlayered, above the foundation's reset, elements, and utilities sheets; it reads only the + * baseline tokens. * See docs/layout.md */ :host { display: block; } -.label { - position: absolute; - inline-size: 1px; - block-size: 1px; - overflow: hidden; - clip-path: inset(50%); - white-space: nowrap; -} .composer { display: flex; align-items: end; @@ -26,24 +19,12 @@ textarea { flex: 1 1 0; min-inline-size: 12ch; - max-block-size: calc(8lh + 2 * var(--space-3xs) + 2 * var(--line-s)); + max-block-size: calc(8lh + var(--control-edge)); field-sizing: content; resize: none; overflow-wrap: anywhere; } -textarea:disabled { - border-color: var(--border); - background-color: var(--bg-1); - color: var(--fg-2); -} .action { flex: none; - display: grid; justify-items: center; } -.action > span { - grid-area: 1 / 1; -} -.action > .off { - visibility: hidden; -} diff --git a/src/composer.ts b/src/composer.ts index df12887..d351b45 100644 --- a/src/composer.ts +++ b/src/composer.ts @@ -5,11 +5,12 @@ // Adapted from spike-html-apps-components (10dde51): src/composer.ts, on @standards-lab/web-foundation. // See docs/internals.md -import { html, LitElement, type PropertyDeclarations } from "lit"; +import { html, LitElement, nothing, type PropertyDeclarations } from "lit"; import { live } from "lit/directives/live.js"; import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define, emit } from "@standards-lab/web-foundation/dom.js"; import styles from "./composer.css" with { type: "css" }; @@ -43,7 +44,7 @@ export type StopDetail = Record; * field, where the reader writes next. */ export class Composer extends LitElement { - static styles = [reset, elements, styles]; + static styles = [reset, elements, utilities, styles]; static properties = { value: { type: String }, @@ -105,7 +106,7 @@ export class Composer extends LitElement { render() { const busy = this.busy; - return html` + return html`
        `; } diff --git a/src/document-list.css b/src/document-list.css index 202e02d..b9fa577 100644 --- a/src/document-list.css +++ b/src/document-list.css @@ -2,8 +2,9 @@ /* * The document list's shadow-root sheet: the status line, on the pagination's summary line or - * a line of its own, and the list of entries. - * Unlayered, above the foundation's reset and elements sheets; it reads only the baseline tokens. + * a line of its own, the utilities' status line, and the list of entries, a bare list. + * Unlayered, above the foundation's reset, elements, and utilities sheets; it reads only the + * baseline tokens. * See docs/layout.md */ @@ -17,18 +18,10 @@ .status[slot="status"] { display: inline; } -.status[slot="status"] .label { - white-space: nowrap; -} .status[slot="status"] .label::before { content: "·" / ""; margin-inline: 0.5ch; } -.status:not([slot]) { - min-block-size: 1lh; - font-size: var(--text-s); - color: var(--fg-2); -} .status .empty { color: var(--fg-3); } @@ -37,9 +30,4 @@ } .documents { margin: 0; - padding: 0; - list-style: none; -} -.documents > li { - margin: 0; } diff --git a/src/document-list.ts b/src/document-list.ts index 5a23b00..a09e788 100644 --- a/src/document-list.ts +++ b/src/document-list.ts @@ -12,6 +12,7 @@ import { repeat } from "lit/directives/repeat.js"; import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define } from "@standards-lab/web-foundation/dom.js"; import "./entry.ts"; import type { FileItem, StatusTone } from "./entry.ts"; @@ -73,7 +74,7 @@ function entryItem(item: DocumentItem): FileItem { * busy, so a page change doesn't empty and refill the list; an error lists none. */ export class DocumentList extends LitElement { - static styles = [reset, elements, styles]; + static styles = [reset, elements, utilities, styles]; static properties = { items: { attribute: false }, @@ -118,15 +119,16 @@ export class DocumentList extends LitElement { this.disabled = false; } - #status(documents: readonly DocumentItem[]) { + #status(documents: readonly DocumentItem[], joins: boolean) { + const label = joins ? "label text-nowrap" : "label"; switch (this.state) { case "loading": - return html`Loading documents…`; + return html`Loading documents…`; case "error": - return html`Couldn't load the documents. + return html`Couldn't load the documents. ${this.message ? html`${this.message}` : nothing}`; } - return documents.length ? nothing : html`No documents.`; + return documents.length ? nothing : html`No documents.`; } #entry(item: DocumentItem) { @@ -151,10 +153,10 @@ export class DocumentList extends LitElement { .pageSizes=${this.pageSizes} .disabled=${this.disabled} > -

        ${this.#status(documents)}

        +

        ${this.#status(documents, joins)}

        ${ documents.length - ? html`
          + ? html`
            ${repeat( documents, (item) => item.id, diff --git a/src/drawer.css b/src/drawer.css index 2dc1927..54b6ee0 100644 --- a/src/drawer.css +++ b/src/drawer.css @@ -2,8 +2,10 @@ /* * The drawer's shadow-root sheet: the docked aside's frame and the modal dialog covering the - * viewport, each a header over a scrolling body, and the dialog's slide. - * Unlayered, above the foundation's reset and elements sheets; it reads only the baseline tokens. + * viewport, each a dialog header over a scrolling body, and the dialog's slide, in the motion + * sheet's --duration-m. + * Unlayered, above the foundation's reset, elements, utilities, glyph-button, dialog, and motion + * sheets; it reads only the baseline tokens. * See docs/layout.md */ @@ -44,20 +46,13 @@ dialog[open] { translate: 0 0; } header { - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--space-s); + margin-block-end: 0; padding: var(--space-s); border-block-end: var(--line-s) solid var(--border); } h2 { - margin: 0; font-size: var(--text-l); } -h2[tabindex="-1"]:focus { - outline: none; -} .body { flex: 1 1 auto; min-block-size: 0; @@ -66,20 +61,12 @@ h2[tabindex="-1"]:focus { padding: var(--space-s); scroll-padding: var(--space-s); } -.hidden { - position: absolute; - inline-size: 1px; - block-size: 1px; - overflow: hidden; - clip-path: inset(50%); - white-space: nowrap; -} @media (prefers-reduced-motion: no-preference) { dialog { transition: - translate 200ms ease-out, - overlay 200ms allow-discrete, - display 200ms allow-discrete; + translate var(--duration-m) ease-out, + overlay var(--duration-m) allow-discrete, + display var(--duration-m) allow-discrete; } @starting-style { dialog[open] { diff --git a/src/drawer.ts b/src/drawer.ts index 86942c8..7774a96 100644 --- a/src/drawer.ts +++ b/src/drawer.ts @@ -1,22 +1,32 @@ // The drawer, Lit with a shadow root: docked inline as a complementary landmark, an aside, in a // wide layout, and a modal dialog covering the viewport, sliding in from the inline-start edge, in -// a narrow one. Both wrappers hold the same header, the label as the one heading that names them, -// over a body holding the slot. The mode is the viewport's, by a media query on `dock`; a switch -// swaps only the shadow root's wrapper and its slot, so the slotted content, the host's own -// children, is never moved, disconnected, or re-created. +// a narrow one, or at every width with `modal`. Both wrappers hold the same header, the label as +// the one heading that names them, over a body holding the slot. The mode is the viewport's, by a +// media query on `dock`, unless `modal` is set; a switch swaps only the shadow root's wrapper and +// its slot, so the slotted content, the host's own children, is never moved, disconnected, or +// re-created. // Adapted from spike-html-apps-components (10dde51): src/drawer.ts, on @standards-lab/web-foundation. +// Adapted from spike-html-hosting-components (9fa5850): src/drawer.ts, its Close a glyph button showing web-icons' x-16. // See docs/internals.md import { html, LitElement, type PropertyDeclarations, type PropertyValues } from "lit"; +import { unsafeHTML } from "lit/directives/unsafe-html.js"; import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import dialogSheet from "@standards-lab/web-foundation/dialog.css" with { type: "css" }; +import glyphButton from "@standards-lab/web-foundation/glyph-button.css" with { type: "css" }; +import motion from "@standards-lab/web-foundation/motion.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define, emit } from "@standards-lab/web-foundation/dom.js"; +import x from "@standards-lab/web-icons/octicon/x-16"; import styles from "./drawer.css" with { type: "css" }; /** The tag the element defines. */ export const tagName = "sl-drawer"; +const CLOSE = "Close"; + /** `open`'s detail: empty. */ export type OpenDetail = Record; @@ -36,16 +46,19 @@ export type CloseDetail = Record; * Below `dock` the drawer is closed until `show()`, `toggle()`, or `open` opens it, a * native dialog shown by `showModal()`: it covers the viewport edge to edge, sliding in from the * inline-start edge, the right in a right-to-left context, and the page behind it inert. Its - * header holds `label` as a visible `h2` that names the dialog, and a Close button whose accessible - * name adds the label, "Close Documents"; the button's visible text is the `close` slot's, "Close" - * by default, for a translation. As the dialog opens, focus moves to its heading, by the heading's - * `tabindex="-1"` and `autofocus`, not to the Close button; the heading, no control, shows no - * focus outline and is out of the Tab order, so Tab from it reaches the Close button. The header - * stays in view while the children scroll below it. The Close button, Escape, `close()`, - * `toggle()`, or `open` set false closes it, and the dialog returns focus to the element that held - * it when it opened. Under reduced motion it opens and closes at once. `open` in the markup, or - * set before the element is connected, opens the drawer as the page loads below `dock`, sending - * `open`, and is undone while docked, sending nothing. + * header holds `label` as a visible `h2` that names the dialog, and a Close button that shows + * web-icons' Octicons x-16 alone: its name is the `close` slot's text, "Close" by default, for a + * translation, then the label, "Close Documents", both visually hidden. It is a glyph button, laid + * out by the foundation's glyph-button.css, and shows its name on hover and keyboard focus in a + * hint popover, by `interestfor`, where the browser supports it, announced once as the name. As + * the dialog opens, focus moves to its heading, by the heading's `tabindex="-1"` and `autofocus`, + * not to the Close button, so the Close shows its hint only when tabbed to or hovered; the + * heading, no control, shows no focus outline and is out of the Tab order, so Tab from it reaches + * the Close button. The header stays in view while the children scroll below it. The Close + * button, Escape, `close()`, `toggle()`, or `open` set false closes it, and the dialog returns + * focus to the element that held it when it opened. Under reduced motion it opens and closes at + * once. `open` in the markup, or set before the element is connected, opens the drawer as the page + * loads below `dock`, sending `open`, and is undone while docked, sending nothing. * * `open` and `close` go out each time the modal drawer opens or closes, however it was asked, * never on a switch between the modes. A switch, as the viewport crosses `dock`, closes an open @@ -54,20 +67,26 @@ export type CloseDetail = Record; * unless `open` is set again before. `dock` is read in a media query, `(width < )`, where * rem and em are the initial font size's, so a viewport of exactly `dock` docks; a length the * query can't read never matches, so the drawer stays docked. + * `modal`, reflected, makes the drawer a modal dialog at every width, as below `dock`, and `dock` + * is ignored while it is set. Setting or removing `modal` is a switch too: it closes an open drawer + * silently, whether or not the mode changes. * Each mode renders only its own header, so the shadow tree holds one heading at a time. The mode * is the custom state `docked` or `drawer`, which a page may style. */ export class Drawer extends LitElement { - static styles = [reset, elements, styles]; + static styles = [reset, elements, utilities, glyphButton, dialogSheet, motion, styles]; static properties = { open: { type: Boolean, reflect: true }, + modal: { type: Boolean, reflect: true }, dock: { type: String }, label: { type: String }, } satisfies PropertyDeclarations; /** Whether the modal drawer is open; reflected to `open`, and always false while docked. */ declare open: boolean; + /** Whether the drawer is a modal dialog at every width, ignoring `dock`; reflected to `modal`. */ + declare modal: boolean; /** The width at which the drawer docks, and wider: a CSS length, read in a media query. */ declare dock: string; /** The visible heading of the docked aside and of the drawer, which names each. */ @@ -81,6 +100,7 @@ export class Drawer extends LitElement { constructor() { super(); this.open = false; + this.modal = false; this.dock = "48rem"; this.label = ""; } @@ -104,7 +124,7 @@ export class Drawer extends LitElement { this.#dialog?.close(); } - /** Opens the modal drawer; below `dock` only. */ + /** Opens the modal drawer; below `dock`, or at any width with `modal`, only. */ show(): void { if (this.#query) this.#change(); if (!this.#narrow || this.open) return; @@ -133,7 +153,7 @@ export class Drawer extends LitElement { } #change = (): void => { - const narrow = this.#query?.matches ?? false; + const narrow = this.modal || (this.#query?.matches ?? false); if (narrow === this.#narrow) return; const switched = this.#narrow !== null; this.#narrow = narrow; @@ -149,6 +169,14 @@ export class Drawer extends LitElement { protected override willUpdate(changed: PropertyValues): void { if (changed.has("dock") && this.#query) this.#watch(); + if (changed.has("modal") && this.#query) { + if (this.#modal) { + this.#modal = false; + this.open = false; + this.#dialog?.close(); + } + this.#change(); + } if (!this.#narrow) this.open = false; } @@ -178,19 +206,45 @@ export class Drawer extends LitElement { emit(this, "close", {}); } + #slotted = (): void => { + this.requestUpdate(); + }; + + #closeText(): string { + const assigned = [...this.children].filter((child) => child.slot === "close"); + if (assigned.length === 0) return CLOSE; + return assigned + .map((child) => child.textContent ?? "") + .join("") + .replace(/\s+/g, " ") + .trim(); + } + render() { if (!this.#narrow) { return html``; } return html` -
            +

            ${this.label}

            - +
            `; diff --git a/src/entry.css b/src/entry.css index 13148f5..3cb89da 100644 --- a/src/entry.css +++ b/src/entry.css @@ -1,9 +1,10 @@ /* From spike-html-apps-components (10dde51): src/entry.css. */ /* - * The entry's shadow-root sheet: the button's head of the name and status, its meta line, the - * status tones, and the selected frame. - * Unlayered, above the foundation's reset and elements sheets; it reads only the baseline tokens. + * The entry's shadow-root sheet: the button's head of the name and status on the utilities' head + * row, its meta line, the status tones, and the selected frame. + * Unlayered, above the foundation's reset, elements, and utilities sheets; it reads only the + * baseline tokens. * See docs/layout.md */ @@ -21,32 +22,16 @@ text-align: start; } :host([selected]) .entry:not(:focus-visible) { - border-color: var(--accent-color, var(--magenta)); - box-shadow: inset 0 0 0 var(--line-s) var(--accent-color, var(--magenta)); -} -.head { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: var(--space-3xs) var(--space-xs); - min-inline-size: 0; + border-color: var(--color-accent, var(--magenta)); + box-shadow: inset 0 0 0 var(--line-s) var(--color-accent, var(--magenta)); } .name { - flex: 1 1 16ch; - max-inline-size: max-content; - min-inline-size: 0; font-size: var(--text-m); font-weight: 600; overflow-wrap: anywhere; } -.status { - margin-inline-start: auto; - font-size: var(--text-xs); - color: var(--fg-2); - white-space: nowrap; -} :host([status-tone="active"]) .status { - color: var(--accent-color, var(--magenta)); + color: var(--color-accent, var(--magenta)); } :host([status-tone="complete"]) .status { color: var(--green); @@ -57,31 +42,17 @@ :host([status-tone="failed"]) .status { color: var(--red); } -.kind { - position: absolute; - inline-size: 1px; - block-size: 1px; - overflow: hidden; - clip-path: inset(50%); - white-space: nowrap; -} .meta { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--space-3xs) var(--space-xs); min-inline-size: 0; - font-size: var(--text-s); - color: var(--fg-2); } .type { min-inline-size: 0; overflow-wrap: break-word; } -.size, -time > .clock { - white-space: nowrap; -} time { min-inline-size: 0; overflow-wrap: break-word; diff --git a/src/entry.ts b/src/entry.ts index 6a9aa7a..64b8732 100644 --- a/src/entry.ts +++ b/src/entry.ts @@ -6,6 +6,7 @@ import { html, LitElement, nothing, type PropertyDeclarations } from "lit"; import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define, emit } from "@standards-lab/web-foundation/dom.js"; import { formatBytes, formatDate, formatDateTime } from "@standards-lab/web-foundation/format.js"; import styles from "./entry.css" with { type: "css" }; @@ -67,7 +68,7 @@ function renderTime(updatedAt: string) { return html``; @@ -87,7 +88,7 @@ function renderTime(updatedAt: string) { * consumer's reading of the status, not the item's data, so the item keeps its API's shape. */ export class Entry extends LitElement { - static styles = [reset, elements, styles]; + static styles = [reset, elements, utilities, styles]; static properties = { item: { attribute: false }, @@ -121,15 +122,15 @@ export class Entry extends LitElement { const file = "content_type" in item ? item : null; return html` `; } @@ -203,10 +204,10 @@ export class SearchResults extends LitElement { const needle = needleOf(this.#answered); const answered = needle.join(""); const matches = this.state === "error" ? [] : (this.items ?? []); - return html`

            ${this.#status(query, answered, matches)}

            + return html`

            ${this.#status(query, answered, matches)}

            ${ matches.length - ? html`
              + ? html`
                ${repeat( matches, (match) => match.id, diff --git a/src/settings.css b/src/settings.css new file mode 100644 index 0000000..7831526 --- /dev/null +++ b/src/settings.css @@ -0,0 +1,95 @@ +/* Adapted from spike-html-hosting-components (9fa5850): src/settings.css, with the theme menu's rows and preview in it. */ +/* Adapted from web-foundation (309e6b9): src/theme-menu.css, its rows, preview, and buttons rules, unlayered, without the dialog's. */ +/* From spike-html-apps-foundation (07ba39a): src/theme-menu.css. */ +/* Adapted from spike-html-design (fe75220): modules/theme-menu.js. */ + +/* + * The settings' shadow-root sheet: a block host holding the theme and the keyboard sections, the + * keyboard's --space-m below the theme's. .theme-menu-body sets the preview beside the rows, + * sharing the width two to three, while the element is wide enough for both at their narrowest, + * and below them otherwise; .theme-menu-rows stacks the rows; .theme-menu-row is one ◀ value ▶ row, + * its legend leading, its value in the code font, its other radios and every radio box hidden + * visually, framed while a radio in it has visible focus; .theme-menu-preview is the card; + * .theme-menu-buttons lays out its buttons. + * Unlayered, above the foundation's reset, elements, meta, structure, and utilities sheets; it + * reads only the baseline tokens. + */ + +:host { + display: block; +} +section + section { + margin-block-start: var(--space-m); +} +.theme-menu-body { + display: flex; + flex-wrap: wrap; + gap: var(--space-s); + align-items: start; +} +.theme-menu-rows { + display: grid; + flex: 2 1 0; + gap: var(--space-3xs); +} +.theme-menu-row { + position: relative; + display: flex; + align-items: center; + gap: var(--space-2xs); + margin: 0; + padding: var(--space-3xs) var(--space-2xs); + border: var(--line-s) solid transparent; + border-radius: var(--radius-sm); +} +.theme-menu-row:has(:focus-visible) { + border-color: var(--border-2); + background-color: var(--bg-2); +} +.theme-menu-row > legend { + float: inline-start; + flex: 1; + padding: 0; +} +.theme-menu-row > [data-step] { + padding-inline: var(--space-3xs); + color: var(--fg-3); + cursor: pointer; + user-select: none; +} +.theme-menu-row > [data-step]:hover { + color: var(--fg); +} +.theme-menu-row > label { + min-inline-size: 11ch; + font-family: var(--font-code); + text-align: center; +} +.theme-menu-row input, +.theme-menu-row > label:not(:has(:checked)) { + position: absolute; + inline-size: 1px; + block-size: 1px; + margin: 0; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} +.theme-menu-preview { + display: grid; + flex: 3 1 0; + gap: var(--space-xs); + padding: var(--space-s); + border: var(--line-s) solid var(--border); + border-radius: var(--radius-md); + background-color: var(--bg); + color: var(--fg); +} +.theme-menu-preview > * { + margin-block: 0; +} +.theme-menu-buttons { + display: flex; + flex-wrap: wrap; + gap: var(--space-2xs); +} diff --git a/src/settings.ts b/src/settings.ts new file mode 100644 index 0000000..bb42ce0 --- /dev/null +++ b/src/settings.ts @@ -0,0 +1,330 @@ +// The settings, Lit with a shadow root: the reader's theme, its color, scheme, space, and type, in +// rows beside an inert preview card, and the keys module's character-key switch and wait between +// presses, for a Settings dialog that holds the element. Every change applies and is stored at +// once, with no Save and no Cancel, and fires a bubbling, composed change at the host. It binds no +// page key. +// Adapted from spike-html-hosting-components (9fa5850): src/settings.ts, on @standards-lab/web-foundation, its theme layout in its own sheet. +// Adapted from spike-html-apps-foundation (618cb83): src/theme-menu.ts, its rows, steppers, preview, and moves, without Save, Cancel, and the snapshot; and src/keys-help.ts, its settings form. + +import { html, LitElement, nothing, type PropertyDeclarations } from "lit"; +import { live } from "lit/directives/live.js"; + +import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; +import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import meta from "@standards-lab/web-foundation/meta.css" with { type: "css" }; +import structure from "@standards-lab/web-foundation/structure.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; +import { define } from "@standards-lab/web-foundation/dom.js"; +import { + changeSettings, + settings, + WAITS, + type Settings as KeySettings, +} from "@standards-lab/web-foundation/keys.js"; +import { + apply, + ATTRIBUTES, + save, + SCHEMES, + type Choice, + type Key, +} from "@standards-lab/web-foundation/preferences.js"; +import { DEFAULTS, FACETS, profiles } from "@standards-lab/web-foundation/registry.js"; +import styles from "./settings.css" with { type: "css" }; + +/** The tag the element defines. */ +export const tagName = "sl-settings"; + +/** The character-key switch's label. */ +export const SWITCH_LABEL = + "Character-key shortcuts (combinations with Control, Alt, or Meta stay on)"; + +/** The wait select's label. */ +export const WAIT_LABEL = "Wait between presses"; + +const SECTIONS: readonly (readonly [Key, string])[] = [ + ["color", "Color"], + ["scheme", "Scheme"], + ["space", "Space"], + ["type", "Type"], +]; + +const PREVIEW = html`

                Nightly build

                +

                + Read the release notes, run mise run check, or press + Ctrl K to search. +

                +

                + +

                +
                + +
                + + + + + + + + + + + + + + + + + + + + + + + + + +
                RunStatusTime
                1204passed2m 14s
                1205failed48s
                1206queued—
                `; + +function options(key: Key): string[] { + return key === "scheme" ? [...SCHEMES] : profiles(key); +} + +function current(): Choice { + const root = document.documentElement; + const choice = { scheme: root.getAttribute(ATTRIBUTES.scheme) ?? SCHEMES[0] } as Choice; + for (const facet of FACETS) { + choice[facet] = root.getAttribute(ATTRIBUTES[facet]) ?? DEFAULTS[facet]; + } + return choice; +} + +function rowOf(node: EventTarget | null): HTMLFieldSetElement | null { + return node instanceof Element ? node.closest(".theme-menu-row") : null; +} + +const shown = (ms: number): string => `${ms / 1000} s`; + +/** + * The reader's settings, for a Settings dialog that holds the element. The theme is a row each + * for color, scheme, space, and type, each a radio group drawn as ◀ value ▶, its other radios + * hidden visually and kept in the group, its arrows spans hidden from assistive technology that + * take no focus; a click on an arrow steps the row. On a row, H and L step it, wrapping, J and K + * or the down and up arrows move to the next and the previous row, stopping at the ends, and the + * left and right arrows cycle its radios natively; none of these keys leaves the rows. Beside the + * rows, an inert preview card shows the theme on a heading, a link, code, kbd, buttons, a field, + * and a striped table. Each step applies the choice to the page's root and stores it through the + * foundation's preferences module. The keyboard settings are the character-key switch and the + * wait between presses, one of `WAITS`, each stored through the keys module's `changeSettings`; a + * stored wait not among `WAITS` shows as an option that clears it. Every change fires a bubbling, + * composed `change` at the host. It reads both settings again as it connects, as its dialog + * opens, at each `change` in the document, and at each `storage` event; as the dialog opens it + * focuses the first row's checked radio, unless an element in the dialog has `autofocus`. + */ +export class Settings extends LitElement { + static styles = [reset, elements, meta, structure, utilities, styles]; + + static properties = { + _choice: { state: true }, + _keys: { state: true }, + } satisfies PropertyDeclarations; + + declare _choice: Choice; + declare _keys: KeySettings; + + #dialog: HTMLDialogElement | null = null; + + constructor() { + super(); + this._choice = current(); + this._keys = settings(); + } + + connectedCallback(): void { + super.connectedCallback(); + this.#dialog = this.closest("dialog"); + this.#dialog?.addEventListener("toggle", this.#toggled); + document.addEventListener("change", this.#refresh); + addEventListener("storage", this.#refresh); + this.#refresh(); + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + this.#dialog?.removeEventListener("toggle", this.#toggled); + this.#dialog = null; + document.removeEventListener("change", this.#refresh); + removeEventListener("storage", this.#refresh); + } + + render() { + const { enabled, wait } = this._keys; + const odd = !WAITS.some((ms) => ms === wait); + return html` +
                +

                Theme

                +
                +
                + ${SECTIONS.map(([key, legend]) => this.#row(key, legend))} +
                +
                ${PREVIEW}
                +
                +
                +
                +

                Keyboard

                + +

                + +

                +
                + `; + } + + #row(key: Key, legend: string) { + const value = this._choice[key]; + return html` +
                + ${legend} + + ${options(key).map( + (option) => + html``, + )} + +
                + `; + } + + #refresh = (): void => { + this._choice = current(); + this._keys = settings(); + }; + + #toggled = async (event: Event): Promise => { + if ((event as ToggleEvent).newState !== "open") return; + this.#refresh(); + if (this.#dialog?.querySelector("[autofocus]")) return; + await this.updateComplete; + this.renderRoot.querySelector(".theme-menu-row :checked")?.focus(); + }; + + #changed(): void { + this.dispatchEvent(new Event("change", { bubbles: true, composed: true })); + } + + async #choose(key: Key, value: string, focus: boolean): Promise { + const choice = { ...this._choice, [key]: value }; + this._choice = choice; + apply(choice); + save(choice); + this.#changed(); + if (!focus) return; + await this.updateComplete; + this.renderRoot.querySelector(`[data-section="${key}"] :checked`)?.focus(); + } + + #step(row: HTMLFieldSetElement, delta: number): void { + const key = row.dataset.section as Key; + const names = options(key); + if (names.length === 0) return; + const at = names.indexOf(this._choice[key]); + void this.#choose(key, names[(at + delta + names.length) % names.length], true); + } + + #move(row: HTMLFieldSetElement, delta: number): void { + const rows = [...this.renderRoot.querySelectorAll(".theme-menu-row")]; + const to = Math.min(Math.max(rows.indexOf(row) + delta, 0), rows.length - 1); + rows[to].querySelector(":checked")?.focus(); + } + + #picked = (event: Event): void => { + const radio = event.target as HTMLInputElement; + const row = rowOf(radio); + if (row) void this.#choose(row.dataset.section as Key, radio.value, false); + }; + + #clicked = (event: Event): void => { + const arrow = event.target instanceof Element ? event.target.closest("[data-step]") : null; + const row = rowOf(arrow); + if (arrow instanceof HTMLElement && row) this.#step(row, Number(arrow.dataset.step)); + }; + + #onkey = (event: KeyboardEvent): void => { + const row = rowOf(event.target); + if (!row || event.ctrlKey || event.altKey || event.metaKey) return; + switch (event.key) { + case "ArrowUp": + case "k": + this.#move(row, -1); + break; + case "ArrowDown": + case "j": + this.#move(row, 1); + break; + case "ArrowLeft": + case "ArrowRight": + event.stopPropagation(); + return; + case "h": + case "l": + this.#step(row, event.key === "h" ? -1 : 1); + break; + default: + return; + } + event.preventDefault(); + event.stopPropagation(); + }; + + #switched = (event: Event): void => { + this._keys = changeSettings({ enabled: (event.target as HTMLInputElement).checked }); + this.#changed(); + }; + + #waited = (event: Event): void => { + const { value } = event.target as HTMLSelectElement; + this._keys = changeSettings({ wait: value === "" ? null : Number(value) }); + this.#changed(); + }; +} + +define(tagName, Settings); + +declare global { + interface HTMLElementTagNameMap { + "sl-settings": Settings; + } +} diff --git a/src/shortcuts.css b/src/shortcuts.css new file mode 100644 index 0000000..74b0107 --- /dev/null +++ b/src/shortcuts.css @@ -0,0 +1,24 @@ +/* Adapted from spike-html-hosting-components (9fa5850): src/shortcuts.css, its note's type the utilities' text-quiet-s. */ + +/* + * The shortcuts list's shadow-root sheet: a block host as wide as its table, a row turned off by + * the reader's setting in the muted text tier, and the note below the table, wrapping within the + * table's width and counting as sixteen --space-base steps toward the element's intrinsic width. + * Unlayered, above the foundation's reset, elements, and utilities sheets; it reads only the + * baseline tokens. + */ + +:host { + display: block; +} +tr.off td:first-child { + color: var(--fg-2); +} +tr.off kbd { + --kbd-color: var(--fg-2); +} +.note { + margin-block: var(--space-s) 0; + contain: inline-size; + contain-intrinsic-inline-size: calc(var(--space-2xl) * 4); +} diff --git a/src/shortcuts.ts b/src/shortcuts.ts new file mode 100644 index 0000000..704c7c5 --- /dev/null +++ b/src/shortcuts.ts @@ -0,0 +1,155 @@ +// The shortcuts list, Lit with a shadow root: the page's keyboard shortcuts, as the foundation's +// keys module lists them for the dialog that holds the element, in a plain-text table of each +// binding's keys and its action, with the screen-reader note after it. It runs no binding, binds +// no key, holds no setting, and renders no [data-keys-list]. +// Adapted from spike-html-hosting-components (9fa5850): src/shortcuts.ts, on @standards-lab/web-foundation, its note in the utilities' quiet type. + +import { html, LitElement, nothing, type PropertyDeclarations, type TemplateResult } from "lit"; + +import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; +import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; +import { define } from "@standards-lab/web-foundation/dom.js"; +import { bindings, type Listed } from "@standards-lab/web-foundation/keys.js"; +import { labels, type Sequence } from "@standards-lab/web-foundation/keys-grammar.js"; +import styles from "./shortcuts.css" with { type: "css" }; + +/** The tag the element defines. */ +export const tagName = "sl-shortcuts"; + +/** The screen-reader note after the table: how to pass the next key through a screen reader. */ +export const NOTE = + "Screen readers: a screen reader may take a key before the page does. To pass the next key " + + "through, press NVDA+F2 in NVDA, JAWS+3 in JAWS, Narrator+3 in Narrator, or VO+Tab in VoiceOver."; + +/** The word after the keys of a row the reader's setting turns off. */ +export const OFF = "off"; + +function textOf(el: Element): string { + const copy = el.cloneNode(true) as Element; + for (const kbd of copy.querySelectorAll("kbd")) { + const joiner = kbd.nextSibling; + const after = joiner?.nextSibling; + if ( + joiner?.nodeType === Node.TEXT_NODE && + after instanceof Element && + after.localName === "kbd" + ) { + joiner.remove(); + } + kbd.remove(); + } + return (copy.textContent ?? "").replace(/\s+/g, " ").trim(); +} + +function labelOf({ element, label, keys }: Listed): string { + if (!element) return label ?? ""; + const aria = element.getAttribute("aria-label")?.trim(); + if (aria) return aria; + const text = textOf(element); + if (text) return text; + const field = (element as Partial>).labels?.[0]; + return (field && textOf(field)) || keys; +} + +function keysOf(sequences: Sequence[]): (string | TemplateResult)[] { + const parts: (string | TemplateResult)[] = []; + sequences.forEach((sequence, a) => { + if (a > 0) parts.push(" or "); + labels(sequence).forEach((press, p) => { + if (p > 0) parts.push(" then "); + press.forEach((name, k) => { + if (k > 0) parts.push("+"); + parts.push(html`${name}`); + }); + }); + }); + return parts; +} + +/** + * Lists the page's keyboard shortcuts, for a help dialog: exactly the bindings the foundation's + * keys module's `bindings(dialog)` gives for the dialog that holds the element, or + * `bindings(null)` outside one, in its order. Each row's keys are the binding's sequences, each key + * in a `kbd` as the keys grammar labels it, "+" within a press, " then " between presses, " or " + * between sequences; its action is the binding's registered label or its element's name, as plain + * text. A row the reader's setting turns off carries the word "off" after its keys, shown and + * read, and the class `off`. Nothing in it takes focus. The screen-reader note follows the table. + * It reads the bindings again as it connects, as its dialog opens, and at each `change` in the + * document, as a settings form sends, and each `storage` event, as another tab's change sends. + */ +export class Shortcuts extends LitElement { + static styles = [reset, elements, utilities, styles]; + + static properties = { + _rows: { state: true }, + } satisfies PropertyDeclarations; + + declare _rows: Listed[]; + + #dialog: HTMLDialogElement | null = null; + + constructor() { + super(); + this._rows = []; + } + + connectedCallback(): void { + super.connectedCallback(); + this.#dialog = this.closest("dialog"); + this.#dialog?.addEventListener("beforetoggle", this.#toggled); + document.addEventListener("change", this.#refresh); + addEventListener("storage", this.#refresh); + this.#refresh(); + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + this.#dialog?.removeEventListener("beforetoggle", this.#toggled); + this.#dialog = null; + document.removeEventListener("change", this.#refresh); + removeEventListener("storage", this.#refresh); + } + + render() { + return html` + + + + + + + + + ${this._rows.map( + (binding) => html` + + + + + `, + )} + +
                KeysAction
                + ${keysOf(binding.sequences)}${binding.off ? html` ${OFF}` : nothing} + ${labelOf(binding)}
                +

                ${NOTE}

                + `; + } + + #toggled = (event: Event): void => { + if ((event as ToggleEvent).newState === "open") this.#refresh(); + }; + + #refresh = (): void => { + this._rows = bindings(this.#dialog); + }; +} + +define(tagName, Shortcuts); + +declare global { + interface HTMLElementTagNameMap { + "sl-shortcuts": Shortcuts; + } +} diff --git a/src/stage-timeline.css b/src/stage-timeline.css index 5bdcf0c..27f942f 100644 --- a/src/stage-timeline.css +++ b/src/stage-timeline.css @@ -1,9 +1,11 @@ /* From spike-html-apps-components (10dde51): src/stage-timeline.css. */ /* - * The stage timeline's shadow-root sheet: the list of steps, each a marker, a connector to the - * next, a name, a detail line of the state's label and time, and a failed stage's reason. - * Unlayered, above the foundation's reset and elements sheets; it reads only the baseline tokens. + * The stage timeline's shadow-root sheet: the bare list of steps, each a marker, with the active + * one's ring, which the motion sheet's ring runs, a connector to the next, a name, a detail line of + * the state's label and time, each on the utilities' alternatives, and a failed stage's reason. + * Unlayered, above the foundation's reset, elements, utilities, and motion sheets; it reads only + * the baseline tokens. * See docs/layout.md */ @@ -12,15 +14,12 @@ } .stages { margin: 0; - padding: 0; - list-style: none; } .stage { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto auto var(--space-s); column-gap: var(--space-xs); - margin: 0; } .stage:last-child { grid-template-rows: auto auto auto; @@ -63,9 +62,9 @@ stroke-linejoin: round; } .active .marker { - border-color: var(--accent-color, var(--magenta)); - background-color: color-mix(in srgb, var(--accent-color, var(--magenta)) 12%, transparent); - color: var(--accent-color, var(--magenta)); + border-color: var(--color-accent, var(--magenta)); + background-color: color-mix(in srgb, var(--color-accent, var(--magenta)) 12%, transparent); + color: var(--color-accent, var(--magenta)); font-weight: 600; } .complete .marker { @@ -79,23 +78,11 @@ color: var(--bg); } @media (prefers-reduced-motion: no-preference) { - .active .marker::after { - content: ""; + .marker > .ring { position: absolute; inset: calc(-1 * var(--line-m)); - border: var(--line-m) solid var(--accent-color, var(--magenta)); + border: var(--line-m) solid var(--color-accent, var(--magenta)); border-radius: var(--radius-full); - animation: ring 1.6s ease-out infinite; - } -} -@keyframes ring { - from { - opacity: 0.6; - transform: scale(1); - } - to { - opacity: 0; - transform: scale(1.6); } } .name { @@ -115,26 +102,16 @@ flex-wrap: wrap; align-items: baseline; gap: 0 var(--space-xs); - font-size: var(--text-s); - color: var(--fg-2); } .slot { - display: inline-grid; justify-items: start; } -.slot > * { - grid-area: 1 / 1; -} -.slot > .hold { - visibility: hidden; -} .label { font-family: var(--font-ui); font-weight: 600; - white-space: nowrap; } .active .label { - color: var(--accent-color, var(--magenta)); + color: var(--color-accent, var(--magenta)); } .complete .label { color: var(--green); @@ -142,15 +119,9 @@ .failed .label { color: var(--red); } -.when { - white-space: nowrap; - font-variant-numeric: tabular-nums; -} .reason { grid-column: 2; grid-row: 3; contain: inline-size; - font-size: var(--text-s); - color: var(--fg-2); overflow-wrap: anywhere; } diff --git a/src/stage-timeline.ts b/src/stage-timeline.ts index dbdea62..b951896 100644 --- a/src/stage-timeline.ts +++ b/src/stage-timeline.ts @@ -10,6 +10,8 @@ import { repeat } from "lit/directives/repeat.js"; import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import motion from "@standards-lab/web-foundation/motion.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define } from "@standards-lab/web-foundation/dom.js"; import { formatDateTime } from "@standards-lab/web-foundation/format.js"; import styles from "./stage-timeline.css" with { type: "css" }; @@ -72,7 +74,7 @@ function timeOf(stage: TimelineStage): Date | null { * wrapping to the timeline's width and never widening it. */ export class StageTimeline extends LitElement { - static styles = [reset, elements, styles]; + static styles = [reset, elements, utilities, motion, styles]; static properties = { stages: { attribute: false }, @@ -93,7 +95,7 @@ export class StageTimeline extends LitElement { glyph === nothing ? html`${stage.position}` : html`${glyph}` - }` : nothing}`; } @@ -107,15 +109,15 @@ export class StageTimeline extends LitElement { > ${this.#marker(stage)} ${stage.name} - - + + ${(Object.keys(labels) as StageState[]).map((state) => state === stage.state ? html`${labels[state]}` : html``, )} - + ${ date ? html` - ${reason === null ? nothing : html`${reason}`} + ${reason === null ? nothing : html`${reason}`} `; } render() { const stages = [...(this.stages ?? [])].sort((a, b) => a.position - b.position); - return html`
                  + return html`
                    ${repeat( stages, (stage) => stage.name, diff --git a/src/upload-dropzone.css b/src/upload-dropzone.css index e304b1a..415ac45 100644 --- a/src/upload-dropzone.css +++ b/src/upload-dropzone.css @@ -1,9 +1,11 @@ /* From spike-html-apps-components (10dde51): src/upload-dropzone.css. */ /* - * The upload dropzone's shadow-root sheet: the dashed zone, its drag-over and disabled looks, - * and the list of uploads, each a name, a detail line, and a trailing label or cancel control. - * Unlayered, above the foundation's reset and elements sheets; it reads only the baseline tokens. + * The upload dropzone's shadow-root sheet: the dashed zone, its drag-over and disabled looks, the + * drag-over's change in the motion sheet's --duration-s, and the bare list of uploads, each a + * name, a detail line, and a trailing label or cancel control. + * Unlayered, above the foundation's reset, elements, utilities, and motion sheets; it reads only + * the baseline tokens. * See docs/layout.md */ @@ -24,15 +26,15 @@ } .zone.over { border-style: solid; - border-color: var(--interaction-color, var(--blue)); - background-color: color-mix(in srgb, var(--interaction-color, var(--blue)) 10%, transparent); + border-color: var(--color-primary, var(--blue)); + background-color: color-mix(in srgb, var(--color-primary, var(--blue)) 10%, transparent); color: var(--fg); } @media (prefers-reduced-motion: no-preference) { .zone { transition: - border-color 120ms ease-out, - background-color 120ms ease-out; + border-color var(--duration-s) ease-out, + background-color var(--duration-s) ease-out; } } :host([disabled]) .zone { @@ -41,8 +43,6 @@ } .uploads { margin: var(--space-s) 0 0; - padding: 0; - list-style: none; } .upload { display: grid; @@ -51,14 +51,13 @@ "name end" "detail end"; align-items: center; - gap: calc(var(--line-m) + 2px + var(--space-3xs)) var(--space-s); - margin: 0; + gap: calc(var(--focus-reach) + var(--space-3xs)) var(--space-s); padding-block: var(--space-2xs); } .upload::before { content: ""; grid-area: name; - min-block-size: calc(1lh + 2 * var(--space-3xs) + 2 * var(--line-s)); + min-block-size: var(--control-block-size); font-family: var(--font-ui); line-height: var(--leading-ui); } @@ -72,9 +71,6 @@ } .name { grid-area: name; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; } .end { grid-area: end; @@ -87,7 +83,6 @@ .state { font-size: var(--text-s); font-weight: 600; - white-space: nowrap; } .done .state { color: var(--green); @@ -105,8 +100,6 @@ align-items: center; gap: var(--space-xs); min-block-size: 1lh; - font-size: var(--text-s); - color: var(--fg-2); } progress { flex: 1 1 0; @@ -122,8 +115,6 @@ progress { } .bytes { flex: none; - white-space: nowrap; - font-variant-numeric: tabular-nums; } .sent { display: inline-block; diff --git a/src/upload-dropzone.ts b/src/upload-dropzone.ts index b0b1c40..d565b1d 100644 --- a/src/upload-dropzone.ts +++ b/src/upload-dropzone.ts @@ -10,6 +10,8 @@ import { repeat } from "lit/directives/repeat.js"; import elements from "@standards-lab/web-foundation/baseline/elements.css" with { type: "css" }; import reset from "@standards-lab/web-foundation/baseline/reset.css" with { type: "css" }; +import motion from "@standards-lab/web-foundation/motion.css" with { type: "css" }; +import utilities from "@standards-lab/web-foundation/utilities.css" with { type: "css" }; import { define, emit } from "@standards-lab/web-foundation/dom.js"; import { formatBytes } from "@standards-lab/web-foundation/format.js"; import styles from "./upload-dropzone.css" with { type: "css" }; @@ -66,7 +68,7 @@ function carriesFiles(event: DragEvent): boolean { * cancelled. */ export class UploadDropzone extends LitElement { - static styles = [reset, elements, styles]; + static styles = [reset, elements, utilities, motion, styles]; static properties = { uploads: { attribute: false }, @@ -155,18 +157,18 @@ export class UploadDropzone extends LitElement { > Cancel ` - : html`${finished[upload.state]}`; + : html`${finished[upload.state]}`; const sent = Math.min(Math.max(upload.sent, 0), upload.size); const detail = uploading ? html`${formatBytes(sent)} of ${size}` + >${formatBytes(sent)} of ${size}` : upload.state === "failed" && upload.message - ? html`${size}${upload.message}` - : html`${size}`; + ? html`${size}${upload.message}` + : html`${size}`; return html`
                  1. - ${upload.name} + ${upload.name} ${end} - ${detail} + ${detail}
                  2. `; } @@ -195,7 +197,7 @@ export class UploadDropzone extends LitElement {
    ${ uploads.length - ? html`
      + ? html`
        ${repeat( uploads, (upload) => upload.id, diff --git a/test/browser/components.test.ts b/test/browser/components.test.ts index 34d0056..b0d8523 100644 --- a/test/browser/components.test.ts +++ b/test/browser/components.test.ts @@ -68,6 +68,8 @@ describe("components", { timeout: 60_000 }, () => { "sl-pagination", "sl-entry", "sl-status-badge", + "sl-shortcuts", + "sl-settings", ]; const schemes = ["light", "dark"]; @@ -132,7 +134,7 @@ describe("components", { timeout: 60_000 }, () => { assert.match(verdict, /^ok: /, verdict); }); - test(`each component adopts the foundation's reset and elements sheets, then its own, ${run.name}`, async () => { + test(`each component adopts the foundation's reset and elements sheets, then the opt-in sheets it uses, then its own, ${run.name}`, async () => { const page = await open(run); try { const { adopted, label }: { adopted: Record; label: string } = @@ -142,6 +144,16 @@ describe("components", { timeout: 60_000 }, () => { const foundation = "@standards-lab/web-foundation"; const reset = await sheet(foundation + "/baseline/reset.css"); const elements = await sheet(foundation + "/baseline/elements.css"); + const named = new Map([ + [reset, "reset"], + [elements, "elements"], + [await sheet(foundation + "/meta.css"), "meta"], + [await sheet(foundation + "/structure.css"), "structure"], + [await sheet(foundation + "/utilities.css"), "utilities"], + [await sheet(foundation + "/glyph-button.css"), "glyph-button"], + [await sheet(foundation + "/dialog.css"), "dialog"], + [await sheet(foundation + "/motion.css"), "motion"], + ]); const components = [ ["sl-drawer", "drawer", "drawer.css"], ["sl-document-list", "document-list", "document-list.css"], @@ -155,6 +167,8 @@ describe("components", { timeout: 60_000 }, () => { ["sl-pagination", "pagination", "pagination.css"], ["sl-entry", "entry", "entry.css"], ["sl-status-badge", "status-badge", "status-badge.css"], + ["sl-shortcuts", "shortcuts", "shortcuts.css"], + ["sl-settings", "settings", "settings.css"], ]; const adopted = {}; for (const [tag, module, own] of components) { @@ -163,15 +177,24 @@ describe("components", { timeout: 60_000 }, () => { const element = document.body.appendChild(document.createElement(tag)); await element.updateComplete; adopted[tag] = element.shadowRoot.adoptedStyleSheets.map((s) => - s === reset ? "reset" : s === elements ? "elements" : s === ownSheet ? "own" : "other"); + s === ownSheet ? "own" : named.get(s) ?? "other"); } const badge = document.querySelector("sl-status-badge"); badge.label = "Draft"; await badge.updateComplete; return { adopted, label: badge.shadowRoot.querySelector("button").textContent }; })()`); + const base = ["reset", "elements"]; + const expected: Record = { + "sl-drawer": [...base, "utilities", "glyph-button", "dialog", "motion", "own"], + "sl-stage-timeline": [...base, "utilities", "motion", "own"], + "sl-upload-dropzone": [...base, "utilities", "motion", "own"], + "sl-chat-thread": [...base, "utilities", "motion", "own"], + "sl-status-badge": [...base, "own"], + "sl-settings": [...base, "meta", "structure", "utilities", "own"], + }; for (const tag of tags) { - assert.deepEqual(adopted[tag], ["reset", "elements", "own"], tag); + assert.deepEqual(adopted[tag], expected[tag] ?? [...base, "utilities", "own"], tag); } assert.equal(label, "Draft"); } finally { @@ -235,7 +258,7 @@ describe("components", { timeout: 60_000 }, () => { root.querySelector("button").click(); const meta = root.querySelector(".meta"); return { - parts: [...meta.children].map((part) => part.className || part.localName), + parts: [...meta.children].map((part) => part.classList[0] ?? part.localName), meta: meta.textContent.replace(/\\s+/g, " ").trim(), opened, }; @@ -299,7 +322,7 @@ describe("components", { timeout: 60_000 }, () => { byAttribute.item = { id: "d-attr", name: "designs", status: "failed", updated_at: "2026-10-12T16:41:07Z" }; main.append(byAttribute); } - ${hook ? `main.style.setProperty("--accent-color", "rgb(1, 2, 3)");` : ""} + ${hook ? `main.style.setProperty("--color-accent", "rgb(1, 2, 3)");` : ""} const entries = [...main.querySelectorAll("sl-entry")]; await Promise.all(entries.map((entry) => entry.updateComplete)); const root = entries[0].shadowRoot; @@ -311,7 +334,7 @@ describe("components", { timeout: 60_000 }, () => { return resolved; }; const hues = { - accent: resolve("var(--accent-color, var(--magenta))"), + accent: resolve("var(--color-accent, var(--magenta))"), green: resolve("var(--green)"), orange: resolve("var(--orange)"), red: resolve("var(--red)"), @@ -328,7 +351,7 @@ describe("components", { timeout: 60_000 }, () => { }; })()`); for (const hook of [false, true]) { - const where = hook ? "--accent-color set" : "at the accent hook's fallback"; + const where = hook ? "--color-accent set" : "at the accent hook's fallback"; const shown: { distinct: boolean; entries: unknown[][] } = await read(hook); assert.ok(shown.distinct, `${where}: the hues differ`); assert.deepEqual( @@ -359,7 +382,7 @@ describe("components", { timeout: 60_000 }, () => { tag: string; width: number; height: number; - look: { color: string; font: string; padding: number }; + look: { color: string; font: string; body: string; padding: number }; } test(`each component renders under each of the ${profiles.length} profile combinations`, async () => { @@ -373,8 +396,10 @@ describe("components", { timeout: 60_000 }, () => { await page.evaluate(`(async () => { const registry = await import("@standards-lab/web-foundation/registry.js"); const { directories, files } = await import("/demo/documents.js"); - await Promise.all(["drawer", "document-list", "search-results", "event-log", "stage-timeline", "upload-dropzone", "composer", "chat-thread", "artifact-viewer", "pagination", "entry", "status-badge"].map( + await Promise.all(["drawer", "document-list", "search-results", "event-log", "stage-timeline", "upload-dropzone", "composer", "chat-thread", "artifact-viewer", "pagination", "entry", "status-badge", "shortcuts", "settings"].map( (module) => import("/dist/" + module + ".js"))); + const keys = await import("@standards-lab/web-foundation/keys.js"); + keys.register("Alt+n", "New note", () => {}); const components = { "sl-drawer": () => { const drawer = Object.assign(document.createElement("sl-drawer"), { label: "Documents" }); @@ -440,6 +465,8 @@ describe("components", { timeout: 60_000 }, () => { Object.assign(document.createElement("sl-entry"), { item: files.items[0] }), "sl-status-badge": () => Object.assign(document.createElement("sl-status-badge"), { label: "Draft" }), + "sl-shortcuts": () => document.createElement("sl-shortcuts"), + "sl-settings": () => document.createElement("sl-settings"), }; const defaults = ${JSON.stringify(defaults)}; const attributes = { color: "data-palette", space: "data-space", type: "data-type", scheme: "data-scheme" }; @@ -459,10 +486,12 @@ describe("components", { timeout: 60_000 }, () => { const thread = tag === "sl-chat-thread"; const timeline = tag === "sl-stage-timeline"; const log = tag === "sl-event-log"; + const shortcuts = tag === "sl-shortcuts"; + const settings = tag === "sl-settings"; const style = getComputedStyle(entries.length ? entries[0].shadowRoot.querySelector("button") : element.shadowRoot.querySelector( - drawer ? "aside" : viewer ? ".body > *" : thread ? ".user > .message" : timeline ? ".complete > .marker" : log ? ".events" : "button")); + drawer ? "aside" : viewer ? ".body > *" : thread ? ".user > .message" : timeline ? ".complete > .marker" : log ? ".events" : shortcuts ? "th" : settings ? ".theme-menu-preview" : "button")); const font = drawer ? getComputedStyle(element.querySelector("button")) : viewer @@ -473,10 +502,15 @@ describe("components", { timeout: 60_000 }, () => { ? getComputedStyle(element.shadowRoot.querySelector(".label")) : log ? getComputedStyle(element.shadowRoot.querySelector(".when")) - : style; + : shortcuts + ? getComputedStyle(element.shadowRoot.querySelector(".note")) + : settings + ? getComputedStyle(element.shadowRoot.querySelector(".theme-menu-preview button")) + : style; const look = { color: style.color + " on " + style.backgroundColor, font: font.fontFamily, + body: getComputedStyle(document.body).fontFamily, padding: timeline ? parseFloat(getComputedStyle(element.shadowRoot.querySelector(".stage")).columnGap) : drawer @@ -526,7 +560,13 @@ describe("components", { timeout: 60_000 }, () => { tag, (shown) => shown.scheme === scheme && shown.space === "compact", ); - assert.notEqual(sans.font, mono.font, `${tag}, ${scheme}: sans sets the font`); + if (tag === "sl-shortcuts") { + for (const look of [mono, sans]) { + assert.equal(look.font, look.body, `${tag}, ${scheme}: its note in the body font`); + } + } else { + assert.notEqual(sans.font, mono.font, `${tag}, ${scheme}: sans sets the font`); + } assert.ok( compact.padding < mono.padding, `${tag}, ${scheme}: compact pads ${compact.padding}, regular ${mono.padding}`, @@ -571,9 +611,13 @@ describe("components", { timeout: 60_000 }, () => { } const LINES = `(element) => { - const range = document.createRange(); - range.selectNodeContents(element); - const rects = [...range.getClientRects()].filter((rect) => rect.width > 0); + const texts = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + const rects = []; + for (let text = texts.nextNode(); text; text = texts.nextNode()) { + const range = document.createRange(); + range.selectNodeContents(text); + rects.push(...[...range.getClientRects()].filter((rect) => rect.width > 0)); + } return new Set(rects.map((rect) => Math.round(rect.top))).size; }`; const ENTRIES = `(section) => [...document.querySelectorAll(section + " sl-entry")] @@ -598,7 +642,7 @@ describe("components", { timeout: 60_000 }, () => { return { name: entry.item.name, sizes: { name: size(".name"), status: size(".status"), meta: size(".meta") }, - first: first.className || first.localName, + first: first.classList[0] ?? first.localName, starts: [rect(root.querySelector(".name")).left, rect(first).left], under: rect(first).top >= rect(root.querySelector(".name")).bottom - 0.5, }; @@ -701,7 +745,7 @@ describe("components", { timeout: 60_000 }, () => { .flatMap((selector) => [...root.querySelectorAll(selector)]); return { name: entry.item.name, - parts: [...time.children].map((part) => part.className), + parts: [...time.children].map((part) => part.classList[0]), lines: values.map((value) => [value.textContent, (${LINES})(value)]), }; }) })`; @@ -1016,7 +1060,7 @@ describe("components", { timeout: 60_000 }, () => { const root = entry.shadowRoot; const button = root.querySelector(".entry"); const probe = root.appendChild(document.createElement("span")); - probe.style.color = "var(--accent-color, var(--magenta))"; + probe.style.color = "var(--color-accent, var(--magenta))"; const accent = getComputedStyle(probe).color; probe.remove(); const look = () => { @@ -1069,7 +1113,7 @@ describe("components", { timeout: 60_000 }, () => { const entry = document.querySelector("#focus sl-entry"); const button = entry.shadowRoot.querySelector(".entry"); const probe = entry.shadowRoot.appendChild(document.createElement("span")); - probe.style.color = "var(--accent-color, var(--magenta))"; + probe.style.color = "var(--color-accent, var(--magenta))"; const accent = getComputedStyle(probe).color; probe.remove(); const style = getComputedStyle(button); @@ -1182,11 +1226,11 @@ describe("components", { timeout: 60_000 }, () => { probe.remove(); return resolved; }; - const accent = resolve("color", "var(--accent-color, var(--magenta))"); - const interaction = resolve("color", "var(--interaction-color, var(--blue))"); + const accent = resolve("color", "var(--color-accent, var(--magenta))"); + const interaction = resolve("color", "var(--color-primary, var(--blue))"); const tint = resolve( "backgroundColor", - "color-mix(in srgb, var(--accent-color, var(--magenta)) 12%, transparent)", + "color-mix(in srgb, var(--color-accent, var(--magenta)) 12%, transparent)", ); const root = (selector) => subtree.querySelector(selector).shadowRoot; const [framed, focused] = [...subtree.querySelectorAll("sl-entry")] @@ -1206,10 +1250,10 @@ describe("components", { timeout: 60_000 }, () => { "the active marker's border": is(style.borderTopColor), "the active marker's tint": style.backgroundColor === tint ? "accent" : style.backgroundColor, "the active marker's glyph": is(style.color), - "the active marker's ring": is(getComputedStyle(marker, "::after").borderTopColor), + "the active marker's ring": is(getComputedStyle(marker.querySelector(".ring")).borderTopColor), "the active label": is(getComputedStyle(timeline.querySelector(".active .label")).color), "the streaming dot": is(getComputedStyle( - root("sl-chat-thread").querySelector(".status.in_progress"), "::before").backgroundColor), + root("sl-chat-thread").querySelector(".status.in_progress > .dot")).backgroundColor), "the selected frame's border": is(getComputedStyle(framed).borderTopColor), "the selected frame's shadow": getComputedStyle(framed).boxShadow.includes(accent) ? "accent" : getComputedStyle(framed).boxShadow, @@ -1233,7 +1277,7 @@ describe("components", { timeout: 60_000 }, () => { "the drag-over zone's border": "interaction", "the focus ring": "interaction", }; - for (const hook of ["", "--accent-color", "--interaction-color"]) { + for (const hook of ["", "--color-accent", "--color-primary"]) { const shown: { distinct: boolean; focused: boolean; over: boolean; marks: object } = await read(hook); const { marks, ...state } = shown; @@ -1250,6 +1294,57 @@ describe("components", { timeout: 60_000 }, () => { } }); + test("the motion sheet runs the streaming dot's pulse and the active marker's ring inside their shadow roots, and the drag-over's change in its --duration-s; under reduced motion none of them", async () => { + const page = await browser.open(`${server.origin}/test/fixtures/components.html`); + try { + await page.evaluate(`window.verdict.then(async () => { + await Promise.all(["stage-timeline", "chat-thread", "upload-dropzone"] + .map((name) => import("/dist/" + name + ".js"))); + window.motion = async () => { + const subtree = document.createElement("div"); + subtree.append( + Object.assign(document.createElement("sl-stage-timeline"), { stages: [ + { name: "extraction", position: 1, state: "active", completedAt: null }, + ] }), + Object.assign(document.createElement("sl-chat-thread"), { items: [ + { type: "message", id: "m-1", role: "assistant", status: "in_progress", + content: [{ type: "output_text", text: "Reading" }] }, + ] }), + Object.assign(document.createElement("sl-upload-dropzone"), { uploads: [] }), + ); + document.querySelector("main").replaceChildren(subtree); + await Promise.all([...subtree.children].map((element) => element.updateComplete)); + const [timeline, thread, dropzone] = [...subtree.children].map((element) => element.shadowRoot); + const names = (element) => element.getAnimations().map((animation) => animation.animationName); + const zone = dropzone.querySelector(".zone"); + const durations = () => getComputedStyle(zone).transitionDuration; + const before = durations(); + dropzone.host.style.setProperty("--duration-s", "345ms"); + return { + ring: names(timeline.querySelector(".active .marker > .ring")), + dot: names(thread.querySelector(".status.in_progress > .dot")), + zone: [before, durations()], + }; + }; + })`); + const shown = (): Promise<{ ring: string[]; dot: string[]; zone: string[] }> => + page.evaluate(`window.motion()`); + await page.cdp("Emulation.setEmulatedMedia", { + features: [{ name: "prefers-reduced-motion", value: "no-preference" }], + }); + const moving = await shown(); + assert.deepEqual([moving.ring, moving.dot], [["ring"], ["pulse"]]); + assert.notEqual(moving.zone[0], "0s", "the motion sheet's --duration-s resolves"); + assert.equal(moving.zone[1], "0.345s, 0.345s", "the drag-over's change takes --duration-s"); + await page.cdp("Emulation.setEmulatedMedia", { + features: [{ name: "prefers-reduced-motion", value: "reduce" }], + }); + assert.deepEqual(await shown(), { ring: [], dot: [], zone: ["0s", "0s"] }); + } finally { + await page.close(); + } + }); + const VIEWERS = `(section) => [...document.querySelectorAll(section + " sl-artifact-viewer")]`; test("the artifact viewer's specimen renders every state, at full size or held, within 20rem, in every profile", async () => { @@ -1825,8 +1920,8 @@ describe("components", { timeout: 60_000 }, () => { .filter((part) => lines(part) > 1) .map((part) => part.textContent), identifiers: [...root.querySelectorAll(".event")].map((event, index) => ({ - texts: [...event.querySelectorAll("dd.cut")].map((dd) => dd.textContent), - titles: [...event.querySelectorAll("dd.cut")].map((dd) => dd.title), + texts: [...event.querySelectorAll("dd.text-truncate")].map((dd) => dd.textContent), + titles: [...event.querySelectorAll("dd.text-truncate")].map((dd) => dd.title), expected: [log.events[index].subject, log.events[index].id].filter(Boolean), })), scrolls: frame.scrollHeight > frame.clientHeight, @@ -1904,7 +1999,7 @@ describe("components", { timeout: 60_000 }, () => { width: box.width / rem, events: log.events.length, values: [...root.querySelectorAll(".event")].flatMap((event, index) => - [...event.querySelectorAll("dd.cut")].map((dd, at) => { + [...event.querySelectorAll("dd.text-truncate")].map((dd, at) => { const rect = dd.getBoundingClientRect(); return { expected: [log.events[index].subject, log.events[index].id].filter(Boolean)[at], diff --git a/test/browser/document-list.test.ts b/test/browser/document-list.test.ts index d70f299..ffc0e98 100644 --- a/test/browser/document-list.test.ts +++ b/test/browser/document-list.test.ts @@ -337,7 +337,7 @@ describe("document list", { timeout: 60_000 }, () => { await mount({ total: 0 }); const { state, status, statusSlot, summary, list, entries } = await read(); assert.equal(state, "ready"); - assert.deepEqual(status, ["status", "No documents.", "status ready"]); + assert.deepEqual(status, ["status", "No documents.", "status ready status-line"]); assert.deepEqual([summary, statusSlot], [null, ""]); assert.equal(list, null); assert.deepEqual(entries, []); @@ -362,7 +362,7 @@ describe("document list", { timeout: 60_000 }, () => { await mount({ state: "loading" }); let shown = await read(); assert.equal(shown.state, "loading"); - assert.deepEqual(shown.status, ["status", "Loading documents…", "status loading"]); + assert.deepEqual(shown.status, ["status", "Loading documents…", "status loading status-line"]); assert.equal(shown.statusSlot, "", "a first load has no summary to join"); assert.equal(shown.list, null); await mount({ ...paging, items: documents }); @@ -413,7 +413,7 @@ describe("document list", { timeout: 60_000 }, () => { assert.deepEqual(status, [ "status", "Couldn't load the documents. 503 Service Unavailable.", - "status error", + "status error status-line", ]); assert.equal(list, null); assert.deepEqual(entries, []); diff --git a/test/browser/drawer.test.ts b/test/browser/drawer.test.ts index 1606388..6fb31df 100644 --- a/test/browser/drawer.test.ts +++ b/test/browser/drawer.test.ts @@ -1,4 +1,5 @@ // Adapted from spike-html-apps-components (10dde51): test/browser/drawer.test.ts, on @standards-lab/web-tooling. +// Adapted from spike-html-hosting-components (9fa5850): test/browser/drawer.test.ts, its Close glyph button and hint cases. import assert from "node:assert/strict"; import { after, before, beforeEach, describe, test } from "node:test"; @@ -8,6 +9,16 @@ import type { Browser, Page } from "@standards-lab/web-tooling/browser.js"; import { serve } from "@standards-lab/web-tooling/server.js"; import type { Server } from "@standards-lab/web-tooling/server.js"; +import x from "@standards-lab/web-icons/octicon/x-16"; + +import { + descriptions, + glyphButton, + hintShown, + hover, + pointAway, + untilHint, +} from "./support/glyph-button.ts"; import { served } from "./support/served.ts"; interface Heard { @@ -49,6 +60,7 @@ const DOCK = 768; const WIDE = 1280; const NARROW = 480; const HEIGHT = 800; +const CLOSE = `document.querySelector("sl-drawer").shadowRoot.querySelector("header button")`; describe("drawer", { timeout: 60_000 }, () => { let server: Server; @@ -206,6 +218,15 @@ describe("drawer", { timeout: 60_000 }, () => { .filter((node) => !node.ignored && node.role?.value === role) .map((node) => node.name?.value ?? ""); }; + const closeText = (): Promise<{ box: number[]; text: string }> => + page.evaluate(`(() => { + const hidden = ${CLOSE}.querySelector("slot[name=close]").closest("span"); + const box = hidden.getBoundingClientRect(); + return { + box: [box.width, box.height], + text: hidden.textContent.replace(/\\s+/g, " ").trim(), + }; + })()`); const headings = (): Promise<{ texts: string[]; inWrapper: boolean; @@ -484,6 +505,93 @@ describe("drawer", { timeout: 60_000 }, () => { } }); + for (const width of [WIDE, NARROW]) { + test(`with modal, at ${width}px, it is a closed drawer that opens as a modal dialog, the page behind inert; open goes out once`, async () => { + await mount(width, {}, "", HEIGHT, { attributes: "modal", mode: "drawer" }); + let shown = await read(); + assert.deepEqual( + [shown.mode, shown.wrapper, shown.dialogOpen, shown.open, shown.sent], + ["drawer", "dialog", false, false, []], + ); + await openByKeyboard(); + shown = await read(); + assert.deepEqual( + [shown.mode, shown.dialogOpen, shown.modal, shown.open, shown.attribute, shown.visible], + ["drawer", true, true, true, true, true], + ); + assert.equal(shown.box.width, width, "the dialog covers the viewport"); + assert.deepEqual(await exposed("dialog"), ["Documents"]); + assert.deepEqual(await exposed("complementary"), []); + assert.equal(shown.focused, "drawer h2"); + assert.equal(await pageLive(), false, "the page behind takes no focus"); + assert.deepEqual(shown.heard, [{ type: "open", detail: {}, bubbles: true, composed: true }]); + }); + } + + test("with modal, dock is ignored: a dock below the viewport, one the query can't read, and a resize across dock leave it a drawer, open", async () => { + for (const dock of ["20rem", "wide"]) { + await mount(WIDE, { dock }, "", HEIGHT, { attributes: "modal", mode: "drawer" }); + const shown = await read(); + assert.deepEqual([shown.mode, shown.wrapper], ["drawer", "dialog"], `with dock ${dock}`); + } + await call("show"); + await resize(NARROW); + await resize(WIDE); + await page.evaluate(`document.querySelector("sl-drawer").dock = "48rem"`); + const shown = await read(); + assert.deepEqual( + [shown.mode, shown.wrapper, shown.modal, shown.open, shown.sent], + ["drawer", "dialog", true, true, ["open"]], + ); + }); + + test("modal reflects from the property, and removing it docks the drawer again at dock and wider", async () => { + await mount(WIDE); + await page.evaluate(`document.querySelector("sl-drawer").modal = true`); + await settled("drawer"); + let shown = await read(); + assert.equal( + await page.evaluate(`document.querySelector("sl-drawer").hasAttribute("modal")`), + true, + ); + assert.deepEqual([shown.wrapper, shown.dialogOpen, shown.sent], ["dialog", false, []]); + await page.evaluate(`document.querySelector("sl-drawer").modal = false`); + await settled("docked"); + shown = await read(); + assert.equal( + await page.evaluate(`document.querySelector("sl-drawer").hasAttribute("modal")`), + false, + ); + assert.deepEqual([shown.wrapper, shown.sent], ["aside", []]); + }); + + test("modal set or removed while open closes it silently, either way, whether or not the mode changes", async () => { + const quiet = async (modal: boolean, mode: "docked" | "drawer", wrapper: string) => { + await page.evaluate(`document.querySelector("sl-drawer").modal = ${modal}`); + await settled(mode); + await page.evaluate("new Promise((resolve) => setTimeout(resolve, 50))"); + const shown = await read(); + assert.deepEqual( + [shown.wrapper, shown.dialogOpen, shown.modal, shown.open, shown.attribute], + [wrapper, false, false, false, false], + `modal set ${modal}, ${mode}`, + ); + return shown.sent; + }; + await mount(NARROW); + await call("show"); + assert.deepEqual(await quiet(true, "drawer", "dialog"), ["open"]); + await call("show"); + assert.deepEqual(await quiet(false, "drawer", "dialog"), ["open", "open"]); + await mount(WIDE, {}, "", HEIGHT, { attributes: "modal", mode: "drawer" }); + await call("show"); + assert.deepEqual(await quiet(false, "docked", "aside"), ["open"]); + await call("show"); + assert.deepEqual(await quiet(true, "drawer", "dialog"), ["open"]); + await call("show"); + assert.deepEqual((await read()).modal, true, "it opens again"); + }); + test("docked, show(), toggle(), and open leave it docked and send nothing", async () => { await mount(WIDE); await call("show"); @@ -618,31 +726,107 @@ describe("drawer", { timeout: 60_000 }, () => { await mount(NARROW); await openByKeyboard(); assert.ok((await exposed("button")).includes("Close Documents"), "the button's name"); + const shown = await glyphButton(page, CLOSE, x); + assert.deepEqual( + [shown.glyphs, shown.matches, shown.hidden, shown.drawn], + [1, true, "true", true], + "it shows web-icons' x-16 alone, hidden from the accessibility tree", + ); + assert.deepEqual(await closeText(), { box: [1, 1], text: "Close Documents" }); await clickAt(await center("header button", true)); await closedHeard(1); - const shown = await read(); + const closed = await read(); assert.deepEqual( - [shown.dialogOpen, shown.modal, shown.open, shown.attribute, shown.focused], + [closed.dialogOpen, closed.modal, closed.open, closed.attribute, closed.focused], [false, false, false, false, "opener"], ); assert.equal(await pageLive(), true); - assert.deepEqual(shown.sent, ["open", "close"]); + assert.deepEqual(closed.sent, ["open", "close"]); }); - test("a replacement for the Close button's text, through its close slot, shows and leads its name", async () => { + test("a replacement for the Close button's text, through its close slot, leads its name, visually hidden beside the glyph", async () => { await mount(NARROW, {}, 'Fermer'); await openByKeyboard(); const names = await exposed("button"); assert.ok(names.includes("Fermer Documents"), `the button's name: ${names}`); assert.ok(!names.some((name) => name.startsWith("Close")), "the default text is replaced"); - const shown: { visible: boolean; inButton: boolean } = await page.evaluate(`(() => { - const fermer = document.querySelector("#fermer"); - return { - visible: fermer.checkVisibility(), - inButton: fermer.assignedSlot?.closest("button") != null, - }; + const slotted: boolean = await page.evaluate( + `document.querySelector("#fermer").assignedSlot === ${CLOSE}.querySelector("slot[name=close]")`, + ); + assert.ok(slotted, "the replacement fills the Close button's close slot"); + assert.deepEqual((await closeText()).box, [1, 1], "visually hidden"); + assert.equal((await glyphButton(page, CLOSE, x)).matches, true, "the glyph stays"); + }); + + for (const [what, extra, name] of [ + ["its default text", "", "Close Documents"], + [ + "a replacement through its close slot", + 'Fermer', + "Fermer Documents", + ], + ]) { + test(`the Close button is a glyph button whose hint, by interestfor, is its name, with ${what}, announced once`, async () => { + await mount(NARROW, {}, extra); + await openByKeyboard(); + const shown = await glyphButton(page, CLOSE, x); + assert.ok(shown.classed, "a native button of the class glyph-button"); + assert.equal(shown.surface, shown.native, "the native button's border and surface"); + assert.deepEqual( + [shown.interestfor !== null, shown.resolves, shown.popover, shown.hintHidden], + [true, true, "hint", "true"], + "interestfor names a hint popover in its tree, hidden from the accessibility tree", + ); + assert.equal(shown.hint, name, "the hint's text is the button's name"); + assert.ok((await exposed("button")).includes(name), "the button's name"); + assert.deepEqual(await descriptions(page, name), [""], "no description"); + }); + } + + test("the Close button's hint follows a changed label and a close slot filled after it opens", async () => { + await mount(NARROW); + await openByKeyboard(); + await page.evaluate(`(async () => { + const drawer = document.querySelector("sl-drawer"); + drawer.label = "Pages"; + const text = document.createElement("span"); + text.slot = "close"; + text.textContent = "Fermer"; + drawer.append(text); + await new Promise((resolve) => setTimeout(resolve)); + await drawer.updateComplete; })()`); - assert.deepEqual(shown, { visible: true, inButton: true }); + assert.equal((await glyphButton(page, CLOSE, x)).hint, "Fermer Pages"); + assert.ok((await exposed("button")).includes("Fermer Pages"), "the button's name"); + }); + + test("keyboard focus on the Close button, tabbed to from the heading, shows its hint beside it, and focus moved on hides it", async () => { + await mount(NARROW); + await openByKeyboard(); + await untilHint(page, CLOSE, false); + await press("Tab", 9); + await until(page, `document.querySelector("sl-drawer").shadowRoot.activeElement === ${CLOSE}`); + await untilHint(page, CLOSE, true); + const shown = await hintShown(page, CLOSE); + assert.ok(shown.open && (shown.below || shown.above) && shown.overlaps, JSON.stringify(shown)); + await page.evaluate(`document.querySelector("#filter").focus()`); + await untilHint(page, CLOSE, false); + assert.equal((await read()).focused, "filter"); + }); + + test("hovering the Close button, focus elsewhere, shows its hint beside it, and pointing away hides it", async () => { + await mount(NARROW); + await openByKeyboard(); + await page.evaluate(`document.querySelector("#filter").focus()`); + await pointAway(page); + await untilHint(page, CLOSE, false); + await hover(page, CLOSE); + await untilHint(page, CLOSE, true); + const shown = await hintShown(page, CLOSE); + assert.ok(shown.open && (shown.below || shown.above) && shown.overlaps, JSON.stringify(shown)); + assert.equal((await read()).focused, "filter", "the hint shows with focus elsewhere"); + await pointAway(page); + await untilHint(page, CLOSE, false); }); test("Escape closes it, focus returns to the opener, and close goes out once", async () => { @@ -889,6 +1073,19 @@ describe("drawer", { timeout: 60_000 }, () => { await mount(NARROW); const motion = await running(); assert.ok(motion.transitions.includes("translate"), `transitions ${motion.transitions}`); + const durations = (duration: string) => new Set(duration.split(", ")); + assert.equal(durations(motion.duration).size, 1, `durations ${motion.duration}`); + assert.notEqual( + motion.duration.split(", ")[0], + "0s", + "the motion sheet's --duration-m resolves", + ); + await mount(NARROW, {}, "", HEIGHT, { attributes: 'style="--duration-m: 345ms"' }); + assert.deepEqual( + durations((await running()).duration), + new Set(["0.345s"]), + "the slide takes --duration-m", + ); await page.cdp("Emulation.setEmulatedMedia", { features: [{ name: "prefers-reduced-motion", value: "reduce" }], }); diff --git a/test/browser/json.test.ts b/test/browser/json.test.ts deleted file mode 100644 index 0ef6cef..0000000 --- a/test/browser/json.test.ts +++ /dev/null @@ -1,185 +0,0 @@ -// Adapted from spike-html-apps-components (10dde51): test/browser/json.test.ts, on @standards-lab/web-tooling. - -import assert from "node:assert/strict"; -import { after, before, describe, test } from "node:test"; - -import { launch } from "@standards-lab/web-tooling/browser.js"; -import type { Browser, Page } from "@standards-lab/web-tooling/browser.js"; -import { serve } from "@standards-lab/web-tooling/server.js"; -import type { Server } from "@standards-lab/web-tooling/server.js"; - -import { served } from "./support/served.ts"; - -const tokensOf = (text: string): string => - text.replace(/("(?:[^"\\]|\\.)*")|[ \t\n\r]+/g, (_, string?: string) => string ?? ""); - -describe("json", { timeout: 60_000 }, () => { - let server: Server; - let browser: Browser; - let page: Page; - before(async () => { - server = await serve(served); - browser = await launch(); - page = await browser.open(`${server.origin}/test/fixtures/components.html`); - await page.evaluate(`window.verdict.then(async () => { - window.formatJson = (await import("/dist/json.js")).formatJson; - })`); - }); - after(async () => { - await page?.close(); - await browser?.close(); - await server?.stop(); - }); - - const formatted = (text: string): Promise => - page.evaluate(`window.formatJson(${JSON.stringify(text)})`); - - const cases: Record = { - "keys in their order, integer-like keys where they stand": [ - '{"b":1,"10":2,"2":3,"a":4}', - '{\n "b": 1,\n "10": 2,\n "2": 3,\n "a": 4\n}', - ], - "number literals as written": [ - "[1.0,-0,1e3,1E-7,9007199254740993,0.10,-12.5e+02]", - "[\n 1.0,\n -0,\n 1e3,\n 1E-7,\n 9007199254740993,\n 0.10,\n -12.5e+02\n]", - ], - "duplicate keys, each kept": ['{"a":1,"a":2,"a":3}', '{\n "a": 1,\n "a": 2,\n "a": 3\n}'], - "strings with their escapes, byte for byte": [ - String.raw`{"q\"k":"say \"hi\"","path":"C:\\dir\\","e":"caf\u00e9 é","nl":"a\nb\/c","sp":" { [ , : ] } "}`, - String.raw`{ - "q\"k": "say \"hi\"", - "path": "C:\\dir\\", - "e": "caf\u00e9 é", - "nl": "a\nb\/c", - "sp": " { [ , : ] } " -}`, - ], - "minified text, indented two spaces a depth": [ - '{"id":"run-1","stages":[{"name":"classify","outputs":3,"ok":true,"err":null}],"done":false}', - '{\n "id": "run-1",\n "stages": [\n {\n "name": "classify",\n "outputs": 3,\n' + - ' "ok": true,\n "err": null\n }\n ],\n "done": false\n}', - ], - "oddly spaced text, normalized": [ - '\r\n { "a"\t:\n[ 1 ,\n\n 2 ] ,"b" :{ }\n, "c":[\t]} \n', - '{\n "a": [\n 1,\n 2\n ],\n "b": {},\n "c": []\n}', - ], - "nested empty objects and arrays": [ - '{"a":{},"b":[],"c":[{}, [ ], {"d":{ }}]}', - '{\n "a": {},\n "b": [],\n "c": [\n {},\n [],\n {\n "d": {}\n }\n ]\n}', - ], - "an empty object at the top": ["{ }", "{}"], - "an empty array at the top": ["[\n]", "[]"], - "a top-level array": [ - '[1,"two",[3],{"four":4}]', - '[\n 1,\n "two",\n [\n 3\n ],\n {\n "four": 4\n }\n]', - ], - "a top-level string": [' "a \\"b\\"" ', '"a \\"b\\""'], - "a top-level number": [" 1.50E+3 ", "1.50E+3"], - "a top-level literal": ["\nnull\n", "null"], - }; - for (const [kind, [text, expected]] of Object.entries(cases)) { - test(`formats ${kind}`, async () => { - const output = await formatted(text); - assert.equal(output, expected); - assert.equal(tokensOf(output), tokensOf(text), "only whitespace between tokens changed"); - }); - } - - test("changes only the whitespace between tokens, over a document of every kind", async () => { - const text = - ' { "z" : [ 1.0 , -0 , 1e3 , { "10" : "a\\u0000\\t b" , "2" : [ ] } ] , "z" : { "y" : ' + - 'true , "x" : false , "w" : null } , "\\ud83d\\ude00" : "😀" , "big" : 9007199254740993 } '; - const output = await formatted(text); - assert.equal(tokensOf(output), tokensOf(text)); - assert.ok(!/[ \t\r]\n|\n\n/.test(output), "no trailing space and no blank line"); - }); - - test("formats about 1 MB of JSON without a stall", async (t) => { - const timing: { bytes: number; lines: number; ms: number; same: boolean } = - await page.evaluate(`(() => { - const record = (i) => ({ - id: "run-" + i, "10": i, "2": -i * 1.5, note: "line \\"" + i + "\\"\\n\\u00e9", - stages: [{ name: "classify", outputs: [i, i + 1, i + 2], ok: true }, { name: "summarize", err: null }], - meta: {}, - }); - const text = JSON.stringify(Array.from({ length: 6000 }, (_, i) => record(i))); - window.formatJson(text); - const start = performance.now(); - const output = window.formatJson(text); - const ms = performance.now() - start; - return { - bytes: new TextEncoder().encode(text).length, - lines: output.split("\\n").length, - ms, - same: output.replace(/("(?:[^"\\\\]|\\\\.)*")|[ \\n]+/g, (_, s) => s ?? "") === text, - }; - })()`); - t.diagnostic(`${timing.bytes} bytes to ${timing.lines} lines in ${timing.ms.toFixed(1)} ms`); - assert.ok(timing.bytes > 900_000, `the document is ${timing.bytes} bytes`); - assert.ok(timing.same, "only whitespace between tokens changed"); - assert.ok(timing.ms < 250, `formatting took ${timing.ms} ms`); - }); - - const indent = (depth: number): string => " ".repeat(depth); - - test("formats every level of text nested 64 deep", async () => { - const text = "[".repeat(64) + "1" + "]".repeat(64); - const opening = Array.from({ length: 64 }, (_, depth) => `${indent(depth)}[`); - const closing = Array.from({ length: 64 }, (_, depth) => `${indent(63 - depth)}]`); - const expected = [...opening, `${indent(64)}1`, ...closing].join("\n"); - const output = await formatted(text); - assert.equal(output, expected); - assert.equal(tokensOf(output), tokensOf(text), "only whitespace between tokens changed"); - }); - - test("keeps a container that would open at depth 65 as written, on its line", async () => { - const inner = '[ 1 ,{"b" : "] }"} ,\t[ ] ]'; - const text = "[".repeat(63) + `{"a":${inner} , "c":3}` + "]".repeat(63); - const opening = Array.from({ length: 63 }, (_, depth) => `${indent(depth)}[`); - const closing = Array.from({ length: 63 }, (_, depth) => `${indent(62 - depth)}]`); - const object = [`${indent(63)}{`, `${indent(64)}"a": ${inner},`, `${indent(64)}"c": 3`]; - const expected = [...opening, ...object, `${indent(63)}}`, ...closing].join("\n"); - const output = await formatted(text); - assert.equal(output, expected); - assert.equal(tokensOf(output), tokensOf(text), "only whitespace between tokens changed"); - }); - - test("keeps a container at depth 65 whole when its strings hold quotes and brackets", async () => { - const kept = String.raw`{"{k\"": [ "\"]}", "\\", {"[" :"}]"} ] }`; - const after = String.raw`"]]}\"["`; - const text = "[".repeat(64) + `${kept},${after}` + "]".repeat(64); - const opening = Array.from({ length: 64 }, (_, depth) => `${indent(depth)}[`); - const closing = Array.from({ length: 64 }, (_, depth) => `${indent(63 - depth)}]`); - const inner = [`${indent(64)}${kept},`, `${indent(64)}${after}`]; - const output = await formatted(text); - assert.equal(output, [...opening, ...inner, ...closing].join("\n")); - assert.equal(tokensOf(output), tokensOf(text), "only whitespace between tokens changed"); - }); - - test("formats text nested 20,000 deep in output linear in its length, without a stall", async (t) => { - const result: { text: number; output: number; ms: number; same: boolean; tail: boolean } = - await page.evaluate(`(() => { - const text = "[".repeat(20000) + ' 1 ' + "]".repeat(20000); - window.formatJson(text); - const start = performance.now(); - const output = window.formatJson(text); - const ms = performance.now() - start; - const kept = "[".repeat(20000 - 64) + ' 1 ' + "]".repeat(20000 - 64); - return { - text: text.length, - output: output.length, - ms, - same: output.replace(/[ \\n]+/g, "") === text.replace(/ /g, ""), - tail: output.includes("\\n" + " ".repeat(64) + kept + "\\n"), - }; - })()`); - t.diagnostic(`${result.text} characters to ${result.output} in ${result.ms.toFixed(1)} ms`); - assert.ok( - result.output <= result.text + 4 * 64 * 64, - `${result.output} characters from ${result.text}`, - ); - assert.ok(result.same, "only whitespace between tokens changed"); - assert.ok(result.tail, "the levels past 64 kept as written, on their line"); - assert.ok(result.ms < 50, `formatting took ${result.ms} ms`); - }); -}); diff --git a/test/browser/settings.test.ts b/test/browser/settings.test.ts new file mode 100644 index 0000000..b9e3700 --- /dev/null +++ b/test/browser/settings.test.ts @@ -0,0 +1,621 @@ +// Adapted from spike-html-hosting-components (9fa5850): test/browser/settings.test.ts, on @standards-lab/web-tooling, its stores read back through the foundation's modules, the host's change events and the arrow keys, open, document change, and focus cases added, and the theme-menu request case dropped. + +import assert from "node:assert/strict"; +import { after, before, beforeEach, describe, test } from "node:test"; + +import { launch, SETTLED, until } from "@standards-lab/web-tooling/browser.js"; +import type { Browser, Page } from "@standards-lab/web-tooling/browser.js"; +import { serve } from "@standards-lab/web-tooling/server.js"; +import type { Server } from "@standards-lab/web-tooling/server.js"; + +import { served } from "./support/served.ts"; + +interface Row { + key: string; + legend: string; + options: string[]; + checked: string | null; +} + +interface Change { + target: string; + bubbles: boolean; + composed: boolean; +} + +const FIXTURE = "/test/fixtures/settings.html"; +const SHADOW = `document.querySelector("sl-settings").shadowRoot`; +const SETTINGS = `document.querySelector("#settings")`; +const HELP = `document.querySelector("#help")`; +const PREFERENCES = "web-foundation.preferences"; +const KEYS_STORAGE = "web-foundation.keys"; +const SWITCH_LABEL = "Character-key shortcuts (combinations with Control, Alt, or Meta stay on)"; + +const KEYS = { + h: { key: "h", code: "KeyH", windowsVirtualKeyCode: 72, text: "h" }, + j: { key: "j", code: "KeyJ", windowsVirtualKeyCode: 74, text: "j" }, + k: { key: "k", code: "KeyK", windowsVirtualKeyCode: 75, text: "k" }, + l: { key: "l", code: "KeyL", windowsVirtualKeyCode: 76, text: "l" }, + p: { key: "p", code: "KeyP", windowsVirtualKeyCode: 80, text: "p" }, + s: { key: "s", code: "KeyS", windowsVirtualKeyCode: 83, text: "s" }, + "?": { key: "?", code: "Slash", windowsVirtualKeyCode: 191, modifiers: 8, text: "?" }, + ArrowUp: { key: "ArrowUp", code: "ArrowUp", windowsVirtualKeyCode: 38 }, + ArrowDown: { key: "ArrowDown", code: "ArrowDown", windowsVirtualKeyCode: 40 }, + ArrowLeft: { key: "ArrowLeft", code: "ArrowLeft", windowsVirtualKeyCode: 37 }, + ArrowRight: { key: "ArrowRight", code: "ArrowRight", windowsVirtualKeyCode: 39 }, + Escape: { key: "Escape", code: "Escape", windowsVirtualKeyCode: 27 }, + "Control+k": { key: "k", code: "KeyK", windowsVirtualKeyCode: 75, modifiers: 2 }, +}; + +async function press(page: Page, name: keyof typeof KEYS): Promise { + const { text, ...key } = { text: undefined, ...KEYS[name] }; + await page.cdp("Input.dispatchKeyEvent", { + type: text === undefined ? "rawKeyDown" : "keyDown", + ...key, + ...(text === undefined ? {} : { text, unmodifiedText: text }), + }); + await page.cdp("Input.dispatchKeyEvent", { type: "keyUp", ...key }); +} + +const rows = (page: Page): Promise => + page.evaluate(`[...${SHADOW}.querySelectorAll(".theme-menu-row")].map((row) => ({ + key: row.dataset.section, + legend: row.querySelector("legend").textContent.trim(), + options: [...row.querySelectorAll("input")].map((radio) => radio.value), + checked: row.querySelector(":checked")?.value ?? null, + }))`); + +const checked = async (page: Page): Promise> => + Object.fromEntries((await rows(page)).map((row) => [row.key, row.checked])); + +const root = (page: Page): Promise> => + page.evaluate(`(() => { + const el = document.documentElement; + return { + color: el.getAttribute("data-palette"), + scheme: el.getAttribute("data-scheme"), + space: el.getAttribute("data-space"), + type: el.getAttribute("data-type"), + }; + })()`); + +const stored = (page: Page): Promise | null> => + page.evaluate(`window.preferences.read()`); + +const keySettings = (page: Page): Promise<{ enabled: boolean; wait: number }> => + page.evaluate(`window.keys.settings()`); + +const storedKeys = (page: Page): Promise | null> => + page.evaluate(`JSON.parse(localStorage.getItem(${JSON.stringify(KEYS_STORAGE)}) ?? "null")`); + +const rendered = (page: Page): Promise => + page.evaluate(`document.querySelector("sl-settings").updateComplete`); + +const focusedRow = (page: Page): Promise<{ key: string; value: string } | null> => + page.evaluate(`(() => { + const el = ${SHADOW}.activeElement; + const row = el?.closest(".theme-menu-row"); + return row ? { key: row.dataset.section, value: el.value } : null; + })()`); + +const listen = (page: Page): Promise => + page.evaluate(`document.addEventListener("change", (event) => + (window.changes ??= []).push({ + target: event.target.localName, + bubbles: event.bubbles, + composed: event.composed, + }))`); + +const changes = (page: Page): Promise => page.evaluate(`window.changes ?? []`); + +interface Placed { + host: number; + rows: { left: number; right: number; top: number; bottom: number }; + preview: { left: number; right: number; top: number; bottom: number }; + outside: string[]; + overflowing: string[]; +} + +const place = (page: Page, inlineSize: string): Promise => + page.evaluate(`(async () => { + const host = document.querySelector("sl-settings"); + const box = document.createElement("div"); + box.style.inlineSize = ${JSON.stringify(inlineSize)}; + document.body.append(box); + box.append(host); + await host.updateComplete; + const bounds = host.getBoundingClientRect(); + const rect = (el) => { + const { left, right, top, bottom } = el.getBoundingClientRect(); + return { left, right, top, bottom }; + }; + const name = (el) => el.localName + (el.className ? "." + el.className : ""); + const drawn = [...${SHADOW}.querySelectorAll("*")].filter((el) => el.checkVisibility() && + el.getBoundingClientRect().width > 1); + return { + host: bounds.width, + rows: rect(${SHADOW}.querySelector(".theme-menu-rows")), + preview: rect(${SHADOW}.querySelector(".theme-menu-preview")), + outside: drawn.filter((el) => { + const { left, right } = el.getBoundingClientRect(); + return left < bounds.left - 0.5 || right > bounds.right + 0.5; + }).map(name), + overflowing: [host, ...drawn].filter((el) => el.scrollWidth > el.clientWidth + 1 && + getComputedStyle(el).display !== "inline").map(name), + }; + })()`); + +const intersect = ({ rows, preview }: Placed): boolean => + rows.left < preview.right && + preview.left < rows.right && + rows.top < preview.bottom && + preview.top < rows.bottom; + +const HOST: Change = { target: "sl-settings", bubbles: true, composed: true }; + +async function openSettings(page: Page): Promise { + await page.evaluate( + `document.querySelector('[commandfor="settings"][command="show-modal"]').click()`, + ); + await until(page, `${SETTINGS}.open`); + await until( + page, + `${SHADOW}.activeElement?.closest(".theme-menu-row")?.dataset.section === "color"`, + ); +} + +async function arrow(page: Page, key: string, delta: number): Promise { + await page.evaluate( + `${SHADOW}.querySelector('[data-section="${key}"] [data-step="${delta}"]').click()`, + ); + await rendered(page); +} + +describe("sl-settings", { timeout: 60_000 }, () => { + let server: Server; + let browser: Browser; + let page: Page; + before(async () => { + server = await serve(served); + browser = await launch(); + page = await browser.open("about:blank"); + await page.cdp("Emulation.setFocusEmulationEnabled", { enabled: true }); + }); + after(async () => { + await page?.close(); + await browser?.close(); + await server?.stop(); + }); + + beforeEach(async () => { + await page.goto(`${server.origin}${FIXTURE}`); + await page.evaluate(`localStorage.clear()`); + await page.goto(`${server.origin}${FIXTURE}`); + await page.evaluate(`window.ready.then(() => ${SETTLED})`); + }); + + test("the rows list the registry's names and SCHEMES, checked at what applies", async () => { + const registry: { profiles: Record; defaults: Record } = + await page.evaluate(`(async () => { + const registry = await import("@standards-lab/web-foundation/registry.js"); + return { + profiles: Object.fromEntries(registry.FACETS.map((facet) => [facet, registry.profiles(facet)])), + defaults: registry.DEFAULTS, + }; + })()`); + const { profiles, defaults } = registry; + assert.deepEqual(await rows(page), [ + { key: "color", legend: "Color", options: profiles.color, checked: defaults.color }, + { key: "scheme", legend: "Scheme", options: ["system", "light", "dark"], checked: "system" }, + { key: "space", legend: "Space", options: profiles.space, checked: defaults.space }, + { key: "type", legend: "Type", options: profiles.type, checked: defaults.type }, + ]); + assert.ok(profiles.color.length > 2, "the full entry registers several palettes"); + assert.deepEqual(await page.evaluate(`window.errors`), []); + }); + + test("each row's arrows step it, wrapping, applied and stored at once, each step a change at the host", async () => { + const before = await checked(page); + await listen(page); + const all = await rows(page); + for (const row of all) { + const at = row.options.indexOf(row.checked!); + await arrow(page, row.key, 1); + const next = row.options[(at + 1) % row.options.length]; + assert.equal((await checked(page))[row.key], next, `${row.key}: ▶ checks the next`); + assert.equal((await root(page))[row.key], next, `${row.key}: applied to the root`); + assert.equal((await stored(page))?.[row.key], next, `${row.key}: stored at once`); + await arrow(page, row.key, -1); + await arrow(page, row.key, -1); + const previous = row.options[(at - 1 + row.options.length) % row.options.length]; + assert.equal((await checked(page))[row.key], previous, `${row.key}: ◀ wraps to the last`); + assert.equal((await stored(page))?.[row.key], previous, `${row.key}: stored at once`); + await arrow(page, row.key, 1); + } + assert.deepEqual(await stored(page), before); + assert.deepEqual( + await root(page), + { ...before, scheme: null }, + "system leaves data-scheme off", + ); + assert.deepEqual(await changes(page), Array(all.length * 4).fill(HOST)); + }); + + test("the arrows are hidden from assistive technology, take no focus, and are no buttons", async () => { + const arrows: { glyph: string; hidden: string | null; tag: string; tabIndex: number }[] = + await page.evaluate(`[...${SHADOW}.querySelectorAll("[data-step]")].map((el) => ({ + glyph: el.textContent, hidden: el.getAttribute("aria-hidden"), tag: el.localName, + tabIndex: el.tabIndex, + }))`); + assert.equal(arrows.length, 8, "two arrows a row"); + for (const [i, el] of arrows.entries()) { + assert.deepEqual(el, { glyph: i % 2 ? "▶" : "◀", hidden: "true", tag: "span", tabIndex: -1 }); + } + const buttons: number = await page.evaluate( + `${SHADOW}.querySelectorAll(".theme-menu-rows button").length`, + ); + assert.equal(buttons, 0, "no button among the rows"); + }); + + test("the dialog's opening focuses the first row's checked radio", async () => { + await openSettings(page); + const colors = (await rows(page))[0]; + assert.deepEqual(await focusedRow(page), { key: "color", value: colors.checked }); + }); + + test("H and L step a row and J and K move between rows, stopping at the ends, none reaching the page", async () => { + await openSettings(page); + await listen(page); + const colors = (await rows(page))[0].options; + await press(page, "l"); + await rendered(page); + assert.deepEqual(await focusedRow(page), { key: "color", value: colors[1] }); + assert.equal((await stored(page))?.color, colors[1], "stored at once"); + assert.equal((await root(page)).color, colors[1], "applied at once"); + await press(page, "k"); + assert.equal((await focusedRow(page))?.key, "color", "K stops at the first row"); + await press(page, "j"); + assert.deepEqual(await focusedRow(page), { key: "scheme", value: "system" }); + await press(page, "l"); + await rendered(page); + assert.deepEqual(await focusedRow(page), { key: "scheme", value: "light" }); + assert.equal((await root(page)).scheme, "light"); + await press(page, "j"); + await press(page, "j"); + await press(page, "j"); + assert.equal((await focusedRow(page))?.key, "type", "J stops at the last row"); + await press(page, "k"); + await press(page, "k"); + await press(page, "k"); + await press(page, "h"); + await rendered(page); + assert.deepEqual(await focusedRow(page), { key: "color", value: colors[0] }); + assert.equal((await stored(page))?.color, colors[0]); + assert.deepEqual(await changes(page), [HOST, HOST, HOST]); + await page.evaluate(`document.querySelector("#settings-close").focus()`); + await press(page, "j"); + await page.evaluate(SETTLED); + assert.equal(await page.evaluate(`window.ran`), 0, "no press ran the page's J or K"); + assert.equal(await page.evaluate(`${SETTINGS}.open`), true); + assert.deepEqual(await page.evaluate(`window.errors`), []); + }); + + test("the down and up arrows move between rows and the left and right arrows step one, each applied and stored", async () => { + await openSettings(page); + await listen(page); + const colors = (await rows(page))[0].options; + await press(page, "ArrowUp"); + assert.equal((await focusedRow(page))?.key, "color", "up stops at the first row"); + await press(page, "ArrowDown"); + assert.deepEqual(await focusedRow(page), { key: "scheme", value: "system" }); + await press(page, "ArrowRight"); + await rendered(page); + assert.deepEqual(await focusedRow(page), { key: "scheme", value: "light" }); + assert.equal((await root(page)).scheme, "light", "applied at once"); + assert.equal((await stored(page))?.scheme, "light", "stored at once"); + await press(page, "ArrowUp"); + await press(page, "ArrowLeft"); + await rendered(page); + const last = colors[colors.length - 1]; + assert.deepEqual(await focusedRow(page), { key: "color", value: last }); + assert.equal((await root(page)).color, last); + assert.equal((await stored(page))?.color, last); + assert.deepEqual(await changes(page), [HOST, HOST]); + assert.equal(await page.evaluate(`window.ran`), 0); + }); + + test("Escape closes the dialog natively and keeps every change: no Save, no Cancel", async () => { + await openSettings(page); + const colors = (await rows(page))[0].options; + await press(page, "l"); + await rendered(page); + await press(page, "Escape"); + await until(page, `!${SETTINGS}.open`); + assert.equal((await root(page)).color, colors[1], "the root keeps the change"); + assert.equal((await stored(page))?.color, colors[1], "the store keeps the change"); + const controls: string[] = await page.evaluate( + `[...${SHADOW}.querySelectorAll("button")].filter((button) => + !button.closest(".theme-menu-preview")).map((button) => button.textContent)`, + ); + assert.deepEqual(controls, [], "no Save and no Cancel"); + }); + + test("the preview card renders, drawn by the foundation's sheets, and takes no focus", async () => { + await openSettings(page); + const preview: Record = await page.evaluate(`(() => { + const card = ${SHADOW}.querySelector(".theme-menu-preview"); + const deploy = card.querySelector("button.button-blue"); + const style = (el, name) => getComputedStyle(el).getPropertyValue(name).trim(); + const probe = document.createElement("span"); + probe.style.color = "var(--blue)"; + card.append(probe); + const blue = getComputedStyle(probe).color; + probe.remove(); + const focusable = [...card.querySelectorAll("a, button, input")]; + for (const el of focusable) el.focus(); + return { + inert: card.inert, + focused: focusable.some((el) => ${SHADOW}.activeElement === el), + heading: card.querySelector("h3").textContent, + link: card.querySelector("a").textContent, + code: card.querySelector("code").textContent, + kbd: [...card.querySelectorAll("kbd")].map((kbd) => kbd.textContent), + buttons: [...card.querySelectorAll("button")].map((button) => button.textContent), + field: card.querySelector(".field input").value, + label: card.querySelector(".field input").labels[0].textContent, + rows: card.querySelectorAll("table.table-striped tbody tr").length, + display: style(card, "display"), + border: style(card, "border-top-style"), + rowsDisplay: style(${SHADOW}.querySelector(".theme-menu-row"), "display"), + fieldDisplay: style(card.querySelector(".field"), "display"), + deployBlue: style(deploy, "border-top-color") === blue, + striped: style(card.querySelector("tbody tr:nth-child(2)"), "background-color") + !== style(card.querySelector("tbody tr:nth-child(1)"), "background-color"), + valueFont: style(${SHADOW}.querySelector(".theme-menu-row > label:has(:checked)"), + "font-family") === style(card.querySelector("code"), "font-family"), + }; + })()`); + assert.deepEqual(preview, { + inert: true, + focused: false, + heading: "Nightly build", + link: "release notes", + code: "mise run check", + kbd: ["Ctrl", "K"], + buttons: ["Retry", "Deploy"], + field: "main", + label: "Branch", + rows: 3, + display: "grid", + border: "solid", + rowsDisplay: "flex", + fieldDisplay: "grid", + deployBlue: true, + striped: true, + valueFont: true, + }); + }); + + test("nothing in the element animates or transitions", async () => { + await openSettings(page); + const moving: string[] = await page.evaluate(`[...${SHADOW}.querySelectorAll("*")] + .filter((el) => { + const style = getComputedStyle(el); + return style.animationName !== "none" || + style.transitionDuration.split(",").some((d) => parseFloat(d) > 0); + }) + .map((el) => el.localName)`); + assert.deepEqual(moving, []); + }); + + test("the element reads both settings again as its dialog opens", async () => { + const choice = { color: "github", scheme: "dark", space: "compact", type: "sans" }; + await page.evaluate(`(() => { + window.preferences.apply(${JSON.stringify(choice)}); + window.keys.changeSettings({ enabled: false, wait: 3000 }); + })()`); + await rendered(page); + assert.notDeepEqual(await checked(page), choice, "no event yet"); + await openSettings(page); + assert.deepEqual(await checked(page), choice, "the rows follow the root"); + const keys: { enabled: boolean; wait: string } = await page.evaluate(`({ + enabled: ${SHADOW}.querySelector("input[type=checkbox]").checked, + wait: ${SHADOW}.querySelector("select").value, + })`); + assert.deepEqual(keys, { enabled: false, wait: "3000" }, "the keyboard settings follow"); + }); + + test("a change in the document reads both settings again", async () => { + const choice = { color: "github", scheme: "light", space: "compact", type: "sans" }; + await page.evaluate(`(() => { + window.preferences.apply(${JSON.stringify(choice)}); + window.keys.changeSettings({ enabled: false, wait: 1000 }); + document.body.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + await rendered(page); + assert.deepEqual(await checked(page), choice); + const keys: { enabled: boolean; wait: string } = await page.evaluate(`({ + enabled: ${SHADOW}.querySelector("input[type=checkbox]").checked, + wait: ${SHADOW}.querySelector("select").value, + })`); + assert.deepEqual(keys, { enabled: false, wait: "1000" }); + }); + + test("another tab's change updates the root, the rows, and the keyboard settings", async () => { + const choice = { color: "github", scheme: "dark", space: "compact", type: "sans" }; + await page.evaluate(`(() => { + localStorage.setItem(${JSON.stringify(PREFERENCES)}, ${JSON.stringify(JSON.stringify(choice))}); + dispatchEvent(new StorageEvent("storage", { key: ${JSON.stringify(PREFERENCES)} })); + localStorage.setItem(${JSON.stringify(KEYS_STORAGE)}, JSON.stringify({ enabled: false, wait: 3000 })); + dispatchEvent(new StorageEvent("storage", { key: ${JSON.stringify(KEYS_STORAGE)} })); + })()`); + await rendered(page); + assert.deepEqual(await root(page), choice, "the root follows"); + assert.deepEqual(await checked(page), choice, "the rows follow"); + const keys: { enabled: boolean; wait: string } = await page.evaluate(`({ + enabled: ${SHADOW}.querySelector("input[type=checkbox]").checked, + wait: ${SHADOW}.querySelector("select").value, + })`); + assert.deepEqual(keys, { enabled: false, wait: "3000" }, "the keyboard settings follow"); + }); + + test("the switch and the wait are stored at once through the keys module, each a change at the host", async () => { + const labels: { switch: string; wait: string; options: string[] } = await page.evaluate(`({ + switch: ${SHADOW}.querySelector("input[type=checkbox]").labels[0].textContent + .replace(/\\s+/g, " ").trim(), + wait: [...${SHADOW}.querySelector("select").labels[0].childNodes] + .filter((node) => node.nodeType === Node.TEXT_NODE) + .map((node) => node.textContent).join("").trim(), + options: [...${SHADOW}.querySelectorAll("select option")].map((o) => o.textContent.trim()), + })`); + assert.deepEqual(labels, { + switch: SWITCH_LABEL, + wait: "Wait between presses", + options: ["1 s", "1.5 s", "3 s", "5 s"], + }); + assert.equal(await page.evaluate(`${SHADOW}.querySelector("select").value`), "1500"); + + await openSettings(page); + await listen(page); + await page.evaluate(`${SHADOW}.querySelector("input[type=checkbox]").click()`); + assert.deepEqual(await keySettings(page), { enabled: false, wait: 1500 }, "the switch stored"); + await page.evaluate(`(() => { + const select = ${SHADOW}.querySelector("select"); + select.value = "3000"; + select.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + assert.deepEqual(await keySettings(page), { enabled: false, wait: 3000 }, "the wait stored"); + assert.deepEqual(await changes(page), [HOST, HOST]); + await page.evaluate(`${SETTINGS}.close()`); + await until(page, `!${SETTINGS}.open`); + + await page.evaluate(`document.activeElement?.blur()`); + await press(page, "p"); + await press(page, "?"); + await press(page, "s"); + await press(page, "j"); + await press(page, "k"); + await page.evaluate(SETTLED); + const off: Record = await page.evaluate(`({ + pages: window.pages, ran: window.ran, help: ${HELP}.open, settings: ${SETTINGS}.open, + })`); + assert.deepEqual(off, { pages: 0, ran: 0, help: false, settings: false }); + await page.evaluate(`document.querySelector("#search").addEventListener("click", + () => (window.searched = true))`); + await press(page, "Control+k"); + assert.equal(await page.evaluate(`window.searched`), true, "Control+K still fires"); + + await openSettings(page); + await page.evaluate(`${SHADOW}.querySelector("input[type=checkbox]").click()`); + await page.evaluate(`(() => { + const select = ${SHADOW}.querySelector("select"); + select.value = "1500"; + select.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + assert.equal(await storedKeys(page), null, "the defaults store nothing"); + await page.evaluate(`${SETTINGS}.close()`); + await until(page, `!${SETTINGS}.open`); + await page.evaluate(`document.activeElement?.blur()`); + await press(page, "s"); + await until(page, `${SETTINGS}.open`); + }); + + test("the switch updates, in the same tab, aria-keyshortcuts and an open shortcuts list", async () => { + const declared = (): Promise> => + page.evaluate(`(() => { + const of = (el) => el.getAttribute("aria-keyshortcuts"); + return { + pages: of(document.querySelector("#pages")), + help: of(document.querySelector('[commandfor="help"][command="show-modal"]')), + settings: of(document.querySelector('[commandfor="settings"][command="show-modal"]')), + search: of(document.querySelector("#search")), + }; + })()`); + const listed = (): Promise<{ keys: string; off: boolean }[]> => + page.evaluate(`[...document.querySelector("sl-shortcuts").shadowRoot + .querySelectorAll("tbody tr")].map((tr) => ({ + keys: tr.cells[0].querySelector("kbd").textContent, + off: tr.classList.contains("off"), + }))`); + assert.deepEqual(await declared(), { + pages: "P", + help: "Shift+/", + settings: "S", + search: "Control+K", + }); + + await page.evaluate( + `document.querySelector('[commandfor="help"][command="show-modal"]').click()`, + ); + await until(page, `${HELP}.open`); + assert.ok( + (await listed()).every((row) => !row.off), + "every row on", + ); + await listen(page); + await page.evaluate(`${SHADOW}.querySelector("input[type=checkbox]").click()`); + await page.evaluate(`document.querySelector("sl-shortcuts").updateComplete`); + assert.deepEqual(await changes(page), [HOST], "the document sees the host's change alone"); + assert.deepEqual(await declared(), { + pages: null, + help: null, + settings: null, + search: "Control+K", + }); + assert.deepEqual(await listed(), [ + { keys: "P", off: true }, + { keys: "?", off: true }, + { keys: "S", off: true }, + { keys: "Control", off: false }, + { keys: "J", off: true }, + { keys: "K", off: true }, + ]); + + await page.evaluate(`${SHADOW}.querySelector("input[type=checkbox]").click()`); + await page.evaluate(`document.querySelector("sl-shortcuts").updateComplete`); + assert.equal((await declared()).settings, "S"); + assert.ok( + (await listed()).every((row) => !row.off), + "every row on again", + ); + }); + describe("in a wide viewport", () => { + before(async () => { + await page.cdp("Emulation.setDeviceMetricsOverride", { + width: 1280, + height: 800, + deviceScaleFactor: 1, + mobile: false, + }); + }); + after(async () => { + await page.cdp("Emulation.clearDeviceMetricsOverride"); + }); + + test("at 20rem the preview goes below the rows, nothing overlapping or overflowing the host", async () => { + const placed = await place(page, "20rem"); + assert.ok(placed.preview.top >= placed.rows.bottom, JSON.stringify(placed)); + assert.ok(!intersect(placed), JSON.stringify(placed)); + assert.deepEqual(placed.outside, []); + assert.deepEqual(placed.overflowing, []); + }); + + test("at 60rem the preview stands beside the rows, nothing overlapping or overflowing the host", async () => { + const placed = await place(page, "60rem"); + assert.ok(placed.preview.left >= placed.rows.right, JSON.stringify(placed)); + assert.ok(placed.preview.top < placed.rows.bottom, JSON.stringify(placed)); + assert.ok(!intersect(placed), JSON.stringify(placed)); + assert.deepEqual(placed.outside, []); + assert.deepEqual(placed.overflowing, []); + }); + + test("in a shrink-to-fit parent the element is as wide as its content, nothing overlapping or overflowing it", async () => { + const placed = await place(page, "max-content"); + const rows = placed.rows.right - placed.rows.left; + assert.ok(placed.host >= rows && placed.host <= 1280, JSON.stringify(placed)); + assert.ok(!intersect(placed), JSON.stringify(placed)); + assert.deepEqual(placed.outside, []); + assert.deepEqual(placed.overflowing, []); + }); + }); +}); diff --git a/test/browser/shortcut-dialogs.test.ts b/test/browser/shortcut-dialogs.test.ts new file mode 100644 index 0000000..98ec0c5 --- /dev/null +++ b/test/browser/shortcut-dialogs.test.ts @@ -0,0 +1,211 @@ +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; + +import { launch, until } from "@standards-lab/web-tooling/browser.js"; +import type { Browser, Page } from "@standards-lab/web-tooling/browser.js"; +import { serve } from "@standards-lab/web-tooling/server.js"; +import type { Server } from "@standards-lab/web-tooling/server.js"; +import gear from "@standards-lab/web-icons/octicon/gear-16"; +import question from "@standards-lab/web-icons/octicon/question-16"; +import x from "@standards-lab/web-icons/octicon/x-16"; + +import { glyphButton } from "./support/glyph-button.ts"; +import { served } from "./support/served.ts"; + +const PAGES = ["components", "settings", "shortcuts"]; + +const KEYS = { + s: { key: "s", code: "KeyS", windowsVirtualKeyCode: 83, text: "s" }, + "?": { key: "?", code: "Slash", windowsVirtualKeyCode: 191, modifiers: 8, text: "?" }, + Enter: { key: "Enter", code: "Enter", windowsVirtualKeyCode: 13, text: "\r" }, + Escape: { key: "Escape", code: "Escape", windowsVirtualKeyCode: 27 }, +}; + +async function press(page: Page, name: keyof typeof KEYS): Promise { + const { text, ...key } = { text: undefined, ...KEYS[name] }; + await page.cdp("Input.dispatchKeyEvent", { + type: text === undefined ? "rawKeyDown" : "keyDown", + ...key, + ...(text === undefined ? {} : { text, unmodifiedText: text }), + }); + await page.cdp("Input.dispatchKeyEvent", { type: "keyUp", ...key }); +} + +const DIALOGS = [ + { + id: "settings", + key: "s", + name: "Settings", + glyph: gear, + width: "dialog-wide", + holds: "sl-settings", + }, + { + id: "help", + key: "?", + name: "Help", + glyph: question, + width: "dialog-fit", + holds: "sl-shortcuts", + }, +] as const; + +type Dialog = (typeof DIALOGS)[number]; + +const opener = (dialog: Dialog): string => + `document.querySelector('[commandfor="${dialog.id}"][command="show-modal"]')`; +const closer = (dialog: Dialog): string => + `document.querySelector('#${dialog.id} > .dialog-header [commandfor="${dialog.id}"][command="close"]')`; + +const shown = ( + page: Page, + dialog: Dialog, +): Promise<{ open: boolean; modal: boolean; focus: string }> => + page.evaluate(`(() => { + const dialog = document.querySelector("#${dialog.id}"); + const active = document.activeElement; + return { + open: dialog.open, + modal: dialog.matches(":modal"), + focus: active === ${opener(dialog)} ? "opener" : active.id || active.localName, + }; + })()`); + +describe("the Settings and Help pattern on the demo pages", { timeout: 60_000 }, () => { + let server: Server; + let browser: Browser; + before(async () => { + server = await serve(served); + browser = await launch(); + }); + after(async () => { + await browser?.close(); + await server?.stop(); + }); + + async function open(name: string): Promise { + const page = await browser.open(`${server.origin}/demo/${name}.html`); + await page.cdp("Emulation.setFocusEmulationEnabled", { enabled: true }); + await page.evaluate(`Promise.all(["sl-settings", "sl-shortcuts"].map((tag) => + customElements.whenDefined(tag)))`); + return page; + } + + for (const name of PAGES) { + test(`the ${name} page's header holds the Help and Settings glyph buttons, each its web-icons glyph and its key, bound by data-keys`, async () => { + const page = await open(name); + try { + for (const dialog of DIALOGS) { + const button = await glyphButton(page, opener(dialog), dialog.glyph); + assert.deepEqual( + { + classed: button.classed, + glyphs: button.glyphs, + matches: button.matches, + hint: button.hint, + }, + { classed: true, glyphs: 1, matches: true, hint: dialog.name }, + dialog.name, + ); + const read: { + label: string | null; + keys: string | null; + kbd: string; + inActions: boolean; + } = await page.evaluate(`(() => { + const button = ${opener(dialog)}; + return { + label: button.getAttribute("aria-label"), + keys: button.dataset.keys ?? null, + kbd: button.querySelector("kbd")?.textContent ?? "", + inActions: button.closest("body > header .header-actions") !== null, + }; + })()`); + assert.deepEqual( + read, + { + label: dialog.name, + keys: dialog.key, + kbd: dialog.key.toUpperCase(), + inActions: true, + }, + dialog.name, + ); + } + } finally { + await page.close(); + } + }); + + test(`the ${name} page's dialogs: Settings wide holding sl-settings, Help fit holding sl-shortcuts, each headed by a Close glyph showing Esc`, async () => { + const page = await open(name); + try { + for (const dialog of DIALOGS) { + const read: { classes: string[]; holds: boolean; header: boolean; kbd: string } = + await page.evaluate(`(() => { + const dialog = document.querySelector("#${dialog.id}"); + const header = dialog.firstElementChild; + return { + classes: [...dialog.classList], + holds: dialog.querySelector("${dialog.holds}") !== null, + header: header.matches("header.dialog-header") && header.contains(${closer(dialog)}), + kbd: ${closer(dialog)}.querySelector("kbd").textContent, + }; + })()`); + assert.deepEqual( + read, + { classes: [dialog.width], holds: true, header: true, kbd: "Esc" }, + dialog.name, + ); + const close = await glyphButton(page, closer(dialog), x); + assert.deepEqual( + { classed: close.classed, matches: close.matches, hint: close.hint }, + { classed: true, matches: true, hint: "Close" }, + `${dialog.name}'s Close`, + ); + } + } finally { + await page.close(); + } + }); + + test(`on the ${name} page, S opens Settings and ? opens Help as modals, Escape closes each, and focus returns to the opener`, async () => { + const page = await open(name); + try { + for (const dialog of DIALOGS) { + await page.evaluate(`${opener(dialog)}.focus()`); + await press(page, dialog.key); + await until(page, `document.querySelector("#${dialog.id}").open`); + const opened = await shown(page, dialog); + assert.equal(opened.open && opened.modal, true, `${dialog.key} opens ${dialog.name}`); + assert.notEqual(opened.focus, "opener", `focus moves into ${dialog.name}`); + await press(page, "Escape"); + await until(page, `!document.querySelector("#${dialog.id}").open`); + assert.deepEqual( + await shown(page, dialog), + { open: false, modal: false, focus: "opener" }, + `Escape closes ${dialog.name}`, + ); + } + } finally { + await page.close(); + } + }); + + test(`on the ${name} page, each opener's Enter opens its dialog, its Close closes it, and focus returns to the opener`, async () => { + const page = await open(name); + try { + for (const dialog of DIALOGS) { + await page.evaluate(`${opener(dialog)}.focus()`); + await press(page, "Enter"); + await until(page, `document.querySelector("#${dialog.id}").open`); + await page.evaluate(`${closer(dialog)}.click()`); + await until(page, `!document.querySelector("#${dialog.id}").open`); + assert.equal((await shown(page, dialog)).focus, "opener", dialog.name); + } + } finally { + await page.close(); + } + }); + } +}); diff --git a/test/browser/shortcuts.test.ts b/test/browser/shortcuts.test.ts new file mode 100644 index 0000000..9afe456 --- /dev/null +++ b/test/browser/shortcuts.test.ts @@ -0,0 +1,280 @@ +// Adapted from spike-html-hosting-components (9fa5850): test/browser/shortcuts.test.ts, on @standards-lab/web-tooling, its key presses inside the open list and the document change cases added. + +import assert from "node:assert/strict"; +import { after, before, beforeEach, describe, test } from "node:test"; + +import { launch, SETTLED, until } from "@standards-lab/web-tooling/browser.js"; +import type { Browser, Page } from "@standards-lab/web-tooling/browser.js"; +import { serve } from "@standards-lab/web-tooling/server.js"; +import type { Server } from "@standards-lab/web-tooling/server.js"; + +import { served } from "./support/served.ts"; + +interface Row { + keys: string; + action: string; + off: boolean; +} + +interface Key { + key: string; + code: string; + windowsVirtualKeyCode: number; + modifiers: number; + text?: string; +} + +const FIXTURE = "/test/fixtures/shortcuts.html"; +const SHADOW = `document.querySelector("sl-shortcuts").shadowRoot`; +const HELP = `document.querySelector("#help")`; + +const ROWS: Row[] = [ + { keys: "?", action: "Help", off: false }, + { keys: "Control+K", action: "Search", off: false }, + { keys: "G then E", action: "End", off: false }, + { keys: "J", action: "Next section", off: false }, + { keys: "Alt+N", action: "New note", off: false }, +]; + +const OFF_ROWS = ROWS.map((row) => ({ ...row, off: !/^(Control|Alt)\+/.test(row.keys) })); + +const QUESTION: Key = { + key: "?", + code: "Slash", + windowsVirtualKeyCode: 191, + modifiers: 8, + text: "?", +}; +const J: Key = { key: "j", code: "KeyJ", windowsVirtualKeyCode: 74, modifiers: 0, text: "j" }; +const ALT_N: Key = { key: "n", code: "KeyN", windowsVirtualKeyCode: 78, modifiers: 1 }; + +async function press(page: Page, { text, ...key }: Key): Promise { + await page.cdp("Input.dispatchKeyEvent", { + type: "keyDown", + ...key, + ...(text === undefined ? {} : { text, unmodifiedText: text }), + }); + await page.cdp("Input.dispatchKeyEvent", { type: "keyUp", ...key }); +} + +const rows = (page: Page): Promise => + page.evaluate(`[...${SHADOW}.querySelectorAll("tbody tr")].map((tr) => { + const small = tr.cells[0].querySelector("small"); + const marked = small !== null && small.textContent.trim() === "off" && small.checkVisibility(); + return { + keys: tr.cells[0].textContent.replace(/\\s+/g, " ").trim().replace(/ off$/, ""), + action: tr.cells[1].textContent.trim(), + off: marked && tr.cells[0].textContent.trim().endsWith(" off") && tr.classList.contains("off"), + }; + })`); + +const rendered = (page: Page): Promise => + page.evaluate(`document.querySelector("sl-shortcuts").updateComplete.then(() => {})`); + +async function open(page: Page, byKey = true): Promise { + if (byKey) await press(page, QUESTION); + else + await page.evaluate( + `document.querySelector('[commandfor="help"][command="show-modal"]').click()`, + ); + await until(page, `${HELP}.open`); + await rendered(page); +} + +async function close(page: Page): Promise { + await page.evaluate(`${HELP}.close()`); + await until(page, `!${HELP}.open`); +} + +describe("shortcuts", { timeout: 60_000 }, () => { + let server: Server; + let browser: Browser; + let page: Page; + before(async () => { + server = await serve(served); + browser = await launch(); + page = await browser.open("about:blank"); + await page.cdp("Emulation.setFocusEmulationEnabled", { enabled: true }); + }); + after(async () => { + await page?.close(); + await browser?.close(); + await server?.stop(); + }); + + beforeEach(async () => { + await page.goto(`${server.origin}${FIXTURE}`); + await page.evaluate(`localStorage.clear()`); + await page.goto(`${server.origin}${FIXTURE}`); + await page.evaluate(`window.ready.then(() => ${SETTLED})`); + }); + + test("the rows are exactly bindings(dialog), each key in a kbd, under Keys and Action", async () => { + await open(page); + assert.deepEqual(await rows(page), ROWS); + const listed: { given: string[]; kbds: number[]; header: string[] } = await page.evaluate(`({ + given: window.keys.bindings(${HELP}).map((binding) => binding.keys), + kbds: [...${SHADOW}.querySelectorAll("tbody tr")].map((tr) => + tr.cells[0].querySelectorAll("kbd").length), + header: [...${SHADOW}.querySelectorAll("thead th")].map((th) => th.textContent.trim()), + })`); + assert.deepEqual(listed.given, ["?", "Control+k", "g e", "j", "Alt+n"], "bindings(dialog)"); + assert.deepEqual(listed.kbds, [1, 2, 2, 1, 2], "each key in its own kbd"); + assert.deepEqual(listed.header, ["Keys", "Action"]); + assert.deepEqual(await page.evaluate(`window.errors`), []); + }); + + test("the list reads the bindings again at each open of its dialog", async () => { + await page.evaluate(`document.querySelector("#search").hidden = true`); + await open(page); + assert.deepEqual( + await rows(page), + ROWS.filter((row) => row.action !== "Search"), + ); + await close(page); + await page.evaluate(`document.querySelector("#search").hidden = false`); + await open(page); + assert.deepEqual(await rows(page), ROWS); + await close(page); + }); + + test("with character keys off, their rows are marked off and the combinations' aren't", async () => { + await page.evaluate(`window.keys.changeSettings({ enabled: false })`); + await open(page, false); + assert.deepEqual(await rows(page), OFF_ROWS); + await close(page); + }); + + test("an open list follows a settings change the document's change event reports", async () => { + await open(page); + await page.evaluate(`(() => { + window.keys.changeSettings({ enabled: false }); + document.body.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + await rendered(page); + assert.deepEqual(await rows(page), OFF_ROWS); + await page.evaluate(`(() => { + window.keys.changeSettings({ enabled: null }); + document.body.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + await rendered(page); + assert.deepEqual(await rows(page), ROWS); + await close(page); + }); + + test("an open list follows a change of the setting in another tab", async () => { + await open(page); + await page.evaluate(`(() => { + const key = "web-foundation.keys"; + localStorage.setItem(key, JSON.stringify({ enabled: false })); + dispatchEvent(new StorageEvent("storage", { key })); + })()`); + await rendered(page); + assert.deepEqual(await rows(page), OFF_ROWS); + await close(page); + }); + + test("the screen-reader note follows the table, and the element holds no setting", async () => { + await open(page); + const { note, ...shown }: { last: string; note: string; after: boolean; fields: number } = + await page.evaluate(`(() => { + const note = ${SHADOW}.querySelector("p"); + const table = ${SHADOW}.querySelector("table"); + return { + last: ${SHADOW}.lastElementChild.localName, + note: note.textContent.trim(), + after: Boolean(table.compareDocumentPosition(note) & Node.DOCUMENT_POSITION_FOLLOWING), + fields: ${SHADOW}.querySelectorAll("input, select, textarea, fieldset").length, + }; + })()`); + assert.deepEqual(shown, { last: "p", after: true, fields: 0 }); + assert.match(note, /^Screen readers: .*NVDA.*VoiceOver\.$/); + await close(page); + }); + + test("in a shrink-to-fit parent the element is as wide as its table, or sixteen --space-base steps, the note wrapping within it", async () => { + await open(page); + const sized: { host: number; table: number; floor: number; note: number; lines: number } = + await page.evaluate(`(async () => { + const host = document.querySelector("sl-shortcuts"); + const parent = document.createElement("div"); + parent.style.inlineSize = "max-content"; + host.replaceWith(parent); + parent.append(host); + await host.updateComplete; + const note = ${SHADOW}.querySelector(".note"); + const lineHeight = parseFloat(getComputedStyle(note).lineHeight); + const probe = parent.appendChild(document.createElement("div")); + probe.style.inlineSize = "calc(var(--space-base) * 16)"; + const floor = probe.getBoundingClientRect().width; + probe.remove(); + return { + floor, + host: host.getBoundingClientRect().width, + table: ${SHADOW}.querySelector("table").getBoundingClientRect().width, + note: note.getBoundingClientRect().width, + lines: Math.round(note.getBoundingClientRect().height / lineHeight), + }; + })()`); + const wide = Math.max(sized.table, sized.floor); + assert.ok( + Math.abs(sized.host - wide) < 1, + `host ${sized.host}, table ${sized.table}, floor ${sized.floor}`, + ); + assert.ok(sized.note <= wide + 0.5, `note ${sized.note}, host ${sized.host}`); + assert.ok(sized.lines > 1, `the note in ${sized.lines} line`); + await close(page); + }); + + test("nothing in the list takes focus, and the dialog opened by ? focuses its title", async () => { + await open(page); + const shown: { focusable: number; tabbable: number; focused: string | null } = + await page.evaluate(`({ + focusable: ${SHADOW}.querySelectorAll( + "button, a[href], input, select, textarea, summary, [tabindex], [contenteditable]", + ).length, + tabbable: [...${SHADOW}.querySelectorAll("*")].filter((el) => el.tabIndex >= 0).length, + focused: document.activeElement === document.querySelector("#help-title") + ? "title" + : document.activeElement?.localName ?? null, + })`); + assert.deepEqual(shown, { focusable: 0, tabbable: 0, focused: "title" }); + await close(page); + }); + + test("pressing a listed key with the pointer in the table runs nothing, which outside the dialog runs", async () => { + await open(page); + const { x, y }: { x: number; y: number } = await page.evaluate(`(() => { + const cell = ${SHADOW}.querySelector("tbody tr:last-child td:last-child"); + const { left, top, width, height } = cell.getBoundingClientRect(); + return { x: left + width / 2, y: top + height / 2 }; + })()`); + for (const type of ["mousePressed", "mouseReleased"]) { + await page.cdp("Input.dispatchMouseEvent", { type, x, y, button: "left", clickCount: 1 }); + } + await press(page, J); + await press(page, ALT_N); + const inside: { ran: number; open: boolean; focusedInList: boolean } = await page.evaluate(`({ + ran: window.ran, + open: ${HELP}.open, + focusedInList: ${SHADOW}.activeElement !== null, + })`); + assert.deepEqual(inside, { ran: 0, open: true, focusedInList: false }); + await close(page); + await press(page, ALT_N); + assert.equal( + await page.evaluate(`window.ran`), + 1, + "the page's binding runs outside the dialog", + ); + }); + + test("no [data-keys-list] is in the page or the element's shadow root", async () => { + await open(page); + const lists: number = await page.evaluate( + `document.querySelectorAll("[data-keys-list]").length + ${SHADOW}.querySelectorAll("[data-keys-list]").length`, + ); + assert.equal(lists, 0); + await close(page); + }); +}); diff --git a/test/browser/support/deep.ts b/test/browser/support/deep.ts index 9cff7c2..6bccff9 100644 --- a/test/browser/support/deep.ts +++ b/test/browser/support/deep.ts @@ -1,5 +1,5 @@ -// The output formatJson owes text nested in arrays alone: the outer MAX_DEPTH levels indented, the -// levels below them kept as written. +// The output the foundation's formatJson owes text nested in arrays alone: the outer +// JSON_MAX_DEPTH levels indented, the levels below them kept as written. // From spike-html-apps-components (10dde51): test/browser/support/deep.ts. /** `"[".repeat(depth) + "1" + "]".repeat(depth)` as formatJson formats it. */ diff --git a/test/browser/support/glyph-button.ts b/test/browser/support/glyph-button.ts new file mode 100644 index 0000000..1b5e82c --- /dev/null +++ b/test/browser/support/glyph-button.ts @@ -0,0 +1,126 @@ +// A glyph button as a component's shadow root shows it: its glyph, the very svg an icons module +// exports, hidden from the accessibility tree; the class's row against a plain native button in +// the same root; the interest hint its interestfor names, resolved in the button's own tree, a +// hint popover holding the button's name; the descriptions the accessibility tree exposes for it; +// and the mouse moved onto the button, or off it, as a user points at it to show the hint. +// Adapted from spike-html-hosting-components (9fa5850): test/browser/support/glyph-button.ts and test/browser/support/glyphs.ts, as one module, its name and tokens read without the target size. +// See docs/testing.md + +import { until } from "@standards-lab/web-tooling/browser.js"; +import type { Page } from "@standards-lab/web-tooling/browser.js"; + +/** A glyph button as the page renders it. */ +export interface GlyphButton { + /** Whether it is a native button of the class glyph-button. */ + classed: boolean; + /** How many svg elements it holds, and whether the first is `markup`, node for node. */ + glyphs: number; + matches: boolean; + /** Its svg's aria-hidden, and whether the svg renders with a box. */ + hidden: string | null; + drawn: boolean; + /** Its border and surface, and a plain native button's in the same root. */ + surface: string; + native: string; + /** The interest target's id, whether interestForElement resolves to it in the button's own + * tree, its popover state, its text, and whether it is hidden from the accessibility tree. */ + interestfor: string | null; + resolves: boolean; + popover: string | null; + hint: string; + hintHidden: string | null; +} + +/** + * The glyph button the page expression `button` names, read in the page against `markup`, the + * default export of the icon's module, parsed in the page as the components parse it. + */ +export const glyphButton = (page: Page, button: string, markup: string): Promise => + page.evaluate(`(() => { + const button = ${button}; + const root = button.getRootNode(); + const plain = document.createElement("button"); + plain.type = "button"; + button.parentNode.append(plain); + const surface = (it) => { + const s = getComputedStyle(it); + return [s.borderTopStyle, s.borderTopWidth, s.borderTopColor, s.borderRadius, + s.backgroundColor, s.color].join(" "); + }; + const native = surface(plain); + plain.remove(); + const svgs = button.querySelectorAll("svg"); + const svg = svgs[0]; + const template = document.createElement("template"); + template.innerHTML = ${JSON.stringify(markup)}; + const box = svg?.getBoundingClientRect(); + const id = button.getAttribute("interestfor"); + const target = id === null ? null : root.getElementById(id); + return { + classed: button.localName === "button" && button.classList.contains("glyph-button"), + glyphs: svgs.length, + matches: svg ? template.content.firstElementChild.isEqualNode(svg) : false, + hidden: svg?.getAttribute("aria-hidden") ?? null, + drawn: (svg?.checkVisibility() ?? false) && box.width > 0 && box.height > 0, + surface: surface(button), + native, + interestfor: id, + resolves: target !== null && button.interestForElement === target, + popover: target?.getAttribute("popover") ?? null, + hint: (target?.textContent ?? "").replace(/\\s+/g, " ").trim(), + hintHidden: target?.getAttribute("aria-hidden") ?? null, + }; + })()`); + +interface Described { + ignored: boolean; + role?: { value: string }; + name?: { value: string }; + description?: { value: string }; +} + +/** The descriptions the page's accessibility tree exposes for the buttons named `name`. */ +export async function descriptions(page: Page, name: string): Promise { + const { nodes }: { nodes: Described[] } = await page.cdp("Accessibility.getFullAXTree", {}); + return nodes + .filter((node) => !node.ignored && node.role?.value === "button" && node.name?.value === name) + .map((node) => node.description?.value ?? ""); +} + +/** + * Whether the button's hint shows, as a popover open, and where, against the button's box: the + * page expression `button` names the button, its interest target the hint. + */ +export const hintShown = ( + page: Page, + button: string, +): Promise<{ open: boolean; below: boolean; above: boolean; overlaps: boolean }> => + page.evaluate(`(() => { + const button = ${button}; + const hint = button.interestForElement; + const b = button.getBoundingClientRect(); + const h = hint.getBoundingClientRect(); + return { + open: hint.matches(":popover-open"), + below: h.top >= b.bottom, + above: h.bottom <= b.top, + overlaps: h.left < b.right && h.right > b.left, + }; + })()`); + +/** Waits until the button's hint is open, or closed. */ +export const untilHint = (page: Page, button: string, open: boolean): Promise => + until(page, `(${button}).interestForElement?.matches(":popover-open") === ${open}`); + +/** Moves the mouse onto the center of the button the page expression `button` names. */ +export async function hover(page: Page, button: string): Promise { + const { x, y }: { x: number; y: number } = await page.evaluate(`(() => { + const { left, top, width, height } = (${button}).getBoundingClientRect(); + return { x: left + width / 2, y: top + height / 2 }; + })()`); + await page.cdp("Input.dispatchMouseEvent", { type: "mouseMoved", x, y }); +} + +/** Moves the mouse to the viewport's top-left corner, off any button. */ +export const pointAway = (page: Page): Promise => + page.cdp("Input.dispatchMouseEvent", { type: "mouseMoved", x: 0, y: 0 }); diff --git a/test/browser/support/served.ts b/test/browser/support/served.ts index 13714ef..c635685 100644 --- a/test/browser/support/served.ts +++ b/test/browser/support/served.ts @@ -10,8 +10,8 @@ import type { ServeOptions } from "@standards-lab/web-tooling/server.js"; /** The repository root, the served tree. */ export const root = join(import.meta.dirname, "../../.."); -/** The packages served under /deps/: lit, marked, and the foundation. */ -export const deps = ["lit", "marked", "@standards-lab/web-foundation"]; +/** The packages served under /deps/: lit, marked, the foundation, and the icons. */ +export const deps = ["lit", "marked", "@standards-lab/web-foundation", "@standards-lab/web-icons"]; /** The serve options for the repository: the root and its deps. */ export const served: ServeOptions = { root, deps }; diff --git a/test/browser/themes.test.ts b/test/browser/themes.test.ts index ad29d74..4f11553 100644 --- a/test/browser/themes.test.ts +++ b/test/browser/themes.test.ts @@ -86,14 +86,14 @@ const READ = `async (choice) => { return resolved; }; const tokens = Object.fromEntries(${JSON.stringify(TOKENS)}.map((token) => [token, resolve("var(" + token + ")")])); - const interaction = resolve("var(--interaction-color, var(--blue))"); + const interaction = resolve("var(--color-primary, var(--blue))"); const texts = []; const walk = (root, path) => { for (const element of root.querySelectorAll("*")) { if (element.shadowRoot) walk(element.shadowRoot, path + " " + element.localName); if (root === document) continue; const shows = [...element.childNodes].some((node) => node.nodeType === Node.TEXT_NODE && node.data.trim()) - || (element.matches("input, textarea") && (element.value || element.placeholder)); + || (element.matches("textarea, input:not([type=radio], [type=checkbox])") && (element.value || element.placeholder)); if (!shows || element.getClientRects().length === 0) continue; const style = getComputedStyle(element); if (style.visibility !== "visible") continue; @@ -225,7 +225,9 @@ describe("themes", { timeout: 120_000 }, () => { for (let press = 0; press < presses; press++) await tab(page); } - for (const name of pages.filter((page) => page !== "stage-timeline")) { + const unfocusable = { "stage-timeline": "sl-stage-timeline", shortcuts: "sl-shortcuts" }; + + for (const name of pages.filter((page) => !Object.hasOwn(unfocusable, page))) { test(`the ${name} page's focus ring, brought by the keyboard, is the interaction color each color profile resolves, light and dark`, async () => { const page = await open(name); try { @@ -250,17 +252,25 @@ describe("themes", { timeout: 120_000 }, () => { }); } - test("the stage timeline, which the focus ring cases skip, renders nothing the keyboard can focus", async () => { - const page = await open("stage-timeline"); - try { - const focusable: string[] = - await page.evaluate(`[...document.querySelectorAll("sl-stage-timeline")] - .flatMap((timeline) => [...timeline.shadowRoot.querySelectorAll("*")]) - .filter((element) => element.tabIndex >= 0) - .map((element) => element.localName)`); - assert.deepEqual(focusable, []); - } finally { - await page.close(); - } - }); + for (const [name, tag] of Object.entries(unfocusable)) { + test(`the ${name} page's ${tag}, which the focus ring cases skip, renders nothing the keyboard can focus`, async () => { + const page = await open(name); + try { + const found: { hosts: number; focusable: string[] } = await page.evaluate(`(() => { + const hosts = [...document.querySelectorAll("${tag}")]; + return { + hosts: hosts.length, + focusable: hosts + .flatMap((host) => [...host.shadowRoot.querySelectorAll("*")]) + .filter((element) => element.tabIndex >= 0) + .map((element) => element.localName), + }; + })()`); + assert.ok(found.hosts > 0, `${name}: no ${tag} rendered`); + assert.deepEqual(found.focusable, []); + } finally { + await page.close(); + } + }); + } }); diff --git a/test/fixtures/components.html b/test/fixtures/components.html index d108d31..a6d0939 100644 --- a/test/fixtures/components.html +++ b/test/fixtures/components.html @@ -1,9 +1,10 @@ + + + + + settings case + + + + + + +
        +

        Settings

        +

        + + + + +

        +
        +
        +

        First

        +

        A section to move to.

        +
        + +

        Keyboard shortcuts

        + + +
        + +

        Settings

        + + +
        + + diff --git a/test/fixtures/shortcuts.html b/test/fixtures/shortcuts.html new file mode 100644 index 0000000..ab1062e --- /dev/null +++ b/test/fixtures/shortcuts.html @@ -0,0 +1,81 @@ + + + + + + + shortcuts case + + + + + + +
        +

        Shortcuts

        +

        + + + End +

        +
        +
        +

        First

        +

        A section to move to.

        +

        End

        +

        The last section.

        +
        + +

        Keyboard shortcuts

        + + +
        + + diff --git a/test/unit/layers-tree.ts b/test/unit/layers-tree.ts index 8c644e7..b213a36 100644 --- a/test/unit/layers-tree.ts +++ b/test/unit/layers-tree.ts @@ -1,7 +1,7 @@ // The layer's import cases as one file tree in the repository's shape: a file per forbidden import // and form, each with the rules that catch it, and the imports the layer may make in the same -// layout. -// Adapted from spike-html-apps-components (10dde51): test/unit/layers-tree.ts, its sibling and above layers the stack's web-app-sdk and web-app-sdk-template. +// layout. The tree sits in a workspace directory beside webappgen's checkout, the layer above. +// Adapted from spike-html-apps-components (10dde51): test/unit/layers-tree.ts, its sibling and above layers the stack's web-app-sdk and webappgen, and web-icons below. // See docs/testing.md import { spawnSync } from "node:child_process"; @@ -24,8 +24,11 @@ const foundationManifest = readFileSync( "utf8", ); +const icons = components.replace(/components$/, "icons"); +const iconsManifest = readFileSync(join(root, "node_modules", icons, "package.json"), "utf8"); + const sdk = components.replace(/components$/, "app-sdk"); -const app = components.replace(/components$/, "app-sdk-template"); +const webappgen = "../webappgen/internal/starter/files/src/main.ts"; /** The layer table's rule. */ export const table = "boundaries/dependencies"; @@ -66,17 +69,25 @@ const undeclaredPackages = by([table, extraneous], { ...forms("src/forms/sdk", `${sdk}/client.js`), "src/lit-html.ts": `import { html } from "lit-html";`, ...forms("src/forms/lit-html", "lit-html/directives/repeat.js"), - "src/app.ts": `import { define } from "${app}/main.js";`, ...forms("src/forms/typescript", "typescript"), }); const ownName = by([table], forms("src/forms/self-name", `${components}/status-badge.js`)); +const siblingCheckout = by([table], { + "src/app.ts": `import { define } from "../${webappgen}";`, + ...forms("src/forms/app", `../../${webappgen}`), +}); + +const installedIcons = `../node_modules/${icons}`; + const relativeIntoNodeModules = by([table, relativePackages], { "src/foundation-path.ts": `import { define } from "${installedFoundation}/dist/dom.js";`, ...forms("src/forms/foundation-path", `../${installedFoundation}/dist/dom.js`), "src/foundation-sheet-path.ts": `import sheet from "${installedFoundation}/dist/baseline/reset.css" with { type: "css" };`, "src/lit-path.ts": `import "../node_modules/lit/index.js";`, + "src/icons-path.ts": `import x from "${installedIcons}/dist/octicon/x-16.js";`, + ...forms("src/forms/icons-path", `../${installedIcons}/dist/octicon/x-16.js`), }); const declarationValueImports = by([table], { @@ -109,6 +120,7 @@ const nonModuleCss = by([cssModule], { export const violations = { ...undeclaredPackages, ...ownName, + ...siblingCheckout, ...relativeIntoNodeModules, ...declarationValueImports, ...nonModuleCss, @@ -143,6 +155,11 @@ export const allowed: Record = { `await import("${foundation}/dom.js");`, `import type { BytesOptions } from "${foundation}/format.js";`, ].join("\n"), + "src/icons.ts": [ + `import x from "${icons}/octicon/x-16";`, + `export { default } from "${icons}/octicon/x-16";`, + `await import("${icons}/octicon/x-16");`, + ].join("\n"), "src/foundation-sheets.ts": [ `import reset from "${foundation}/baseline/reset.css" with { type: "css" };`, `import elements from "${foundation}/baseline/elements.css" with { "type": "css" };`, @@ -161,9 +178,10 @@ const targets = { "src/x.css": ".x {}", "dist/status-badge.js": "export {};", "dist/status-badge.d.ts": "export interface X {}", + [webappgen]: "export const define = () => {};", }; -const externals = ["lit", "lit-html", sdk, app, "typescript"]; +const externals = ["lit", "lit-html", sdk, "typescript"]; const stub = (name: string): Record => ({ "package.json": JSON.stringify({ name, @@ -198,7 +216,16 @@ const foundationFiles = { "dist/baseline/elements.css": ".elements {}", }; -/** Writes `files` and everything they import under `dir`, returning the code files under src/. */ +const iconsFiles = { + "package.json": iconsManifest, + "dist/octicon/x-16.js": 'export default "";', + "dist/octicon/x-16.d.ts": "declare const svg: string;\nexport default svg;", +}; + +/** + * Writes `files` and everything they import under `dir`, and webappgen's checkout beside it in + * `dir`'s parent, returning the code files under src/. + */ export function writeTree(dir: string, files: Record): string[] { const written: Record = { ...files, @@ -213,6 +240,9 @@ export function writeTree(dir: string, files: Record): string[] for (const [path, source] of Object.entries(foundationFiles)) { written[join("node_modules", foundation, path)] = source; } + for (const [path, source] of Object.entries(iconsFiles)) { + written[join("node_modules", icons, path)] = source; + } for (const [path, source] of Object.entries(written)) { mkdirSync(dirname(join(dir, path)), { recursive: true }); writeFileSync(join(dir, path), `${source}\n`); diff --git a/test/unit/layers.test.ts b/test/unit/layers.test.ts index ba207a7..d89ea50 100644 --- a/test/unit/layers.test.ts +++ b/test/unit/layers.test.ts @@ -4,7 +4,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { basename, join } from "node:path"; import { after, before, describe, test } from "node:test"; import { allowed, lint, manifest, sources, violations, watched, writeTree } from "./layers-tree.ts"; @@ -19,13 +19,15 @@ describe("layer imports", () => { const files = { ...sources(violations), ...allowed }; let scratch: string; + let dir: string; let found: Record; before(() => { scratch = mkdtempSync(join(tmpdir(), "layers-")); - const code = writeTree(scratch, files); - const report = lint(scratch); + dir = join(scratch, basename(root)); + const code = writeTree(dir, files); + const report = lint(dir); assert.deepEqual( - report.map((file) => file.filePath.slice(scratch.length + 1)).sort(), + report.map((file) => file.filePath.slice(dir.length + 1)).sort(), code.sort(), "ESLint lints every code file under src/", ); @@ -40,7 +42,7 @@ describe("layer imports", () => { const rules = [...new Set(file.messages.map((m) => m.ruleId))].filter( (id): id is string => id !== null && watched.includes(id), ); - if (rules.length > 0) found[file.filePath.slice(scratch.length + 1)] = rules.sort(); + if (rules.length > 0) found[file.filePath.slice(dir.length + 1)] = rules.sort(); } }); after(() => rmSync(scratch, { recursive: true, force: true })); diff --git a/test/unit/release.test.ts b/test/unit/release.test.ts index 96eade4..f4d8e27 100644 --- a/test/unit/release.test.ts +++ b/test/unit/release.test.ts @@ -1,4 +1,4 @@ -// Adapted from spike-html-apps-components (10dde51): test/unit/release.test.ts, on @standards-lab/web-foundation. +// Adapted from spike-html-apps-components (10dde51): test/unit/release.test.ts, on @standards-lab/web-foundation and @standards-lab/web-icons. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; @@ -76,8 +76,80 @@ describe("release pack", () => { assert.equal(packed.scripts, undefined); }); - const foundation = "@standards-lab/web-foundation"; - const github = "github:standards-lab/web-foundation"; + const peers = { + "@standards-lab/web-foundation": "standards-lab/web-foundation", + "@standards-lab/web-icons": "standards-lab/web-icons", + }; + const peerFaults = (peer: string, repository: string): Record => { + const github = `github:${repository}`; + const name = repository.split("/")[1]; + return { + "in dependencies": [ + (_, copy) => (copy.dependencies[peer] = `${github}#v0.3.0`), + `package.json declares ${peer} in dependencies, not as a peer`, + ], + "a peer by a git spec": [ + (_, copy) => (copy.peerDependencies[peer] = `${github}#v0.3.0`), + `package.json declares peer ${peer} ${github}#v0.3.0, not a caret range`, + ], + "a peer by a #semver: spec": [ + (_, copy) => (copy.peerDependencies[peer] = `${github}#semver:^0.3.0`), + `package.json declares peer ${peer} ${github}#semver:^0.3.0, not a caret range`, + ], + "a peer by an exact version": [ + (_, copy) => (copy.peerDependencies[peer] = "0.3.0"), + `package.json declares peer ${peer} 0.3.0, not a caret range`, + ], + "a peer by a tilde range": [ + (_, copy) => (copy.peerDependencies[peer] = "~0.3.0"), + `package.json declares peer ${peer} ~0.3.0, not a caret range`, + ], + "a peer by any version": [ + (_, copy) => (copy.peerDependencies[peer] = "*"), + `package.json declares peer ${peer} *, not a caret range`, + ], + "no peer": [ + (_, copy) => delete copy.peerDependencies[peer], + `package.json doesn't declare peer ${peer}`, + ], + "the devDependency by a #semver: range": [ + (_, copy) => (copy.devDependencies[peer] = `${github}#semver:^0.3.0`), + `package.json declares devDependency ${peer} ${github}#semver:^0.3.0, not an exact release tag`, + ], + "the devDependency by a branch": [ + (_, copy) => (copy.devDependencies[peer] = `${github}#main`), + `package.json declares devDependency ${peer} ${github}#main, not an exact release tag`, + ], + "the devDependency by a commit": [ + (_, copy) => (copy.devDependencies[peer] = `${github}#29d16c0`), + `package.json declares devDependency ${peer} ${github}#29d16c0, not an exact release tag`, + ], + "the devDependency by its default branch": [ + (_, copy) => (copy.devDependencies[peer] = github), + `package.json declares devDependency ${peer} ${github}, not an exact release tag`, + ], + "the devDependency from the registry": [ + (_, copy) => (copy.devDependencies[peer] = "0.3.0"), + `package.json declares devDependency ${peer} 0.3.0, not an exact release tag`, + ], + "the devDependency by a local path": [ + (_, copy) => (copy.devDependencies[peer] = `link:../${name}`), + `package.json declares devDependency ${peer} link:../${name}, not an exact release tag`, + ], + "the devDependency from another repository": [ + (_, copy) => (copy.devDependencies[peer] = "github:standards-lab/web-tooling#v0.3.0"), + `package.json declares devDependency ${peer} github:standards-lab/web-tooling#v0.3.0, not an exact release tag`, + ], + "the devDependency from another owner's fork": [ + (_, copy) => (copy.devDependencies[peer] = `github:fork/${name}#v0.3.0`), + `package.json declares devDependency ${peer} github:fork/${name}#v0.3.0, not an exact release tag`, + ], + "no devDependency": [ + (_, copy) => delete copy.devDependencies[peer], + `package.json doesn't declare devDependency ${peer}`, + ], + }; + }; const faults: Record = { "a source .css with no built copy": [ remove("dist/status-badge.css"), @@ -137,74 +209,10 @@ describe("release pack", () => { (_, copy) => (copy.dependencies.lit = "latest"), "package.json declares lit latest, not an exact pin", ], - "the foundation in dependencies": [ - (_, copy) => (copy.dependencies[foundation] = `${github}#v0.3.0`), - `package.json declares ${foundation} in dependencies, not as a peer`, - ], - "a peer by a git spec": [ - (_, copy) => (copy.peerDependencies[foundation] = `${github}#v0.3.0`), - `package.json declares peer ${foundation} ${github}#v0.3.0, not a caret range`, - ], - "a peer by a #semver: spec": [ - (_, copy) => (copy.peerDependencies[foundation] = `${github}#semver:^0.3.0`), - `package.json declares peer ${foundation} ${github}#semver:^0.3.0, not a caret range`, - ], - "a peer by an exact version": [ - (_, copy) => (copy.peerDependencies[foundation] = "0.3.0"), - `package.json declares peer ${foundation} 0.3.0, not a caret range`, - ], - "a peer by a tilde range": [ - (_, copy) => (copy.peerDependencies[foundation] = "~0.3.0"), - `package.json declares peer ${foundation} ~0.3.0, not a caret range`, - ], - "a peer by any version": [ - (_, copy) => (copy.peerDependencies[foundation] = "*"), - `package.json declares peer ${foundation} *, not a caret range`, - ], - "no peer": [ - (_, copy: Partial) => delete copy.peerDependencies, - `package.json doesn't declare peer ${foundation}`, - ], "an undeclared extra peer": [ (_, copy) => (copy.peerDependencies["lit-html"] = "^3.3.3"), "package.json declares peer lit-html, which no release needs", ], - "the devDependency by a #semver: range": [ - (_, copy) => (copy.devDependencies[foundation] = `${github}#semver:^0.3.0`), - `package.json declares devDependency ${foundation} ${github}#semver:^0.3.0, not an exact release tag`, - ], - "the devDependency by a branch": [ - (_, copy) => (copy.devDependencies[foundation] = `${github}#main`), - `package.json declares devDependency ${foundation} ${github}#main, not an exact release tag`, - ], - "the devDependency by a commit": [ - (_, copy) => (copy.devDependencies[foundation] = `${github}#29d16c0`), - `package.json declares devDependency ${foundation} ${github}#29d16c0, not an exact release tag`, - ], - "the devDependency by its default branch": [ - (_, copy) => (copy.devDependencies[foundation] = github), - `package.json declares devDependency ${foundation} ${github}, not an exact release tag`, - ], - "the devDependency from the registry": [ - (_, copy) => (copy.devDependencies[foundation] = "0.3.0"), - `package.json declares devDependency ${foundation} 0.3.0, not an exact release tag`, - ], - "the devDependency by a local path": [ - (_, copy) => (copy.devDependencies[foundation] = "link:../web-foundation"), - `package.json declares devDependency ${foundation} link:../web-foundation, not an exact release tag`, - ], - "the devDependency from another repository": [ - (_, copy) => (copy.devDependencies[foundation] = "github:standards-lab/web-tooling#v0.3.0"), - `package.json declares devDependency ${foundation} github:standards-lab/web-tooling#v0.3.0, not an exact release tag`, - ], - "the devDependency from another owner's fork": [ - (_, copy) => (copy.devDependencies[foundation] = "github:fork/web-foundation#v0.3.0"), - `package.json declares devDependency ${foundation} github:fork/web-foundation#v0.3.0, not an exact release tag`, - ], - "no devDependency": [ - (_, copy) => delete copy.devDependencies[foundation], - `package.json doesn't declare devDependency ${foundation}`, - ], "marked by a range": [ (_, copy) => (copy.dependencies.marked = "^18.1.2"), "package.json declares marked ^18.1.2, not an exact pin", @@ -248,25 +256,37 @@ describe("release pack", () => { "^0.0.3": ["v0.0.2", "v0.0.4", "v0.1.3"], "^1.2.0": ["v1.1.9", "v2.2.0"], }; - for (const [range, tags] of Object.entries(admitted)) { - for (const tag of tags) { - test(`a devDependency tag ${tag} passes a peer range ${range}`, () => { - const problems = faulted((_, copy) => { - copy.peerDependencies[foundation] = range; - copy.devDependencies[foundation] = `${github}#${tag}`; + for (const [peer, repository] of Object.entries(peers)) { + const github = `github:${repository}`; + for (const [range, tags] of Object.entries(admitted)) { + for (const tag of tags) { + test(`a ${peer} devDependency tag ${tag} passes a peer range ${range}`, () => { + const problems = faulted((_, copy) => { + copy.peerDependencies[peer] = range; + copy.devDependencies[peer] = `${github}#${tag}`; + }); + assert.deepEqual(problems, []); }); - assert.deepEqual(problems, []); - }); + } } - } - for (const [range, tags] of Object.entries(denied)) { - for (const tag of tags) { - test(`fails on a devDependency tag ${tag} with a peer range ${range}`, () => { - const problems = faulted((_, copy) => { - copy.peerDependencies[foundation] = range; - copy.devDependencies[foundation] = `${github}#${tag}`; + for (const [range, tags] of Object.entries(denied)) { + for (const tag of tags) { + test(`fails on a ${peer} devDependency tag ${tag} with a peer range ${range}`, () => { + const problems = faulted((_, copy) => { + copy.peerDependencies[peer] = range; + copy.devDependencies[peer] = `${github}#${tag}`; + }); + const problem = `package.json's devDependency ${peer} ${github}#${tag} is outside its peer range ${range}`; + assert.ok( + problems.includes(problem), + `expected: ${problem}\ngot: ${problems.join("\n")}`, + ); }); - const problem = `package.json's devDependency ${foundation} ${github}#${tag} is outside its peer range ${range}`; + } + } + for (const [fault, [change, problem]] of Object.entries(peerFaults(peer, repository))) { + test(`fails on ${peer} ${fault}`, () => { + const problems = faulted(change); assert.ok(problems.includes(problem), `expected: ${problem}\ngot: ${problems.join("\n")}`); }); } diff --git a/test/unit/release.ts b/test/unit/release.ts index 7190fb9..d79b97a 100644 --- a/test/unit/release.ts +++ b/test/unit/release.ts @@ -1,6 +1,6 @@ // A release's shape: a pack of the build checked against the sources, package.json's files and // exports as Node resolves them, the Apache 2.0 LICENSE its manifest declares, and its dependencies. -// Adapted from spike-html-apps-components (10dde51): test/unit/release.ts, on @standards-lab/web-foundation. +// Adapted from spike-html-apps-components (10dde51): test/unit/release.ts, on @standards-lab/web-foundation and @standards-lab/web-icons. // See docs/release.md import { execFileSync } from "node:child_process"; @@ -91,12 +91,16 @@ export function licenseProblems(root: string): string[] { return problems; } -const foundation = "@standards-lab/web-foundation"; +const peerRepositories: Record = { + "@standards-lab/web-foundation": "standards-lab/web-foundation", + "@standards-lab/web-icons": "standards-lab/web-icons", +}; const exactVersion = /^\d+\.\d+\.\d+$/; const dependencies = { lit: exactVersion, marked: exactVersion }; const caretRange = /^\^\d+\.\d+\.\d+$/; -const foundationTag = /^github:standards-lab\/web-foundation#(v\d+\.\d+\.\d+)$/; +const releaseTag = (repository: string) => + new RegExp(`^github:${repository}#(v\\d+\\.\\d+\\.\\d+)$`); /** Whether the caret range, ^x.y.z, admits the version, x.y.z or its tag vx.y.z, as npm reads it. */ export function caretAdmits(range: string, version: string): boolean { @@ -125,34 +129,44 @@ export function dependencyProblems(root: string): string[] { } } for (const name of Object.keys(declared)) { - if (name === foundation) { - problems.push(`package.json declares ${foundation} in dependencies, not as a peer`); + if (name in peerRepositories) { + problems.push(`package.json declares ${name} in dependencies, not as a peer`); } else if (!(name in dependencies)) { problems.push(`package.json declares ${name}, which no release needs`); } } for (const name of Object.keys(peers)) { - if (name !== foundation) + if (!(name in peerRepositories)) problems.push(`package.json declares peer ${name}, which no release needs`); } - const range = caretRange.test(peers[foundation]) ? peers[foundation] : undefined; - if (!(foundation in peers)) problems.push(`package.json doesn't declare peer ${foundation}`); + for (const [peer, repository] of Object.entries(peerRepositories)) { + problems.push(...peerProblems(peer, repository, peers, dev)); + } + return problems; +} + +function peerProblems( + peer: string, + repository: string, + peers: Record, + dev: Record, +): string[] { + const problems: string[] = []; + const range = caretRange.test(peers[peer]) ? peers[peer] : undefined; + if (!(peer in peers)) problems.push(`package.json doesn't declare peer ${peer}`); else if (!range) { - problems.push( - `package.json declares peer ${foundation} ${peers[foundation]}, not a caret range`, - ); + problems.push(`package.json declares peer ${peer} ${peers[peer]}, not a caret range`); } - const tag = dev[foundation]?.match(foundationTag); - if (!(foundation in dev)) - problems.push(`package.json doesn't declare devDependency ${foundation}`); + const tag = dev[peer]?.match(releaseTag(repository)); + if (!(peer in dev)) problems.push(`package.json doesn't declare devDependency ${peer}`); else if (!tag) { problems.push( - `package.json declares devDependency ${foundation} ${dev[foundation]}, not an exact release tag`, + `package.json declares devDependency ${peer} ${dev[peer]}, not an exact release tag`, ); } if (range && tag && !caretAdmits(range, tag[1])) { problems.push( - `package.json's devDependency ${foundation} ${dev[foundation]} is outside its peer range ${peers[foundation]}`, + `package.json's devDependency ${peer} ${dev[peer]} is outside its peer range ${peers[peer]}`, ); } return problems;