Keep your coding agent up to date with the latest web best practices
Release v0.0.111
github-actions[bot]c147a172247c
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 15e2892..d6d27ad 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -7,7 +7,7 @@{"name": "modern-web-guidance","source": "./",- "description": "Google Chrome's agent skills collection",+ "description": "Keep your coding agent up to date with the latest web best practices","version": "0.0.111"}]diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex b8c2431..f0dd7f3 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "modern-web-guidance",- "description": "Google Chrome's agent skills collection",+ "description": "Keep your coding agent up to date with the latest web best practices","version": "0.0.111","author": {"name": "Google Chrome"diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.jsonindex ac6a16a..f0dd7f3 100644--- a/.cursor-plugin/plugin.json+++ b/.cursor-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.109",+ "version": "0.0.111","author": {"name": "Google Chrome"}diff --git a/README.md b/README.mdindex 2ccb3b4..9498f0e 100644--- a/README.md+++ b/README.md@@ -1,226 +1,369 @@# Modern Web Guidance-This curated collection of skills, tools, and AI-ready documentation injects Chrome's web platform knowledge directly into your workflow, ensuring your coding agent builds apps that are modern, fast, and secure by default.+Inject web platform expertise, best practices, and modern API patterns directly into your AI coding agents.-#### Skill Coverage in `v0.0.111`+modern-web-guidance is an agent skill (aka [SKILL.md](http://SKILL.md)) to help ensure that when your coding agent works on a web application, it uses modern, high-performance, accessible, and secure APIs rather than legacy, outdated workarounds.++<!-- <LIKE A DEMO VIDEO LOOP OR SOMETHING?> -->++## Why?++AI coding agents often default to older patterns/libraries because their training data contains vast amounts of legacy code. This often leads them to generate unnecessary, bloated JavaScript for common tasks that are now native.++### Bridging the "High-Recall, Low-Coverage" Knowledge Gap++Every developer knows about the **knowledge cutoff**—but for coding agents, the real issue is **knowledge representation**. Even for web platform features released over the last 10 years, our current frontier models lack the density and coverage of high-quality, modern implementation patterns. The models have *high recall* (they know an API exists) but *low coverage* of actual production best practices.++**This repository bridges that gap.** We don't waste your agent's context on general knowledge it already has. Instead, we inject targeted, high-density, expert-curated guidance specifically focused on:++1. Advanced browser APIs models consistently misuse or fail to structure.+2. High-performance, accessible, and secure patterns that eliminate legacy bloat.+3. Responsible cross-browser fallback strategies that models are incapable of inventing on-the-fly.++## What++Our content is evergrowing, but we cover from the bleeding edge of the web platform, through the past several years of new features handling fallback strategies. But **we don't waste your tokens** on stuff models already know.++### Core disciplines++Just a tiny sampling of the **134+ use-case-centric guides**:++* **User Experience**: Smooth and modern visual states: View Transitions, CSS `scrollbar-color` styling, high-contrast adaptation, entry/exit transition animations, parallax scrolling.+* **CSS layout:** container queries (both size and style queries), modern color spaces (`oklch`, `color-mix`) and `subgrid`, text-wrap tuning (`balance`, `pretty`), subgrid, and typography line height trimming (`text-box`)+* **Performance**: instant page preloading, Interaction to Next Paint (INP) diagnostics, and background task scheduling using `scheduler.yield`.+* **Forms**: auto-sizing input fields (`field-sizing: content`), precise validation with `:user-invalid`, and accent color synchronization.+* **Native UI Components**: Direct control over dialogs, CSS Anchor Positioning for tooltips, same-document and cross-document View Transitions, and the Popover API.+* **Accessibility & Security**: accessible error announcements, keyboard focus management.+* **Built-in AI**: Leveraging local, on-device client models (native Language Detection, Summarization, and Translation APIs).++#### Full Skill Coverage (v0.0.111)<details>-<summary><strong>83 web features with implementation guidance from Chrome's experts</strong>: `::backdrop`, `:autofill`, `:has()`, `:not()`, `:user-valid and :user-invalid`, `@starting-style`, `<details>`, `<dialog closedby>`, `<dialog>`, `<link rel="expect">`, `<link rel="preload">`, `AbortController and AbortSignal`, `accent-color`, `Active view transition`, `Anchor position container queries`, `Anchor positioning`, `blocking="render"`, `calc-size()`, `color-scheme`, `Container queries`, `Container scroll-state queries`, `content-visibility`, `Cross-document view transitions`, `Customizable <select>`, `Email, telephone, and URL <input> types`, `enterkeyhint`, `Event timing`, `Fetch`, `Fetch priority`, `fetchLater`, `field-sizing`, `font-size-adjust`, `Form-associated WebMCP attributes`, `hidden="until-found"`, `image-set()`, `Individual transform properties`, `inert`, `inputmode`, `Interest invokers`, `interpolate-size`, `Intersection observer`, `Intl.DurationFormat`, `Invoker commands`, `Language detector`, `light-dark()`, `linear() easing`, `Long animation frames`, `Masks`, `moveBefore()`, `Mutually exclusive <details> elements`, `Navigation API`, `navigator.modelContext`, `overlay`, `Page visibility`, `Page visibility state`, `Popover`, `popover="hint"`, `prefers-color-scheme media query`, `prefers-contrast media query`, `prefers-reduced-motion media query`, `Registered custom properties`, `Scheduler API`, `Scroll snap`, `Scroll-driven animations`, `scroll-initial-target`, `scrollbar-color`, `scrollbar-width`, `scrollend`, `scrollIntoView()`, `sibling-count() and sibling-index()`, `sin(), cos(), tan(), asin(), acos(), atan(), and atan2() (CSS)`, `Speculation rules`, `Summarizer`, `Temporal`, `text-box`, `text-wrap`, `text-wrap: balance`, `text-wrap: pretty`, `Top-level await`, `transition-behavior`, `Translator`, `View transitions`, `view-transition-class`</summary>--- **[::backdrop](https://webstatus.dev/features/backdrop), [<dialog>](https://webstatus.dev/features/dialog), [overlay](https://webstatus.dev/features/overlay), [Popover](https://webstatus.dev/features/popover), [@starting-style](https://webstatus.dev/features/starting-style), [transition-behavior](https://webstatus.dev/features/transition-behavior)**- - **animate-to-from-top-layer**: Animate elements such as dialogs, popovers, and tooltips as they're entering/exiting the top layer.-- **[:autofill](https://webstatus.dev/features/autofill)**- - **autofill-address-form**: Build an address form with correct autocomplete attributes and autofill support.- - **autofill-highlight-inputs**: Use CSS to highlight form fields that have been autofilled by the browser and not edited by the user.-- **[:has()](https://webstatus.dev/features/has), [:not()](https://webstatus.dev/features/not)**- - **child-state-based-styling**: Build a component that changes its styling based on the state of one of its child elements. For example, a component that renders in light or dark mode based on whether a theme toggle is checked (or not).- - **content-based-styling**: Build a component that changes its layout based on whether it contains specific child elements (or not). For example, if the component contains an image, use a multi-column layout, otherwise default to a single-column layout.-- **[:user-valid and :user-invalid](https://webstatus.dev/features/user-pseudos)**- - **accessible-error-announcement**: Synchronize programmatic accessibility states (like aria-invalid) with the visual :user-invalid state to ensure screen reader users receive error feedback only after interaction, mirroring the visual experience.- - **required-field-feedback**: Provide error message for required form fields that were skipped or left empty *only* after user interaction, to avoid preemptive errors and ensure feedback is timely and contextually relevant to the user's flow.- - **select-menu-interaction**: 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**: 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.- - **style-parent-with-has**: Style parent elements of a form field (e.g. labels or fieldsets) when the field is invalid.-- **[@starting-style](https://webstatus.dev/features/starting-style), [transition-behavior](https://webstatus.dev/features/transition-behavior)**- - **animate-element-entry-exit**: Smoothly hide/show elements as they are added/removed from the DOM or as their display values are toggled.-- **[<details>](https://webstatus.dev/features/details), [Mutually exclusive <details> elements](https://webstatus.dev/features/details-name), [hidden="until-found"](https://webstatus.dev/features/hidden-until-found)**- - **search-hidden-content**: 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.-- **[<dialog closedby>](https://webstatus.dev/features/dialog-closedby)**- - **light-dismiss-a-dialog**: Create a modal dialog that can be closed via light dismiss (i.e. clicking or tapping outside of the dialog)- - **platform-controls-dismiss-dialog**: Create a modal dialog that can be closed via standard platform-specific user actions, such as pressing the `Esc` key on desktop platforms, or a "back" or "dismiss" gesture on mobile platforms-- **[<dialog>](https://webstatus.dev/features/dialog), [Invoker commands](https://webstatus.dev/features/invoker-commands), [Popover](https://webstatus.dev/features/popover)**- - **declarative-dialog-popover-control**: Toggle the visibility of a dialog or popover from a button without writing JavaScript.-- **[AbortController and AbortSignal](https://webstatus.dev/features/aborting), [fetchLater](https://webstatus.dev/features/fetchlater)**- - **batch-analytics-events**: 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.- - **full-session-analytics**: Reliably track analytics, errors, and telemetry data across the user's entire page visit, and defer sending of the data until the user leaves the page.-- **[accent-color](https://webstatus.dev/features/accent-color)**- - **brand-consistent-forms**: Match checkboxes, radio buttons, range sliders, and progress bars to your site's color palette without replacing them with custom components.-- **[accent-color](https://webstatus.dev/features/accent-color), [color-scheme](https://webstatus.dev/features/color-scheme), [light-dark()](https://webstatus.dev/features/light-dark), [prefers-color-scheme media query](https://webstatus.dev/features/prefers-color-scheme)**- - **browser-ui-color-theme**: Configure built-in browser UI (e.g. scrollbars, form controls, etc) to respect the user's light/dark theme preference.-- **[Active view transition](https://webstatus.dev/features/active-view-transition), [View transitions](https://webstatus.dev/features/view-transitions)**- - **directional-navigation-transitions**: Animate visual state changes to reflect the direction of a user's navigational flow, such as sliding new content in from the right when advancing forward or from the left when returning to a previous screen.-- **[Anchor position container queries](https://webstatus.dev/features/container-anchor-position-queries), [Popover](https://webstatus.dev/features/popover)**- - **position-aware-tooltips**: 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.-- **[Anchor positioning](https://webstatus.dev/features/anchor-positioning), [prefers-reduced-motion media query](https://webstatus.dev/features/prefers-reduced-motion)**- - **anchor-positioning-tab-underline**: Transition an element seamlessly between two target element positions. For example, moving a selected tab underline between the previously selected tab and the currently selected tab.-- **[Anchor positioning](https://webstatus.dev/features/anchor-positioning), [Interest invokers](https://webstatus.dev/features/interest-invokers), [Popover](https://webstatus.dev/features/popover), [popover="hint"](https://webstatus.dev/features/popover-hint)**- - **interest-triggered-tooltips**: Show a tooltip or supplemental information when a user hovers over, focuses on, or long-presses an interactive element, without requiring a click.-- **[Anchor positioning](https://webstatus.dev/features/anchor-positioning), [Popover](https://webstatus.dev/features/popover)**- - **persistent-app-tours**: Create persistent onboarding walkthroughs using tethered native overlays that stay open during user interaction.- - **resilient-context-menus-and-nested-dropdowns**: 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.-- **[Anchor positioning](https://webstatus.dev/features/anchor-positioning), [Popover](https://webstatus.dev/features/popover), [sibling-count() and sibling-index()](https://webstatus.dev/features/sibling-count), [transition-behavior](https://webstatus.dev/features/transition-behavior)**- - **persistent-toast-notifications**: Create non-intrusive toast and overlay notifications for persistent, stackable messaging and state communication.-- **[blocking="render"](https://webstatus.dev/features/blocking-render), [Cross-document view transitions](https://webstatus.dev/features/cross-document-view-transitions), [<link rel="expect">](https://webstatus.dev/features/link-rel-expect)**- - **consistent-cross-document-transitions**: Ensure critical page state is loaded and stable before initiating a cross-document view transition. This means critical CSS styles are loaded and applied, critical JavaScript is loaded and run, and the HTML visible for the user's initial view of the page has been parsed before the transition runs.-- **[blocking="render"](https://webstatus.dev/features/blocking-render)**- - **flicker-free-client-side-ab-testing**: Deliver and render A/B tests, multi-variate tests, or other experiments using client-side JavaScript to alter or inject HTML, CSS, and JavaScript without the original content showing first before flickering or flashing to show the experiment content.-- **[calc-size()](https://webstatus.dev/features/calc-size), [interpolate-size](https://webstatus.dev/features/interpolate-size)**- - **animate-to-intrinsic-sizes**: Smoothly animate interactive components (like accordions, menus, and expanding cards) to and from their natural dimensions.- - **calculate-with-intrinsic-sizes**: Calculate the size of an element based on its intrinsic size, while ensuring it fits within given design constraints.-- **[color-scheme](https://webstatus.dev/features/color-scheme), [prefers-color-scheme media query](https://webstatus.dev/features/prefers-color-scheme), [scrollbar-color](https://webstatus.dev/features/scrollbar-color)**- - **adapt-scrollbar-to-light-dark-preferences**: Ensure the scrollbar visually matches the user's operating system light/dark mode preference-- **[color-scheme](https://webstatus.dev/features/color-scheme), [light-dark()](https://webstatus.dev/features/light-dark)**- - **component-specific-light-dark-theme**: Create component-specific themes by forcing explicit color schemes on individual UI elements, giving users theme choices that are decoupled from their global operating system preferences-- **[Container queries](https://webstatus.dev/features/container-queries)**- - **fluid-scaling**: Scale items like font size, spacing, and media sizes smoothly based on the parent container's size rather than using fixed breakpoints- - **size-aware-styling**: Build a component whose styles can be conditionally dependent on its own width or height, rather than the width or height of the viewport. For example a card component that can change its layouts depending on how large it is, or a call-to-action button that can conditionally display helper text based on its width.-- **[Container scroll-state queries](https://webstatus.dev/features/container-scroll-state-queries)**- - **carousel-snap-highlights**: Visually highlight the currently snapped non-interactive item in scroll-snapping carousels, galleries, or full-page swipe experiences. For example, expanding a card when snapped, or revealing hidden content.- - **scroll-position-aware-elements**: 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.- - **scrollability-affordance-hints**: 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.-- **[content-visibility](https://webstatus.dev/features/content-visibility), [hidden="until-found"](https://webstatus.dev/features/hidden-until-found)**- - **defer-rendering-heavy-content**: Reduce rendering times in content-heavy web pages (e.g. pages with long feeds, lots of articles, or complex dashboards), by deferring rendering for any content that is not immediately visible to the user.-- **[content-visibility](https://webstatus.dev/features/content-visibility)**- - **efficient-background-processing**: Conserve system resources and battery life by pausing background JavaScript execution (such as `<canvas>` animations, WebGL rendering, or high-frequency WebSocket data polling) when the component is off-screen and then resume them just-in-time when they scroll back into view.- - **faster-spa-view-transitions**: Enable faster transitions back to previously visited views in a Single-Page Application (SPA) by preserving their structural DOM state instead of destroying and rebuilding them on every navigation.- - **interactions-in-complex-layouts**: 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.-- **[Cross-document view transitions](https://webstatus.dev/features/cross-document-view-transitions), [Navigation API](https://webstatus.dev/features/navigation), [View transitions](https://webstatus.dev/features/view-transitions)**- - **cross-document-transitions**: Create smooth, seamless transitions between full page navigations, such as cross-fades, custom reveal effects, or morphing of content from one page to the next.-- **[Customizable <select>](https://webstatus.dev/features/customizable-select)**- - **animated-select-picker**: Create a custom select component whose dropdown is animated. For example, the menu fades or slides into view, or the options animate upon selection.- - **branded-select-styling**: Create custom select elements whose button, picker, arrow icon, and checkmark all seamlessly match your brand or design system's typography, colors, spacing, and border treatments.- - **custom-select-picker-layouts**: Create custom select pickers whose options are positioned in unique or interesting ways, rather than the traditional stacked list of options.- - **rich-media-picker**: Create a custom select component whose options can contain complex HTML formatting (e.g. images, icons, and other rich formatting) rather than just plain text.-- **[Email, telephone, and URL <input> types](https://webstatus.dev/features/input-email-tel-url), [inputmode](https://webstatus.dev/features/inputmode)**- - **autofill-sign-in-form**: Build a sign-in form with correct autocomplete values and autofill support.- - **autofill-sign-up-form**: Build a sign-up form with correct autocomplete values and autofill support.-- **[enterkeyhint](https://webstatus.dev/features/enterkeyhint), [Email, telephone, and URL <input> types](https://webstatus.dev/features/input-email-tel-url), [inputmode](https://webstatus.dev/features/inputmode)**- - **autofill-payment-form**: Build a payment form that collects card details with correct autocomplete values and autofill support.-- **[Event timing](https://webstatus.dev/features/event-timing), [Long animation frames](https://webstatus.dev/features/long-animation-frames)**- - **identify-inp-causes**: Identify slow running JavaScript that is impacting INP metric-- **[Fetch](https://webstatus.dev/features/fetch), [Fetch priority](https://webstatus.dev/features/fetch-priority)**- - **deprioritize-background-fetches**: Deprioritize background data fetches made with the Fetch API to prevent network contention with user-initiated requests.-- **[Fetch priority](https://webstatus.dev/features/fetch-priority)**- - **optimize-image-priority**: Optimize the loading priority of Largest Contentful Paint (LCP) candidate images and deprioritize non-critical images to reduce critical resource load delays.- - **optimize-script-priority**: 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.-- **[Fetch priority](https://webstatus.dev/features/fetch-priority), [<link rel="preload">](https://webstatus.dev/features/link-rel-preload)**- - **optimize-preload-priority**: Optimize the relative priority of preloaded content to reduce critical resource load delays.-- **[field-sizing](https://webstatus.dev/features/field-sizing)**- - **form-fields-automatically-fit-contents**: Allow form fields to grow and shrink to fit the user input, e.g. as the user types or selects a different option. Apply maximum and minimum size limits to create dynamic and responsive form fields that conform with the page design.-- **[font-size-adjust](https://webstatus.dev/features/font-size-adjust)**- - **visually-stable-font-fallbacks**: 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**: 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.-- **[Form-associated WebMCP attributes](https://webstatus.dev/features/declarative-webmcp)**- - **agentic-forms**: Expose client-side functionality as tools to AI agents by annotating standard HTML forms with WebMCP attributes.-- **[image-set()](https://webstatus.dev/features/image-set)**- - **resolution-optimized-pseudo-elements**: Use resolution-optimized images in CSS pseudo-elements (such as `::before` and `::after`) to reduce the number of DOM nodes.- - **deliver-optimized-decorative-images**: Deliver optimized decorative images (such as backgrounds, UI icons, or complex masks) by simultaneously providing next-generation image formats (like AVIF or WebP) alongside multiple pixel densities (like 1x and 2x) so the browser can dynamically negotiate the best combination of file size and visual quality for the user's device capabilities.-- **[Individual transform properties](https://webstatus.dev/features/individual-transforms)**- - **individual-transform-properties**: Animate or override individual CSS transform properties (e.g. translate, rotate, scale) independently of other transform properties on a single element.-- **[inert](https://webstatus.dev/features/inert), [Intersection observer](https://webstatus.dev/features/intersection-observer), [Popover](https://webstatus.dev/features/popover), [Registered custom properties](https://webstatus.dev/features/registered-custom-properties), [Scroll-driven animations](https://webstatus.dev/features/scroll-driven-animations), [scroll-initial-target](https://webstatus.dev/features/scroll-initial-target), [Scroll snap](https://webstatus.dev/features/scroll-snap)**- - **navigation-drawer**: Create a navigation drawer component that, when triggered from a menu button, slides in from the side overlayed on top of existing page content, and slides out when dismissed (by swiping away, tapping outside, or pressing escape).-- **[Interest invokers](https://webstatus.dev/features/interest-invokers)**- - **interest-triggered-action-previews**: Show a live preview of a button's effect when a user signals interest (e.g. hovering, focusing, or long-pressing) but before they commit to clicking.-- **[Intl.DurationFormat](https://webstatus.dev/features/intl-duration-format), [Temporal](https://webstatus.dev/features/temporal)**- - **format-human-readable-durations**: Present elapsed time or durations to users in a readable, localized format, with the flexibility to display either detailed unit breakdowns (e.g., "1 hour and 30 minutes") or total unit counts (e.g., "90 minutes") depending on context.-- **[Invoker commands](https://webstatus.dev/features/invoker-commands)**- - **declarative-button-actions**: Declaratively connect a button to any element to trigger custom, application-specific actions using declarative button commands, invoker commands, button commands, custom commands, or declarative toggle actions.-- **[Language detector](https://webstatus.dev/features/languagedetector)**- - **language-detection**: Detect the language of user-generated content or already present site content.-- **[linear() easing](https://webstatus.dev/features/linear-easing)**- - **physics-based-easing**: Create custom, physics-based animation and transition effects, like bounce and spring, that feel more natural and engaging than traditional easing curves.-- **[Long animation frames](https://webstatus.dev/features/long-animation-frames)**- - **identify-heavy-scripts**: Identify the scripts most responsible for long animation frames-- **[Masks](https://webstatus.dev/features/masks), [Registered custom properties](https://webstatus.dev/features/registered-custom-properties)**- - **interactive-content-reveal**: Create interactive reveal effects, such as a spotlight that follows the user's pointer to uncover details within an image or UI section.-- **[moveBefore()](https://webstatus.dev/features/move-before)**- - **move-dom-element-without-losing-state**: Move or reparent a DOM element without losing important element state, such as interactivity states (:focus/:active), <iframe> loading state, animation/transition state, etc- - **persistent-top-layer-ui**: Keep a modal dialog, fullscreen element, or native popover visibly open and functionally active when its underlying DOM node is moved or reparented in the DOM.-- **[navigator.modelContext](https://webstatus.dev/features/navigator-modelcontext)**- - **agentic-javascript-tools**: Programmatically register client-side JavaScript functions as tools for AI agents using the WebMCP Imperative API.-- **[Page visibility](https://webstatus.dev/features/page-visibility), [Page visibility state](https://webstatus.dev/features/page-visibility-state)**- - **detect-initial-visibility-state**: Reliably determine whether a page was initially loaded in the background, even in cases where the script is loaded asynchronously after the user foregrounded the page.-- **[Page visibility state](https://webstatus.dev/features/page-visibility-state)**- - **calculate-total-foreground-time**: Calculate the total time a user actually spent viewing a page, excluding periods when the tab was in the background.-- **[prefers-contrast media query](https://webstatus.dev/features/prefers-contrast), [scrollbar-color](https://webstatus.dev/features/scrollbar-color)**- - **adapt-scrollbar-to-contrast-preferences**: Enhance scrollbar visibility for users who prefer high-contrast interfaces-- **[Scheduler API](https://webstatus.dev/features/scheduler)**- - **break-up-long-tasks**: 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.- - **schedule-tasks-by-priority**: Schedule tasks with different priorities to ensure critical work runs first while background work is deferred.-- **[Scroll-driven animations](https://webstatus.dev/features/scroll-driven-animations), [Scroll snap](https://webstatus.dev/features/scroll-snap)**- - **carousel-slide-effects**: Create a carousel of slides with images or other visual elements, where each slide animates as they enter/center/exit their scroller. For example, the slides may fade-in/fade-out, rotate, get bigger or smaller, etc.-- **[Scroll-driven animations](https://webstatus.dev/features/scroll-driven-animations)**- - **parallax-scroll-effects**: Create scroll-based effects (such as parallax) where foreground and background layers move at different rates, creating a sense of depth as the user scrolls.- - **scroll-entry-exit-effects**: Create fade-in, scale-up, or other complex reveal-type effects on elements as they enter and exit the scrollport (or viewport) while the user is scrolling.- - **scroll-progress-indicator**: 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.- - **scrollytelling**: 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.- - **shrinking-header-on-scroll**: Smoothly animate a fixed header or full-page cover on scroll to dynamically shrink, gain shadows, and transform its layout over a predefined scroll distance.-- **[scroll-initial-target](https://webstatus.dev/features/scroll-initial-target), [Scroll snap](https://webstatus.dev/features/scroll-snap)**- - **pull-to-reveal**: 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.-- **[scroll-initial-target](https://webstatus.dev/features/scroll-initial-target), [scrollIntoView()](https://webstatus.dev/features/scroll-into-view)**- - **scroll-target-on-load**: 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.-- **[scrollbar-color](https://webstatus.dev/features/scrollbar-color), [scrollbar-width](https://webstatus.dev/features/scrollbar-width)**- - **customize-scrollbar-color-and-thickness**: Customize the color or thickness of a scrollbar-- **[scrollend](https://webstatus.dev/features/scrollend)**- - **defer-work-until-scroll-ends**: Defer expensive operations like DOM updates, data fetching, analytics tracking, or layout recalculation until after scrolling completes to maintain smooth scroll performance.-- **[sibling-count() and sibling-index()](https://webstatus.dev/features/sibling-count)**- - **dynamic-sibling-animations**: Stagger animation or transition timing across sibling elements so each one starts after a computed delay based on its position in the sibling list.-- **[sibling-count() and sibling-index()](https://webstatus.dev/features/sibling-count), [sin(), cos(), tan(), asin(), acos(), atan(), and atan2() (CSS)](https://webstatus.dev/features/trig-functions)**- - **dynamic-sibling-styling**: Create dynamic visual spectrums or layout arrangements that automatically adapt to the number of elements in a group.-- **[Speculation rules](https://webstatus.dev/features/speculation-rules)**- - **improve-next-page-load-performance**: Improve page load performance by prefetching or prerendering pages that the user is likely to visit next.-- **[Summarizer](https://webstatus.dev/features/summarizer)**- - **summarizer**: Summarize text content using the on-device Summarizer API.-- **[Temporal](https://webstatus.dev/features/temporal)**- - **sequence-distributed-events**: Log and sequence operations in distributed microservices or high-throughput tracing environments by recording timestamps with nanosecond resolution.- - **calculate-event-differentials**: Calculate the duration and time remaining between dates and times.- - **capture-location-agnostic-data**: Record chronological data that should not change based on a user's location, such as birthdates, recurring alarms, or national holidays.- - **coordinate-global-events**: Schedule future meetings or events by explicitly binding them to a geographical IANA time zone so that event times remain accurate regardless of Daylight Saving Time (DST) transitions, "skipped" or "repeated" hours during clock changes.- - **manage-recurring-intervals**: Calculate recurring intervals for subscription billings or payroll cycles, automatically adjusting for edge cases such as month-end transitions (e.g., adding one month to January 31st) to ensure accurate period calculations.- - **model-partial-time-concepts**: Model date and time concepts that inherently lack a standard component (such as a specific year, day, or date) without using arbitrary placeholder values that introduce calculation errors.- - **stabilize-reactive-state**: Manage task deadlines or schedules in data-driven views without unexpected side effects from shared mutable state.- - **support-global-calendar-systems**: Display and calculate dates in non-Gregorian calendar systems (e.g., Islamic, Hebrew, or Chinese) accurately for international users.-- **[text-box](https://webstatus.dev/features/text-box)**- - **precise-text-alignment**: 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.-- **[text-wrap](https://webstatus.dev/features/text-wrap)**- - **prevent-text-wrapping**: Ensure the browser does not insert line breaks into text and will allow text to overflow its container.-- **[text-wrap: balance](https://webstatus.dev/features/text-wrap-balance), [text-wrap: pretty](https://webstatus.dev/features/text-wrap-pretty)**- - **improve-text-layout-and-legibility**: 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.-- **[Top-level await](https://webstatus.dev/features/top-level-await)**- - **conditional-async-dependencies**: Conditionally load or initialize async dependencies (such as importing polyfills for missing web features) without requiring complex orchestration across all of a page's script dependencies.-- **[Translator](https://webstatus.dev/features/translator)**- - **translator**: Translate text between languages using the on-device Translator API.-- **[View transitions](https://webstatus.dev/features/view-transitions)**- - **same-document-transitions**: Visually connect persisting elements across different page states or navigations in a Single Page Application (SPA) (e.g. expanding a product thumbnail into a full-bleed hero image) by smoothly morphing their size, position, or other styling properties.-- **[view-transition-class](https://webstatus.dev/features/view-transition-class), [View transitions](https://webstatus.dev/features/view-transitions)**- - **group-element-transitions**: Transition a group of similar elements simultaneously using the same transition logic, such as removing a product from a shopping cart and having all the other products animate into their new positions.+<summary>Includes expert guidance across <strong>85 modern web features</strong></summary>++- [::backdrop](https://web-platform-dx.github.io/web-features-explorer/features/backdrop/)+- [:autofill](https://web-platform-dx.github.io/web-features-explorer/features/autofill/)+- [:has()](https://web-platform-dx.github.io/web-features-explorer/features/has/)+- [:not()](https://web-platform-dx.github.io/web-features-explorer/features/not/)+- [:user-valid and :user-invalid](https://web-platform-dx.github.io/web-features-explorer/features/user-pseudos/)+- [@function](https://web-platform-dx.github.io/web-features-explorer/features/function/)+- [@starting-style](https://web-platform-dx.github.io/web-features-explorer/features/starting-style/)+- [<details>](https://web-platform-dx.github.io/web-features-explorer/features/details/)+- [<dialog closedby>](https://web-platform-dx.github.io/web-features-explorer/features/dialog-closedby/)+- [<dialog>](https://web-platform-dx.github.io/web-features-explorer/features/dialog/)+- [<link rel="expect">](https://web-platform-dx.github.io/web-features-explorer/features/link-rel-expect/)+- [<link rel="preload">](https://web-platform-dx.github.io/web-features-explorer/features/link-rel-preload/)+- [AbortController and AbortSignal](https://web-platform-dx.github.io/web-features-explorer/features/aborting/)+- [accent-color](https://web-platform-dx.github.io/web-features-explorer/features/accent-color/)+- [Active view transition](https://web-platform-dx.github.io/web-features-explorer/features/active-view-transition/)+- [Anchor position container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-anchor-position-queries/)+- [Anchor positioning](https://web-platform-dx.github.io/web-features-explorer/features/anchor-positioning/)+- [blocking="render"](https://web-platform-dx.github.io/web-features-explorer/features/blocking-render/)+- [calc-size()](https://web-platform-dx.github.io/web-features-explorer/features/calc-size/)+- [color-scheme](https://web-platform-dx.github.io/web-features-explorer/features/color-scheme/)+- [Container queries](https://web-platform-dx.github.io/web-features-explorer/features/container-queries/)+- [Container scroll-state queries](https://web-platform-dx.github.io/web-features-explorer/features/container-scroll-state-queries/)+- [content-visibility](https://web-platform-dx.github.io/web-features-explorer/features/content-visibility/)+- [Cross-document view transitions](https://web-platform-dx.github.io/web-features-explorer/features/cross-document-view-transitions/)+- [Customizable <select>](https://web-platform-dx.github.io/web-features-explorer/features/customizable-select/)+- [Email, telephone, and URL <input> types](https://web-platform-dx.github.io/web-features-explorer/features/input-email-tel-url/)+- [enterkeyhint](https://web-platform-dx.github.io/web-features-explorer/features/enterkeyhint/)+- [Event timing](https://web-platform-dx.github.io/web-features-explorer/features/event-timing/)+- [Fetch](https://web-platform-dx.github.io/web-features-explorer/features/fetch/)+- [Fetch priority](https://web-platform-dx.github.io/web-features-explorer/features/fetch-priority/)+- [fetchLater](https://web-platform-dx.github.io/web-features-explorer/features/fetchlater/)+- [field-sizing](https://web-platform-dx.github.io/web-features-explorer/features/field-sizing/)+- [font-size-adjust](https://web-platform-dx.github.io/web-features-explorer/features/font-size-adjust/)+- [Form-associated WebMCP attributes](https://web-platform-dx.github.io/web-features-explorer/features/declarative-webmcp/)+- [hidden="until-found"](https://web-platform-dx.github.io/web-features-explorer/features/hidden-until-found/)+- [image-set()](https://web-platform-dx.github.io/web-features-explorer/features/image-set/)+- [Individual transform properties](https://web-platform-dx.github.io/web-features-explorer/features/individual-transforms/)+- [inert](https://web-platform-dx.github.io/web-features-explorer/features/inert/)+- [inputmode](https://web-platform-dx.github.io/web-features-explorer/features/inputmode/)+- [Interest invokers](https://web-platform-dx.github.io/web-features-explorer/features/interest-invokers/)+- [interpolate-size](https://web-platform-dx.github.io/web-features-explorer/features/interpolate-size/)+- [Intersection observer](https://web-platform-dx.github.io/web-features-explorer/features/intersection-observer/)+- [Intl.DurationFormat](https://web-platform-dx.github.io/web-features-explorer/features/intl-duration-format/)+- [Invoker commands](https://web-platform-dx.github.io/web-features-explorer/features/invoker-commands/)+- [Language detector](https://web-platform-dx.github.io/web-features-explorer/features/languagedetector/)+- [light-dark()](https://web-platform-dx.github.io/web-features-explorer/features/light-dark/)+- [linear() easing](https://web-platform-dx.github.io/web-features-explorer/features/linear-easing/)+- [Long animation frames](https://web-platform-dx.github.io/web-features-explorer/features/long-animation-frames/)+- [Masks](https://web-platform-dx.github.io/web-features-explorer/features/masks/)+- [moveBefore()](https://web-platform-dx.github.io/web-features-explorer/features/move-before/)+- [Mutually exclusive <details> elements](https://web-platform-dx.github.io/web-features-explorer/features/details-name/)+- [Navigation API](https://web-platform-dx.github.io/web-features-explorer/features/navigation/)+- [navigator.modelContext](https://web-platform-dx.github.io/web-features-explorer/features/navigator-modelcontext/)+- [overlay](https://web-platform-dx.github.io/web-features-explorer/features/overlay/)+- [Page visibility](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility/)+- [Page visibility state](https://web-platform-dx.github.io/web-features-explorer/features/page-visibility-state/)+- [Popover](https://web-platform-dx.github.io/web-features-explorer/features/popover/)+- [popover="hint"](https://web-platform-dx.github.io/web-features-explorer/features/popover-hint/)+- [prefers-color-scheme media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-color-scheme/)+- [prefers-contrast media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-contrast/)+- [prefers-reduced-motion media query](https://web-platform-dx.github.io/web-features-explorer/features/prefers-reduced-motion/)+- [Registered custom properties](https://web-platform-dx.github.io/web-features-explorer/features/registered-custom-properties/)+- [Scheduler API](https://web-platform-dx.github.io/web-features-explorer/features/scheduler/)+- [Scroll snap](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap/)+- [Scroll snap events](https://web-platform-dx.github.io/web-features-explorer/features/scroll-snap-events/)+- [Scroll-driven animations](https://web-platform-dx.github.io/web-features-explorer/features/scroll-driven-animations/)+- [scroll-initial-target](https://web-platform-dx.github.io/web-features-explorer/features/scroll-initial-target/)+- [scrollbar-color](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-color/)+- [scrollbar-width](https://web-platform-dx.github.io/web-features-explorer/features/scrollbar-width/)+- [scrollend](https://web-platform-dx.github.io/web-features-explorer/features/scrollend/)+- [scrollIntoView()](https://web-platform-dx.github.io/web-features-explorer/features/scroll-into-view/)+- [sibling-count() and sibling-index()](https://web-platform-dx.github.io/web-features-explorer/features/sibling-count/)+- [sin(), cos(), tan(), asin(), acos(), atan(), and atan2() (CSS)](https://web-platform-dx.github.io/web-features-explorer/features/trig-functions/)+- [Speculation rules](https://web-platform-dx.github.io/web-features-explorer/features/speculation-rules/)+- [Summarizer](https://web-platform-dx.github.io/web-features-explorer/features/summarizer/)+- [Temporal](https://web-platform-dx.github.io/web-features-explorer/features/temporal/)+- [text-box](https://web-platform-dx.github.io/web-features-explorer/features/text-box/)+- [text-wrap](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap/)+- [text-wrap: balance](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-balance/)+- [text-wrap: pretty](https://web-platform-dx.github.io/web-features-explorer/features/text-wrap-pretty/)+- [Top-level await](https://web-platform-dx.github.io/web-features-explorer/features/top-level-await/)+- [transition-behavior](https://web-platform-dx.github.io/web-features-explorer/features/transition-behavior/)+- [Translator](https://web-platform-dx.github.io/web-features-explorer/features/translator/)+- [View transitions](https://web-platform-dx.github.io/web-features-explorer/features/view-transitions/)+- [view-transition-class](https://web-platform-dx.github.io/web-features-explorer/features/view-transition-class/)+</details>++<details>+<summary>Covers <strong>109 real-world developer use cases</strong> with production-ready code patterns</summary>++<h3>accessibility</h3>++- **[accessible-error-announcement](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/accessibility/accessible-error-announcement.md)**: Synchronize programmatic accessibility states (like aria-invalid) with the visual :user-invalid state to ensure screen reader users receive error feedback only after interaction, mirroring the visual experience.++<h3>built-in-ai</h3>++- **[language-detection](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/built-in-ai/language-detection.md)**: Detect the language of user-generated content or already present site content.+- **[summarizer](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/built-in-ai/summarizer.md)**: Summarize text content using the on-device Summarizer API.+- **[translator](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/built-in-ai/translator.md)**: Translate text between languages using the on-device Translator API.++<h3>forms</h3>++- **[animated-select-picker](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/animated-select-picker.md)**: Create a custom select component whose dropdown is animated. For example, the menu fades or slides into view, or the options animate upon selection.+- **[autofill-address-form](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-address-form.md)**: Build an address form with correct autocomplete attributes and autofill support.+- **[autofill-highlight-inputs](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-highlight-inputs.md)**: Use CSS to highlight form fields that have been autofilled by the browser and not edited by the user.+- **[autofill-payment-form](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-payment-form.md)**: Build a payment form that collects card details with correct autocomplete values and autofill support.+- **[autofill-sign-in-form](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-sign-in-form.md)**: Build a sign-in form with correct autocomplete values and autofill support.+- **[autofill-sign-up-form](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/autofill-sign-up-form.md)**: Build a sign-up form with correct autocomplete values and autofill support.+- **[brand-consistent-forms](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/brand-consistent-forms.md)**: Match checkboxes, radio buttons, range sliders, and progress bars to your site's color palette without replacing them with custom components.+- **[branded-select-styling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/branded-select-styling.md)**: Create custom select elements whose button, picker, arrow icon, and checkmark all seamlessly match your brand or design system's typography, colors, spacing, and border treatments.+- **[custom-select-picker-layouts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/custom-select-picker-layouts.md)**: Create custom select pickers whose options are positioned in unique or interesting ways, rather than the traditional stacked list of options.+- **[form-fields-automatically-fit-contents](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/form-fields-automatically-fit-contents.md)**: Allow form fields to grow and shrink to fit the user input, e.g. as the user types or selects a different option. Apply maximum and minimum size limits to create dynamic and responsive form fields that conform with the page design.+- **[required-field-feedback](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/required-field-feedback.md)**: Provide error message for required form fields that were skipped or left empty *only* after user interaction, to avoid preemptive errors and ensure feedback is timely and contextually relevant to the user's flow.+- **[rich-media-picker](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/rich-media-picker.md)**: Create a custom select component whose options can contain complex HTML formatting (e.g. images, icons, and other rich formatting) rather than just plain text.+- **[select-menu-interaction](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/forms/select-menu-interaction.md)**: Validate that a non-default option has been chosen in a select menu only after the user has interacted with the control.+- **[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>performance</h3>++- **[batch-analytics-events](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/batch-analytics-events.md)**: Debounce and batch multiple analytics events together in a single beacon to minimize network contention and reduce server load, while still delivering real-time updates.+- **[break-up-long-tasks](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/break-up-long-tasks.md)**: Break up heavy synchronous processing (complex computations and/or long loops) or DOM updates, to let the browser handle user input and repaint the screen.+- **[calculate-total-foreground-time](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/calculate-total-foreground-time.md)**: Calculate the total time a user actually spent viewing a page, excluding periods when the tab was in the background.+- **[conditional-async-dependencies](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/conditional-async-dependencies.md)**: Conditionally load or initialize async dependencies (such as importing polyfills for missing web features) without requiring complex orchestration across all of a page's script dependencies.+- **[defer-rendering-heavy-content](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/defer-rendering-heavy-content.md)**: Reduce rendering times in content-heavy web pages (e.g. pages with long feeds, lots of articles, or complex dashboards), by deferring rendering for any content that is not immediately visible to the user.+- **[defer-work-until-scroll-ends](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/defer-work-until-scroll-ends.md)**: Defer expensive operations like DOM updates, data fetching, analytics tracking, or layout recalculation until after scrolling completes to maintain smooth scroll performance.+- **[deprioritize-background-fetches](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/deprioritize-background-fetches.md)**: Deprioritize background data fetches made with the Fetch API to prevent network contention with user-initiated requests.+- **[detect-initial-visibility-state](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/detect-initial-visibility-state.md)**: Reliably determine whether a page was initially loaded in the background, even in cases where the script is loaded asynchronously after the user foregrounded the page.+- **[efficient-background-processing](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/efficient-background-processing.md)**: Conserve system resources and battery life by pausing background JavaScript execution (such as `<canvas>` animations, WebGL rendering, or high-frequency WebSocket data polling) when the component is off-screen and then resume them just-in-time when they scroll back into view.+- **[faster-spa-view-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/faster-spa-view-transitions.md)**: Enable faster transitions back to previously visited views in a Single-Page Application (SPA) by preserving their structural DOM state instead of destroying and rebuilding them on every navigation.+- **[full-session-analytics](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/full-session-analytics.md)**: Reliably track analytics, errors, and telemetry data across the user's entire page visit, and defer sending of the data until the user leaves the page.+- **[identify-heavy-scripts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/identify-heavy-scripts.md)**: Identify the scripts most responsible for long animation frames+- **[identify-inp-causes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/identify-inp-causes.md)**: Identify slow running JavaScript that is impacting INP metric+- **[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.+- **[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.+- **[resolution-optimized-pseudo-elements](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/resolution-optimized-pseudo-elements.md)**: Use resolution-optimized images in CSS pseudo-elements (such as `::before` and `::after`) to reduce the number of DOM nodes.+- **[schedule-tasks-by-priority](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/schedule-tasks-by-priority.md)**: Schedule tasks with different priorities to ensure critical work runs first while background work is deferred.+- **[sequence-distributed-events](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/performance/sequence-distributed-events.md)**: Log and sequence operations in distributed microservices or high-throughput tracing environments by recording timestamps with nanosecond resolution.++<h3>user-experience</h3>++- **[adapt-scrollbar-to-contrast-preferences](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/adapt-scrollbar-to-contrast-preferences.md)**: Enhance scrollbar visibility for users who prefer high-contrast interfaces+- **[adapt-scrollbar-to-light-dark-preferences](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.md)**: Ensure the scrollbar visually matches the user's operating system light/dark mode preference+- **[anchor-positioning-tab-underline](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/anchor-positioning-tab-underline.md)**: Transition an element seamlessly between two target element positions. For example, moving a selected tab underline between the previously selected tab and the currently selected tab.+- **[animate-element-entry-exit](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/animate-element-entry-exit.md)**: Smoothly hide/show elements as they are added/removed from the DOM or as their display values are toggled.+- **[animate-to-from-top-layer](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/animate-to-from-top-layer.md)**: Animate elements such as dialogs, popovers, and tooltips as they're entering/exiting the top layer.+- **[animate-to-intrinsic-sizes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/animate-to-intrinsic-sizes.md)**: Smoothly animate interactive components (like accordions, menus, and expanding cards) to and from their natural dimensions.+- **[browser-ui-color-theme](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/browser-ui-color-theme.md)**: Configure built-in browser UI (e.g. scrollbars, form controls, etc) to respect the user's light/dark theme preference.+- **[calculate-event-differentials](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/calculate-event-differentials.md)**: Calculate the duration and time remaining between dates and times.+- **[calculate-with-intrinsic-sizes](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/calculate-with-intrinsic-sizes.md)**: Calculate the size of an element based on its intrinsic size, while ensuring it fits within given design constraints.+- **[capture-location-agnostic-data](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/capture-location-agnostic-data.md)**: Record chronological data that should not change based on a user's location, such as birthdates, recurring alarms, or national holidays.+- **[carousel-slide-effects](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/carousel-slide-effects.md)**: Create a carousel of slides with images or other visual elements, where each slide animates as they enter/center/exit their scroller. For example, the slides may fade-in/fade-out, rotate, get bigger or smaller, etc.+- **[carousel-snap-highlights](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/carousel-snap-highlights.md)**: Visually highlight the currently snapped non-interactive item in scroll-snapping carousels, galleries, or full-page swipe experiences. For example, expanding a card when snapped, or revealing hidden content.+- **[child-state-based-styling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/child-state-based-styling.md)**: Build a component that changes its styling based on the state of one of its child elements. For example, a component that renders in light or dark mode based on whether a theme toggle is checked (or not).+- **[component-specific-light-dark-theme](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/component-specific-light-dark-theme.md)**: Create component-specific themes by forcing explicit color schemes on individual UI elements, giving users theme choices that are decoupled from their global operating system preferences+- **[consistent-cross-document-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/consistent-cross-document-transitions.md)**: Ensure critical page state is loaded and stable before initiating a cross-document view transition. This means critical CSS styles are loaded and applied, critical JavaScript is loaded and run, and the HTML visible for the user's initial view of the page has been parsed before the transition runs.+- **[content-based-styling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/content-based-styling.md)**: Build a component that changes its layout based on whether it contains specific child elements (or not). For example, if the component contains an image, use a multi-column layout, otherwise default to a single-column layout.+- **[coordinate-global-events](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/coordinate-global-events.md)**: Schedule future meetings or events by explicitly binding them to a geographical IANA time zone so that event times remain accurate regardless of Daylight Saving Time (DST) transitions, "skipped" or "repeated" hours during clock changes.+- **[cross-document-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/cross-document-transitions.md)**: Create smooth, seamless transitions between full page navigations, such as cross-fades, custom reveal effects, or morphing of content from one page to the next.+- **[customize-scrollbar-color-and-thickness](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/customize-scrollbar-color-and-thickness.md)**: Customize the color or thickness of a scrollbar+- **[declarative-button-actions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/declarative-button-actions.md)**: Declaratively connect a button to any element to trigger custom, application-specific actions using declarative button commands, invoker commands, button commands, custom commands, or declarative toggle actions.+- **[declarative-dialog-popover-control](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/declarative-dialog-popover-control.md)**: Toggle the visibility of a dialog or popover from a button without writing JavaScript.+- **[deliver-optimized-decorative-images](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/deliver-optimized-decorative-images.md)**: Deliver optimized decorative images (such as backgrounds, UI icons, or complex masks) by simultaneously providing next-generation image formats (like AVIF or WebP) alongside multiple pixel densities (like 1x and 2x) so the browser can dynamically negotiate the best combination of file size and visual quality for the user's device capabilities.+- **[directional-navigation-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/directional-navigation-transitions.md)**: Animate visual state changes to reflect the direction of a user's navigational flow, such as sliding new content in from the right when advancing forward or from the left when returning to a previous screen.+- **[dynamic-sibling-animations](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/dynamic-sibling-animations.md)**: Stagger animation or transition timing across sibling elements so each one starts after a computed delay based on its position in the sibling list.+- **[dynamic-sibling-styling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/dynamic-sibling-styling.md)**: Create dynamic visual spectrums or layout arrangements that automatically adapt to the number of elements in a group.+- **[flicker-free-client-side-ab-testing](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/flicker-free-client-side-ab-testing.md)**: Deliver and render A/B tests, multi-variate tests, or other experiments using client-side JavaScript to alter or inject HTML, CSS, and JavaScript without the original content showing first before flickering or flashing to show the experiment content.+- **[fluid-scaling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/fluid-scaling.md)**: Scale items like font size, spacing, and media sizes smoothly based on the parent container's size rather than using fixed breakpoints+- **[format-human-readable-durations](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/format-human-readable-durations.md)**: Present elapsed time or durations to users in a readable, localized format, with the flexibility to display either detailed unit breakdowns (e.g., "1 hour and 30 minutes") or total unit counts (e.g., "90 minutes") depending on context.+- **[group-element-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/group-element-transitions.md)**: Transition a group of similar elements simultaneously using the same transition logic, such as removing a product from a shopping cart and having all the other products animate into their new positions.+- **[improve-text-layout-and-legibility](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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.+- **[individual-transform-properties](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/individual-transform-properties.md)**: Animate or override individual CSS transform properties (e.g. translate, rotate, scale) independently of other transform properties on a single element.+- **[interactive-content-reveal](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/interactive-content-reveal.md)**: Create interactive reveal effects, such as a spotlight that follows the user's pointer to uncover details within an image or UI section.+- **[interest-triggered-action-previews](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/interest-triggered-action-previews.md)**: Show a live preview of a button's effect when a user signals interest (e.g. hovering, focusing, or long-pressing) but before they commit to clicking.+- **[interest-triggered-tooltips](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/interest-triggered-tooltips.md)**: Show a tooltip or supplemental information when a user hovers over, focuses on, or long-presses an interactive element, without requiring a click.+- **[light-dismiss-a-dialog](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/light-dismiss-a-dialog.md)**: Create a modal dialog that can be closed via light dismiss (i.e. clicking or tapping outside of the dialog)+- **[manage-recurring-intervals](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/manage-recurring-intervals.md)**: Calculate recurring intervals for subscription billings or payroll cycles, automatically adjusting for edge cases such as month-end transitions (e.g., adding one month to January 31st) to ensure accurate period calculations.+- **[model-partial-time-concepts](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/model-partial-time-concepts.md)**: Model date and time concepts that inherently lack a standard component (such as a specific year, day, or date) without using arbitrary placeholder values that introduce calculation errors.+- **[move-dom-element-without-losing-state](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/move-dom-element-without-losing-state.md)**: Move or reparent a DOM element without losing important element state, such as interactivity states (:focus/:active), <iframe> loading state, animation/transition state, etc+- **[navigation-drawer](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/navigation-drawer.md)**: Create a navigation drawer component that, when triggered from a menu button, slides in from the side overlayed on top of existing page content, and slides out when dismissed (by swiping away, tapping outside, or pressing escape).+- **[parallax-scroll-effects](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/parallax-scroll-effects.md)**: Create scroll-based effects (such as parallax) where foreground and background layers move at different rates, creating a sense of depth as the user scrolls.+- **[persistent-app-tours](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/persistent-app-tours.md)**: Create persistent onboarding walkthroughs using tethered native overlays that stay open during user interaction.+- **[persistent-toast-notifications](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/persistent-toast-notifications.md)**: Create non-intrusive toast and overlay notifications for persistent, stackable messaging and state communication.+- **[persistent-top-layer-ui](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/persistent-top-layer-ui.md)**: Keep a modal dialog, fullscreen element, or native popover visibly open and functionally active when its underlying DOM node is moved or reparented in the DOM.+- **[physics-based-easing](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/physics-based-easing.md)**: Create custom, physics-based animation and transition effects, like bounce and spring, that feel more natural and engaging than traditional easing curves.+- **[platform-controls-dismiss-dialog](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/platform-controls-dismiss-dialog.md)**: Create a modal dialog that can be closed via standard platform-specific user actions, such as pressing the `Esc` key on desktop platforms, or a "back" or "dismiss" gesture on mobile platforms+- **[position-aware-tooltips](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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.+- **[precise-text-alignment](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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/user-experience/prevent-text-wrapping.md)**: Ensure the browser does not insert line breaks into text and will allow text to overflow its container.+- **[pull-to-reveal](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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.+- **[reduce-style-repetition](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/reduce-style-repetition.md)**: Reduce excessive style repetition by encapsulating complex or dynamic styling logic into reusable functions (such as a function that computes a gradient based on a set of input parameters).+- **[resilient-context-menus-and-nested-dropdowns](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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.+- **[same-document-transitions](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/same-document-transitions.md)**: Visually connect persisting elements across different page states or navigations in a Single Page Application (SPA) (e.g. expanding a product thumbnail into a full-bleed hero image) by smoothly morphing their size, position, or other styling properties.+- **[scroll-entry-exit-effects](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/scroll-entry-exit-effects.md)**: Create fade-in, scale-up, or other complex reveal-type effects on elements as they enter and exit the scrollport (or viewport) while the user is scrolling.+- **[scroll-position-aware-elements](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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/user-experience/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.+- **[scroll-snap-realtime-feedback](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/scroll-snap-realtime-feedback.md)**: Provide real-time visual feedback in linked UI elements while a user scrolls through snap-aligned content, before the scroll gesture completes.+- **[scroll-snap-state-sync](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/scroll-snap-state-sync.md)**: Synchronize navigation indicators, linked content panels, and analytics tracking with the actively snapped item in a scrollable container.+- **[scroll-target-on-load](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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.+- **[scrollability-affordance-hints](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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.+- **[scrollytelling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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/user-experience/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.+- **[shrinking-header-on-scroll](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/shrinking-header-on-scroll.md)**: Smoothly animate a fixed header or full-page cover on scroll to dynamically shrink, gain shadows, and transform its layout over a predefined scroll distance.+- **[size-aware-styling](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/size-aware-styling.md)**: Build a component whose styles can be conditionally dependent on its own width or height, rather than the width or height of the viewport. For example a card component that can change its layouts depending on how large it is, or a call-to-action button that can conditionally display helper text based on its width.+- **[stabilize-reactive-state](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/stabilize-reactive-state.md)**: Manage task deadlines or schedules in data-driven views without unexpected side effects from shared mutable state.+- **[style-parent-with-has](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/style-parent-with-has.md)**: Style parent elements of a form field (e.g. labels or fieldsets) when the field is invalid.+- **[support-global-calendar-systems](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/support-global-calendar-systems.md)**: Display and calculate dates in non-Gregorian calendar systems (e.g., Islamic, Hebrew, or Chinese) accurately for international users.+- **[visually-stable-font-fallbacks](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/user-experience/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/user-experience/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.++<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.+- **[agentic-javascript-tools](https://github.com/GoogleChrome/modern-web-guidance/blob/main/skills/modern-web-guidance/guides/webmcp/agentic-javascript-tools.md)**: Programmatically register client-side JavaScript functions as tools for AI agents using the WebMCP Imperative API.</details>+### The modern web platform that you can *use,* safely++* **Responsible Fallbacks**: We don't recommend heavy polyfills that bloat your bundle or block the main thread. Instead, we suggest what an **in-tune senior front-end developer would appreciate**:+ 1. Prioritizing lightweight, case-specific custom implementations (\<50 lines of code).+ 2. Conditional loading of performant polyfills *only* when native support is absent. And avoiding both risky CDNs (like polyfill.io) and CSS-parsing polyfills.+ 3. Using bulletproof prototype-level feature detection rather than naive environment checks.+* **Gotchas & Quirk Mitigation**: Tricky API boundaries and platform quirks (e.g., the 64KB payload quota for `fetchLater()`, macOS specific scrollbar gutters, and WebKit flickering bugs) are fully documented.+* **Baseline-Aware Decisions**: Dynamic compatibility data from the Baseline project ensures agents make micro-architectural decisions on-the-fly—applying progressive enhancement conditionally, not blindly.++## How+### How Coding Agents use our skill-## Installation+* **Bootstrapped Awareness**: When loaded, the agent receives a system prompt instruction: *"To use modern web platform APIs, query the `modern-web` tool."*+* **Semantic Vector Discovery**: The agent executes `modern-web search "<query>"` in your terminal. The tool uses an optimized `MiniLM-L6-v2` TensorFlow.js model running **entirely offline** on your CPU (thx `MiniLM`! No network calls, latency, or API keys required) to calculate the **cosine distance** between the query and our pre-computed guide embeddings.+* **Precision Retrieval**: The agent executes `modern-web retrieve <guide-id>` to fetch the exact, clean Markdown guidelines it discovered.+* **State-of-the-Art Generation**: The guide's precise code snippets, DO/DO NOT rules, and responsible cross-browser fallbacks are injected directly into the agent's context window, enabling it to generate clean, modern code instantly.-```bash+Token-efficient, targeted, and private guidance injected right into the context window. Yeah, buddy.++## Get started++```shellnpx modern-web-guidance install```-### 🍦 Universal Skills Pack-Consult your coding agent's documentation for installation instructions. You can also use Vercel's `skills` CLI:-```bash-DISABLE_TELEMETRY=1 npx skills add GoogleChrome/modern-web-guidance+This will run a quick interactive wizard to install the modern-web-guidance-skill to your preferences, and for your configured agents.++### Not ready to install? All good. Search our guides manually++```shell+# Search for relevant guides+npx modern-web-guidance@latest search "animate a dialog modal backdrop"+# Retrieve a guide by ID+npx modern-web-guidance@latest retrieve "animate-to-from-top-layer"```-### ✴️ Claude Code-```bash+### Alternative installation methods++#### Vercel `skills` CLI: `npx skills add GoogleChrome/modern-web-guidance`++#### Github CLI: `gh skill install GoogleChrome/modern-web-guidance`++#### Google Antigravity: `agy plugin install https://github.com/GoogleChrome/modern-web-guidance`++#### Claude Code plugin++We don't recommend this method, but it will work.++```shell/plugin marketplace add GoogleChrome/modern-web-guidance/plugin install modern-web-guidance@googlechrome+/plugin # Select GoogleChrome marketplace, hit enter, enable AutoUpdate/reload-plugins```-### ♊ Gemini CLI-```bash-gemini extensions install https://github.com/GoogleChrome/modern-web-guidance --auto-update+## This isn't slop. We've got the evals to prove it. ;)++Every piece of guidance in this pack isn't just a tutorial—it is **empirically proven and continuously calibrated** to guarantee AI agents write better code. We test every guide using an automated quality-assurance harness to ensure correct agent behavior.++### Validation Pipeline++```+ [ SME-Authored Guidance ]+ │+ ▼+ [ Gemini CLI Generator ] ──> Playwright Grader (.spec.ts) & Calibrated Negative Demo (.html)+ │+ ▼+ [ Calibration Loop ] ───────> Runs Grader on Gold-Standard Demo (Must Pass 100%)+ │ Runs Grader on Negative Demo (Must Fail 100%)+ ▼+ [ E2E Agent Evals ] ────────> Runs coding agents in Guided vs. Unguided modes+ Compares accuracy pre/post guide injection to prove impact```-*(Note: If the CLI hits a 404 error and asks to install via "git clone" instead, simply say yes! This is perfectly normal while the project is in private alpha.)*-### 🌐 VSCode Extension+### 1. Real-World, Outcome-Based Assertions++For each guide, we develop a Playwright script (`.spec.ts`) that asserts the guide's implementation details were followed, such as:++* Verifying accessibility tags and computed styles (e.g., `@media (prefers-contrast: more)` overrides).+* Asserting exact functional layouts and performance behaviors as interpreted by the browser.++### 2. Self-Healing Playwright Calibration++To ensure our test suites aren't nonsense, the pipeline runs a continuous, closed-loop calibration:++* **Golden Master vs. Anti-Pattern**: We run our per-usecase Playwright scripts against both a perfect reference implementation (`demo.html`, expects 100% pass) and a deliberately flawed implementation (`negative-demo.html`, expects 0% pass).+* **Autonomous Refinement**: If calibration fails, the generator automatically retries with detailed failure context until the grader achieves 100% calibration.++Last, we validate that the calibrated graders aren't taking shortcuts and honor the sanctity of the intent.++### 3. E2E Agent Evals for Every Guide++Finally, we run end-to-end evaluations on real base applications:++* **Unguided (Control)**: The agent addresses a coding task using only its default training data.+* **Guided (Experiment)**: The agent addresses the exact same task, but with access to this skill pack.+We grade both outputs and only release guides that demonstrate a massive, quantifiable improvement in code quality (e.g., improving success rates from **20% up to 90%**).-*Note: We'll publish to a markplace soon; In the meantime, install the slow way (which won't auto-update):*+# Available Skills-* Clone this repo-* In VSCode, open the Command Palette (`Cmd+Shift+P` or `Ctrl+Shift+P`)-* Select "Extensions: Install from Location..."-* Navigate to the `modern-web-guidance` directory and select it.+* **`modern-web-guidance`**: (234 tokens) Everything mentioned above+* **`chrome-extensions`**: (181 tokens) Manifest V3 development, background service workers, content scripts, and extension APIs. Manage Chrome Web Store metadata, permissions justifications, privacy policies, and publishing readiness.-Compatibility with VSCode forks: unknown.+\# Choose which skills you want+`npx modern-web-guidance install --choose`diff --git a/gemini-extension.json b/gemini-extension.jsonindex df89ac4..f0dd7f3 100644--- a/gemini-extension.json+++ b/gemini-extension.json@@ -1,6 +1,6 @@{"name": "modern-web-guidance",- "description": "Google Chrome's web development agent skills.",+ "description": "Keep your coding agent up to date with the latest web best practices","version": "0.0.111","author": {"name": "Google Chrome"diff --git a/skills/modern-web-guidance/guides/accessibility/accessibility.md b/skills/modern-web-guidance/guides/accessibility/accessibility.mdnew file mode 100644index 0000000..30f7e62--- /dev/null+++ b/skills/modern-web-guidance/guides/accessibility/accessibility.md@@ -0,0 +1,463 @@+# Accessibility Coding Guidelines++This guide provides actionable DOs and DON'Ts for AI coding agents to ensure web applications are accessible to all users, including those using assistive technologies.++Keep these principles in mind throughout:++- **Accessibility is the minimum, not the ceiling.** Conformance to standards is the floor; aim for genuine usability.+- **Patterns are use-case specific.** No checklist replaces real testing — including testing with disabled users — to confirm a given implementation is actually accessible in context.++## 1. Content Navigability and Structure++### Actionable Guidelines++#### DOs+- **Place all content within landmarks**: Wrap the page in `<header>`, `<nav>`, `<main>`, `<aside>`, and `<footer>` so assistive-tech users can jump between regions.+- **Structure main content with headings**: Use `<h1>`–`<h6>` sequentially (no jumping `<h1>` → `<h4>`) so screen-reader users get a navigable outline.+- **Use lists for repeated, contiguous content**: `<ul>`/`<ol>` give assistive tech a count up front and let users skip the entire group.+- **Provide skip links** prior to repeated content like site headers with navigation or long/infinite lists, so that keyboard users can easily bypass them. Make sure the target is focusable (e.g. `<main id="content" tabindex="-1">`).+- **Semantic Tables**: Use `<caption>` and `<th scope="col">` (or `<th scope="row">`) for data tables.++#### DON'Ts+- **Don't use fake headings**: Never style `<div>` or `<span>` to look like headings without standard `<h1>`–`<h6>` tags.+- **Don't place headings inside `<summary>`, and avoid relying on headings inside `<details>` content**: Headings inside `<summary>` may be hidden from screen-reader heading lists and heading-navigation shortcuts entirely; headings inside `<details>` content are only reachable via heading navigation when the disclosure is open.+ - **Caveat**: If a heading must act as a disclosure trigger, use a more robust alternative to `<details>`/`<summary>` instead, e.g. an accordion or a disclosure implemented with ARIA where the heading wraps the button.+- **Don't use tables for layout**: Use CSS Grid/Flexbox for visual layouts.+- **Don't overuse landmarks**: Too many landmarks dilute their value. In particular, avoid labeling a `<section>` (which turns it into a `region` landmark) — `region` should be a last resort when no other landmark fits.++### Code Examples++```html+<!-- Good: Semantic landmarks, heading hierarchy, skip link -->+<header>+ <a href="#content" class="skip-link visually-hidden">Skip to content</a>+ <nav aria-label="Primary">+ <ul>+ <li><a href="/">Home</a></li>+ </ul>+ </nav>+</header>+<main id="content" tabindex="-1">+ <h1>Platform Dashboard</h1>+ <section>+ <h2>User Statistics</h2>+ <table>+ <caption>Monthly active users</caption>+ <tr>+ <th scope="col">Month</th>+ <th scope="col">Users</th>+ </tr>+ <tr>+ <td>January</td>+ <td>12,000</td>+ </tr>+ </table>+ </section>+</main>+```++## 2. Semantic HTML and ARIA++### Actionable Guidelines++#### DOs+- **Prefer HTML elements and attributes to ARIA**: A native element comes with the right role and behavior. `<button>` already implies `role="button"`; `required` already implies `aria-required`.+- **Match ARIA implementations to actual behavior**: If you set `role="tab"`, the element must behave like a tab — including keyboard interactions. Many ARIA patterns can't be implemented in CSS alone and need JavaScript.+- **Be deliberate about `disabled` vs `aria-disabled`**: `disabled` removes the element from the focus order entirely (and `tabindex="0"` won't bring it back), which is often wrong for toolbar buttons or links. `aria-disabled="true"` keeps the element focusable so users can land on it and learn it's disabled.++#### DON'Ts+- **Don't use ARIA when native HTML exists**: Avoid `<div role="button">` or `<a role="button">` if `<button>` works.+- **Don't add redundant ARIA roles or properties**: Avoid `<ul role="list">`, `<nav role="navigation">`, or `<input required aria-required="true">`.+ - **Caveat**: Safari removes list semantics from `<ul>`/`<ol>` outside `<nav>` when `list-style: none` or `display: flex`/`grid` is applied. In that case `role="list"` is required to restore them.+- **Don't assume custom elements have no ARIA**: Custom elements can attach ARIA via `ElementInternals`, which some automated test tools can't see — so the absence of `role`/`aria-*` attributes in markup doesn't prove the element has no semantics. Verify with the browser's accessibility-tree inspector.++## 3. Accessible Names and Descriptions++Every interactive element and some landmarks need an accessible name, and many benefit from an accessible description. Names are short and identify the element; descriptions add context.++### Actionable Guidelines++#### DOs+- **Prefer native naming mechanisms**: `<label>` for form controls, `<caption>` for `<table>`, `<legend>` for `<fieldset>`, `<figcaption>` for `<figure>`.+- **Explicitly associate `<label>` with its control via `for`/`id`**, even when nesting the input inside the label — explicit association improves assistive-tech support.+- **Prefer `aria-labelledby` over `aria-label` when a visible label exists**: avoids duplication, improves maintainability, and translates better.+- **Prefer to reuse the same accessible name for hyperlinks that share an `href`.**+- **Use visually hidden text to disambiguate controls** that look identical visually but do different things (e.g. multiple "Edit" buttons in a list).++#### DON'Ts+- **Don't put `aria-label`/`aria-labelledby` on elements that shouldn't be named** — e.g. plain `<div>`, `<span>`, or custom elements without a role. Custom elements may have an implicit role set via `ElementInternals`, so the absence of a `role` attribute isn't conclusive.+- **Don't reuse an accessible name across controls with different effects in the same view** (close buttons for two different open dialogs are fine because only one is reachable at a time; multiple “Edit” buttons for different content is not).+- **Don't reuse an accessible name across hyperlinks pointing to different `href`s.**+- **Don't pack descriptions, error messages, or instructions into the label.**+- **Don't repeat state already exposed via ARIA** (`aria-expanded`, `aria-checked`, `aria-selected`, `aria-pressed`) inside the accessible name — it creates redundancy and ambiguity.+- **Don't include the role name in the label**: `<nav aria-label="Primary navigation">` reads as "Primary navigation navigation."+- **Don't use `title` or `placeholder` as a naming mechanism.**+- **Don't include interactive elements in an `aria-describedby` target** unless their text content reads sensibly as a description on its own (e.g. if a link’s text is the same as how it’s labelled elsewhere, it can be included within a description).++### Code Example: Visually Hidden Utility++A `.visually-hidden` utility lets you provide text for screen readers without rendering it visually. It's commonly used for skip links, additional context on icon-only buttons, and supplementary labels.++```css+/* Hides content visually but keeps it in the accessibility tree.+ :focus-within / :active opt elements out — useful for skip links and+ any focusable content wrapped in this class. */+.visually-hidden:where(:not(:focus-within, :active)) {+ position: absolute !important;+ clip-path: inset(50%) !important;+ overflow: hidden !important;+ width: 1px !important;+ height: 1px !important;+ margin: -1px !important;+ padding: 0 !important;+ border: 0 !important;+ white-space: nowrap !important;+}+```++When the hidden content is focusable (skip links, focus-receiving wrappers), the `:focus-within`/`:active` exception lets it become visible. Style the visible state per situation, e.g. a skip link to the main content typically wants fixed positioning at the top-left of the viewport so the rest of the page doesn't shift.++## 4. Document Metadata and Language++### Actionable Guidelines++#### DOs+- **Declare Visual Language**: Always set `<html lang="en">` (or appropriate code).+- **Unique Page Titles**: Front-load unique context in `<title>` (e.g., `Page Topic | Site Name`).+- **Inline Language Switches**: Use `lang="..."` for block quotes or text in different languages.+- **IFrame Titles**: Always provide a descriptive `title="..."` for `<iframe>` elements.+- **Update document title on Page Transitions in SPAs**: Shift focus to updated titles.++#### DON'Ts+- **Don't Disable iframe Scrolling**: Avoid `scrolling="no"` (deprecated) or `overflow: hidden` on iframes. Users who zoom in or enlarge text need to scroll to reach content that overflows.++### Code Examples++```html+<!-- Good: Distinct title and language declaration -->+<html lang="en">+<head>+ <title>Analytics Reports | Guidance Platform</title>+</head>+<body>+ <p>The motto is <span lang="la">"Carpe diem"</span>.</p>+ <iframe title="Interactive Sales Chart" src="/chart"></iframe>+</body>+</html>+```++## 5. Keyboard and Focus Management++### Actionable Guidelines++#### DOs+- **Logical Tab Order**: Ensure tab order matches visual layouts (top-to-bottom).+- **Visible Focus Indicators**: Always style `:focus-visible` states explicitly. If disabling defaults, provide overrides with sufficient contrast.+- **Custom Trigger Keyboards**: Attach Enter/Space handlers for custom simulated interactive elements. When implementing a custom keyboard handler for button-like elements, `Enter` should be a `keydown` handler and `Space` should be a `keyup` handler (matching native `<button>` behavior where `Enter` repeats and `Space` triggers on release).+- **Use `tabindex` deliberately**: Anything focusable — by keyboard or programmatically — should have an implicit or explicit ARIA role, so don't make every element focusable. When focus is needed, choose `tabindex="0"` to add the element to the tab order or `tabindex="-1"` to make it programmatically focusable only (e.g., a skip-link target).+- **Manage Toggle States**: Utilize `aria-expanded` and `aria-pressed` to communicate toggle states for custom controls.++#### DON'Ts+- **Don't disable outlines without replacements**: Avoid `outline: none` without styling alternatives.+- **Don't use Positive Tabindex values**: Never use `tabindex="1"` or greater.+- **Don't hide interactive elements from screen readers**: Avoid `aria-hidden="true"` or `role="presentation"` on elements that can receive focus.++### Code Examples++```css+/* Good: High contrast focus border */+:where(a:any-link, button):focus-visible {+ outline: 3px solid #ff0055;+ outline-offset: 3px;+}+```++```html+<!-- Good: Skip to main content -->+<a href="#content" class="skip-link">Skip to main content</a>+<main id="content" tabindex="-1">...</main>+```++```javascript+// Good: Keyboard handlers for complex custom widgets (e.g., Tree items, tabs).+// NOTE: This pattern applies ONLY to non-standard UI where no native HTML tag exists.+// Always prioritize native <button> or <input> elements for standard interactions.+// Elements MUST have the appropriate ARIA role (e.g., role="treeitem" or role="tab").+customWidget.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ toggleWidgetState();+ }+ if (e.key === ' ') {+ e.preventDefault(); // Prevent page scrolling on Spacebar keydown+ }+});++customWidget.addEventListener('keyup', (e) => {+ if (e.key === ' ') {+ toggleWidgetState();+ }+});++function toggleWidgetState() {+ // E.g., Manage toggle/expanded states for custom controls+ const isExpanded = customWidget.getAttribute('aria-expanded') === 'true';+ customWidget.setAttribute('aria-expanded', !isExpanded);+}+```++## 6. Alternate Text and Media++### Actionable Guidelines++#### DOs+- **Informative Visual Descriptions**: Describe the purpose of the image (e.g., "Search", not "Magnifying glass").+- **Empty Alt properties for decorative visuals**: Use `alt=""` to remove decorative images from the accessibility tree so they aren't announced.+- **Synchronous Captions for videos**: Supply WebVTT captions for video tracks.+- **Transcripts for audio**: Provide text transcripts for purely audio podcasts.+- **Informative View Descriptions for inline SVGs**: Apply `role="img"` and a nested `<title>` tag for informative visuals.+- **Decorative SVGs removal**: Apply `aria-hidden="true"` to remove decorative SVGs from reading flows.+- **Long descriptions for complex images**: Use `<figure>`/`<figcaption>` or `aria-describedby` for charts and infographics.+- **Provide data tables as alternatives**: Consider providing semantic data tables as accessible alternatives for charts and other complex data visualizations.++#### DON'Ts+- **Don't use clichéd prefixes**: Avoid "Image of..." or "Picture of...".+- **Don't use underscores in filenames**: Use dashes if the filename might be announced as fallback.++### Code Examples++```html+<!-- Decorative -->+<img src="divider.png" alt="">++<!-- Inline Decorative SVG (remove from tab flow) -->+<svg aria-hidden="true" viewBox="0 0 24 24">+ <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>+</svg>++<!-- Informative (Functional) -->+<a href="/search">+ <img src="glass.png" alt="Search the platform">+</a>++<!-- Video with Captions tracks -->+<video controls>+ <source src="intro.mp4" type="video/mp4">+ <track src="caps.vtt" kind="captions" srclang="en" label="English">+</video>++<!-- Complex graph with figcaption -->+<figure>+ <img src="chart.png" alt="Sales growth graph 2024.">+ <figcaption>Sales grew 20% in Q3 due to new platform launch.</figcaption>+</figure>++<!-- Audio with expandable transcript details -->+<audio controls src="podcast.mp3" aria-details="podcast-transcript"></audio>+<details id="podcast-transcript">+ <summary>View Transcript</summary>+ <div class="transcript-content">+ Welcome to the show...+ </div>+</details>+```++### Content Visibility Decision Matrix++| Intent | Visual | Screen Reader | Focusable | Structural Pattern |+| :--- | :--- | :--- | :--- | :--- |+| **Visible to all** | Yes | Yes | Yes | Standard rendering |+| **Screen Reader only** | No | Yes | Yes (if interactive) | Visually hidden utility (e.g. `.visually-hidden`) |+| **Visual only** | Yes | No | No | `aria-hidden="true"` / `role="presentation"` |+| **Hidden for all** | No | No | No | `hidden` attribute / `display: none` |++**Heuristic Rule**: If an element can receive keyboard focus, it must not be hidden via `aria-hidden="true"`.++## 7. Forms and Input Controls++### Actionable Guidelines++#### DOs+- **Connect Labels Programmatically**: Use `<label for="id">` linked to `<input id="id">`.+- **Use Autocomplete**: Set valid standard `autocomplete` options (e.g., `"email"` or `"given-name"`) for user profiles.+- **Link hints to inputs via `aria-describedby`**: Associate help text with inputs, and place the hint above the input so autocomplete popovers don't cover it during editing.+- **Announce dynamic errors via live regions**: Use `aria-live` or shift focus to error lists.+- **Provide form validation constraints**: Use `required` (or `aria-required="true"` only when `required` isn't applicable) to signal mandatory inputs.++#### DON'Ts+- **Don't use placeholders as labels**: Placeholders are not persistent labels.+- **Don't trigger context shifts on focus changes**: Avoid auto-submitting forms or jumping pages on focus change events alone.++### Code Examples++```html+<!-- Good: Semantic forms with hints for passwords -->+<form>+ <label for="pwd">Password:</label>+ <span id="pwd-hint">Must contain at least 8 characters.</span>+ <input id="pwd" type="password" aria-describedby="pwd-hint" autocomplete="current-password" required>+</form>+```++## 8. Live Regions++Live regions let assistive tech announce content updates that aren't tied to navigation or focus changes. They're easy to misuse — too many regions, or noisy ones, quickly become spam for screen-reader users.++### Live Region Urgency Table++| Urgency | Visual Analogue | `aria-live` Value | Behavioral Impact | Example |+| :--- | :--- | :--- | :--- | :--- |+| **Critical** | Modal / Alert | `assertive` (or `role="alert"`) | Interrupts immediately, clears speech queue | Session timeout, API failure |+| **Standard**| Toast / Banner | `polite` | Announces at next graceful break | Search results, "Saved" status |+| **Passive** | Silent text | `off` | Only if user navigates to it | Live character count |++**Heuristic Rule**: Use `assertive` only for critical, time-sensitive updates that require immediate attention or prevent safe continuation (e.g., data loss, session timeouts, or network drops).++### Actionable Guidelines++#### DOs+- **Centralize live regions for non-visible announcements**: A single `polite` region and a single `assertive` region per page (with whatever `aria-atomic` configuration you need) keeps announcements consistent and easier to maintain. Many frameworks ship their own announcer abstraction — use it.+- **Debounce frequently-changing regions**: If a region can update many times per second (e.g. a combobox's result count as the user types), debounce so users aren't spammed.+- **Delay slightly when other announcements may collide**: When the user is typing or focus is being managed, a small delay before announcing keeps live-region updates from overlapping other speech.++#### DON'Ts+- **Don't use live regions for interstitial states** like "Loading…" or "Updating…" unless they're meaningfully informative — they usually just create noise.+- **Don't add live-region updates to inert DOM**: When dialogs open or sections become `inert`, queued or debounced messages can end up unannounced — or announced from DOM the user can't reach. Coordinate live-region updates with dialog/inert state changes.++### Code Example++```html+<!-- Session Timeout Warning with controls -->+<div role="alert" aria-live="assertive" class="timeout-warning">+ Your session will expire in 2 minutes.+ <button onclick="extendSession()">Extend Session</button>+</div>+```++## 9. Color, Contrast, and Typography++### Actionable Guidelines++#### DOs+- **Minimum contrast standards**: Maintain 4.5:1 for normal text and 3:1 for large text or icons.+- **Ensure non-text contrast standards**: Maintain a minimum contrast ratio of 3:1 for user interface component boundaries and states.+ - This includes visual elements (borders, backgrounds, box-shadows, underlines) that form the boundary or indicate the presence of a UI component (e.g., input field borders).+ - This also includes visual elements indicating active states within a component (e.g., checkbox checkmarks or switch thumbs).+ - **Caveat**: Meeting 3:1 non-text contrast can challenge minimalistic designs. Soft gradients or subtle inset/outset shadows can soften visual boundaries while satisfying accessibility requirements.+- **Use multiple state indicators**: Do not denote success/errors ONLY with color. Use icons or text.+- **Relative font size units**: Use `rem` or `em` for font sizes instead of `px`.+- **Consistent or Start alignment**: Avoid `justify` alignment as it can be more difficult to read.+- **Avoid long lines of text**: Cap paragraph blocks to a maximum of 80 characters width.+- **Support user zoom preferences**: Allow users to resize text up to 200% without loss of content or functionality.+- **Support light and dark color schemes**: Honor `@media (prefers-color-scheme: dark)` and pair it with the `color-scheme` CSS property so form controls, scrollbars, and other UA-rendered surfaces match.+- **Use `prefers-contrast` only when warranted**: Reach for `@media (prefers-contrast: more)` when the design uses low-contrast accents (e.g., subtle borders, muted secondary text) that need to be reinforced; most sites that already meet baseline contrast won't need it.++#### DON'Ts+- **Don't use color alone to indicate the presence of a user interface component or its state**: Use iconography and/or shape to help differentiate.+- **Don't use Justified Text Alignment**: Avoid `text-align: justify`.+- **Don't use Ornate fonts**: Omit cursive typefaces for main reading content.+- **Don't rely on all-caps for emphasis**: Prefer bolding for visual emphasis, and use `<em>`/`<strong>` when the emphasis is semantic.+- **Limit emphasis overall**: Emphasis loses meaning when it's everywhere — apply it only where it changes how the content should be read.++### Code Examples++```css+/* Good: Relative sizing and line caps */+body {+ line-height: 1.5;+ text-align: start; /* Supports LTR and RTL */+}+article {+ max-width: 80ch; /* Caps line length to ~80 characters for readability */+}+```++```html+<!-- Good: Denotes state without colors alone -->+<div class="error-msg">+ <span aria-hidden="true">❌</span>+ <span>The password entered was invalid.</span>+</div>+```++```css+/* Dark Mode support variables */+:root {+ --bg-color: #ffffff;+ --text-color: #212529;+}+@media (prefers-color-scheme: dark) {+ :root {+ --bg-color: #121212;+ --text-color: #f8f9fa;+ }+}+```++## 10. Motions and Preferences++### Actionable Guidelines++#### DOs+- **Support Reduced Motion media queries**: Support `@media (prefers-reduced-motion: reduce)` media queries.+- **Provide Pause mechanism**: Allow users to stop auto-running carousels banners or other persistent animations.+- **Default to static views**: Consider defaulting to static states and allowing users to opt-in to motion.++#### DON'Ts+- **Don't exceed flash limits (three per second)**: Never include rapid light-to-dark flashing. Such effects can cause seizures.++### Code Examples++```css+/* Good: Dampen spin states for reduced motion queries */+@media (prefers-reduced-motion: reduce) {+ .spinner {+ animation: none;+ opacity: 0.5;+ }+}+```++## 11. Modals and Native Dialogs++Modern browsers provide native solutions for creating modal dialogs which avoid the need for focus traps, managing the accessibility of outside content, ensuring the content is on top, and dimming the background content — all of which can be error prone and require heavy JavaScript event tracking to maintain.++### Actionable Guidelines++#### DOs+- **Use the Native `<dialog>` Element**: Invoke the dialog using the `.showModal()` method to open it in a modal state. When in a modal state, the browser sets outside content as inert (i.e. the outside content is hidden from the accessibility tree and cannot be interacted with nor be focused).+- **Use the `inert` Attribute for Custom Overlays**: When `<dialog>` cannot be used (e.g., some non-modal overlays, framework constraints, or layouts where `<dialog>`'s top-layer/positioning behavior conflicts with the design), apply `inert` to outside content to ensure it cannot be interacted with by keyboard, pointer, or assistive technology. This requires structuring elements in such a way that the custom overlay is not a descendant of the element with `inert` set on it.++#### DON'Ts+- **Don't implement focus traps for native modal dialogs**: When a `<dialog>` element is opened in a modal state, browsers set outside content as inert which is sufficient for ensuring only the dialog’s content can be focused.++### Code Examples++**HTML & JS: Native `<dialog>` with standard close events**+```html+<!-- Dialog opens natively with showModal() and locks focus -->+<button id="open-btn">Open Dialog</button>++<dialog id="accessible-modal" aria-labelledby="title-id">+ <h2 id="title-id">Account Settings</h2>+ <p>Update your details here.</p>+ <button onclick="this.closest('dialog').close()">Close Dialog</button>+</dialog>++<script>+ document.getElementById('open-btn').addEventListener('click', () => {+ document.getElementById('accessible-modal').showModal();+ });+</script>+```++## 12. Testing Validations++### Actionable Guidelines++#### DOs+- **Run Automated checks via axe-core or Lighthouse audits**: Catch missing alt texts or low contrasts (e.g., via Lighthouse in Chrome DevTools MCP).+- **Validate Sequential Navigations using keyboards alone**: Using only keyboard shortcuts, such as Tab/Shift+Tab, arrow keys, Enter, Space, and Esc, confirm every interactive element is reachable and operable, and that focus never gets stuck.+- **Test on Screen Readers with calibrated browsers**: Rely on standard bindings (e.g., JAWS with Chrome, NVDA with Firefox, Narrator with Edge, VoiceOver with Safari on macOS and iOS, TalkBack with Chrome for Android).++#### DON'Ts+- **Don't rely purely on scores**: A 100% score does not guarantee real usability.diff --git a/skills/modern-web-guidance/guides/javascript/javascript.md b/skills/modern-web-guidance/guides/javascript/javascript.mdindex 165ff52..473ef91 100644--- a/skills/modern-web-guidance/guides/javascript/javascript.md+++ b/skills/modern-web-guidance/guides/javascript/javascript.md@@ -4,71 +4,8 @@ This skill is a baseline for writing clean, performant, and secure JavaScript. TThis skill defers to specific use-case guidance found in the `/guides/` directory when applicable.-## Modern Syntax and Variable Declarations--- **Use `const` by Default**: Use `const` for all variable declarations. Use `let` only when reassignment is strictly required.-- **Never Use `var`**: Deprecate the legacy `var` keyword to avoid function-scoping and hoisting bugs.-- **Enforce Strict Mode**: Add `"use strict";` at the top of scripts or functions if not inside an ES module or class (which are strict by default).-- **Prefer Primitives and Literals**: Avoid object wrappers (e.g., `new String()`, `new Number()`). Define variables using literals (e.g., `""`, `0`, `true`), standard conversion functions (e.g., `Number()`, `String()`) for type conversion, and standard parse functions (e.g.,`parseInt()`, `parseFloat()`) for string-to-number parsing.-- **Use Strict Equality `===`**: Always use `===` and `!==` over `==` and `!=` to bypass dangerous implicit type coercion. Use `Number.isNaN()` to check if a value is `NaN`.-- **Nullish Operators for Safety**:- - Use Optional Chaining (`?.`) to safely traverse nested objects without throwing `TypeError`.- - Use Nullish Coalescing (`??`) for defaults instead of logical OR (`||`) to avoid accidentally overriding valid falsy values like `0` or `""`.-- **Use Template Literals**: Use backticks `` ` `` and `${}` for string interpolation instead of concatenation `+`.-- **Naming Conventions**: Use `camelCase` for variables and functions, `PascalCase` for classes.-- **Use `structuredClone()` to Recursively Copy Objects**: Avoid using `JSON.parse(JSON.stringify(object))` to clone an object.-- **Precise Calculations**: Use integers or whole numbers for precision-critical math (e.g., currency) to avoid floating-point issues (`0.1 + 0.2 !== 0.3`).-- **Document with JSDoc**: Provide inline code documentation that integrates with tooling with JSDoc. DO include `@param` and `@returns` to document functions.--```javascript-// ✅ GOOD-const score = 0;-const finalScore = score ?? 10; // 0--// ❌ BAD-const finalScoreLegacy = score || 10; // 10 (incorrectly overrides 0)-```--## Functions and Async Flow--- **Prefer Rest and Default Parameters**: Use Rest parameters (`...args`) instead of the legacy `arguments` object. Define defaults inside the signature (`param = value`).-- **Arrow Functions for Lexical `this`**: Use arrow functions when you want to preserve the surrounding context's `this` (e.g., inside callbacks or timers).-- **Standard Functions for Dynamic `this`**: Use standard function syntax (`functionName() {}`) when you need `this` to bind dynamically (e.g., object methods or event handlers).-- **Asynchronous Flow with `async/await`**: Use `async`/`await` for readable asynchronous code instead of heavy promise chains or callbacks. Always wrap with `try/catch` for error handling.-- **Fail Fast with Early Returns**: Return early from functions to keep code flat and avoid deep `if-else` nesting.-- **Use Ternary Statements for Conditional Variable Assignment**: Prefer standard `if/else` statements over side effects in a conditional ternary statement.(e.g., `condition ? doSomething() : doSomethingElse()`). Avoid nesting ternary operators, prefer `if-else` or switch statements.-- **Throw Error Objects**: Don't throw strings or other literals (e.g., `throw "CustomError"`). Instead throw an `Error` or a subclass of `Error`, (e.g., `throw new Error('CustomError')`).--```javascript-// ✅ GOOD: Readable async flow-async function fetchData(url) {- try {- const response = await fetch(url);- const data = await response.json();- return data;- } catch (error) {- console.error("Fetch failed:", error);- throw error; // Propagate or handle- }-}-```--### Async Patterns Decision Matrix--| Pattern | Best For | Error Behavior | Execution |-| :--- | :--- | :--- | :--- |-| **`async / await`** | Sequential dependencies | `try/catch` per call | Serial (One by one) |-| **`Promise.all()`** | Parallel tasks, all required | Fails fast (rejects on first error) | Parallel |-| **`Promise.allSettled()`** | Parallel tasks, independent | Never fails (returns status for all) | Parallel |--**Heuristic Rule**: Use `Promise.all()` when you need all results to proceed (e.g., initial data load). Use `Promise.allSettled()` when results are independent (e.g., batching multiple analytics pings).-## Objects, Classes, and Prototypes-- **Prefer Class Syntax**: Use modern `class` over legacy constructor functions and `prototype` manipulation.-- **Use `#` for Private Encapsulation**: Utilize the `#` prefix for internal fields and methods to expose only necessary surface area.-- **Super Calls First**: In subclass constructors, always call `super()` before accessing `this`.-- **Static Utilities**: Use `static` methods for utility functions or domain factories that do not need instance state.- **Safe Property Checks**: Use `Object.hasOwn(obj, "prop")` instead of `obj.hasOwnProperty("prop")`.- **Avoid Prototype Poisoning**: Use `Object.getPrototypeOf()` and `Object.setPrototypeOf()` instead of the legacy `__proto__`.- **Use Getters and Setters**: Encapsulate custom logic, value validation and formatting using `get` and `set`.@@ -92,32 +29,9 @@ class UserService {get hasValidToken(){return validateToken(this.#privateToken)}-- static fromConfig(config) { // Factory utility- return new UserService(config.token);- }}```-## Collections and Iteration--- **Prefer Array Literals**: Use `[]` over `new Array()`.-- **Iterate with `for...of`**: Use `for...of` for standard iterable collections. Use `for...in` sparingly and only for plain object properties (paired with `Object.hasOwn`).-- **Sets for Uniqueness**: Use `Set` when you require collections of unique values.-- **Maps for Complex Keys**: Use `Map` when keys are complex objects or when insertion order is critical.-- **Weak Collections for Memory Management**: Use `WeakMap` or `WeakSet` to associate temporary data with objects without preventing garbage collection.--### JS Collection Decision Matrix--| Requirement | Data Structure | Key Type | Order Preserved |-| :--- | :--- | :--- | :--- |-| **Unique values** | `Set` | Value itself | ✅ Yes |-| **Object-keyed pairs** | `Map` | Any (Objects/Primitives) | ✅ Yes |-| **Standard JSON pairs** | Object `{}` | String / Symbol | ❌ No |-| **Ordered lists** | Array `[]` | Integer Index | ✅ Yes |--**Heuristic Rule**: Use `Map` for dynamic dictionaries and lookup tables, `Set` for lists of unique items, and arrays for ordered lists of non-unique items.-## DOM Manipulation and Performance- **Reduce Layout Thrashing (Reflows)**: Accessing geometric properties (`offsetHeight`, `clientWidth`) after a DOM write forces synchronous layout. Batch all DOM reads first, then all DOM writes.@@ -158,20 +72,17 @@ list.appendChild(fragment); // Single layout recalculation pass## Modern Browser APIs-- **Prefer Modern Browser APIs over Third Party Libraries** - Use native APIs like `document.querySelectorAll()` over jQuery selectors, and `Object.groupBy()` over Lodash `groupBy()`.+- **Use Object.groupBy()**: Prefer the native modern `Object.groupBy()` to group collection objects by criteria. Do **not** use Lodash `groupBy` or manual loop-based grouping logic.- **Prefer HTML and CSS for UI over JavaScript** - Don't use JavaScript when a feature is possible without it, (e.g., `<details>` and `<summary>` for simple accordion components, Relative Color Syntax for color manipulation, `position:sticky` for sticky positioning, or native form validation).- **Prefer HTML and CSS features over Observers**: Use `<img loading="lazy" />` or scroll driven animations over `IntersectionObserver`, and container queries over `ResizeObserver`.- **Use JavaScript as a Progressive Enhancement**: Anticipate that JavaScript will not always be able to run, and ensure your site is functional without it.-- **Trigger Actions Using `addEventListener()`**: Don't use `on*` HTML attributes like `onclick`.- **Avoid Extending CustomEvent**: Use native events like `TouchEvent` or `FocusEvent` when possible, or extend `Event`.- **Avoid Recreating Native Elements**: Use `<button>` to trigger events, `<a>` to navigate, etc. Avoid replicating their behavior by adding event listeners to `<div>` or other generic elements. Do use JavaScript to add required dynamic ARIA, for instance `aria-expanded` or `aria-selected`.## Security- **Prevent DOM-XSS with Trusted Types**: Enforce Trusted Types in CSP to reject direct raw string assignments to dangerous sinks (like `innerHTML`). Use standard sanitization libraries like **DOMPurify** with `RETURN_TRUSTED_TYPE: true`.-- **Never Use Eval Utilities**: Avoid `eval()`, `setTimeout(string)`, or `new Function()`. Use `JSON.parse()` for parsing and standard functions for evaluation.## Delivery- **Use Import Maps**: Use `<script type="importmap">` to control how `import` statements resolve.-- **Preprocess Scripts to Reduce Filesize**: Use preprocessor tooling to minimize and tree shake the scripts delivered in production.diff --git a/skills/modern-web-guidance/guides/security/security.md b/skills/modern-web-guidance/guides/security/security.mdnew file mode 100644index 0000000..d30b6f2--- /dev/null+++ b/skills/modern-web-guidance/guides/security/security.md@@ -0,0 +1,350 @@+# Web Security++Guidelines for implementing preventative security measures on the web safely and incrementally.++**NOTE**: This skill covers standard web platform defenses, focusing mostly on the browser. Applications still require comprehensive server-side security, authorization models, and input validation.++## Table of Contents++- When to apply this skill+- Phase 1: Quick Wins & Obvious Anti-Patterns+ - 1.1 Secure Contexts+ - 1.2 Avoid Dangerous DOM Sinks+ - 1.3 Secure Cookies+ - 1.4 Clickjacking Protection (Frame-Ancestors & X-Frame-Options)+ - 1.5 Secure Window Messaging (postMessage)+- Phase 2: Discovery & Data Collection (Prerequisites)+ - 2.1 Inspect the Application+ - 2.2 Deploy Report-Only Policies+ - 2.3 Data Hygiene for Reports+ - 2.4 Automated Discovery via Browser APIs and DevTools+- Phase 3: Interpreting Results & Enforcement+ - Core enforcement (data-driven rollouts)+ - 3.1 Analyzing CSP Reports+ - 3.2 Transitioning to CSP Enforcement+ - 3.3 Trusted Types Enforcement+ - 3.4 Cross-Origin Opener Policy (COOP)+ - 3.5 Cross-Origin Resource Policy (CORP)+ - 3.6 Cross-Origin Isolation+ - 3.7 Fetch Metadata (Resource Isolation)+ - Companion policies (deploy in parallel)+ - HTTP Strict Transport Security (HSTS)+ - X-Content-Type-Options+ - Referrer Policy+ - Permissions Policy+ - Subresource Integrity (SRI)+ - Cross-Origin Resource Sharing (CORS)+ - Clear-Site-Data (Logout)++## When to apply this skill++The right starting point depends on the application:++- **Retrofitting an existing app**: Always start at Phase 1. Strict policies applied without discovery will break the app. Treat Phase 2 (report-only) as a prerequisite for any Phase 3 enforcement.+- **Greenfield app or new feature**: You can adopt Phase 3 enforced policies directly, but still wire up reporting from day one.+- **SaaS template / framework defaults**: Ship Phase 1 hygiene and Phase 3 policies enabled by default, with Phase 2 reporting on so downstream users can detect regressions.++If you are unsure which case applies, default to Phase 1 → 2 → 3 in order.++**Focusing on Leverage**: While Phase 1 and 2 establish baseline hygiene and data gathering, Phase 3 core enforcement represents the highest-leverage security work. Specifically, Injection/XSS mitigation through CSP (§3.2) and Trusted Types (§3.3) addresses the largest practical threat, while companion policies and isolation defenses provide important defense-in-depth.++## Phase 1: Quick Wins & Obvious Anti-Patterns++Before attempting to deploy global security policies, focus on code-level hygiene and immediate fixes that do not risk breaking the application.++### 1.1 Secure Contexts+- **DO**: Deliver resources over HTTPS to protect against both passive and active network attackers.+- **DO**: Serve a header like `Strict-Transport-Security: max-age=31536000; includeSubDomains; preload` to force HTTPS whenever possible.+- **TIP**: In production rollout, start with a short `max-age` (e.g., 300 seconds) and incrementally increase to 1 year. A misconfigured HSTS with a long max-age can render the site permanently inaccessible until the cache expires in every browser that saw it.++### 1.2 Avoid Dangerous DOM Sinks+- **DO**: Prefer `textContent` or `innerText` over `innerHTML` when setting text content.+- **DO**: Use `setHTML` (part of the Sanitizer API) when available to safely insert HTML.+- **DO NOT**: Use `innerHTML` or `setHTMLUnsafe` with untrusted or unsanitized input.+- **DO**: Use DOMParser or create elements programmatically (`document.createElement`) instead of concatenating HTML strings.++**Dangerous sinks to grep for**: `innerHTML`, `outerHTML`, `document.write`, `eval`, `setTimeout` with a string argument, `script.src`.++**Code Pattern:**+```javascript+// Unsafe+element.innerHTML = `Hello, ${untrustedName}!`;++// Safe+element.textContent = `Hello, ${untrustedName}!`;+```++Trusted Types can enforce this pattern at runtime by blocking string assignments to dangerous sinks. Deploying it is a CSP enforcement step with real breakage risk — see §3.3.++### 1.3 Secure Cookies+Ensure new cookies are configured securely by default.+- **DO**: Prefer naming cookies with the `__Host-` prefix when they'll only be used by one domain. This requires the `Secure` and `Path=/` attributes to be set, and the `Domain` attribute to be omitted. This protects against same-site and network attackers.+- **DO**: Prefer naming cookies with the `__Secure-` prefix when `__Host-` isn't appropriate. This requires the `Secure` attribute, and protects against network attackers.+- **DO**: Explicitly set `SameSite=Lax` for standard first-party cookies.+- **DO**: If your application will be embedded as an iframe in third-party contexts, use `SameSite=None; Secure; Partitioned`.+- **DO NOT**: Rely on unpartitioned `SameSite=None` — these are being systematically blocked for tracking prevention.++```http+Set-Cookie: __Host-session_id=value; SameSite=Lax; HttpOnly; Secure; Path=/+Set-Cookie: third_party_var=value; SameSite=None; Secure; Partitioned+```++### 1.4 Clickjacking Protection (Frame-Ancestors & X-Frame-Options)+Clickjacking protection is easy to deploy, carries extremely low risk of breaking legitimate functionality, and provides immediate defense against malicious UI redressing.+- **DO**: Set the `X-Frame-Options: SAMEORIGIN` header to prevent other sites from embedding your pages in an iframe (or use `DENY` if you should never be embedded).+- **DO**: For fine-grained control, use `frame-ancestors 'self'` (or specified trusted domains) in your CSP header.++```http+X-Frame-Options: SAMEORIGIN+Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com;+```++### 1.5 Secure Window Messaging (postMessage)+If your application communicates with other origins using `window.postMessage`, you must strictly validate the sender and receiver.+- **DO**: Always validate the `event.origin` of incoming messages on the receiver side using strict equality against a list of trusted origins. Do **not** trust wildcards (`*`) or unverified payloads.+- **DO**: Always specify a target origin (rather than the wildcard `*`) when calling `postMessage` to send sensitive data, ensuring only the intended origin can receive it.+- **DO**: Validate and sanitize the properties of incoming message payloads before performing operations or writing them to DOM sinks. Manual JSON serialization is unnecessary as `postMessage` handles object cloning internally.++```javascript+// Receiver (Safe - traditional string check)+window.addEventListener('message', (event) => {+ if (event.origin !== 'https://trusted-origin.com') return;+ const data = event.data;+ if (data && data.action === 'update') {+ // Process data safely+ }+});++// Sender (Safe)+targetWindow.postMessage({ action: 'update' }, 'https://trusted-origin.com');+```++## Phase 2: Discovery & Data Collection (Prerequisites)++Do not blindly apply strict policies to an existing application. You must first understand the application's constraints by collecting data.++### 2.1 Inspect the Application+Before turning anything on, gather facts:+- **Grep for existing security headers** in server config, middleware, CDN/edge config, and meta tags: `Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`, `Permissions-Policy`, `Cross-Origin-*`, `Access-Control-*`, `Timing-Allow-Origin`, `Reporting-Endpoints`.+- **Enumerate inline scripts and styles** in server-rendered templates and static HTML — these will need nonces, hashes, or refactoring.+- **List third-party script origins** loaded by the app (analytics, ads, tag managers, CDNs). These dictate what `script-src` must allow or whether `'strict-dynamic'` is viable.+- **Identify popup-dependent flows**: OAuth, payment gateways, SSO. These constrain COOP choices.+- **Identify cross-origin embeds and embedders**: iframes the app loads, and sites that embed the app. These constrain COEP/CORP/`frame-ancestors`.+- **Enumerate required browser features**: List any features (camera, geolocation, microphone, fullscreen) used by the app or embedded third-party widgets to inform `Permissions-Policy`.+- **Identify dynamic dependencies**: Check if third-party scripts are versioned or if they receive silent updates, determining if `SRI` can be used.+- **Map cross-site integrations**: List all incoming Webhooks, cross-site APIs, or SSO redirect endpoints so `Fetch Metadata` resource isolation policies don't break them.++### 2.2 Deploy Report-Only Policies+Use "Report-Only" headers to identify potential breakages before they happen.+- **DO**: Use report-only headers to dry-run policies without enforcement. Standard report-only headers include:+ - `Content-Security-Policy-Report-Only` for CSP rules.+ - `Cross-Origin-Opener-Policy-Report-Only` for COOP isolation.+ - `Cross-Origin-Embedder-Policy-Report-Only` for COEP isolation.+ - `Document-Policy-Report-Only` for document features.+- **DO**: Define a `Reporting-Endpoints` header so violations have somewhere to go, and reference its name from `report-to`. Recommend setting an endpoint named `default`, which will automatically capture deprecation and crash reports.+- **DO**: Run report-only for long enough to cover real traffic patterns (typically days to weeks), not just synthetic testing.++**Example headers:**+```http+Reporting-Endpoints: default="https://reports.example/default", main-endpoint="https://reports.example/main"+Content-Security-Policy-Report-Only: script-src 'nonce-{RANDOM}' 'strict-dynamic' 'report-sample'; object-src 'none'; base-uri 'none'; report-to main-endpoint;+```++The `'strict-dynamic'`, `https:`, and `'unsafe-inline'` tokens together form a backwards-compatibility ladder: modern browsers honor `'strict-dynamic'` (nonce-propagating) and ignore the others; older browsers fall back to `https:`; very old browsers fall back to `'unsafe-inline'`. The fallbacks are harmless on any browser that supports a stricter token.++**Managing report false-positives**: Reporting endpoints receive a significant volume of false-positive violation reports caused by client-side middleware, aggressive browser extensions, ancient browsers, web crawlers, or antivirus scanners. When analyzing report-only logs, focus on high-frequency patterns from modern user-agents and filter out noise before making deployment decisions. Specifically:+- **Filter out noise**: Ignore reports sent by old browsers with known bugs triggering spurious violations, reports for markup known to be injected by popular browser extensions or client-side middleware (like identical reports seen across many distinct applications), and reports that do not contain enough information to debug.+- **Ignore low-volume reports**: If a policy is deployed, a low violation volume often indicates a false positive that can be safely ignored.+- **Leverage `'report-sample'`**: Always include `'report-sample'` in your `script-src` directives. This instructs the browser to include the first 40 characters of the violating script or inline code snippet in the violation report, which makes debugging much easier.++### 2.3 Data Hygiene for Reports+- **DO NOT**: Include sensitive data (PII, authentication tokens, session identifiers, query strings with secrets) in logs or violation reports. Mask or omit them at the edge before they reach the reporting endpoint.++### 2.4 Automated Discovery via Browser APIs and DevTools+- **Reporting API**: Use `Reporting-Endpoints` in combination with report-only headers (e.g., `Content-Security-Policy-Report-Only`, `Document-Policy-Report-Only`) to have the browser automatically post violations to your server.+- **Browser DevTools**: Use the **Issues Tab** in modern browsers (e.g., Chrome DevTools). It automatically surfaces blocked resources, mixed content, third-party cookie deprecation warnings, and feature policy violations without you having to crawl the codebase manually.++## Phase 3: Interpreting Results & Enforcement++After collecting data, decide how to proceed with enforcement. Phase 3 has two tracks that run in parallel, not in sequence:++- **Core enforcement (data-driven rollouts)** — high-breakage-risk policies that depend on Phase 2 report-only data. These are the rollouts you stage and watch.+- **Companion policies (deploy in parallel)** — lower-risk headers that can be turned on alongside or before the core work, with little or no Phase 2 discovery required.++### Core enforcement (data-driven rollouts)++#### 3.1 Analyzing CSP Reports++When reviewing CSP violation reports, first separate the noise (per §2.2) from legitimate application issues. For violations that appear to be caused by an incompatibility in your application (usually those where the "Sample" or "Blocked URI" seem like legitimate scripts or assets that might be present in your markup):+- **Code Search**: Search your codebase for the offending script source, URL, or hash to see if it is present in your code, dynamic server templates, or static HTML files.+- **Console Auditing**: Open the page that triggered the violation (the "Document URI" in the report) using the same browser, and check the developer tools/console for CSP violations while exercising as much application functionality as possible (some violations only trigger on specific user interactions).++Once filtered and triaged, analyze the reports against the following common scenarios:++- **Scenario**: Many violations for inline scripts.+ - **Condition**: The app uses a framework that relies on inline scripts.+ - **Decision**: Implement Nonces (server-rendered) or Hashes (static) before enforcing.+- **Scenario**: Violations for third-party analytics scripts.+ - **Condition**: The scripts are required.+ - **Decision**: Use `'strict-dynamic'` with a per-request nonce so the analytics loader can attach its dependencies. Do **not** add the analytics origin to a URL allowlist — domain allowlists are bypassable via open redirects, JSONP, and dependency injection on the listed origin.+- **Scenario**: Trusted Types violations on specific sinks.+ - **Condition**: Legacy code paths still write strings to `innerHTML` etc.+ - **Decision**: Refactor those sinks (per §1.2) or route them through a Trusted Types policy (§3.3) before enforcing.++#### 3.2 Transitioning to CSP Enforcement+Only move to enforced mode when:+1. Violations in the report-only logs have dropped to near zero or are accounted for.+2. Reporting remains wired up after the switch — keep `report-to` on the enforced header so regressions are visible.++**Key directives to set:**+- `script-src` with nonces or hashes — this is the core directive of any CSP and the primary mechanism to prevent XSS.+- `base-uri 'none'` to block `<base>` hijacking. Legacy directives like `object-src 'none'` can be omitted in modern, post-Flash web environments.+- *Optional but potentially breaking*: `default-src 'self'` is sometimes used as a fallback for unspecified fetch directives, but it dramatically complicates deployment and has little security value beyond `script-src`. It is generally safer to focus on robust `script-src` enforcement first.+- *Optional*: `form-action 'self'` prevents form submissions to attacker-controlled origins.+- *Optional*: `upgrade-insecure-requests` auto-upgrades subresource HTTP loads to HTTPS, though modern browsers largely auto-upgrade mixed content anyway.++**Enforced Header Example (CSP with reporting):**+```http+Reporting-Endpoints: main-endpoint="https://reports.example/main"+Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic' 'report-sample'; object-src 'none'; base-uri 'none'; report-to main-endpoint;+```++HTML for nonce-based CSP:+```html+<script nonce="{RANDOM}" src="https://example.com/script.js"></script>+```++For static/cached HTML (SPAs) where a per-response nonce is not possible, use hash-based CSP: hash each inline script and list the hashes in `script-src`.++**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.++- **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.++```javascript+if (window.trustedTypes && trustedTypes.createPolicy) {+ const policy = trustedTypes.createPolicy('escapePolicy', {+ createHTML: str => str.replace(/</g, '<').replace(/>/g, '>')+ });+ el.innerHTML = policy.createHTML(untrustedString);+}+```++#### 3.4 Cross-Origin Opener Policy (COOP)++Lowest-risk of the three. Deploy if the app is **not** an OAuth provider, payment processor, or otherwise expected to be reached from an opener.++- **DO**: Use `Cross-Origin-Opener-Policy: same-origin-allow-popups` — prevents a malicious opener from mounting XS-leaks attacks while still allowing OAuth and payment flows that *the app itself* initiates.+- **DO NOT**: Jump straight to `same-origin` unless you have explicitly verified that no integrations rely on cross-origin `window.opener` access.++#### 3.5 Cross-Origin Resource Policy (CORP)++Set CORP explicitly on each response based on whether it should be embeddable in other contexts. Two core benefits: it protects resources from malicious cross-origin reads, and ensures compatibility when pages request stronger client-side isolation.++- **DO**: Default to `Cross-Origin-Resource-Policy: same-origin` for app-internal resources (authenticated data, user session JSON, restricted internal scripts).+- **DO**: Use `same-site` for endpoints utilized across subdomains of the same eTLD+1.+- **DO**: Provide `cross-origin` exclusively for resources created for generic embedding or widely cached delivery (e.g., static shared assets or public CDNs).++#### 3.6 Cross-Origin Isolation++Highest deployment breakage risk. You only need to deploy this infrastructure if the application requires features relying on `SharedArrayBuffer` (e.g., WebAssembly multi-threading or shared memory architectures). If not required, skip this policy group.++- **Preferred path (Chromium environments)**: Enable `Document-Isolation-Policy: isolate-and-credentialless`. This provides client-side isolation comparable to COEP while instructing the browser to strip cookies and authentication credentials from non-CORS cross-origin resource fetches rather than blocking them outright. Note that this is supported primarily in Chrome (142+) and other vendors have not yet shown interest, so evaluate carefully based on your target audience. Apps that need to *block* cross-origin resources lacking explicit CORP opt-in (rather than load them with credentials stripped) can adopt `isolate-and-require-corp` instead. This is stricter and harder to deploy — it requires the same subresource audit as the cross-browser path below.+- **Cross-browser path (Complex enforcement)**: Require `Cross-Origin-Opener-Policy: same-origin` coupled with `Cross-Origin-Embedder-Policy: require-corp`. Every embedded subresource (images, styles, external media) MUST serve an explicit `Cross-Origin-Resource-Policy` header or the browser will prevent it from loading.++```http+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corp+Cross-Origin-Resource-Policy: same-origin+```++#### 3.7 Fetch Metadata (Resource Isolation)+Server-side enforcement that uses `Sec-Fetch-*` request headers to reject suspicious cross-site requests. Requires the cross-site integration mapping from §2.1 before enforcing.++- **DO**: Implement a server-side resource isolation policy that checks `Sec-Fetch-*` headers and rejects `cross-site` requests for non-navigational endpoints.+- **DO**: Reject disallowed requests *before* authentication or authorization checks, so the response does not leak timing information about whether a resource or session exists.+- **DO**: Include `Vary: Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site` to prevent intermediate caches (CDNs) from serving cached responses to attackers.+- **CAUTION**: `same-site` trusts every subdomain under your eTLD+1. If any subdomain hosts user-generated content, a legacy app, or otherwise untrusted code, drop `same-site` from the allowlist and accept only `same-origin` and `none`.+- **CAUTION**: Misconfiguring these checks will block legitimate API requests coming from cross-site integrations, SSO handlers, or Webhooks. Ensure you log and test your `Sec-Fetch-*` constraints beforehand.++```javascript+app.use((req, res, next) => {+ const site = req.get('Sec-Fetch-Site');+ const mode = req.get('Sec-Fetch-Mode');+ const dest = req.get('Sec-Fetch-Dest');++ if (!site) return next(); // Fallback for legacy browsers++ if (['same-origin', 'same-site', 'none'].includes(site)) return next();++ // Allow standard navigate GET requests (link clicks)+ if (site === 'cross-site' && mode === 'navigate' && req.method === 'GET' && !['object', 'embed'].includes(dest)) {+ return next();+ }++ res.status(403).send('Forbidden');+});+```++### Companion policies (deploy in parallel)++These carry significantly lower breakage risk than the core enforcement track. They can be deployed alongside — or before — the CSP and isolation rollouts.++#### HTTP Strict Transport Security (HSTS)+- **DO**: `Strict-Transport-Security: max-age=31536000; includeSubDomains; preload` to force HTTPS.+- **TIP**: In production rollout, start with a short `max-age` (e.g., 300 seconds) and incrementally increase to 1 year. A misconfigured HSTS with a long max-age can render the site permanently inaccessible until the cache expires in every browser that saw it.++#### X-Content-Type-Options+- **DO**: Set `X-Content-Type-Options: nosniff` to block MIME-type sniffing.+- **DO**: Ensure the server serves correct `Content-Type` headers for all resources (`application/javascript` for scripts, `application/json` for APIs, `text/html` for documents, etc.) so the browser can strictly enforce the `nosniff` constraint.++#### Referrer Policy+- **DO**: Use `Referrer-Policy: strict-origin-when-cross-origin` as a safe default.++#### Permissions Policy+- **DO**: Disable unused browser features (camera, geolocation, microphone) for the page and iframes using Structured Fields syntax.+- **DO**: When delegating features to an iframe, use the `allow` attribute in HTML *in addition* to the header.+- **CAUTION**: Unintentionally blocking a delegated feature will cause silent failures in third-party widgets (like embedded video players or payment gateways). Audit third-party dependencies before blocking.++```http+Permissions-Policy: camera=(), geolocation=(), microphone=()+```++```html+<iframe src="https://trusted-video.com/player" allow="fullscreen; camera"></iframe>+```++#### Subresource Integrity (SRI)+- **DO**: Use the `integrity` attribute with a cryptographic hash (preferring `sha256` or `sha512`) when loading third-party scripts, combined with `crossorigin="anonymous"`.+- **DO**: Ensure the server/CDN sends an appropriate `Access-Control-Allow-Origin` header so the browser can compute the hash.+- **DO NOT**: Use SRI for dynamic or unversioned assets — silent updates will cause script execution to fail. SRI is strictly for immutable, versioned assets.++```html+<script src="https://cdn.example.com/lib.js" integrity="sha256-H8df...39v" crossorigin="anonymous"></script>+```++#### Cross-Origin Resource Sharing (CORS)+CORS is a permission grant, not a defense — it tells the browser which cross-origin reads to allow. The risk is misconfiguring it as too permissive.++- **DO**: Validate the `Origin` header on the server and set `Access-Control-Allow-Origin` dynamically to specific origins (rather than wildcard `*`).+- **DO NOT**: Use wildcard `*` for `Access-Control-Allow-Origin` if `Access-Control-Allow-Credentials: true` is required — the browser will reject the response.+- **DO**: Handle preflight (`OPTIONS`) requests by returning appropriate headers before processing data.++```http+Access-Control-Allow-Origin: https://trusted-app.com+Access-Control-Allow-Credentials: true+```++#### Clear-Site-Data (Logout)+- **DO**: Use `Clear-Site-Data` on logout endpoints to ensure complete session termination.++```http+Clear-Site-Data: "cookies", "storage", "cache"+```diff --git a/skills/modern-web-guidance/guides/user-experience/reduce-style-repetition.md b/skills/modern-web-guidance/guides/user-experience/reduce-style-repetition.mdnew file mode 100644index 0000000..7fd6e9f--- /dev/null+++ b/skills/modern-web-guidance/guides/user-experience/reduce-style-repetition.md@@ -0,0 +1,85 @@+# Reduce Style Repetition with CSS Functions++Maintaining large stylesheets often leads to repetitive logic, especially when dealing with design system tokens like gradients or responsive layout patterns.++The CSS `@function` at-rule allows you to encapsulate this logic into reusable, parameterized functions, making your CSS more maintainable, consistent and DRY (Don't Repeat Yourself).++## The `@function` Syntax++A custom function is defined using the `@function` rule followed by a dashed name and a list of parameters. The function returns a value using the `result` property.++```css+@function --my-function(--input1 <length>, --input2: default-value) returns <length> {+ /* Logic goes here */+ result: var(--input1);+}+```++### Key Concepts+- **Parameters:** Must start with a double dash (`--`).+- **Defaults:** You can provide default values using a colon (`:`).+- **Result:** The `result` property determines the value the function returns. The last `result` declared in the function body wins.+- **Scoping:** Parameters and variables defined inside the function are locally scoped.+- **Types:** You can require parameters and the returned value to match a CSS type with bracket notation (e.g., `<color>`) and allow multiple types with the `type` function (e.g., `type(<number> | <percentage>)`).++## Practical Examples++### 1. Design System Tokens (Gradients)+Ensure consistent color gradients across your app by encapsulating gradient logic. The `--angle` provides a default value to provide consistency that can be overridden.++```css+@function --fancy-gradient(--start-color <color>, --end-color <color>, --angle: 98deg) returns <image>{+ result: linear-gradient(in oklab var(--angle), var(--start-color), var(--end-color) );+}++.card {+ background: --fancy-gradient(#ed73d7, #5d87e9);+}+```++### 2. Conditional Layout Logic+You can use `@media` or other queries directly inside a function to return different values based on the environment. When using conditional logic in a function, note that the `@function` does not "return" at the first value of `result`, but rather follows the CSS cascade, and resolves to the last value that matches based on the screen size, container size, or other query.++```css+@function --grid-template(--count <number>){+ /* MANDATORY: Put default value first. */+ result: 1fr; /* Default: stack */+ @media (min-width: 800px) {+ result: repeat(var(--count), 1fr); /* Grid on larger screens */+ }+}++main {+ display: grid;+ grid-template-columns: --grid-template(2);+}+```++## Best Practices+- **Use Dashed Names:** Always prefix your function names and parameters with `--`.+- **Provide Defaults:** Make your functions more robust by providing sensible default values.+- **Keep it Simple:** Use functions for logic that is actually repeated or complex. Don't over-engineer simple property-value pairs.+- **Use Types:** Ensure your parameters and return values are the expected types.+- **Consider Precompiled Alternatives:** For functions that do not depend on user input, media queries or other client-side variation, consider using a CSS precompiler to avoid doing unnecessary work on the client.++### Fallback strategies++@function has limited availability.++In browsers that do not support CSS Functions, values set using CSS functions will be invalid. To support other browsers, provide a fallback value for the property first. This will be overridden in browsers with CSS function support.++```css+.card {+ /* Provide fallback, in this case a solid color. */+ background: #5d87e9;+ background: --fancy-gradient(#ed73d7, #5d87e9);+}++main {+ /* Provide fallback, in this case a simple stacked default. */+ grid-template-columns: 1fr;+ grid-template-columns: --grid-template(2);+}+```++If it is a requirement to reduce style repetition while supporting other browsers, consider a CSS precompiler with functions, like Sass.diff --git a/skills/modern-web-guidance/guides/user-experience/scroll-snap-realtime-feedback.md b/skills/modern-web-guidance/guides/user-experience/scroll-snap-realtime-feedback.mdnew file mode 100644index 0000000..c34d2d1--- /dev/null+++ b/skills/modern-web-guidance/guides/user-experience/scroll-snap-realtime-feedback.md@@ -0,0 +1,150 @@+## Overview+Users expect immediate visual feedback when interacting with UI elements like carousels or galleries. Traditional scroll snap only provides feedback *after* the scroll gesture completes and the element settles. By using Scroll Snap Events, specifically `scrollsnapchanging`, you can provide real-time feedback during the scroll gesture, highlighting the pending snap target before the user releases their touch or mouse.++## Implementation++### 1. Listen for `scrollsnapchanging`+Attach an event listener for `scrollsnapchanging` to the scroll container. This event fires when the browser determines a new snap target is likely to be selected.++```javascript+const container = document.querySelector('#gallery');+const thumbnails = document.querySelectorAll('.thumbnail');+const items = document.querySelectorAll('.gallery-item');++container.addEventListener('scrollsnapchanging', (event) => {+ // Highlight pending snap target during scroll for real-time feedback.+ const pendingTarget = event.snapTargetInline;+ const index = [...items].indexOf(pendingTarget);++ if (index === -1 || !thumbnails[index]) return;++ // Use lightweight class toggle to avoid layout thrashing during rapid events.+ // Note: aria-current is NOT toggled here. It tracks the settled "current"+ // item, which is updated in the scrollsnapchange handler below.+ thumbnails.forEach((thumb) => thumb.classList.remove('pending'));+ thumbnails[index].classList.add('pending');+});+```++This example uses `snapTargetInline` because the gallery scrolls horizontally. If your scroll container scrolls vertically, use `snapTargetBlock` instead.++### 2. Listen for `scrollsnapchange`+To finalize the state when the scroll gesture completes and the element actually snaps, listen for the `scrollsnapchange` event. This is required to establish the final active state.++```javascript+container.addEventListener('scrollsnapchange', (event) => {+ // Promote pending state to active on scroll completion.+ const snappedTarget = event.snapTargetInline;+ const index = [...items].indexOf(snappedTarget);++ if (index === -1 || !thumbnails[index]) return;++ // Establish final active state and clean up pending.+ thumbnails.forEach((thumb) => {+ thumb.classList.remove('pending', 'active');+ thumb.removeAttribute('aria-current');+ });+ thumbnails[index].classList.add('active');+ thumbnails[index].setAttribute('aria-current', 'true');+});+```++### 3. Sync initial state+When the page loads, the scroll position might be restored by the browser (e.g., via history traversal or an anchor link). Neither `scrollsnapchange` nor `scroll` events will fire automatically. Run a one-off geometric check to sync the UI with the initial scroll position.++```javascript+// Note: For item.offsetLeft to be relative to the container,+// the container MUST be the offsetParent (e.g., `position: relative`).+const findClosestItemIndex = () => {+ // Center-distance assumes scroll-snap-align: center on items.+ // For start-aligned snap, compare scrollLeft to item.offsetLeft directly.+ const containerCenter = container.scrollLeft + container.clientWidth / 2;+ let closestIndex = 0;+ let minDistance = Infinity;++ items.forEach((item, index) => {+ const itemCenter = item.offsetLeft + item.offsetWidth / 2;+ const distance = Math.abs(containerCenter - itemCenter);+ if (distance < minDistance) {+ minDistance = distance;+ closestIndex = index;+ }+ });+ return closestIndex;+};++const initActiveItem = () => {+ const closestIndex = findClosestItemIndex();+ if (!thumbnails[closestIndex]) return;++ thumbnails.forEach((thumb) => {+ thumb.classList.remove('pending', 'active');+ thumb.removeAttribute('aria-current');+ });+ thumbnails[closestIndex].classList.add('active');+ thumbnails[closestIndex].setAttribute('aria-current', 'true');+};++if (document.readyState === 'complete') {+ initActiveItem();+} else {+ window.addEventListener('load', initActiveItem, { once: true });+}+```++### Fallback strategies+Scroll snap events has limited availability.+Baseline status for Scroll snap: Widely available. It's been Baseline since 2020-01-15.++For browsers that do not support `scrollsnapchanging`, the UI will not provide eager feedback during the scroll gesture by default, and the linked UI will desynchronize from the content.++**MANDATORY:** Provide a fallback for browsers without support, or the linked UI will desynchronize from the content.++**DO** simulate the real-time nature of `scrollsnapchanging` with a `scroll` event listener coupled with `requestAnimationFrame` and geometric distance calculations to determine the closest snap target while the user is actively scrolling.++```javascript+if ('onscrollsnapchanging' in Element.prototype) {+ // Use native scroll snap events+} else {+ // Fallback: use scroll + requestAnimationFrame for eager feedback+ // (assumes the same container, thumbnails, items defined in step 1)+ let scrollTimeout;+ let rafId = null;++ const promotePendingToActive = () => {+ const closestIndex = findClosestItemIndex();+ if (!thumbnails[closestIndex]) return;+ thumbnails.forEach((thumb) => {+ thumb.classList.remove('pending', 'active');+ thumb.removeAttribute('aria-current');+ });+ thumbnails[closestIndex].classList.add('active');+ thumbnails[closestIndex].setAttribute('aria-current', 'true');+ };++ container.addEventListener('scroll', () => {+ if (rafId) return;+ rafId = requestAnimationFrame(() => {+ rafId = null;+ const closestIndex = findClosestItemIndex();+ if (!thumbnails[closestIndex]) return;++ // DO NOT forget to clean up stale pending classes+ thumbnails.forEach((thumb) => thumb.classList.remove('pending'));+ thumbnails[closestIndex].classList.add('pending');+ });++ // Debounce fallback for browsers that don't support scrollend+ clearTimeout(scrollTimeout);+ scrollTimeout = setTimeout(promotePendingToActive, 100);+ }, { passive: true });++ // Fallback: use Baseline `scrollend` event to promote pending to active cleanly where supported+ container.addEventListener('scrollend', () => {+ clearTimeout(scrollTimeout);+ promotePendingToActive();+ });+}+```++The geometric `scroll` + `requestAnimationFrame` fallback closely emulates the behavior of native snap prediction, including handling programmatic scrolling correctly. Because functions like `scrollIntoView` naturally fire `scroll` events during their execution, the UI will stay smoothly synchronized throughout the scroll animation without requiring additional custom logic.diff --git a/skills/modern-web-guidance/guides/user-experience/scroll-snap-state-sync.md b/skills/modern-web-guidance/guides/user-experience/scroll-snap-state-sync.mdnew file mode 100644index 0000000..c045af7--- /dev/null+++ b/skills/modern-web-guidance/guides/user-experience/scroll-snap-state-sync.md@@ -0,0 +1,81 @@+Synchronizing UI state with a scrollable container's snap position traditionally required complex scroll event listeners, manual calculations of scroll offsets, and intersection observers. The `scrollsnapchange` event provides a native, efficient way to detect when a scroller has settled on a new snap target, making it useful for synchronizing sidebars or highlighting the active section in a table of contents.++## Implementation++### 1. Configure Scroll Snap in CSS+The container must have `scroll-snap-type` defined, and have children with `scroll-snap-align` for the browser to track snap targets. In a long article with a table of contents, you can use this to snap section headers to the top of the viewport.++```css+main {+ /* Enable scroll snapping on the container */+ scroll-snap-type: y proximity;+ overflow-y: auto;+}++h2 {+ /* Define how headers align when snapped */+ scroll-snap-align: start;+}+```++### 2. Listen for Snap Changes+Use the `scrollsnapchange` event on the scroll container to react when the user finishes scrolling and the browser snaps to a new element. In our TOC demo, we use this to highlight the active link in the sidebar.++```javascript+const main = document.getElementById('main');+const links = document.querySelectorAll('nav a');++// The event fires when the scroller settles on a new snap target+main.addEventListener('scrollsnapchange', (event) => {+ // Use snapTargetBlock for vertical or snapTargetInline for horizontal+ const snappedHeader = event.snapTargetBlock;++ if (snappedHeader) {+ setSelectedParagraph(snappedHeader.id);+ }+});+```+++## Accessibility++Caution: While Scroll Snap Events make it possible to visually synchronize other content to the state of the scroller, it does not automatically expose that information programmatically. Relationships between elements, active states, and live content must be reflected in the Accessibility Tree.++For a table of contents, ensure the sidebar links use `aria-current="true"` or `aria-current="location"` when they are active.++In addition, be careful when using the `mandatory` value for `scroll-snap-type`, as it can cause content in-between snap-points to become inaccessible when longer than the screen.+++## Fallback strategies++Scroll snap events has limited availability.++If `scrollsnapchange` is not supported, use `IntersectionObserver` to detect which element is currently at the top of the scroller. Note this is different behavior than `scrollsnapchange`, as this will trigger while the scroll happens, rather than only when the scroll has settled.++```javascript+// Feature detect support for scroll snap events+if (!('onscrollsnapchange' in HTMLElement.prototype)) {+ const observer = new IntersectionObserver(+ () => {+ // Each time the set of intersecting headers changes, find the top+ // header that is visible.+ const topEntry = [...headers].reduce((currentTop, header) => {+ // Use the bottom to handle scrolling up, when the top is still offscreen+ const {bottom} = header.getBoundingClientRect();+ // Don't match if the header's bottom is aboce the scrollport+ if (bottom < 0) return;+ if (!currentTop) return header;+ return bottom <+ currentTop.getBoundingClientRect().bottom+ ? header+ : currentTop;+ }, undefined);+ if (topEntry) setSelectedParagraph(topEntry.id);+ },+ { root: main, threshold: 0.9 // Adjust based on your use case },+ );++ // Observe all snap targets (e.g., section headers)+ document.querySelectorAll('h2').forEach(header => observer.observe(header));+}+```