Skip to content

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

Release v0.0.191

github-actions[bot]84ae7251ee91
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
index d9c5296..9ebd271 100644
--- a/.agents/plugins/marketplace.json
+++ b/.agents/plugins/marketplace.json
@@ -15,7 +15,7 @@
"authentication": "ON_INSTALL"
},
"category": "Developer Tools",
- "version": "0.0.190"
+ "version": "0.0.191"
}
]
}
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 629cc94..58113e4 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-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.190"
+ "version": "0.0.191"
}
]
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 6d2760c..6291184 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.190",
+ "version": "0.0.191",
"author": {
"name": "Google Chrome"
}
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 52c9a03..066e8a6 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "modern-web-guidance",
- "version": "0.0.190",
+ "version": "0.0.191",
"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 4d46aff..97907a9 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.190",
+ "version": "0.0.191",
"author": {
"name": "Google Chrome"
}
diff --git a/.github/plugin/plugin.json b/.github/plugin/plugin.json
index 4d46aff..97907a9 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.190",
+ "version": "0.0.191",
"author": {
"name": "Google Chrome"
}
diff --git a/.grok-plugin/marketplace.json b/.grok-plugin/marketplace.json
index 629cc94..58113e4 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.190"
+ "version": "0.0.191"
}
]
}
diff --git a/README.md b/README.md
index db15ab7..0199317 100644
--- a/README.md
+++ b/README.md
@@ -85,66 +85,72 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
#### The full list
<details>
-<summary><strong>113 modern web features</strong></summary>
+<summary><strong>130 modern web features</strong></summary>
-### CSS & Layout (55 features)
+### CSS & Layout (58 features)
| | | |
| :--- | :--- | :--- |
-| [::backdrop](https://web-platform-dx.github.io/web-features-explorer/features/backdrop/) | [Custom highlights](https://web-platform-dx.github.io/web-features-explorer/features/highlight/) | [Scroll-driven animations](https://web-platform-dx.github.io/web-features-explorer/features/scroll-driven-animations/) |
-| [:has()](https://web-platform-dx.github.io/web-features-explorer/features/has/) | [field-sizing](https://web-platform-dx.github.io/web-features-explorer/features/field-sizing/) | [scroll-initial-target](https://web-platform-dx.github.io/web-features-explorer/features/scroll-initial-target/) |
-| [:not()](https://web-platform-dx.github.io/web-features-explorer/features/not/) | [font-size-adjust](https://web-platform-dx.github.io/web-features-explorer/features/font-size-adjust/) | [scroll-target-group](https://web-platform-dx.github.io/web-features-explorer/features/scroll-target-group/) |
-| [:user-valid and :user-invalid](https://web-platform-dx.github.io/web-features-explorer/features/user-pseudos/) | [image-set()](https://web-platform-dx.github.io/web-features-explorer/features/image-set/) | [scrollbar-color](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-color/) |
-| [@function](https://web-platform-dx.github.io/web-features-explorer/features/function/) | [Individual transform properties](https://web-platform-dx.github.io/web-features-explorer/features/individual-transforms/) | [scrollbar-width](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-width/) |
-| [@starting-style](https://web-platform-dx.github.io/web-features-explorer/features/starting-style/) | [interpolate-size](https://web-platform-dx.github.io/web-features-explorer/features/interpolate-size/) | [scrollend](https://web-platform-dx.github.io/web-features-explorer/features/scrollend/) |
-| [accent-color](https://web-platform-dx.github.io/web-features-explorer/features/accent-color/) | [light-dark()](https://web-platform-dx.github.io/web-features-explorer/features/light-dark/) | [scrollIntoView()](https://web-platform-dx.github.io/web-features-explorer/features/scroll-into-view/) |
+| [::backdrop](https://web-platform-dx.github.io/web-features-explorer/features/backdrop/) | [Cross-document view transitions](https://web-platform-dx.github.io/web-features-explorer/features/cross-document-view-transitions/) | [Scroll-driven animations](https://web-platform-dx.github.io/web-features-explorer/features/scroll-driven-animations/) |
+| [: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/) | [scroll-initial-target](https://web-platform-dx.github.io/web-features-explorer/features/scroll-initial-target/) |
+| [:host-context()](https://web-platform-dx.github.io/web-features-explorer/features/host-context/) | [field-sizing](https://web-platform-dx.github.io/web-features-explorer/features/field-sizing/) | [scroll-target-group](https://web-platform-dx.github.io/web-features-explorer/features/scroll-target-group/) |
+| [:not()](https://web-platform-dx.github.io/web-features-explorer/features/not/) | [font-size-adjust](https://web-platform-dx.github.io/web-features-explorer/features/font-size-adjust/) | [scrollbar-color](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-color/) |
+| [:user-valid and :user-invalid](https://web-platform-dx.github.io/web-features-explorer/features/user-pseudos/) | [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/) |
+| [@function](https://web-platform-dx.github.io/web-features-explorer/features/function/) | [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/) |
+| [@starting-style](https://web-platform-dx.github.io/web-features-explorer/features/starting-style/) | [interpolate-size](https://web-platform-dx.github.io/web-features-explorer/features/interpolate-size/) | [scrollIntoView()](https://web-platform-dx.github.io/web-features-explorer/features/scroll-into-view/) |
+| [accent-color](https://web-platform-dx.github.io/web-features-explorer/features/accent-color/) | [light-dark()](https://web-platform-dx.github.io/web-features-explorer/features/light-dark/) | [Shadow parts](https://web-platform-dx.github.io/web-features-explorer/features/shadow-parts/) |
| [Active view transition](https://web-platform-dx.github.io/web-features-explorer/features/active-view-transition/) | [linear() easing](https://web-platform-dx.github.io/web-features-explorer/features/linear-easing/) | [sibling-count() and sibling-index()](https://web-platform-dx.github.io/web-features-explorer/features/sibling-count/) |
-| [Anchor position container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-anchor-position-queries/) | [Masks](https://web-platform-dx.github.io/web-features-explorer/features/masks/) | [text-box](https://web-platform-dx.github.io/web-features-explorer/features/text-box/) |
-| [Anchor positioning](https://web-platform-dx.github.io/web-features-explorer/features/anchor-positioning/) | [overflow-clip-margin](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip-margin/) | [text-wrap](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap/) |
+| [Anchor position container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-anchor-position-queries/) | [Masks](https://web-platform-dx.github.io/web-features-explorer/features/masks/) | [Sticky positioning](https://web-platform-dx.github.io/web-features-explorer/features/sticky-positioning/) |
+| [Anchor positioning](https://web-platform-dx.github.io/web-features-explorer/features/anchor-positioning/) | [overflow-clip-margin](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip-margin/) | [text-box](https://web-platform-dx.github.io/web-features-explorer/features/text-box/) |
| [calc-size()](https://web-platform-dx.github.io/web-features-explorer/features/calc-size/) | [overflow: clip](https://web-platform-dx.github.io/web-features-explorer/features/overflow-clip/) | [text-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-balance/) |
-| [color-scheme](https://web-platform-dx.github.io/web-features-explorer/features/color-scheme/) | [overlay](https://web-platform-dx.github.io/web-features-explorer/features/overlay/) | [text-wrap: pretty](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-pretty/) |
-| [Conic gradients](https://web-platform-dx.github.io/web-features-explorer/features/conic-gradients/) | [overscroll-behavior](https://web-platform-dx.github.io/web-features-explorer/features/overscroll-behavior/) | [transition-behavior](https://web-platform-dx.github.io/web-features-explorer/features/transition-behavior/) |
-| [Container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-queries/) | [prefers-color-scheme media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-color-scheme/) | [Trigonometric functions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/trig-functions/) |
-| [Container scroll-state queries](https://web-platform-dx.github.io/web-features-explorer/features/container-scroll-state-queries/) | [prefers-contrast media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-contrast/) | [View transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions/) |
-| [Container style queries](https://web-platform-dx.github.io/web-features-explorer/features/container-style-queries/) | [prefers-reduced-motion media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-reduced-motion/) | [view-transition-class](https://web-platform-dx.github.io/web-features-explorer/features/view-transition-class/) |
-| [content-visibility](https://web-platform-dx.github.io/web-features-explorer/features/content-visibility/) | [Scroll marker target pseudo-classes](https://web-platform-dx.github.io/web-features-explorer/features/scroll-marker-targets/) | [Web animations](https://web-platform-dx.github.io/web-features-explorer/features/web-animations/) |
-| [contrast-color()](https://web-platform-dx.github.io/web-features-explorer/features/contrast-color/) | [Scroll snap](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap/) | |
-| [Cross-document view transitions](https://web-platform-dx.github.io/web-features-explorer/features/cross-document-view-transitions/) | [Scroll snap events](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap-events/) | |
+| [Cascade layers](https://web-platform-dx.github.io/web-features-explorer/features/cascade-layers/) | [overlay](https://web-platform-dx.github.io/web-features-explorer/features/overlay/) | [text-wrap: pretty](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-pretty/) |
+| [color-scheme](https://web-platform-dx.github.io/web-features-explorer/features/color-scheme/) | [overscroll-behavior](https://web-platform-dx.github.io/web-features-explorer/features/overscroll-behavior/) | [transition-behavior](https://web-platform-dx.github.io/web-features-explorer/features/transition-behavior/) |
+| [Conic gradients](https://web-platform-dx.github.io/web-features-explorer/features/conic-gradients/) | [prefers-color-scheme media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-color-scheme/) | [Trigonometric functions (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/trig-functions/) |
+| [Container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-queries/) | [prefers-contrast media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-contrast/) | [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/) | [prefers-reduced-motion media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-reduced-motion/) | [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/) | [Scroll marker target pseudo-classes](https://web-platform-dx.github.io/web-features-explorer/features/scroll-marker-targets/) | [Web animations](https://web-platform-dx.github.io/web-features-explorer/features/web-animations/) |
+| [content-visibility](https://web-platform-dx.github.io/web-features-explorer/features/content-visibility/) | [Scroll snap](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap/) | |
+| [contrast-color()](https://web-platform-dx.github.io/web-features-explorer/features/contrast-color/) | [Scroll snap events](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap-events/) | |
-### HTML & DOM (23 features)
+### HTML & DOM (28 features)
| | | |
| :--- | :--- | :--- |
| [:autofill](https://web-platform-dx.github.io/web-features-explorer/features/autofill/) | [Customizable &lt;select>](https://web-platform-dx.github.io/web-features-explorer/features/customizable-select/) | [Interest invokers](https://web-platform-dx.github.io/web-features-explorer/features/interest-invokers/) |
-| [&lt;details>](https://web-platform-dx.github.io/web-features-explorer/features/details/) | [Email, telephone, and URL &lt;input> types](https://web-platform-dx.github.io/web-features-explorer/features/input-email-tel-url/) | [Invoker commands](https://web-platform-dx.github.io/web-features-explorer/features/invoker-commands/) |
-| [&lt;dialog closedby>](https://web-platform-dx.github.io/web-features-explorer/features/dialog-closedby/) | [Fetch priority](https://web-platform-dx.github.io/web-features-explorer/features/fetch-priority/) | [moveBefore()](https://web-platform-dx.github.io/web-features-explorer/features/move-before/) |
-| [&lt;dialog>](https://web-platform-dx.github.io/web-features-explorer/features/dialog/) | [hidden="until-found"](https://web-platform-dx.github.io/web-features-explorer/features/hidden-until-found/) | [MutationObserver](https://web-platform-dx.github.io/web-features-explorer/features/mutationobserver/) |
-| [&lt;link rel="expect">](https://web-platform-dx.github.io/web-features-explorer/features/link-rel-expect/) | [HTML in canvas](https://web-platform-dx.github.io/web-features-explorer/features/canvas-html/) | [Mutually exclusive &lt;details> elements](https://web-platform-dx.github.io/web-features-explorer/features/details-name/) |
-| [&lt;link rel="preload">](https://web-platform-dx.github.io/web-features-explorer/features/link-rel-preload/) | [HTML setter methods](https://web-platform-dx.github.io/web-features-explorer/features/html-setters/) | [Popover](https://web-platform-dx.github.io/web-features-explorer/features/popover/) |
-| [&lt;progress>](https://web-platform-dx.github.io/web-features-explorer/features/progress/) | [HTML streaming setters](https://web-platform-dx.github.io/web-features-explorer/features/html-streaming-setters/) | [popover="hint"](https://web-platform-dx.github.io/web-features-explorer/features/popover-hint/) |
+| [&lt;details>](https://web-platform-dx.github.io/web-features-explorer/features/details/) | [Declarative shadow DOM](https://web-platform-dx.github.io/web-features-explorer/features/declarative-shadow-dom/) | [Invoker commands](https://web-platform-dx.github.io/web-features-explorer/features/invoker-commands/) |
+| [&lt;dialog closedby>](https://web-platform-dx.github.io/web-features-explorer/features/dialog-closedby/) | [Email, telephone, and URL &lt;input> types](https://web-platform-dx.github.io/web-features-explorer/features/input-email-tel-url/) | [moveBefore()](https://web-platform-dx.github.io/web-features-explorer/features/move-before/) |
+| [&lt;dialog>](https://web-platform-dx.github.io/web-features-explorer/features/dialog/) | [Fetch priority](https://web-platform-dx.github.io/web-features-explorer/features/fetch-priority/) | [MutationObserver](https://web-platform-dx.github.io/web-features-explorer/features/mutationobserver/) |
+| [&lt;link rel="expect">](https://web-platform-dx.github.io/web-features-explorer/features/link-rel-expect/) | [Form-associated custom elements](https://web-platform-dx.github.io/web-features-explorer/features/form-associated-custom-elements/) | [Mutually exclusive &lt;details> elements](https://web-platform-dx.github.io/web-features-explorer/features/details-name/) |
+| [&lt;link rel="preload">](https://web-platform-dx.github.io/web-features-explorer/features/link-rel-preload/) | [hidden="until-found"](https://web-platform-dx.github.io/web-features-explorer/features/hidden-until-found/) | [Popover](https://web-platform-dx.github.io/web-features-explorer/features/popover/) |
+| [&lt;progress>](https://web-platform-dx.github.io/web-features-explorer/features/progress/) | [HTML in canvas](https://web-platform-dx.github.io/web-features-explorer/features/canvas-html/) | [popover="hint"](https://web-platform-dx.github.io/web-features-explorer/features/popover-hint/) |
+| [&lt;slot>](https://web-platform-dx.github.io/web-features-explorer/features/slot/) | [HTML setter methods](https://web-platform-dx.github.io/web-features-explorer/features/html-setters/) | [Shadow DOM](https://web-platform-dx.github.io/web-features-explorer/features/shadow-dom/) |
+| [Autonomous custom elements](https://web-platform-dx.github.io/web-features-explorer/features/autonomous-custom-elements/) | [HTML streaming setters](https://web-platform-dx.github.io/web-features-explorer/features/html-streaming-setters/) | |
| [blocking="render"](https://web-platform-dx.github.io/web-features-explorer/features/blocking-render/) | [inert](https://web-platform-dx.github.io/web-features-explorer/features/inert/) | |
-### JavaScript & APIs (35 features)
+### JavaScript & APIs (44 features)
| | | |
| :--- | :--- | :--- |
-| [&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/) | [Sanitizer API](https://web-platform-dx.github.io/web-features-explorer/features/sanitizer/) |
-| [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/) | [Scheduler API](https://web-platform-dx.github.io/web-features-explorer/features/scheduler/) |
-| [document.modelContext](https://web-platform-dx.github.io/web-features-explorer/features/document-modelcontext/) | [LanguageModel](https://web-platform-dx.github.io/web-features-explorer/features/languagemodel/) | [Speculation rules](https://web-platform-dx.github.io/web-features-explorer/features/speculation-rules/) |
-| [enterkeyhint](https://web-platform-dx.github.io/web-features-explorer/features/enterkeyhint/) | [Lazy-loading images and iframes](https://web-platform-dx.github.io/web-features-explorer/features/loading-lazy/) | [Summarizer](https://web-platform-dx.github.io/web-features-explorer/features/summarizer/) |
-| [Event timing performance entries](https://web-platform-dx.github.io/web-features-explorer/features/event-timing/) | [Long animation frames performance entries](https://web-platform-dx.github.io/web-features-explorer/features/long-animation-frames/) | [SVG](https://web-platform-dx.github.io/web-features-explorer/features/svg/) |
-| [Federated credential management](https://web-platform-dx.github.io/web-features-explorer/features/fedcm/) | [Navigation API](https://web-platform-dx.github.io/web-features-explorer/features/navigation/) | [Temporal](https://web-platform-dx.github.io/web-features-explorer/features/temporal/) |
-| [Fetch](https://web-platform-dx.github.io/web-features-explorer/features/fetch/) | [Page visibility](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility/) | [Top-level await](https://web-platform-dx.github.io/web-features-explorer/features/top-level-await/) |
-| [fetchLater](https://web-platform-dx.github.io/web-features-explorer/features/fetchlater/) | [Page visibility state performance entries](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility-state/) | [Translator](https://web-platform-dx.github.io/web-features-explorer/features/translator/) |
-| [Form-associated WebMCP attributes](https://web-platform-dx.github.io/web-features-explorer/features/declarative-webmcp/) | [Partitioned cookies](https://web-platform-dx.github.io/web-features-explorer/features/partitioned-cookies/) | [User agent client hints](https://web-platform-dx.github.io/web-features-explorer/features/ua-client-hints/) |
-| [inputmode](https://web-platform-dx.github.io/web-features-explorer/features/inputmode/) | [Permissions policy](https://web-platform-dx.github.io/web-features-explorer/features/permissions-policy/) | [Web authentication](https://web-platform-dx.github.io/web-features-explorer/features/webauthn/) |
-| [Intersection observer](https://web-platform-dx.github.io/web-features-explorer/features/intersection-observer/) | [Registered custom properties](https://web-platform-dx.github.io/web-features-explorer/features/registered-custom-properties/) | [Web authentication signal methods](https://web-platform-dx.github.io/web-features-explorer/features/webauthn-signals/) |
-| [Intl.DurationFormat](https://web-platform-dx.github.io/web-features-explorer/features/intl-duration-format/) | [Resize observer](https://web-platform-dx.github.io/web-features-explorer/features/resize-observer/) | |
+| [&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/) | [Subresource integrity](https://web-platform-dx.github.io/web-features-explorer/features/subresource-integrity/) |
+| [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/) | [Summarizer](https://web-platform-dx.github.io/web-features-explorer/features/summarizer/) |
+| [cross-origin-storage](https://web-platform-dx.github.io/web-features-explorer/features/tmp-cross-origin-storage/) | [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/) |
+| [document.modelContext](https://web-platform-dx.github.io/web-features-explorer/features/document-modelcontext/) | [Local network access](https://web-platform-dx.github.io/web-features-explorer/features/local-network-access/) | [Temporal](https://web-platform-dx.github.io/web-features-explorer/features/temporal/) |
+| [enterkeyhint](https://web-platform-dx.github.io/web-features-explorer/features/enterkeyhint/) | [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/) |
+| [Event timing performance entries](https://web-platform-dx.github.io/web-features-explorer/features/event-timing/) | [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/) |
+| [Federated credential management](https://web-platform-dx.github.io/web-features-explorer/features/fedcm/) | [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/) |
+| [Fetch](https://web-platform-dx.github.io/web-features-explorer/features/fetch/) | [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/) |
+| [fetchLater](https://web-platform-dx.github.io/web-features-explorer/features/fetchlater/) | [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/) |
+| [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](https://web-platform-dx.github.io/web-features-explorer/features/webauthn/) |
+| [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/) | [Web authentication signal methods](https://web-platform-dx.github.io/web-features-explorer/features/webauthn-signals/) |
+| [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/) | [Web Cryptography](https://web-platform-dx.github.io/web-features-explorer/features/web-cryptography/) |
+| [Intersection observer](https://web-platform-dx.github.io/web-features-explorer/features/intersection-observer/) | [Sanitizer API](https://web-platform-dx.github.io/web-features-explorer/features/sanitizer/) | [WebAssembly](https://web-platform-dx.github.io/web-features-explorer/features/wasm/) |
+| [Intl.DurationFormat](https://web-platform-dx.github.io/web-features-explorer/features/intl-duration-format/) | [Scheduler API](https://web-platform-dx.github.io/web-features-explorer/features/scheduler/) | |
</details>
<details>
-<summary><strong>138 real-world developer use cases</strong></summary>
+<summary><strong>153 real-world developer use cases</strong></summary>
<h3>accessibility</h3>
@@ -191,6 +197,16 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[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.
- **[validate-input-after-interaction](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/validate-input-after-interaction.md)**: Show form field validation feedback (e.g. password complexity or email format requirements) only after the user has finished their initial interaction, avoiding premature errors on page load or while the user is typing.
+<h3>html</h3>
+
+- **[accessible-web-components](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/html/accessible-web-components.md)**: Make custom elements accessible by default, setting roles and ARIA state via the ElementInternals ARIA mixin, managing focus with delegatesFocus, and keeping ARIA relationships within a single shadow root.
+- **[custom-elements](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/html/custom-elements.md)**: Define, register, and manage the lifecycle of autonomous custom elements, covering constructor rules, lifecycle callbacks, upgrade timing, attribute/property reflection, and naming conventions.
+- **[form-associated-custom-elements](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/html/form-associated-custom-elements.md)**: Make a custom control participate natively in forms with formAssociated and ElementInternals, submitting its own value, integrating with constraint validation, and reacting to reset, disable, and state-restore.
+- **[prerendering-custom-elements](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/html/prerendering-custom-elements.md)**: Server-render a custom element, then hydrate it in place without re-rendering or a flash of unstyled content.
+- **[shadow-dom](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/html/shadow-dom.md)**: Encapsulate a component's DOM and styles with Shadow DOM, construct the tree efficiently with HTML templates, and project consumer content with slots.
+- **[styling-web-components](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/html/styling-web-components.md)**: Style across the shadow boundary with :host selectors, inherited and custom properties for theming, ::slotted and ::part, and cascade layers and container queries inside components.
+- **[web-components](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/html/web-components.md)**: Orientation and cross-cutting principles for authoring and using Web Components, covering Custom Elements, Shadow DOM, templates and slots, Declarative Shadow DOM, styling across the shadow boundary, Form-Associated Custom Elements, and accessibility requirements. Use this guide when building reusable UI components, design systems, or server-rendered custom elements.
+
<h3>js</h3>
- **[calculate-event-differentials](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/js/calculate-event-differentials.md)**: Calculate the duration and time remaining between dates and times.
@@ -204,6 +220,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
<h3>performance</h3>
+- **[avoid-redundant-large-asset-downloads](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/avoid-redundant-large-asset-downloads.md)**: Avoid re-downloading and re-storing large shared assets, such as AI models, Wasm modules, or fully-bundled JavaScript libraries, that a visitor's browser may already hold from an unrelated site.
- **[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.
- **[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.
@@ -221,6 +238,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[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
- **[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.
- **[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.
+- **[load-shared-resources-declaratively](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/load-shared-resources-declaratively.md)**: Serve popular, unmodified scripts, stylesheets, and JavaScript modules from a shared cross-origin cache using markup or import syntax alone, without writing custom caching logic.
- **[optimize-image-priority](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/optimize-image-priority.md)**: Optimize the loading priority of Largest Contentful Paint (LCP) candidate images and deprioritize non-critical images to reduce critical resource load delays.
- **[optimize-preload-priority](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/optimize-preload-priority.md)**: Optimize the relative priority of preloaded content to reduce critical resource load delays.
- **[optimize-script-priority](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/optimize-script-priority.md)**: Optimize the loading priority of scripts by boosting critical asynchronous scripts and deprioritizing non-essential or late-body scripts to improve sequencing and reduce delays.
@@ -228,13 +246,19 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[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.
+- **[share-web-fonts-across-origins](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/share-web-fonts-across-origins.md)**: Serve large, popular web fonts from a shared cross-origin cache instead of re-downloading them from a font CDN on every site that references them.
<h3>privacy</h3>
- **[privacy](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/privacy/privacy.md)**: Action-oriented guidelines for web developers to implement privacy by design, data minimization, third-party audits, and secure data handling. Use this skill when designing applications, integrating third-party services, handling user data, or configuring security headers.
+<h3>pwa</h3>
+
+- **[migrate-web-app-origin](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md)**: Transfer an installed web app to a new origin while preserving user configuration and OS-level shortcuts.
+
<h3>security</h3>
+- **[local-network-access](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/local-network-access.md)**: Access resources on a user's local network or loopback interface from a public web application.
- **[passkey-authentication](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/passkey-authentication.md)**: Authenticate a returning user with a passkey for primary sign-in.
- **[passkey-conditional-create](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/passkey-conditional-create.md)**: Silently register a passkey for an existing user after a successful password login.
- **[passkey-management](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/security/passkey-management.md)**: Let users view and manage the passkeys registered to their account.
@@ -242,6 +266,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[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.
- **[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 ensuring all untrusted content is sanitized before being inserted into the page.
<h3>ui-atoms</h3>
@@ -250,6 +275,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[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.
@@ -286,6 +312,7 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[scroll-target-on-load](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/scroll-target-on-load.md)**: Build a scrollable list of elements (e.g. a carousel of images or a chat conversation thread) that can be displayed with a particular element scrolled into view on the initial render.
- **[scrollytelling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/scrollytelling.md)**: Animate visual properties on a target element — such as fading a backdrop, shifting a background color, or to create scrollytelling experiences — driven entirely by the scrollport position of a completely different element.
- **[search-hidden-content](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/search-hidden-content.md)**: Hide content from view using patterns such as accordions, tabs, and "Read more" sections, while ensuring the hidden text reveals itself during native "Find in page" searches, allows search engine indexing, supports URL fragment deep links, and maintains ARIA accessibility.
+- **[spatial-navigation](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md)**: Implement accessible spatial navigation using arrow keys that works correctly in different layout modes (grid etc)
- **[swipe-to-remove](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/ui-behaviors/swipe-to-remove.md)**: Let users act on items in a list (remove, archive, mark as read, etc.) with a horizontal swipe gesture, so they can process entries quickly without tapping a separate control.
<h3>ui-components</h3>
@@ -311,13 +338,16 @@ _View an example:_ [the `navigation-drawer` guide](https://github.com/GoogleChro
- **[improve-text-layout-and-legibility](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/improve-text-layout-and-legibility.md)**: Improve the layout and legibility of short standalone text content, such as headings no longer than a few lines, by enabling the browser to apply evenly balanced line breaks when wrapping text.
- **[interactive-content-in-3d-scenes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/interactive-content-in-3d-scenes.md)**: Integrate interactive HTML elements into a 3D scene.
- **[precise-text-alignment](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/precise-text-alignment.md)**: Achieve precise vertical alignment with text of any font. For example, exactly equal visual padding above and below text, or aligning text perfectly flush with adjacent icons or images.
-- **[prevent-text-wrapping](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/prevent-text-wrapping.md)**: Ensure the browser does not insert line breaks into text and will allow text to overflow its container.
- **[shaped-cutouts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/shaped-cutouts.md)**: Combine multiple shapes to create complex cutouts or 'knockout' effects in elements, such as adding a notch to an element.
- **[soft-edge-content-fade](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/soft-edge-content-fade.md)**: Apply a transparency gradient to content edges to indicate further scrollable areas or to obscure payment-walled text.
- **[visually-stable-font-fallbacks](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/visually-stable-font-fallbacks.md)**: Define font styles such that text remains readable and visually consistent in the event that there's a swap between the perferred font and one of the fallbacks (or vise versa).
- **[visually-stable-mixed-fonts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/visually-stable-mixed-fonts.md)**: Define font styles such that text remains readable and visually consistent in situations where multiple fonts are used to render a single block of text.
- **[visually-texture-content](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/visual-design/visually-texture-content.md)**: Apply realistic weathering and texture patterns to elements to give them an organic, aged, or physical material appearance.
+<h3>wasm</h3>
+
+- **[cpp-on-the-web](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/wasm/cpp-on-the-web.md)**: Compile C/C++ to WebAssembly using Emscripten
+
<h3>webmcp</h3>
- **[agentic-forms](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/webmcp/agentic-forms.md)**: Expose client-side functionality as tools to AI agents by annotating standard HTML forms with WebMCP attributes.
diff --git a/gemini-extension.json b/gemini-extension.json
index 6d2760c..6291184 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.190",
+ "version": "0.0.191",
"author": {
"name": "Google Chrome"
}
diff --git a/kimi.plugin.json b/kimi.plugin.json
index 3cc1138..5b00024 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.190",
+ "version": "0.0.191",
"author": {
"name": "Google Chrome"
},
diff --git a/package.json b/package.json
index 320a249..8cce923 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.190",
+ "version": "0.0.191",
"publisher": "GoogleChrome",
"repository": {
"url": "https://github.com/GoogleChrome/modern-web-guidance-src"
diff --git a/skills/modern-web-guidance/guides/forms/animated-select-picker.md b/skills/modern-web-guidance/guides/forms/animated-select-picker.md
index 4a86e12..b7ccd76 100644
--- a/skills/modern-web-guidance/guides/forms/animated-select-picker.md
+++ b/skills/modern-web-guidance/guides/forms/animated-select-picker.md
@@ -151,8 +151,9 @@ The following example demonstrates a custom select styled with standard page ani
- **DO** use `@starting-style` when you need animations to trigger exactly when an element transitions from `display: none` to visible.
- **DO NOT** use ad-hoc scroll locking. Top-layer elements managed by ‘base-select’ should allow natural backdrop dismiss behaviors.
- **DO** verify reduced motion preferences. Always wrap animation constraints in a `prefers-reduced-motion` media query to ensure accessible environments for those affected by motion sickness.
-- **DO** test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
-- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
+- Test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
+- Ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
+- Use standard `value` attributes on options to ensure form submission works exactly as before.
## Fallback strategies
diff --git a/skills/modern-web-guidance/guides/forms/branded-select-styling.md b/skills/modern-web-guidance/guides/forms/branded-select-styling.md
index 8b2b667..8d9bfa9 100644
--- a/skills/modern-web-guidance/guides/forms/branded-select-styling.md
+++ b/skills/modern-web-guidance/guides/forms/branded-select-styling.md
@@ -87,8 +87,9 @@ The following example demonstrates a custom select styled with a monospace font
- **DO** use `appearance: base-select` when your design system requires high-fidelity, visual consistency across all form controls that cannot be achieved with standard cross-browser select overrides.
- **DO NOT** use this if you rely on the operating system's native picker experience (e.g., the standard scroll wheel picker on iOS devices). Opting into `base-select` opts out of native mobile UI controls in favor of web-rendered top-layer menus.
- **DO** verify that color contrast meets WCAG standards. The customizable picker allows you to set ad-hoc colors, but you are responsible for ensuring text remains legible against custom backgrounds.
-- **DO** test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
-- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
+- Test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
+- Ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
+- Use standard `value` attributes on options to ensure form submission works exactly as before.
## Fallback strategies
diff --git a/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md b/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md
index 5234b21..744678d 100644
--- a/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md
+++ b/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md
@@ -1,83 +1,146 @@
# Custom Select Picker Layouts
-"Custom Select Picker Layouts" allow developers to break away from the traditional vertical list of options in a `<select>` dropdown. Using `appearance: base-select` and the `::picker(select)` pseudo-element, you can style the options list using modern CSS layout techniques like Grid or Flexbox. This is ideal for color pickers, emoji selectors, or product variants where a visual menu is more effective than a list.
+The CSS property `appearance: base-select` unlocks the ability to style a `<select>` element and its picker (via `::picker(select)`) like regular HTML elements.
+Combined with modern CSS layout techniques like Grid or Flexbox, you can break away from the traditional stacked vertical list and create a rich visual experience without custom JS.
+For example, you can use `display: grid` to style the options as a 2D grid of cards.
-The CSS property `appearance: base-select` unlocks the ability to style the internal parts of a `<select>` element. By targeting `select::picker(select)`, you can apply `display: grid` and position options in columns, creating a rich visual experience without custom JavaScript.
+This is ideal for color pickers, emoji selectors, or product variants where a rich visual menu is more effective than a list.
## How to Implement
-To implement a custom select picker layout:
-
-1. **Activate Base Styling:** Apply `appearance: base-select` to both the `<select>` element and its internal picker pseudo-element `select::picker(select)`.
-2. **Style the Picker Container:** Target `select::picker(select)` and apply `display: grid` (or `display: flex`). Define columns and gaps as you would for any container.
-3. **Style Options:** Target the `<option>` elements to style them as grid items or cards. You can add images, SVGs, or complex layouts inside them.
-4. **Customize the Trigger (Optional):** Use `<selectedcontent>` inside a `<button>` to render rich content for the selected value.
-
-## Example Code: Custom Grid Picker
-
-```html
-<label for="weather-picker">Select weather</label>
-<select class="grid-picker" name="weather" id="weather-picker">
- <button>
- <selectedcontent></selectedcontent>
- </button>
- <option value="sunny">
- <span class="icon">☀️</span>
- <span class="label">Sunny</span>
- </option>
- <option value="cloudy">
- <span class="icon">☁️</span>
- <span class="label">Cloudy</span>
- </option>
- <!-- More options... -->
-</select>
-```
+### 1. Activate Base Styling
+
+Apply `appearance: base-select` to both the `<select>` element and its internal picker pseudo-element `select::picker(select)`:
```css
-/* Activate the customizable select state */
-.grid-picker,
-.grid-picker::picker(select) {
- appearance: base-select;
+select.grid-picker {
+ &, &::picker(select) {
+ appearance: base-select;
+ }
}
-/* Style the dropdown list as a grid */
-.grid-picker::picker(select) {
+```
+
+### 2. Style the Picker Container
+
+Target `select:open::picker(select)` and apply `display: grid` (or `display: flex`).
+Define columns and gaps as you would for any container.
+
+```css
+select.grid-picker:open::picker(select) {
display: grid;
- grid-template-columns: repeat(2, 1fr); /* 2 columns */
- gap: 10px;
- padding: 15px;
- background: white;
- border: 1px solid #ccc;
- border-radius: 8px;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 1rem;
}
+```
+
+IMPORTANT: The `:open` is necessary. If you style `select::picker(select)`, it will make the picker visible even when the select is closed!
+
+### 3. Style the Options
+Target the `<option>` elements to style them as grid items or cards.
+You can add images, SVGs, or complex layouts inside them.
+
+```css
/* Style options as grid cards */
.grid-picker option {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
- padding: 15px;
- border: 1px solid #eee;
- border-radius: 6px;
+ /* padding, border-radius, background, etc. */
}
+```
+
+### 4. Style the selected option
+
+To style the selected *option*, use `option:checked`. For example:
-/* MANDATORY: Use multiple visual indicators (distinct border thickness, background shift, and font weight) for the checked state to avoid color-only state communication */
+```css
.grid-picker option:checked {
- border: 2px solid #007bff;
- background-color: #f0f7ff;
- font-weight: 700;
+ position: relative;
+ border: 2px solid var(--primary-color);
+ background-color: oklab(from var(--primary-color) l a b / 8%);
+}
+```
+
+As with any UI control, do not communicate state with color alone, and use multiple visual indicators (e.g. colors, border thickness, checkmark) to communicate which option is selected.
+
+### 5. (Optional) Style the selected option checkmark
+
+By default, the browser renders a checkmark as the first child of every `<option>`.
+
+It behaves like a `::before` with `content: "✓" / ""`, rendered before an author-provided `::before`, if one exists.
+
+If the option is not selected, the checkmark is hidden via `visibility: hidden`.
+
+You can style it using the `::checkmark` pseudo-element, or hide it entirely if you want to convey selection via styling alone or use a custom indicator.
+
+For example, to place it at the top-right corner of the option, you could do something like:
+
+```css
+select.grid-picker {
+ > option::checkmark {
+ /* Hide the checkmark for unselected options */
+ display: none;
+ }
+
+ > option:checked {
+ position: relative;
+
+ &::checkmark {
+ position: absolute;
+ inset-block-start: -.4em;
+ inset-inline-end: -.5em;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ box-sizing: border-box;
+ min-inline-size: 1.6em;
+ aspect-ratio: 1;
+ padding-right: 0.12em;
+ padding-left: 0.05em;
+ border-radius: 50%;
+ background: var(--primary-color);
+ color: white;
+ font-size: 70%;
+ font-weight: bold;
+ }
+ }
}
```
-## Strategic Implementation & Best Practices
+**Tip:** When painting a container (e.g. a circle) around the checkmark, nudge it a little towards the top (as we did here with `padding-bottom` and `padding-left`) for optical centering that accounts for its shape.
+Do NOT use `padding-inline-start` or `padding-block-end` for this, as they will change depending on writing mode, whereas the shape of the checkmark does not.
+
+### 6. (Optional) Customize the selected option display
+
+By default, the `<select>` will show a text-only version of the selected option.
+To display rich content for the selected value, use `<selectedcontent>` inside a `<button>` and/or to display the selected option differently (e.g. hide certain details).
+
+Not **NOT** use `<selectedcontent>` without the `<button>` around it, as the `<selectedcontent>` will just become part of the picker, like any other content element.
+
+### Best practices
+
+- Test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
+- Ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
+- Use standard `value` attributes on options to ensure form submission works exactly as before.
+
+## Accessibility
+
+<!-- See https://github.com/GoogleChrome/modern-web-guidance-src/pull/960#pullrequestreview-4880620093 -->
+
+A native `<select>` only handles linear Up/Down arrow navigation, so Left/Right do nothing in the open picker and Up/Down still navigate items sequentially, regardless of rows and columns.
+
+To implement spatial navigation that follows the grid, you can intercept `keydown` and route focus to the nearest option in the pressed direction (e.g. using `getBoundingClientRect()`) when arrow keys are used.
+To determine the appropriate next/previous item, use DOM methods that operate on actual geometry (e.g. `getBoundingClientRect()`) rather than parsing CSS strings like `grid-template-columns` or `grid-column`, which can be brittle and error-prone for complex grids, subgrid, RTL, and other layout scenarios.
+That said, do not unnecessarily overengineer; use what invariants you know are true about the layout to simplify this logic.
+
+**Note:** This _only_ addresses keyboard navigation. The `<select>` and its `::picker()` still have their default roles (`menu` or `listbox`), and these cannot be overridden, nor are they allowed to contain an element with `role="grid"`.
+Nesting a wrapper with `role="grid"` inside the picker works in practice, but is not valid, and may surprise AT users.
+In some cases, using `<optgroup>` to group options may produce a good screen reader UX without `role="grid"`.
+Otherwise, it may be ultimately necessary to switch to a custom solution using the popover API, anchor positioning, and `role="grid"` to achieve the desired UX for screen reader users.
-- **DO** use `appearance: base-select` when you need to change the visual layout of options from a standard list to a 2D grid or custom flex flow.
-- **DO NOT** assume the styles apply to all browsers equally yet; verify support and provide a fallback.
-- **MANDATORY Accessibility Routing**: A native `<select>` element enforces one-dimensional linear arrow-key navigation (Up/Down). Arranging options in a 2D visual grid creates a spatial mismatch where pressing Left/Right arrows does not move focus horizontally between adjacent columns. If true two-dimensional keyboard navigation is essential for usability, do not use a native `<select>`; implement a custom ARIA `role="listbox"` composite widget with manual JavaScript matrix-based arrow key navigation instead.
-- **DO** use `<selectedcontent>` if you want the trigger button to show images or icons from the selected option automatically.
-- **DO** use standard `value` attributes on options to ensure form submission works exactly as before.
-- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
## Fallback Strategy
@@ -100,4 +163,4 @@ document.addEventListener("DOMContentLoaded", () => {
// Custom select overrides are not supported natively.
}
});
-```
\ No newline at end of file
+```
diff --git a/skills/modern-web-guidance/guides/forms/rich-media-picker.md b/skills/modern-web-guidance/guides/forms/rich-media-picker.md
index 1f495ac..34ca6ec 100644
--- a/skills/modern-web-guidance/guides/forms/rich-media-picker.md
+++ b/skills/modern-web-guidance/guides/forms/rich-media-picker.md
@@ -105,8 +105,9 @@ select.custom-select option:checked .option-title {
- **DO NOT** use ad-hoc elements if you notice performance lags; the browser handles native keyboard focus natively.
- **DO** account for top-layer rendering. The picker renders in the top-layer, meaning it overrides relative `z-index` of page content.
- **DO** hide secondary details (like descriptions) in the button state if they take too much space, by styling `.custom-select selectedcontent .option-desc { display: none; }`.
-- **DO** test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
-- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
+- Test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.
+- Ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.
+- Use standard `value` attributes on options to ensure form submission works exactly as before.
## Fallback Strategies
diff --git a/skills/modern-web-guidance/guides/html/accessible-web-components.md b/skills/modern-web-guidance/guides/html/accessible-web-components.md
new file mode 100644
index 0000000..dd6fc1e
--- /dev/null
+++ b/skills/modern-web-guidance/guides/html/accessible-web-components.md
@@ -0,0 +1,47 @@
+# Accessible Web Components
+
+A shadow boundary changes how semantics and ARIA work. Two failures dominate: missing semantics inside the shadow tree, and ARIA references that silently break because they cannot cross shadow roots.
+
+Start from semantic markup: use real `<button>`, `<nav>`, `<ul>` inside the template so most semantics come for free, and reserve `ElementInternals`/ARIA for the gaps.
+
+## Default semantics via the ElementInternals ARIA mixin
+
+Set a custom element's role and ARIA state in JS through `ElementInternals`, rather than writing ARIA attributes onto the host. This keeps the semantics as defaults the component owns, while still letting a consumer override them with attributes in the Light DOM.
+
+```javascript
+class ToggleSwitch extends HTMLElement {
+ #internals;
+ constructor() {
+ super();
+ this.#internals = this.attachInternals();
+ this.#internals.role = 'switch'; // default role, no host attribute needed
+ this.#internals.ariaChecked = 'false'; // exposed to the accessibility tree
+ }
+ toggle() {
+ const on = this.#internals.ariaChecked !== 'true';
+ this.#internals.ariaChecked = String(on);
+ }
+}
+customElements.define('toggle-switch', ToggleSwitch);
+```
+
+This avoids polluting the DOM with ARIA attributes and prevents consumers from accidentally clobbering them, while the accessibility tree still sees the correct role and state.
+
+## Focus management and `delegatesFocus`
+
+- Attach the shadow root with `delegatesFocus: true` when the component wraps focusable controls. Focusing the host then forwards focus to the first focusable child, and `:focus`/label clicks behave as users expect.
+- For roving focus or moving focus into a newly revealed region, give the target `tabindex="-1"` and call `.focus()`; make programmatically-focusable targets explicit rather than relying on tab order.
+
+## ARIA relationships cannot cross shadow roots
+
+- **MANDATORY**: an `id` referenced by `aria-labelledby`, `aria-describedby`, `aria-controls`, etc. must live in the **same** tree as the referencing element. An attribute in the Light DOM cannot point at an `id` inside the shadow tree, and vice versa; the reference is silently ignored.
+- Keep each ARIA relationship within one root. If a label in the shadow tree must describe a slotted Light DOM element, move the relationship into one tree (e.g. render the label in the Light DOM, or use `aria-label` text instead of an `id` reference).
+- For element-to-element references that genuinely must cross roots, the emerging **Reference Target** mechanism is the standards direction, but it is not yet broadly available; design to keep references within a single tree today.
+- The reflected ARIA *element* properties — `ariaLabelledByElements`, `ariaDescribedByElements`, and siblings — let you set these relationships to actual element references in JS, with no `id` needed. Browser support is still limited and the rules for referencing across shadow roots are constrained and evolving, so verify before relying on them; today, treat them mainly as a cleaner way to wire *same-tree* relationships without minting ids.
+
+## Fallback strategies
+
+Baseline status for ARIA attribute reflection: Widely available. It's been Baseline since 2023-10-24.
+Supported by: Chrome 103 (Jun 2022), Edge 103 (Jun 2022), Firefox 119 (Oct 2023), and Safari 16.4 (Mar 2023).
+
+Where the `ElementInternals` ARIA mixin is unavailable, set the role and ARIA state as attributes on the host instead (`this.setAttribute('role', 'switch')`). It works everywhere, at the cost of putting attributes in the DOM that a consumer could override.
diff --git a/skills/modern-web-guidance/guides/html/custom-elements.md b/skills/modern-web-guidance/guides/html/custom-elements.md
new file mode 100644
index 0000000..944073d
--- /dev/null
+++ b/skills/modern-web-guidance/guides/html/custom-elements.md
@@ -0,0 +1,118 @@
+# Custom Elements
+
+A custom element is a class registered against a tag name via `customElements.define()`. Registration and basic lifecycle are well understood; the rules below target the parts routinely implemented incorrectly.
+
+## Lifecycle: the parts that get implemented wrong
+
+The callbacks themselves are well documented; these are the misconceptions that cause bugs:
+
+- **`connectedCallback` can run more than once.** It fires on every insertion, so moving the element re-runs it. Make setup idempotent — don't assume a single first run.
+- **`connectedMoveCallback` skips the disconnect/reconnect pair on a move.** When an element is relocated with `Node.moveBefore()`, this callback fires *instead of* `disconnectedCallback` → `connectedCallback`, so state, focus, and iframe/media playback survive the move. Define it when your setup or teardown is expensive or observably re-runs.
+- **Tear down in `disconnectedCallback`.** Remove global listeners, timers, and observers or you leak; but the element may be re-inserted, so don't treat teardown as permanent.
+- **Do not depend on the full DOM being present in the constructor.** Attributes are usually (but not always) present; long lists of children may not have finished parsing. Use `connectedCallback` for one-shot initialization, `slotchange` to monitor direct children, and `attributeChangedCallback` to monitor attributes. `connectedCallback` may still fire before all children are parsed, so do not ignore subsequent `slotchange` / `attributeChangedCallback` calls.
+- **`attributeChangedCallback` fires only for `observedAttributes`,** and should stay cheap for attributes that don't affect output.
+- **Lifecycle hooks and `observedAttributes` are snapshotted at registration.** `customElements.define()` reads both once; adding a hook or extending `observedAttributes` on the class *after* the call is silently ignored. In particular, `attributeChangedCallback` never fires unless `observedAttributes` was already present at `define()` time.
+
+## Upgrade timing and `:defined`
+
+An element can exist in the DOM *before* its class is registered (in server-rendered HTML, or when the script loads late). Until defined it is an inert `HTMLElement` with none of your behavior; when `customElements.define()` runs, the browser **upgrades** every matching element already in the document, running its constructor and `connectedCallback` then.
+
+Two consequences models routinely miss:
+
+1. **Attributes and children may already be present** when your constructor/`connectedCallback` runs on upgrade. Read existing attributes in `connectedCallback` to sync initial state, and never assume the element started empty.
+2. **Children may still be missing** even in `connectedCallback` — the HTML parser can yield mid-parse of long child lists, so the callback sometimes runs before every child is attached. See the constructor bullet in *Lifecycle* above for the pattern (`slotchange` + `attributeChangedCallback`).
+
+Hide undefined elements to avoid a flash of unstyled content — but **fail open**, so the content stays reachable if the script never loads. Animate `opacity` with a delay rather than hard-hiding with `visibility: hidden`, so the element reveals itself after a timeout even when it is never upgraded:
+
+```css
+my-element:not(:defined) {
+ opacity: 0;
+ /* Reveal anyway after 2s, so a failed or slow script never hides content for good. */
+ animation: defined-fallback 0.2s 2s forwards;
+}
+@keyframes defined-fallback { to { opacity: 1; } }
+```
+
+Scope these guards to the elements that need them — or to a specific subtree via `:has(:not(:defined))` — rather than the whole `body`. One slow, non-critical widget (a share button, say) should not delay paint for the entire page.
+
+## Attribute ⇄ property reflection
+
+Keep the HTML attribute and the JS property in sync so the element is usable from both markup and script. Attribute values are **always strings**; coerce them.
+
+```javascript
+class MyToggle extends HTMLElement {
+ static observedAttributes = ['label', 'disabled'];
+
+ // String attribute reflected via getter/setter.
+ get label() { return this.getAttribute('label') ?? ''; }
+ set label(v) {
+ v ? this.setAttribute('label', v) : this.removeAttribute('label');
+ }
+
+ // Boolean attribute: present = true, absent = false. Never set it to "false".
+ get disabled() { return this.hasAttribute('disabled'); }
+ set disabled(on) { this.toggleAttribute('disabled', !!on); }
+
+ attributeChangedCallback(name, oldVal, newVal) {
+ if (oldVal !== newVal) this.render();
+ }
+}
+```
+
+### Where the value lives
+
+The example above keeps the **DOM as the source of truth** — each getter reads `getAttribute`. That's the right default for a handful of simple, string-ish attributes: there is only one place the state can live, so it can't desync.
+
+For richer components, keep the **source of truth in a JS field** and reflect *outward* to an attribute only when something else must see it — CSS targeting, or a consumer reading it. Reading a field is far cheaper than parsing and coercing an attribute on every access, and non-string values never round-trip through serialization. This is why libraries like Lit hold state in JS and reflect selectively rather than treating attributes as storage: reflect only what the outside world must observe, not every property.
+
+Pitfalls:
+
+- **`observedAttributes` discipline**: list only attributes whose change must re-render or trigger a side effect. Observing everything adds a callback to every mutation for no benefit.
+- **Reflection loops**: a setter that writes an attribute will re-enter `attributeChangedCallback`. Guard with an `oldVal !== newVal` check, as above.
+- **Style-only state**: for internal state that exists only to drive styling (loading, active, expanded), prefer **custom states** over reflecting a synthetic attribute — see [Custom states](#custom-states) below. Reflect to an attribute only when consumers must be able to set the state from markup.
+
+## Custom states
+
+Custom states are boolean flags an element exposes *about itself* for CSS to target, set through `ElementInternals` and matched with the `:state()` pseudo-class. Use them for internal, runtime UI state — `busy`, `expanded`, `invalid` — instead of reflecting a synthetic attribute: they can't collide with a consumer's attributes, never appear in the DOM, and are read-only from outside (a consumer can *style* `:state()` but can't forge it).
+
+```javascript
+class AsyncButton extends HTMLElement {
+ #internals;
+ #action = async () => {};
+
+ constructor() {
+ super();
+ this.#internals = this.attachInternals();
+ }
+
+ set action(fn) { this.#action = fn; } // host supplies the work to run
+
+ async run() {
+ if (this.#internals.states.has('busy')) return; // guard re-entry
+ this.#internals.states.add('busy');
+ this.#internals.states.delete('success');
+ try {
+ await this.#action();
+ this.#internals.states.add('success');
+ } catch {
+ this.#internals.states.add('error');
+ } finally {
+ this.#internals.states.delete('busy');
+ }
+ }
+}
+```
+
+`CustomStateSet` is a set, so independent states compose (`busy` plus `error`) without inventing a combined `data-status` enum.
+
+**Custom state is runtime-only.** It is not serialized to the DOM, so it does not survive a reload, the element being re-created, or server rendering. If the state must be set declaratively in markup or persist across loads, that is a job for an **attribute** (see [Where the value lives](#where-the-value-lives)) — restore it in `connectedCallback` from your source of truth. Rule of thumb: custom state for what the component derives and owns at runtime and only needs to *style*; an attribute for what must be set from markup or serialized.
+
+For styling these states — both inside the component and from a consumer's stylesheet — see `styling-web-components` (via `npx -y modern-web-guidance@latest retrieve "styling-web-components"`).
+
+## Naming conventions
+
+- True-private state: native `#` fields (`#count`) for hard encapsulation; a `_` prefix only when subclasses must still reach it. Note `#` fields are not inherited — a subclass cannot see a base class's private fields.
+- Symbol-keyed properties are a middle ground: hidden from ordinary enumeration, but reachable by any code holding the symbol (export it, or expose it as a `static` field on the class). Because each symbol is unique, two symbols sharing a description never collide — handy when a subclass or sibling needs controlled access that `#` fields can't provide.
+- Do **not** shadow global attributes (`style`, `class`, `id`, `slot`, `part`, `title`, `lang`, `dir`) with your own properties; doing so breaks their built-in behavior. Note `disabled` is only global on form controls; on other elements you must implement its effect yourself.
+
+When naming a new API surface, follow the platform's own conventions — see the [W3C naming principles](https://www.w3.org/TR/design-principles/#naming-is-hard).
diff --git a/skills/modern-web-guidance/guides/html/form-associated-custom-elements.md b/skills/modern-web-guidance/guides/html/form-associated-custom-elements.md
new file mode 100644
index 0000000..48f1006
--- /dev/null
+++ b/skills/modern-web-guidance/guides/html/form-associated-custom-elements.md
@@ -0,0 +1,61 @@
+# Form-Associated Custom Elements
+
+Do not fall back to a hidden `<input>` to surface a custom control's value to a form. Use **Form-Associated Custom Elements** (FACE): with `formAssociated` and `ElementInternals`, the element submits its own value, participates in validation, and reflects form state natively.
+
+```javascript
+class RatingInput extends HTMLElement {
+ // MANDATORY: opt in. Without this, attachInternals() form APIs are unavailable.
+ static formAssociated = true;
+
+ #internals;
+ #value = '';
+
+ constructor() {
+ super();
+ this.#internals = this.attachInternals();
+ this.attachShadow({ mode: 'open' });
+ }
+
+ get value() { return this.#value; }
+ set value(v) {
+ this.#value = v;
+ // Push the value into the owning <form> for submission.
+ this.#internals.setFormValue(v);
+ this.#validate();
+ }
+
+ #validate() {
+ if (this.hasAttribute('required') && !this.#value) {
+ // Mark invalid and supply the native validation message + anchor.
+ this.#internals.setValidity(
+ { valueMissing: true },
+ 'Please choose a rating.',
+ this.shadowRoot.querySelector('[tabindex]'),
+ );
+ } else {
+ this.#internals.setValidity({}); // clear
+ }
+ }
+
+ // Optional FACE lifecycle hooks:
+ formResetCallback() { this.value = ''; }
+ formDisabledCallback(disabled) { this.toggleAttribute('disabled', disabled); }
+ formStateRestoreCallback(state) { this.value = state; }
+}
+customElements.define('rating-input', RatingInput);
+```
+
+Key points:
+
+- `static formAssociated = true` is **MANDATORY**; it unlocks the form-related `ElementInternals` methods and the `formXxxCallback` lifecycle.
+- `setFormValue(value)` is what submits, with no hidden input required. Pass a `FormData` for multi-value controls.
+- `setValidity(flags, message, anchor)` integrates with native constraint validation: the form won't submit while invalid, `:invalid`/`:valid` apply, and the anchor element receives focus on report. Call `setValidity({})` to clear. The interaction-aware `:user-valid`/`:user-invalid` pseudo-classes are *not* consistently wired up for form-associated elements across browsers — verify support before relying on them rather than assuming they track user interaction the way they do for native controls.
+- Implement `formResetCallback`, `formDisabledCallback`, and `formStateRestoreCallback` so the element behaves like a native control on reset, `fieldset[disabled]`, and back/forward autofill restore.
+- Follow platform conventions for dispatched events and prefer the built-in `input` and `change` events over custom ones. `input` fires when the value changes as a direct result of user action (typing, dragging a slider); `change` fires once per stream of changes, when the user commits (releasing the slider, blurring the field). Construct them with `InputEvent` and `Event` respectively.
+
+## Fallback strategies
+
+Baseline status for Form-associated custom elements: Widely available. It's been Baseline since 2023-03-27.
+Supported by: Chrome 77 (Sep 2019), Edge 79 (Jan 2020), Firefox 98 (Mar 2022), and Safari 16.4 (Mar 2023).
+
+Feature-detect with `static formAssociated` support before relying on it: `'attachInternals' in HTMLElement.prototype && 'setFormValue' in ElementInternals.prototype`. Where it is unavailable, fall back to a visually-hidden native `<input>` synced to the control's value so the form still submits — the one case where the hidden-input pattern is justified.
diff --git a/skills/modern-web-guidance/guides/html/prerendering-custom-elements.md b/skills/modern-web-guidance/guides/html/prerendering-custom-elements.md
new file mode 100644
index 0000000..8a91316
--- /dev/null
+++ b/skills/modern-web-guidance/guides/html/prerendering-custom-elements.md
@@ -0,0 +1,61 @@
+# Pre-rendering custom elements
+
+Pre-rendering means shipping a custom element's markup — including its shadow tree — from the server, so the component is styled and structured *before* any JavaScript runs. The main platform primitive for this is **Declarative Shadow DOM (DSD)**: the parser attaches the shadow root from HTML alone, and the element is later upgraded ("hydrated") by its class if one is registered. Use this pattern for server-side rendering, streaming, and avoiding a flash of unstyled content (FOUC).
+
+## Authoring a declarative shadow root
+
+Nest a `<template>` with the `shadowrootmode` attribute as the first child of the host. The parser attaches its content as a shadow root and removes the template; no script needed.
+
+```html
+<my-card>
+ <template shadowrootmode="open">
+ <style>
+ .card { border: 1px solid; border-radius: 8px; padding: 1rem; }
+ </style>
+ <div class="card">
+ <slot name="header"></slot>
+ <div class="body"><slot></slot></div>
+ </div>
+ </template>
+
+ <!-- Light DOM children are projected into the slots above. -->
+ <h2 slot="header">Server-rendered title</h2>
+ <p>Visible and styled before JS loads.</p>
+</my-card>
+```
+
+## Hydration timing
+
+When the matching class is registered, the browser upgrades the host. Because the shadow root **already exists**, the constructor must not blindly create a second one:
+
+```javascript
+class MyCard extends HTMLElement {
+ constructor() {
+ super();
+ // Reuse the server-rendered shadow root if present; only create one if absent.
+ if (!this.shadowRoot) {
+ this.attachShadow({ mode: 'open' });
+ this.shadowRoot.append(template.content.cloneNode(true));
+ }
+ // Otherwise hydrate in place: wire up listeners against existing markup,
+ // and do NOT re-render; that would discard the server's DOM and flash.
+ }
+}
+```
+
+Set `shadowrootmode="open"` (not `closed`) for almost all cases, so scripts and tools can reach `this.shadowRoot` to hydrate. To serialize an existing shadow root back to HTML on the server or in tests, use `getHTML({ serializableShadowRoots: true })` and attach the root with `serializable: true`.
+
+## Avoiding FOUC
+
+DSD renders correctly on first paint only if styles ship inside the declarative template. To preserve that:
+
+- Put component CSS **inside** the `<template shadowrootmode>` (a `<style>` tag or a `<link>`), not in a separate script-loaded sheet.
+- Pair with `my-card:not(:defined) { … }` only for styles that must wait for JS — typically page-level guard rules like a fade-out on client-rendered instances that miss the SSR pass. These live in the light-DOM (page) stylesheet, since the shadow root doesn't yet exist there and `:host` selectors don't apply from outside. Structural styles inside the DSD template need no such guard.
+- Do not re-render the shadow tree on hydration. Treat the server markup as authoritative and attach behavior to it.
+
+## Fallback strategies
+
+Baseline status for Declarative shadow DOM: Widely available. It's been Baseline since 2024-02-20.
+Supported by: Chrome 111 (Mar 2023), Edge 111 (Mar 2023), Firefox 123 (Feb 2024), and Safari 16.4 (Mar 2023).
+
+In engines that don't parse `shadowrootmode`, the template is inert and its content is not attached as a shadow root. Detect this (`HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode')`) and, if absent, attach the shadow root imperatively from the same markup during upgrade so the component still renders.
diff --git a/skills/modern-web-guidance/guides/html/shadow-dom.md b/skills/modern-web-guidance/guides/html/shadow-dom.md
new file mode 100644
index 0000000..cfc9c07
--- /dev/null
+++ b/skills/modern-web-guidance/guides/html/shadow-dom.md
@@ -0,0 +1,79 @@
+# Shadow DOM, Templates & Slots
+
+A shadow root is an encapsulated DOM subtree attached to a host element: styles inside it do not leak out, and page styles do not leak in (except inherited properties). Templates construct the tree efficiently; slots project Light DOM content into it.
+
+## Attaching a shadow root
+
+```javascript
+this.attachShadow({ mode: 'open', delegatesFocus: true });
+```
+
+`delegatesFocus: true` makes focusing the host move focus to the first focusable element inside the shadow tree, and routes `:focus` styling to the host. Set it whenever the component wraps focusable controls; it is required for label-click and keyboard accessibility. (Use `mode: 'open'` in almost all cases — see the cross-cutting rules in `web-components` (via `npx -y modern-web-guidance@latest retrieve "web-components"`).)
+
+## Templates: construct the tree efficiently
+
+Define a `<template>` **once** (module scope or a static field) and clone it per instance. Cloning a parsed fragment is far faster than re-parsing an `innerHTML` string on every construction.
+
+```javascript
+const template = document.createElement('template');
+template.innerHTML = `
+ <div class="card">
+ <slot name="header"></slot>
+ <div class="body"><slot></slot></div>
+ <slot name="footer"></slot>
+ </div>
+`;
+
+class MyCard extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+ // MANDATORY: deep-clone the template content so each instance gets its own nodes.
+ this.shadowRoot.append(template.content.cloneNode(true));
+ }
+}
+customElements.define('my-card', MyCard);
+```
+
+Keep templates lean. Deeply nested "div soup" and many levels of nested shadow roots both add measurable style-resolution and layout cost, a major performance hit at scale. Prefer a flat structure and semantic elements.
+
+## Slots: the parts that surprise people
+
+Default vs. named slots work as documented; these are the behaviors that bite:
+
+- **Whitespace counts.** Text nodes between elements (including pure whitespace) are assigned to the default slot, so a default slot is rarely truly "empty."
+- **DOM order is preserved, not slot order.** Projected nodes keep their original Light DOM order for `:first-child`/`:last-child` purposes, regardless of which slot they fill. A `::slotted(*:first-child)` rule targets the first *DOM* child, not the first child of that slot, so it often will not match what you expect.
+- **`slotchange` is the upgrade-timing signal.** It fires when assigned nodes change (including initial assignment) and is the reliable way to know Light DOM children have arrived after an upgrade, when they may not have existed during `connectedCallback`.
+
+```javascript
+this.shadowRoot.querySelector('slot[name="header"]')
+ .addEventListener('slotchange', (e) => {
+ const nodes = e.target.assignedElements();
+ this.toggleAttribute('has-header', nodes.length > 0);
+ });
+```
+
+## Loading stylesheets into a shadow root
+
+| Method | Pros | Cons |
+| :--- | :--- | :--- |
+| `<style>` in the template | Simple, fully encapsulated, works without JS. | Duplicated per instance; bloats the DOM at scale. |
+| `<link rel="stylesheet">` | Cacheable external file. | Extra request; risks a flash of unstyled content. |
+| `adoptedStyleSheets` | One shared `CSSStyleSheet` across all instances; fastest at scale. | Requires JS; constructed sheets don't support `@import`. |
+
+For many instances of one component, prefer a shared constructed stylesheet:
+
+```javascript
+const sheet = new CSSStyleSheet();
+sheet.replaceSync(`:host { display: block; }`);
+
+class MyCard extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+ // The same sheet object is reused by every instance; no per-instance parse.
+ this.shadowRoot.adoptedStyleSheets = [sheet];
+ }
+}
+```
+
diff --git a/skills/modern-web-guidance/guides/html/styling-web-components.md b/skills/modern-web-guidance/guides/html/styling-web-components.md
new file mode 100644
index 0000000..fbc48b5
--- /dev/null
+++ b/skills/modern-web-guidance/guides/html/styling-web-components.md
@@ -0,0 +1,127 @@
+# Styling Web Components
+
+Shadow DOM is a style boundary: page rules don't reach in and component rules don't leak out, except **inherited** properties (including custom properties). Cross it deliberately through the channels below.
+
+## `:host`, `:host()`, `:host-context()`
+
+```css
+/* The component's own host element, styled from inside its shadow tree. */
+:host { display: block; }
+
+/* Only when the host matches a selector (e.g. a reflected state attribute). */
+:host([disabled]) { opacity: 0.5; pointer-events: none; }
+
+/* Based on an ancestor in the Light DOM; useful for theming. */
+:host-context([theme="dark"]) { background: #111; color: #eee; }
+```
+
+**Avoid `:host-context()`.** It reaches *outside* the boundary to test ancestors, but Firefox and Safari have declined to ship it and the CSSWG is leaning toward not developing it further — treat it as a Chromium-only dead end, not a forward-looking option. Theme through an inherited CSS custom property instead (below): the consumer sets the property on an ancestor and the component reads it across the boundary, which works everywhere and keeps both sides decoupled.
+
+## Inherited properties and custom properties cross the boundary
+
+Inherited CSS properties (`color`, `font-family`, `line-height`, and CSS custom properties) **do** pass through the shadow boundary. This makes custom properties the primary theming API: expose them with sensible fallbacks.
+
+```css
+:host {
+ /* Consumers override --card-bg from outside; the fallback keeps it usable. */
+ background: var(--card-bg, white);
+ color: var(--card-fg, black);
+}
+```
+
+A custom property *defined* on `:host` can only be overridden by rules targeting the host element specifically. To let it inherit and be overridable from anywhere up the tree, leave the public property unset on `:host` and rely on the fallback in each `var()`; do not seed the public property on `:host`.
+
+To keep the fallback declared once rather than repeated at every `var()`, define a private "shadow" property on `:host` that reads the public one, and reference the private property internally:
+
+```css
+:host {
+ --_card-bg: var(--card-bg, white);
+ --_card-fg: var(--card-fg, black);
+}
+.card { background: var(--_card-bg); color: var(--_card-fg); }
+```
+
+Consumers still override `--card-bg` from outside; the leading underscore signals the alias is internal, and the fallback lives in exactly one place.
+
+## `::slotted()`: styling projected Light DOM
+
+`::slotted(selector)` targets the **top-level** nodes assigned to a slot. It cannot reach their descendants, and it loses to any Light DOM rule (the consumer owns their own content), so use it for light touch-ups, not control. `::slotted(...) !important` can beat consumer rules, but doing so overrides styling the consumer is entitled to own — reserve it for structural fixes, not aesthetic overrides.
+
+```css
+/* Matches a slotted <p>, but NOT a <p> nested inside a slotted <div>. */
+::slotted(p) { margin: 0; }
+```
+
+## `::part()` and `exportparts`: expose internals for theming
+
+Mark an internal element with `part="name"` to let consumers style it with any property, without learning your internal structure.
+
+```html
+<!-- inside the shadow template -->
+<button part="submit">Submit</button>
+```
+
+```css
+/* consumer stylesheet */
+my-card::part(submit) { background: navy; color: white; }
+```
+
+Expose a few **high-level** parts (button, input, label), not every `<div>`; broad part surfaces become a brittle API. To re-expose a nested component's parts upward through your own component, forward them with `exportparts`:
+
+```html
+<inner-widget exportparts="submit: card-submit"></inner-widget>
+```
+
+Choose between the two channels deliberately: **custom properties** for a constrained, design-system-safe set of values; **parts** for unrestricted styling of a specific element.
+
+## Forwarding styles to a wrapped native element
+
+When a custom element wraps a native control (`<my-button>` around a real `<button>`), three things routinely trip people up:
+
+- **Form controls don't inherit typography.** `color` and custom properties cross the boundary, but `<button>`, `<input>`, and `<select>` take `font` and friends from the UA stylesheet, which does *not* inherit. The wrapped control therefore renders in the platform font, not the page font, until you set `font: inherit` (and usually `color: inherit`) on it inside the shadow tree. This is the single most common miss.
+- **`:host` styles don't reach the inner element.** Setting `background`/`border`/`padding` on `:host` styles the host box, not the control inside it. Forward deliberately: expose the control as a `::part` for open-ended styling, or pipe a fixed set of values through custom properties — a `:host` rule does not cascade into the wrapped element.
+- **`display: contents` + `all: inherit` is a real tradeoff, not a shortcut.** Collapsing the host with `display: contents` and resetting the inner control with `all: inherit` is currently the only generic way to pass arbitrary styles through to a wrapped native element without consumers learning per-component parts or custom properties — and removing the host's own box is usually *the point* of the pattern (composition compensating for a missing built-in inheritance). Two real caveats: `all: inherit` wipes UA defaults, so scope to specific properties or use `revert` when you want defaults back; and the concrete blocker — `getBoundingClientRect()` and `getClientRects()` return zero for `display: contents` elements, so anchor positioning against the host is broken. Reach for `::part` or custom properties when those tradeoffs don't fit.
+
+## `:state()`: style the component's own states
+
+A custom element can expose internal boolean states through `ElementInternals` (see `custom-elements` (via `npx -y modern-web-guidance@latest retrieve "custom-elements"`) for setting them), and those states become a styling channel across the boundary — like `::part` and custom properties, but for *state* rather than structure or values. Match them inside the shadow tree with `:host(:state(name))`, and from a consumer's stylesheet with `tag-name:state(name)`:
+
+```css
+/* Inside the component's shadow tree. */
+:host(:state(busy)) button { opacity: 0.6; pointer-events: none; }
+
+/* From the consumer's stylesheet — a read-only public hook. */
+favorite-button:state(favorited) { filter: drop-shadow(0 0 4px crimson); }
+```
+
+Unlike a reflected attribute, a custom state is **read-only to the outside**: consumers can style it but cannot set or forge it, so the component stays the sole writer. Prefer it over a `data-*` attribute whenever the state is owned by the component and only needs to be styled.
+
+## `@layer` and container queries inside components
+
+- **Cascade layers** (`@layer`) work inside a shadow root and are scoped to it; a layer name in the shadow tree is independent of a same-named layer in the page. Use them to order your own component styles (e.g. `@layer base, theme;`) so consumer overrides via custom properties and `::part` still win predictably.
+- **Container queries** are the right tool for responsive components: a component should respond to the space it's given, not the viewport. Declare the host or a wrapper as a container and query it, so the same component adapts in a sidebar or a full-width region.
+
+```css
+:host { container-type: inline-size; }
+
+@container (min-width: 30rem) {
+ .card { grid-template-columns: 1fr 2fr; }
+}
+```
+
+## Fallback strategies
+
+Baseline status for Shadow parts: Widely available. It's been Baseline since 2020-07-28.
+Supported by: Chrome 73 (Mar 2019), Edge 79 (Jan 2020), Firefox 72 (Jan 2020), Safari 13.1 (Mar 2020), and Safari iOS 13.4 (Mar 2020).
+
+Baseline status for Cascade layers: Widely available. It's been Baseline since 2022-03-14.
+Supported by: Chrome 99 (Mar 2022), Edge 99 (Mar 2022), Firefox 97 (Feb 2022), and Safari 15.4 (Mar 2022).
+
+Baseline status for Container queries: Widely available. It's been Baseline since 2023-02-14.
+Supported by: Chrome 105 (Sep 2022), Edge 105 (Sep 2022), Firefox 110 (Feb 2023), and Safari 16 (Sep 2022).
+
+:host-context() has limited availability.
+Supported by: Chrome 54 (Oct 2016) and Edge 79 (Jan 2020).
+Unsupported in: Firefox and Safari.
+
+`::part`, cascade layers, and container queries are broadly available; theme primarily through inherited custom properties, which work even where these don't. As noted above, do **not** rely on `:host-context()` — it is effectively Chromium-only and not a forward-looking option.
diff --git a/skills/modern-web-guidance/guides/html/web-components.md b/skills/modern-web-guidance/guides/html/web-components.md
new file mode 100644
index 0000000..3931909
--- /dev/null
+++ b/skills/modern-web-guidance/guides/html/web-components.md
@@ -0,0 +1,50 @@
+# Web Components Orientation
+
+Web Components are Custom Elements, Shadow DOM, and HTML Templates: the platform primitives for reusable, framework-agnostic components whose markup and styles are encapsulated from the document. Use them for design systems, embeddable widgets, and self-contained UI.
+
+The rules below are cross-cutting. Retrieve the specific guide for the task at hand; each restates the context it needs and documents the APIs and pitfalls unique to it.
+
+## Decide whether you even need a custom element
+
+Reach for a custom element only when you need encapsulated behavior, lifecycle, or a reusable JS-backed API on a tag. Do **not** build one when:
+
+- A plain HTML element with CSS would do. A styled `<button>` or `<details>` is more accessible and cheaper than a re-implementation.
+- The thing is purely presentational with no behavior. A class on a native element is more performant, and scopable with `@layer` or `@scope`.
+- You only need style scoping on the server with no interactivity; a scoped stylesheet or Declarative Shadow DOM (without an upgrade) may be enough.
+
+Rebuilding native semantics (a custom `<my-button>` that re-creates focus, activation, and ARIA) is the most common misuse: you inherit the platform's accessibility for free only if you reuse the native element. When a `<my-button>`-style wrapper *is* warranted — usually for shared styling hooks, extra markup, or behavior a native element can't express — wrap the real `<button>` rather than re-implementing it (see `styling-web-components` (via `npx -y modern-web-guidance@latest retrieve "styling-web-components"`) for forwarding styles to an internal native element).
+
+The test is whether you need **encapsulated state, a scriptable API, or behavior the native element can't express** — not merely a different look. A like/favorite toggle qualifies: it carries latched domain state, exposes that state as a styling hook for the surrounding page, and dispatches its own `change` event — none of which a styled `<button>` gives you. A button that only changes color when pressed does not: reach for `<button>` + CSS. When you do build it, model its state with a custom state or attribute as appropriate (see `custom-elements` (via `npx -y modern-web-guidance@latest retrieve "custom-elements"`)).
+
+## Match the tool to the codebase
+
+Whether something *should* be a custom element depends on what the project already uses. Agents tend to over-abstract and reach for a new element too eagerly — when in doubt, the lighter option (native element, CSS, a server template) is usually right, and you can promote to a custom element later if reuse or behavior actually demands it. Heuristics, in rough priority:
+
+- **The codebase already has a component model (React, Vue, Svelte, …).** Default to that framework's component for in-app UI. Reach for a custom element only when the thing must escape or outlive the framework: a design-system primitive shared across apps or frameworks, a widget dropped into markup the framework doesn't control, or output that must work as plain HTML (email, CMS, SSR fragments). Don't stand up a parallel component system for ordinary in-app views.
+- **No tooling, mostly static markup.** Prefer plain HTML + CSS, or a server template/partial. A custom element earns its keep only where you genuinely need behavior, lifecycle, or a JS-backed API on the tag — not merely to share markup, which a server include or `<template>` does without shipping any JS.
+- **Static site generator with islands of interactivity.** Render the markup statically; reserve the custom element for the interactive part. For "lots of markup, a little interactivity," keep the markup in Light DOM (or Declarative Shadow DOM) and let a small custom element progressively enhance it, rather than re-rendering everything from JS.
+- **You could push a built-in element further instead.** Taking a native element as far as it goes (CSS, a few listeners, the occasional pseudo-element) is usually preferable to a custom element, because you keep the platform's accessibility and behavior for free. Cross over to a custom element when the workarounds stop being maintainable — when you'd be fighting the element's built-in behavior, or the authoring experience becomes worse than a clean component API would be. Needing a little JS on a built-in element is not, by itself, a reason to replace it.
+
+## Cross-cutting rules
+
+These hold across every guide below:
+
+- **MANDATORY**: the tag name must be kebab-case with at least one hyphen (e.g. `my-element`). This is what distinguishes custom elements from current and future built-ins.
+- **MANDATORY**: call `super()` first in the constructor, before touching `this`; calling it after any statement that reads or writes `this` throws.
+- **MANDATORY**: use semantic elements (`<button>`, `<nav>`, `<ul>`) inside shadow templates. Most accessibility failures in shadow trees come from non-semantic markup; a slot does not change the role of what it projects.
+- **MANDATORY**: ARIA `id` references (`aria-labelledby`, `aria-describedby`, `aria-controls`) cannot cross a shadow boundary; the referencing element and the `id` it points to must live in the same tree.
+- Prefer `attachShadow({ mode: 'open' })` so dev tools, page scripts, and server hydration can reach `element.shadowRoot`. Use `'closed'` only when you must hide internal structure from page scripts.
+- Avoid *customized built-in elements* (`extends HTMLButtonElement` with `is="…"`); Safari has permanently declined to ship them.
+
+## Use-case guide matrix
+
+Identify the task and retrieve its guide:
+
+| If you need to… | Retrieve |
+| :--- | :--- |
+| Define a new semantic tag with behavior and lifecycle | `custom-elements` (via `npx -y modern-web-guidance@latest retrieve "custom-elements"`) |
+| Scope styles and markup to a component, and project consumer content into it | `shadow-dom` (via `npx -y modern-web-guidance@latest retrieve "shadow-dom"`) |
+| Render a component's shadow tree on the server (SSR) without a flash of unstyled content | `prerendering-custom-elements` (via `npx -y modern-web-guidance@latest retrieve "prerendering-custom-elements"`) |
+| Style across the shadow boundary (theming, `::part`, custom properties) | `styling-web-components` (via `npx -y modern-web-guidance@latest retrieve "styling-web-components"`) |
+| Submit a custom control's value to a surrounding `<form>` | `form-associated-custom-elements` (via `npx -y modern-web-guidance@latest retrieve "form-associated-custom-elements"`) |
+| Make a custom element accessible (roles, focus, ARIA across shadow roots) | `accessible-web-components` (via `npx -y modern-web-guidance@latest retrieve "accessible-web-components"`) |
diff --git a/skills/modern-web-guidance/guides/performance/avoid-redundant-large-asset-downloads.md b/skills/modern-web-guidance/guides/performance/avoid-redundant-large-asset-downloads.md
new file mode 100644
index 0000000..2a1c2d7
--- /dev/null
+++ b/skills/modern-web-guidance/guides/performance/avoid-redundant-large-asset-downloads.md
@@ -0,0 +1,135 @@
+# Avoid redundant large asset downloads
+
+Large shared assets such as AI model weights, Wasm modules, game engine cores, or fully-bundled JavaScript libraries are often identical across many unrelated sites. Without a shared cache, each origin downloads and stores its own copy, even when the visitor's browser already holds the exact same bytes from a different site. The Cross-Origin Storage (COS) API, exposed via `navigator.crossOriginStorage`, lets origins store and retrieve such files by content hash instead of by URL, so one on-device copy can serve every site that needs it.
+
+## How to implement
+
+1. **Compute the asset's hash when you build or publish your site.** Hash the exact bytes of the large asset you serve (for example, a model file, a Wasm binary, or a third-party library such as three.js) with `crypto.subtle.digest()`, and include the result as a lowercase hex string in your built code. The hash is what identifies the file in COS, and computing it on page load would require downloading the file first.
+2. **Feature-detect before use, then fall back immediately if it's absent.** Check `navigator.crossOriginStorage?.requestFileHandle` once up front. If COS isn't implemented in this browser, skip straight to a normal network fetch.
+3. **Once support is confirmed, still call every method defensively.** Wrap each COS call in `try`/`catch`, as described in the "Handle rejections" section.
+4. **Check COS before fetching from the network.** Call `requestFileHandle(hash)` first. If it resolves, read the file with `handle.getFile()` and skip the network entirely.
+5. **Fall back to the network on any rejection.** A `NotFoundError` is a cache miss that never proves the file is absent.
+6. **Store what you fetch.** After a network fetch, request a writable handle with `{ create: true }`, write the complete file, and close the stream, so the next origin that asks for the same hash can skip the download.
+7. **Choose the `origins` scope deliberately.** Pick it from the resource's real distribution, as described in the "Sharing scope" section.
+
+## Example code
+
+At build time, compute the hash once and inline it into your code:
+
+```javascript
+// build-hash.js (Node.js)
+import { readFile } from 'node:fs/promises';
+
+const bytes = await readFile('dist/assets/shared-library.js');
+const digest = await crypto.subtle.digest('SHA-256', bytes);
+const hex = Array.from(new Uint8Array(digest), (byte) =>
+ byte.toString(16).padStart(2, '0'),
+).join('');
+```
+
+At runtime, load every large shared asset through one reusable helper that looks the file up by that hash:
+
+```javascript
+/**
+ * Loads a large shared asset from COS when available, otherwise from the
+ * network, and stores network responses in COS for the next origin.
+ * @param {string} url The asset's real, working network URL.
+ * @param {{algorithm: string, value: string}} hash The build-time hash.
+ * @param {'*' | string[]} [origins] Sharing scope; omit for same-site only.
+ * @returns {Promise<Blob>}
+ */
+async function loadAsset(url, hash, origins) {
+ // Feature-detect once, up front, and fall back to the network
+ // immediately if COS isn't implemented in this browser.
+ const supportsCOS = !!navigator.crossOriginStorage?.requestFileHandle;
+ // Set when Permissions Policy blocks COS in this context, since every
+ // further COS call here rejects the same way.
+ let blocked = false;
+
+ if (supportsCOS) {
+ try {
+ // Check COS first. If another origin already stored this exact
+ // hash, this resolves with no network request at all.
+ const handle = await navigator.crossOriginStorage.requestFileHandle(hash);
+ return await handle.getFile();
+ } catch (err) {
+ // A NotFoundError does not prove the file is absent from COS. Fall
+ // back to the network either way; never treat it as fatal.
+ blocked = err.name === 'NotAllowedError';
+ }
+ }
+
+ const response = await fetch(url);
+ const fileBlob = await response.blob();
+
+ if (supportsCOS && !blocked) {
+ // Write back to the cache.
+ try {
+ const handle = await navigator.crossOriginStorage.requestFileHandle(hash, {
+ create: true,
+ // Only pass `origins` when the caller chose a scope, so omitting it
+ // keeps the same-site-only default.
+ ...(origins && { origins }),
+ });
+ const writable = await handle.createWritable();
+ await writable.write(fileBlob);
+ await writable.close();
+ // Never call getFile() on this handle before write()/close() has
+ // resolved; use the blob already in hand instead.
+ } catch {
+ // Storing is a nice-to-have for future visitors, not required for
+ // this page to work.
+ }
+ }
+
+ return fileBlob;
+}
+
+const library = await loadAsset(
+ '/assets/shared-library.js',
+ {
+ algorithm: 'SHA-256',
+ // Example-only hash value; use the hex string from your build step.
+ value: '8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4',
+ },
+ // MANDATORY: origins: '*' is only appropriate for genuinely popular,
+ // non-proprietary resources.
+ '*',
+);
+```
+
+## Handle rejections
+
+A browser that implements COS can still reject any call, so a passed feature-detection check never guarantees success. Fall back to the network on every rejection, and read the error name to decide what else to do:
+
+- **`NotFoundError` from `requestFileHandle(hash)`:** an ordinary cache miss that never proves the file is absent. The file may not exist, your origin may be outside its sharing scope, a globally shared file may not be on the browser's list of popular hashes yet, or the browser may deliberately report a stored file as missing to protect privacy (GREASE'ing). Store the file after the network fetch as usual.
+- **`NotAllowedError` from `requestFileHandle()`:** Permissions Policy blocks COS in this context, for example in a cross-origin iframe whose embedder didn't grant the `cross-origin-storage` feature (its default allowlist is `self`). Every further COS call in this context rejects the same way, so skip the write-back too.
+- **`NotAllowedError` from `getFile()`:** you called it on a handle obtained with `{ create: true }` before your own write completed, which applies even when another origin already stored the file. Use the blob you already have.
+
+## Sharing scope
+
+Every Cross-Origin Storage (COS) surface takes a sharing scope that controls which origins can later retrieve the stored file. Pick the scope that matches the resource's real distribution:
+
+- **Same-site only (default):** for resources that only your own site uses.
+- **Explicit origin list:** for a small, trusted set of origins, for example proprietary assets shared between your own properties.
+- **Global (`*`):** **MANDATORY:** only for genuinely popular, non-proprietary resources, such as open-weight AI models or widely used open-source libraries.
+
+| Surface | Same-site only | Origin list | Global |
+|---|---|---|---|
+| `requestFileHandle()` `origins` option | Omit `origins` | Array of origin strings | `'*'` |
+| HTML `crossoriginstorage` attribute | Valueless attribute | Space-separated origins | `"*"` |
+| `crossOriginStorage` import attribute | Empty string (`''`) | Space-separated origins | `'*'` |
+| CSS `cross-origin-storage()` modifier | No arguments | Comma-separated origin strings | `*` |
+
+**MANDATORY:** An origin list only takes effect for origins that a `Cross-Origin-Storage-Allow-Origin` response header also names, for example `Cross-Origin-Storage-Allow-Origin: https://a.example, https://b.example`. The header comes from whoever supplies the bytes: the response of the page that calls `requestFileHandle()`, or the response of the fetched resource itself (the script, stylesheet, module, or font) for the HTML, import attribute, and CSS forms. Origins the header doesn't name are dropped, and if none remain, the file is stored with the same-site default. The same-site default and `*` need no header.
+
+## Best practices
+
+- **DO** write the complete file with `createWritable()` / `write()` / `close()` (or `pipeTo()`) every time you store, even if the file might already exist in COS.
+- **DO** use `Promise.all()` over individual `requestFileHandle()` calls to look up several distinct hashes concurrently, since each call takes exactly one hash.
+
+## Fallback strategy
+
+Cross-Origin Storage (COS) is being implemented in Chromium and is not yet natively supported by any major browser. Until it ships, the Cross-Origin Storage browser extension adds it to Chrome and other Chromium-based browsers (from the Chrome Web Store), Firefox on desktop and Android (from Firefox Add-ons), and Safari on macOS, iOS, and iPadOS (from the App Store). The extension supports the literal syntax of the `navigator.crossOriginStorage` API, the HTML `crossoriginstorage` attribute, and the CSS `cross-origin-storage()` modifier. It does not support the literal `crossOriginStorage` import attribute, since import attribute syntax can't be polyfilled.
+
+The COS API is a progressive enhancement over a normal network fetch. Guard every access to `navigator.crossOriginStorage` with a single up-front feature-detection check, and always keep a working network-fetch path as the fallback for browsers without COS support.
diff --git a/skills/modern-web-guidance/guides/performance/load-shared-resources-declaratively.md b/skills/modern-web-guidance/guides/performance/load-shared-resources-declaratively.md
new file mode 100644
index 0000000..ec79d73
--- /dev/null
+++ b/skills/modern-web-guidance/guides/performance/load-shared-resources-declaratively.md
@@ -0,0 +1,86 @@
+# Load shared resources declaratively
+
+Popular scripts, stylesheets, and JavaScript modules, such as UI frameworks or widget libraries served from a CDN, are byte-for-byte identical across many unrelated sites, yet every site's visitors download and cache their own copy. Cross-Origin Storage (COS) lets the browser keep one on-device copy of such a file, identified by its content hash, and serve it to every site that references the same bytes. Resources that already carry an `integrity` hash opt in through markup or import syntax alone: the `crossoriginstorage` attribute on `<link>` and `<script>` elements, or the `crossOriginStorage` import attribute on static and dynamic module imports. The browser handles the lookup, the network fallback, and storing the file, so no custom caching code is needed.
+
+## How to implement
+
+1. **Start from `integrity`.** Both declarative forms require an existing, valid `integrity` hash on the element or import, since that hash is what identifies the file in COS.
+2. **Add the COS attribute alongside it.** For HTML, add `crossoriginstorage` to a `<link>` or `<script>` element. For module imports, add `crossOriginStorage` inside the same `with { ... }` block as `integrity`.
+3. **Choose the sharing scope.** Pick it from the resource's real distribution, as described in the "Sharing scope" section.
+4. **For module imports, use dynamic `import()` inside `try`/`catch`.** A static `import` with an unsupported `crossOriginStorage` key fails the whole module at parse time, and a dynamic `import()` with one rejects before fetching anything. Catch the rejection and import the same URL without the attribute.
+
+## Example code
+
+```html
+<link
+ rel="stylesheet"
+ href="/assets/shared-widget.css"
+ integrity="sha256-example-only-hash"
+ crossorigin="anonymous"
+ crossoriginstorage="*"
+/>
+<script
+ src="/assets/shared-widget.js"
+ integrity="sha256-example-only-hash"
+ crossorigin="anonymous"
+ crossoriginstorage="*"
+ defer
+></script>
+```
+
+```javascript
+// MANDATORY: Use dynamic import() inside try/catch. A browser without
+// native support for the crossOriginStorage import attribute rejects it
+// before fetching anything, even when navigator.crossOriginStorage exists
+// (for example, added by an extension), so that object is no signal for
+// import attribute support.
+let mod;
+try {
+ mod = await import('/assets/shared-config.js', {
+ with: {
+ integrity: 'sha256-YKd8aU4ILF6re6EiM6lTEdAiGTFjVgVk9867zPSCAhs=',
+ crossOriginStorage: '*',
+ },
+ });
+} catch {
+ // Fall back to a plain import of the same URL.
+ mod = await import('/assets/shared-config.js');
+}
+```
+
+## Sharing scope
+
+Every Cross-Origin Storage (COS) surface takes a sharing scope that controls which origins can later retrieve the stored file. Pick the scope that matches the resource's real distribution:
+
+- **Same-site only (default):** for resources that only your own site uses.
+- **Explicit origin list:** for a small, trusted set of origins, for example proprietary assets shared between your own properties.
+- **Global (`*`):** **MANDATORY:** only for genuinely popular, non-proprietary resources, such as open-weight AI models or widely used open-source libraries.
+
+| Surface | Same-site only | Origin list | Global |
+|---|---|---|---|
+| `requestFileHandle()` `origins` option | Omit `origins` | Array of origin strings | `'*'` |
+| HTML `crossoriginstorage` attribute | Valueless attribute | Space-separated origins | `"*"` |
+| `crossOriginStorage` import attribute | Empty string (`''`) | Space-separated origins | `'*'` |
+| CSS `cross-origin-storage()` modifier | No arguments | Comma-separated origin strings | `*` |
+
+**MANDATORY:** An origin list only takes effect for origins that a `Cross-Origin-Storage-Allow-Origin` response header also names, for example `Cross-Origin-Storage-Allow-Origin: https://a.example, https://b.example`. The header comes from whoever supplies the bytes: the response of the page that calls `requestFileHandle()`, or the response of the fetched resource itself (the script, stylesheet, module, or font) for the HTML, import attribute, and CSS forms. Origins the header doesn't name are dropped, and if none remain, the file is stored with the same-site default. The same-site default and `*` need no header.
+
+## Best practices
+
+- **DO** keep the `src`/`href`/module specifier pointing at the resource's real, working network URL, since a COS lookup that doesn't succeed falls back to that URL exactly like ordinary `integrity`-checked fetches do.
+- **DO NOT** introduce a separate imperative fetch/cache step in JavaScript for a resource that already carries `integrity`; add the declarative attribute instead.
+- **DO NOT** confuse the HTML `crossoriginstorage` attribute with the unrelated `crossorigin` attribute. `crossorigin` sets the CORS request mode, and both can coexist on the same element.
+- **DO NOT** confuse the CSS `cross-origin-storage()` modifier with the unrelated CSS `cross-origin()` modifier, which also sets the CORS request mode.
+
+## Fallback strategy
+
+Cross-Origin Storage (COS) is being implemented in Chromium and is not yet natively supported by any major browser. Until it ships, the Cross-Origin Storage browser extension adds it to Chrome and other Chromium-based browsers (from the Chrome Web Store), Firefox on desktop and Android (from Firefox Add-ons), and Safari on macOS, iOS, and iPadOS (from the App Store). The extension supports the literal syntax of the `navigator.crossOriginStorage` API, the HTML `crossoriginstorage` attribute, and the CSS `cross-origin-storage()` modifier. It does not support the literal `crossOriginStorage` import attribute, since import attribute syntax can't be polyfilled.
+
+The HTML form degrades gracefully: a browser that doesn't recognize `crossoriginstorage` simply ignores the attribute, per ordinary HTML attribute-parsing rules, and the element still loads via its plain `href`/`src`. The static JavaScript import-attribute form does not degrade the same way, since an unrecognized `with` key is a hard failure; use dynamic `import()` inside `try`/`catch` as shown in the example.
+
+With the extension installed, `navigator.crossOriginStorage` exists, but the literal import attribute still fails: a static `import` fails to parse, and a dynamic `import()` rejects. For module imports, the extension provides two non-standard shims:
+
+- **`<script type="module-cos">`:** the extension reads the script as text, resolves every static or dynamic import that carries `crossOriginStorage` and has a literal string specifier, and runs the rewritten source as a regular module. Computed specifiers such as variables or template literals are not rewritten.
+- **`navigator.crossOriginStorage.__non_standard__import(specifier, options)`:** takes the same arguments as dynamic `import()`, including a computed specifier.
+
+**DO NOT** make either shim the only code path, since neither exists outside the extension.
diff --git a/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md b/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md
index e12edde..2dfd3bd 100644
--- a/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md
+++ b/skills/modern-web-guidance/guides/performance/out-of-order-html-streaming.md
@@ -70,7 +70,32 @@ Once a `<template>` replaces an insertion point, that insertion point no longer
```
### 2. Imperative JS Streaming
-You can now pipe fetch responses directly into the DOM without manual chunk handling.
+
+The browser provides a suite of 24 methods (6 actions, each with 4 variations) to update the DOM either statically (from a string) or via a stream.
+
+#### API Reference Matrix
+
+| Action | Static (Safe) | Streaming (Safe) | Static (Unsafe) | Streaming (Unsafe) |
+| :--- | :--- | :--- | :--- | :--- |
+| **Set** | `setHTML()` | `streamHTML()` | `setHTMLUnsafe()` | `streamHTMLUnsafe()` |
+| **Replace** | `replaceWithHTML()` | `streamReplaceWithHTML()` | `replaceWithHTMLUnsafe()` | `streamReplaceWithHTMLUnsafe()` |
+| **Before** | `beforeHTML()` | `streamBeforeHTML()` | `beforeHTMLUnsafe()` | `streamBeforeHTMLUnsafe()` |
+| **Prepend** | `prependHTML()` | `streamPrependHTML()` | `prependHTMLUnsafe()` | `streamPrependHTMLUnsafe()` |
+| **Append** | `appendHTML()` | `streamAppendHTML()` | `appendHTMLUnsafe()` | `streamAppendHTMLUnsafe()` |
+| **After** | `afterHTML()` | `streamAfterHTML()` | `afterHTMLUnsafe()` | `streamAfterHTMLUnsafe()` |
+
+#### Key Concepts
+
+* **Safe vs. Unsafe**:
+ * **Safe** methods (e.g., `setHTML()`) use a built-in sanitizer by default to strip potentially dangerous content like `<script>` tags. You can pass a custom `Sanitizer` object in the options to apply in addition to the default sanitizer.
+ * **Unsafe** methods (e.g., `setHTMLUnsafe()`) do not sanitize by default, but you can still pass a custom `Sanitizer`. To allow scripts to execute in the new content, you must explicitly pass `{ runScripts: true }` in the options. **IMPORTANT**: Only use unsafe methods with trusted content where safe methods would not work.
+* **Static vs. Streaming**:
+ * **Static** methods take a string (or `TrustedHTML`) and apply it immediately.
+ * **Streaming** methods return a `WritableStream`. This allows you to pipe content (e.g., from a `fetch` response) directly into the DOM, and the browser will render it incrementally as chunks arrive.
+
+#### Example: Streaming a Fetch Response
+
+You can pipe fetch responses directly into the DOM without manual chunk handling.
```javascript
const main = document.querySelector('main');
@@ -110,4 +135,10 @@ HTML setter methods is not natively supported by any major browser yet.
HTML streaming setters is not natively supported by any major browser yet.
+HTML processing instructions has limited availability.
+Supported by: Chrome 150 and Edge 150.
+Unsupported in: Firefox and Safari.
+
You can use polyfills like `template-for-polyfill` and `html-setters-polyfill` to emulate the API surface for non-supporting browsers.
+
+Browsers without `html-processing-instructions` support parse `<?marker>`, `<?start>`, and `<?end>` as comments. `template-for-polyfill` still recognizes these comments as markers, so keep the same processing instruction syntax for all browsers. Do not rewrite the markers as HTML comments or elements for non-supporting browsers.
diff --git a/skills/modern-web-guidance/guides/performance/share-web-fonts-across-origins.md b/skills/modern-web-guidance/guides/performance/share-web-fonts-across-origins.md
new file mode 100644
index 0000000..a2632b1
--- /dev/null
+++ b/skills/modern-web-guidance/guides/performance/share-web-fonts-across-origins.md
@@ -0,0 +1,51 @@
+# Share web fonts across origins
+
+Large icon fonts, emoji fonts, and fonts with extensive Unicode coverage are downloaded across an enormous number of unrelated sites every day, even though most visitors already hold an identical copy from some other site that referenced the same font. The Cross-Origin Storage (COS) API reaches CSS through a new `cross-origin-storage()` request-url-modifier, used alongside the existing `integrity()` modifier inside an `@font-face` `src: url(...)` descriptor. This is the recommended path for shared web fonts, since the imperative JavaScript API is not a natural fit for resources referenced purely from CSS.
+
+## How to implement
+
+1. **Get the font's integrity hash.** `cross-origin-storage()` always pairs with `integrity()`; the integrity hash is what identifies the font file in COS.
+2. **Add `cross-origin-storage()` to the `url()`.** Place it alongside `integrity()` inside the same `url()` function in the `src` descriptor.
+3. **Choose the sharing scope.** Pick it from the font's real distribution, as described in the "Sharing scope" section.
+4. **List the COS-enhanced source first, with a plain fallback after it.** `src` is a prioritized list; a browser uses the first alternative it can parse and load. Putting the plain `url()` first would mean it is always used and the COS-enhanced source is never tried.
+
+## Example code
+
+```css
+@font-face {
+ font-family: 'Shared Emoji Font';
+ src:
+ /* MANDATORY: List the COS-enhanced source first, then the plain fallback. */
+ url('/fonts/shared-emoji.woff2' integrity('sha256-example-only-hash') cross-origin-storage(*)) format('woff2'),
+ url('/fonts/shared-emoji.woff2') format('woff2');
+}
+```
+
+## Sharing scope
+
+Every Cross-Origin Storage (COS) surface takes a sharing scope that controls which origins can later retrieve the stored file. Pick the scope that matches the resource's real distribution:
+
+- **Same-site only (default):** for resources that only your own site uses.
+- **Explicit origin list:** for a small, trusted set of origins, for example proprietary assets shared between your own properties.
+- **Global (`*`):** **MANDATORY:** only for genuinely popular, non-proprietary resources, such as open-weight AI models or widely used open-source libraries.
+
+| Surface | Same-site only | Origin list | Global |
+|---|---|---|---|
+| `requestFileHandle()` `origins` option | Omit `origins` | Array of origin strings | `'*'` |
+| HTML `crossoriginstorage` attribute | Valueless attribute | Space-separated origins | `"*"` |
+| `crossOriginStorage` import attribute | Empty string (`''`) | Space-separated origins | `'*'` |
+| CSS `cross-origin-storage()` modifier | No arguments | Comma-separated origin strings | `*` |
+
+**MANDATORY:** An origin list only takes effect for origins that a `Cross-Origin-Storage-Allow-Origin` response header also names, for example `Cross-Origin-Storage-Allow-Origin: https://a.example, https://b.example`. The header comes from whoever supplies the bytes: the response of the page that calls `requestFileHandle()`, or the response of the fetched resource itself (the script, stylesheet, module, or font) for the HTML, import attribute, and CSS forms. Origins the header doesn't name are dropped, and if none remain, the file is stored with the same-site default. The same-site default and `*` need no header.
+
+## Best practices
+
+- **DO** keep the plain fallback `url()` pointing at the font's real, working network location, since a COS lookup that doesn't succeed falls back to fetching from that URL exactly like ordinary `integrity`-checked font loads do.
+- **DO NOT** confuse the HTML `crossoriginstorage` attribute with the unrelated `crossorigin` attribute. `crossorigin` sets the CORS request mode, and both can coexist on the same element.
+- **DO NOT** confuse the CSS `cross-origin-storage()` modifier with the unrelated CSS `cross-origin()` modifier, which also sets the CORS request mode.
+
+## Fallback strategy
+
+Cross-Origin Storage (COS) is being implemented in Chromium and is not yet natively supported by any major browser. Until it ships, the Cross-Origin Storage browser extension adds it to Chrome and other Chromium-based browsers (from the Chrome Web Store), Firefox on desktop and Android (from Firefox Add-ons), and Safari on macOS, iOS, and iPadOS (from the App Store). The extension supports the literal syntax of the `navigator.crossOriginStorage` API, the HTML `crossoriginstorage` attribute, and the CSS `cross-origin-storage()` modifier. It does not support the literal `crossOriginStorage` import attribute, since import attribute syntax can't be polyfilled.
+
+CSS's forgiving handling of comma-separated values means a browser that doesn't recognize `cross-origin-storage()`/`integrity()` drops only that one list item, not the whole declaration, so a plain fallback `url()` listed afterward still applies. No extra feature detection is required in CSS; the fallback source is always present as a later item in the same `src` list.
diff --git a/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md b/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md
new file mode 100644
index 0000000..df865ac
--- /dev/null
+++ b/skills/modern-web-guidance/guides/pwa/migrate-web-app-origin.md
@@ -0,0 +1,98 @@
+# Migrating the Origin of an Installed Web App
+
+Transferring an installed web app (PWA) to a new origin typically requires users to manually uninstall the old app and reinstall the new one. This process usually causes the loss of OS-level integration, such as taskbar shortcuts and notification permissions. Web App Origin Migration automates this transition by establishing a secure handover between the old and new origins.
+
+The migration is a two-step verification process: the new site claims the old site as its predecessor, and the old site authorizes the new site as its successor.
+
+### Important Constraints
+
+> [!WARNING]
+> **Data and Permissions are NOT migrated.**
+> This feature only migrates the **installation** (shortcuts, home screen icons). User data (LocalStorage, IndexedDB, Cookies) and browser permissions (Notifications, Geolocation) are tied to the origin and are NOT transferred. You must migrate data separately using cross-origin messaging or server-side synchronization.
+
+## Implementation steps
+
+### 1. Verification of "Same-Site" status
+
+MANDATORY: Both the new and old origins MUST be **"Same-Site"**. They must share the same **Registrable Domain (eTLD+1)**.
+
+* **Allowed**: Migrating from `app.example.com` to `new.example.com` (both share `example.com`).
+* **Allowed**: Migrating from `example.com/app1` to `example.com/app2`.
+* **Prohibited**: Migrating from `example.com` to `example.org` (different registrable domains).
+
+### 2. Configure the new application
+
+The new application must declare its predecessor. The new app must have an `id`.
+
+In the **new** site's `manifest.json`, add the `migrate_from` field:
+
+```json
+{
+ "name": "My New App",
+ "id": "/demo.html",
+ "start_url": "/demo.html",
+ "migrate_from": [
+ {
+ "id": "https://old-app.example.com/"
+ }
+ ]
+}
+```
+
+### 3. Authorize the migration on the old origin
+
+The old origin must explicitly authorize the migration to prevent origin hijacking. Create a configuration file served from the `.well-known` directory.
+
+File location: `https://old-app.example.com/.well-known/web-app-origin-association`
+
+```json
+{
+ "https://new-app.example.com": {
+ "allow_migration": true
+ }
+}
+```
+
+### 4. Proactively signal the migration (Optional)
+
+To trigger the migration immediately for existing users without waiting for them to visit the new site, update the **old** site's manifest with a `migrate_to` hint.
+
+```json
+{
+ "migrate_to": [
+ {
+ "id": "https://new-app.example.com/",
+ "install_url": "https://new-app.example.com/demo.html"
+ }
+ ]
+}
+```
+
+### 5. Require users to migrate (Optional)
+
+By default, a migration is suggested to users. To make the transition mandatory, set the `behavior` to `force` in the **new** app's manifest.
+
+```json
+{
+ "migrate_from": [
+ {
+ "id": "https://old-app.example.com/",
+ "behavior": "force"
+ }
+ ]
+}
+```
+
+**Note**: `behavior: "force"` does not silently delete the old app. The browser will present the user with a dialog requiring them to either **Update** to the new version or **Remove** the app entirely.
+
+## Fallbacks & browser support
+
+Web app origin migration has limited availability.
+Supported by: Chrome 149 (Jun 2026) and Edge 149 (Jun 2026).
+Unsupported in: Firefox and Safari.
+
+### Manual reinstallation prompt
+
+For browsers that do not support automatic migration, the user will remain on the old installation. You should implement a UI element (e.g., a notification banner) on the old origin that directs the user to the new site.
+
+The user's settings will not be migrated, and the old app will not be automatically uninstalled.
diff --git a/skills/modern-web-guidance/guides/security/local-network-access.md b/skills/modern-web-guidance/guides/security/local-network-access.md
new file mode 100644
index 0000000..c0db478
--- /dev/null
+++ b/skills/modern-web-guidance/guides/security/local-network-access.md
@@ -0,0 +1,207 @@
+# Local Network Access
+
+When a web application served from a `public` origin (or an intranet `local` origin) connects to a user's private local network (such as a LAN printer, IoT hub, or router at `192.168.1.x` or `device.local`) or to a local companion service running on the user's machine (`127.0.0.1`, `[::1]`, or `localhost`), browsers gate the connection behind a **Local Network Access (LNA)** permission prompt.
+
+Local Network Access splits access into two granular permissions and `Permissions-Policy` tokens based on the IP address space lattice (`public` → `local` → `loopback`), enforcing checks **only** when a request crosses from a *less private* address space into a *more private* address space:
+- **`local-network`**: Required when connecting from a `public` origin to the `local` address space (RFC 1918 private IPv4 ranges `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, link-local `169.254.0.0/16` / `fe80::/10`, IPv6 Unique Local Addresses `fc00::/7`, and `.local` mDNS hostnames).
+- **`loopback-network`**: Required when connecting from a `public` or `local` origin to the `loopback` address space (`127.0.0.0/8`, `::1/128`, or `localhost`).
+
+Because `localhost` (`127.0.0.1`) is already in the most private (`loopback`) address space, serving your web app from `http://localhost` during local development will **not** trigger LNA checks by default. To test LNA prompts and permission states locally without deploying to a public server, either override your local dev server's address space to `public` using the `--ip-address-space-overrides=127.0.0.1:8080=public` Chromium flag, or manually toggle **Local network** and **Loopback network** between `Ask`, `Allow`, and `Block` in browser **Site settings**.
+
+**MANDATORY:** Serve any web application that initiates local or loopback network requests from a **Secure Context (`https://`)**. Local Network Access permissions are denied automatically in insecure (`http://`) top-level contexts.
+
+**DO NOT** rely on deprecated Private Network Access (PNA) preflight headers (`Access-Control-Request-Private-Network: true` / `Access-Control-Allow-Private-Network: true`). Local Network Access enforces access via client-side user permission prompts (`local-network` and `loopback-network`) combined with standard CORS headers (`Access-Control-Allow-Origin`) when reading cross-origin responses. PNA preflights were never enforced as a blocking requirement and are not needed as a fallback. Existing servers or device firmware that already return `Access-Control-Allow-Private-Network: true` can keep doing so harmlessly, but do not add PNA handling to new code.
+
+## Implementation Steps
+
+### 1. Pre-Check Granular Permission State and Gate on User Gesture
+
+Never fire local network or loopback requests unconditionally on page load (`DOMContentLoaded`) when the permission state is `'prompt'`, and never initiate the first permission-triggering request from a **Service Worker** or **Shared Worker** (which lack an attached `Document` and will immediately fail if permission is not already `'granted'`).
+
+Instead, query `navigator.permissions.query()` for `'local-network'` or `'loopback-network'` first:
+- If `state === 'granted'`, connect automatically.
+- If `state === 'prompt'`, display clear UI explaining why the app needs access to the local device or companion app, and trigger the request from an explicit user gesture (such as a button click).
+- If `state === 'denied'`, render actionable remediation UI instructing the user how to re-enable Local Network or Loopback access in browser site settings.
+
+```javascript
+/**
+ * Queries the granular Local Network Access permission for the target space.
+ * @param {'local-network' | 'loopback-network'} permissionName
+ */
+export async function checkNetworkPermission(permissionName) {
+ const status = await navigator.permissions.query({ name: permissionName });
+
+ // Keep UI synchronized if the user changes permission in browser site settings
+ status.addEventListener('change', () => {
+ updatePermissionUI(permissionName, status.state);
+ });
+
+ updatePermissionUI(permissionName, status.state);
+ return status.state;
+}
+
+function updatePermissionUI(permissionName, state) {
+ const statusBadge = document.querySelector(`[data-permission-status="${permissionName}"]`);
+ const remediationBox = document.querySelector(`[data-remediation="${permissionName}"]`);
+ if (statusBadge) {
+ statusBadge.textContent = state;
+ }
+ if (remediationBox) {
+ // Show remediation instructions whenever permission is explicitly denied
+ remediationBox.hidden = state !== 'denied';
+ }
+}
+```
+
+### 2. Declare `targetAddressSpace` in `fetch()` and `Request`
+
+When an `https://` page requests an `http://` endpoint on the local network or loopback interface, specify `targetAddressSpace: 'local'` or `targetAddressSpace: 'loopback'` in the `fetch()` or `Request` options.
+
+Explicitly setting `targetAddressSpace` does two critical things:
+1. **Mixed Content Exemption**: Mixed Content checks run *before* DNS resolution. Declaring `targetAddressSpace: 'local'` (or `'loopback'`) informs the browser ahead of DNS resolution that an `http://` URL (including a custom DNS hostname that resolves to a local IP) targets a local/loopback endpoint and should be exempted from Mixed Content blocking once the user grants the permission.
+2. **Address Space Verification**: After DNS resolution, the browser verifies that the resolved IP address actually belongs to the declared `targetAddressSpace`. If a hostname with `targetAddressSpace: 'local'` unexpectedly resolves to a `public` IP address, the browser immediately aborts the request with a `TypeError` network error.
+
+```javascript
+/**
+ * Connects to a local network device (e.g., LAN printer or IoT hub) over HTTP.
+ * Example endpoint URL is illustrative; replace with your device's address.
+ */
+export async function fetchLocalDeviceStatus(deviceUrl = 'http://192.168.1.100:8080/api/status') {
+ const request = new Request(deviceUrl, {
+ method: 'GET',
+ mode: 'cors',
+ // MANDATORY: Declare 'local' when targeting RFC 1918 / .local LAN addresses
+ targetAddressSpace: 'local',
+ });
+
+ const response = await fetch(request);
+ if (!response.ok) {
+ throw new Error(`Device responded with HTTP ${response.status}`);
+ }
+ return response.json();
+}
+
+/**
+ * Connects to a local companion daemon running on the user's loopback interface.
+ * Example loopback port is illustrative; replace with your service's port.
+ */
+export async function fetchLoopbackDaemon(daemonUrl = 'http://127.0.0.1:45678/health') {
+ const request = new Request(daemonUrl, {
+ method: 'GET',
+ mode: 'cors',
+ // MANDATORY: Declare 'loopback' when targeting 127.0.0.1, [::1], or localhost
+ targetAddressSpace: 'loopback',
+ });
+
+ const response = await fetch(request);
+ if (!response.ok) {
+ throw new Error(`Companion app responded with HTTP ${response.status}`);
+ }
+ return response.json();
+}
+```
+
+### 3. Real-Time Connections with `WebSocket` and `WebTransport`
+
+Local Network Access restrictions also govern `WebSocket` and `WebTransport` connections:
+
+- **`WebSocket`**: Pass a `WebSocketInit` options dictionary as the second argument (`{ protocols, targetAddressSpace: 'local' | 'loopback' }`) when opening a `ws://` connection to a local or loopback endpoint from an `https://` page.
+- **`WebTransport`**: Because `WebTransport` strictly requires `https://` (HTTP/3 over QUIC with TLS or `serverCertificateHashes` for local self-signed certificates), it never triggers Mixed Content blocks and does not accept a `targetAddressSpace` option. Instead, the browser automatically verifies the resolved IP address space and gates the `transport.ready` promise behind the `local-network` or `loopback-network` permission prompt.
+
+```javascript
+/**
+ * Opens a WebSocket connection to a local network device with targetAddressSpace.
+ */
+export function openLocalWebSocket(wsUrl = 'ws://192.168.1.100:8080/stream') {
+ // Pass WebSocketInit with targetAddressSpace so ws:// from an https:// page
+ // is permitted once the user grants 'local-network' permission.
+ const socket = new WebSocket(wsUrl, {
+ protocols: ['v1.telemetry'],
+ targetAddressSpace: 'local',
+ });
+ return socket;
+}
+
+/**
+ * Opens a WebTransport session to a local network endpoint using a pinned self-signed certificate hash.
+ */
+export async function openLocalWebTransport(wtUrl = 'https://192.168.1.100:4433/wt', certSha256Bytes) {
+ const transport = new WebTransport(wtUrl, {
+ serverCertificateHashes: [
+ {
+ algorithm: 'sha-256',
+ value: certSha256Bytes,
+ },
+ ],
+ });
+
+ // transport.ready resolves only after the user grants the 'local-network' permission
+ // and rejects with WebTransportError if the permission is denied.
+ await transport.ready;
+ return transport;
+}
+```
+
+### 4. Delegate Access to Cross-Origin Iframes via `Permissions-Policy`
+
+By default, `local-network` and `loopback-network` have a default allowlist of `'self'`, blocking cross-origin `<iframe>` embeds from making local or loopback requests. To allow an embedded cross-origin `<iframe>` (such as a hardware setup widget or an SSO frame that communicates with a local agent) to initiate local or loopback requests, explicitly delegate the granular permissions in the `allow` attribute and/or HTTP `Permissions-Policy` header:
+
+```html
+<!-- Delegate granular local-network and loopback-network permissions to the embedded iframe -->
+<iframe
+ src="https://setup.partner.example.com/device-bridge"
+ allow="local-network; loopback-network"
+ title="Local Device Bridge">
+</iframe>
+```
+
+Send the `Permissions-Policy` header on the **top-level (embedding) document's** response, not on the iframe's response:
+
+```http
+Permissions-Policy: local-network=(self "https://setup.partner.example.com"), loopback-network=(self "https://setup.partner.example.com")
+```
+
+## Fallback Strategies
+
+Local network access has limited availability.
+Supported by: Chrome 142 (Oct 2025) and Edge 142 (Oct 2025).
+Unsupported in: Firefox and Safari.
+
+Because Local Network Access permissions and `targetAddressSpace` options are not yet supported across all browsers (and older browser versions only accepted a protocol string/array in `new WebSocket(url, protocols)`), implement **feature detection with progressive fallback**:
+
+1. **Permission Query Fallback**: Wrap `navigator.permissions.query({ name: permissionName })` in a `try / catch`. If the browser throws a `TypeError` because `'local-network'` or `'loopback-network'` is an unrecognized `PermissionName`, treat the state as `'prompt'` so the request still runs on an explicit user click (the connection attempt itself triggers the browser prompt where LNA is supported).
+2. **DO NOT** query the legacy combined permission name `{ name: 'local-network-access' }`. In older Chrome versions this query crashes the renderer process, and `try / catch` cannot prevent it. Newer Chrome versions treat `'local-network-access'` only as a legacy alias for the granular permissions.
+3. **`WebSocket` Constructor Fallback**: Wrap `new WebSocket(url, { protocols, targetAddressSpace })` in a `try / catch` and fall back to `new WebSocket(url, protocols)` when the browser does not support the `WebSocketInit` options dictionary.
+4. **Graceful Rejection Handling**: Always wrap `fetch()`, `WebSocket` error events, and `transport.ready` in error handlers that catch `TypeError` / connection failures and present clear remediation steps (checking that the local device is powered on, connected to the same network, and allowed in browser permissions).
+
+```javascript
+/**
+ * Cross-browser permission check for the granular LNA permissions.
+ * Never falls back to querying 'local-network-access', which crashes older Chrome versions.
+ * @param {'local-network' | 'loopback-network'} permissionName
+ */
+export async function queryLnaPermissionSafe(permissionName) {
+ if (!navigator.permissions?.query) {
+ return 'prompt';
+ }
+ try {
+ const status = await navigator.permissions.query({ name: permissionName });
+ return status.state;
+ } catch {
+ // Unrecognized permission name; proceed on user gesture
+ return 'prompt';
+ }
+}
+
+/**
+ * Cross-browser WebSocket helper that uses WebSocketInit ({ protocols, targetAddressSpace })
+ * when supported and falls back to standard new WebSocket(url, protocols).
+ */
+export function connectLocalWebSocketSafe(url, { protocols = [], targetAddressSpace = 'local' } = {}) {
+ try {
+ return new WebSocket(url, { protocols, targetAddressSpace });
+ } catch {
+ return new WebSocket(url, protocols);
+ }
+}
+```
diff --git a/skills/modern-web-guidance/guides/security/sanitize-untrusted-html.md b/skills/modern-web-guidance/guides/security/sanitize-untrusted-html.md
index a5f850e..fe556d8 100644
--- a/skills/modern-web-guidance/guides/security/sanitize-untrusted-html.md
+++ b/skills/modern-web-guidance/guides/security/sanitize-untrusted-html.md
@@ -2,7 +2,7 @@
Safely displaying user-generated HTML is a common security challenge. The native **Sanitizer API** provides a built-in, browser-optimized way to strip dangerous content (like `<script>` tags or `on*` attributes) before it reaches the DOM.
-MANDATORY: Do not rely solely on client-side sanitization for user-generated content. Always sanitize content on the server. Make sure that the server and client sanitization rules do not conflict.
+Client-side sanitization protects the page that renders the content. If the same user-generated content is also rendered elsewhere (other clients, server-rendered pages, or emails), sanitize it on the server as well as defence in depth, and make sure the server and client sanitization rules do not conflict.
## 1. Safely Inserting HTML with `setHTML()`
@@ -19,16 +19,16 @@ const untrustedHTML = `
const container = document.getElementById('output');
// Sanitize and insert in one call
-// Default behavior strips scripts and event handlers
+// The default sanitizer removes scripts and event handlers, plus other
+// elements and attributes outside its built-in allowlist (such as style)
container.setHTML(untrustedHTML);
```
## 2. Using Custom Sanitizer Configurations
-You can customize the sanitization rules by creating a `Sanitizer` instance. This allows you to define exactly which elements and attributes are permitted for your specific use case.
-
-When using `Element.setHTML()` and `Document.parseHTML()`, the default `Sanitizer` settings remove all XSS-unsafe elements and attributes. You can not make a more permissive `Sanitizer` that allows those elements, but you can further restrict what is allowed.
+You can customize the sanitization rules by creating a `Sanitizer` instance. This allows you to define exactly which elements and attributes are permitted for your specific use case.
+When using `Element.setHTML()` and `Document.parseHTML()`, the default `Sanitizer` settings remove all XSS-unsafe elements and attributes. You cannot make a more permissive `Sanitizer` that allows those elements, but you can further restrict what is allowed.
```javascript
// Define a restrictive configuration that only allows the specified elements and attributes.
@@ -44,20 +44,22 @@ const mySanitizer = new Sanitizer(config);
container.setHTML(untrustedHTML, { sanitizer: mySanitizer });
```
+Elements that are not in `elements` are removed **together with their content**. List wrapper elements whose text you want to keep (such as `div` above) in `replaceWithChildrenElements`, which removes the element but keeps its children.
+
If you need a more permissive `Sanitizer` that allows some XSS-unsafe elements or attributes, you can use a custom Sanitizer with `Element.setHTMLUnsafe()` and `Document.parseHTMLUnsafe()`.
## 3. Parsing User Input with `Document.parseHTML()`
-If you need to parse untrusted HTML without immediately inserting it into the live DOM, use `Document.parseHTML()`. This method returns a `Document` that has been sanitized according to default or custom rules.
+If you need to parse untrusted HTML without immediately inserting it into the live DOM, use `Document.parseHTML()`. This method returns a `Document` that has been sanitized according to default or custom rules, so you can inspect or transform the sanitized nodes (for example, to build a preview or extract text) before inserting them.
-This can be used for sanitizing user content before sending it to a server.
+Move the resulting nodes into the page rather than serializing them to a string and re-parsing it with `innerHTML`, which can reintroduce mutation XSS (mXSS).
```javascript
const rawHTML = '<p>Hello <script>console.log("bad")</script></p>';
const doc = Document.parseHTML(rawHTML);
// doc.body now contains the sanitized nodes: <p>Hello </p>
-console.log(doc.body.innerHTML);
+preview.replaceChildren(...doc.body.childNodes);
```
## Fallbacks & browser support for Sanitizer API
@@ -66,25 +68,36 @@ Sanitizer API has limited availability.
Supported by: Chrome 146 (Mar 2026), Edge 146 (Mar 2026), and Firefox 148 (Feb 2026).
Unsupported in: Safari.
-If the native Sanitizer API is not available in your target browsers, you MUST use a library like **DOMPurify** to ensure security. You must also apply a configuration via DOMPurify's API to match the Sanitizer API.
+If the native Sanitizer API is not available in your target browsers, load a library like **DOMPurify** only when native support is missing, to avoid shipping it to browsers that don't need it. Use `in` checks for feature detection so the check itself works in older browsers.
```javascript
-function safeSetHTML(el, html) {
- if (Object.hasOwn(Element.prototype, 'setHTML') && 'Sanitizer' in window) {
- const config = {
- elements: ["p", "b", "i", "strong", "em"],
- attributes: ["style"],
- replaceWithChildrenElements: ['div']
- };
-
- const mySanitizer = new Sanitizer(config);
- el.setHTML(html, {sanitizer: mySanitizer});
+let domPurifyPromise;
+
+function loadDOMPurify() {
+ // Code-split with your bundler so DOMPurify is only downloaded when needed
+ domPurifyPromise ??= import('dompurify').then((mod) => mod.default ?? mod);
+ return domPurifyPromise;
+}
+
+export async function safeSetHTML(el, html) {
+ const elements = ['p', 'b', 'i', 'strong', 'em'];
+ const attributes = ['class'];
+
+ if ('setHTML' in Element.prototype) {
+ // setHTML() accepts a plain configuration object as the sanitizer
+ el.setHTML(html, { sanitizer: { elements, attributes } });
} else {
- // Load DOMPurify only in browsers that do not support Element.setHTML(). Match configuration.
+ const DOMPurify = await loadDOMPurify();
el.innerHTML = DOMPurify.sanitize(html, {
- ALLOWED_TAGS: ["p", "b", "i", "strong", "em"],
- ALLOWED_ATTR: ["style"]
+ ALLOWED_TAGS: [...elements, '#text'],
+ ALLOWED_ATTR: attributes,
+ // Match the native Sanitizer: remove disallowed elements with their content
+ KEEP_CONTENT: false
});
}
}
```
+
+By default, DOMPurify keeps the text content of elements it removes, while the native Sanitizer removes disallowed elements together with their content. Setting `KEEP_CONTENT: false` and allowing `#text` makes DOMPurify match the native behavior. DOMPurify has no built-in option equivalent to `replaceWithChildrenElements`, so avoid that option in configurations that need a matching fallback.
+
+If the page enforces Trusted Types (`require-trusted-types-for 'script'`), assigning a string to `innerHTML` throws. `setHTML()` does not need a Trusted Types policy, but the fallback does: pass `RETURN_TRUSTED_TYPE: true` to `DOMPurify.sanitize()` and allow its `dompurify` policy name in your `trusted-types` CSP directive.
diff --git a/skills/modern-web-guidance/guides/security/security.md b/skills/modern-web-guidance/guides/security/security.md
index 61ece2e..7af0fdf 100644
--- a/skills/modern-web-guidance/guides/security/security.md
+++ b/skills/modern-web-guidance/guides/security/security.md
@@ -219,23 +219,13 @@ For static/cached HTML (SPAs) where a per-response nonce is not possible, use ha
**Avoid**: URL allowlists like `script-src https://cdn.example.com` — they are easily bypassed by open redirects, JSONP endpoints, and dependency injection on the allowed origin.
#### 3.3 Trusted Types Enforcement
-Trusted Types enforces the §1.2 source-level guidance at runtime: once enabled, the browser blocks string assignments to dangerous sinks unless they pass through a named policy.
+Trusted Types enforces source-level guidance at runtime by blocking string assignments to dangerous sinks unless they pass through a named policy.
-- **Incremental Rollout Strategy**: While full enforcement carries real breakage risk, you do not need to do everything at once. A highly viable approach is to define and roll out a policy for a small portion of the application under refactoring, and slowly expand its usage as you replace sinks. This simplifies eventual global enforcement without short-term breakage risk.
-- **Prerequisite**: Trusted Types requires framework cooperation. If the app's framework (or any third-party widget that writes to DOM sinks) does not produce `TrustedHTML` / `TrustedScript` values, the policy cannot be enforced without breaking that code. Audit framework support before starting the report-only rollout.
-- **Prerequisite**: The code-level sink refactor from Phase 1 is a prerequisite for complete Trusted Types enforcement. (Standard CSP `script-src` enforcement, by contrast, does not police DOM sinks and can be deployed without refactoring them.)
-- **DO**: Roll out via `Content-Security-Policy-Report-Only: require-trusted-types-for 'script'` first to find every offending sink.
-- **DO**: Define a single named policy that performs sanitization (or escaping) and route all sink writes through it.
-- **DO**: Move to full global `Content-Security-Policy: require-trusted-types-for 'script'` enforcement once the policy has been successfully integrated and violations in report-only logs drop to zero.
+Because deployment involves site-wide enforcement and framework compatibility checks, it should be treated as a major security initiative.
-```javascript
-if (window.trustedTypes && trustedTypes.createPolicy) {
- const policy = trustedTypes.createPolicy('escapePolicy', {
- createHTML: str => str.replace(/</g, '&lt;').replace(/>/g, '&gt;')
- });
- el.innerHTML = policy.createHTML(untrustedString);
-}
-```
+- **DO**: Consult the dedicated `trusted-types` (via `npx -y modern-web-guidance@latest retrieve "trusted-types"`) guide for full implementation details, including policy creation and rollout strategies.
+- **Prerequisite**: Audit framework and third-party widget support before starting. If dependencies write to DOM sinks without producing Trusted Types, enforcement will break that code.
+- **Incremental Rollout**: Always start with `Content-Security-Policy-Report-Only` to identify all offending sinks before moving to full enforcement.
#### 3.4 Cross-Origin Opener Policy (COOP)
diff --git a/skills/modern-web-guidance/guides/security/trusted-types.md b/skills/modern-web-guidance/guides/security/trusted-types.md
new file mode 100644
index 0000000..9fed33c
--- /dev/null
+++ b/skills/modern-web-guidance/guides/security/trusted-types.md
@@ -0,0 +1,127 @@
+# Prevent DOM-based XSS attacks with Trusted Types
+
+Trusted Types is a security feature that helps prevent DOM-based Cross-Site Scripting (DOM XSS) by requiring that data being passed into "dangerous" browser APIs (known as sinks) is first converted into a specific type, such as `TrustedHTML`.
+
+By default, many DOM APIs (like `innerHTML` or `document.write`) accept raw strings. If a string contains malicious script from an untrusted source, it can be executed. Trusted Types changes this behavior: once enabled via CSP, these sinks will only accept `TrustedHTML` objects created by authorized policies.
+
+## Key Implementation Details
+
+To use Trusted Types, follow four main steps:
+
+1. Define a security policy that specifies how to sanitize or transform strings.
+2. Use that policy to create Trusted Type objects from raw strings.
+3. Use the Trusted Type objects when writing to DOM sinks.
+4. Enforce Trusted Types using a Content Security Policy (CSP).
+
+### 1. Creating a Policy
+
+A policy is a set of rules for sanitizing content. You create it using `trustedTypes.createPolicy()`.
+
+```javascript
+const myPolicy = trustedTypes.createPolicy('my-no-pretzel-policy', {
+ createHTML: (input) => {
+ // A simple replacement rule.
+ // In a real app, you might use the Sanitizer API, or a library like DOMPurify.
+ return input
+ .replace(/pretzel/g, "popcorn");
+ }
+});
+```
+
+### 2. Using the Policy
+
+Instead of passing a string directly to a sink, you call the policy's creation method.
+
+```javascript
+const untrustedInput = 'I love eating a soft pretzel.';
+
+// In an enforced environment, this would throw a TypeError:
+// element.innerHTML = untrustedInput;
+
+// This returns a TrustedHTML object:
+const cleanHTML = myPolicy.createHTML(untrustedInput);
+// Result: "I love eating a soft popcorn."
+```
+
+### 3. Transitioning sinks to use Trusted Types
+
+Update each instance where you write to a sink to first convert it to a Trusted Type object. To help locate where code needs to be updated, you can define a temporary `default` policy that logs when a sink is written to with a string rather than a TrustedType.
+
+```javascript
+trustedTypes.createPolicy("default", {
+ createHTML(value) {
+ console.warn("String passed instead of Trusted Type.");
+ return sanitize(value);
+ },
+});
+```
+
+Common sinks that support Trusted Types include:
+- **HTML:** `element.innerHTML`, `element.outerHTML`, `document.write()`, `element.setHTMLUnsafe()`, `document.parseHTMLUnsafe()`
+- **Script:** `<script src>`, `eval()`
+- **ScriptURL:** `Worker()`, `SharedWorker()`
+
+```javascript
+// Assign the TrustedHTML object.
+element.innerHTML = cleanHTML;
+```
+
+Note that the "safe" HTML sanitization methods (`element.setHTML()` and `document.parseHTML()`, for instance), do not support Trusted Types, as they always sanitize potential XSS attacks.
+
+### 4. Enforcing Trusted Types with CSP
+
+Trusted Types should be rolled out incrementally to avoid breaking your application. While full enforcement provides the strongest protection, it carries a risk of site breakage if every sink write hasn't been migrated.
+
+#### Prerequisites
+
+- **Framework cooperation**: If your application's framework (or any third-party library that writes to DOM sinks) does not produce `TrustedHTML` or `TrustedScript` values, you cannot enforce Trusted Types without breaking that code. Audit framework support before starting the rollout.
+- **Sink refactoring**: Ensure you have identified and refactored dangerous sinks to use your Trusted Types policies.
+
+#### Rollout Strategy
+
+1. **Report-Only**: First, roll out using the `Content-Security-Policy-Report-Only` header. This will log violations to your reporting endpoint without actually blocking the writes.
+ ```http
+ Content-Security-Policy-Report-Only: require-trusted-types-for 'script';
+ ```
+2. **Enforcement**: Once you have integrated your policies and violation reports drop to zero, move to full enforcement.
+
+ ```http
+ Content-Security-Policy: require-trusted-types-for 'script';
+ ```
+
+You can also restrict which policies are allowed to be created:
+
+```http
+Content-Security-Policy: trusted-types my-no-pretzel-policy;
+```
+
+With this CSP in place, any writes to a sink that don't use Trusted Types will throw an error. In addition, attempting to create a Trusted Type with a name that isn't `my-no-pretzel-policy` will throw an error.
+
+You can also set this CSP as a `<meta>` tag in your document's `<head>`, although this is potentially less secure.
+
+```html
+<!-- First child of `<head>`, as earlier tags will not enforce this CSP. -->
+<meta
+ http-equiv="Content-Security-Policy"
+ content="require-trusted-types-for 'script'; trusted-types my-no-pretzel-policy;"
+/>
+```
+
+## Fallback strategies
+
+Baseline status for Trusted types: Newly available. It's been Baseline since 2026-02-24.
+Supported by: Chrome 83 (May 2020), Edge 83 (May 2020), Firefox 148 (Feb 2026), and Safari 26 (Sep 2025).
+
+For browsers that do not yet support Trusted Types, you can use a minimal "tinyfill" to ensure your code doesn't break while still providing sanitization.
+
+```javascript
+if (!window.trustedTypes) {
+ window.trustedTypes = {
+ createPolicy: (name, rules) => rules,
+ };
+}
+```
+
+This allows you to write your code using the Trusted Types pattern today. Supporting browsers will enforce the types, while older browsers will still execute your sanitization logic via the mock policy.
+
+If a browser doesn't support Trusted Types, it will simply treat the `TrustedHTML` objects as strings (if using the tinyfill) or won't have the enforcement check at the sink level.
diff --git a/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md b/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md
new file mode 100644
index 0000000..f9fc192
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-atoms/responsive-table.md
@@ -0,0 +1,118 @@
+# Responsive tables
+
+Large data tables often become unreadable on small screens as columns overflow or shrink beyond legibility. This guide demonstrates how to use **sticky positioning** to keep headers visible during scrolling and how to transform the table into a mobile-friendly "stacked" layout when space is limited.
+
+## Recommended Approach
+
+The core of a responsive table is maintaining the relationship between data cells and their headers.
+
+1. **Semantic Foundation**: Use standard `<table>` elements with `<thead>`, `<tbody>`, and `<th>` elements.
+2. **Sticky Context**: Apply `position: sticky` to both column headers and row headers. This ensures that no matter how far a user scrolls in any direction, they never lose the context of what the data represents.
+3. **Adaptive Transformations**: Use `@container` queries instead of `@media` queries. This allows the table to adapt based on its own width (e.g., when placed in a sidebar or a narrow dashboard widget) rather than the entire viewport.
+4. **Label Injection**: In the stacked layout, the `<thead>` is hidden, and accessible headers are injected into each cell using `::before` pseudo-elements and CSS variables.
+
+## 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.
+
+```html
+<div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Employee</th>
+ <th>Role</th>
+ <th>Status</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <!-- Row header remains sticky horizontally on desktop,
+ and becomes a sticky card header on mobile -->
+ <th>Alex Rivera</th>
+ <td>Engineer</td>
+ <td>Active</td>
+ </tr>
+ </tbody>
+ </table>
+</div>
+```
+
+### 2. Configure Sticky Headers
+Enable scrolling and make headers sticky. Use logical properties and explicit z-index values to manage the stacking order.
+
+```css
+.table-wrapper {
+ overflow: auto;
+ max-inline-size: 100%;
+ max-block-size: min(500px, 80vh);
+ container-type: inline-size;
+}
+
+table {
+ border-collapse: separate;
+ border-spacing: 0;
+}
+
+/* Sticky column headers (desktop) */
+thead {
+ position: sticky;
+ inset-block-start: 0;
+ z-index: 1; /* Above sticky row headers */
+}
+
+/* Sticky row headers (desktop) */
+tbody th {
+ position: sticky;
+ inset-inline-start: 0;
+ background: white; /* Required to cover background during scroll */
+}
+```
+
+### 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.
+
+```css
+@container (width < 600px) {
+ table, thead, tbody, tr, th, td {
+ display: block;
+ }
+
+ thead {
+ /* MANDATORY: Hide column header from layout and screen readers. */
+ display: none
+ }
+
+ tr {
+ margin-block-end: 1.5rem;
+ border: 1px solid #ccc;
+ }
+
+ /* Sticky row headers at the top of each block/card */
+ tbody th {
+ position: sticky;
+ inset-block-start: 0;
+ z-index: 2;
+ background: #eee;
+ }
+
+ /* Define column labels as CSS variables (often set via JS) */
+ table {
+ --label-1: "Employee";
+ --label-2: "Role";
+ --label-3: "Status";
+ }
+
+ /* Inject labels with accessible names */
+ 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: Map the label for each column */
+ td:nth-child(3)::before {
+ content: var(--label-3) ": " / var(--label-3);
+ }
+}
+```
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/consistent-cross-document-transitions.md b/skills/modern-web-guidance/guides/ui-behaviors/consistent-cross-document-transitions.md
index 6d86d28..4bb2732 100644
--- a/skills/modern-web-guidance/guides/ui-behaviors/consistent-cross-document-transitions.md
+++ b/skills/modern-web-guidance/guides/ui-behaviors/consistent-cross-document-transitions.md
@@ -206,6 +206,7 @@ window.addEventListener('pagereveal', async (event) => {
- **DO** assign `view-transition-name` via CSS whenever possible. Reserve JavaScript assignment (via `pagereveal`) for cases where the name depends on navigation context.
- **DO** keep render-blocking scripts small and fast. The browser has a built-in timeout (around 4 seconds), after which the transition is skipped entirely with a `TimeoutError`.
- **DO NOT** use `<link rel="expect">` to block on elements deep in the page that are not visible in the initial viewport. This delays the transition without visual benefit.
+- **DO NOT** mark analytics, ad-network, tag-manager or other third-party loaders with `blocking="render"`, even if they inject content into the initial viewport. Their network latency counts toward the transition timeout and their output is not part of the page's stable state.
- **DO NOT** assign the same `view-transition-name` to multiple elements on the same page. Duplicate names cause the entire transition to be skipped.
- **Assistive Technology Timing Impact**: Using `blocking="render"` delays visual updates and initial paint. While this prevents visual glitches for sighted users, it can cause processing latency or deferred initialization for screen readers and other assistive technologies that depend on rendered accessibility trees. Weigh the visual continuity benefits against the initial read latency for non-visual users, and ensure render-blocking scripts are minimal and extremely optimized.
diff --git a/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md b/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md
new file mode 100644
index 0000000..9bab3dd
--- /dev/null
+++ b/skills/modern-web-guidance/guides/ui-behaviors/spatial-navigation.md
@@ -0,0 +1,56 @@
+# Spatial Navigation (Directional Keypad Focus)
+
+Directional focus navigation (using arrow keys or D-Pads) enables keyboard-only and alternative-input users to navigate interactive items based on their visual 2D layout. It is highly beneficial for spatial user interfaces (such as media rails, dashboard panels, or nested catalogs), but it must be implemented carefully to avoid breaking native browser behaviors like viewport scrolling.
+
+This guide covers building performant, accessible 2D directional navigation inside composite widgets.
+
+---
+
+### Core Architectural Principles
+
+When implementing custom arrow-key spatial focus, adhere to these foundational rules:
+
+1. **Limit to composite widgets**: Do not override arrow keys on normal document text flow or simple vertical list layouts where default sequential Tab navigation is expected. See `accessibility` (via `npx -y modern-web-guidance@latest retrieve "accessibility"`) for general document flow guidance.
+2. **Preserve native boundary scrolling**: If there is no focusable element in the pressed direction, **do not prevent default browser behavior**. Let the event bubble so the browser can scroll the viewport natively. Overriding arrow keys unconditionally breaks accessibility (WCAG 1.4.10).
+3. **Ensure focus visibility and alignment**: When focus changes, ensure the newly focused element is scrolled into view (e.g., using `scrollIntoView({ block: 'nearest', inline: 'nearest' })`) so that it remains fully visible.
+4. **Coordinate with the layout system**: Determine focus candidate positions from live bounding geometries (`getBoundingClientRect()`) while handling each keypress. Avoid assuming that DOM order or a fixed grid structure represents the visual layout. See `css-layout` (via `npx -y modern-web-guidance@latest retrieve "css-layout"`) for modern layout recommendations.
+
+---
+
+### Accessible Focus Management
+
+The spatial container must expose a single tab stop to sequential Page Tab navigation. Inside the widget, manage keyboard focus using the **Roving Tabindex Pattern**:
+* The active item has `tabindex="0"`.
+* All inactive items have `tabindex="-1"`.
+* When navigating, programmatically move focus by shifting the `tabindex="0"` attribute and calling `focus()`.
+
+---
+
+### Visual Candidate Selection
+
+In asymmetrical, wrapped, or grid layouts, index-based mapping fails. Instead, derive candidates from the live visual geometry for the current keypress:
+
+* **Candidates**: Use the focusable descendants of the widget container that pass `checkVisibility()`. Hidden elements can have a zero-sized rect at `(0, 0)` and must not become accidental `up` or `left` targets.
+* **Geometry**: Read `getBoundingClientRect()` for the focused element and every candidate while handling the keypress. Do not cache these rects globally: layout can change for many reasons, and a small number of geometry reads is cheap when handling a user-paced key event.
+* **Direction filter**: A candidate is in the pressed direction only when its near edge is at or beyond the current element’s far edge on that axis, allowing a small tolerance for sub-pixel rounding. For example, a candidate for `right` must have `candidate.left >= current.right - tolerance`. Do not compare centres to determine whether a candidate is in the direction.
+* **Aligned candidates first**: Among candidates that pass the direction filter, prefer candidates whose extent on the perpendicular axis overlaps the current element’s extent. Choose the smallest gap on the navigation axis, breaking ties with the smallest perpendicular centre offset. This keeps navigation in the adjacent visual row or column even when an item is unusually wide.
+* **Fallback scoring**: If no candidate overlaps on the perpendicular axis, score the remaining candidates as `gap + w * perpendicularCentreOffset` and choose the minimum. Use a weight `w >= 2` as a starting point, then tune it for the layout; a larger weight favours candidates that are more closely aligned.
+* **No candidate**: Return nothing. The event handler must not call `preventDefault()`, allowing the browser to scroll natively.
+
+The exact implementation can vary, but keep the direction test edge-based and apply the overlap preference before the weighted fallback. This is the crux of the algorithm; avoid presenting a cache or a fixed weight as universally correct.
+
+---
+
+### Keypress Integration & Scroll Cooperation
+
+Your event router must prevent standard viewport scrolling **only** when a valid spatial focus transition occurs:
+
+* Do not intercept the event when a modifier key is held, when `e.defaultPrevented` is already true, or when the innermost event target consumes arrow keys itself. Use `e.composedPath()[0]` rather than only `e.target`, because `e.target` can be retargeted to a shadow host. A practical editable/control check is `target.matches(':read-write, select, input[type="range"], [role="slider"]')`; closed shadow roots cannot be inspected.
+* Scope the listener to the widget container, so multiple spatial widgets can coexist on a page.
+* Act only when the focused element is itself a candidate. If items contain their own focusable controls, either make those controls candidates too or leave them alone; do not resolve a parent with `closest()`.
+* When a candidate is found, call `preventDefault()`, update the roving `tabindex`, call `focus()`, and use `scrollIntoView({ block: 'nearest', inline: 'nearest' })`.
+* When no candidate is found, return without calling `preventDefault()` so native scrolling continues.
+
+---
+
+Avoid adding single-character shortcuts such as `h`/`j`/`k`/`l` or `W`/`A`/`S`/`D` for spatial navigation. Arrow keys are not character keys, and preserving native scrolling when no candidate exists avoids unnecessarily blocking viewport movement.
diff --git a/skills/modern-web-guidance/guides/visual-design/prevent-text-wrapping.md b/skills/modern-web-guidance/guides/visual-design/prevent-text-wrapping.md
deleted file mode 100644
index 2abfb4d..0000000
--- a/skills/modern-web-guidance/guides/visual-design/prevent-text-wrapping.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# Prevent text wrapping
-
-Modern CSS provides the `text-wrap` property to control how text breaks within its container. To ensure text stays on a single line and ignores container boundaries, use `text-wrap: nowrap`. This is the modern, more semantic replacement for `white-space: nowrap`.
-
-Preventing text wrapping is useful for UI elements like navigation tabs, horizontal scrolling chips, or any scenario where a line break would break the layout or visual design.
-
-## How to implement `text-wrap: nowrap`
-
-### Basic Usage
-
-To prevent any automatic line breaks, apply `text-wrap: nowrap` to the element containing the text.
-
-1. **MANDATORY**: Apply `text-wrap: nowrap` to the target element.
-2. **OPTIONAL**: Use an `overflow` property (such as `hidden`, `scroll`, or `auto`) to manage the resulting overflow.
-3. **OPTIONAL**: Use `text-overflow: ellipsis` to provide a visual cue when text is truncated. Note: This requires `overflow: hidden`.
-
-### Example code
-
-```css
-.no-wrap-text {
- /* MANDATORY: Prevents automatic line breaks */
- text-wrap: nowrap;
-
- /* OPTIONAL: Handles the overflow visually */
- overflow: hidden;
- text-overflow: ellipsis;
-
- /* OPTIONAL: Constrain width to force and handle overflow within this element */
- max-width: 200px;
-}
-```
-
-### Specific Control with Longhands
-
-The `text-wrap` property is a shorthand for `text-wrap-mode` (whether text wraps) and `text-wrap-style` (how it wraps). Since `text-wrap-style` is ignored when wrapping is disabled, you should generally stick to the `text-wrap` shorthand.
-
-While the longhand `text-wrap-mode: nowrap` exists, the property name is currently considered a placeholder by the CSS Working Group and may change in the future.
-
-```css
-.granular-control {
- /* Modern longhand equivalent to white-space: nowrap */
- /* Preferred: text-wrap: nowrap; */
- text-wrap-mode: nowrap;
-}
-```
-
-### Fallback strategies
-
-Baseline status for text-wrap: Newly available. It's been Baseline since 2024-10-17.
-Supported by: Chrome 130 (Oct 2024), Edge 130 (Oct 2024), Firefox 124 (Mar 2024), and Safari 17.5 (May 2024).
-
-For browsers that do not yet support `text-wrap`, use the legacy `white-space` property. Modern browsers treat `white-space` as a shorthand for setting both the `text-wrap-mode` and `white-space-collapse` properties.
-
-```css
-.no-wrap-with-fallback {
- /* Fallback for older browsers */
- white-space: nowrap;
-
- /* Modern standard */
- text-wrap: nowrap;
-}
-```
diff --git a/skills/modern-web-guidance/guides/wasm/cpp-on-the-web.md b/skills/modern-web-guidance/guides/wasm/cpp-on-the-web.md
new file mode 100644
index 0000000..ebb90f0
--- /dev/null
+++ b/skills/modern-web-guidance/guides/wasm/cpp-on-the-web.md
@@ -0,0 +1,74 @@
+# Compiling C and C++ to WebAssembly with Emscripten
+
+Use Emscripten to compile C and C++ into high-performance WebAssembly (Wasm)
+modules for the browser.
+
+## 1. Modern Emscripten Compilation Flags
+
+When compiling and linking with `emcc` or `em++`, always use modern modular
+flags:
+
+- `-sEXPORT_ES6`: Emits standard ES6 module syntax (`import`/`export`) rather
+ than legacy global objects. This automatically sets `-sMODULARIZE`.
+- `-sENVIRONMENT=web`: Strips Node.js/shell runtime code to minimize bundle
+ size.
+- `-sSTRICT`: Enforces modern Emscripten defaults and fails on deprecated
+ flags.
+- `-sALLOW_MEMORY_GROWTH`: Allows the WebAssembly linear memory heap to expand
+ dynamically when allocating memory.
+- `-Oz` (or `-O3`) + `-flto`: Optimizes for minimal payload size in release builds.
+
+## 2. Avoid blocking the main thread
+
+If a call into WebAssembly is likely to take a significant amount of time (i.e.
+more than a few milliseconds) it should **not** be called on the main browser
+thread.
+
+To avoid running such code on the main browser thread there are several possible
+approaches:
+
+1. Run the whole WebAssembly program in a Web Worker. This is often the
+ simplest solution since it doesn't involve setting up SharedArrayBuffer
+ access, or changing the program source.
+
+2. Use pthreads or Wasm Workers. This allows the work to be shared across
+ many workers but requires SharedArrayBuffer access which can involve adding
+ COOP/COEP HTTP headers.
+
+3. Refactor the C/C++ code to avoid long running calls. For example slicing
+ the work into small pieces that can be called from `requestIdleCallback`.
+
+## 3. Pay attention for runtime warnings and errors
+
+Make sure you actually test the resulting WebAssembly program and that no
+warnings or errors are generated on the console.
+
+Build and run the programs with `-sASSERTIONS` enabled and fix any runtime
+failures that are produced.
+
+## 4. Avoid dynamic linking if possible
+
+Emscripten works best with static libraries (`.a`). Shared libraries (`.so`,
+`.dylib`, `.dll`) are less useful in browser deployment and can complicate
+things unnecessarily.
+
+## 5. Porting Existing C/C++ Libraries
+
+When integrating existing C/C++ libraries with standard build systems:
+
+### CMake Projects
+
+Wrap CMake commands with `emcmake` and `emmake`:
+```bash
+mkdir build && cd build
+emcmake cmake .. -DCMAKE_BUILD_TYPE=Release
+emmake make
+```
+
+### Autoconf / Make Projects
+
+Use `emconfigure` to set cross-compilation toolchain targets:
+```bash
+emconfigure ./configure --host=wasm32-unknown-emscripten --disable-shared
+emmake make
+```
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 e7d741b..2aa145c 100644
--- a/skills/modern-web-guidance/guides/webmcp/agentic-javascript-tools.md
+++ b/skills/modern-web-guidance/guides/webmcp/agentic-javascript-tools.md
@@ -2,9 +2,16 @@
The Imperative API uses `document.modelContext.registerTool()` to programmatically define JavaScript tools. This is ideal for Single Page Applications (SPAs) where tools need to be added or removed based on the current route or user state.
+WebMCP operates on a producer/consumer architecture:
+* **Web pages are tool producers:** You define and register tools using `document.modelContext.registerTool()`. That is all a web page needs to implement. **You do not need to call `getTools()` or `executeTool()` on the page to expose tools to agents.**
+* **Browser and extension agents are the primary consumers:** Agents provided by or through the browser — including the browser's built-in agent, browser extensions, DevTools, and system-level assistants — discover and invoke registered tools out-of-band through internal platform mechanisms.
+* **In-page agents and test harnesses:** `getTools()` and `executeTool()` exist specifically for in-page JavaScript assistants (e.g. an embedded chat widget or `<iframe>`) and automated test suites that need to discover and invoke tools directly within the page context.
+
## Registration and Lifecycle
-Tools are registered by passing a tool definition object and an optional options object containing an `AbortSignal`.
+Tools are registered by passing a tool definition object and an optional options object (`ModelContextRegisterToolOptions`), which supports two optional members:
+* `signal`: An `AbortSignal` used to unregister the tool when it is no longer needed.
+* `exposedTo`: An array of origin strings controlling which documents in the document tree are allowed to discover and execute the tool across frame boundaries.
### Lifecycle Handling with `AbortController`
@@ -28,6 +35,34 @@ await document.modelContext.registerTool({
controller.abort();
```
+Aborting the registration signal only unregisters the tool — it does not cancel executions that are already running. Tools that start long-running work must also honor the per-execution signal described below, or unregistering will leave orphaned requests and stale UI updates behind.
+
+### Controlling cross-origin tool exposure with `exposedTo`
+
+By default, a registered tool is private to the registering document and same-origin frames. When your application is embedded in an `<iframe>` (or embeds third-party widgets) and you need ancestor or sibling frames to discover and invoke the tool, specify the allowed origins using `exposedTo`.
+
+```javascript
+const controller = new AbortController();
+
+await document.modelContext.registerTool({
+ name: "get_cart_items",
+ description: "Retrieves items currently in the user's shopping cart.",
+ inputSchema: { type: "object", properties: {} },
+ async execute(input, { signal }) {
+ return await cartService.getItems({ signal });
+ },
+ annotations: { readOnlyHint: true },
+}, {
+ signal: controller.signal,
+ exposedTo: ["https://checkout.example.com"],
+});
+```
+
+* **Mutual opt-in handshake**: Cross-origin tool discovery is a two-way opt-in. The tool provider frame authorizes the consumer origin via `exposedTo`, and the consumer frame must explicitly request that provider origin via `getTools({ fromOrigins: [...] })`. Without `fromOrigins`, `getTools()` queries only same-origin documents.
+* **Origin matching**: The registering document's own origin always has access. Origins specified in `exposedTo` are granted permission to discover the tool via `document.modelContext.getTools({ fromOrigins: [...] })` and execute it via `document.modelContext.executeTool()`.
+* **Security requirement**: Every origin in `exposedTo` MUST be potentially trustworthy (HTTPS or localhost). Passing an invalid or non-secure origin causes `registerTool()` to reject with a `SecurityError`.
+* **Scope**: `exposedTo` controls in-page cross-document discovery across frames in the document tree.
+
## Defining Parameters
Parameters (params) are defined using the `inputSchema` property. This must be a **JSON Schema** object that describes the structured data the tool expects.
@@ -54,6 +89,8 @@ await document.modelContext.registerTool({
## Execution Patterns
+The `execute` callback always receives two arguments: the input object, and an options object carrying an `AbortSignal` — `execute(inputObject, { signal })`.
+
### When to use `async execute`
Use `async` when the tool involves operations that return a Promise or take time to complete:
- **Network calls**: Fetching data from an API.
@@ -61,14 +98,14 @@ Use `async` when the tool involves operations that return a Promise or take time
- **External Events**: Waiting for a specific state change or animation to finish.
```javascript
-async execute(input) {
- const response = await fetch(`/api/data/${input.id}`);
+async execute(input, { signal }) {
+ const response = await fetch(`/api/data/${input.id}`, { signal });
return await response.json();
}
```
### When to use `execute` (Synchronous)
-Use a standard synchronous function for immediate operations:
+Use a standard synchronous function for immediate operations. A synchronous tool runs to completion before cancellation can be observed, so it can ignore the signal:
- **Pure logic**: Math, filtering, or sorting data already in memory.
- **Synchronous state**: Reading from `localStorage` or a synchronous state manager.
@@ -78,6 +115,174 @@ execute(input) {
}
```
+### Cancelling in-flight executions
+
+Cancellation is initiated by the user or the agent. **MANDATORY:** Any tool that performs network requests or other long-running async work MUST honor `signal`, otherwise cancelled executions keep consuming resources and can write stale data into the UI after the agent has moved on.
+
+* **APIs that accept a signal** (`fetch()`, `addEventListener()`, `ReadableStream` readers): pass `signal` straight through.
+* **APIs that do not** (`setTimeout`, `setInterval`, polling loops, `await`-heavy pipelines): call `signal.throwIfAborted()` between steps, and/or reject on `signal.addEventListener('abort', ...)`. Timers accept no signal, so you must clear them yourself in the abort listener.
+
+```javascript
+await document.modelContext.registerTool({
+ name: "fetch_tool",
+ description: "Fetch the text content of a URL and show it on the page.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ url: { type: "string", description: "The URL to fetch" },
+ priority: {
+ type: "string",
+ enum: ["high", "low", "auto"],
+ description: "Relative network priority for the request",
+ },
+ },
+ required: ["url"],
+ },
+ execute: async ({ url, priority }, { signal }) => {
+ const output = document.querySelector("pre");
+ output.textContent = "Loading…";
+ try {
+ // Passing `signal` aborts the network request the moment execution is cancelled.
+ const response = await fetch(url, { priority, signal });
+ const text = await response.text();
+ output.textContent = text;
+ return text;
+ } catch (err) {
+ // Roll back the UI state this execution set, so a cancelled run leaves no trace.
+ output.textContent = "";
+ // Re-throw, including AbortError: it carries the caller's cancellation reason.
+ throw err;
+ }
+ },
+ annotations: { readOnlyHint: true }
+});
+```
+
+## Flagging Consequential Tools
+
+Since Chrome 154, `annotations` supports `consequentialHint`. Set it to `true` for tools that take high-stakes, irreversible, or real-world actions — booking travel, moving money, sending messages, or deleting data. It signals agents to request explicit user confirmation before execution.
+
+```javascript
+await document.modelContext.registerTool({
+ name: 'book_flight',
+ description: 'Book a flight for the user with confirmed flight details.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ flightId: { type: 'string', description: 'ID of the flight to book' },
+ passengers: { type: 'number', description: 'Number of tickets to purchase' },
+ },
+ required: ['flightId', 'passengers'],
+ },
+ execute: async ({ flightId, passengers }, { signal }) => {
+ // Forward `signal` to the transaction API to honor cancellation:
+ return await bookFlightReservation({ flightId, passengers }, { signal });
+ },
+ annotations: {
+ readOnlyHint: false, // This tool mutates state (it makes a booking).
+ consequentialHint: true, // Spends money and is not trivially reversible.
+ untrustedContentHint: false, // Output is first-party data, not third-party content.
+ }
+});
+```
+
+**MANDATORY:** Treat `consequentialHint` as a hint, not an enforcement mechanism. It does not block execution on its own, and browsers that predate the hint will not prompt at all. Keep whatever in-app confirmation the action already warrants.
+
+## Flagging Debugging Tools
+
+Since Chrome 156, `annotations` supports `debugging`. Set `annotations.debugging` to `true` for tools built for debugging and developer tooling rather than end-user tasks. Examples: dumping internal app state, toggling feature flags, or seeding test data. This lets agents tell developer-only tools apart from tools meant to act for the user. It defaults to `false`. In-page agents and test harnesses can read it from `RegisteredTool.annotations.debugging` via `getTools()`.
+
+```javascript
+await document.modelContext.registerTool({
+ name: "dump_app_state",
+ description: "Returns a snapshot of the internal application store for debugging.",
+ execute() {
+ return appStore.getState();
+ },
+ annotations: {
+ readOnlyHint: true, // Only reads state.
+ debugging: true, // Developer tooling, not an end-user action.
+ }
+});
+```
+
+## In-Page Agents and Testing (`getTools` and `executeTool`)
+
+**Web pages do not need `getTools()` or `executeTool()` to expose tools to AI agents.** Simply calling `document.modelContext.registerTool()` is all that is required for browser agents, browser extensions, DevTools, and system-level assistants to discover and execute your tools out-of-band.
+
+The `getTools()` and `executeTool()` methods exist specifically for consumers running inside the JavaScript environment:
+1. **In-page JavaScript agents:** An AI assistant, copilot widget, or chat interface embedded directly in the page (or running inside an `<iframe>`) that needs to discover what tools the surrounding page or accessible frames in the document tree offer, and invoke them on behalf of the user.
+2. **Automated testing and debugging:** Test suites (such as Playwright, Vitest, or in-browser unit tests) that inspect registered tool metadata and simulate agent tool invocations without requiring a live external LLM harness.
+
+### Discovering available tools with `getTools()`
+
+In-page agents call `document.modelContext.getTools()` to retrieve an array of `RegisteredTool` objects from the current document and any accessible frames in the document tree.
+
+Since Chrome 155, `RegisteredTool.inputSchema` is returned directly as a JavaScript object (a deep copy of the schema supplied at registration). Mutating this object does not alter the registered tool's actual schema.
+
+```javascript
+// Example: An in-page AI assistant discovering tools available on the page:
+const tools = await document.modelContext.getTools();
+
+// In-page agents can listen for tools being registered or unregistered dynamically:
+document.modelContext.addEventListener("toolchange", async () => {
+ const updatedTools = await document.modelContext.getTools();
+ console.log(`Active tools updated: ${updatedTools.map((t) => t.name).join(", ")}`);
+});
+```
+
+To discover tools registered inside cross-origin descendant iframes (which must explicitly grant access via `exposedTo` during registration), pass `fromOrigins` in the options dictionary:
+
+```javascript
+// Query tools registered in the embedded cart frame that exposed them to this checkout origin:
+const cartTools = await document.modelContext.getTools({
+ fromOrigins: ["https://cart.example.com"],
+});
+```
+
+### Invoking tools with `executeTool()`
+
+In-page agents and test scripts call `document.modelContext.executeTool(tool, inputObject, options)` to execute a registered tool. The tool runs on the document where it was registered, and the promise resolves to the stringified result returned by the tool's `execute` callback.
+
+Since Chrome 155, `executeTool()` accepts a plain JavaScript object directly for `inputObject`, matching the input format your tool's `execute` callback receives.
+
+```javascript
+// 1. Discover the tool (typically done during agent initialization or test setup):
+const tools = await document.modelContext.getTools();
+const areaTool = tools.find((t) => t.name === "calculate_area");
+
+if (areaTool) {
+ const controller = new AbortController();
+ // Example input payload matching the tool's inputSchema:
+ const inputObject = { width: 10, height: 20 };
+ const options = { signal: controller.signal };
+
+ // 2. Pass input arguments as a JavaScript object, with a JSON string fallback for Chrome <155:
+ let resultString;
+ try {
+ resultString = await document.modelContext.executeTool(areaTool, inputObject, options);
+ } catch (err) {
+ if (err?.message?.startsWith("Failed to parse input")) {
+ resultString = await document.modelContext.executeTool(
+ areaTool,
+ JSON.stringify(inputObject),
+ options
+ );
+ } else {
+ // Re-throw real tool execution or cancellation errors:
+ throw err;
+ }
+ }
+
+ console.log("Execution output string:", resultString);
+}
+```
+
+The returned promise rejects if:
+* `inputObject` is not an object or cannot be serialized to a JSON string (e.g. circular references or `BigInt` values). Note that values omitted by JSON serialization (such as functions and `undefined`) will be omitted from the object received by the tool rather than causing a rejection.
+* The execution is aborted via `options.signal`.
+* The tool was unregistered prior to execution or encounters an unhandled runtime error.
+
## Tool Factory Pattern
To pass context (like stores or application instances) to your tools, use factory functions.
@@ -100,8 +305,16 @@ export function createInventoryTool(inventoryManager) {
* **annotations**: (Optional) A dictionary for tool metadata.
* **readOnlyHint**: (Optional) Set to `true` if the tool does not modify any state and only reads data. This helps agents decide when it is safe to call the tool.
+ * **consequentialHint**: (Optional, Chrome 154+) Set to `true` for high-stakes, irreversible, or real-world actions so agents request user confirmation first.
+ * **untrustedContentHint**: (Optional) Set to `true` when the tool returns content your site does not control, such as user-generated text or third-party API responses.
+ * **debugging**: (Optional, Chrome 156+) Set to `true` when the tool is meant for debugging and developer tooling, not end-user tasks. Defaults to `false`.
+* **Registration Options**:
+ * **signal**: (Optional) An `AbortSignal` used to unregister the tool when it is no longer needed.
+ * **exposedTo**: (Optional) An array of secure origin strings controlling which documents in the document tree are allowed to discover and execute the tool across frame boundaries.
+* **Tool Discovery Options (`ModelContextGetToolOptions`)**:
+ * **fromOrigins**: (Optional) An array of secure origin strings to query in accessible frames. Calling `getTools()` without `fromOrigins` queries only same-origin documents.
* **Return Format**: The `execute` function can return any value (object, array, string, number, boolean). Select a structure that best serves your specific use case while ensuring the content is optimized for the LLM to process. The output may encompass raw data, specific error logs, or direct instructions to influence the agent's next action.
-* **Secure Context**: WebMCP requires HTTPS.
+* **Secure Context**: WebMCP requires HTTPS. All origins in `exposedTo` and `fromOrigins` must also be potentially trustworthy.
* **Deprecated/Removed**: `navigator.modelContext` (deprecated in Chromium 150), `unregisterTool()`, `provideContext()`, and `clearContext()` are no longer supported.
## Fallback strategies
@@ -111,8 +324,7 @@ document.modelContext is not natively supported by any major browser yet.
The WebMCP Imperative API should be used with feature detection to ensure compatibility with browsers that do not yet support WebMCP.
```javascript
-const modelContext = document.modelContext || navigator.modelContext;
-if (modelContext && 'registerTool' in modelContext) {
+if ('modelContext' in document) {
// Register tools
}
```