Skip to content

Keep your coding agent up to date with the latest web best practices

Release v0.0.195

github-actions[bot]65e7edd67e77
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
index 1af2480..3b16195 100644
--- a/.agents/plugins/marketplace.json
+++ b/.agents/plugins/marketplace.json
@@ -15,7 +15,7 @@
"authentication": "ON_INSTALL"
},
"category": "Developer Tools",
- "version": "0.0.194"
+ "version": "0.0.195"
}
]
}
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index b97ec48..07cf7d8 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -9,7 +9,7 @@
"name": "modern-web-guidance",
"source": "./",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.194"
+ "version": "0.0.195"
}
]
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 81b3bb6..3f8511b 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.194",
+ "version": "0.0.195",
"author": {
"name": "Google Chrome"
}
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 7590728..d62315a 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "modern-web-guidance",
- "version": "0.0.194",
+ "version": "0.0.195",
"description": "Keep your coding agent up to date with the latest web best practices",
"author": {
"name": "Google Chrome",
diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json
index c20f77f..1cbd889 100644
--- a/.cursor-plugin/plugin.json
+++ b/.cursor-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Supported by the Google Chrome team, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
- "version": "0.0.194",
+ "version": "0.0.195",
"author": {
"name": "Google Chrome"
}
diff --git a/.github/plugin/plugin.json b/.github/plugin/plugin.json
index c20f77f..1cbd889 100644
--- a/.github/plugin/plugin.json
+++ b/.github/plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Supported by the Google Chrome team, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
- "version": "0.0.194",
+ "version": "0.0.195",
"author": {
"name": "Google Chrome"
}
diff --git a/.grok-plugin/marketplace.json b/.grok-plugin/marketplace.json
index b71924a..54f2118 100644
--- a/.grok-plugin/marketplace.json
+++ b/.grok-plugin/marketplace.json
@@ -8,7 +8,7 @@
"name": "modern-web-guidance",
"source": "./",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.194"
+ "version": "0.0.195"
}
]
}
diff --git a/README.md b/README.md
index fc19a8f..3700f21 100644
--- a/README.md
+++ b/README.md
@@ -85,52 +85,53 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
#### The full list
<details>
-<summary><strong>212 modern web features</strong></summary>
+<summary><strong>217 modern web features</strong></summary>
-### CSS & Layout (120 features)
+### CSS & Layout (123 features)
| | | |
| :--- | :--- | :--- |
-| [::backdrop](https://web-platform-dx.github.io/web-features-explorer/features/backdrop/) | [Content](https://web-platform-dx.github.io/web-features-explorer/features/content/) | [overlay](https://web-platform-dx.github.io/web-features-explorer/features/overlay/) |
-| [::file-selector-button](https://web-platform-dx.github.io/web-features-explorer/features/file-selector-button/) | [content-visibility](https://web-platform-dx.github.io/web-features-explorer/features/content-visibility/) | [overscroll-behavior](https://web-platform-dx.github.io/web-features-explorer/features/overscroll-behavior/) |
-| [::placeholder](https://web-platform-dx.github.io/web-features-explorer/features/placeholder/) | [contrast-color()](https://web-platform-dx.github.io/web-features-explorer/features/contrast-color/) | [prefers-color-scheme media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-color-scheme/) |
-| [::selection](https://web-platform-dx.github.io/web-features-explorer/features/selection/) | [Cross-document view transitions](https://web-platform-dx.github.io/web-features-explorer/features/cross-document-view-transitions/) | [prefers-contrast media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-contrast/) |
-| [:dir()](https://web-platform-dx.github.io/web-features-explorer/features/dir-pseudo/) | [currentColor](https://web-platform-dx.github.io/web-features-explorer/features/currentcolor/) | [prefers-reduced-motion media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-reduced-motion/) |
-| [:has()](https://web-platform-dx.github.io/web-features-explorer/features/has/) | [Custom highlights](https://web-platform-dx.github.io/web-features-explorer/features/highlight/) | [progress()](https://web-platform-dx.github.io/web-features-explorer/features/progress-function/) |
-| [:host-context()](https://web-platform-dx.github.io/web-features-explorer/features/host-context/) | [Custom properties](https://web-platform-dx.github.io/web-features-explorer/features/custom-properties/) | [Relative colors](https://web-platform-dx.github.io/web-features-explorer/features/relative-color/) |
-| [:is()](https://web-platform-dx.github.io/web-features-explorer/features/is/) | [display animation](https://web-platform-dx.github.io/web-features-explorer/features/display-animation/) | [rem](https://web-platform-dx.github.io/web-features-explorer/features/rem/) |
-| [:modal](https://web-platform-dx.github.io/web-features-explorer/features/modal/) | [em unit](https://web-platform-dx.github.io/web-features-explorer/features/em-unit/) | [resize (CSS property)](https://web-platform-dx.github.io/web-features-explorer/features/resize/) |
-| [:not()](https://web-platform-dx.github.io/web-features-explorer/features/not/) | [field-sizing](https://web-platform-dx.github.io/web-features-explorer/features/field-sizing/) | [revert](https://web-platform-dx.github.io/web-features-explorer/features/revert-value/) |
+| [::backdrop](https://web-platform-dx.github.io/web-features-explorer/features/backdrop/) | [content-visibility](https://web-platform-dx.github.io/web-features-explorer/features/content-visibility/) | [overscroll-behavior](https://web-platform-dx.github.io/web-features-explorer/features/overscroll-behavior/) |
+| [::file-selector-button](https://web-platform-dx.github.io/web-features-explorer/features/file-selector-button/) | [contrast-color()](https://web-platform-dx.github.io/web-features-explorer/features/contrast-color/) | [prefers-color-scheme media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-color-scheme/) |
+| [::placeholder](https://web-platform-dx.github.io/web-features-explorer/features/placeholder/) | [Cross-document view transitions](https://web-platform-dx.github.io/web-features-explorer/features/cross-document-view-transitions/) | [prefers-contrast media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-contrast/) |
+| [::selection](https://web-platform-dx.github.io/web-features-explorer/features/selection/) | [currentColor](https://web-platform-dx.github.io/web-features-explorer/features/currentcolor/) | [prefers-reduced-motion media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-reduced-motion/) |
+| [:dir()](https://web-platform-dx.github.io/web-features-explorer/features/dir-pseudo/) | [Custom highlights](https://web-platform-dx.github.io/web-features-explorer/features/highlight/) | [progress()](https://web-platform-dx.github.io/web-features-explorer/features/progress-function/) |
+| [:has()](https://web-platform-dx.github.io/web-features-explorer/features/has/) | [Custom properties](https://web-platform-dx.github.io/web-features-explorer/features/custom-properties/) | [Relative colors](https://web-platform-dx.github.io/web-features-explorer/features/relative-color/) |
+| [:host-context()](https://web-platform-dx.github.io/web-features-explorer/features/host-context/) | [display animation](https://web-platform-dx.github.io/web-features-explorer/features/display-animation/) | [rem](https://web-platform-dx.github.io/web-features-explorer/features/rem/) |
+| [:is()](https://web-platform-dx.github.io/web-features-explorer/features/is/) | [Element-scoped view transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions-element-scoped/) | [resize (CSS property)](https://web-platform-dx.github.io/web-features-explorer/features/resize/) |
+| [:modal](https://web-platform-dx.github.io/web-features-explorer/features/modal/) | [em unit](https://web-platform-dx.github.io/web-features-explorer/features/em-unit/) | [revert](https://web-platform-dx.github.io/web-features-explorer/features/revert-value/) |
+| [:not()](https://web-platform-dx.github.io/web-features-explorer/features/not/) | [field-sizing](https://web-platform-dx.github.io/web-features-explorer/features/field-sizing/) | [revert-rule](https://web-platform-dx.github.io/web-features-explorer/features/revert-rule/) |
| [:nth-child() of &lt;selector>](https://web-platform-dx.github.io/web-features-explorer/features/nth-child-of/) | [filter](https://web-platform-dx.github.io/web-features-explorer/features/filter/) | [Scroll marker target pseudo-classes](https://web-platform-dx.github.io/web-features-explorer/features/scroll-marker-targets/) |
| [:placeholder-shown](https://web-platform-dx.github.io/web-features-explorer/features/placeholder-shown/) | [flex-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/flexbox-flex-wrap-balance/) | [Scroll method promises](https://web-platform-dx.github.io/web-features-explorer/features/scroll-promises/) |
| [:user-valid and :user-invalid](https://web-platform-dx.github.io/web-features-explorer/features/user-pseudos/) | [Flexbox](https://web-platform-dx.github.io/web-features-explorer/features/flexbox/) | [Scroll snap](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap/) |
| [:where()](https://web-platform-dx.github.io/web-features-explorer/features/where/) | [font-size](https://web-platform-dx.github.io/web-features-explorer/features/font-size/) | [Scroll snap events](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap-events/) |
-| [@function](https://web-platform-dx.github.io/web-features-explorer/features/function/) | [font-size-adjust](https://web-platform-dx.github.io/web-features-explorer/features/font-size-adjust/) | [Scroll-driven animations](https://web-platform-dx.github.io/web-features-explorer/features/scroll-driven-animations/) |
-| [@scope](https://web-platform-dx.github.io/web-features-explorer/features/scope/) | [Forced colors](https://web-platform-dx.github.io/web-features-explorer/features/forced-colors/) | [scroll-initial-target](https://web-platform-dx.github.io/web-features-explorer/features/scroll-initial-target/) |
-| [@starting-style](https://web-platform-dx.github.io/web-features-explorer/features/starting-style/) | [Gradient interpolation](https://web-platform-dx.github.io/web-features-explorer/features/gradient-interpolation/) | [scroll-target-group](https://web-platform-dx.github.io/web-features-explorer/features/scroll-target-group/) |
-| [@supports](https://web-platform-dx.github.io/web-features-explorer/features/supports/) | [Gradients](https://web-platform-dx.github.io/web-features-explorer/features/gradients/) | [scrollbar-color](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-color/) |
-| [accent-color](https://web-platform-dx.github.io/web-features-explorer/features/accent-color/) | [Grid](https://web-platform-dx.github.io/web-features-explorer/features/grid/) | [scrollbar-gutter](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-gutter/) |
-| [Active view transition](https://web-platform-dx.github.io/web-features-explorer/features/active-view-transition/) | [Grid lanes](https://web-platform-dx.github.io/web-features-explorer/features/grid-lanes/) | [scrollbar-width](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-width/) |
-| [Alt text for generated content](https://web-platform-dx.github.io/web-features-explorer/features/alt-text-generated-content/) | [image-set()](https://web-platform-dx.github.io/web-features-explorer/features/image-set/) | [scrollend](https://web-platform-dx.github.io/web-features-explorer/features/scrollend/) |
-| [Anchor position container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-anchor-position-queries/) | [Individual transform properties](https://web-platform-dx.github.io/web-features-explorer/features/individual-transforms/) | [scrollIntoView()](https://web-platform-dx.github.io/web-features-explorer/features/scroll-into-view/) |
-| [Anchor positioning](https://web-platform-dx.github.io/web-features-explorer/features/anchor-positioning/) | [inherit](https://web-platform-dx.github.io/web-features-explorer/features/inherit-value/) | [Shadow parts](https://web-platform-dx.github.io/web-features-explorer/features/shadow-parts/) |
-| [Animations (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/animations-css/) | [initial](https://web-platform-dx.github.io/web-features-explorer/features/initial-value/) | [sibling-count() and sibling-index()](https://web-platform-dx.github.io/web-features-explorer/features/sibling-count/) |
-| [appearance](https://web-platform-dx.github.io/web-features-explorer/features/appearance/) | [interpolate-size](https://web-platform-dx.github.io/web-features-explorer/features/interpolate-size/) | [Sticky positioning](https://web-platform-dx.github.io/web-features-explorer/features/sticky-positioning/) |
-| [aspect-ratio](https://web-platform-dx.github.io/web-features-explorer/features/aspect-ratio/) | [isolation](https://web-platform-dx.github.io/web-features-explorer/features/isolation/) | [Subgrid](https://web-platform-dx.github.io/web-features-explorer/features/subgrid/) |
-| [at-rule()](https://web-platform-dx.github.io/web-features-explorer/features/supports-at-rule/) | [Lab and LCH](https://web-platform-dx.github.io/web-features-explorer/features/lab/) | [System colors](https://web-platform-dx.github.io/web-features-explorer/features/system-color/) |
-| [attr()](https://web-platform-dx.github.io/web-features-explorer/features/attr/) | [light-dark()](https://web-platform-dx.github.io/web-features-explorer/features/light-dark/) | [text-box](https://web-platform-dx.github.io/web-features-explorer/features/text-box/) |
-| [background-blend-mode](https://web-platform-dx.github.io/web-features-explorer/features/background-blend-mode/) | [line-clamp](https://web-platform-dx.github.io/web-features-explorer/features/line-clamp/) | [text-wrap](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap/) |
-| [border-radius](https://web-platform-dx.github.io/web-features-explorer/features/border-radius/) | [line-height](https://web-platform-dx.github.io/web-features-explorer/features/line-height/) | [text-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-balance/) |
-| [box-shadow](https://web-platform-dx.github.io/web-features-explorer/features/box-shadow/) | [linear() easing](https://web-platform-dx.github.io/web-features-explorer/features/linear-easing/) | [text-wrap: pretty](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-pretty/) |
-| [calc-size()](https://web-platform-dx.github.io/web-features-explorer/features/calc-size/) | [Logical properties](https://web-platform-dx.github.io/web-features-explorer/features/logical-properties/) | [transition-behavior](https://web-platform-dx.github.io/web-features-explorer/features/transition-behavior/) |
-| [Cascade layers](https://web-platform-dx.github.io/web-features-explorer/features/cascade-layers/) | [Masks](https://web-platform-dx.github.io/web-features-explorer/features/masks/) | [Transitions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/transitions/) |
-| [clip-path](https://web-platform-dx.github.io/web-features-explorer/features/clip-path/) | [min(), max(), and clamp()](https://web-platform-dx.github.io/web-features-explorer/features/min-max-clamp/) | [Trigonometric functions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/trig-functions/) |
-| [color-mix()](https://web-platform-dx.github.io/web-features-explorer/features/color-mix/) | [mix-blend-mode](https://web-platform-dx.github.io/web-features-explorer/features/mix-blend-mode/) | [unset](https://web-platform-dx.github.io/web-features-explorer/features/unset-value/) |
-| [color-scheme](https://web-platform-dx.github.io/web-features-explorer/features/color-scheme/) | [Nesting](https://web-platform-dx.github.io/web-features-explorer/features/nesting/) | [user-select](https://web-platform-dx.github.io/web-features-explorer/features/user-select/) |
-| [Conic gradients](https://web-platform-dx.github.io/web-features-explorer/features/conic-gradients/) | [Oklab and OkLCh](https://web-platform-dx.github.io/web-features-explorer/features/oklab/) | [View transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions/) |
-| [Container queries (size)](https://web-platform-dx.github.io/web-features-explorer/features/container-queries/) | [overflow-clip-margin](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip-margin/) | [view-transition-class](https://web-platform-dx.github.io/web-features-explorer/features/view-transition-class/) |
-| [Container scroll-state queries](https://web-platform-dx.github.io/web-features-explorer/features/container-scroll-state-queries/) | [overflow-wrap](https://web-platform-dx.github.io/web-features-explorer/features/overflow-wrap/) | [Viewport units](https://web-platform-dx.github.io/web-features-explorer/features/viewport-units/) |
-| [Container style queries](https://web-platform-dx.github.io/web-features-explorer/features/container-style-queries/) | [overflow: clip](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip/) | [Web animations](https://web-platform-dx.github.io/web-features-explorer/features/web-animations/) |
+| [@function](https://web-platform-dx.github.io/web-features-explorer/features/function/) | [font-size-adjust](https://web-platform-dx.github.io/web-features-explorer/features/font-size-adjust/) | [scroll-axis-lock](https://web-platform-dx.github.io/web-features-explorer/features/scroll-axis-lock/) |
+| [@scope](https://web-platform-dx.github.io/web-features-explorer/features/scope/) | [Forced colors](https://web-platform-dx.github.io/web-features-explorer/features/forced-colors/) | [Scroll-driven animations](https://web-platform-dx.github.io/web-features-explorer/features/scroll-driven-animations/) |
+| [@starting-style](https://web-platform-dx.github.io/web-features-explorer/features/starting-style/) | [Gradient interpolation](https://web-platform-dx.github.io/web-features-explorer/features/gradient-interpolation/) | [scroll-initial-target](https://web-platform-dx.github.io/web-features-explorer/features/scroll-initial-target/) |
+| [@supports](https://web-platform-dx.github.io/web-features-explorer/features/supports/) | [Gradients](https://web-platform-dx.github.io/web-features-explorer/features/gradients/) | [scroll-target-group](https://web-platform-dx.github.io/web-features-explorer/features/scroll-target-group/) |
+| [accent-color](https://web-platform-dx.github.io/web-features-explorer/features/accent-color/) | [Grid](https://web-platform-dx.github.io/web-features-explorer/features/grid/) | [scrollbar-color](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-color/) |
+| [Active view transition](https://web-platform-dx.github.io/web-features-explorer/features/active-view-transition/) | [Grid lanes](https://web-platform-dx.github.io/web-features-explorer/features/grid-lanes/) | [scrollbar-gutter](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-gutter/) |
+| [Alt text for generated content](https://web-platform-dx.github.io/web-features-explorer/features/alt-text-generated-content/) | [image-set()](https://web-platform-dx.github.io/web-features-explorer/features/image-set/) | [scrollbar-width](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-width/) |
+| [Anchor position container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-anchor-position-queries/) | [Individual transform properties](https://web-platform-dx.github.io/web-features-explorer/features/individual-transforms/) | [scrollend](https://web-platform-dx.github.io/web-features-explorer/features/scrollend/) |
+| [Anchor positioning](https://web-platform-dx.github.io/web-features-explorer/features/anchor-positioning/) | [inherit](https://web-platform-dx.github.io/web-features-explorer/features/inherit-value/) | [scrollIntoView()](https://web-platform-dx.github.io/web-features-explorer/features/scroll-into-view/) |
+| [Animations (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/animations-css/) | [initial](https://web-platform-dx.github.io/web-features-explorer/features/initial-value/) | [Shadow parts](https://web-platform-dx.github.io/web-features-explorer/features/shadow-parts/) |
+| [appearance](https://web-platform-dx.github.io/web-features-explorer/features/appearance/) | [interpolate-size](https://web-platform-dx.github.io/web-features-explorer/features/interpolate-size/) | [sibling-count() and sibling-index()](https://web-platform-dx.github.io/web-features-explorer/features/sibling-count/) |
+| [aspect-ratio](https://web-platform-dx.github.io/web-features-explorer/features/aspect-ratio/) | [isolation](https://web-platform-dx.github.io/web-features-explorer/features/isolation/) | [Sticky positioning](https://web-platform-dx.github.io/web-features-explorer/features/sticky-positioning/) |
+| [at-rule()](https://web-platform-dx.github.io/web-features-explorer/features/supports-at-rule/) | [Lab and LCH](https://web-platform-dx.github.io/web-features-explorer/features/lab/) | [Subgrid](https://web-platform-dx.github.io/web-features-explorer/features/subgrid/) |
+| [attr()](https://web-platform-dx.github.io/web-features-explorer/features/attr/) | [light-dark()](https://web-platform-dx.github.io/web-features-explorer/features/light-dark/) | [System colors](https://web-platform-dx.github.io/web-features-explorer/features/system-color/) |
+| [background-blend-mode](https://web-platform-dx.github.io/web-features-explorer/features/background-blend-mode/) | [line-clamp](https://web-platform-dx.github.io/web-features-explorer/features/line-clamp/) | [text-box](https://web-platform-dx.github.io/web-features-explorer/features/text-box/) |
+| [border-radius](https://web-platform-dx.github.io/web-features-explorer/features/border-radius/) | [line-height](https://web-platform-dx.github.io/web-features-explorer/features/line-height/) | [text-wrap](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap/) |
+| [box-shadow](https://web-platform-dx.github.io/web-features-explorer/features/box-shadow/) | [linear() easing](https://web-platform-dx.github.io/web-features-explorer/features/linear-easing/) | [text-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-balance/) |
+| [calc-size()](https://web-platform-dx.github.io/web-features-explorer/features/calc-size/) | [Logical properties](https://web-platform-dx.github.io/web-features-explorer/features/logical-properties/) | [text-wrap: pretty](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-pretty/) |
+| [Cascade layers](https://web-platform-dx.github.io/web-features-explorer/features/cascade-layers/) | [Masks](https://web-platform-dx.github.io/web-features-explorer/features/masks/) | [transition-behavior](https://web-platform-dx.github.io/web-features-explorer/features/transition-behavior/) |
+| [clip-path](https://web-platform-dx.github.io/web-features-explorer/features/clip-path/) | [min(), max(), and clamp()](https://web-platform-dx.github.io/web-features-explorer/features/min-max-clamp/) | [Transitions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/transitions/) |
+| [color-mix()](https://web-platform-dx.github.io/web-features-explorer/features/color-mix/) | [mix-blend-mode](https://web-platform-dx.github.io/web-features-explorer/features/mix-blend-mode/) | [Trigonometric functions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/trig-functions/) |
+| [color-scheme](https://web-platform-dx.github.io/web-features-explorer/features/color-scheme/) | [Nesting](https://web-platform-dx.github.io/web-features-explorer/features/nesting/) | [unset](https://web-platform-dx.github.io/web-features-explorer/features/unset-value/) |
+| [Conic gradients](https://web-platform-dx.github.io/web-features-explorer/features/conic-gradients/) | [Oklab and OkLCh](https://web-platform-dx.github.io/web-features-explorer/features/oklab/) | [user-select](https://web-platform-dx.github.io/web-features-explorer/features/user-select/) |
+| [Container queries (size)](https://web-platform-dx.github.io/web-features-explorer/features/container-queries/) | [overflow-clip-margin](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip-margin/) | [View transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions/) |
+| [Container scroll-state queries](https://web-platform-dx.github.io/web-features-explorer/features/container-scroll-state-queries/) | [overflow-wrap](https://web-platform-dx.github.io/web-features-explorer/features/overflow-wrap/) | [view-transition-class](https://web-platform-dx.github.io/web-features-explorer/features/view-transition-class/) |
+| [Container style queries](https://web-platform-dx.github.io/web-features-explorer/features/container-style-queries/) | [overflow: clip](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip/) | [Viewport units](https://web-platform-dx.github.io/web-features-explorer/features/viewport-units/) |
+| [Content](https://web-platform-dx.github.io/web-features-explorer/features/content/) | [overlay](https://web-platform-dx.github.io/web-features-explorer/features/overlay/) | [Web animations](https://web-platform-dx.github.io/web-features-explorer/features/web-animations/) |
### HTML & DOM (34 features)
@@ -149,35 +150,35 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
| [&lt;progress>](https://web-platform-dx.github.io/web-features-explorer/features/progress/) | [HTML setter methods](https://web-platform-dx.github.io/web-features-explorer/features/html-setters/) | |
| [&lt;slot>](https://web-platform-dx.github.io/web-features-explorer/features/slot/) | [HTML streaming setters](https://web-platform-dx.github.io/web-features-explorer/features/html-streaming-setters/) | |
-### JavaScript & APIs (58 features)
+### JavaScript & APIs (60 features)
| | | |
| :--- | :--- | :--- |
-| [&lt;meta name="text-scale">](https://web-platform-dx.github.io/web-features-explorer/features/meta-text-scale/) | [Intl.DurationFormat](https://web-platform-dx.github.io/web-features-explorer/features/intl-duration-format/) | [Soft navigation performance entries](https://web-platform-dx.github.io/web-features-explorer/features/soft-navigations/) |
-| [&lt;template for>](https://web-platform-dx.github.io/web-features-explorer/features/template-for/) | [Keyboard events](https://web-platform-dx.github.io/web-features-explorer/features/keyboard-events/) | [Speculation rules](https://web-platform-dx.github.io/web-features-explorer/features/speculation-rules/) |
-| [AbortController and AbortSignal](https://web-platform-dx.github.io/web-features-explorer/features/aborting/) | [Language detector](https://web-platform-dx.github.io/web-features-explorer/features/languagedetector/) | [Summarizer](https://web-platform-dx.github.io/web-features-explorer/features/summarizer/) |
-| [ARIA attribute reflection](https://web-platform-dx.github.io/web-features-explorer/features/aria-attribute-reflection/) | [LanguageModel](https://web-platform-dx.github.io/web-features-explorer/features/languagemodel/) | [SVG](https://web-platform-dx.github.io/web-features-explorer/features/svg/) |
-| [autocorrect](https://web-platform-dx.github.io/web-features-explorer/features/autocorrect/) | [Lazy-loading images and iframes](https://web-platform-dx.github.io/web-features-explorer/features/loading-lazy/) | [Temporal](https://web-platform-dx.github.io/web-features-explorer/features/temporal/) |
-| [Connection allowlists](https://web-platform-dx.github.io/web-features-explorer/features/connection-allowlists/) | [light-dark() image values](https://web-platform-dx.github.io/web-features-explorer/features/light-dark-image/) | [text-fit](https://web-platform-dx.github.io/web-features-explorer/features/text-fit/) |
-| [corner-shape](https://web-platform-dx.github.io/web-features-explorer/features/corner-shape/) | [Local network access](https://web-platform-dx.github.io/web-features-explorer/features/local-network-access/) | [Top-level await](https://web-platform-dx.github.io/web-features-explorer/features/top-level-await/) |
-| [document.modelContext](https://web-platform-dx.github.io/web-features-explorer/features/document-modelcontext/) | [Long animation frames performance entries](https://web-platform-dx.github.io/web-features-explorer/features/long-animation-frames/) | [touch-action](https://web-platform-dx.github.io/web-features-explorer/features/touch-action/) |
-| [email-verification](https://web-platform-dx.github.io/web-features-explorer/features/tmp-email-verification/) | [Navigation API](https://web-platform-dx.github.io/web-features-explorer/features/navigation/) | [Translator](https://web-platform-dx.github.io/web-features-explorer/features/translator/) |
-| [enterkeyhint](https://web-platform-dx.github.io/web-features-explorer/features/enterkeyhint/) | [Origin](https://web-platform-dx.github.io/web-features-explorer/features/origin/) | [Trusted types](https://web-platform-dx.github.io/web-features-explorer/features/trusted-types/) |
-| [Event timing performance entries](https://web-platform-dx.github.io/web-features-explorer/features/event-timing/) | [Page visibility](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility/) | [User agent client hints](https://web-platform-dx.github.io/web-features-explorer/features/ua-client-hints/) |
-| [Federated credential management](https://web-platform-dx.github.io/web-features-explorer/features/fedcm/) | [Page visibility state performance entries](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility-state/) | [Web app origin migration](https://web-platform-dx.github.io/web-features-explorer/features/app-migration/) |
-| [Fetch](https://web-platform-dx.github.io/web-features-explorer/features/fetch/) | [Partitioned cookies](https://web-platform-dx.github.io/web-features-explorer/features/partitioned-cookies/) | [Web authentication](https://web-platform-dx.github.io/web-features-explorer/features/webauthn/) |
-| [fetchLater](https://web-platform-dx.github.io/web-features-explorer/features/fetchlater/) | [Permissions policy](https://web-platform-dx.github.io/web-features-explorer/features/permissions-policy/) | [Web authentication signal methods](https://web-platform-dx.github.io/web-features-explorer/features/webauthn-signals/) |
-| [Form-associated WebMCP attributes](https://web-platform-dx.github.io/web-features-explorer/features/declarative-webmcp/) | [Pointer Events](https://web-platform-dx.github.io/web-features-explorer/features/pointer-events-api/) | [Web Cryptography](https://web-platform-dx.github.io/web-features-explorer/features/web-cryptography/) |
-| [HTML processing instructions](https://web-platform-dx.github.io/web-features-explorer/features/html-processing-instructions/) | [Registered custom properties](https://web-platform-dx.github.io/web-features-explorer/features/registered-custom-properties/) | [WebAssembly](https://web-platform-dx.github.io/web-features-explorer/features/wasm/) |
-| [image()](https://web-platform-dx.github.io/web-features-explorer/features/image-function/) | [Resize observer](https://web-platform-dx.github.io/web-features-explorer/features/resize-observer/) | [webcrypto-modern-algos](https://web-platform-dx.github.io/web-features-explorer/features/tmp-webcrypto-modern-algos/) |
-| [inputmode](https://web-platform-dx.github.io/web-features-explorer/features/inputmode/) | [Sanitizer API](https://web-platform-dx.github.io/web-features-explorer/features/sanitizer/) | [WebOTP](https://web-platform-dx.github.io/web-features-explorer/features/web-otp/) |
-| [Interaction contentful paint performance entries](https://web-platform-dx.github.io/web-features-explorer/features/interaction-contentful-paint/) | [Scheduler API](https://web-platform-dx.github.io/web-features-explorer/features/scheduler/) | |
-| [Intersection observer](https://web-platform-dx.github.io/web-features-explorer/features/intersection-observer/) | [Small, large, and dynamic viewport units](https://web-platform-dx.github.io/web-features-explorer/features/viewport-unit-variants/) | |
+| [&lt;meta name="text-scale">](https://web-platform-dx.github.io/web-features-explorer/features/meta-text-scale/) | [Intersection observer](https://web-platform-dx.github.io/web-features-explorer/features/intersection-observer/) | [Scheduler API](https://web-platform-dx.github.io/web-features-explorer/features/scheduler/) |
+| [&lt;template for>](https://web-platform-dx.github.io/web-features-explorer/features/template-for/) | [Intl.DurationFormat](https://web-platform-dx.github.io/web-features-explorer/features/intl-duration-format/) | [Small, large, and dynamic viewport units](https://web-platform-dx.github.io/web-features-explorer/features/viewport-unit-variants/) |
+| [AbortController and AbortSignal](https://web-platform-dx.github.io/web-features-explorer/features/aborting/) | [Keyboard events](https://web-platform-dx.github.io/web-features-explorer/features/keyboard-events/) | [Soft navigation performance entries](https://web-platform-dx.github.io/web-features-explorer/features/soft-navigations/) |
+| [ARIA attribute reflection](https://web-platform-dx.github.io/web-features-explorer/features/aria-attribute-reflection/) | [Language detector](https://web-platform-dx.github.io/web-features-explorer/features/languagedetector/) | [Speculation rules](https://web-platform-dx.github.io/web-features-explorer/features/speculation-rules/) |
+| [autocorrect](https://web-platform-dx.github.io/web-features-explorer/features/autocorrect/) | [LanguageModel](https://web-platform-dx.github.io/web-features-explorer/features/languagemodel/) | [Summarizer](https://web-platform-dx.github.io/web-features-explorer/features/summarizer/) |
+| [Connection allowlists](https://web-platform-dx.github.io/web-features-explorer/features/connection-allowlists/) | [Lazy-loading images and iframes](https://web-platform-dx.github.io/web-features-explorer/features/loading-lazy/) | [SVG](https://web-platform-dx.github.io/web-features-explorer/features/svg/) |
+| [corner-shape](https://web-platform-dx.github.io/web-features-explorer/features/corner-shape/) | [light-dark() image values](https://web-platform-dx.github.io/web-features-explorer/features/light-dark-image/) | [Temporal](https://web-platform-dx.github.io/web-features-explorer/features/temporal/) |
+| [Credential management](https://web-platform-dx.github.io/web-features-explorer/features/credential-management/) | [Local network access](https://web-platform-dx.github.io/web-features-explorer/features/local-network-access/) | [text-fit](https://web-platform-dx.github.io/web-features-explorer/features/text-fit/) |
+| [document.modelContext](https://web-platform-dx.github.io/web-features-explorer/features/document-modelcontext/) | [Long animation frames performance entries](https://web-platform-dx.github.io/web-features-explorer/features/long-animation-frames/) | [Top-level await](https://web-platform-dx.github.io/web-features-explorer/features/top-level-await/) |
+| [email-verification](https://web-platform-dx.github.io/web-features-explorer/features/tmp-email-verification/) | [Navigation API](https://web-platform-dx.github.io/web-features-explorer/features/navigation/) | [touch-action](https://web-platform-dx.github.io/web-features-explorer/features/touch-action/) |
+| [enterkeyhint](https://web-platform-dx.github.io/web-features-explorer/features/enterkeyhint/) | [Origin](https://web-platform-dx.github.io/web-features-explorer/features/origin/) | [Translator](https://web-platform-dx.github.io/web-features-explorer/features/translator/) |
+| [Event timing performance entries](https://web-platform-dx.github.io/web-features-explorer/features/event-timing/) | [Page visibility](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility/) | [Trusted types](https://web-platform-dx.github.io/web-features-explorer/features/trusted-types/) |
+| [Federated credential management](https://web-platform-dx.github.io/web-features-explorer/features/fedcm/) | [Page visibility state performance entries](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility-state/) | [User agent client hints](https://web-platform-dx.github.io/web-features-explorer/features/ua-client-hints/) |
+| [Fetch](https://web-platform-dx.github.io/web-features-explorer/features/fetch/) | [Partitioned cookies](https://web-platform-dx.github.io/web-features-explorer/features/partitioned-cookies/) | [Web app origin migration](https://web-platform-dx.github.io/web-features-explorer/features/app-migration/) |
+| [fetchLater](https://web-platform-dx.github.io/web-features-explorer/features/fetchlater/) | [Password credentials](https://web-platform-dx.github.io/web-features-explorer/features/password-credentials/) | [Web authentication](https://web-platform-dx.github.io/web-features-explorer/features/webauthn/) |
+| [Form-associated WebMCP attributes](https://web-platform-dx.github.io/web-features-explorer/features/declarative-webmcp/) | [Permissions policy](https://web-platform-dx.github.io/web-features-explorer/features/permissions-policy/) | [Web authentication signal methods](https://web-platform-dx.github.io/web-features-explorer/features/webauthn-signals/) |
+| [HTML processing instructions](https://web-platform-dx.github.io/web-features-explorer/features/html-processing-instructions/) | [Pointer Events](https://web-platform-dx.github.io/web-features-explorer/features/pointer-events-api/) | [Web Cryptography](https://web-platform-dx.github.io/web-features-explorer/features/web-cryptography/) |
+| [image()](https://web-platform-dx.github.io/web-features-explorer/features/image-function/) | [Registered custom properties](https://web-platform-dx.github.io/web-features-explorer/features/registered-custom-properties/) | [WebAssembly](https://web-platform-dx.github.io/web-features-explorer/features/wasm/) |
+| [inputmode](https://web-platform-dx.github.io/web-features-explorer/features/inputmode/) | [Resize observer](https://web-platform-dx.github.io/web-features-explorer/features/resize-observer/) | [webcrypto-modern-algos](https://web-platform-dx.github.io/web-features-explorer/features/tmp-webcrypto-modern-algos/) |
+| [Interaction contentful paint performance entries](https://web-platform-dx.github.io/web-features-explorer/features/interaction-contentful-paint/) | [Sanitizer API](https://web-platform-dx.github.io/web-features-explorer/features/sanitizer/) | [WebOTP](https://web-platform-dx.github.io/web-features-explorer/features/web-otp/) |
</details>
<details>
-<summary><strong>180 real-world developer use cases</strong></summary>
+<summary><strong>185 real-world developer use cases</strong></summary>
<h3>accessibility</h3>
@@ -225,7 +226,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[branded-select-styling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/branded-select-styling.md)**: Create custom select elements whose button, picker, arrow icon, and checkmark all seamlessly match your brand or design system's typography, colors, spacing, and border treatments.
- **[custom-select-picker-layouts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md)**: Create custom select pickers whose options are positioned in unique or interesting ways, rather than the traditional stacked list of options.
- **[form-fields-automatically-fit-contents](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/form-fields-automatically-fit-contents.md)**: Allow form fields to grow and shrink to fit the user input, e.g. as the user types or selects a different option. Apply maximum and minimum size limits to create dynamic and responsive form fields that conform with the page design.
-- **[ime-safe-enter-submit](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/ime-safe-enter-submit.md)**: Implement keyboard text submission (like enter-to-submit in chat/textareas) safely for IME (Input Method Editor) users to prevent premature submission of incomplete text.
+- **[ime-safe-enter-submit](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/ime-safe-enter-submit.md)**: Implement Enter-to-submit in textareas and single-line inputs (chat, search, inline rename) safely for IME (Input Method Editor) users to prevent submitting incomplete text.
- **[required-field-feedback](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/required-field-feedback.md)**: Provide error message for required form fields that were skipped or left empty *only* after user interaction, to avoid preemptive errors and ensure feedback is timely and contextually relevant to the user's flow.
- **[rich-media-picker](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/rich-media-picker.md)**: Create a custom select component whose options can contain complex HTML formatting (e.g. images, icons, and other rich formatting) rather than just plain text.
- **[select-menu-interaction](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/select-menu-interaction.md)**: Validate that a non-default option has been chosen in a select menu only after the user has interacted with the control.
@@ -252,12 +253,13 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[format-human-readable-durations](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/js/format-human-readable-durations.md)**: Present elapsed time or durations to users in a readable, localized format, with the flexibility to display either detailed unit breakdowns (e.g., "1 hour and 30 minutes") or total unit counts (e.g., "90 minutes") depending on context.
- **[manage-recurring-intervals](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/js/manage-recurring-intervals.md)**: Calculate recurring intervals for subscription billings or payroll cycles, automatically adjusting for edge cases such as month-end transitions (e.g., adding one month to January 31st) to ensure accurate period calculations.
- **[model-partial-time-concepts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/js/model-partial-time-concepts.md)**: Model date and time concepts that inherently lack a standard component (such as a specific year, day, or date) without using arbitrary placeholder values that introduce calculation errors.
+- **[sequence-distributed-events](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/js/sequence-distributed-events.md)**: Sort timestamped events collected from servers, databases, or log files and measure the intervals between them.
- **[stabilize-reactive-state](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/js/stabilize-reactive-state.md)**: Manage task deadlines or schedules in data-driven views without unexpected side effects from shared mutable state.
- **[support-global-calendar-systems](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/js/support-global-calendar-systems.md)**: Display and calculate dates in non-Gregorian calendar systems (e.g., Islamic, Hebrew, or Chinese) accurately for international users.
<h3>performance</h3>
-- **[batch-analytics-events](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/batch-analytics-events.md)**: Debounce and batch multiple analytics events together in a single beacon to minimize network contention and reduce server load, while still delivering real-time updates.
+- **[batch-analytics-events](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/batch-analytics-events.md)**: Debounce and batch multiple analytics, telemetry, and Core Web Vitals events together in a single beacon to minimize network contention and reduce server load, while still delivering real-time updates.
- **[break-up-long-tasks](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/break-up-long-tasks.md)**: Break up heavy synchronous processing (complex computations and/or long loops) or DOM updates, to let the browser handle user input and repaint the screen.
- **[calculate-total-foreground-time](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/calculate-total-foreground-time.md)**: Calculate the total time a user actually spent viewing a page, excluding periods when the tab was in the background.
- **[conditional-async-dependencies](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/conditional-async-dependencies.md)**: Conditionally load or initialize async dependencies (such as importing polyfills for missing web features) without requiring complex orchestration across all of a page's script dependencies.
@@ -269,9 +271,9 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[efficient-background-processing](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/efficient-background-processing.md)**: Conserve system resources and battery life by pausing background JavaScript execution (such as `&lt;canvas&gt;` animations, WebGL rendering, or high-frequency WebSocket data polling) when the component is off-screen and then resume them just-in-time when they scroll back into view.
- **[faster-spa-view-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/faster-spa-view-transitions.md)**: Enable faster transitions back to previously visited views in a Single-Page Application (SPA) by preserving their structural DOM state instead of destroying and rebuilding them on every navigation.
- **[flicker-free-client-side-ab-testing](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/flicker-free-client-side-ab-testing.md)**: Deliver and render A/B tests, multi-variate tests, or other experiments using client-side JavaScript to alter or inject HTML, CSS, and JavaScript without the original content showing first before flickering or flashing to show the experiment content.
-- **[full-session-analytics](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/full-session-analytics.md)**: Reliably track analytics, errors, and telemetry data across the user's entire page visit, and defer sending of the data until the user leaves the page.
+- **[full-session-analytics](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/full-session-analytics.md)**: Reliably track analytics, Core Web Vitals, errors, and telemetry data across the user's entire page visit, and defer sending of the data until the user leaves the page.
- **[identify-heavy-scripts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/identify-heavy-scripts.md)**: Identify the scripts most responsible for long animation frames
-- **[identify-inp-causes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/identify-inp-causes.md)**: Identify slow running JavaScript that is impacting INP metric
+- **[identify-inp-causes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/identify-inp-causes.md)**: Identify slow-running JavaScript and other causes of poor Interaction to Next Paint (INP) responsiveness.
- **[improve-next-page-load-performance](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/improve-next-page-load-performance.md)**: Improve page load performance by prefetching or prerendering pages that the user is likely to visit next.
- **[interaction-paint-timing](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/interaction-paint-timing.md)**: Measure the time it takes for user interactions and client-side navigations to render new contentful updates on screen.
- **[interactions-in-complex-layouts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/interactions-in-complex-layouts.md)**: Make interactions snappier and more responsive (reducing Interaction to Next Paint (INP) scores) by avoiding layout re-calculations in complex layouts, such as data-heavy dashboards or spreadsheet-style grids.
@@ -282,7 +284,6 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[out-of-order-html-streaming](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md)**: Declaratively update a page with content streamed later into the same HTML document or via imperative JavaScript APIs.
- **[resolution-optimized-pseudo-elements](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/resolution-optimized-pseudo-elements.md)**: Use resolution-optimized images in CSS pseudo-elements (such as `::before` and `::after`) to reduce the number of DOM nodes.
- **[schedule-tasks-by-priority](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/schedule-tasks-by-priority.md)**: Schedule tasks with different priorities to ensure critical work runs first while background work is deferred.
-- **[sequence-distributed-events](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/sequence-distributed-events.md)**: Log and sequence operations in distributed microservices or high-throughput tracing environments by recording timestamps with nanosecond resolution.
<h3>privacy</h3>
@@ -303,6 +304,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[passkey-reauthentication](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/passkey-reauthentication.md)**: Verify a signed-in user's identity using their existing passkeys before a sensitive action.
- **[passkey-registration](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/passkey-registration.md)**: Register a passkey for an existing user account.
- **[passkeys](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/passkeys.md)**: Comprehensive orientation and cross-cutting principles for implementing WebAuthn and Passkeys in web applications. Use this guide when handling passkey registration, authentication, management, or reauthentication.
+- **[quick-sign-ins](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/quick-sign-ins.md)**: Authenticate returning users in place with their saved passkeys or passwords before navigating to a sign-in page or interrupting their workflow.
- **[restrict-outbound-connections](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/restrict-outbound-connections.md)**: Restrict a page or worker to communicating only with an explicit allowlist of network endpoints to prevent unauthorized third-party requests and client-side data exfiltration.
- **[sanitize-untrusted-html](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/sanitize-untrusted-html.md)**: Safely parse and display untrusted HTML content from user input by removing unsafe elements and attributes.
- **[trusted-types](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/trusted-types.md)**: Help prevent DOM-based XSS attacks by locking down dangerous DOM sinks so they reject raw strings and only accept policy-validated HTML.
@@ -313,18 +315,20 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[carousel-slide-effects](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/carousel-slide-effects.md)**: Create a carousel of slides with images or other visual elements, where each slide animates as they enter/center/exit their scroller. For example, the slides may fade-in/fade-out, rotate, get bigger or smaller, etc.
- **[component-specific-light-dark-theme](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/component-specific-light-dark-theme.md)**: Force certain elements to be in light mode or dark mode (e.g. code blocks, media players, etc) independently of the page's color-scheme.
+- **[icons](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/icons.md)**: Display and manage icons that can be set and parameterized from CSS, are fast to load, crisp at any resolution and are properly exposed to (or hidden from) assistive technologies.
- **[position-aware-tooltips](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md)**: Build tooltips and popovers with directional arrows (or other visual styling) that automatically point the correct way when the element flips to a fallback position.
- **[pull-to-reveal](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/pull-to-reveal.md)**: Build a pull-to-reveal feature that would enable the user to pull down on the screen to reveal more content, like a search bar.
-- **[resilient-context-menus-and-nested-dropdowns](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/resilient-context-menus-and-nested-dropdowns.md)**: Build accessible, responsive menus, tooltips, dropdowns, or contextual overlays that must be tethered to specific UI elements, guaranteeing that the overlay automatically repositions itself (e.g., flipping axes) when it encounters viewport edges, ensuring it never gets cut off.
- **[responsive-table](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md)**: Build a data table that presents tabular data with proper header semantics, and remains readable and navigable on small screens and with assistive technologies.
- **[scroll-position-aware-elements](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/scroll-position-aware-elements.md)**: Build floating buttons or widgets (back-to-top, scroll-to-bottom, chat launchers, etc.) that appear and disappear based on whether the user has scrolled at all.
- **[scroll-progress-indicator](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/scroll-progress-indicator.md)**: Create a scroll progress bar, stepped progress tracker, or any visual affordance that communicates how far through a page or section the user has scrolled.
- **[scrollability-affordance-hints](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/scrollability-affordance-hints.md)**: Build scroll-shadow overlays, gradient fades, or directional arrow indicators that appear only when there's actually more content to scroll to in that direction.
- **[shrinking-header-on-scroll](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/shrinking-header-on-scroll.md)**: Smoothly animate a fixed header or full-page cover on scroll to dynamically shrink, gain shadows, and transform its layout over a predefined scroll distance.
- **[state-aware-sticky-headers](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/state-aware-sticky-headers.md)**: Build sticky section headers or navbars that visually transform when they're actually "stuck" at the top, changing their color scheme or gaining a shadow.
+- **[viewport-aware-dropdowns](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md)**: Position dropdowns, flyouts, or contextual action panels tethered to a trigger button so they automatically flip axes at viewport edges instead of getting clipped.
<h3>ui-behaviors</h3>
+- **[2d-panning](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/2d-panning.md)**: Allow users to freely pan or scroll two-dimensional surfaces—such as maps, zoomed images, infinite canvases, or large data grids—across both directions (whether diagonally or changing direction mid-gesture) without the gesture locking to a single horizontal or vertical axis.
- **[anchor-positioning-tab-underline](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/anchor-positioning-tab-underline.md)**: Transition an element seamlessly between two target element positions. For example, moving a selected tab underline between the previously selected tab and the currently selected tab.
- **[animate-element-entry-exit](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/animate-element-entry-exit.md)**: Smoothly hide/show elements as they are added/removed from the DOM or as their display values are toggled.
- **[animate-to-from-top-layer](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/animate-to-from-top-layer.md)**: Animate elements such as dialogs, popovers, and tooltips as they're entering/exiting the top layer.
@@ -350,6 +354,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[platform-controls-dismiss-dialog](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/platform-controls-dismiss-dialog.md)**: Create a modal dialog that can be closed via standard platform-specific user actions, such as pressing the `Esc` key on desktop platforms, or a "back" or "dismiss" gesture on mobile platforms
- **[prevent-page-scroll-under-modal-dialog](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/prevent-page-scroll-under-modal-dialog.md)**: Prevent the underlying page from scrolling while a modal dialog is open.
- **[same-document-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/same-document-transitions.md)**: Visually connect persisting elements across different page states or navigations in a Single Page Application (SPA) (e.g. expanding a product thumbnail into a full-bleed hero image) by smoothly morphing their size, position, or other styling properties.
+- **[scoped-component-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/scoped-component-transitions.md)**: Animate state changes inside a single component (a card, list, panel, or other subtree) while the rest of the page remains interactive, and other transitions run concurrently.
- **[scroll-completion-effects](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/scroll-completion-effects.md)**: Trigger visual effects, animations, or focus changes on a target element only after a smooth programmatic scroll to that element has finished.
- **[scroll-entry-exit-effects](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/scroll-entry-exit-effects.md)**: Create fade-in, scale-up, or other complex reveal-type effects on elements as they enter and exit the scrollport (or viewport) while the user is scrolling.
- **[scroll-snap-realtime-feedback](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/scroll-snap-realtime-feedback.md)**: Provide real-time visual feedback in linked UI elements while a user scrolls through snap-aligned content, before the scroll gesture completes.
@@ -369,6 +374,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[navigation-drawer](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/navigation-drawer.md)**: Create a navigation drawer component that, when triggered from a menu button, slides in from the side overlaid on top of existing page content, and slides out when dismissed (by swiping away, tapping outside, or pressing escape).
- **[persistent-app-tours](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/persistent-app-tours.md)**: Create persistent onboarding walkthroughs using tethered native overlays that stay open during user interaction.
- **[persistent-toast-notifications](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/persistent-toast-notifications.md)**: Create non-intrusive toast and overlay notifications for persistent, stackable messaging and state communication.
+- **[progress](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/progress.md)**: Build a styled progress bar that communicates completion of a task or process, in both determinate and indeterminate states.
- **[progress-ring](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/progress-ring.md)**: Build a progress ring component that visually represents the completion status of a task or process, with support for content in the center and brand-consistent styling.
- **[scrollspy](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/scrollspy.md)**: Highlight the currently visible section of a page in a navigation menu
- **[spinner](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-components/spinner.md)**: Build a loading spinner that communicates busy state to all users, respects reduced-motion preferences, and animates efficiently.
@@ -531,15 +537,16 @@ We developed a robust eval harness to ensure that the content is **empirically p
<!-- INJECT_EVAL_RESULTS_START -->
| Date | Agent + Model | Tasks / Assertions | Unguided → Guided (Uplift) |
| :--- | :--- | :---: | :---: |
+| Oct 19 | codex_cli (gpt-6.1-sol) | 172 / 1445 | 56% → 83% (**+27pp**) |
+| Oct 19 | claude_code (sonnet-5-5) | 171 / 1438 | 56% → 88% (**+32pp**) |
+| Oct 19 | antigravity_cli (gemini-3.8-flash) | 166 / 704 | 59% → 88% (**+29pp**) |
+| Oct 16 | codex_cli (gpt-6.1-sol) | 166 / 1382 | 58% → 84% (**+26pp**) |
+| Oct 16 | claude_code (sonnet-5-5) | 166 / 1382 | 54% → 89% (**+35pp**) |
+| Oct 16 | antigravity_cli (gemini-3.8-flash) | 166 / 1344 | 60% → 93% (**+33pp**) |
+| Oct 14 | codex_cli (gpt-6.1-sol) | 165 / 1396 | 60% → 82% (**+22pp**) |
+| Oct 14 | claude_code (sonnet-5-5) | 165 / 1406 | 58% → 89% (**+31pp**) |
+| Oct 14 | antigravity_cli (gemini-3.8-flash) | 165 / 1336 | 63% → 91% (**+28pp**) |
| Oct 9 | codex_cli (gpt-6.1-sol) | 153 / 1284 | 58% → 77% (**+19pp**) |
-| Oct 9 | claude_code (sonnet-5-5) | 153 / 1297 | 59% → 87% (**+28pp**) |
-| Oct 9 | antigravity_cli (gemini-3.8-flash) | 153 / 1062 | 65% → 90% (**+25pp**) |
-| Oct 7 | codex_cli (gpt-6.1-sol) | 147 / 1251 | 56% → 75% (**+19pp**) |
-| Oct 7 | claude_code (sonnet-5-5) | 147 / 1251 | 56% → 84% (**+28pp**) |
-| Oct 7 | antigravity_cli (gemini-3.8-flash) | 147 / 1195 | 64% → 89% (**+25pp**) |
-| Oct 6 | claude_code (opus-5-5) | 145 / 1236 | 61% → 89% (**+28pp**) |
-| Oct 6 | codex_cli (gpt-6.1-sol) | 145 / 1236 | 57% → 77% (**+20pp**) |
-| Oct 6 | antigravity_cli (gemini-3.8-flash) | 145 / 1057 | 62% → 88% (**+26pp**) |
<!-- INJECT_EVAL_RESULTS_END -->
diff --git a/gemini-extension.json b/gemini-extension.json
index 81b3bb6..3f8511b 100644
--- a/gemini-extension.json
+++ b/gemini-extension.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Keep your coding agent up to date with the latest web best practices",
- "version": "0.0.194",
+ "version": "0.0.195",
"author": {
"name": "Google Chrome"
}
diff --git a/kimi.plugin.json b/kimi.plugin.json
index 6af6237..36b1333 100644
--- a/kimi.plugin.json
+++ b/kimi.plugin.json
@@ -1,7 +1,7 @@
{
"name": "modern-web-guidance",
"description": "Modern Web Guidance is an agent skill and CLI tool designed to help AI coding agents build web applications using modern, secure, and high-performance APIs rather than outdated workarounds. Supported by the Google Chrome team, it injects expert-curated web platform best practices directly into an agent's context window to prevent the generation of bloated, legacy code.",
- "version": "0.0.194",
+ "version": "0.0.195",
"author": {
"name": "Google Chrome"
},
diff --git a/package.json b/package.json
index a09ddf6..bf1bc61 100644
--- a/package.json
+++ b/package.json
@@ -3,7 +3,7 @@
"displayName": "Modern Web Guidance",
"description": "Keep your agent up to date on the latest web best practices.",
"license": "Apache-2.0",
- "version": "0.0.194",
+ "version": "0.0.195",
"publisher": "GoogleChrome",
"repository": {
"url": "https://github.com/GoogleChrome/modern-web-guidance-src"
diff --git a/skills/modern-web-guidance/SKILL.md b/skills/modern-web-guidance/SKILL.md
index e3ad5dd..f4e0dbc 100644
--- a/skills/modern-web-guidance/SKILL.md
+++ b/skills/modern-web-guidance/SKILL.md
@@ -4,17 +4,17 @@ description: |
Search tool for modern web development best practices. MANDATORY: Execute FIRST for all HTML/CSS and clientside JS tasks. Do NOT skip — web APIs evolve rapidly and training weights contain obsolete patterns.
Trigger immediately for:
- - UI/Layout: Modals, dialogs, popovers, Glassmorphism/backdrop-filters, anchor positioning, container queries, `:has()`, `:user-valid`.
- - Scroll/Motion: View Transitions, Scroll-driven animations, scroll parallax/reveals.
- - Performance: CWV (LCP, INP), content-visibility, Fetch Priority, image optimization.
- - System/APIs: Local filesystem access, WebUSB, WebSockets sync, WebAssembly widgets.
- - Frameworks: Adapting layout/styles in React, Vue, Angular.
- - General Frontend: Forms, autofill, advanced inputs, custom scrollbars, modern component states, etc.
+ - UI/Layout: Modals/dialogs/popovers, tables, dark mode, anchor positioning, container queries, `:has()`, etc.
+ - Scroll/Motion: View Transitions, Scroll-driven animations, parallax/reveals, etc.
+ - Performance: CWV (LCP, INP), content-visibility, Fetch Priority, image optimization, etc.
+ - System/APIs: Security, passkeys, HTML sanitization, Web Components, dates/timezones, Built-in AI, WebAssembly, etc.
+ - Frameworks: Standard HTML/CSS/DOM in React, Vue, Angular, etc.
+ - General Frontend: Forms, validation (`:user-valid`), autofill, accessibility, custom selects, scrollbars, etc.
DO NOT trigger for:
- - Backend: Database SQL, ORMs, Express API routes.
- - Pipelines: CI/CD deployment, Docker, Actions.
- - Generic: Local scripts (Python/Go tools), ESLint, Git.
+ - Backend: SQL, ORMs, API routes, etc.
+ - Infra/Scripts: CI/CD, Docker, Actions, Python/Go, Git, etc.
+ - Tooling/Trivial: Vite, tsconfig, ESLint, tests, copy/renames, 3P docs, etc.
---
# Modern Web Guidance
@@ -24,18 +24,20 @@ A skill to search for specific web development use cases and retrieve their corr
## When to use
Must use this skill:
-- At the **start** of implementing any web feature.
-- Before creating a new component, to check if a standardized pattern already exists.
+- At the **start** of implementing any web UI, CSS layout/animation, or client-side JS logic (dates/timezones, sanitization, performance, accessibility)—including when fixing UX symptoms (e.g., janky interactions, layout shifts).
+- Before creating or updating a component, to check if a standardized modern web pattern already exists.
- To avoid implementing ad-hoc solutions or loading large dependencies unnecessarily.
## Usage Instructions
### Step 1. Search Use Cases
-Search with an action-oriented query summarizing what you want to achieve using the `search` command. Run `modern-web-guidance` directly with `npx`.
+Run `modern-web-guidance` directly with `npx` using a **2–5 word action-oriented query** for a **single web platform capability or UI pattern**:
+- **Keep queries focused and generic**: Describe the user-visible capability (`<verb> + <UI/platform object>`, optionally paired with the target HTML/CSS/JS feature name if known). Omit framework/library names (`React`, `Vue`, `Tailwind`, etc.) and app/domain nouns (product, route, or component/file names). Split multi-feature tasks into separate `search` calls.
+- **Example**: Search `"light dismiss dialog"` or `"responsive data table"`, **not** `"dialog"` (too terse), `"responsive table dark mode"` (compound — split into two searches), or `"close React settings modal on outside click"` (framework/app noise).
```sh
-npx -y modern-web-guidance@latest search "<query>" --skill-version 2026_10_12-dacb5911
+npx -y modern-web-guidance@latest search "<query>" --skill-version 2026_10_16-6654652b
```
**Example Output**:
@@ -60,16 +62,16 @@ npx -y modern-web-guidance@latest search "<query>" --skill-version 2026_10_12-da
]
```
-> **Note**: If search results are vague, return no matches, or show low similarity scores, run the `list` command to browse all guides:
-> ```sh
-> npx -y modern-web-guidance@latest list
-> ```
+> **Note**: Judge results by their `description` fields (not raw `similarity` scores):
+> - **Match found**: Call `retrieve` directly—do not also run `list`.
+> - **No match on a web UI/CSS/DOM behavior (or broad UI audit)**: If `search` returns `[]` or unrelated descriptions because your phrasing differed from the catalog (or your task spans multiple categories), run `npx -y modern-web-guidance@latest list` once to check if the pattern is covered under more general terminology.
+> - **Topic not covered**: If no guide `description` directly matches your task, proceed with your implementation without retry loops or retrieving unrelated guides.
---
### Step 2. Retrieve Best Practices
-Once you have a relevant `id` from the search results, call this script using the `retrieve` command to get the full guide. You can pass multiple IDs separated by commas.
+Once you have relevant `id`(s) from the search results, call `retrieve` to get the full guide(s)—including both specific use-case guides that match your task and any broader discipline guide (e.g., `html`, `css`, `forms`, `accessibility`, `color`, `performance`, `security`) that applies. You can pass multiple IDs separated by commas.
```sh
npx -y modern-web-guidance@latest retrieve "<id>"
@@ -109,7 +111,10 @@ When you consult `modern-web-guidance` for a task, end the response where you de
## Guidelines
- Always search **first** to find the most relevant guides.
-- These guides are usually framework-agnostic; adapt them correctly to your setup.
+- These guides use vanilla HTML/CSS/JS; adapt them to your framework without dropping the modern feature:
+ - **Types**: Spread/cast newly shipped HTML attributes (`{...({ popover: 'hint', interestfor: id, commandfor: id, switch: '' } as any)}`, `[attr.*]`) rather than removing them or merging `@types/react`.
+ - **SSR & Bundlers**: Guard `window`/`HTMLElement` in SSR and load polyfills via bare `import('<pkg>')` in client effects (or set Vite `build.target: 'esnext'` for top-level `await`)—never copy files from `node_modules`.
+ - **DOM, IDs & CSS**: Call `showModal()`/`moveBefore()` via refs on non-VDOM-managed nodes, generate per-instance IDs/`anchor-name`s (`useId()`), and keep `:root` and `@starting-style` top-level/unscoped.
- Do not hallucinate guides or ignore them; they represent the preferred local standard for the user's project.
## Interpreting Browser Support & Fallbacks
diff --git a/skills/modern-web-guidance/guides/css/css-layout.md b/skills/modern-web-guidance/guides/css/css-layout.md
index e562b08..65cf63f 100644
--- a/skills/modern-web-guidance/guides/css/css-layout.md
+++ b/skills/modern-web-guidance/guides/css/css-layout.md
@@ -232,7 +232,7 @@ Unsupported in: Chrome, Edge, and Firefox.
- Don't mix physical and logical keywords in a single `position-area` value — pick one coordinate system.
- Feature-detect with `@supports (anchor-name: --x)` and provide an absolute-position fallback.
-> For full implementation detail, polyfill strategies, and `popover` value reference, see `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest retrieve "declarative-dialog-popover-control"`) and `position-aware-tooltips` (via `npx -y modern-web-guidance@latest retrieve "position-aware-tooltips"`). For anchor positioning applied to menus and tab indicators, see `resilient-context-menus-and-nested-dropdowns` (via `npx -y modern-web-guidance@latest retrieve "resilient-context-menus-and-nested-dropdowns"`) and `anchor-positioning-tab-underline` (via `npx -y modern-web-guidance@latest retrieve "anchor-positioning-tab-underline"`).
+> For full implementation detail, polyfill strategies, and `popover` value reference, see `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest retrieve "declarative-dialog-popover-control"`) and `position-aware-tooltips` (via `npx -y modern-web-guidance@latest retrieve "position-aware-tooltips"`). For anchor positioning applied to dropdowns, flyouts, and tab indicators, see `viewport-aware-dropdowns` (via `npx -y modern-web-guidance@latest retrieve "viewport-aware-dropdowns"`) and `anchor-positioning-tab-underline` (via `npx -y modern-web-guidance@latest retrieve "anchor-positioning-tab-underline"`).
## 6 Overflow tracking and layout stability
@@ -286,9 +286,7 @@ Supported by: Chrome 108 (Nov 2022), Edge 108 (Dec 2022), Firefox 101 (May 2022)
## 8 Grid lanes (aka masonry)
-Browser support for Grid lanes: Limited availability.
-Supported by: Safari 26.4 (Mar 2026).
-Unsupported in: Chrome, Edge, and Firefox.
+Grid lanes is not natively supported by any major browser yet.
The specification is in development under the name "grid lanes" (e.g., `display: grid-lanes`), while earlier experimental prototypes used `grid-template-rows: masonry`.
diff --git a/skills/modern-web-guidance/guides/forms/ime-safe-enter-submit.md b/skills/modern-web-guidance/guides/forms/ime-safe-enter-submit.md
index 200c839..a263a8e 100644
--- a/skills/modern-web-guidance/guides/forms/ime-safe-enter-submit.md
+++ b/skills/modern-web-guidance/guides/forms/ime-safe-enter-submit.md
@@ -6,11 +6,11 @@ This works for users typing with direct Latin keyboard input (e.g. English), but
In these contexts, the `Enter`/`Return` key is used to confirm the current character conversion candidate. If custom JavaScript listens to `keydown` on `Enter` and submits immediately, the user's message is sent while they are still converting characters, resulting in incomplete, fragmented, or incorrect messages.
-Note that the composition-active check only matters for multiline `<textarea>` fields where custom JavaScript intercepts `Enter` for submission. For single-line `<input>` fields inside a `<form>`, no explicit handling is required, as browsers natively suppress implicit submission when the `Enter` keystroke is consumed by an IME.
+The composition-active check applies to any custom `keydown` handler that acts on `Enter`, not only to multiline `<textarea>` fields. Single-line `<input>` fields with their own `Enter` handling, such as search and find bars, inline rename fields, modal dialog fields, and command palettes, receive the same IME-confirming `Enter` keydown as a `<textarea>` does, with `isComposing` set to `true`. Native implicit submission of a `<form>` from an `<input>` with no custom `Enter` handler needs no explicit handling, because browsers suppress implicit submission when the `Enter` keystroke is consumed by an IME.
## Implementation strategy
-For a `<textarea>` with custom enter-to-submit, check the native `isComposing` property of the `KeyboardEvent` before submitting the content. The default action of `Enter` in a `<textarea>` is to insert a newline, so you must also call `event.preventDefault()` to suppress that.
+For a `<textarea>` or `<input>` with custom enter-to-submit, check the native `isComposing` property of the `KeyboardEvent` before submitting the content. Also call `event.preventDefault()`: the default action of `Enter` inserts a newline in a `<textarea>`, and in an `<input>` inside a `<form>` it triggers the browser's implicit submission, which would submit a second time.
```html
<form id="chat-form">
@@ -26,7 +26,7 @@ const form = document.getElementById('chat-form');
textarea.addEventListener('keydown', (event) => {
if (event.key === 'Enter' && !event.shiftKey) {
- // Prevent the default newline behavior
+ // Prevent the default action (newline in a textarea, implicit form submission in an input)
event.preventDefault();
// If the user is composing text, return early.
@@ -39,6 +39,8 @@ textarea.addEventListener('keydown', (event) => {
});
```
+For a single-line `<input>`, use the same handler without the `!event.shiftKey` condition, which exists only because `Shift+Enter` inserts a newline in a `<textarea>`.
+
Note: Other custom submission shortcuts (such as `Cmd+Enter` or `Ctrl+Enter`) do not conflict with IME confirmation keys and do not require IME safety checks.
## Accessibility and testing
diff --git a/skills/modern-web-guidance/guides/js/calculate-event-differentials.md b/skills/modern-web-guidance/guides/js/calculate-event-differentials.md
index 86a6f9c..b8f0841 100644
--- a/skills/modern-web-guidance/guides/js/calculate-event-differentials.md
+++ b/skills/modern-web-guidance/guides/js/calculate-event-differentials.md
@@ -20,31 +20,33 @@ To calculate differentials between two events:
const now = Temporal.Now.zonedDateTimeISO();
const tz = now.timeZoneId;
-// 2. Parse inputs (assuming ISO strings from form inputs)
+// 2. Combine separate date and time strings directly.
+// Do not build an ISO string with template literals; chain the Temporal methods instead.
const startDateStr = "2025-01-01";
const startTimeStr = "12:00:00";
const endDateStr = "2025-01-31";
const endTimeStr = "12:00:00";
-const startDate = Temporal.PlainDate.from(startDateStr);
-const startTime = Temporal.PlainTime.from(startTimeStr);
-const start = startDate.toPlainDateTime(startTime).toZonedDateTime(tz);
-
-const endDate = Temporal.PlainDate.from(endDateStr);
-const endTime = Temporal.PlainTime.from(endTimeStr);
-const end = endDate.toPlainDateTime(endTime).toZonedDateTime(tz);
+const start = Temporal.PlainDate.from(startDateStr).toPlainDateTime(startTimeStr).toZonedDateTime(tz);
+const end = Temporal.PlainDate.from(endDateStr).toPlainDateTime(endTimeStr).toZonedDateTime(tz);
// 3. Calculate difference using .since() and .until()
-// By default, units larger than hours might not wrap automatically.
-// Use largestUnit to ensure differences are expressed in larger units if applicable.
-const timeActive = now.since(start, { largestUnit: 'year' });
-const timeRemaining = now.until(end, { largestUnit: 'year' });
-
-console.log(`Active: ${timeActive.days} days, ${timeActive.hours} hours`);
-console.log(`Remaining: ${timeRemaining.days} days, ${timeRemaining.hours} hours`);
-
-// 4. Compare dates
-const isExpired = Temporal.ZonedDateTime.compare(now, end) > 0;
+// ZonedDateTime differences default to largestUnit: 'hour' (days are not a fixed
+// length across DST, so Temporal won't balance into days unless asked). Pass
+// largestUnit: 'day' or a calendar unit ('week', 'month', 'year') when you want a
+// human-scale breakdown instead of e.g. PT1763H. smallestUnit rounds away
+// seconds and sub-second noise so the formatted string stays readable.
+const timeActive = now.since(start, { largestUnit: 'year', smallestUnit: 'minute' });
+const timeRemaining = now.until(end, { largestUnit: 'year', smallestUnit: 'minute' });
+
+// Format durations for display with .toLocaleString() (Intl.DurationFormat)
+// instead of manually concatenating unit numbers and suffixes. 'en-US' is used
+// here for deterministic output; pass undefined to use the user's locale.
+console.log(`Active: ${timeActive.toLocaleString('en-US', { style: 'narrow' })}`);
+console.log(`Remaining: ${timeRemaining.toLocaleString('en-US', { style: 'narrow' })}`);
+
+// 4. Check status by leveraging the native .sign property on computed Duration objects
+const isExpired = timeRemaining.sign < 0;
if (isExpired) {
console.log("Subscription is expired.");
}
@@ -53,10 +55,14 @@ if (isExpired) {
## Strategic Implementation & Best Practices
- **DO** use `Temporal.ZonedDateTime` for calculations involving real-world events that occur in specific time zones (like subscription renewals or event scheduling).
-- **DO** use `largestUnit` to specify the largest unit you want in the result (e.g., `'year'` or `'month'`). If you omit it, it defaults to `'auto'` which might not always sum up to years/months as expected for human-readable durations.
+- **DO** combine separate date and time strings with Temporal methods, e.g. `Temporal.PlainDate.from(dateStr).toPlainDateTime(timeStr).toZonedDateTime(tz)` or `Temporal.PlainDate.from(dateStr).toZonedDateTime({ timeZone: tz, plainTime: timeStr })`, instead of interpolating an ISO string like `` `${dateStr}T${timeStr}` ``.
+- **DO** pass `largestUnit` (e.g. `'day'`, `'month'`, `'year'`) when you want durations balanced beyond hours; `ZonedDateTime` difference methods default to `'hour'`.
- **DO** use `.since()` when calculating time elapsed *since* a past event (e.g., `now.since(start)`), and `.until()` for time remaining *until* a future event (e.g., `now.until(end)`).
+- **DO** format durations for display using `.toLocaleString()` (e.g., `duration.toLocaleString(undefined, { style: 'narrow' })` or `{ style: 'digital' }`), which uses `Intl.DurationFormat` under the hood, instead of manually concatenating unit numbers and suffixes.
+- **DO** render a `PlainTime` as `HH:MM` (e.g., for `<input type="time">`) using `.toPlainTime().toString({ smallestUnit: 'minute' })` rather than string `.slice(0, 5)`.
- **DO NOT** modify instances directly; `Temporal` objects are **immutable**. Operations like `add()`, `subtract()`, or `with()` return a *new* instance.
-- **DO** use `Temporal.ZonedDateTime.compare` to check if one time point is after another. It returns `1` if the first is after the second, `-1` if before, and `0` if equal.
+- **DO NOT** fall back to `Date`/`getTime()` arithmetic for the differential itself; `Date` has no time-zone-aware calendar math and only millisecond precision.
+- **DO** use the native `.sign` property of the computed `Temporal.Duration` (or use `Temporal.ZonedDateTime.compare`) to check if a duration represents a past/expired time point (negative sign) or future pending start.
## Fallback Strategy
diff --git a/skills/modern-web-guidance/guides/js/capture-location-agnostic-data.md b/skills/modern-web-guidance/guides/js/capture-location-agnostic-data.md
index b1c2c80..d195d74 100644
--- a/skills/modern-web-guidance/guides/js/capture-location-agnostic-data.md
+++ b/skills/modern-web-guidance/guides/js/capture-location-agnostic-data.md
@@ -1,6 +1,6 @@
# Capturing Location-Agnostic Data with Temporal
-Recording chronological data that should remain identical regardless of the viewer's location (such as birthdates, recurring alarms, or national holidays) has historically been error-prone with the legacy `Date` object. Because `Date` objects always represent a specific instant in time and are tied to a time zone, saving a date like "1990-01-01" can result in users in different time zones seeing "1989-12-31" due to offset shifts.
+Recording chronological data that should remain identical regardless of the viewer's location (such as birthdates, recurring alarms, or national holidays) has historically been error-prone with the legacy `Date` object. Because a `Date` always represents a specific instant in time and is displayed using whatever time zone the viewer's device happens to be in, saving a date like "1990-01-01" can result in users in different time zones seeing "1989-12-31" due to offset shifts.
The `Temporal` API introduces "Plain" types—such as `Temporal.PlainDate` and `Temporal.PlainTime`—which have no concept of a time zone. These types represent calendar dates and wall-clock times exactly as you would read them off a calendar or a clock, making them ideal for location-agnostic data.
@@ -21,12 +21,35 @@ const plainDate = Temporal.PlainDate.from(birthdateStr);
// 2. Display the date
// This will output "01/01/1990" (or equivalent) in any time zone
-console.log(plainDate.toLocaleString('en-GB'));
+console.log(plainDate.toLocaleString('en-GB'));
-// 3. Compare with standard Date (which might drift)
-const dateObj = new Date("1990-01-01T00:00:00Z");
-// In a UTC-5 time zone, this might print "31/12/1989"
-console.log(new Intl.DateTimeFormat('en-GB', { timeZone: 'America/New_York' }).format(dateObj));
+// 3. Read calendar fields directly from the Plain type. A PlainDate already *is*
+// a calendar date, so there is no need for the formatToParts() workaround that
+// legacy Date code uses to recover year/month/day from an instant.
+const { year, month, day } = plainDate;
+```
+
+### Example: Interoperating with legacy `Date`
+
+A legacy `Date` is a timestamp (an instant), not a calendar date. Storing "1990-01-01" as a `Date` forces you to pick *some* instant (typically midnight UTC), and reading it back in a time zone west of UTC yields "31/12/1989". If a library or API still requires a `Date`, convert explicitly through `Temporal.Instant` rather than building ISO strings by hand:
+
+```javascript
+// PlainDate -> Date: attach a time zone (time of day defaults to the start of
+// that day) to get an Instant, then hand the epoch milliseconds to Date.
+// 'UTC' is a deliberate choice and must be documented; any zone would do,
+// but the stored instant depends on it.
+const instant = plainDate.toZonedDateTime('UTC').toInstant();
+const legacyDate = new Date(instant.epochMilliseconds);
+
+// Date -> PlainDate: go back through Instant (legacyDate.toTemporalInstant()
+// is equivalent), then project into an explicit time zone. The result depends
+// on the zone, which is exactly the drift risk.
+const viewedDate = Temporal.Instant.fromEpochMilliseconds(legacyDate.getTime())
+ .toZonedDateTimeISO('America/New_York')
+ .toPlainDate();
+
+// Compare Plain types with .equals() (or Temporal.PlainDate.compare), not strings.
+console.log(viewedDate.equals(plainDate)); // false: the calendar date drifted to 1989-12-31
```
## Strategic Implementation & Best Practices
@@ -34,6 +57,9 @@ console.log(new Intl.DateTimeFormat('en-GB', { timeZone: 'America/New_York' }).f
- **DO** use `Temporal.PlainDate` for "calendar dates" like birthdates, anniversaries, and holidays where the specific time of day or time zone is irrelevant.
- **DO** use `Temporal.PlainTime` for "wall-clock times" like a daily reminder at 9:00 AM, where the time should be 9:00 AM in whatever time zone the user happens to be in.
- **DO NOT** use Plain types if you need to represent a specific moment in physical time (an "instant"). Use `Temporal.Instant` or `Temporal.ZonedDateTime` for logs, event timestamps, or anything requiring time zone awareness.
+- **DO NOT** construct `Date` objects from hand-built ISO strings (such as `` `${date}T00:00:00Z` ``). Produce a `Date` from the `epochMilliseconds` of a `Temporal.Instant` or `Temporal.ZonedDateTime`, and read one back with `Temporal.Instant.fromEpochMilliseconds(date.getTime())` or `date.toTemporalInstant()`, so the time zone assumption is explicit.
+- **DO NOT** use `Intl.DateTimeFormat.prototype.formatToParts()` to extract or compare year, month, or day values. Read the `.year`, `.month`, and `.day` properties of a Plain type, and compare with `.equals()`.
+- **DO** identify time zones by IANA name (e.g., `America/New_York`) and never by a fixed UTC offset. Offsets change with daylight saving time and legislation, so labels like "UTC-5" become wrong for part of the year.
- **DO** remember that `Temporal` objects are **immutable**. Methods like `add()` or `with()` return a new instance rather than modifying the original.
## Fallback Strategy
diff --git a/skills/modern-web-guidance/guides/js/coordinate-global-events.md b/skills/modern-web-guidance/guides/js/coordinate-global-events.md
index aca4c1b..0066fe6 100644
--- a/skills/modern-web-guidance/guides/js/coordinate-global-events.md
+++ b/skills/modern-web-guidance/guides/js/coordinate-global-events.md
@@ -40,7 +40,8 @@ console.log(`Resolved time: ${hostTime.toString()}`);
// 4. Convert to another time zone (e.g., Tokyo)
const tokyoTime = hostTime.withTimeZone("Asia/Tokyo");
-console.log(`Tokyo time: ${tokyoTime.toString()}`);
+// Use toLocaleString() for user-facing display instead of manual hour/minute padding
+console.log(`Tokyo time: ${tokyoTime.toLocaleString('en-US', { hour: 'numeric', minute: '2-digit' })}`);
```
## Strategic Implementation & Best Practices
@@ -50,6 +51,7 @@ console.log(`Tokyo time: ${tokyoTime.toString()}`);
- **DO** use `disambiguation: 'compatible'` (the default) when you want the system to automatically pick a sensible time when conflicts occur.
- **DO NOT** use `Temporal.PlainDateTime` for global events, as it does not carry time zone information and cannot account for DST changes.
- **DO** use `.withTimeZone()` to calculate the equivalent time in other locations without mutating the original object (Temporal objects are immutable).
+- **DO** use native `.toLocaleString()` formatting (such as `{ hour: 'numeric', minute: '2-digit' }`) for user-facing time displays instead of manual time calculations and padding.
### Fallback strategies
diff --git a/skills/modern-web-guidance/guides/js/sequence-distributed-events.md b/skills/modern-web-guidance/guides/js/sequence-distributed-events.md
new file mode 100644
index 0000000..48b2b0a
--- /dev/null
+++ b/skills/modern-web-guidance/guides/js/sequence-distributed-events.md
@@ -0,0 +1,91 @@
+# Sequencing Distributed Events
+
+Tracing dashboards, audit logs, and telemetry viewers often receive events from many services, each stamped by a central source such as a database, message broker, or log pipeline. Those timestamps are frequently recorded with microsecond or nanosecond precision (for example, `2026-04-01T12:00:00.000123456Z`). The legacy `Date` object can only represent milliseconds, so parsing such strings with `new Date()` silently truncates the fractional seconds, causing events that occurred at different times to appear simultaneous and sort in an unstable order.
+
+`Temporal.Instant` represents an exact point on the UTC timeline with nanosecond precision and no attached time zone. That makes it the right type for events that were all measured against the same clock: it preserves the full precision of the recorded timestamp, sorts unambiguously, and yields an exact `Temporal.Duration` between any two events.
+
+## How to Implement
+
+To sequence events that arrive with high-precision timestamps:
+
+1. **Parse the recorded timestamps as `Temporal.Instant`**: Use `Temporal.Instant.from(isoString)` on the timestamp string supplied by the server, database, or log line. Keep the timestamp the source recorded; do not replace it with a timestamp captured in the browser.
+2. **Sort events chronologically**: Use `Temporal.Instant.compare(a, b)` as the comparator passed to `Array.prototype.sort()`. It compares the full nanosecond value, so sub-millisecond ordering is preserved.
+3. **Calculate intervals**: Use `instant.since(previousInstant)` to get a `Temporal.Duration` between consecutive events. Use `a.equals(b)` to detect events with identical timestamps.
+4. **Display intervals with `toLocaleString()`**: Format the `Temporal.Duration` for users with `duration.toLocaleString()`, which uses `Intl.DurationFormat` under the hood. Do not convert to a single `Number` of nanoseconds for display.
+5. **Serialize for transmission**: Use `Temporal.Instant.prototype.toString()` to emit a standard ISO 8601 string (always in UTC with a `Z` suffix) when sending events onward.
+
+## Example Code: Sequencing a Server-Side Trace
+
+```javascript
+// Events as received from a central source (for example, a tracing backend).
+// The timestamps were all recorded against the same clock, so they can be
+// ordered and compared with each other exactly.
+const rawEvents = [
+ { nodeId: 'api-2', eventType: 'db.query', ts: '2026-04-01T12:00:00.000123456Z' },
+ { nodeId: 'api-1', eventType: 'request.start', ts: '2026-04-01T12:00:00.000120000Z' },
+ { nodeId: 'api-2', eventType: 'request.end', ts: '2026-04-01T12:00:00.000987654Z' },
+];
+
+// 1. Parse recorded timestamps as Temporal.Instant (never `new Date(ts)`,
+// which drops everything below the millisecond).
+const events = rawEvents.map(evt => ({
+ ...evt,
+ timestamp: Temporal.Instant.from(evt.ts),
+}));
+
+// 2. Sort chronologically with the static compare() method
+function sequenceEvents(events) {
+ // Instant.compare returns -1, 0, or 1, which is exactly what sort() expects.
+ return [...events].sort((a, b) => Temporal.Instant.compare(a.timestamp, b.timestamp));
+}
+
+// 3. Calculate and display the interval between consecutive events
+function analyzeTrace(sortedEvents) {
+ for (let i = 1; i < sortedEvents.length; i++) {
+ const prev = sortedEvents[i - 1];
+ const curr = sortedEvents[i];
+
+ // since() returns a Temporal.Duration that retains nanosecond precision.
+ const gap = curr.timestamp.since(prev.timestamp);
+
+ // 4. toLocaleString() formats the duration for people (e.g., "3μs 456ns").
+ // Avoid gap.total('nanoseconds'): spans over ~104 days exceed Number.MAX_SAFE_INTEGER.
+ // 'en-US' is used here for deterministic output; pass undefined to use the user's locale.
+ console.log(`${prev.eventType} → ${curr.eventType}: ${gap.toLocaleString('en-US', { style: 'narrow' })}`);
+ }
+}
+
+analyzeTrace(sequenceEvents(events));
+```
+
+## Strategic Implementation & Best Practices
+
+- **DO** use `Temporal.Instant` for timestamps that were all recorded against one clock (a server, database, or log pipeline) and only need to be ordered or differenced. This is the canonical case for `Instant` rather than `Temporal.PlainDateTime`, which has no offset and therefore cannot be placed unambiguously on the timeline.
+- **DO** keep the timestamp recorded by the source. Browsers deliberately coarsen `Temporal.Now.instant()` to mitigate timing attacks and fingerprinting (the spec explicitly permits this), so it does not give sub-millisecond resolution; for local in-page timing use `performance.now()` / `performance.mark()`, and for cross-service ordering use the timestamp recorded by the source.
+- **DO** use `Temporal.Instant.compare()` for sorting and `a.equals(b)` for equality checks; do not compare `Instant.compare(a, b) === 0` or compare `toString()` output.
+- **DO NOT** parse high-precision timestamp strings with `new Date()` or `Date.parse()` for ordering, because they truncate to milliseconds and produce collisions.
+- **DO NOT** collapse an interval to a single number for display. `duration.total('nanoseconds')` returns a `Number`, which exceeds `Number.MAX_SAFE_INTEGER` for spans longer than ~104 days and silently loses precision. Subtracting `epochNanoseconds` (a `BigInt`) is exact but discards unit structure and usually ends up converted to `Number`; keep intervals as `Temporal.Duration` and format them with `toLocaleString()`.
+- **DO** convert an `Instant` to `Temporal.ZonedDateTime` with `instant.toZonedDateTimeISO(timeZone)` when you need to show the wall-clock time of an event to a user.
+- **DO** verify that the environment supports `Temporal` before using it natively or providing a fallback.
+
+## Fallback strategies
+
+Browser support for Temporal: Limited availability.
+Supported by: Chrome 144 (Jan 2026), Edge 144 (Jan 2026), and Firefox 139 (May 2025).
+Unsupported in: Safari.
+
+For environments without native support, use a standards-compliant polyfill such as `@js-temporal/polyfill`. Load it conditionally to avoid bloating the payload for modern clients. Note that `@js-temporal/polyfill` does not automatically install a global `Temporal` object, so you must explicitly assign it if you need it globally.
+
+```javascript
+(async () => {
+ // Check for native support
+ if (typeof Temporal === 'undefined') {
+ // Dynamically load polyfill using an ESM-compatible CDN
+ const module = await import('https://esm.sh/@js-temporal/polyfill');
+ // The polyfill does not auto-install globally, so we must assign it
+ globalThis.Temporal = module.Temporal;
+ }
+
+ // Proceed with application logic
+})();
+```
diff --git a/skills/modern-web-guidance/guides/performance/batch-analytics-events.md b/skills/modern-web-guidance/guides/performance/batch-analytics-events.md
index 37ba44d..a5ca12c 100644
--- a/skills/modern-web-guidance/guides/performance/batch-analytics-events.md
+++ b/skills/modern-web-guidance/guides/performance/batch-analytics-events.md
@@ -1,6 +1,6 @@
# Debounce and batch multiple analytics events
-Most analytics and telemetry data is low priority and you can safely defer sending it until the user leaves the page. The exception to this is if you need to deliver real-time updates, in which case timeliness matters.
+Most analytics, telemetry, and Core Web Vitals analytics data is lower priority than responding to the user, so you can safely defer sending it until the user leaves the page. The exception to this is if you need to deliver real-time updates, in which case timeliness matters.
The optimal way to provide real-time analytics updates, while still minimizing beacons, is to use `fetchLater()` with the `activateAfter` configuration option. This allows you to effectively debounce and batch all analytics events that occur within a given time window into a single beacon, that is reliably sent even if the user leaves the page before the timeout expires.
diff --git a/skills/modern-web-guidance/guides/performance/full-session-analytics.md b/skills/modern-web-guidance/guides/performance/full-session-analytics.md
index 58ca8d5..584e327 100644
--- a/skills/modern-web-guidance/guides/performance/full-session-analytics.md
+++ b/skills/modern-web-guidance/guides/performance/full-session-analytics.md
@@ -1,6 +1,6 @@
# Reliably measure full-session analytics and telemetry
-To reliably analytics and telemetry data that covers the entirety of a user's visit to a web page (not just until page load) use the `fetchLater()` API.
+To reliably track analytics, Core Web Vitals, and telemetry data that covers the entirety of a user's visit to a web page (not just until page load), use the `fetchLater()` API.
The `fetchLater()` API is the most reliably way to send data to a server in cases where a response is not required and delivery timing is not urgent, which applies to data such as user analytics, telemetry, error tracking, and performance metrics like Core Web Vitals.
diff --git a/skills/modern-web-guidance/guides/performance/sequence-distributed-events.md b/skills/modern-web-guidance/guides/performance/sequence-distributed-events.md
deleted file mode 100644
index 5f0eba3..0000000
--- a/skills/modern-web-guidance/guides/performance/sequence-distributed-events.md
+++ /dev/null
@@ -1,76 +0,0 @@
-# Sequencing Distributed Events
-
-High-frequency tracing and event logging in distributed systems require precise timestamps to ensure correct causal ordering. Standard JavaScript `Date.now()` provides millisecond resolution, which can lead to timestamp collisions when multiple events occur within the same millisecond.
-
-The `Temporal` API, specifically `Temporal.Instant`, provides nanosecond-resolution timestamps, enabling precise sequencing of events without collisions.
-
-## How to Implement
-
-To sequence high-frequency events using `Temporal`:
-
-1. **Capture exact timestamps**: Use `Temporal.Now.instant()` to get the current exact time with nanosecond precision.
-2. **Sort events chronologically**: Use `Temporal.Instant.compare(a, b)` to sort event objects. This method resolves ordering differences up to the nanosecond level.
-3. **Calculate delays**: Use `Temporal.Instant.prototype.since(other)` to find the precise duration between events.
-4. **Serialize for transmission**: Use `Temporal.Instant.prototype.toString()` to convert the timestamp to a standard ISO-8601 string for logging or network transmission.
-
-## Example Code: High-Frequency Event Sequencing
-
-```javascript
-// 1. Capture timestamps for incoming events
-function recordEvent(eventType, nodeId) {
- return {
- nodeId,
- eventType,
- timestamp: Temporal.Now.instant() // Nanosecond resolution
- };
-}
-
-// 2. Sort events chronologically
-function sequenceEvents(events) {
- // Always use Temporal.Instant.compare for sorting instants
- return [...events].sort((a, b) => Temporal.Instant.compare(a.timestamp, b.timestamp));
-}
-
-// 3. Calculate delays between events
-function analyzeTelemetry(sortedEvents) {
- for (let i = 1; i < sortedEvents.length; i++) {
- const prev = sortedEvents[i - 1];
- const curr = sortedEvents[i];
-
- // Calculate difference in nanoseconds
- const duration = curr.timestamp.since(prev.timestamp);
- const nsDiff = duration.total('nanoseconds');
-
- console.log(`Delay between Event ${prev.eventType} and Event ${curr.eventType}: ${nsDiff}ns`);
- }
-}
-```
-
-## Strategic Implementation & Best Practices
-
-- **DO** use `Temporal.Now.instant()` for server-side tracing or client-side telemetry where millisecond precision is insufficient (e.g., microsecond profiling).
-- **DO NOT** use `Date.now()` if you require stable sorting of events that happen back-to-back.
-- **DO NOT** use `Temporal.Instant` for wall-clock time display unless you pair it with a time zone (use `Temporal.ZonedDateTime` for localized display).
-- **DO** verify that the environment supports `Temporal` before using it natively or providing a fallback.
-
-## Fallback strategies
-
-Browser support for Temporal: Limited availability.
-Supported by: Chrome 144 (Jan 2026), Edge 144 (Jan 2026), and Firefox 139 (May 2025).
-Unsupported in: Safari.
-
-For environments without native support, use a standards-compliant polyfill such as `@js-temporal/polyfill`. Load it conditionally to avoid bloating the payload for modern clients. Note that `@js-temporal/polyfill` does not automatically install a global `Temporal` object, so you must explicitly assign it if you need it globally.
-
-```javascript
-(async () => {
- // Check for native support
- if (typeof Temporal === 'undefined') {
- // Dynamically load polyfill using an ESM-compatible CDN
- const module = await import('https://esm.sh/@js-temporal/polyfill');
- // The polyfill does not auto-install globally, so we must assign it
- globalThis.Temporal = module.Temporal;
- }
-
- // Proceed with application logic
-})();
-```
diff --git a/skills/modern-web-guidance/guides/security/passkeys.md b/skills/modern-web-guidance/guides/security/passkeys.md
index 32d6037..be2df60 100644
--- a/skills/modern-web-guidance/guides/security/passkeys.md
+++ b/skills/modern-web-guidance/guides/security/passkeys.md
@@ -33,6 +33,7 @@ Specific passkey and WebAuthn implementation details are mapped to the following
* **Passkey Registration**: `passkey-registration` (via `npx -y modern-web-guidance@latest retrieve "passkey-registration"`) — Offering new passkey registration and promotions.
* **Passkey Conditional Create**: `passkey-conditional-create` (via `npx -y modern-web-guidance@latest retrieve "passkey-conditional-create"`) — Silently registering passkeys immediately after successful password login.
* **Passkey Authentication**: `passkey-authentication` (via `npx -y modern-web-guidance@latest retrieve "passkey-authentication"`) — Discoverable-autofill and button sign-ins.
+* **Quick Sign-Ins**: `quick-sign-ins` (via `npx -y modern-web-guidance@latest retrieve "quick-sign-ins"`) — Contextual in-place sign-ins with local passkeys and saved passwords before page navigation.
* **Passkey Management**: `passkey-management` (via `npx -y modern-web-guidance@latest retrieve "passkey-management"`) — Syncing lists, renames, and deletions with password managers.
* **Passkey Reauthentication**: `passkey-reauthentication` (via `npx -y modern-web-guidance@latest retrieve "passkey-reauthentication"`) — Re-verifying returning signed-in users for sensitive steps.
diff --git a/skills/modern-web-guidance/guides/security/quick-sign-ins.md b/skills/modern-web-guidance/guides/security/quick-sign-ins.md
new file mode 100644
index 0000000..a9ba473
--- /dev/null
+++ b/skills/modern-web-guidance/guides/security/quick-sign-ins.md
@@ -0,0 +1,242 @@
+# Quick sign-ins with immediate UI mode
+
+Navigating an unauthenticated user to a dedicated sign-in page when they click a "Sign in" link, start checkout, save an item to favorites, or reach an article paywall causes context loss and increases user drop-off. Immediate UI mode (`uiMode: 'immediate'` in `navigator.credentials.get()`) enables contextual quick sign-ins by presenting a unified browser account chooser immediately when local passkeys (`publicKey`) or saved passwords (`password: true`) exist on the device.
+
+Unlike standard modal WebAuthn prompts—which always display browser UI and fall back to cross-device QR codes or external security keys—Immediate UI mode fails fast with a `NotAllowedError` if no eligible credentials are locally available on the device. This lets your application authenticate returning users in place with a single tap while seamlessly transitioning users without local credentials to your standard sign-in page, guest checkout, or inline login form.
+
+## Recommended UX patterns and anti-patterns
+
+Trigger Immediate UI mode inside a user-initiated event handler (requiring transient user activation) at moments of clear user intent **right before** navigating away from the current page. If immediate authentication succeeds, complete the user's intent immediately (whether by updating the current page in place or proceeding directly to their authenticated destination). If it fails with `NotAllowedError`, show a sign-in or registration flow with a path to complete the user's intent on completion.
+
+Potential use cases:
+
+- **Header sign-in link or button interception**: Intercept a click on a global "Sign in" link (`event.preventDefault()`) to authenticate returning users immediately, or continue navigating to the dedicated sign-in page on `NotAllowedError`.
+- **Dynamic sign-in before checkout**: Authenticate returning shoppers with a single tap when they click "Proceed to checkout" so they land directly on the shipping and payment step, or transition to the standard sign-in or guest checkout screen on fallback.
+- **Inline sign-in for micro-actions (Favorite, Like, Bookmark, Save)**: Authenticate in place when a signed-out user clicks a micro-action button and immediately complete the action (for example, toggling `aria-pressed="true"`), or open a fallback login modal or sign-in page with a return URL parameter.
+- **In-article soft paywalls**: Authenticate readers in place when they click "Continue reading with your account" on a paywall banner, or expand an inline sign-in or registration form on fallback.
+
+Anti-patterns to avoid:
+
+- **DO NOT use Immediate UI mode on a dedicated sign-in page**: Never attach `uiMode: 'immediate'` to the primary "Sign in" or "Sign in with a passkey" button on your final destination sign-in page. Users reach the dedicated sign-in page specifically when they have no local credentials on the current device, or when they intend to use a cross-device passkey (scanning a QR code with a phone) or an external hardware security key. Because `uiMode: 'immediate'` suppresses cross-device QR code and security key options and immediately throws `NotAllowedError` when no local credentials exist, using it on a dedicated sign-in page traps the user in a dead end where clicking the button does nothing. On a dedicated sign-in page, use Conditional UI (`mediation: 'conditional'` with `autocomplete="username webauthn"`) on form inputs paired with a standard modal `navigator.credentials.get({ publicKey })` button (see `passkey-authentication` (via `npx -y modern-web-guidance@latest retrieve "passkey-authentication"`)).
+- **DO NOT use Immediate UI mode for step-up reauthentication**: Never use `uiMode: 'immediate'` to reauthenticate an already signed-in user before sensitive operations (such as changing a password, updating a shipping address, editing saved payment methods, or adding a new passkey). Reauthentication must restrict the prompt to the signed-in user's credentials via a non-empty `allowCredentials` list, which Immediate UI mode rejects with `NotAllowedError`, and omitting `allowCredentials` would let the user inadvertently select a different account than the one currently signed in. For step-up reauthentication, follow `passkey-reauthentication` (via `npx -y modern-web-guidance@latest retrieve "passkey-reauthentication"`).
+
+## Privacy and security constraints
+
+Browsers enforce strict privacy and security rules when `uiMode: 'immediate'` is requested:
+
+- **Transient user activation is required**: You MUST call `navigator.credentials.get({ uiMode: 'immediate' })` inside a user-initiated event handler (such as a `click` listener on a `<button>` or `<a>` element) to prevent silent credential probing. Never invoke it automatically on page load (`DOMContentLoaded`). Calling the API does not consume the transient activation.
+- **Do not pass a non-empty `allowCredentials` list**: Do **NOT** populate `publicKey.allowCredentials` when `uiMode: 'immediate'` is specified. Browsers immediately reject any Immediate UI mode request with a non-empty `allowCredentials` list by throwing `NotAllowedError` so relying parties cannot probe for specific credential IDs to infer prior visits or track users across sessions.
+- **Do not pass an `AbortSignal` (`signal`)**: Do **NOT** set the `signal` property on `navigator.credentials.get()` when `uiMode: 'immediate'` is specified, as browsers disallow programmatic dismissal of the immediate login dialog. If your page also runs a background Conditional UI (`mediation: 'conditional'`) request, call `abort()` on that Conditional UI `AbortController` before invoking Immediate UI mode, and omit `signal` from the immediate request itself.
+- **Incognito and private browsing sessions**: Requests made in Incognito or private browsing windows always reject with `NotAllowedError` so private sessions remain indistinguishable from sessions without local credentials.
+
+## Server-side setup
+
+### Options generation endpoint
+
+Expose an endpoint that generates discoverable WebAuthn request options for unauthenticated visitors:
+
+1. **Generate a session-bound challenge**: Create a cryptographically random challenge buffer, store it in the server session, and encode it as Base64URL.
+2. **Persist user verification preference**: Set `userVerification: 'preferred'` and store `expectedUserVerification: 'preferred'` in the session.
+3. **Omit `allowCredentials`**: Do not include a non-empty `allowCredentials` list in the options for Immediate UI mode, as browsers reject non-empty allowlists with `NotAllowedError`.
+
+```javascript
+// Server-side options generation example (/api/login/options)
+router.post('/api/login/options', (req, res) => {
+ const options = {
+ challenge: serverGeneratedBase64UrlChallenge, // High-entropy random challenge stored in session
+ rpId: 'example.com',
+ userVerification: 'preferred',
+ };
+
+ req.session.challenge = options.challenge;
+ req.session.expectedUserVerification = 'preferred';
+ return res.json(options);
+});
+```
+
+### Dual credential verification endpoints
+
+Because `navigator.credentials.get({ password: true, publicKey, uiMode: 'immediate' })` can resolve with either a passkey (`PublicKeyCredential`) or a saved password (`PasswordCredential`), provide verification handlers for both credential types:
+
+1. **WebAuthn assertion verification (`/api/login/verify`)**: Verify the assertion against the session challenge and stored public key. If the credential ID is not found in the database, return HTTP status `404` so the client can notify the password manager via `PublicKeyCredential.signalUnknownCredential()`.
+2. **Password verification (`/api/login/password`)**: Verify the `username` (`cred.id`) and `password` (`cred.password`) against the user database and establish an authenticated session.
+
+## Client-side implementation
+
+### Unified credential request
+
+1. **Request both passkeys and passwords**: Decode the server options using `PublicKeyCredential.parseRequestOptionsFromJSON()` and call `navigator.credentials.get()` inside a user-initiated click handler with `password: true`, `publicKey`, and `uiMode: 'immediate'` (without passing `signal`).
+2. **Branch verification by `cred.type`**:
+ - If `cred.type === 'public-key'`, serialize the assertion with `cred.toJSON()` and POST it to your WebAuthn verification endpoint. When the server responds with HTTP `404`, call `PublicKeyCredential.signalUnknownCredential({ rpId: publicKey.rpId, credentialId: encoded.id })`.
+ - If `cred.type === 'password'`, POST `{ username: cred.id, password: cred.password }` to your password verification endpoint.
+3. **Handle `NotAllowedError` when no local credentials exist**: Catch `NotAllowedError` (thrown immediately when no local passkeys or saved passwords exist on the device, or when the user dismisses the chooser) and transition to your standard sign-in flow (such as opening an inline sign-in dialog or navigating to `/signin` with a return URL).
+
+```javascript
+let isAuthenticating = false;
+
+async function authenticateWithImmediateUi() {
+ const optionsResponse = await fetch('/api/login/options', { method: 'POST' });
+ if (!optionsResponse.ok) {
+ throw new Error('Failed to fetch authentication options');
+ }
+ const optionsJSON = await optionsResponse.json();
+ const publicKey = PublicKeyCredential.parseRequestOptionsFromJSON(optionsJSON);
+
+ // MANDATORY: Request both password and publicKey with uiMode: 'immediate' and NO signal parameter
+ const cred = await navigator.credentials.get({
+ password: true,
+ publicKey,
+ uiMode: 'immediate',
+ });
+
+ if (!cred) {
+ throw new DOMException('No credential returned', 'NotAllowedError');
+ }
+
+ if (cred.type === 'public-key') {
+ const encoded = cred.toJSON();
+ const verifyResponse = await fetch('/api/login/verify', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(encoded),
+ });
+
+ if (verifyResponse.status === 404) {
+ await PublicKeyCredential.signalUnknownCredential({
+ rpId: publicKey.rpId || window.location.hostname,
+ credentialId: encoded.id, // Base64URL-encoded credential ID string
+ });
+ throw new Error('Passkey credential is no longer recognized by the server');
+ }
+
+ if (!verifyResponse.ok) {
+ throw new Error('Passkey verification failed');
+ }
+ return await verifyResponse.json();
+ }
+
+ if (cred.type === 'password') {
+ const verifyResponse = await fetch('/api/login/password', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ username: cred.id,
+ password: cred.password,
+ }),
+ });
+
+ if (!verifyResponse.ok) {
+ throw new Error('Password verification failed');
+ }
+ return await verifyResponse.json();
+ }
+
+ throw new Error(`Unsupported credential type: ${cred.type}`);
+}
+
+// Example: Intercepting an inline micro-action (Favorite button) or Header Sign-in click
+const favoriteButton = document.getElementById('favorite-btn');
+
+favoriteButton.addEventListener('click', async (event) => {
+ event.preventDefault();
+ if (isAuthenticating) return;
+
+ // If already signed in, toggle the micro-action state immediately
+ if (document.body.dataset.signedIn === 'true') {
+ const nextPressed = favoriteButton.getAttribute('aria-pressed') !== 'true';
+ favoriteButton.setAttribute('aria-pressed', String(nextPressed));
+ return;
+ }
+
+ isAuthenticating = true;
+ try {
+ const user = await authenticateWithImmediateUi();
+ // Complete the user's intended action immediately
+ document.body.dataset.signedIn = 'true';
+ favoriteButton.setAttribute('aria-pressed', 'true');
+ updateHeaderUserState(user);
+ } catch (err) {
+ if (err.name === 'NotAllowedError') {
+ // No local credentials available or user dismissed dialog:
+ // transition smoothly to fallback sign-in UI or redirect with return URL
+ showFallbackSignInUi({ returnAction: 'favorite' });
+ return;
+ }
+ console.error('Authentication error:', err);
+ } finally {
+ isAuthenticating = false;
+ }
+});
+```
+
+## Fallback strategies
+
+### Immediate UI mode fallback
+
+- **Progressive enhancement experience**: Treat `uiMode: 'immediate'` as a progressive enhancement. Do not infer support from a browser's name or version; the only reliable support signal is the `capabilities.immediateGet` runtime check via `PublicKeyCredential.getClientCapabilities()`. **MANDATORY**: Always check `capabilities.immediateGet` before calling `navigator.credentials.get({ uiMode: 'immediate' })`—browsers that do not recognize `uiMode: 'immediate'` ignore the unknown dictionary key and open a blocking modal passkey and QR code dialog. When `capabilities.immediateGet` is falsy, or when `navigator.credentials.get()` rejects with `NotAllowedError`, fall back to your application's standard sign-in experience (such as opening an inline sign-in modal or navigating to the dedicated sign-in page with a return URL parameter), so users in unsupported browsers see your existing sign-in flow unchanged:
+
+```javascript
+async function isImmediateUiSupported() {
+ if (!window.PublicKeyCredential || !PublicKeyCredential.getClientCapabilities) {
+ return false;
+ }
+ try {
+ const capabilities = await PublicKeyCredential.getClientCapabilities();
+ return Boolean(capabilities?.immediateGet);
+ } catch {
+ return false;
+ }
+}
+
+async function authenticateWithImmediateUi() {
+ // MANDATORY: Check immediateGet support so unsupported browsers do not open a modal QR dialog
+ const supported = await isImmediateUiSupported();
+ if (!supported) {
+ // Throw NotAllowedError so the caller's single catch path treats "unsupported" like "no local credentials"
+ throw new DOMException('Immediate UI mode is not supported', 'NotAllowedError');
+ }
+ // Proceed with fetching options and calling navigator.credentials.get({ password: true, publicKey, uiMode: 'immediate' })
+}
+```
+
+### Client capabilities detection fallback
+
+Baseline status for the api.PublicKeyCredential.getClientCapabilities_static capability: Newly available. It's been Baseline since 2025-02-06.
+Supported by: Chrome 133 (Feb 2025), Edge 133 (Feb 2025), Firefox 135 (Feb 2025), and Safari 17.4 (Mar 2024).
+
+Always install `'webauthn-polyfills'` and import it in your client module so `PublicKeyCredential.getClientCapabilities()` is available whenever `PublicKeyCredential` is supported:
+
+```javascript
+import 'webauthn-polyfills';
+```
+
+### Password credentials fallback
+
+Browser support for Password credentials: Limited availability.
+Supported by: Chrome 60 (Jul 2017) and Edge 79 (Jan 2020).
+Unsupported in: Firefox and Safari.
+
+Passing `password: true` alongside `publicKey` in `navigator.credentials.get()` allows supporting browsers to include saved passwords from the browser's password manager in the unified immediate account chooser.
+
+- **Fallback experience**: Browsers that do not support `PasswordCredential` ignore the `password: true` option or fall back via the `capabilities.immediateGet` feature check to the standard sign-in form, where `<input autocomplete="username webauthn">` and `<input type="password" autocomplete="current-password">` provide native password autofill.
+
+### Easy JSON serialization fallback
+
+Baseline status for the api.PublicKeyCredential.parseRequestOptionsFromJSON_static capability: Newly available. It's been Baseline since 2025-03-31.
+Supported by: Chrome 129 (Sep 2024), Edge 129 (Sep 2024), Firefox 119 (Oct 2023), and Safari 18.4 (Mar 2025).
+
+Always install `'webauthn-polyfills'` and import it in the client bundle so `PublicKeyCredential.parseRequestOptionsFromJSON()` and `PublicKeyCredential.prototype.toJSON()` work consistently across browsers supporting `PublicKeyCredential`:
+
+```javascript
+import 'webauthn-polyfills';
+```
+
+### Signal API synchronization fallback
+
+Browser support for Web authentication signal methods: Limited availability.
+Supported by: Chrome 132 (Jan 2025), Edge 132 (Jan 2025), and Safari 26 (Sep 2025).
+Unsupported in: Firefox.
+
+The WebAuthn Signal API (`webauthn-signals`) is a progressive enhancement that removes stale passkeys from the user's password manager when the server responds with HTTP `404`.
+
+- **Fallback experience**: Gate calls behind `if (PublicKeyCredential.signalUnknownCredential)`. When unsupported, skip the signal call gracefully and display a clear message guiding the user to sign in with an alternative method.
diff --git a/skills/modern-web-guidance/guides/security/validate-origins.md b/skills/modern-web-guidance/guides/security/validate-origins.md
index 67bfa0e..c3bafd1 100644
--- a/skills/modern-web-guidance/guides/security/validate-origins.md
+++ b/skills/modern-web-guidance/guides/security/validate-origins.md
@@ -1,9 +1,9 @@
# Compare and validate web origins and sites
-While comparing `event.origin` against a fixed, port-normalized string literal (such as `event.origin === 'https://trusted.example.com'`) works for simple allowlists, manual string comparisons and regular expressions break down when validating arbitrary URLs, DOM link elements, cross-subdomain redirects, or sandboxed messages:
+While comparing `event.origin` against a fixed, port-normalized string literal (such as `event.origin === 'https://app.example.com'`) works for simple allowlists, manual string comparisons and regular expressions break down when validating arbitrary URLs, DOM link elements, cross-subdomain redirects, or sandboxed messages:
-- **Prefix and substring spoofing:** Checking `url.startsWith('https://trusted.example.com')` is bypassed by `'https://trusted.example.com.attacker.example'`.
-- **Unnormalized URLs:** Full URLs with paths, query strings, or explicit default ports (`'https://trusted.example.com:443/path'`) do not match `'https://trusted.example.com'` under string equality without first parsing and normalizing.
+- **Prefix and substring spoofing:** Checking `url.startsWith('https://app.example.com')` is bypassed by `'https://app.example.com.attacker.example'`.
+- **Unnormalized URLs:** Full URLs with paths, query strings, or explicit default ports (`'https://app.example.com:443/path'`) do not match `'https://app.example.com'` under string equality without first parsing and normalizing.
- **Public Suffix List mistakes:** Splitting hostnames on `.` to check same-site relationships fails on multi-label public suffixes (such as `.co.uk` or shared hosting domains like `.github.io`) and ignores scheme mismatches (`http:` vs. `https:`).
- **Opaque `"null"` origin collisions:** Sandboxed iframes (`<iframe sandbox="allow-scripts">`) and `data:` URLs serialize `event.origin` to the literal string `"null"`. Comparing two serialized runtime origins with `originA === originB` falsely equates two unrelated opaque contexts (`"null" === "null"`).
@@ -21,7 +21,7 @@ Use `Origin.from()` to extract an `Origin` object and compare it against a trust
- **Both sides must be `Origin` instances:** `isSameOrigin(other)` and `isSameSite(other)` only accept an `Origin` object—passing a raw string throws a `TypeError`.
- **Supported `Origin.from()` inputs:**
- - Serialized URL strings (for example, `'https://trusted.example.com:443/path'`). Note that any invalid URL string—for instance `'example'`, or the `'null'` string serialized by `event.origin` for opaque origins—causes `Origin.from()` to throw a `TypeError`.
+ - Serialized URL strings (for example, `'https://app.example.com:443/path'`). Note that any invalid URL string—for instance `'example'`, or the `'null'` string serialized by `event.origin` for opaque origins—causes `Origin.from()` to throw a `TypeError`.
- Platform objects that define origin-extraction steps in the HTML specification: `Origin`, `URL`, `HTMLAnchorElement` (`<a>`), `HTMLAreaElement` (`<area>`), same-origin `Window` or `WorkerGlobalScope` (`Origin.from(self)`), and browser-dispatched `MessageEvent` instances (`Origin.from(event)`).
- Objects such as `Location`, `WorkerLocation`, `Document`, `Request`, and `Response` do **not** define origin-extraction steps and throw a `TypeError` if passed directly to `Origin.from()`—pass `self` (for the current context) or `request.url` / `response.url` instead.
- **Handle both browser-dispatched and synthetic `MessageEvent` instances:** Real browser `postMessage` events carry an internal origin extracted by `Origin.from(event)`, whereas synthetic `new MessageEvent('message', { origin })` events created in unit tests only populate the `event.origin` string and throw on `Origin.from(event)`. Falling back to `Origin.from(event.origin)` inside a `try...catch` handles both cleanly while still rejecting invalid or `"null"` strings.
diff --git a/skills/modern-web-guidance/guides/ui-atoms/icons.md b/skills/modern-web-guidance/guides/ui-atoms/icons.md
new file mode 100644
index 0000000..5b00fba
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-atoms/icons.md
@@ -0,0 +1,290 @@
+# Using and managing icons
+
+
+## Choosing an Icon Technique
+
+Icon storage and rendering are separate choices. For example, an SVG sprite can supply an icon to the CSS icon system or be referenced with `<use>`.
+
+* **CSS icon system:** Use when CSS should choose when and which icon to show. Use a mask for a single-color icon or a background image for a full-color icon.
+* **SVG with `<use>`:** Use to reuse a symbol when its built-in styling options are enough. CSS can't arbitrarily style or animate the referenced SVG's contents, but inherited properties and custom properties can be passed in when the symbol is designed to use them. For example, a path can use `fill="var(--icon-accent, currentColor)"` to let CSS color that part of the icon.
+* **Inline SVG:** Use when you need arbitrary styling or animation of the SVG's contents.
+* **`<img>` with CSS filters:** Avoid this for recoloring icons. Filters can't reliably apply an arbitrary CSS color value to the image, so recoloring is cumbersome and inflexible.
+
+To decide, ask two questions. Does CSS need to pick or swap the icon (component defaults, state changes, theming)? If yes, use the CSS icon system. Do you need to reach inside the icon beyond color? If yes and you control the icon source, design the symbol with custom properties and use `<use>`; if you do not control the source, inline the SVG. Third-party icon sets rarely expose custom properties, so `<use>` against them gives you color and little else.
+
+### Embedded or remote icons
+
+Both the CSS icon system and `<use>` can take icons from a data URI, an individual file, or a sprite. Embedding (data URIs or inline SVG) avoids a request and renders with the first paint, but bloats CSS or HTML and cannot be cached separately, so it suits a small set of icons that appear on every page. Individual files are cached independently and loaded on demand, at the cost of one request each. A sprite is one cacheable request for the whole set, but downloads every icon whether used or not, and `<use>` can only reference a sprite from the same origin. Prefer embedding for a handful of core icons and a sprite or individual files for larger sets.
+
+If a page renders thousands of icons at once, benchmark the actual page and assets. In a stress test, inline SVG had a small performance advantage at that scale, but results depend on the browser and implementation. [Cloud Four's SVG icon stress test](https://cloudfour.com/thinks/svg-icon-stress-test/)
+
+## Primary Approach: CSS-Driven Icon Engine
+
+Icons are design tokens: each icon is a custom property holding an image, and any element can display one by setting `--icon-start` or `--icon-end`. The engine combines three CSS capabilities:
+
+* **Registered custom properties (`@property`)** keep `--icon-start` and `--icon-end` from inheriting, so an icon set on a component does not cascade into its children.
+* **Container style queries (`@container style(...)`)** detect when an element has an icon assigned and render it, with no class or markup changes.
+* **CSS masks and `currentColor`** render the icon in a pseudo-element that follows the element's text color. Size, color, spacing and vertical offset are read from inheritable `--icon-style-*` properties with sensible fallbacks, so a whole subtree can be restyled from an ancestor. The `--icon-style-` prefix keeps these settings from colliding with the icon tokens themselves, which also live under `--icon-*`.
+
+### Defining icon design tokens
+
+Define SVG icons and any `--icon-style-*` overrides as reusable custom properties using inline SVG data URIs or root-relative URLs (e.g., `url("/icons/trash.svg")`). When an icon is loaded from an external SVG file, use a root-relative URL or an embedded data URI. A relative URL used through a custom property can resolve relative to the stylesheet where the icon is used, rather than the stylesheet where the custom property is defined. If those stylesheets are in different directories, the URL may resolve to the wrong file.
+
+To keep a URL relative to the stylesheet that defines the icon token, a registered property is meant to help: the computed value of a registered `<url>` or `<image>` is resolved against the stylesheet that declared it. DO NOT rely on registering the token as `<image>` with the URL in `initial-value`. Chrome and Safari resolve `initial-value` URLs against the document, so it only works in Firefox. Chrome also resolves values declared on `:root` against the document unless the syntax starts with `<url>`.
+
+When relative URLs are unavoidable, such as stylesheets in different directories, register the token with a syntax that starts with `<url>` and declare the actual URL on `:root`. This resolves against the declaring stylesheet in every browser:
+
+```css
+@property --icon-caret {
+ /* The syntax must start with <url>. A syntax that starts with <image> resolves against the document in Chrome. */
+ syntax: "<url> | <image> | none";
+ inherits: true;
+ initial-value: none;
+}
+
+:root {
+ /* Declared here, the URL resolves against this stylesheet */
+ --icon-caret: url("icons/caret.svg");
+}
+```
+
+Each icon now lives in two places, and there is much more boilerplate, so this is only worth it when a project has stylesheets in different directories and a manageable number of icons. Past a dozen or so icons, register the `--icon-*` tokens (excluding `--icon-style-*`) from a script with `CSS.registerProperty`, using the same syntax, instead of writing each `@property` by hand. Registered properties are global and do not work in shadow roots, so this may not fit every project. If root-relative URLs or data URIs are an option, they are simpler and work everywhere.
+
+```css
+:root {
+ /* Optional: override the built-in fallbacks (1em, currentColor, 0.3em, -0.02em) */
+ --icon-style-size: 1em;
+ --icon-style-spacing: 0.4em;
+ --icon-trash: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'%3E%3Cpath d='M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0-1 14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2L4 6h16Z'/%3E%3C/svg%3E");
+ --icon-favorite: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor'%3E%3Cpath d='M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z'/%3E%3C/svg%3E");
+}
+```
+
+### Rendering icons from tokens
+
+An element displays an icon by setting `--icon-start` (leading) or `--icon-end` (trailing) to one of the tokens above. Two pieces of CSS turn that assignment into a rendered icon.
+
+First, register `--icon-start` and `--icon-end` with `@property`. The `"*"` syntax accepts any value, and `inherits: false` is the important part: without it, an icon set on a button would inherit into every descendant, and each of them would render the icon too.
+
+```css
+@property --icon-start {
+ syntax: "*";
+ inherits: false;
+}
+
+@property --icon-end {
+ syntax: "*";
+ inherits: false;
+}
+```
+
+Second, a container style query detects when the property is set on an element and renders the icon in a pseudo-element. Because the pseudo-element does not inherit `--icon-start` (it was registered as non-inheriting), the first declaration forwards the value explicitly with `inherit`. The remaining declarations handle sizing, masking, alignment and spacing. Because the fill defaults to `currentColor`, the icon adopts the element's text color and follows its transitions.
+
+```css
+/* Style query for elements configuring a start icon */
+@container style(--icon-start) {
+ ::before {
+ --icon-start: inherit; /* Forward the value inside the query block */
+ content: "" / var(--icon-style-alt, "");
+ display: inline-block;
+ width: var(--icon-style-size, 1em);
+ height: var(--icon-style-size, 1em);
+ background-color: var(--icon-style-color, currentColor);
+ mask: var(--icon-start) no-repeat center / contain;
+ /* Center on the cap height, nudged slightly up for optical balance */
+ vertical-align: calc(0.5cap - var(--icon-style-size, 1em) / 2 + var(--icon-style-voffset, -0.02em));
+ flex: none;
+ pointer-events: none;
+ forced-color-adjust: none;
+ }
+
+ /* Automatically add spacing ONLY if the element has other text or sibling content */
+ :where(:not(.icon, :empty))::before {
+ margin-inline-end: var(--icon-style-spacing, 0.3em);
+ }
+}
+```
+
+Each declaration earns its place:
+
+* **`vertical-align`**: `middle` aligns to half the x-height, which sits visibly low for most icon sets. Centering on `0.5cap` keeps the icon's center fixed as `--icon-style-size` grows, and the small negative `--icon-style-voffset` compensates for the eye weighting the space above an icon more than the space below.
+* **`flex: none`**: An empty pseudo-element has a zero minimum size, so inside a flex button it is the first thing to shrink when the label is long, potentially to nothing. Icon size is a design decision, not something layout pressure should negotiate.
+* **`pointer-events: none`**: Keeps the icon from trapping clicks or becoming the `event.target`.
+* **`forced-color-adjust: none`**: In forced-colors mode the browser otherwise replaces `background-color`, making a masked icon disappear. The mask fill is preserved, and `currentColor` still follows the forced text color.
+* **`content: "" / var(--icon-style-alt, "")`**: Alternative text for generated content lets an icon-only control take its accessible name from the icon via `--icon-style-alt` (see Icon-Only Controls below). The default empty alt keeps decorative icons hidden from assistive technology.
+
+For a trailing icon, follow the same pattern with `--icon-end` and `::after` instead of `--icon-start` and `::before`. Use `mask: var(--icon-end)` and apply spacing with `margin-inline-start` instead of `margin-inline-end`.
+
+### Standalone and icon-only elements
+
+For standalone icons or icon-only buttons, apply `.icon` directly to the empty element (the button itself for an icon-only control) and set its icon with `--icon`. Here, `--icon` is the higher-level property; the `.icon:empty` rule maps it to `--icon-start` for a leading icon:
+
+```css
+.icon:empty {
+ --icon-start: var(--icon);
+}
+```
+
+## Usage Examples
+
+### Component defaults in the stylesheet
+
+The main benefit of icons as custom properties is that they participate in the cascade. Set an icon on a selector and every matching element gets it, with no markup changes:
+
+```css
+.button-delete {
+ --icon-start: var(--icon-trash);
+}
+
+a[href^="http"]:not([href*="example.com"]) {
+ --icon-end: var(--icon-external);
+}
+```
+
+```html
+<button class="button-delete">Delete item</button>
+```
+
+### Changing icons with state
+
+Because the icon is just a property, a state change is an ordinary CSS override. There is no second element to show or hide and no class to toggle:
+
+```css
+.button-expand {
+ --icon-start: var(--icon-caret-right);
+}
+
+.button-expand[aria-expanded="true"] {
+ --icon-start: var(--icon-caret-down);
+}
+```
+
+The same applies to presentation: set `--icon-style-size`, `--icon-style-color` or `--icon-style-spacing` on a container such as a toolbar and every icon inside it updates.
+
+### One-off icons with inline styles
+
+An element that no component rule covers can set the same property inline, for example `<button style="--icon-start: var(--icon-trash)">`. Treat this as the escape hatch rather than the default: once the same icon appears on the same kind of element more than once, move it into a stylesheet rule.
+
+### Icon-Only Controls
+
+Icon-only buttons use the `.icon` class and `--icon` described above. Give the button an accessible name with `aria-label`, or let the icon supply one through `--icon-style-alt`; without either, the CSS-generated icon is decorative. For standalone informative icons, expose the `.icon` element with `role="img"` and `aria-label`:
+
+```css
+.button-close {
+ --icon: var(--icon-close);
+ --icon-style-alt: "Close";
+}
+```
+
+```html
+<!-- Icon-only interactive control, icon and name from the stylesheet -->
+<button class="icon button-close"></button>
+
+<!-- Icon-only interactive control, named via aria-label -->
+<button class="icon" style="--icon: var(--icon-trash);" aria-label="Delete item"></button>
+
+<!-- Standalone informative icon -->
+<span class="icon" style="--icon: var(--icon-favorite);" role="img" aria-label="Favorite"></span>
+```
+
+## Working with SVG directly
+
+When the CSS icon system is not the right fit, use inline SVG and `<use>` together rather than as alternatives. Inline the SVG the first time an icon appears on a page and reference it with `<use href="#id">` for every repeat; the local reference costs no request and has no cross-origin restriction. Reserve an external sprite (`<use href="/icons.svg#id">`) for icons shared across many pages.
+
+With `<use>`, the referenced content is cloned into a shadow tree, so page CSS cannot select its elements. What does reach it is inheritance: `color`, `currentColor`, and any custom property. Beyond SVG presentation attributes, modern CSS can change many geometry attributes as well, so an icon you control can expose exactly the hooks you need, for example `stroke-width="var(--icon-stroke, 2)"` or even `d: var(--icon-path, path(…))` on a particular path.
+
+Browser support for the css.properties.d capability: Limited availability.
+Supported by: Chrome 52 (Jul 2016), Edge 79 (Jan 2020), and Firefox 97 (Feb 2022).
+Unsupported in: Safari.
+
+CSS `d` is not supported in Safari, so use this customization only when that support gap is acceptable. If you do not control the icon, inline it.
+
+`<use>` gotchas worth knowing:
+
+* The `viewBox` must be on the `<symbol>` or referenced `<svg>`; the outer `<svg>` wrapping `<use>` does not pick it up from the reference, so set `width` and `height` on the wrapper and keep the `viewBox` with the symbol.
+* Styles do not cross the boundary in either direction: `<style>` inside an external sprite does not apply to the page, and page stylesheets do not apply inside the referenced tree. Only inherited properties and custom properties pass through.
+* External references are same-origin only; cross-origin sprites fail silently.
+* Sprites inlined into the document share the page's `id` namespace, so namespace symbol ids to avoid collisions.
+
+Mark decorative SVGs with `aria-hidden="true"` and give the containing control its own accessible name, as with the CSS icon system.
+
+## Fallback Strategies
+
+### Registered Custom Properties
+
+Baseline status for Registered custom properties: Newly available. It's been Baseline since 2024-07-09.
+Supported by: Chrome 85 (Aug 2020), Edge 85 (Aug 2020), Firefox 128 (Jul 2024), and Safari 16.4 (Mar 2023).
+
+Without `@property`, `--icon-start` and `--icon-end` behave as ordinary inheriting custom properties, so an icon set on an element would also render on its descendants. Prevent this by resetting the properties on children inside the style query (`@container style(--icon-start) { * { --icon-start: initial; } }`), the same approach the Safari workaround below uses.
+
+### Container Style Queries
+
+Baseline status for Container style queries: Newly available. It's been Baseline since 2026-05-19.
+Supported by: Chrome 111 (Mar 2023), Edge 111 (Mar 2023), Firefox 151 (May 2026), and Safari 18 (Sep 2024).
+
+To support browsers without Container Style Queries, use classes or component selectors as fallback hooks. Keep icon selection in custom properties; inline-style selectors alone miss icons assigned through CSS rules.
+
+```css
+:where(.icon-start, .icon:empty)::before {
+ content: image-set(linear-gradient(transparent 0 100%), var(--icon-start)) / var(--icon-style-alt, "");
+ /* icon styles */
+}
+
+:where(.icon-start)::before {
+ --icon-start: inherit;
+}
+
+:where(.icon:empty)::before {
+ --icon-start: var(--icon);
+}
+
+:where(.icon-start:not(.icon, :empty))::before {
+ margin-inline-end: var(--icon-style-spacing, 0.3em);
+}
+```
+
+For trailing icons, use the same class-hook fallback with `.icon-end`, `--icon-end`, and `::after` instead of `.icon-start`, `--icon-start`, and `::before`. Apply spacing to non-empty content with `margin-inline-start` instead of `margin-inline-end`.
+
+This `image-set()` pattern makes `content` invalid when the custom property is unset, so it falls back to `none` and the pseudo-element disappears without adding or removing a class. It does not remove the pseudo-element's other styles or prevent conflicts with other `::before` or `::after` rules, so use these hooks only where those pseudo-elements are available for icons.
+
+### Safari Browser Workarounds
+
+Safari has two rendering bugs affecting icons: WebKit [#301609](https://bugs.webkit.org/show_bug.cgi?id=301609) can prevent them from appearing until user interaction, and [#320220](https://bugs.webkit.org/show_bug.cgi?id=320220) also affects their rendering. The workaround below addresses both:
+
+```css
+@keyframes webkit-301609 {}
+
+@supports ((-webkit-nbsp-mode: normal) or (-webkit-touch-callout: none) or (font: -apple-system-body)) and (content-visibility: auto) {
+ @layer webkit-301609-fix {
+ ::before, ::after {
+ animation: webkit-301609 0s;
+ }
+ }
+}
+```
+
+The `@supports` query targets Safari only, and `@layer` reduces animation conflicts.
+
+WebKit bug #325900 can prevent a direct override of `--icon-start` from taking effect in some cases, such as changing the icon on hover. This affects the workaround for non-inheriting registered properties. For Safari, register `--icon-start` as inheriting and reset it on descendants inside the style query:
+
+```css
+@supports ((-webkit-nbsp-mode: normal) or
+ (-webkit-touch-callout: none) or
+ (font: -apple-system-body)) and (content-visibility: auto) {
+ /* Override previous declaration */
+ @property --icon-start {
+ syntax: "*";
+ inherits: true;
+ }
+
+ @layer webkit-325900-fix {
+ @container style(--icon-start) {
+ * {
+ --icon-start: initial;
+ }
+ }
+ }
+}
+```
+
+The reset prevents the icon value from propagating to descendants. Keeping it in a layer lets unlayered icon declarations take precedence over the reset.
diff --git a/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md b/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md
index ed37233..a5a2430 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/position-aware-tooltips.md
@@ -2,7 +2,7 @@
When building tooltips or popovers with CSS Anchor Positioning, the browser can automatically "flip" the element to a fallback position if it would otherwise overflow the viewport. When this happens, you may want to adjust the style of the positioned content, for instance to reposition an arrow that points from the positioned content to the anchor.
-**Anchored Container Queries** solve this by allowing you to query the active positioning state of an element and apply styles accordingly.
+**Anchored Container Queries** solve this by allowing you to query the active positioning state of an element and apply styles accordingly. For general anchored dropdown and flyout positioning with viewport collision flipping (without directional arrow restyling), see `viewport-aware-dropdowns` (via `npx -y modern-web-guidance@latest retrieve "viewport-aware-dropdowns"`).
## The problem
diff --git a/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md b/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md
index f9fc192..3392965 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md
@@ -14,11 +14,15 @@ The core of a responsive table is maintaining the relationship between data cell
## Implementation Steps
### 1. Markup and Layout
-Structure your table with standard semantic headers. Use a `.table-wrapper` to handle overflow and provide a container for queries.
+
+Structure your table with standard semantic headers. Use a `.table-wrapper` to handle overflow and provide a container for queries. Add a `tabindex="0"` attribute to the container, to ensure that people using only a keyboard can consistently scroll the table.
+
+Give the wrapper a `role="region"` attribute to communicate its purpose. Provide it with an accessible name using `aria-labelledby` (referencing the `id` attribute of an existing element that captions/names the table) or an `aria-label` attribute.
```html
-<div class="table-wrapper">
+<div tabindex="0" role="region" aria-labelledby="employee-table-caption" class="table-wrapper">
<table>
+ <caption id="employee-table-caption">Current employee directory</caption>
<thead>
<tr>
<th>Employee</th>
@@ -71,7 +75,7 @@ tbody th {
```
### 3. Responsive Stacked Layout
-When space is limited, hide the original header row and transform the table into cards. Inject labels using pseudo-elements, providing the accessible name directly in CSS.
+When space is limited, hide the original header row and transform the table into cards. Inject labels using pseudo-elements. Only provide alternative text for non-text content, otherwise this may result in both the text content and accessible name being announced by screen readers.
```css
@container (width < 600px) {
@@ -104,15 +108,14 @@ When space is limited, hide the original header row and transform the table into
--label-3: "Status";
}
- /* Inject labels with accessible names */
+ /* Inject labels */
td:nth-child(2)::before {
- /* MANDATORY: The accessible name (after the /) ensures screen readers
- announce the label correctly without the trailing colon. */
- content: var(--label-2) ": " / var(--label-2);
+ /* MANDATORY: If using non-text content, provide the accessible name (after the /) which ensures screen readers hear the text alternative. */
+ content: var(--label-2) ": ";
}
/* MANDATORY: Map the label for each column */
td:nth-child(3)::before {
- content: var(--label-3) ": " / var(--label-3);
+ content: var(--label-3) ": ";
}
}
```
diff --git a/skills/modern-web-guidance/guides/ui-atoms/resilient-context-menus-and-nested-dropdowns.md b/skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md
similarity index 93%
rename from skills/modern-web-guidance/guides/ui-atoms/resilient-context-menus-and-nested-dropdowns.md
rename to skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md
index baebe5e..ae04738 100644
--- a/skills/modern-web-guidance/guides/ui-atoms/resilient-context-menus-and-nested-dropdowns.md
+++ b/skills/modern-web-guidance/guides/ui-atoms/viewport-aware-dropdowns.md
@@ -1,4 +1,4 @@
-# Resilient Context Menus And Nested Dropdowns
+# Viewport-Aware Dropdowns
A revealed action panel or popover button group is a useful pattern for users to access additional functionality while taking up minimal space. This overlay pattern comes with layout complexity, as the panel must remain tethered to a trigger element while adapting to viewport constraints. Traditionally, this required complex JavaScript libraries (like Popper.js or Floating UI) to calculate positions and handle collisions.
@@ -61,6 +61,8 @@ To prevent the panel from being cut off at the edge of the screen, define "try t
}
```
+If your dropdown or flyout includes a directional arrow or border that needs to change style depending on which fallback position was chosen, see `position-aware-tooltips` (via `npx -y modern-web-guidance@latest retrieve "position-aware-tooltips"`). For declarative invocation of dialogs and popovers without JavaScript, see `declarative-dialog-popover-control` (via `npx -y modern-web-guidance@latest retrieve "declarative-dialog-popover-control"`).
+
## Fallback strategies
### Fallbacks & browser support for Popover
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/2d-panning.md b/skills/modern-web-guidance/guides/ui-behaviors/2d-panning.md
new file mode 100644
index 0000000..8cd4f59
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-behaviors/2d-panning.md
@@ -0,0 +1,151 @@
+# Two-Dimensional Panning
+
+When a user scrolls a two-dimensional scroll container, browsers typically apply a scroll axis-locking heuristic (also known as "railing"). If a gesture begins with significantly more movement along one axis than the perpendicular axis, the browser locks the scroll to that single horizontal or vertical axis and ignores perpendicular deltas—often for the remainder of the gesture.
+
+While axis-locking prevents accidental sideways drift in one-dimensional reading flows, it creates friction on two-dimensional panning surfaces such as interactive maps, zoomed images, infinite canvases, node graphs, and large data grids. Because the lock persists across the gesture, it affects any panning that involves two directions—whether both axes are panned simultaneously (diagonal panning) or one after the other within a single gesture (such as curved, circular, or L-shaped paths). The CSS `scroll-axis-lock` property disables this heuristic directly on a native scroll container, allowing unrestricted two-dimensional panning while preserving compositor-thread scrolling, momentum physics, native scrollbars, and keyboard navigation.
+
+## Implementation
+
+### 1. Disable axis-locking and contain overscroll on the two-dimensional scroll container
+
+Apply `scroll-axis-lock: none` directly to the element that establishes the two-dimensional scroll container (`overflow: auto` or `overflow: scroll`). While a 2D scroll container can already update scroll deltas along both axes under the default `auto` value, `auto` allows the browser's railing heuristic to kick in when a gesture starts predominantly along one axis. Setting `scroll-axis-lock: none` prevents that railing from engaging across touchscreens, trackpads, and mouse wheels.
+
+Pair `scroll-axis-lock: none` with `overscroll-behavior: none` (or `overscroll-behavior: contain`) on the scroll container so that reaching an edge does not chain scrolling to the parent page or trigger accidental browser overscroll navigations (such as horizontal back/forward swipe navigation or pull-to-refresh).
+
+### 2. Preserve keyboard focusability and accessibility
+
+Because a 2D panning surface often lacks focusable child controls (for example, a map or zoomed image), ensure keyboard users can focus the container and pan it with the Arrow keys by adding `tabindex="0"`, an appropriate `role` and accessible label, and a visible `:focus-visible` indicator.
+
+## Example Code
+
+```html
+<!-- Make the 2D scroll container keyboard-focusable and labeled so keyboard
+ users can focus the viewport and pan in all directions with Arrow keys. -->
+<div class="pan-viewport" tabindex="0" role="region" aria-label="Interactive canvas">
+ <div class="pan-surface">
+ <!-- 2D overflowing content (map tiles, zoomed image, canvas nodes, or grid) -->
+ </div>
+</div>
+```
+
+```css
+.pan-viewport {
+ /* Example viewport dimensions; adjust to fit your layout. */
+ inline-size: 100%;
+ block-size: 500px;
+
+ /* MANDATORY: Establish a scroll container that can overflow on both axes. */
+ overflow: auto;
+
+ /* MANDATORY: Prevent browser scroll axis-locking ("railing") from kicking in
+ so 2D gestures never get locked to a single axis. */
+ scroll-axis-lock: none;
+
+ /* Contain scrolling and prevent accidental swipe navigations at edges
+ (use `none` or `contain`). */
+ overscroll-behavior: none;
+}
+
+/* Provide a clear focus indicator when keyboard users focus the viewport. */
+.pan-viewport:focus-visible {
+ outline: 3px solid #005fcc;
+ outline-offset: 2px;
+}
+
+.pan-surface {
+ /* Example surface dimensions larger than .pan-viewport in both axes. */
+ inline-size: 3000px;
+ block-size: 3000px;
+}
+```
+
+## Best Practices & Constraints
+
+- **Apply it to the scroll container itself, not an ancestor wrapper**: `scroll-axis-lock` is not inherited, so setting it on a wrapper has no effect on descendant scroll containers.
+- **Contain overscroll and prevent accidental navigations**: Add `overscroll-behavior: none` or `overscroll-behavior: contain` to the 2D scroll container so panning into a boundary does not chain to the parent page or trigger browser back/forward swipe navigation and pull-to-refresh gestures.
+- **Nested one-dimensional panels keep railing automatically**: Because `scroll-axis-lock` does not inherit, a sidebar or inspector panel nested inside `.pan-viewport` retains the default `scroll-axis-lock: auto` behavior.
+- **Keep `auto` on standard vertical feeds, articles, and one-dimensional lists**: Axis-locking prevents unintentional perpendicular drift in unidirectional content.
+- **Do not set `touch-action: none` unconditionally**: `touch-action` controls whether the browser handles touch gestures at all (and has no effect on trackpad or wheel input), so setting it disables native compositor touch scrolling. Only apply it inside `@supports not (scroll-axis-lock: none)` when implementing the JavaScript pointer fallback.
+- **Pan with `scrollLeft` / `scrollTop`, never CSS `transform`**: Translating the surface with `transform` stops the element from functioning as a scroll container—breaking native scrollbars, boundary clamping, keyboard Arrow-key scrolling, `scroll` events, `IntersectionObserver`, and scroll-driven animations.
+
+## Fallback strategies
+
+Browser support for scroll-axis-lock: Limited availability.
+Supported by: Chrome 153.
+Unsupported in: Edge, Firefox, and Safari.
+
+Choose between **progressive enhancement** and a **JavaScript fallback** based on your application's requirements:
+
+### Option 1: Progressive Enhancement (No JavaScript)
+
+Use progressive enhancement when preserving native compositor-thread touch scrolling, inertial fling momentum, and pinch-to-zoom is more important than eliminating axis-locking in unsupported browsers:
+
+- **Supporting browsers**: The browser prevents its axis-locking ("railing") heuristic from kicking in on the 2D scroll container during scroll gestures.
+- **Unsupported browsers**: Browsers that do not recognize `scroll-axis-lock: none` safely ignore the declaration and keep their default `auto` 2D scrolling behavior—scrolling across both axes natively, while still railing gestures that begin predominantly along a single axis.
+
+### Option 2: JavaScript Fallback (`wheel` + `pointermove` with `scrollLeft`/`scrollTop`)
+
+If unrestricted two-dimensional panning across all browsers is required, use `@supports not (scroll-axis-lock: none)` and `CSS.supports('scroll-axis-lock', 'none')` to conditionally intercept `wheel` and pointer drag gestures.
+
+Because `wheel` (`e.deltaX`, `e.deltaY`) and `pointermove` (`e.clientX`, `e.clientY`) expose raw, unlocked 2D deltas before the browser's scrolling engine applies axis-locking, you can apply those deltas directly to `scrollLeft` and `scrollTop`:
+
+- **Why `scrollLeft`/`scrollTop` instead of CSS `transform`**: Updating `scrollLeft` and `scrollTop` keeps the element as a true scroll container. The browser automatically clamps scroll positions to `[0, scrollWidth - clientWidth]` and `[0, scrollHeight - clientHeight]`, native scrollbars stay synchronized, keyboard Arrow-key scrolling continues to work, and `scroll` events and `IntersectionObserver` fire normally.
+- **Trade-offs**: Intercepting `wheel` with `{ passive: false }` moves scrolling onto the main thread, and setting `touch-action: none` on touchscreens disables native inertial fling momentum after `pointerup` (as well as native pinch-to-zoom).
+
+```css
+/* Only disable native touch scrolling when scroll-axis-lock is unsupported
+ and the JavaScript pointer fallback below is active. */
+@supports not (scroll-axis-lock: none) {
+ .pan-viewport {
+ touch-action: none;
+ }
+}
+```
+
+```javascript
+// Only attach the main-thread gesture fallback when native support is missing
+if (!CSS.supports('scroll-axis-lock', 'none')) {
+ const viewport = document.querySelector('.pan-viewport');
+ let lastPointer = null;
+
+ // 1. Trackpad and mouse wheel fallback
+ viewport.addEventListener(
+ 'wheel',
+ (e) => {
+ e.preventDefault();
+ viewport.scrollLeft += e.deltaX;
+ viewport.scrollTop += e.deltaY;
+ },
+ { passive: false },
+ );
+
+ // 2. Touch and pointer drag fallback
+ viewport.addEventListener('pointerdown', (e) => {
+ // Ignore non-primary buttons and clicks on native scrollbars
+ const rect = viewport.getBoundingClientRect();
+ if (
+ !e.isPrimary ||
+ e.button !== 0 ||
+ e.clientX - rect.left - viewport.clientLeft >= viewport.clientWidth ||
+ e.clientY - rect.top - viewport.clientTop >= viewport.clientHeight
+ ) {
+ return;
+ }
+ lastPointer = { x: e.clientX, y: e.clientY };
+ viewport.setPointerCapture(e.pointerId);
+ });
+
+ viewport.addEventListener('pointermove', (e) => {
+ if (!lastPointer) return;
+ viewport.scrollLeft -= e.clientX - lastPointer.x;
+ viewport.scrollTop -= e.clientY - lastPointer.y;
+ lastPointer = { x: e.clientX, y: e.clientY };
+ });
+
+ const endPointerPan = () => {
+ lastPointer = null;
+ };
+ viewport.addEventListener('pointerup', endPointerPan);
+ viewport.addEventListener('pointercancel', endPointerPan);
+}
+```
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/motion.md b/skills/modern-web-guidance/guides/ui-behaviors/motion.md
index b263ad0..b617263 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/motion.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/motion.md
@@ -28,39 +28,46 @@ Use `prefers-reduced-motion` media queries to turn off heavy motion for users wh
- **Default to static views**: Consider defaulting to static states and allowing users to opt-in to motion.
- **Don't exceed flash limits (three per second)**: Never include rapid light-to-dark flashing. Such effects can cause seizures.
+**DO NOT** globally apply `animation-duration: 0.01ms;` as it can cause certain animations to become _more_ jarring.
+Instead, handle motion preferences on a case-by-case basis using one of two approaches, nesting the `@media` query inside the rule so both versions are kept together:
+
+- **Start with animations enabled by default, and tone them down using `@media (prefers-reduced-motion: reduce)`**:
+
```css
-/* Good: Dampen spin states for reduced motion queries */
-@media (prefers-reduced-motion: reduce) {
- .spinner {
+/* Good: Dampen spin states or slow down animations for reduced motion */
+.spinner {
+ animation: spin 1s linear infinite;
+ @media (prefers-reduced-motion: reduce) {
animation: none;
opacity: 0.5;
}
}
-```
-
-**DO NOT** globally apply `animation-duration: 0.01ms;` globally as it can cause certain animations to become _more_ jarring.
-Either apply reduced motion versions on a case by case basis, or use a custom property like:
-
-```css
-@property --animation-reduced {
- syntax: "*";
- inherits: false;
- initial-value: none;
-}
-@media (prefers-reduced-motion: reduce) {
- * {
- animation: var(--animation-reduced) !important;
+progress:not([value]) {
+ animation: slide 1s infinite linear;
+ @media (prefers-reduced-motion: reduce) {
+ animation-duration: 20s;
}
}
```
-Then, reduced motion versions can be kept together with the original animations:
+- **Start with no animations by default, and enable them using `@media (prefers-reduced-motion: no-preference)`**:
```css
+/* Good: Default to static or gentle states and opt-in to full motion */
+.spinner {
+ opacity: 0.5;
+ @media (prefers-reduced-motion: no-preference) {
+ opacity: 1;
+ animation: spin 1s linear infinite;
+ }
+}
+
progress:not([value]) {
- animation: slide 1s infinite linear;
- --animation-reduced: slide 20s infinite linear;
+ animation: slide 20s infinite linear;
+ @media (prefers-reduced-motion: no-preference) {
+ animation-duration: 1s;
+ }
}
```
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/scoped-component-transitions.md b/skills/modern-web-guidance/guides/ui-behaviors/scoped-component-transitions.md
new file mode 100644
index 0000000..5b33125
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-behaviors/scoped-component-transitions.md
@@ -0,0 +1,229 @@
+# Scoped Component Transitions
+
+Starting a view transition with `document.startViewTransition()` attaches the `::view-transition` overlay to the `:root` element, which blocks pointer events on the rest of the page, prevents concurrent transitions, and obscures `position: fixed` headers or open `[popover]` elements (even when nested view transition groups are used to prevent overflow bleeding).
+
+Calling `element.startViewTransition()` on a component root addresses this by scoping the transition to that DOM subtree: the `::view-transition` pseudo-element tree is injected directly onto the element, preserving external stacking contexts and page interactivity while allowing multiple components to transition concurrently.
+
+## Implementation
+
+### 1. Trigger a Scoped Transition
+
+Call `element.startViewTransition()` on the component's root container element instead of `document.startViewTransition()`. The element you call `startViewTransition()` on becomes the transition's scope (the scope element): only elements within its subtree are captured, only rendering of the scope halts during the update callback, and the resulting `::view-transition` overlay matches the scope element's size, shape, and stacking context.
+
+### 2. Name Participating Elements
+
+Assign a `view-transition-name` to child elements inside the scope that should animate. You can use `view-transition-name: match-element` on dynamic list items to automatically derive each element's transition name from its DOM node identity, or assign explicit names (which only need to be unique within that scope).
+
+Names are isolated within each scope, preventing collisions across components in different parts of the DOM. However, `view-transition-name`s can collide with names in nested scoped view transitions. To prevent this, add `view-transition-scope: all` to the child scope element.
+
+### 3. Self-Participation and Overflow Clipping
+
+The scope element automatically participates in its own view transition because the user-agent stylesheet applies `view-transition-name: root` and `view-transition-group: contain` to it. This way, when the scope’s geometry is affected by the change you make in the DOM, it smoothly animates its own geometry alongside its children, as part of the View Transition.
+
+When the scope clips its overflow (`overflow: hidden`, `scroll`, or `clip`), `::view-transition-group-children(root)` automatically applies `overflow: clip`, preventing transitioning children from bleeding outside the component bounds.
+
+> **Note:** Automatic overflow clipping only applies to the scope element itself (`root`). If a captured element inside the scope clips its own overflow and contains other nested captured elements (for example, a scrollable or clipped `<ul>` inside a `.card`), use Nested View Transition Groups so those nested elements stay clipped to their outer captured container:
+>
+> ```css
+> .card ul {
+> height: 200px;
+> overflow-y: auto;
+> view-transition-name: match-element;
+> view-transition-group: contain;
+> view-transition-class: list;
+> }
+>
+> ::view-transition-group-children(.list) {
+> overflow: clip;
+> }
+> ```
+
+### 4. Concurrent and Nested Transitions
+
+Separate component subtrees can run `element.startViewTransition()` concurrently without skipping each other. Active scopes automatically receive `view-transition-scope: all` in the UA stylesheet so internal `view-transition-name` values do not leak into outer transitions. Apply `view-transition-scope: all` in CSS on repeated component containers to prevent outer transitions from capturing internal names even when the component is idle.
+
+If an outer transition needs to move a component while its inner transition is active, assign a `view-transition-name` to an element wrapping the inner scope. The outer transition then captures and animates only the wrapper instead of the inner scope element, allowing the inner transition to run to completion.
+
+## Example
+
+No CSS is needed on the scope element itself (`.card` or `.card ul`) to establish the scope—the scope is determined by calling `startViewTransition()` on the element instead of `document` (if the component will be nested inside an outer view transition, see [Running an outer transition](#running-an-outer-transition) for `view-transition-scope: all`).
+
+```css
+/* 1. Name participating child items */
+.card ul li {
+ view-transition-name: match-element;
+}
+
+/* 2. OPTIONAL: Customize transition timing (300ms is an example duration) */
+::view-transition-group(*) {
+ animation-duration: 300ms;
+ animation-timing-function: ease-in-out;
+}
+
+/* 3. MANDATORY: Respect user preference for reduced motion */
+@media (prefers-reduced-motion: reduce) {
+ ::view-transition-group(*),
+ ::view-transition-old(*),
+ ::view-transition-new(*) {
+ animation: none !important;
+ }
+}
+```
+
+```javascript
+// 1. Trigger a transition scoped to a single component subtree
+function runScopedTransition(scopeEl, updateDOM) {
+ // MANDATORY: Call startViewTransition on the component element, not document
+ const transition = scopeEl.startViewTransition(() => {
+ updateDOM();
+ });
+
+ // Re-triggering startViewTransition() on the same element skips the active transition
+ // and rejects `ready`. Catch the rejection to avoid unhandled promise rejection errors.
+ transition.ready.catch(() => {});
+}
+
+// 2. Reorder items by moving existing DOM nodes (required for `match-element`)
+// Scope to `listEl` since only the list order changes, keeping controls outside `listEl` interactive
+function reorderItems(listEl, orderedIds) {
+ const existing = new Map(
+ Array.from(listEl.children, (li) => [li.dataset.id, li]),
+ );
+
+ runScopedTransition(listEl, () => {
+ for (const id of orderedIds) {
+ const li = existing.get(id);
+ if (li) listEl.appendChild(li);
+ }
+ });
+}
+
+// 3. Remove an item while preserving exit animation and keyboard focus
+// Scope to the outer `cardEl` so the card itself also transitions its height change
+function removeItem(cardEl, itemEl) {
+ const hadFocus = itemEl.contains(document.activeElement);
+ const nextFocusTarget =
+ itemEl.nextElementSibling?.querySelector('button') ??
+ itemEl.previousElementSibling?.querySelector('button') ??
+ cardEl.querySelector('button');
+
+ runScopedTransition(cardEl, () => {
+ itemEl.remove();
+ if (hadFocus) {
+ nextFocusTarget?.focus();
+ }
+ });
+}
+```
+
+## Running an outer transition
+
+When starting a view transition outside of the intended scope (e.g. from a parent component, or from the document for a page-level transition), the outer transition will capture and animate the scope element and everything inside it.
+
+To prevent this from happening, wrap the scope element in a separate wrapper element with its own `view-transition-name`, and apply `view-transition-scope: all` to the inner scope element. This allows the wrapper itself to be captured and animated by the outer transition while preventing the inner scope's contents from being captured.
+
+```html
+<div class="page" id="page">
+ <div class="card-wrapper">
+ <section class="card" id="left">
+ <h2>Card A</h2>
+ <ul id="left-list">
+ <li>…</li>
+ </ul>
+ </section>
+ </div>
+ <div class="card-wrapper">
+ <section class="card" id="right">
+ <h2>Card B</h2>
+ <ul id="right-list">
+ <li>…</li>
+ </ul>
+ </section>
+ </div>
+</div>
+```
+
+```javascript
+document.querySelector('#page').startViewTransition(() => {
+ // do your DOM updates here...
+});
+```
+
+```css
+/* Apply a view-transition-name on the wrapper */
+.card-wrapper {
+ view-transition-name: match-element;
+}
+
+/* Prevent the contents of the card being captured by an outer transition */
+.card {
+ view-transition-scope: all;
+}
+
+.card ul li {
+ view-transition-name: match-element;
+}
+```
+
+Alternatively, you can allow the outer transition to capture the children. In order to retain clipping effects, resort to using Nested View Transition Groups to clip the captured children at the boundaries of their wrapper. In that case, though, you need to manually apply the `clip` onto the resulting `::view-transition-group-children()` pseudo.
+
+```css
+.card-wrapper {
+ overflow: clip;
+ view-transition-name: match-element; /* Capture me as part of the outer VT */
+ view-transition-group: contain; /* Nest children that also have a view-transition-name */
+ view-transition-class: card; /* For targeting purposes */
+}
+
+/* Manually copy back the clip onto the ::view-transition-group-children pseudo */
+::view-transition-group-children(.card) {
+ overflow: clip;
+}
+
+.card ul li {
+ view-transition-name: match-element;
+}
+```
+
+## Constraints & Accessibility
+
+- **MANDATORY**: Call `startViewTransition()` on the component root element rather than `document` so external `position: fixed` elements and `[popover]` overlays remain layered on top and the rest of the page stays interactive.
+- **MANDATORY**: Preserve and move existing DOM nodes (rather than recreating them with `innerHTML`) when using `view-transition-name: match-element`, as `match-element` tracks DOM node identity.
+- **MANDATORY**: Respect user preferences for reduced motion using `@media (prefers-reduced-motion: reduce)` by setting `animation: none !important` on `::view-transition-group(*)`, `::view-transition-old(*)`, and `::view-transition-new(*)`.
+- **MANDATORY**: Preserve keyboard focus when removing a focused element during a transition by shifting focus to an adjacent item or control inside the update callback.
+- **DO**: Use Nested View Transition Groups (`view-transition-group: contain` and `overflow: clip` on `::view-transition-group-children()`) when a captured element inside the scope clips its own overflow and contains nested captured elements.
+- **DO**: Attach `transition.ready.catch(() => {})` when rapid interactions can re-trigger `element.startViewTransition()` on the same scope element.
+- **DO**: Wrap an inner scope element in a separate named wrapper element if an outer transition needs to animate the component's position while an inner transition is running.
+- **DO NOT**: Set `view-transition-name: none` on a scope element that clips its overflow (`overflow: hidden`, `scroll`, or `clip`) or changes its own geometry, as opting out of self-participation disables automatic overflow clipping.
+
+## Fallback strategies
+
+Browser support for Element-scoped view transitions: Limited availability.
+Supported by: Chrome 147 (Apr 2026) and Edge 147 (Apr 2026).
+Unsupported in: Firefox and Safari.
+
+Baseline status for View transitions: Newly available. It's been Baseline since 2025-10-14.
+Supported by: Chrome 111 (Mar 2023), Edge 111 (Mar 2023), Firefox 144 (Oct 2025), and Safari 18 (Sep 2024).
+
+If your Baseline target does not support element-scoped view transitions, degrade gracefully by running the DOM update callback immediately without animation. While you could fall back to `document.startViewTransition()` this is not recommended for isolated component updates, as a document-scoped transition blocks concurrent component transitions and obscures `position: fixed` and `[popover]` elements in the top layer.
+
+```javascript
+// Feature detect specifically on Element.prototype (not document.startViewTransition)
+const supportsScopedTransition = 'startViewTransition' in Element.prototype;
+
+function runWithTransition(scopeEl, updateDOM) {
+ if (!supportsScopedTransition) {
+ // Fallback: apply the DOM update immediately without animation
+ updateDOM();
+ return;
+ }
+
+ const transition = scopeEl.startViewTransition(() => {
+ updateDOM();
+ });
+
+ transition.ready.catch(() => {});
+}
+```
+
+If you really need to have a fallback using `document.startViewTransition()`, you’ll need to make sure that clipping effects of containers are preserved, as detailed in the [Running an outer transition](#running-an-outer-transition) section. Note that this fallback approach breaks the ability to run multiple view transitions concurrently and will obscure `position: fixed` and `[popover]` elements in the top layer.
\ No newline at end of file
diff --git a/skills/modern-web-guidance/guides/ui-components/checkbox.md b/skills/modern-web-guidance/guides/ui-components/checkbox.md
index a386b8e..53e8ab2 100644
--- a/skills/modern-web-guidance/guides/ui-components/checkbox.md
+++ b/skills/modern-web-guidance/guides/ui-components/checkbox.md
@@ -11,7 +11,7 @@ For simple, brand-consistent styling that retains native rendering, keyboard beh
```css
.checkbox-native {
accent-color: #1a73e8;
-
+
/* Sizing is controlled via relative units */
inline-size: 1.25em;
aspect-ratio: 1;
@@ -119,6 +119,12 @@ selectAll.indeterminate = true;
```
- **DO** provide a `:disabled` style variant that lowers opacity and sets `cursor: not-allowed` to convey inactive states clearly.
+### Issues to be aware of when using accent-color
+
+Browser rendering of `accent-color` varies.
+For indicators generally painted over an accent color background, such as checkbox marks and radio-button dots, browsers may apply different treatments:
+- **Chromium** and **Firefox** generally select a contrasting indicator color.
+- **Safari** may instead preserve a white indicator in light mode or a black indicator in dark mode, while modifying the accent color behind it. This adjustment does not always provide sufficient contrast for every supplied color, so test important combinations in Safari, including both light and dark color schemes. Do not assume that Safari will automatically choose whichever indicator color provides the best contrast.
## Fallback strategies
@@ -129,6 +135,7 @@ Supported by: Chrome 93 (Aug 2021), Edge 93 (Sep 2021), Firefox 92 (Sep 2021), a
The `accent-color` property is progressive enhancement.
Browsers that do not support this property will ignore it and use their default UI colors.
+
### CSS Masks
Baseline status for Masks: Widely available. It's been Baseline since 2023-12-07.
diff --git a/skills/modern-web-guidance/guides/ui-components/progress.md b/skills/modern-web-guidance/guides/ui-components/progress.md
new file mode 100644
index 0000000..cea9a38
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-components/progress.md
@@ -0,0 +1,181 @@
+# Build a Styled Progress Bar
+
+The `<progress>` element is the semantic way to represent the completion progress of a task, like downloading or uploading information or completing part of a multi-step process. Using the native element helps with accessibility, as screen readers have an implicit `role="progressbar"` and can announce values.
+
+This guide implements a fully styled horizontal progress bar with style customizations.
+
+## Progress bar or progress ring?
+
+- If space is constrained or a square aspect ratio is preferable, consider using a circular progress bar (progress ring): `progress-ring` (via `npx -y modern-web-guidance@latest retrieve "progress-ring"`)
+- Prefer spinners for most indeterminate progress scenarios (`spinner` (via `npx -y modern-web-guidance@latest retrieve "spinner"`)). Use indeterminate progress bars when the indeterminate state is temporary and will soon be replaced by a determinate progress bar (e.g. waiting for metadata around an upload before a progress % can be shown)
+
+## Markup
+
+1. **Use a native `<progress>` element**: It provides built-in accessibility and platform-consistent behavior.
+2. Use `max` if a scale different from the default 0-1 scale is needed.
+3. For a specific progress value, set a `value` attribute. Omit `value` for an indeterminate state (e.g. before more concrete feedback starts).
+4. Use `<label for="...">`, `aria-labelledby`, or `aria-label` to associate the progress element with a label.
+
+## What type of customization is needed?
+
+For limited styling, these properties are sufficient:
+- `accent-color` to change the color of the progress bar
+- `width` / `inline-size` to change the width of the progress bar
+- `height`/`block-size` applies inconsistently — test first
+- `writing-mode: vertical-lr` for vertical bars.
+- Effects that apply after painting: `opacity`, `filter`, `clip-path`, masks, transforms, `box-shadow`, etc.
+
+If limited styling suffices, skip the next section.
+
+WARNING: Certain properties (e.g. `border-radius`, `background`, `border`) will silently disable the default progress bar styling. If you need styling beyond the properties above, you must implement fully custom styling as described in the next section. Do NOT apply more extensive styling "just in case it works".
+
+## Fully custom styling
+
+### 1. Basic setup
+
+- MANDATORY: Use `appearance: none` to enable custom styling.
+- Reset UA borders with `border: 0 solid`
+- To clip the active bar to the element’s border-radius, use `overflow: clip` OR apply the same `border-radius` to the bar. Do NOT use `border-radius: inherit` on the bar, which depends on the specific structure of elements in the shadow DOM.
+
+```css
+progress {
+ /* Reset default browser styles */
+ appearance: none;
+ border: 0 solid;
+ /* Clip bar to element’s border-radius */
+ overflow: clip;
+}
+```
+
+### 2. Styling
+
+- Style the track on the `progress` element itself.
+- Use the appropriate browser-targeted pseudo-element to target the progress bar itself: `::-webkit-progress-value` for WebKit/Blink and `::-moz-progress-bar` for Firefox.
+- MANDATORY: Do NOT group `-webkit-` and `-moz-` pseudo-elements in the same rule. The rule will be deemed invalid and will be ignored. `:is()` and `:where()` do not help here, as they don't support pseudo-elements.
+- Each browser-targeted pseudo-element should appear exactly once. State-specific customizations (such as the indeterminate segment size and animation) should be routed through custom properties set on the `progress` element itself.
+- Optional: Transition `inline-size` on the fill so determinate value changes animate instead of jumping. Firefox sizes the fill in layout and ignores it, which is harmless.
+
+```css
+progress {
+ --progress-bar-radius: 1e5px;
+ border-radius: var(--progress-bar-radius);
+ /* Apply color for custom progress track (background) */
+ background: var(--progress-bar-track, var(--color-neutral-90));
+ /* Subtle depth on the empty part of the track */
+ box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
+}
+
+/* Let <progress> styling show through */
+progress::-webkit-progress-bar {
+ background: transparent;
+}
+
+/* Webkit, Chrome */
+progress::-webkit-progress-value {
+ background: var(--progress-bar-fill, var(--accent-color));
+ border-radius: var(--progress-bar-radius);
+ transition: inline-size 0.3s;
+}
+
+/* Firefox */
+progress::-moz-progress-bar {
+ background: var(--progress-bar-fill, var(--accent-color));
+ border-radius: var(--progress-bar-radius);
+ transition: inline-size 0.3s;
+}
+```
+
+### 3. Indeterminate state styling
+
+**Add a custom animation for the indeterminate state:** Turn the fill pseudo-element into a short segment and slide it along the track.
+- Style the fill itself; do NOT recreate it as a background on `progress`.
+- The indeterminate fill exists only through its animation: the keyframes set its length with a real `inline-size` (this beats Chromium's UA inline `inline-size`) and moves it with `translate`. Do NOT use `scale` for the length; it distorts any pattern painted on the fill.
+- `translate` percentages resolve against the fill's own width, so express positions in track units instead: make `progress` an inline-size container and use `cqi` in the keyframes. Include `margin-right: auto` in `from, to` so Chromium lays the fill out at the physical left in RTL too.
+- Use transforms, not margins, to move the fill.
+ - Transforms keep the animation in the compositor (unless `inline-size` is also being animated)
+ - Margins break in RTL, for two separate reasons:
+ - Firefox positions the indeterminate fill using only its physical left margin, so `margin-inline-start` has no effect in RTL and the fill never moves.
+ - In Chromium and WebKit, which lay the fill out as a normal block, once a margin pushes the fill past the end of the track the margins add up to more than the track. Standard CSS resolves that by ignoring `margin-left` in RTL, so the segment jumps to the edge instead of sliding off it.
+ - `translate` is applied after layout, so neither problem applies.
+- To mirror the motion in RTL (as Chrome's native bar does), reverse the animation under `:dir(rtl)`:
+
+```css
+progress:dir(rtl) {
+ --progress-bar-indeterminate-animation: progress-bar-indeterminate var(--progress-bar-indeterminate-animation-duration) infinite linear reverse;
+}
+```
+
+- Define the public `--progress-bar-indeterminate-*` properties on `progress` (their name already scopes them to the state) so consumers can override them without knowing about `:indeterminate`.
+- To vary the segment length (e.g. the leading edge races ahead and the trailing edge catches up), set `--progress-bar-indeterminate-animation` to two concurrent animations: one whose keyframes animate `translate` in `cqi` (position) and one whose keyframes animate `inline-size` (length), so each gets its own keyframes and easing. Do NOT try to shape both edges in a single keyframe list; per-keyframe `animation-timing-function` applies to every property in that keyframe.
+- `--progress-bar-animation` applies in both states and can be used for effects such as a determinate shimmer. `revert-rule` is used to only override when it is set, to maximize composability.
+- Never disable the indeterminate animation (`animation: none` leaves a zero-width fill in Chromium). For reduced motion, slow it down instead.
+
+```css
+progress {
+ /* Lets the fill position itself in track units (cqi) */
+ container-type: inline-size;
+ /* Segment length relative to the track */
+ --progress-bar-indeterminate-size: 30%;
+ --progress-bar-indeterminate-animation-duration: 1.5s;
+
+ /* Respect prefers-reduced-motion */
+ @media (prefers-reduced-motion: reduce) {
+ --progress-bar-indeterminate-animation-duration: 10s;
+ }
+}
+
+progress:indeterminate {
+ --progress-bar-animation: var(
+ --progress-bar-indeterminate-animation,
+ progress-bar-indeterminate var(--progress-bar-indeterminate-animation-duration) infinite linear
+ );
+}
+
+/* Add to the existing pseudo-element rules */
+progress::-webkit-progress-value {
+ animation: var(--progress-bar-animation, revert-rule);
+}
+
+progress::-moz-progress-bar {
+ animation: var(--progress-bar-animation, revert-rule);
+}
+
+/* Physical: left to right regardless of direction (reverse under :dir(rtl) to mirror). */
+@keyframes progress-bar-indeterminate {
+ from, to {
+ inline-size: var(--progress-bar-indeterminate-size);
+ /* Pin to the physical left; Chromium would otherwise lay the fill out at the inline start */
+ margin-right: auto;
+ }
+ from { translate: -100%; } /* Own width: fully outside the left edge */
+ to { translate: 100cqi; } /* Track width: fully outside the right edge */
+}
+```
+
+### Additional Accessibility Considerations
+
+In addition to the guidelines mentioned above:
+* **Announce completion without stealing focus**: Do not set `tabindex` or call `.focus()` on `<progress>`, as it is non-interactive and moving focus to it disrupts keyboard users. To announce when a background task finishes, update a polite status element (`role="status"` or `aria-live="polite"`).
+* **Do not add fallback text inside `<progress>`**: Text inside `<progress>` is ignored by modern browsers and is not used by assistive technologies.
+* Avoid `aria-busy` + `aria-describedby` on an unlabeled generic `<div>`. `aria-busy` has inconsistent screen reader support, and `aria-describedby` on an unnamed `<div>` without a role is ignored by assistive technologies. If a region's content is not ready while loading, hide it with `hidden` or `aria-hidden="true"`.
+* **DO** ensure proper contrast between the progress bar and track when adding custom styles.
+* **Consider alternatives to represent indeterminate state**: Indeterminate progress bar animations displayed in parallel to other content can be considered distracting for some users.
+
+## Fallback strategies
+
+### Fallbacks & browser support for accent-color
+
+Browser support for accent-color: Limited availability.
+Supported by: Chrome 93 (Aug 2021), Edge 93 (Sep 2021), Firefox 92 (Sep 2021), and Safari 26.2 (Dec 2025).
+
+The `accent-color` property is progressive enhancement.
+Browsers that do not support this property will ignore it and use their default UI colors.
+
+If `accent-color` is not supported and styling the progress bar is required, use the customized styling method to apply preferred styling to the progress bar.
+
+### Fallbacks & browser support for `revert-rule`
+
+Baseline status for revert-rule: Newly available. It's been Baseline since 2026-09-14.
+Supported by: Chrome 148 (May 2026), Edge 148 (May 2026), Firefox 150 (Apr 2026), and Safari 27.
+
+If `revert-rule` is not supported, `animation: var(--progress-bar-animation, revert-rule)` falls back to `animation-name: revert-rule` with a `0s` duration when `--progress-bar-animation` is unset, which is a harmless no-op when no `@keyframes revert-rule` exists.
diff --git a/skills/modern-web-guidance/guides/ui-components/spinner.md b/skills/modern-web-guidance/guides/ui-components/spinner.md
index 46d04de..28c582b 100644
--- a/skills/modern-web-guidance/guides/ui-components/spinner.md
+++ b/skills/modern-web-guidance/guides/ui-components/spinner.md
@@ -104,26 +104,26 @@ progress.loading-spinner:indeterminate {
animation:
progress-spin var(--_used-spinner-duration) linear infinite
var(--progress-dash-animation, );
+}
- @keyframes progress-spin {
- to {
- rotate: 1turn;
- }
+@keyframes progress-spin {
+ to {
+ rotate: 1turn;
}
+}
- @keyframes progress-dash {
- from {
- --arc-start: 0deg;
- --arc-end: 3deg;
- }
- 50% {
- --arc-start: 100deg;
- --arc-end: 358deg;
- }
- to {
- --arc-start: 360deg;
- --arc-end: 363deg;
- }
+@keyframes progress-dash {
+ from {
+ --arc-start: 0deg;
+ --arc-end: 3deg;
+ }
+ 50% {
+ --arc-start: 100deg;
+ --arc-end: 358deg;
+ }
+ to {
+ --arc-start: 360deg;
+ --arc-end: 363deg;
}
}
```
diff --git a/skills/modern-web-guidance/guides/visual-design/apply-webgl-shaders.md b/skills/modern-web-guidance/guides/visual-design/apply-webgl-shaders.md
index ba42b5e..accc235 100644
--- a/skills/modern-web-guidance/guides/visual-design/apply-webgl-shaders.md
+++ b/skills/modern-web-guidance/guides/visual-design/apply-webgl-shaders.md
@@ -6,20 +6,23 @@ WebGL shaders provide powerful GPU-accelerated visual effects, enabling advanced
1. Check if HTML-in-Canvas is supported in the browser:
-```
-if ('requestPaint' in HTMLCanvasElement.prototype) {
+```js
+if ('content' in HTMLCanvasElement.prototype) {
// Use HTML in Canvas API
} else {
// Use fallback strategy
}
```
-2. Add the `layoutsubtree` attribute to the `<canvas>` HTML element.
-3. Place your HTML content inside the `<canvas>` element with the `layoutsubtree` attribute.
+> [!NOTE]
+> HTML-in-Canvas is supported from Chrome 157.
+
+2. Add the `content="drawable"` attribute to the `<canvas>` HTML element.
+3. Place your HTML content inside the `<canvas>` element, and add the `drawable` attribute to every element that you draw. An element with `drawable` captures its subtree, except nested descendants that are also `drawable`.
```html
-<canvas id="canvas" layoutsubtree>
- <div id="html-content"></div>
+<canvas id="canvas" content="drawable">
+ <div id="html-content" drawable></div>
</canvas>
```
@@ -45,21 +48,84 @@ const options = supportsDevicePixelContentBox
observer.observe(canvas, options);
```
-5. Render the HTML content to the canvas inside a `canvas.onpaint` event handler using the `texElementImage2D` method:
+5. Pre-allocate the texture backing first using the `texImage2D` method. The snippets in this guide use a WebGL 2 context (`canvas.getContext("webgl2")`).
+
+Allocate texture storage first by calling `texImage2D()` with `null` instead of pixel data, which reserves GPU memory of the given size and format without uploading any pixels. Follow these rules:
+ - Size the texture from `canvas.captureElementImage(element)`. Its `width` and `height` are in canvas grid (backing store) pixels, so round them up with `Math.ceil()`. `captureElementImage()` throws if the element has no paint record yet: call `requestPaint()`, and retry on the next `paint` event.
+ - Allocate level 0 only on the first upload, or when the size changes, because reallocating clears the texture. Use mutable storage: immutable `texStorage2D()` storage can't be resized when the element changes size.
+
+```js
+// Returns the element's size in canvas grid pixels, or null if the element
+// has no paint record yet.
+function getElementImageSize(canvas, element) {
+ let elementImage;
+ try {
+ elementImage = canvas.captureElementImage(element);
+ } catch (err) {
+ canvas.requestPaint(); // No paint record yet: retry on the next paint event.
+ return null;
+ }
+ const width = Math.ceil(elementImage.width);
+ const height = Math.ceil(elementImage.height);
+ elementImage.close();
+ return width > 0 && height > 0 ? { width, height } : null;
+}
+
+// Binds the texture, and allocates its storage on the first upload, and when
+// the element size changes. `state` stores the allocated size.
+function allocateElementTexture(gl, texture, state, width, height) {
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ if (state.width === width && state.height === height) return;
+
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0, // Mipmap level
+ gl.RGBA8, // Internal format: 8 bits per RGBA channel
+ width, // Size in canvas grid pixels
+ height,
+ 0, // Border: must be 0
+ gl.RGBA, // Format and type that match RGBA8
+ gl.UNSIGNED_BYTE,
+ null // null reserves GPU memory without uploading pixels
+ );
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ state.width = width;
+ state.height = height;
+}
+
+const texture = gl.createTexture();
+const textureState = { width: 0, height: 0 };
+```
+
+6. Render the HTML content to the texture inside a `canvas.onpaint` event handler using the `texElementSubImage2D` method. Follow these rules:
+ - An element can only be uploaded after the canvas has painted it. Upload from the `paint` event, and call `canvas.requestPaint()` to request one.
+ - Pass `{ width, height }` in the config. It makes the copy fill the allocated texture regardless of how the canvas is scaled.
+ - Reallocate the texture if the size changed, as shown in step 5.
```js
+// Uploads the element into the texture. Returns false if the element has no
+// paint record yet. In that case, it's uploaded on the next paint event.
+function uploadElementWebGL(gl, canvas, texture, element, state) {
+ const size = getElementImageSize(canvas, element);
+ if (!size) return false;
+ const { width, height } = size;
+
+ // Bind the texture, and reallocate it if the size changed (step 5).
+ allocateElementTexture(gl, texture, state, width, height);
+ gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, element, { width, height });
+ return true;
+}
+
canvas.onpaint = () => {
- if (gl.texElementImage2D) {
- try {
- gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);
- } catch (err) {
- console.error('texElementImage2D copy failed:', err);
- }
+ try {
+ uploadElementWebGL(gl, canvas, texture, uiElement, textureState);
+ } catch (err) {
+ console.error('texElementSubImage2D copy failed:', err);
}
};
```
- When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. Make sure you only re-render the canvas if there has been an update to the descendant HTML elements:
+ When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. `event.changedElements` lists the elements whose rendering changed. Make sure you only re-upload the texture if there has been an update to the descendant HTML elements:
```js
function render() {
@@ -71,76 +137,67 @@ canvas.onpaint = () => {
canvas.onpaint = (event) => {
if (event.changedElements && event.changedElements.length > 0) {
- // Update the texture with texElementImage2D, and update the CSS transform as shown in step 6
+ // Update the texture with uploadElementWebGL()
}
+ // Render the scene, and sync the element geometry as shown in step 7
};
```
-6. Update the CSS transform.
+7. Sync the element geometry.
-The browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
- - Convert WebGL MVP Matrix to DOM Matrix.
- - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from 0 to 1. If you don't normalize, your 200px button will look 200 times larger.
- - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the actual pixel dimensions of your `<canvas>` element on the screen. It also flips the Y-axis, because in WebGL, up is positive, but in CSS, down is positive.
- - Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element layer should sit to align with the 3D drawing.
- - Apply the transform to the HTML element. This moves the HTML element layer to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element.
+Compute a `DOMMatrix` that maps the element's border box, in CSS pixels, to the canvas, in CSS pixels. The browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
+ - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from -0.5 to 0.5. If you don't normalize, your 200px button will look 200 times larger. This step also flips the Y-axis, because in CSS, down is positive, but in WebGL, up is positive.
+ - Convert the WebGL MVP Matrix to a DOM Matrix.
+ - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the CSS pixel dimensions of your `<canvas>` element on the screen, and flips the Y-axis back.
+ - Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element should sit to align with the 3D drawing. The browser performs the perspective divide.
```js
- if (canvas.getElementTransform) {
- // 1. Convert WebGL MVP Matrix to DOM Matrix
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // 2. Normalize the HTML element (Canvas Grid pixels -> WebGL Model Space)
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = targetHTMLElement.offsetWidth * dprX;
- const gridHeight = targetHTMLElement.offsetHeight * dprY;
+ // Maps the element's border box (CSS pixels) to the canvas (CSS pixels), for a
+ // quad that spans -0.5 to 0.5 in model space and is drawn with the `mvp` matrix.
+ function computeCanvasTransform(canvas, element, mvp) {
+ const width = element.offsetWidth;
+ const height = element.offsetHeight;
+ // 1. Normalize the HTML element (CSS pixels -> WebGL Model Space)
const toGLModel = new DOMMatrix()
// Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ .scale(1 / width, -1 / height, 1 / height)
// Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
- .translate(-gridWidth / 2, -gridHeight / 2);
+ .translate(-width / 2, -height / 2);
- // 3. Map to the canvas viewport
+ // 2. Convert WebGL MVP Matrix to DOM Matrix
+ const mvpDOM = new DOMMatrix(Array.from(mvp));
+
+ // 3. Map to the canvas viewport, in CSS pixels
const clipToCanvasViewport = new DOMMatrix()
// Move center (0,0) to center of canvas
- .translate(canvas.width / 2, canvas.height / 2)
- // Scale normalized clip (-1..1) to viewport size
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+ .translate(canvas.clientWidth / 2, canvas.clientHeight / 2)
+ // Scale normalized clip (-1..1) to viewport size, and flip Y back
+ .scale(canvas.clientWidth / 2, -canvas.clientHeight / 2, canvas.clientHeight / 2);
// 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(toGLModel);
-
- // 5. Apply to the transform
- const computedTransform = canvas.getElementTransform(
- targetHTMLElement,
- screenSpaceTransform,
- );
- targetHTMLElement.style.transform = computedTransform.toString();
+ return clipToCanvasViewport.multiply(mvpDOM).multiply(toGLModel);
}
```
-7. [Troubleshooting] If the developer is experiencing a mismatch in the DOM logical layout in 3D even after applying the CSS transform from step 5, check if the developer is experiencing the issue in Chromium 148 or earlier. If that's the case, check if `transform.is2D` is correctly set to false for a 3D DOMMatrix. If not, re-initialize the DOMMatrix which corrects `is2D` to be false before applying the transform to the target HTML element. This issue is fixed in Chromium 149+, and if the developer is experiencing it in newer Chromium versions, the is2D value is not the cause:
+Then pass the transform to `canvas.updateElementGeometry()` as `canvasTransform`. This moves the HTML element to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element. The browser also uses the transform for the element's accessibility bounds, for example, for screen reader focus rings:
-```js
-if (transform.is2D) {
- // Workaround for Chromium bug https://crbug.com/512171941
- // affecting Chrome versions under 149 where `transform.is2D`
- // is incorrectly true for a 3D DOMMatrix. The assignment
- // below re-initializes the DOMMatrix which corrects is2D to be false.
- transform = DOMMatrix.fromFloat64Array(transform.toFloat64Array());
-}
-targetHTMLElement.style.transform = computedTransform.toString();
-```
+ ```js
+ canvas.updateElementGeometry(targetHTMLElement, {
+ canvasTransform: computeCanvasTransform(canvas, targetHTMLElement, htmlElementMVP),
+ });
+ ```
+
+Use these options to control hit testing:
+ - Each `updateElementGeometry()` call moves the element to the top of the hit-testing order. Pass `{ preserveHitTestOrder: true }` to keep its position.
+ - Call `canvas.clearElementGeometry(element)` to remove an element from hit testing, for example, when you hide it.
+ - Pass `{ canvasClip }`, a `DOMRectInit` in the coordinate space of `canvasTransform`, to limit the hit-testable area, for example, when only part of the element is drawn.
## Example code
```html
-<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
- <div id="ui-element">
+<canvas id="canvas" content="drawable" style="width: 400px; height: 400px;">
+ <div id="ui-element" drawable>
<p>WebGL UI Element</p>
<button>Action</button>
</div>
@@ -148,53 +205,32 @@ targetHTMLElement.style.transform = computedTransform.toString();
<script>
const canvas = document.getElementById("canvas");
- const gl = canvas.getContext("webgl");
+ const gl = canvas.getContext("webgl2");
const uiElement = document.getElementById("ui-element");
+ // getElementImageSize() and allocateElementTexture() are defined in step 5.
+ // uploadElementWebGL() is defined in step 6.
+ // computeCanvasTransform() is defined in step 7.
+
// Setup WebGL texture...
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
+ const textureState = { width: 0, height: 0 };
canvas.onpaint = () => {
// 1. Update texture with HTML content
- if (gl.texElementImage2D) {
- try {
- gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);
- } catch (err) {
- console.error('texElementImage2D copy failed:', err);
- }
+ try {
+ uploadElementWebGL(gl, canvas, texture, uiElement, textureState);
+ } catch (err) {
+ console.error('texElementSubImage2D copy failed:', err);
}
// ... Render your 3D scene here, calculating htmlElementMVP matrix ...
- // 2. Sync DOM position with 3D scene
- if (canvas.getElementTransform) {
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // Recalculate the DPR compensation mapping
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = uiElement.offsetWidth * dprX;
- const gridHeight = uiElement.offsetHeight * dprY;
-
- const cssToUnitSpace = new DOMMatrix()
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
- .translate(-gridWidth / 2, -gridHeight / 2);
-
- const clipToCanvasViewport = new DOMMatrix()
- .translate(canvas.width / 2, canvas.height / 2)
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
-
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(cssToUnitSpace);
-
- const computedTransform = canvas.getElementTransform(
- uiElement,
- screenSpaceTransform,
- );
- uiElement.style.transform = computedTransform.toString();
- }
+ // 2. Sync DOM position, hit testing, and accessibility bounds with 3D scene
+ canvas.updateElementGeometry(uiElement, {
+ canvasTransform: computeCanvasTransform(canvas, uiElement, htmlElementMVP),
+ });
};
</script>
```
@@ -202,10 +238,13 @@ targetHTMLElement.style.transform = computedTransform.toString();
## Best Practices
- **MANDATORY**: Check browser support for the HTML-in-Canvas API before using it.
-- **MANDATORY**: Always add the `layoutsubtree` attribute to the `<canvas>` element.
+- **MANDATORY**: Always add the `content="drawable"` attribute to the `<canvas>` element.
+- **MANDATORY**: ALWAYS add the `drawable` attribute to the direct children of the canvas.
+- **MANDATORY**: Add the `drawable` attribute to every element that you want to be able to draw independently from its parent elements.
- **MANDATORY**: Use an `onpaint` event handler to render the HTML content to the canvas.
-- **MANDATORY**: Use the `texElementImage2D` method to render the HTML content to the canvas.
-- **MANDATORY**: Update the CSS transform of the HTML element to match the transform of the rendered content by setting the `style.transform` property of the HTML element.
+- **MANDATORY**: Pre-allocate the texture buffer with `texImage2D()` once (when it's initialized or when the element size changes). Reallocate the texture only when the size changes, and set `TEXTURE_MIN_FILTER` to `LINEAR`.
+- **MANDATORY**: Use the `texElementSubImage2D` method to render the HTML content to a texture that you pre-allocate with `texImage2D()`, sized from `captureElementImage()`.
+- **MANDATORY**: Sync the geometry of the HTML element with the rendered content by calling `canvas.updateElementGeometry(element, { canvasTransform })`.
- **MANDATORY**: Use `ResizeObserver` to observe the screen size and update the canvas size to match device pixels.
- **DO NOT** embed cross-origin content in a canvas, as it is not supported.
- **DO NOT** initialize `ResizeObserver` within the `onpaint` event handler, as it may lead to memory leaks.
diff --git a/skills/modern-web-guidance/guides/visual-design/browser-ui-theming.md b/skills/modern-web-guidance/guides/visual-design/browser-ui-theming.md
index 9c8e8bb..50f7875 100644
--- a/skills/modern-web-guidance/guides/visual-design/browser-ui-theming.md
+++ b/skills/modern-web-guidance/guides/visual-design/browser-ui-theming.md
@@ -13,7 +13,7 @@ Example customizations that are possible:
- Use `accent-color` to apply the page's accent color to any browser-generated UI.
- Use `color-scheme` to have browser UI adapt to light/dark mode.
- Use `scrollbar-color` to customize scrollbar colors and `scrollbar-width` to control scrollbar thickness — keep the thumb visibly distinct from the track (≥3:1), and don't set `scrollbar-width: none` on scrollable regions (use it only when scrolling is fully replaced by another affordance).
-- Use `:user-invalid` / `:user-valid` for validity styling, **not** `:invalid` / `:valid` — they only match after the user has interacted with the field, avoiding the hostile default of flagging required-empty fields as errors on page load.
+- Use `:user-invalid` / `:user-valid` for validity styling, **not** `:invalid` / `:valid` — they only match after the user has interacted with the field, avoiding the hostile default of flagging required-empty fields as errors on page load. Exclude range sliders when targeting `input` broadly (e.g., `input:not(input[type="range"]):user-valid`) so adjusting a slider does not apply field validity borders or backgrounds to it.
- Buttons and text fields (including `<textarea>`) can generally be styled as normal elements.
- Use `font-size` to scale and other textual properties to control typography
diff --git a/skills/modern-web-guidance/guides/visual-design/dark-mode.md b/skills/modern-web-guidance/guides/visual-design/dark-mode.md
index e87caec..aeda645 100644
--- a/skills/modern-web-guidance/guides/visual-design/dark-mode.md
+++ b/skills/modern-web-guidance/guides/visual-design/dark-mode.md
@@ -82,7 +82,10 @@ html {
### Issues to be aware of when using accent-color
-- When placing visual elements over the accent color (e.g. a checkbox checkmark), Chrome and Safari will automatically select a contrasting color, whereas Safari will modify the accent color, and may not maintain adequate contrast.
+Browser rendering of `accent-color` varies.
+For indicators generally painted over an accent color background, such as checkbox marks and radio-button dots, browsers may apply different treatments:
+- **Chromium** and **Firefox** generally select a contrasting indicator color.
+- **Safari** may instead preserve a white indicator in light mode or a black indicator in dark mode, while modifying the accent color behind it. This adjustment does not always provide sufficient contrast for every supplied color, so test important combinations in Safari, including both light and dark color schemes. Do not assume that Safari will automatically choose whichever indicator color provides the best contrast.
### Scrollbar colors
diff --git a/skills/modern-web-guidance/guides/visual-design/export-html-media-from-canvas.md b/skills/modern-web-guidance/guides/visual-design/export-html-media-from-canvas.md
index b985a97..20fdaf4 100644
--- a/skills/modern-web-guidance/guides/visual-design/export-html-media-from-canvas.md
+++ b/skills/modern-web-guidance/guides/visual-design/export-html-media-from-canvas.md
@@ -6,19 +6,22 @@ Web applications frequently need to capture and export rich HTML content—such
1. Check if HTML-in-Canvas is supported in the browser:
-```
-if ('requestPaint' in HTMLCanvasElement.prototype) {
+```js
+if ('content' in HTMLCanvasElement.prototype) {
// Use HTML in Canvas API
} else {
// Use fallback strategy
}
```
-2. Initialize the canvas to support rendering of descendant HTML elements by adding the `layoutsubtree` attribute to the `<canvas>` HTML element. Place your HTML content inside the `<canvas>` element with the `layoutsubtree` attribute:
+> [!NOTE]
+> HTML-in-Canvas is supported from Chrome 157.
+
+2. Initialize the canvas to support rendering of descendant HTML elements by adding the `content="drawable"` attribute to the `<canvas>` HTML element. Place your HTML content inside the `<canvas>` element, and add the `drawable` attribute to every element that you draw. An element with `drawable` captures its subtree, except nested descendants that are also `drawable`:
```html
-<canvas id="canvas" layoutsubtree>
- <div id="html-content"></div>
+<canvas id="canvas" content="drawable">
+ <div id="html-content" drawable></div>
</canvas>
```
@@ -44,54 +47,138 @@ const options = supportsDevicePixelContentBox
observer.observe(canvas, options);
```
-4. Render the HTML content to the canvas inside a `canvas.onpaint` event handler:
-
-- In 2D context, use the `drawElementImage` method:
+4. Render the HTML content to the canvas inside a `canvas.onpaint` event handler.
+- In 2D context, use the `drawElementImage` method. It draws the last snapshot of a `drawable` element, and its drawable subtree (excluding other drawable children), starting at the element's border box, before CSS transforms:
```js
canvas.onpaint = () => {
ctx.reset();
// Draw the form element at x:0, y:0
- let transform = ctx.drawElementImage(form_element, 0, 0);
+ ctx.drawElementImage(form_element, 0, 0);
};
```
-- In WebGL context, use the `texElementImage2D` method:
+- In WebGL and WebGPU contexts, you copy the element into a texture. Size the texture from `canvas.captureElementImage(element)`. Its `width` and `height` are in canvas grid (backing store) pixels, so round them up with `Math.ceil()`. `captureElementImage()` throws if the element has no paint record yet: call `requestPaint()`, and retry on the next `paint` event.
```js
+// Returns the element's size in canvas grid pixels, or null if the element
+// has no paint record yet.
+function getElementImageSize(canvas, element) {
+ let elementImage;
+ try {
+ elementImage = canvas.captureElementImage(element);
+ } catch (err) {
+ canvas.requestPaint(); // No paint record yet: retry on the next paint event.
+ return null;
+ }
+ const width = Math.ceil(elementImage.width);
+ const height = Math.ceil(elementImage.height);
+ elementImage.close();
+ return width > 0 && height > 0 ? { width, height } : null;
+}
+```
+
+- In WebGL context, pre-allocate the texture backing first using the `texImage2D` method. The snippets in this guide use a WebGL 2 context (`canvas.getContext("webgl2")`). Allocate texture storage by calling `texImage2D()` with `null` instead of pixel data, which reserves GPU memory of the given size and format without uploading any pixels. Follow these rules:
+ - Size the texture from `captureElementImage()`, as shown above.
+ - Allocate level 0 only on the first upload, or when the size changes, because reallocating clears the texture. Use mutable storage: immutable `texStorage2D()` storage can't be resized when the element changes size.
+
+```js
+// Binds the texture, and allocates its storage on the first upload, and when
+// the element size changes. `state` stores the allocated size.
+function allocateElementTexture(gl, texture, state, width, height) {
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ if (state.width === width && state.height === height) return;
+
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0, // Mipmap level
+ gl.RGBA8, // Internal format: 8 bits per RGBA channel
+ width, // Size in canvas grid pixels
+ height,
+ 0, // Border: must be 0
+ gl.RGBA, // Format and type that match RGBA8
+ gl.UNSIGNED_BYTE,
+ null // null reserves GPU memory without uploading pixels
+ );
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ state.width = width;
+ state.height = height;
+}
+
+const texture = gl.createTexture();
+const textureState = { width: 0, height: 0 };
+```
+
+- Then, in WebGL context, render the HTML content to the texture using the `texElementSubImage2D` method. Follow these rules:
+ - Pass `{ width, height }` in the config. It makes the copy fill the allocated texture regardless of how the canvas is scaled.
+ - Reallocate the texture if the size changed, as shown above.
+
+```js
+// Uploads the element into the texture. Returns false if the element has no
+// paint record yet. In that case, it's uploaded on the next paint event.
+function uploadElementWebGL(gl, canvas, texture, element, state) {
+ const size = getElementImageSize(canvas, element);
+ if (!size) return false;
+ const { width, height } = size;
+
+ // Bind the texture, and reallocate it if the size changed (see above).
+ allocateElementTexture(gl, texture, state, width, height);
+ gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, element, { width, height });
+ return true;
+}
+
canvas.onpaint = () => {
- if (gl.texElementImage2D) {
- try {
- gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);
- } catch (err) {
- console.error('texElementImage2D copy failed:', err);
- }
+ try {
+ uploadElementWebGL(gl, canvas, texture, uiElement, textureState);
+ } catch (err) {
+ console.error('texElementSubImage2D copy failed:', err);
}
};
```
-- In WebGPU context, use the `copyElementImageToTexture` method:
+- In WebGPU context, use the `drawElementImageToTexture` method. Follow these rules:
+ - Create the texture with `COPY_DST` and `RENDER_ATTACHMENT` usage, and add `TEXTURE_BINDING` to sample it in shaders. A wrong usage is reported as a WebGPU validation error, not as an exception.
+ - Pass the texture size as `size`. Without `size`, a larger element is clipped to the texture. With `size`, the element is scaled to fill it.
+ - Recreate the texture when the element size changes, and rebuild the bind groups that reference it.
```js
+// Create the texture once, and recreate it
+// when the element size changes.
+function ensureElementTexture(device, state, width, height) {
+ if (state.texture?.width === width && state.texture?.height === height) {
+ return state.texture;
+ }
+ state.texture?.destroy();
+ state.texture = device.createTexture({
+ size: { width, height },
+ format: "rgba8unorm",
+ usage:
+ GPUTextureUsage.TEXTURE_BINDING |
+ GPUTextureUsage.COPY_DST |
+ GPUTextureUsage.RENDER_ATTACHMENT,
+ });
+ return state.texture; // Recreate the bind groups that used the previous texture.
+}
+
+const textureState = { texture: null };
+
canvas.onpaint = () => {
- if (root.device.queue.copyElementImageToTexture) {
- try {
- const sourceDict = { source: valueElement };
- const destDict = {
- destination: { texture: targetTexture },
- width: 512,
- height: 128,
- };
- root.device.queue.copyElementImageToTexture(sourceDict, destDict);
- } catch (err) {
- console.error('copyElementImageToTexture copy failed:', err);
- }
+ const size = getElementImageSize(canvas, uiElement);
+ if (!size) return;
+ const previousTexture = textureState.texture;
+ const texture = ensureElementTexture(device, textureState, size.width, size.height);
+ if (texture !== previousTexture) {
+ // New texture: create, or rebuild, the bind groups that reference it.
+ }
+ try {
+ device.queue.drawElementImageToTexture({ source: uiElement }, { texture, size });
+ } catch (err) {
+ console.error('drawElementImageToTexture copy failed:', err);
}
};
```
-
-When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. Make sure you only re-render the canvas if there has been an update to the descendant HTML elements:
+When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. `event.changedElements` lists the elements whose rendering changed. Make sure you only redraw the element, or re-upload its texture, if there has been an update to the descendant HTML elements:
```js
function render() {
@@ -103,92 +190,73 @@ When using a `requestAnimationFrame` loop to render the scene, call `canvas.requ
canvas.onpaint = (event) => {
if (event.changedElements && event.changedElements.length > 0) {
- // Update the texture with drawElementImage, texElementImage2D, or copyElementImageToTexture, and update the CSS transform as shown in step 5
+ // Redraw the element, or update its texture, as shown above
}
+ // In WebGL and WebGPU, render the scene, and sync the element geometry as shown in step 5
};
```
-5. Update the CSS transform.
+5. Sync the element geometry.
-- For the 2D context case, apply the transform returned by the rendering call to the `style.transform` property:
-
-```js
-canvas.onpaint = () => {
- ctx.reset();
- // Draw the form element at x:0, y:0
- let transform = ctx.drawElementImage(form_element, 0, 0);
+The browser needs to know where the HTML element is drawn, so that its DOM position matches its drawn pixels, for example, so that users can click and type into it. A canvas only hit tests the elements that are drawn with the 2D `drawElementImage()` method, or registered with `updateElementGeometry()`.
- // Sync the DOM location with the drawn location
- form_element.style.transform = transform.toString();
-};
-```
+- For the 2D context case, the browser syncs the element automatically. `drawElementImage()` aligns the DOM hit-test bounds and screen reader focus rings with the drawn coordinates, so you don't need to set `style.transform`. To manage the geometry manually, for example, when you draw the same element more than once, pass `{ preserveElementGeometry: true }` to `drawElementImage()`, and apply transforms with `canvas.updateElementGeometry()`.
-- For the 3D case with WebGL or WebGPU, the browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
- - Convert WebGL MVP Matrix to DOM Matrix.
- - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from 0 to 1. If you don't normalize, your 200px button will look 200 times larger.
- - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the actual pixel dimensions of your `<canvas>` element on the screen. It also flips the Y-axis, because in WebGL, up is positive, but in CSS, down is positive.
- - Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element layer should sit to align with the 3D drawing.
- - Apply the transform to the HTML element. This moves the HTML element layer to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element.
+- For the 3D case with WebGL or WebGPU, the canvas can't tell where the HTML element is drawn, so you have to tell it. Compute a `DOMMatrix` that maps the element's border box, in CSS pixels, to the canvas, in CSS pixels. The browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
+ - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from -0.5 to 0.5. If you don't normalize, your 200px button will look 200 times larger. This step also flips the Y-axis, because in CSS, down is positive, but in WebGL, up is positive.
+ - Convert the WebGL MVP Matrix to a DOM Matrix.
+ - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the CSS pixel dimensions of your `<canvas>` element on the screen, and flips the Y-axis back.
+ - Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element should sit to align with the 3D drawing. The browser performs the perspective divide.
```js
- if (canvas.getElementTransform) {
- // 1. Convert WebGL MVP Matrix to DOM Matrix
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // 2. Normalize the HTML element (Canvas Grid pixels -> WebGL Model Space)
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = targetHTMLElement.offsetWidth * dprX;
- const gridHeight = targetHTMLElement.offsetHeight * dprY;
+ // Maps the element's border box (CSS pixels) to the canvas (CSS pixels), for a
+ // quad that spans -0.5 to 0.5 in model space and is drawn with the `mvp` matrix.
+ function computeCanvasTransform(canvas, element, mvp) {
+ const width = element.offsetWidth;
+ const height = element.offsetHeight;
+ // 1. Normalize the HTML element (CSS pixels -> WebGL Model Space)
const toGLModel = new DOMMatrix()
// Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ .scale(1 / width, -1 / height, 1 / height)
// Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
- .translate(-gridWidth / 2, -gridHeight / 2);
+ .translate(-width / 2, -height / 2);
- // 3. Map to the canvas viewport
+ // 2. Convert WebGL MVP Matrix to DOM Matrix
+ const mvpDOM = new DOMMatrix(Array.from(mvp));
+
+ // 3. Map to the canvas viewport, in CSS pixels
const clipToCanvasViewport = new DOMMatrix()
// Move center (0,0) to center of canvas
- .translate(canvas.width / 2, canvas.height / 2)
- // Scale normalized clip (-1..1) to viewport size
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+ .translate(canvas.clientWidth / 2, canvas.clientHeight / 2)
+ // Scale normalized clip (-1..1) to viewport size, and flip Y back
+ .scale(canvas.clientWidth / 2, -canvas.clientHeight / 2, canvas.clientHeight / 2);
// 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(toGLModel);
-
- // 5. Apply to the transform
- const computedTransform = canvas.getElementTransform(
- targetHTMLElement,
- screenSpaceTransform,
- );
- targetHTMLElement.style.transform = computedTransform.toString();
+ return clipToCanvasViewport.multiply(mvpDOM).multiply(toGLModel);
}
```
-6. [Troubleshooting] If the developer is experiencing a mismatch in the DOM logical layout in 3D even after applying the CSS transform from step 5, check if the developer is experiencing the issue in Chromium 148 or earlier. If that's the case, check if `transform.is2D` is correctly set to false for a 3D DOMMatrix. If not, re-initialize the DOMMatrix which corrects `is2D` to be false before applying the transform to the target HTML element. This issue is fixed in Chromium 149+, and if the developer is experiencing it in newer Chromium versions, the is2D value is not the cause:
+Then pass the transform to `canvas.updateElementGeometry()` as `canvasTransform`. This moves the HTML element to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element. The browser also uses the transform for the element's accessibility bounds, for example, for screen reader focus rings:
-```js
-if (transform.is2D) {
- // Workaround for Chromium bug https://crbug.com/512171941
- // affecting Chrome versions under 149 where `transform.is2D`
- // is incorrectly true for a 3D DOMMatrix. The assignment
- // below re-initializes the DOMMatrix which corrects is2D to be false.
- transform = DOMMatrix.fromFloat64Array(transform.toFloat64Array());
-}
-targetHTMLElement.style.transform = computedTransform.toString();
-```
+ ```js
+ canvas.updateElementGeometry(targetHTMLElement, {
+ canvasTransform: computeCanvasTransform(canvas, targetHTMLElement, htmlElementMVP),
+ });
+ ```
+
+Use these options to control hit testing:
+ - Each `updateElementGeometry()` call moves the element to the top of the hit-testing order. Pass `{ preserveHitTestOrder: true }` to keep its position.
+ - Call `canvas.clearElementGeometry(element)` to remove an element from hit testing, for example, when you hide it.
-7. Use regular canvas export methods like `toDataURL()`, `toBlob()`, or `captureStream()`. The exported data will include the rendered HTML content.
+6. Use regular canvas export methods like `toDataURL()`, `toBlob()`, or `captureStream()`. The exported data will include the rendered HTML content.
## Example code
```html
<body>
- <canvas id="canvas" style="width: 400px; height: 200px;" layoutsubtree>
- <input id="element">
+ <canvas id="canvas" style="width: 400px; height: 200px;" content="drawable">
+ <input id="element" drawable>
</canvas>
<button id="download">Download Image</button>
@@ -201,10 +269,9 @@ targetHTMLElement.style.transform = computedTransform.toString();
canvas.onpaint = (event) => {
ctx.reset();
- // Draw the element into the canvas
- const transform = ctx.drawElementImage(element, 10, 10);
- // Synchronize DOM position for hit testing (typing)
- element.style.transform = transform.toString();
+ // Draw the element into the canvas. The browser synchronizes its
+ // DOM position for hit testing (typing).
+ ctx.drawElementImage(element, 10, 10);
};
download.onclick = () => {
@@ -235,10 +302,14 @@ targetHTMLElement.style.transform = computedTransform.toString();
## Best Practices
- **MANDATORY**: Check browser support for the HTML-in-Canvas API before using it.
-- **MANDATORY**: Always add the `layoutsubtree` attribute to the `<canvas>` element.
+- **MANDATORY**: Always add the `content="drawable"` attribute to the `<canvas>` element.
+- **MANDATORY**: Add the `drawable` attribute to every element that you draw, including direct children of the canvas.
- **MANDATORY**: Use an `onpaint` event handler to render the HTML content to the canvas.
-- **MANDATORY**: Use the `drawElementImage`, `texElementImage2D`, or `copyElementImageToTexture` methods to render the HTML content to the canvas.
-- **MANDATORY**: Update the CSS transform of the HTML element to match the transform of the rendered content by setting the `style.transform` property of the HTML element.
+- **MANDATORY**: Use the `drawElementImage` method in 2D, or `drawElementImageToTexture` in WebGPU, to render the HTML content to the canvas.
+- **MANDATORY**: In WebGL, pre-allocate the texture buffer with `texImage2D()` once (when it's initialized or when the element size changes). Reallocate the texture only when the size changes, and set `TEXTURE_MIN_FILTER` to `LINEAR`.
+- **MANDATORY**: In WebGL, use the `texElementSubImage2D` method to render the HTML content to a texture that you pre-allocate with `texImage2D()`, sized from `captureElementImage()`.
+- **MANDATORY**: In WebGPU, size the texture from `captureElementImage()`, and recreate it only when the size changes. Create the texture with `COPY_DST` and `RENDER_ATTACHMENT` usage, and pass the texture size as `size`.
+- **MANDATORY**: Sync the geometry of the HTML element with the rendered content. In 2D, `drawElementImage` does it automatically. In WebGL and WebGPU, call `canvas.updateElementGeometry(element, { canvasTransform })`.
- **MANDATORY**: Use `ResizeObserver` to observe the screen size and update the canvas size to match device pixels.
- **DO NOT** embed cross-origin content in a canvas, as it is not supported.
- **DO NOT** initialize `ResizeObserver` within the `onpaint` event handler, as it may lead to memory leaks.
diff --git a/skills/modern-web-guidance/guides/visual-design/expose-canvas-content-to-browser-features.md b/skills/modern-web-guidance/guides/visual-design/expose-canvas-content-to-browser-features.md
index 4f1eb2c..8569975 100644
--- a/skills/modern-web-guidance/guides/visual-design/expose-canvas-content-to-browser-features.md
+++ b/skills/modern-web-guidance/guides/visual-design/expose-canvas-content-to-browser-features.md
@@ -1,25 +1,28 @@
# Expose canvas content to browser features
-Regular `<canvas>` content is not exposed to browser features such as screen readers, indexing, translation tools, accessibility assistive tools, find-in-page, print, etc. With `HTML in canvas`, you can render real DOM directly in a canvas element. Adding the `layoutsubtree` attribute to a `<canvas>` HTML element allows rendering descendant HTML elements within the canvas's rendering context. You can use it to style and lay out text in a canvas, expose canvas content to browser features (like accessibility, translation, or find-in-page), and apply 2D and 3D effects to HTML.
+Regular `<canvas>` content is not exposed to browser features such as screen readers, indexing, translation tools, accessibility assistive tools, find-in-page, print, etc. With `HTML in canvas`, you can render real DOM directly in a canvas element. Adding the `content="drawable"` attribute to a `<canvas>` HTML element lays out its descendant HTML elements, and the `drawable` attribute marks the elements that you can render within the canvas's rendering context. You can use it to style and lay out text in a canvas, expose canvas content to browser features (like accessibility, translation, or find-in-page), and apply 2D and 3D effects to HTML.
## How to implement
1. Check if HTML-in-Canvas is supported in the browser:
-```
-if ('requestPaint' in HTMLCanvasElement.prototype) {
+```js
+if ('content' in HTMLCanvasElement.prototype) {
// Use HTML in Canvas API
} else {
// Use fallback strategy
}
```
-2. Add the `layoutsubtree` attribute to the `<canvas>` HTML element.
-3. Place your HTML content inside the `<canvas>` element with the `layoutsubtree` attribute.
+> [!NOTE]
+> HTML-in-Canvas is supported from Chrome 157.
+
+2. Add the `content="drawable"` attribute to the `<canvas>` HTML element.
+3. Place your HTML content inside the `<canvas>` element, and add the `drawable` attribute to every element that you draw. An element with `drawable` captures its subtree, except nested descendants that are also `drawable`.
```html
-<canvas id="canvas" layoutsubtree>
- <div id="html-content"></div>
+<canvas id="canvas" content="drawable">
+ <div id="html-content" drawable></div>
</canvas>
```
@@ -45,53 +48,139 @@ const options = supportsDevicePixelContentBox
observer.observe(canvas, options);
```
-5. Render the HTML content to the canvas inside a `canvas.onpaint` event handler:
+5. Render the HTML content to the canvas inside a `canvas.onpaint` event handler. An element can only be drawn after the canvas has painted it: call `canvas.requestPaint()` to request a `paint` event.
-- In 2D context, use the `drawElementImage` method:
+- In 2D context, use the `drawElementImage` method. It draws the last snapshot of a `drawable` element, and its drawable subtree, starting at the element's border box, before CSS transforms:
```js
canvas.onpaint = () => {
ctx.reset();
// Draw the form element at x:0, y:0
- let transform = ctx.drawElementImage(form_element, 0, 0);
+ ctx.drawElementImage(form_element, 0, 0);
};
```
-- In WebGL context, use the `texElementImage2D` method:
+- In WebGL and WebGPU contexts, you copy the element into a texture. Size the texture from `canvas.captureElementImage(element)`. Its `width` and `height` are in canvas grid (backing store) pixels, so round them up with `Math.ceil()`. `captureElementImage()` throws if the element has no paint record yet: call `requestPaint()`, and retry on the next `paint` event.
+
+```js
+// Returns the element's size in canvas grid pixels, or null if the element
+// has no paint record yet.
+function getElementImageSize(canvas, element) {
+ let elementImage;
+ try {
+ elementImage = canvas.captureElementImage(element);
+ } catch (err) {
+ canvas.requestPaint(); // No paint record yet: retry on the next paint event.
+ return null;
+ }
+ const width = Math.ceil(elementImage.width);
+ const height = Math.ceil(elementImage.height);
+ elementImage.close();
+ return width > 0 && height > 0 ? { width, height } : null;
+}
+```
+
+- In WebGL context, pre-allocate the texture backing first using the `texImage2D` method. The snippets in this guide use a WebGL 2 context (`canvas.getContext("webgl2")`). Allocate texture storage by calling `texImage2D()` with `null` instead of pixel data, which reserves GPU memory of the given size and format without uploading any pixels. Follow these rules:
+ - Size the texture from `captureElementImage()`, as shown above.
+ - Allocate level 0 only on the first upload, or when the size changes, because reallocating clears the texture. Use mutable storage: immutable `texStorage2D()` storage can't be resized when the element changes size.
+
+```js
+// Binds the texture, and allocates its storage on the first upload, and when
+// the element size changes. `state` stores the allocated size.
+function allocateElementTexture(gl, texture, state, width, height) {
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ if (state.width === width && state.height === height) return;
+
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0, // Mipmap level
+ gl.RGBA8, // Internal format: 8 bits per RGBA channel
+ width, // Size in canvas grid pixels
+ height,
+ 0, // Border: must be 0
+ gl.RGBA, // Format and type that match RGBA8
+ gl.UNSIGNED_BYTE,
+ null // null reserves GPU memory without uploading pixels
+ );
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ state.width = width;
+ state.height = height;
+}
+
+const texture = gl.createTexture();
+const textureState = { width: 0, height: 0 };
+```
+
+- Then, in WebGL context, render the HTML content to the texture using the `texElementSubImage2D` method. Follow these rules:
+ - Pass `{ width, height }` in the config. It makes the copy fill the allocated texture regardless of how the canvas is scaled.
+ - Reallocate the texture if the size changed, as shown above.
```js
+// Uploads the element into the texture. Returns false if the element has no
+// paint record yet. In that case, it's uploaded on the next paint event.
+function uploadElementWebGL(gl, canvas, texture, element, state) {
+ const size = getElementImageSize(canvas, element);
+ if (!size) return false;
+ const { width, height } = size;
+
+ // Bind the texture, and reallocate it if the size changed (see above).
+ allocateElementTexture(gl, texture, state, width, height);
+ gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, element, { width, height });
+ return true;
+}
+
canvas.onpaint = () => {
- if (gl.texElementImage2D) {
- try {
- gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);
- } catch (err) {
- console.error('texElementImage2D copy failed:', err);
- }
+ try {
+ uploadElementWebGL(gl, canvas, texture, uiElement, textureState);
+ } catch (err) {
+ console.error('texElementSubImage2D copy failed:', err);
}
};
```
-- In WebGPU context, use the `copyElementImageToTexture` method:
+- In WebGPU context, use the `drawElementImageToTexture` method. Follow these rules:
+ - Create the texture with `COPY_DST` and `RENDER_ATTACHMENT` usage, and add `TEXTURE_BINDING` to sample it in shaders. A wrong usage is reported as a WebGPU validation error, not as an exception.
+ - Pass the texture size as `size`. Without `size`, a larger element is clipped to the texture. With `size`, the element is scaled to fill it.
+ - WebGPU textures can't be resized. Recreate the texture when the element size changes, and rebuild the bind groups that reference it.
```js
+// WebGPU textures can't be resized. Create the texture once, and recreate it
+// when the element size changes.
+function ensureElementTexture(device, state, width, height) {
+ if (state.texture?.width === width && state.texture?.height === height) {
+ return state.texture;
+ }
+ state.texture?.destroy();
+ state.texture = device.createTexture({
+ size: { width, height },
+ format: "rgba8unorm",
+ usage:
+ GPUTextureUsage.TEXTURE_BINDING |
+ GPUTextureUsage.COPY_DST |
+ GPUTextureUsage.RENDER_ATTACHMENT,
+ });
+ return state.texture; // Recreate the bind groups that used the previous texture.
+}
+
+const textureState = { texture: null };
+
canvas.onpaint = () => {
- if (root.device.queue.copyElementImageToTexture) {
- try {
- const sourceDict = { source: valueElement };
- const destDict = {
- destination: { texture: targetTexture },
- width: 512,
- height: 128,
- };
- root.device.queue.copyElementImageToTexture(sourceDict, destDict);
- } catch (err) {
- console.error('copyElementImageToTexture copy failed:', err);
- }
+ const size = getElementImageSize(canvas, uiElement);
+ if (!size) return;
+ const previousTexture = textureState.texture;
+ const texture = ensureElementTexture(device, textureState, size.width, size.height);
+ if (texture !== previousTexture) {
+ // New texture: create, or rebuild, the bind groups that reference it.
+ }
+ try {
+ device.queue.drawElementImageToTexture({ source: uiElement }, { texture, size });
+ } catch (err) {
+ console.error('drawElementImageToTexture copy failed:', err);
}
};
```
-When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. Make sure you only re-render the canvas if there has been an update to the descendant HTML elements:
+When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. `event.changedElements` lists the elements whose rendering changed. Make sure you only redraw the element, or re-upload its texture, if there has been an update to the descendant HTML elements:
```js
function render() {
@@ -103,91 +192,72 @@ requestAnimationFrame(render);
canvas.onpaint = (event) => {
if (event.changedElements && event.changedElements.length > 0) {
- // Update the texture with drawElementImage, texElementImage2D, or copyElementImageToTexture, and update the CSS transform as shown in step 6
+ // Redraw the element, or update its texture, as shown above
}
+ // In WebGL and WebGPU, render the scene, and sync the element geometry as shown in step 6
};
```
-6. Update the CSS transform.
+6. Sync the element geometry.
-- For the 2D context case, apply the transform returned by the rendering call to the `style.transform` property:
+The browser needs to know where the HTML element is drawn, so that its DOM position matches its drawn pixels. Hit testing, for example, for clicks and text selection, and accessibility use this geometry: a `drawable` element whose geometry isn't updated is still exposed to the accessibility tree, but without geometry information. A canvas only hit tests the elements that are drawn with the 2D `drawElementImage()` method, or registered with `updateElementGeometry()`.
-```js
-canvas.onpaint = () => {
- ctx.reset();
- // Draw the form element at x:0, y:0
- let transform = ctx.drawElementImage(form_element, 0, 0);
+- For the 2D context case, the browser syncs the element automatically. `drawElementImage()` aligns the DOM hit-test bounds and screen reader focus rings with the drawn coordinates, so you don't need to set `style.transform`. To manage the geometry manually, for example, when you draw the same element more than once, pass `{ preserveElementGeometry: true }` to `drawElementImage()`, and apply transforms with `canvas.updateElementGeometry()`.
- // Sync the DOM location with the drawn location
- form_element.style.transform = transform.toString();
-};
-```
-
-- For the 3D case with WebGL or WebGPU, the browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
- - Convert WebGL MVP Matrix to DOM Matrix.
- - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from 0 to 1. If you don't normalize, your 200px button will look 200 times larger.
- - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the actual pixel dimensions of your `<canvas>` element on the screen. It also flips the Y-axis, because in WebGL, up is positive, but in CSS, down is positive.
- - Calculate the final transform. Multiply the matrices in order: Viewport _ MVP _ Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element layer should sit to align with the 3D drawing.
- - Apply the transform to the HTML element. This moves the HTML element layer to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element.
+- For the 3D case with WebGL or WebGPU, the canvas can't tell where the HTML element is drawn, so you have to tell it. Compute a `DOMMatrix` that maps the element's border box, in CSS pixels, to the canvas, in CSS pixels. The browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
+ - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from -0.5 to 0.5. If you don't normalize, your 200px button will look 200 times larger. This step also flips the Y-axis, because in CSS, down is positive, but in WebGL, up is positive.
+ - Convert the WebGL MVP Matrix to a DOM Matrix.
+ - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the CSS pixel dimensions of your `<canvas>` element on the screen, and flips the Y-axis back.
+ - Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element should sit to align with the 3D drawing. The browser performs the perspective divide.
```js
- if (canvas.getElementTransform) {
- // 1. Convert WebGL MVP Matrix to DOM Matrix
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // 2. Normalize the HTML element (Canvas Grid pixels -> WebGL Model Space)
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = targetHTMLElement.offsetWidth * dprX;
- const gridHeight = targetHTMLElement.offsetHeight * dprY;
+ // Maps the element's border box (CSS pixels) to the canvas (CSS pixels), for a
+ // quad that spans -0.5 to 0.5 in model space and is drawn with the `mvp` matrix.
+ function computeCanvasTransform(canvas, element, mvp) {
+ const width = element.offsetWidth;
+ const height = element.offsetHeight;
+ // 1. Normalize the HTML element (CSS pixels -> WebGL Model Space)
const toGLModel = new DOMMatrix()
// Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
+ .scale(1 / width, -1 / height, 1 / height)
// Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
- .translate(-gridWidth / 2, -gridHeight / 2);
+ .translate(-width / 2, -height / 2);
- // 3. Map to the canvas viewport
+ // 2. Convert WebGL MVP Matrix to DOM Matrix
+ const mvpDOM = new DOMMatrix(Array.from(mvp));
+
+ // 3. Map to the canvas viewport, in CSS pixels
const clipToCanvasViewport = new DOMMatrix()
// Move center (0,0) to center of canvas
- .translate(canvas.width / 2, canvas.height / 2)
- // Scale normalized clip (-1..1) to viewport size
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
+ .translate(canvas.clientWidth / 2, canvas.clientHeight / 2)
+ // Scale normalized clip (-1..1) to viewport size, and flip Y back
+ .scale(canvas.clientWidth / 2, -canvas.clientHeight / 2, canvas.clientHeight / 2);
// 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(toGLModel);
-
- // 5. Apply to the transform
- const computedTransform = canvas.getElementTransform(
- targetHTMLElement,
- screenSpaceTransform,
- );
- targetHTMLElement.style.transform = computedTransform.toString();
+ return clipToCanvasViewport.multiply(mvpDOM).multiply(toGLModel);
}
```
-7. [Troubleshooting] If the developer is experiencing a mismatch in the DOM logical layout in 3D even after applying the CSS transform from step 5, check if the developer is experiencing the issue in Chromium 148 or earlier. If that's the case, check if `transform.is2D` is correctly set to false for a 3D DOMMatrix. If not, re-initialize the DOMMatrix which corrects `is2D` to be false before applying the transform to the target HTML element. This issue is fixed in Chromium 149+, and if the developer is experiencing it in newer Chromium versions, the is2D value is not the cause:
+Then pass the transform to `canvas.updateElementGeometry()` as `canvasTransform`. This moves the HTML element to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element. The browser also uses the transform for the element's accessibility bounds, for example, for screen reader focus rings:
-```js
-if (transform.is2D) {
- // Workaround for Chromium bug https://crbug.com/512171941
- // affecting Chrome versions under 149 where `transform.is2D`
- // is incorrectly true for a 3D DOMMatrix. The assignment
- // below re-initializes the DOMMatrix which corrects is2D to be false.
- transform = DOMMatrix.fromFloat64Array(transform.toFloat64Array());
-}
-targetHTMLElement.style.transform = computedTransform.toString();
-```
+ ```js
+ canvas.updateElementGeometry(targetHTMLElement, {
+ canvasTransform: computeCanvasTransform(canvas, targetHTMLElement, htmlElementMVP),
+ });
+ ```
+
+Use these options to control hit testing:
+ - Each `updateElementGeometry()` call moves the element to the top of the hit-testing order. Pass `{ preserveHitTestOrder: true }` to keep its position.
+ - Call `canvas.clearElementGeometry(element)` to remove an element from hit testing, for example, when you hide it.
## Example code
### 2D Canvas
```html
-<canvas id="canvas" layoutsubtree style="width: 400px; height: 200px;">
- <div id="ui-element">
+<canvas id="canvas" content="drawable" style="width: 400px; height: 200px;">
+ <div id="ui-element" drawable>
<p>
This text is rendered inside the canvas but is present in the DOM tree.
</p>
@@ -203,11 +273,9 @@ targetHTMLElement.style.transform = computedTransform.toString();
canvas.onpaint = () => {
ctx.reset();
- // Draw the HTML element at x:0, y:0
- const transform = ctx.drawElementImage(uiElement, 0, 0);
-
- // Sync the DOM location with the drawn location
- uiElement.style.transform = transform.toString();
+ // Draw the HTML element at x:0, y:0. The browser syncs the DOM location
+ // with the drawn location.
+ ctx.drawElementImage(uiElement, 0, 0);
};
// Handle resizing to match device pixels
@@ -235,8 +303,8 @@ targetHTMLElement.style.transform = computedTransform.toString();
### WebGL Canvas
```html
-<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
- <div id="ui-element">
+<canvas id="canvas" content="drawable" style="width: 400px; height: 400px;">
+ <div id="ui-element" drawable>
<p>WebGL UI Element</p>
<button>Action</button>
</div>
@@ -244,53 +312,32 @@ targetHTMLElement.style.transform = computedTransform.toString();
<script>
const canvas = document.getElementById("canvas");
- const gl = canvas.getContext("webgl");
+ const gl = canvas.getContext("webgl2");
const uiElement = document.getElementById("ui-element");
+ // getElementImageSize(), allocateElementTexture(), and uploadElementWebGL()
+ // are defined in step 5.
+ // computeCanvasTransform() is defined in step 6.
+
// Setup WebGL texture...
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
+ const textureState = { width: 0, height: 0 };
canvas.onpaint = () => {
// 1. Update texture with HTML content
- if (gl.texElementImage2D) {
- try {
- gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);
- } catch (err) {
- console.error('texElementImage2D copy failed:', err);
- }
+ try {
+ uploadElementWebGL(gl, canvas, texture, uiElement, textureState);
+ } catch (err) {
+ console.error('texElementSubImage2D copy failed:', err);
}
// ... Render your 3D scene here, calculating htmlElementMVP matrix ...
- // 2. Sync DOM position with 3D scene
- if (canvas.getElementTransform) {
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // Recalculate the DPR compensation mapping
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = uiElement.offsetWidth * dprX;
- const gridHeight = uiElement.offsetHeight * dprY;
-
- const cssToUnitSpace = new DOMMatrix()
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
- .translate(-gridWidth / 2, -gridHeight / 2);
-
- const clipToCanvasViewport = new DOMMatrix()
- .translate(canvas.width / 2, canvas.height / 2)
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
-
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(cssToUnitSpace);
-
- const computedTransform = canvas.getElementTransform(
- uiElement,
- screenSpaceTransform,
- );
- uiElement.style.transform = computedTransform.toString();
- }
+ // 2. Sync DOM position, hit testing, and accessibility bounds with 3D scene
+ canvas.updateElementGeometry(uiElement, {
+ canvasTransform: computeCanvasTransform(canvas, uiElement, htmlElementMVP),
+ });
};
</script>
```
@@ -298,8 +345,8 @@ targetHTMLElement.style.transform = computedTransform.toString();
### WebGPU Canvas
```html
-<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
- <div id="ui-element">
+<canvas id="canvas" content="drawable" style="width: 400px; height: 400px;">
+ <div id="ui-element" drawable>
<p>WebGPU UI Element</p>
</div>
</canvas>
@@ -309,54 +356,35 @@ targetHTMLElement.style.transform = computedTransform.toString();
const context = canvas.getContext("webgpu");
const uiElement = document.getElementById("ui-element");
+ // getElementImageSize() and ensureElementTexture() are defined in step 5.
+ // computeCanvasTransform() is defined in step 6.
+
// Setup WebGPU...
// const device = ...
- // const targetTexture = ...
+ const textureState = { texture: null };
canvas.onpaint = () => {
- // 1. Copy HTML content to texture
- if (device.queue.copyElementImageToTexture) {
+ // 1. Copy HTML content to a texture that matches the element size
+ const size = getElementImageSize(canvas, uiElement);
+ if (size) {
+ const previousTexture = textureState.texture;
+ const texture = ensureElementTexture(device, textureState, size.width, size.height);
+ if (texture !== previousTexture) {
+ // New texture: create, or rebuild, the bind groups that reference it.
+ }
try {
- const sourceDict = { source: uiElement };
- const destDict = {
- destination: { texture: targetTexture },
- width: width,
- height: height,
- };
- device.queue.copyElementImageToTexture(sourceDict, destDict);
+ device.queue.drawElementImageToTexture({ source: uiElement }, { texture, size });
} catch (err) {
- console.error('copyElementImageToTexture copy failed:', err);
+ console.error('drawElementImageToTexture copy failed:', err);
}
}
- // 2. Sync DOM position (same matrix math as WebGL)
- if (canvas.getElementTransform) {
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // Recalculate the DPR compensation mapping
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = uiElement.offsetWidth * dprX;
- const gridHeight = uiElement.offsetHeight * dprY;
-
- const cssToUnitSpace = new DOMMatrix()
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight) // Retain Z scale
- .translate(-gridWidth / 2, -gridHeight / 2);
-
- const clipToCanvasViewport = new DOMMatrix()
- .translate(canvas.width / 2, canvas.height / 2)
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2); // Retain Z scale
-
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(cssToUnitSpace);
-
- const computedTransform = canvas.getElementTransform(
- uiElement,
- screenSpaceTransform,
- );
- uiElement.style.transform = computedTransform.toString();
- }
+ // ... Render your 3D scene here, calculating htmlElementMVP matrix ...
+
+ // 2. Sync DOM position, hit testing, and accessibility bounds (same matrix math as WebGL)
+ canvas.updateElementGeometry(uiElement, {
+ canvasTransform: computeCanvasTransform(canvas, uiElement, htmlElementMVP),
+ });
};
</script>
```
@@ -364,10 +392,14 @@ targetHTMLElement.style.transform = computedTransform.toString();
## Best Practices
- **MANDATORY**: Check browser support for the HTML-in-Canvas API before using it.
-- **MANDATORY**: Always add the `layoutsubtree` attribute to the `<canvas>` element.
+- **MANDATORY**: Always add the `content="drawable"` attribute to the `<canvas>` element.
+- **MANDATORY**: Add the `drawable` attribute to every element that you draw, including direct children of the canvas.
- **MANDATORY**: Use an `onpaint` event handler to render the HTML content to the canvas.
-- **MANDATORY**: Use the `drawElementImage`, `texElementImage2D`, or `copyElementImageToTexture` methods to render the HTML content to the canvas.
-- **MANDATORY**: Update the CSS transform of the HTML element to match the transform of the rendered content by setting the `style.transform` property of the HTML element.
+- **MANDATORY**: Use the `drawElementImage` method in 2D, or `drawElementImageToTexture` in WebGPU, to render the HTML content to the canvas.
+- **MANDATORY**: In WebGL, pre-allocate the texture buffer with `texImage2D()` once (when it's initialized or when the element size changes). Reallocate the texture only when the size changes, and set `TEXTURE_MIN_FILTER` to `LINEAR`.
+- **MANDATORY**: In WebGL, use the `texElementSubImage2D` method to render the HTML content to a texture that you pre-allocate with `texImage2D()`, sized from `captureElementImage()`.
+- **MANDATORY**: In WebGPU, size the texture from `captureElementImage()`, and recreate it only when the size changes. Create the texture with `COPY_DST` and `RENDER_ATTACHMENT` usage, and pass the texture size as `size`.
+- **MANDATORY**: Sync the geometry of the HTML element with the rendered content. In 2D, `drawElementImage` does it automatically. In WebGL and WebGPU, call `canvas.updateElementGeometry(element, { canvasTransform })`.
- **MANDATORY**: Use `ResizeObserver` to observe the screen size and update the canvas size to match device pixels.
- **DO NOT** embed cross-origin content in a canvas, as it is not supported.
- **DO NOT** initialize `ResizeObserver` within the `onpaint` event handler, as it may lead to memory leaks.
diff --git a/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md b/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md
index 7f867b2..fc9aca8 100644
--- a/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md
+++ b/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md
@@ -1,6 +1,6 @@
# Enable interactive HTML content in 3D scenes
-The HTML-in-Canvas API allows rendering real DOM directly inside a canvas element. When applied to 3D rendering contexts like WebGL, WebGPU, or Three.js, adding the `layoutsubtree` attribute enables descendant HTML elements to be seamlessly projected into the 3D scene. Crucially, because the HTML elements remain part of the active DOM layout tree, they retain full interactivity—allowing users to click buttons, select text, and trigger focus states natively without requiring complex raycasting or custom event handling.
+The HTML-in-Canvas API allows rendering real DOM directly inside a canvas element. When applied to 3D rendering contexts like WebGL, WebGPU, or Three.js, adding the `content="drawable"` attribute to the canvas, and the `drawable` attribute to its descendant HTML elements, enables those elements to be seamlessly projected into the 3D scene. Crucially, because the HTML elements remain part of the active DOM layout tree, they retain full interactivity—allowing users to click buttons, select text, and trigger focus states natively without requiring complex raycasting or custom event handling.
## How to implement
@@ -10,18 +10,21 @@ When using WebGL or WebGPU, follow these steps:
1. Check if HTML-in-Canvas is supported in the browser:
```
-if ('requestPaint' in HTMLCanvasElement.prototype) {
+if ('content' in HTMLCanvasElement.prototype) {
// Use HTML in Canvas API
} else {
// Use fallback strategy
}
```
-2. Initialize `<canvas>` to support descendant HTML elements by adding the `layoutsubtree` attribute to the `<canvas>` HTML element. Place your HTML content inside the `<canvas>` element with the `layoutsubtree` attribute.
+> [!NOTE]
+> HTML-in-Canvas is supported from Chrome 157.
+
+2. Initialize `<canvas>` to support descendant HTML elements by adding the `content="drawable"` attribute to the `<canvas>` HTML element. Place your HTML content inside the `<canvas>` element, and add the `drawable` attribute to every element that you draw. An element with `drawable` captures its subtree, except nested descendants that are also `drawable`:
```html
-<canvas id="canvas" layoutsubtree>
- <div id="html-content"></div>
+<canvas id="canvas" content="drawable">
+ <div id="html-content" drawable></div>
</canvas>
```
@@ -47,43 +50,129 @@ const options = supportsDevicePixelContentBox
observer.observe(canvas, options);
```
-4. Render the HTML content to the canvas inside a `canvas.onpaint` event handler:
+4. Render the HTML content to a texture inside a `canvas.onpaint` event handler. An element can only be uploaded after the canvas has painted it: call `canvas.requestPaint()` to request a `paint` event.
+
+Size the texture from `canvas.captureElementImage(element)`. Its `width` and `height` are in canvas grid (backing store) pixels, so round them up with `Math.ceil()`. `captureElementImage()` throws if the element has no paint record yet: call `requestPaint()`, and retry on the next `paint` event.
+
+```js
+// Returns the element's size in canvas grid pixels, or null if the element
+// has no paint record yet.
+function getElementImageSize(canvas, element) {
+ let elementImage;
+ try {
+ elementImage = canvas.captureElementImage(element);
+ } catch (err) {
+ canvas.requestPaint(); // No paint record yet: retry on the next paint event.
+ return null;
+ }
+ const width = Math.ceil(elementImage.width);
+ const height = Math.ceil(elementImage.height);
+ elementImage.close();
+ return width > 0 && height > 0 ? { width, height } : null;
+}
+```
+
+- In WebGL context, pre-allocate the texture backing first using the `texImage2D` method. The snippets in this guide use a WebGL 2 context (`canvas.getContext("webgl2")`). Allocate texture storage by calling `texImage2D()` with `null` instead of pixel data, which reserves GPU memory of the given size and format without uploading any pixels. Follow these rules:
+ - Size the texture from `captureElementImage()`, as shown above.
+ - Allocate level 0 only on the first upload, or when the size changes, because reallocating clears the texture. Use mutable storage: immutable `texStorage2D()` storage can't be resized when the element changes size.
+
+```js
+// Binds the texture, and allocates its storage on the first upload, and when
+// the element size changes. `state` stores the allocated size.
+function allocateElementTexture(gl, texture, state, width, height) {
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ if (state.width === width && state.height === height) return;
+
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0, // Mipmap level
+ gl.RGBA8, // Internal format: 8 bits per RGBA channel
+ width, // Size in canvas grid pixels
+ height,
+ 0, // Border: must be 0
+ gl.RGBA, // Format and type that match RGBA8
+ gl.UNSIGNED_BYTE,
+ null // null reserves GPU memory without uploading pixels
+ );
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ state.width = width;
+ state.height = height;
+}
+
+const texture = gl.createTexture();
+const textureState = { width: 0, height: 0 };
+```
-- In WebGL context, use the `texElementImage2D` method:
+- Then, in WebGL context, render the HTML content to the texture using the `texElementSubImage2D` method. Follow these rules:
+ - Pass `{ width, height }` in the config. It makes the copy fill the allocated texture regardless of how the canvas is scaled.
+ - Reallocate the texture if the size changed, as shown above.
```js
+// Uploads the element into the texture. Returns false if the element has no
+// paint record yet. In that case, it's uploaded on the next paint event.
+function uploadElementWebGL(gl, canvas, texture, element, state) {
+ const size = getElementImageSize(canvas, element);
+ if (!size) return false;
+ const { width, height } = size;
+
+ // Bind the texture, and reallocate it if the size changed (see above).
+ allocateElementTexture(gl, texture, state, width, height);
+ gl.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, element, { width, height });
+ return true;
+}
+
canvas.onpaint = () => {
- if (gl.texElementImage2D) {
- try {
- gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);
- } catch (err) {
- console.error('texElementImage2D copy failed:', err);
- }
+ try {
+ uploadElementWebGL(gl, canvas, texture, uiElement, textureState);
+ } catch (err) {
+ console.error('texElementSubImage2D copy failed:', err);
}
};
```
-- In WebGPU context, use the `copyElementImageToTexture` method:
+- In WebGPU context, use the `drawElementImageToTexture` method. Follow these rules:
+ - Create the texture with `COPY_DST` and `RENDER_ATTACHMENT` usage, and add `TEXTURE_BINDING` to sample it in shaders. A wrong usage is reported as a WebGPU validation error, not as an exception.
+ - Pass the texture size as `size`. Without `size`, a larger element is clipped to the texture. With `size`, the element is scaled to fill it.
+ - WebGPU textures can't be resized. Recreate the texture when the element size changes, and rebuild the bind groups that reference it.
```js
+// WebGPU textures can't be resized. Create the texture once, and recreate it
+// when the element size changes.
+function ensureElementTexture(device, state, width, height) {
+ if (state.texture?.width === width && state.texture?.height === height) {
+ return state.texture;
+ }
+ state.texture?.destroy();
+ state.texture = device.createTexture({
+ size: { width, height },
+ format: "rgba8unorm",
+ usage:
+ GPUTextureUsage.TEXTURE_BINDING |
+ GPUTextureUsage.COPY_DST |
+ GPUTextureUsage.RENDER_ATTACHMENT,
+ });
+ return state.texture; // Recreate the bind groups that used the previous texture.
+}
+
+const textureState = { texture: null };
+
canvas.onpaint = () => {
- if (root.device.queue.copyElementImageToTexture) {
- try {
- const sourceDict = { source: valueElement };
- const destDict = {
- destination: { texture: targetTexture },
- width: 512,
- height: 128,
- };
- root.device.queue.copyElementImageToTexture(sourceDict, destDict);
- } catch (err) {
- console.error('copyElementImageToTexture copy failed:', err);
- }
+ const size = getElementImageSize(canvas, uiElement);
+ if (!size) return;
+ const previousTexture = textureState.texture;
+ const texture = ensureElementTexture(device, textureState, size.width, size.height);
+ if (texture !== previousTexture) {
+ // New texture: create, or rebuild, the bind groups that reference it.
+ }
+ try {
+ device.queue.drawElementImageToTexture({ source: uiElement }, { texture, size });
+ } catch (err) {
+ console.error('drawElementImageToTexture copy failed:', err);
}
};
```
-When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. Make sure you only re-render the canvas if there has been an update to the descendant HTML elements:
+When using a `requestAnimationFrame` loop to render the scene, call `canvas.requestPaint()` within the loop to ensure that the HTML content is rendered to the canvas. `event.changedElements` lists the elements whose rendering changed. Make sure you only re-upload the texture if there has been an update to the descendant HTML elements:
```js
function render() {
@@ -95,100 +184,105 @@ requestAnimationFrame(render);
canvas.onpaint = (event) => {
if (event.changedElements && event.changedElements.length > 0) {
- // Update the texture with texElementImage2D, and update the CSS transform as shown in step 5
+ // Update the texture as shown above
}
+ // Render the scene, and sync the element geometry as shown in step 5
};
```
-5. Update the CSS transform.
-
-The browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
-
-- Convert the MVP Matrix to DOM Matrix.
-- Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from 0 to 1. If you don't normalize, your 200px button will look 200 times larger.
-- Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the actual pixel dimensions of your `<canvas>` element on the screen. It also flips the Y-axis, because in WebGL, up is positive, but in CSS, down is positive.
-- Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element layer should sit to align with the 3D drawing.
-- Apply the transform to the HTML element. This moves the HTML element layer to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element.
+5. Sync the element geometry.
+
+Compute a `DOMMatrix` that maps the element's border box, in CSS pixels, to the canvas, in CSS pixels. The browser needs to map from the 3D coordinate space into the CSS coordinate space using a viewport transform. To facilitate this, do the following:
+ - Normalize the HTML element. HTML elements are sized in pixels (for example, 200px wide). WebGL, however, usually treats objects as "unit squares", for example, ranging from -0.5 to 0.5. If you don't normalize, your 200px button will look 200 times larger. This step also flips the Y-axis, because in CSS, down is positive, but in WebGL, up is positive.
+ - Convert the WebGL MVP Matrix to a DOM Matrix.
+ - Map to the canvas viewport. This step is the "re-scaling" phase: it stretches that unit-space math back out to match the CSS pixel dimensions of your `<canvas>` element on the screen, and flips the Y-axis back.
+ - Calculate the final transform. Multiply the matrices in order: Viewport * MVP * Normalization. Combining them into one final transform produces a "map" that tells the browser exactly where that HTML element should sit to align with the 3D drawing. The browser performs the perspective divide.
+
+ ```js
+ // Maps the element's border box (CSS pixels) to the canvas (CSS pixels), for a
+ // quad that spans -0.5 to 0.5 in model space and is drawn with the `mvp` matrix.
+ function computeCanvasTransform(canvas, element, mvp) {
+ const width = element.offsetWidth;
+ const height = element.offsetHeight;
+
+ // 1. Normalize the HTML element (CSS pixels -> WebGL Model Space)
+ const toGLModel = new DOMMatrix()
+ // Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
+ .scale(1 / width, -1 / height, 1 / height)
+ // Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
+ .translate(-width / 2, -height / 2);
+
+ // 2. Convert WebGL MVP Matrix to DOM Matrix
+ const mvpDOM = new DOMMatrix(Array.from(mvp));
+
+ // 3. Map to the canvas viewport, in CSS pixels
+ const clipToCanvasViewport = new DOMMatrix()
+ // Move center (0,0) to center of canvas
+ .translate(canvas.clientWidth / 2, canvas.clientHeight / 2)
+ // Scale normalized clip (-1..1) to viewport size, and flip Y back
+ .scale(canvas.clientWidth / 2, -canvas.clientHeight / 2, canvas.clientHeight / 2);
+
+ // 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
+ return clipToCanvasViewport.multiply(mvpDOM).multiply(toGLModel);
+ }
+ ```
-```js
-if (canvas.getElementTransform) {
- // 1. Convert WebGL MVP Matrix to DOM Matrix
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // 2. Normalize the HTML element (Canvas Grid pixels -> WebGL Model Space)
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = targetHTMLElement.offsetWidth * dprX;
- const gridHeight = targetHTMLElement.offsetHeight * dprY;
-
- const toGLModel = new DOMMatrix()
- // Scale pixels to 1 unit, flip Y (as in CSS it points down, and in WebGL it points up)
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
- // Center the origin: (0,0) becomes (-width/2, -height/2) before scaling
- .translate(-gridWidth / 2, -gridHeight / 2);
-
- // 3. Map to the canvas viewport
- const clipToCanvasViewport = new DOMMatrix()
- // Move center (0,0) to center of canvas
- .translate(canvas.width / 2, canvas.height / 2)
- // Scale normalized clip (-1..1) to viewport size
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
-
- // 4. Multiply: (Clip -> Pixels) * (MVP) * (pixels -> unit square)
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(toGLModel);
-
- // 5. Apply to the transform
- const computedTransform = canvas.getElementTransform(
- targetHTMLElement,
- screenSpaceTransform,
- );
- targetHTMLElement.style.transform = computedTransform.toString();
-}
-```
+Then pass the transform to `canvas.updateElementGeometry()` as `canvasTransform`. This moves the HTML element to sit directly on top of its rendered pixels. This ensures that when a user clicks a button or selects text, they are actually hitting the real HTML element. The browser also uses the transform for the element's accessibility bounds, for example, for screen reader focus rings:
-6. [Troubleshooting] If the developer is experiencing a mismatch in the DOM logical layout in 3D even after applying the CSS transform from step 5, check if the developer is experiencing the issue in Chromium 148 or earlier. If that's the case, check if `transform.is2D` is correctly set to false for a 3D DOMMatrix. If not, re-initialize the DOMMatrix which corrects `is2D` to be false before applying the transform to the target HTML element. This issue is fixed in Chromium 149+, and if the developer is experiencing it in newer Chromium versions, the is2D value is not the cause:
+ ```js
+ canvas.updateElementGeometry(targetHTMLElement, {
+ canvasTransform: computeCanvasTransform(canvas, targetHTMLElement, htmlElementMVP),
+ });
+ ```
-```js
-if (transform.is2D) {
- // Workaround for Chromium bug https://crbug.com/512171941
- // affecting Chrome versions under 149 where `transform.is2D`
- // is incorrectly true for a 3D DOMMatrix. The assignment
- // below re-initializes the DOMMatrix which corrects is2D to be false.
- transform = DOMMatrix.fromFloat64Array(transform.toFloat64Array());
-}
-targetHTMLElement.style.transform = computedTransform.toString();
-```
+Use these options to control hit testing:
+ - Each `updateElementGeometry()` call moves the element to the top of the hit-testing order. Pass `{ preserveHitTestOrder: true }` to keep its position.
+ - Call `canvas.clearElementGeometry(element)` to remove an element from hit testing, for example, when you hide it.
### Three.js
1. Check if HTML-in-Canvas is supported in the browser:
-```
-if ('requestPaint' in HTMLCanvasElement.prototype) {
+```js
+if ('content' in HTMLCanvasElement.prototype) {
// Use HTML in Canvas API
} else {
// Use fallback strategy
}
```
+> [!NOTE]
+> HTML-in-Canvas is supported from Chrome 157.
+
2. Create a custom geometry and material for the HTML content.
-3. Pass the DOM element into THREE.HTMLTexture:
+3. Pass the DOM element into THREE.HTMLTexture. The renderer adds the element to its canvas, and sets the required attributes:
```js
material.map = new THREE.HTMLTexture(element);
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
```
+4. Register the mesh with `InteractionManager` to make the HTML element interactive. It keeps the element aligned with the mesh, and syncs the element geometry with the canvas, so that clicks and text selection hit the real HTML element. Call `interactions.update()` in the animation loop, before rendering:
+```js
+ import { InteractionManager } from 'three/addons/interaction/InteractionManager.js';
+
+ const interactions = new InteractionManager();
+ interactions.connect( renderer, camera );
+ interactions.add( mesh );
+
+ // In the animation loop
+ interactions.update();
+ renderer.render( scene, camera );
+```
+
## Example code
### WebGL Canvas
```html
-<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
- <div id="ui-element">
+<canvas id="canvas" content="drawable" style="width: 400px; height: 400px;">
+ <div id="ui-element" drawable>
<p>WebGL UI Element</p>
<button>Action</button>
</div>
@@ -196,53 +290,32 @@ if ('requestPaint' in HTMLCanvasElement.prototype) {
<script>
const canvas = document.getElementById("canvas");
- const gl = canvas.getContext("webgl");
+ const gl = canvas.getContext("webgl2");
const uiElement = document.getElementById("ui-element");
+ // getElementImageSize(), allocateElementTexture(), and uploadElementWebGL()
+ // are defined in step 4.
+ // computeCanvasTransform() is defined in step 5.
+
// Setup WebGL texture...
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
+ const textureState = { width: 0, height: 0 };
canvas.onpaint = () => {
// 1. Update texture with HTML content
- if (gl.texElementImage2D) {
- try {
- gl.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, uiElement);
- } catch (err) {
- console.error('texElementImage2D copy failed:', err);
- }
+ try {
+ uploadElementWebGL(gl, canvas, texture, uiElement, textureState);
+ } catch (err) {
+ console.error('texElementSubImage2D copy failed:', err);
}
// ... Render your 3D scene here, calculating htmlElementMVP matrix ...
- // 2. Sync DOM position with 3D scene
- if (canvas.getElementTransform) {
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // Recalculate the DPR compensation mapping
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = uiElement.offsetWidth * dprX;
- const gridHeight = uiElement.offsetHeight * dprY;
-
- const cssToUnitSpace = new DOMMatrix()
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight)
- .translate(-gridWidth / 2, -gridHeight / 2);
-
- const clipToCanvasViewport = new DOMMatrix()
- .translate(canvas.width / 2, canvas.height / 2)
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2);
-
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(cssToUnitSpace);
-
- const computedTransform = canvas.getElementTransform(
- uiElement,
- screenSpaceTransform,
- );
- uiElement.style.transform = computedTransform.toString();
- }
+ // 2. Sync DOM position, hit testing, and accessibility bounds with 3D scene
+ canvas.updateElementGeometry(uiElement, {
+ canvasTransform: computeCanvasTransform(canvas, uiElement, htmlElementMVP),
+ });
};
</script>
```
@@ -250,8 +323,8 @@ if ('requestPaint' in HTMLCanvasElement.prototype) {
### WebGPU Canvas
```html
-<canvas id="canvas" layoutsubtree style="width: 400px; height: 400px;">
- <div id="ui-element">
+<canvas id="canvas" content="drawable" style="width: 400px; height: 400px;">
+ <div id="ui-element" drawable>
<p>WebGPU UI Element</p>
</div>
</canvas>
@@ -261,54 +334,35 @@ if ('requestPaint' in HTMLCanvasElement.prototype) {
const context = canvas.getContext("webgpu");
const uiElement = document.getElementById("ui-element");
+ // getElementImageSize() and ensureElementTexture() are defined in step 4.
+ // computeCanvasTransform() is defined in step 5.
+
// Setup WebGPU...
// const device = ...
- // const targetTexture = ...
+ const textureState = { texture: null };
canvas.onpaint = () => {
- // 1. Copy HTML content to texture
- if (device.queue.copyElementImageToTexture) {
+ // 1. Copy HTML content to a texture that matches the element size
+ const size = getElementImageSize(canvas, uiElement);
+ if (size) {
+ const previousTexture = textureState.texture;
+ const texture = ensureElementTexture(device, textureState, size.width, size.height);
+ if (texture !== previousTexture) {
+ // New texture: create, or rebuild, the bind groups that reference it.
+ }
try {
- const sourceDict = { source: uiElement };
- const destDict = {
- destination: { texture: targetTexture },
- width: width,
- height: height,
- };
- device.queue.copyElementImageToTexture(sourceDict, destDict);
+ device.queue.drawElementImageToTexture({ source: uiElement }, { texture, size });
} catch (err) {
- console.error('copyElementImageToTexture copy failed:', err);
+ console.error('drawElementImageToTexture copy failed:', err);
}
}
- // 2. Sync DOM position (same matrix math as WebGL)
- if (canvas.getElementTransform) {
- const mvpDOM = new DOMMatrix(Array.from(htmlElementMVP));
-
- // Recalculate the DPR compensation mapping
- const dprX = canvas.width / canvas.clientWidth;
- const dprY = canvas.height / canvas.clientHeight;
- const gridWidth = uiElement.offsetWidth * dprX;
- const gridHeight = uiElement.offsetHeight * dprY;
-
- const cssToUnitSpace = new DOMMatrix()
- .scale(1 / gridWidth, -1 / gridHeight, 1 / gridHeight) // Retain Z scale
- .translate(-gridWidth / 2, -gridHeight / 2);
-
- const clipToCanvasViewport = new DOMMatrix()
- .translate(canvas.width / 2, canvas.height / 2)
- .scale(canvas.width / 2, -canvas.height / 2, canvas.height / 2); // Retain Z scale
-
- const screenSpaceTransform = clipToCanvasViewport
- .multiply(mvpDOM)
- .multiply(cssToUnitSpace);
-
- const computedTransform = canvas.getElementTransform(
- uiElement,
- screenSpaceTransform,
- );
- uiElement.style.transform = computedTransform.toString();
- }
+ // ... Render your 3D scene here, calculating htmlElementMVP matrix ...
+
+ // 2. Sync DOM position, hit testing, and accessibility bounds (same matrix math as WebGL)
+ canvas.updateElementGeometry(uiElement, {
+ canvasTransform: computeCanvasTransform(canvas, uiElement, htmlElementMVP),
+ });
};
</script>
```
@@ -319,7 +373,7 @@ if ('requestPaint' in HTMLCanvasElement.prototype) {
// 1. Initialize Three.js camera, scene, renderer, mesh, interactions;
// 2. Ensure HTML-in-Canvas feature support
-if (!('requestPaint' in HTMLCanvasElement.prototype)) {
+if (!('content' in HTMLCanvasElement.prototype)) {
// Use a fallback strategy
}
@@ -337,8 +391,15 @@ material.map = new THREE.HTMLTexture(element);
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
-// 6. Render Loop
+// 6. Make the HTML element interactive
+interactions = new InteractionManager();
+interactions.connect( renderer, camera );
+interactions.add( mesh );
+
+// 7. Render Loop
function animate() {
+ // Keep the HTML element aligned with the mesh, so it receives input
+ interactions.update();
renderer.render(scene, camera);
}
```
@@ -346,10 +407,14 @@ function animate() {
## Best Practices
- **MANDATORY**: Check browser support for the HTML-in-Canvas API before using it.
-- **MANDATORY**: When using WebGL or WebGPU, always add the `layoutsubtree` attribute to the `<canvas>` element.
+- **MANDATORY**: When using WebGL or WebGPU, always add the `content="drawable"` attribute to the `<canvas>` element.
+- **MANDATORY**: When using WebGL or WebGPU, add the `drawable` attribute to every element that you draw, including direct children of the canvas.
- **MANDATORY**: When using WebGL or WebGPU, use an `onpaint` event handler to render the HTML content to the canvas.
-- **MANDATORY**: When using WebGL or WebGPU, use `texElementImage2D` for WebGL, or `copyElementImageToTexture` for WebGPU, to render the HTML content to the canvas.
-- **MANDATORY**: When using WebGL or WebGPU, update the CSS transform of the HTML element to match the transform of the rendered content by setting the `style.transform` property of the HTML element.
+- **MANDATORY**: When using WebGL, pre-allocate the texture buffer with `texImage2D()` once (when it's initialized or when the element size changes). Reallocate the texture only when the size changes, and set `TEXTURE_MIN_FILTER` to `LINEAR`.
+- **MANDATORY**: When using WebGL, use the `texElementSubImage2D` method to render the HTML content to a texture that you pre-allocate with `texImage2D()`, sized from `captureElementImage()`.
+- **MANDATORY**: When using WebGPU, use the `drawElementImageToTexture` method to render the HTML content to the canvas. Size the texture from `captureElementImage()`, and recreate it only when the size changes. Create the texture with `COPY_DST` and `RENDER_ATTACHMENT` usage, and pass the texture size as `size`.
+- **MANDATORY**: When using WebGL or WebGPU, sync the geometry of the HTML element with the rendered content by calling `canvas.updateElementGeometry(element, { canvasTransform })`.
+- **MANDATORY**: When using Three.js, register the mesh with `InteractionManager`, and call `interactions.update()` in the animation loop, so the HTML element receives input.
- **MANDATORY**: Observe the screen size and update the canvas size to match device pixels, for example, by using `ResizeObserver`.
- **DO NOT** embed cross-origin content in a canvas, as it is not supported.
- **DO NOT** initialize `ResizeObserver` within the `onpaint` event handler, as it may lead to memory leaks.
diff --git a/skills/modern-web-guidance/guides/webmcp/agentic-forms.md b/skills/modern-web-guidance/guides/webmcp/agentic-forms.md
index 472249c..a49b7ae 100644
--- a/skills/modern-web-guidance/guides/webmcp/agentic-forms.md
+++ b/skills/modern-web-guidance/guides/webmcp/agentic-forms.md
@@ -5,9 +5,9 @@ The Declarative API transforms standard HTML `<form>` elements into WebMCP tools
## Form Attributes
* `toolname`: Unique name for the tool.
-* `tooldescription`: Purpose of the tool.
+* `tooldescription`: What the tool does and when an agent should use it. Do not list the form's fields, options, or limits: the browser already includes them in the schema it builds from the form controls.
* `toolautosubmit`: (Optional) If present, the agent can submit the form without waiting for user interaction.
-* `toolparamdescription`: (Optional) Provides a way to define a property description within the JSON Schema.
+* `toolparamdescription`: (Optional) Provides a way to define a property description within the JSON Schema. Use it to explain what the value means (for example, with sample values), not to repeat the control's options or limits.
* **Resolution Order**: The browser uses `toolparamdescription` if present. In its absence, it uses the `textContent` of the associated `<label>` (skipping labelable descendants). If no label exists, it falls back to the `aria-description`.
* **Grouping (Fieldsets)**: To attach a description to a group of related elements (like `<input type="radio">` buttons), place `toolparamdescription` on the nearest parent `<fieldset>` element so it applies to the parameter group as a whole.
diff --git a/skills/modern-web-guidance/guides/webmcp/agentic-javascript-tools.md b/skills/modern-web-guidance/guides/webmcp/agentic-javascript-tools.md
index bf026e7..905029d 100644
--- a/skills/modern-web-guidance/guides/webmcp/agentic-javascript-tools.md
+++ b/skills/modern-web-guidance/guides/webmcp/agentic-javascript-tools.md
@@ -87,6 +87,37 @@ await document.modelContext.registerTool({
});
```
+## Writing Tool and Parameter Descriptions
+
+The agent already receives the full `inputSchema`, so the `description` only needs to say what the tool does and when to use it. **DO NOT** repeat parameter names, types, `enum` values, defaults, or limits in it; declare them in the schema (`enum`, `default`, `minimum`/`maximum`) instead. Parameter descriptions follow the same rule: say what the value means, not its type or allowed values.
+
+The browser does not validate arguments against `inputSchema` or apply `default` values, so do both in `execute`.
+
+```javascript
+const SORT_ORDERS = ["newest", "price_low_to_high"];
+
+await document.modelContext.registerTool({
+ name: "search_products",
+ // Don't list the sort orders here, even via SORT_ORDERS: `enum` already does.
+ description: "Searches the product catalog by keyword. Use when the user wants to find or compare products.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: { type: "string", description: "Words to search for." },
+ sort: { type: "string", enum: SORT_ORDERS, default: "newest", description: "Order of the results." },
+ },
+ required: ["query"],
+ },
+ async execute({ query, sort = "newest" }, { signal }) {
+ if (typeof query !== "string" || !SORT_ORDERS.includes(sort)) {
+ return { error: "Pass a search query and a supported sort order.", sortOrders: SORT_ORDERS };
+ }
+ return await productService.search({ query, sort }, { signal });
+ },
+ annotations: { readOnlyHint: true },
+});
+```
+
## Execution Patterns
The `execute` callback always receives two arguments: the input object, and an options object carrying an `AbortSignal` — `execute(inputObject, { signal })`.
@@ -329,6 +360,22 @@ export function createInventoryTool(inventoryManager) {
}
```
+## TypeScript Types
+
+In TypeScript projects, **DO NOT** hand-write declarations for `document.modelContext`. Install the official `webmcp-types` package (`npm install --save-dev webmcp-types`) and add it to `tsconfig.json`, since it is not picked up automatically:
+
+```jsonc
+{
+ "compilerOptions": {
+ "types": ["webmcp-types"]
+ }
+}
+```
+
+* `document.modelContext` is typed as optional, so guard it with `if (document.modelContext)` before use.
+* With an inline `inputSchema`, the `execute` input type is inferred from the schema.
+* Named types such as `WebMCP.ModelContextTool` are global (no import needed), useful for typing tool factories.
+
## API Notes
* **annotations**: (Optional) A dictionary for tool metadata.
diff --git a/skills/modern-web-guidance/guides/webmcp/webmcp.md b/skills/modern-web-guidance/guides/webmcp/webmcp.md
index b2cd2d8..c714de1 100644
--- a/skills/modern-web-guidance/guides/webmcp/webmcp.md
+++ b/skills/modern-web-guidance/guides/webmcp/webmcp.md
@@ -16,6 +16,7 @@ Currently, WebMCP **only supports Tools**. It does not support the "Resources" o
## Best Practices
* **Naming and Semantics**: Use specific verbs describing exact behavior (e.g. `create-event` vs `start-event-creation-process`). Favor positive descriptions over listing limitations.
+* **Descriptions**: Say what the tool does and when to use it. Do not repeat parameter names, types, enum values, defaults, or limits: the agent already receives them in the input schema (your `inputSchema`, or the one the browser builds from a form's controls). Put those details in the schema, and explain a non-obvious value in that parameter's own description.
* **Schema Design**: Accept raw user input (avoid agent math/calculation). Ensure all parameters have specific types and explain the purpose of options.
* **Reliability**: Validate constraints in code and return descriptive errors for retries. Handle rate limiting gracefully. Ensure the function returns *after* UI state updates for consistency.
* **Tool Strategy**: Tools should be atomic, composable, and distinct. Do not force flow control instructions ("Don't call B after A") — let the agent decide. Register/unregister tools dynamically depending on the current page context. Use `annotations: { readOnlyHint: true }` (placed after `execute`) for tools that do not modify state to inform the agent of safe execution.