Keep your coding agent up to date with the latest web best practices
Release v0.0.53
github-actions[bot]92fdacf2126b
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 084b986..034c2fd 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -8,7 +8,7 @@"name": "modern-web-guidance","source": "./","description": "Google Chrome's agent skills collection",- "version": "0.0.52"+ "version": "0.0.53"}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 30e6415..9230b57 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "modern-web-guidance","description": "Google Chrome's agent skills collection",- "version": "0.0.52",+ "version": "0.0.53","author": {"name": "Google Chrome"}diff --git a/README.md b/README.mdindex 72a112c..798008f 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@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.-#### Skill Coverage in `v0.0.52`+#### Skill Coverage in `v0.0.53`<details><summary><strong>69 web features with implementation guidance from Chrome's experts</strong>: `:autofill`, `:has()`, `:not()`, `:user-valid and :user-invalid`, `@starting-style`, `<details>`, `<dialog closedby>`, `<dialog>`, `<link rel="expect">`, `<link rel="preload">`, `AbortController and AbortSignal`, `Active view transition`, `Anchor positioning`, `blocking="render"`, `calc-size()`, `color-scheme`, `content-visibility`, `Cross-document view transitions`, `Customizable <select>`, `Email, telephone, and URL <input> types`, `enterkeyhint`, `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`, `Intl.DurationFormat`, `Invoker commands`, `light-dark()`, `linear() easing`, `Long animation frames`, `Masks`, `moveBefore()`, `Mutually exclusive <details> elements`, `Navigation API`, `navigator.modelContext`, `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`, `scrollIntoView()`, `sibling-count() and sibling-index()`, `sin(), cos(), tan(), asin(), acos(), atan(), and atan2() (CSS)`, `Speculation rules`, `Temporal`, `text-box`, `text-wrap`, `text-wrap: balance`, `text-wrap: pretty`, `Top-level await`, `transition-behavior`, `View transitions`</summary>diff --git a/gemini-extension.json b/gemini-extension.jsonindex 065b620..b8c5db0 100644--- a/gemini-extension.json+++ b/gemini-extension.json@@ -1,7 +1,7 @@{"name": "modern-web-guidance","description": "Google Chrome's web development agent skills.",- "version": "0.0.52",+ "version": "0.0.53","author": {"name": "Google Chrome"}diff --git a/package.json b/package.jsonindex 1f42c19..d9e444f 100644--- a/package.json+++ b/package.json@@ -3,7 +3,7 @@"displayName": "Modern Web Guidance","private": true,"description": "Curated collection of agent skills for modern web development.",- "version": "0.0.52",+ "version": "0.0.53","publisher": "GoogleChrome","engines": {"vscode": "^1.90.0",@@ -16,11 +16,11 @@"contributes": {"chatSkills": [{- "path": "./skills/modern-web-use-cases/SKILL.md"+ "path": "./skills/modern-web/SKILL.md"}]},"bin": {- "modern-web": "./skills/modern-web-use-cases/modern-web.mjs"+ "modern-web": "./skills/modern-web/modern-web.mjs"}}diff --git a/policies/modern-web-use-cases.toml b/policies/modern-web.tomlsimilarity index 100%rename from policies/modern-web-use-cases.tomlrename to policies/modern-web.tomldiff --git a/skills/modern-web/SKILL.md b/skills/modern-web/SKILL.mdnew file mode 100644index 0000000..fa1e767--- /dev/null+++ b/skills/modern-web/SKILL.md@@ -0,0 +1,62 @@+---+name: modern-web+description: |+ IMPORTANT: This is a search tool that will help you find the most modern and recommended way to implement any web development use case.++ MANDATORY: You MUST execute this FIRST for each and every web development use case, even if you're implementing that use case in a framework like React, especially for writing modern web code. No matter the complexity, you MUST call this tool for ALL web development tasks touching HTML, CSS, or JavaScript.++ Do NOT skip this step even if you already know how to implement the use case — web platform APIs evolve rapidly and your training data may recommend outdated approaches. This tool ensures you use the current best practice.+---++# Modern Web++A skill to search for specific web development use cases and retrieve their corresponding best practice guides.++## When to use++Must use this skill:+- At the **start** of implementing any web feature.+- Before creating a new component, to check if a standardized pattern already exists.+- To avoid implementing ad-hoc solutions or loading large dependencies unnecessarily.++## Usage Instructions++### Step 1. Search Use Cases++Search with an action-oriented query summarizing what you want to achieve using the `--search` flag. Run `modern-web.mjs` directly with `node`.++```sh+node <modern-web-directory>/modern-web.mjs --search "<query>"+```++**Example Output**:+```json+[+ {+ "id": "content-vis",+ "description": "Defer rendering of offscreen content using content-visibility.",+ "category": "performance",+ "distance": "0.85"+ }+]+```++---++### Step 2. Retrieve Best Practices++Once you have a relevant `id` from the search results, call this script using the `--retrieve` flag to get the full guide. You can pass multiple IDs separated by commas.++```sh+node <modern-web-directory>/modern-web.mjs --retrieve "<id>"+```+++**Example Output**:+`The markdown content of the guide describing implementation steps...`++## Guidelines++- Always search **first** to find the most specific design/performance patterns.+- These guides are usually framework-agnostic; adapt them correctly to your setup.+- Do not hallucinate guides or ignore them; they represent the preferred local standard for the user's project.diff --git a/skills/modern-web/guides/accessibility/accessible-error-announcement.md b/skills/modern-web/guides/accessibility/accessible-error-announcement.mdnew file mode 100644index 0000000..6d011dc--- /dev/null+++ b/skills/modern-web/guides/accessibility/accessible-error-announcement.md@@ -0,0 +1,207 @@+# Accessible Error Announcement++## The Problem+Standard HTML5 validation provides visual feedback (via `:invalid` or `:user-invalid`), but it doesn't automatically synchronize with accessibility attributes like `aria-invalid`.++If you use standard `:invalid` styling, screen readers might announce "Invalid entry" the moment a user tabs into a required field that is currently empty. This creates a disruptive experience for users using assistive technologies, as the error is announced before interaction has occurred.++## The Solution+We want the *programmatic* state (`aria-invalid="true"`) to be applied **at the exact same moment** the *visual* state (`:user-invalid`) applies. Since `:user-invalid` relies on the browser's internal "user-interacted" flag, we can use JavaScript to check that this selector matches during standard interaction events.++See [MDN aria-invalid](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-invalid) for more details.++### Implementation Strategy++1. **Visual Layer**: Use CSS `:user-invalid` to show borders/icons.+2. **Accessibility Layer**: Use `aria-invalid` and `aria-errormessage` to communicate state to Assistive Technology (AT).+3. **Bridge Visual & Accessibility Layer**: Create a lightweight JavaScript utility that listens for `blur` and `input` events, checks if the element matches `:user-invalid`, and updates the ARIA attributes accordingly.++## Implementation Guide++### 1. HTML Structure+Link your input to its error message using `aria-errormessage` (or `aria-describedby` for broader support).++```html+<form>+ <div class="field">+ <label for="email">Email</label>+ <input+ type="email"+ id="email"+ required+ aria-errormessage="email-error"+ >+ <span id="email-error" class="error-msg">+ Please enter a valid email address.+ </span>+ </div>+</form>+```++### 2. CSS+Control the visibility of the error message using the native pseudo-class `:user-invalid`.++```css+.error-msg {+ display: none;+ color: #d93025;+}++/* Show error message when input is user-invalid */+input:user-invalid ~ .error-msg {+ display: block;+}++/* Optional: Visual cues on the input itself */+input:user-invalid {+ border-color: #d93025;+}+```++### 3. JavaScript+Since there is no "UserInvalidChanged" event, hook into standard form events to check the state.++```javascript+const updateAriaState = (event) => {+ const input = event.target;+ if (!input.matches?.('input, textarea, select')) return;++ // Check if the browser currently considers this input "user-invalid"+ const isUserInvalid = input.matches(':user-invalid');++ if (isUserInvalid) {+ input.setAttribute('aria-invalid', 'true');+ } else {+ input.removeAttribute('aria-invalid');+ }+};++// Listen on the document to handle dynamically added fields.+// 'blur' and 'focus' do not bubble, so we must use the capture phase (true).+document.addEventListener('blur', updateAriaState, true);+document.addEventListener('focus', updateAriaState, true);++// Also update on input if we've already shown the error,+// so the error clears immediately when fixed.+document.addEventListener('input', (event) => {+ const input = event.target;+ if (!input.matches?.('input, textarea, select')) return;++ const hasAriaInvalid = input.hasAttribute('aria-invalid');+ const ariaInvalid = input.getAttribute('aria-invalid');+ if (hasAriaInvalid && ariaInvalid === 'true') {+ updateAriaState(event);+ }+});+```++## Fallbacking & Browser Support++The `:user-invalid` pseudo-class is widely supported (Baseline 2023), but older browsers need a fallback.++### Feature Detection+You can check for support in CSS and JavaScript.++**JavaScript Check:**+```javascript+if (!CSS.supports('selector(:user-invalid)')) {+ // Fallback logic here+}+```++### CSS for Fallback+To ensure your fallback logic is visually indistinguishable from the native behavior, you must apply your error styles to both the pseudo-class and your fallback class.++```css+/* Apply error styles to both native selector and fallback class */+input:user-invalid,+input.user-invalid-fallback {+ border-color: #d93025;+ background-color: #fce8e6;+}++/* Show error message for both cases */+input:user-invalid ~ .error-msg,+input.user-invalid-fallback ~ .error-msg {+ display: block;+}+```++### Fallback Logic+If `:user-invalid` is missing manually track the interaction state using a `WeakMap`.++```javascript+const UserInvalidFallback = (() => {+ const dirtyState = new WeakMap();++ const updateState = (input) => {+ const isValid = input.checkValidity();++ // Update both visual and ARIA state+ input.classList.toggle('user-invalid-fallback', !isValid);+ input.classList.toggle('user-valid-fallback', isValid);++ if (!isValid) {+ input.setAttribute('aria-invalid', 'true');+ } else {+ input.removeAttribute('aria-invalid');+ }+ };++ const handleEvent = (event) => {+ const input = event.target;++ if (event.type === 'reset' && input.matches?.('form')) {+ const controls = input.elements || [];+ for (const control of controls) {+ dirtyState.delete(control);+ control.classList.remove('user-invalid-fallback');+ control.classList.remove('user-valid-fallback');+ control.removeAttribute('aria-invalid');+ }+ return;+ }++ if (!input.matches?.('input, textarea, select')) return;++ if (event.type === 'input' || event.type === 'change') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasInteracted = true;+ dirtyState.set(input, state);+ if (state.hasBlurred) {+ updateState(input);+ }+ } else if (event.type === 'blur') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasBlurred = true;+ dirtyState.set(input, state);+ if (state.hasInteracted) {+ updateState(input);+ }+ }+ };++ const init = () => {+ if (CSS.supports('selector(:user-invalid)')) return;++ document.addEventListener('blur', handleEvent, true); // Capture phase required+ document.addEventListener('input', handleEvent, true);+ document.addEventListener('change', handleEvent, true);+ document.addEventListener('reset', handleEvent, true); // Capture resets+ };++ return { init };+})();++// Initialize globally+UserInvalidFallback.init();+```++## Other Considerations++1. **`aria-live` vs. `aria-errormessage`**:+ * `aria-errormessage` connects the input to the text, but screen readers might not announce it immediately upon appearance (only when focusing the input).+ * If you need *immediate* announcement when the error appears (e.g., on blur), consider adding `role="alert"` or `aria-live="polite"` to the error message container, but test thoroughly to avoid "double announcement" when the user focuses the field to fix it.++2. **Internationalization**:+ * Ensure the text content of your error message (`#email-error`) is translated. The logic remains the same.diff --git a/skills/modern-web/guides/forms/animated-select-picker.md b/skills/modern-web/guides/forms/animated-select-picker.mdnew file mode 100644index 0000000..425487e--- /dev/null+++ b/skills/modern-web/guides/forms/animated-select-picker.md@@ -0,0 +1,149 @@+# Animated Select Picker++The customizable select API offers a declarative, CSS-driven way to animate `<select>` elements and their dropdown pickers. By combining `appearance: base-select` with modern CSS animation techniques—such as `@starting-style` and the `allow-discrete` transition behavior—you can create fluid, premium UI transitions for top-layer elements without relying on heavy JavaScript libraries.++Previously, animating native select dropdowns was impossible because their UI was rendered outside the accessible viewport constraints. With `appearance: base-select`, the picker becomes styleable and animatable like any other page element.++## How to Implement++To implement an animated select picker:++1. **Opt-in to customization:** Apply `appearance: base-select` to both the `<select>` element and the `::picker(select)` pseudo-element.+2. **Enable auto-sizing transitions (Optional):** Define `interpolate-size: allow-keywords` (usually on `:root`) to allow the browser to transition between discrete metric values like `height: auto` and `height: 0`.+3. **Animate the top-layer container:** Apply standard entry/exit styles to `::picker(select)`. To make sure the opacity transition works when moving between `display: none` and `display: block`, you must use `transition-behavior: allow-discrete` (often written inline as `transition: display 0.3s allow-discrete`).+4. **Hook into the opening state with `@starting-style`:** Use `@starting-style` to define the baseline styles the browser should compute *before* the transition begins. For example, if you want it to fade in, set the opacity to `0` inside the `@starting-style` block.+5. **Rotate the icon:** Use pseudo-element focus or active selectors like `:open::picker-icon` to apply transitions (such as rotation or translation) to the arrow indicator.++## Example Code: Smooth Select Scale and Fade++The following example demonstrates a custom select styled with standard page animations for the picker container.++```html+<!-- Always use a <label> linked via 'for' to the select for accessibility -->+<label for="theme-select">Visual Theme</label>+<select id="theme-select" class="animated-select" name="theme">+ <!-- The <button> inside <select> becomes the visible trigger when appearance: base-select is used -->+ <button>+ <!-- <selectedcontent> automatically displays the content of the chosen <option> -->+ <selectedcontent></selectedcontent>+ </button>+ <option value="system">+ <!-- SVGs are allowed inside options when appearance: base-select is active -->+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>+ <line x1="8" y1="21" x2="16" y2="21"></line>+ <line x1="12" y1="17" x2="12" y2="21"></line>+ </svg>+ System Default+ </option>+ <option value="light">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="5"></circle>+ <line x1="12" y1="1" x2="12" y2="3"></line>+ <line x1="12" y1="21" x2="12" y2="23"></line>+ <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>+ <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>+ <line x1="1" y1="12" x2="3" y2="12"></line>+ <line x1="21" y1="12" x2="23" y2="12"></line>+ <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>+ <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>+ </svg>+ Light UI+ </option>+</select>+```++```css+/* Opt-in to customizable select */+.animated-select,+.animated-select::picker(select) {+ appearance: base-select;+}++/* Enable auto-keyword transitions (usually set globally at :root) */+:root {+ interpolate-size: allow-keywords;+}++/* Style the visible trigger and icon rotation */+.animated-select {+ display: flex;+ align-items: center;+ justify-content: space-between;+ width: 100%;+ padding: 0.875rem 1rem;+ font-size: 1rem;+ border-radius: 8px;+ cursor: pointer;+ transition: border-color 0.2s ease;+}++.animated-select::picker-icon {+ transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);+}++.animated-select:open::picker-icon {+ transform: rotate(180deg);+}++/*+ * The Picker Container+ * Uses top-layer animations with `allow-discrete` visibility hooks+ */+.animated-select::picker(select) {+ background: white;+ border-radius: 12px;+ box-shadow: 0 10px 25px -3px rgba(0,0,0,0.1);+ padding: 0.5rem;+ margin-top: 0.25rem;+ width: anchor-size(width);+ overflow: hidden;++ /* The crucial transition setting for popover animations */+ transition:+ display 0.4s allow-discrete,+ overlay 0.4s allow-discrete,+ opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1),+ height 0.4s cubic-bezier(0.16, 1, 0.3, 1);+ opacity: 0;+ height: 0;+}++/* Open State */+.animated-select:open::picker(select) {+ opacity: 1;+ height: auto;+}++/* @starting-style to hook the transition on initial popover open */+@starting-style {+ .animated-select:open::picker(select) {+ opacity: 0;+ height: 0;+ }+}++/* Support for SVG inside Options and Selected Content */+.animated-select option svg,+.animated-select selectedcontent svg {+ flex-shrink: 0; /* Prevent icons from shrinking */+ width: 1.25rem;+ height: 1.25rem;+}+```++## Strategic Implementation & Best Practices++- **DO** use `@starting-style` when you need animations to trigger exactly when an element transitions from `display: none` to visible.+- **DO NOT** use ad-hoc scroll locking. Top-layer elements managed by ‘base-select’ should allow natural backdrop dismiss behaviors.+- **DO** verify reduced motion preferences. Always wrap animation constraints in a `prefers-reduced-motion` media query to ensure accessible environments for those affected by motion sickness.+- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.++## Fallback strategies++Customizable <select> has limited availability.++For browsers that do not yet support `appearance: base-select`, the `<select>` element degrades gracefully to a standard operating system dropdown.++- **Non-Text Content Ignored**: Older browsers strip HTML tags (like `<svg>` or `<div>`) inside `<option>` tags and render only the text nodes. Ensure the text content of the `<option>` is readable and meaningful on its own.+- **HTML Structure Handling**: Standard parsers may ignore the `<button>` and `<selectedcontent>` tags inside `<select>` or treat them as invalid. No heavy JavaScript polyfills are strictly required for progressive enhancement if you view standard text as a readable fallback.diff --git a/skills/modern-web/guides/forms/autofill-address-form.md b/skills/modern-web/guides/forms/autofill-address-form.mdnew file mode 100644index 0000000..a3d87ea--- /dev/null+++ b/skills/modern-web/guides/forms/autofill-address-form.md@@ -0,0 +1,73 @@+# Build an address form that follows best practice++Create a form that makes it as easy as possible for users to enter address data on desktop and mobile. Ensure the form makes the most of built-in browser features for autofill, validation and data entry constraints.++## How to implement++Outlined below are the most important guidelines for building successful address forms.++### Use meaningful, valid HTML++Make the most of the elements and attributes built for creating forms:++- `<form>`, `<input>`, `<label>`, and `<button>`+- `type`, `autocomplete`, and `inputmode`++These enable built-in browser functionality, improve accessibility, and add meaning to markup.++### Use the <label> element to label form fields for data entry++To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a label with an input by giving the label's `for` attribute the same value as the input's `id`.++### Make the most of HTML attributes++Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.++Always use `type="email"` for email addresses and `type="tel"` for phone numbers.++```html+<!-- type="email"/"tel" gives mobile users the right keyboard and enables built-in validation -->+<input type="email" id="email" name="email" autocomplete="email" required>+<input type="tel" id="phone" name="phone" autocomplete="tel">+```++Every `<input>`, `<select>`, and `<textarea>` element SHOULD have an appropriate `autocomplete` attribute, to improve accessibility and help users avoid re-entering data.++### Make buttons helpful++Use `<button>` for buttons. You can also use `<input type="submit">`, but don't use a `div` or some other random element acting as a button. Button elements provide accessible behaviour, built-in form submission functionality, and can easily be styled.++Give each form submit button a value that says what it does. For each step towards checkout, use a descriptive call-to-action that shows progress and makes the next step obvious. For example, label the submit button on your delivery address form **Proceed to Payment** rather than **Continue** or **Save**.++### Use a single name input where possible++Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.++Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.++### Allow for a variety of address formats++When building an address form, be aware of the variety of address formats, even within a single country. Do not make assumptions about "normal" addresses.++Use a single `<textarea>` element for the street address if possible.++```html+<!-- textarea handles multi-line international address formats that split inputs can't accommodate -->+<textarea id="address" name="address" autocomplete="street-address" required></textarea>+```++This is the most flexible option for a variety of local and international address formats.++### Help save users from accidentally missing data fields++Add the `required` attribute to mandatory fields.++```html+<input type="text" id="city" name="city" autocomplete="address-level2" required>+```++### Fallback strategies++:autofill has limited availability.++Autofill is a progressive enhancement. In browsers that do not support autofill, users will simply need to manually enter their address details. The semantic HTML constraints (such as `type`, `inputmode`, and `required`) will still function appropriately as standard form validation.diff --git a/skills/modern-web/guides/forms/autofill-highlight-inputs.md b/skills/modern-web/guides/forms/autofill-highlight-inputs.mdnew file mode 100644index 0000000..6653f0e--- /dev/null+++ b/skills/modern-web/guides/forms/autofill-highlight-inputs.md@@ -0,0 +1,35 @@+# Use the CSS :autofill pseudo-class to highlight form fields that have been autofilled by the browser and not edited by the user++Use the CSS `:autofill` to highlight fields that have (or have not been) autofilled, to help guide the user to successful form completion.++## How to implement++To highlight a form field that has been autofilled by the browser (and not edited by the user) add a selector to your CSS using the `:autofill` class. This can be used for an `<input>`, `<select>`, or `<textarea>` element.++The following example uses `:autofill` to set border color:++```css+input:autofill,+input:-webkit-autofill,+input:-webkit-autofill:hover,+input:-webkit-autofill:focus {+ /* box-shadow overrides the autofill background color, which cannot be changed via background-color */+ /* box-shadow: 0 0 0 100vmax #efe inset; */+ border-color: green;+ outline: none;+}+```++As shown in this example, the `box-shadow` property can be used to customize the background if required, since `background-color` cannot be overridden directly.++## Use the correct CSS pseudo-class name++**Do not** use `:auto-fill`: this is incorrect.++MANDATORY: Use `:autofill` as this is the correct pseudo-class name.++### Fallback strategies++:autofill has limited availability.++The `:autofill` pseudo-class is a progressive enhancement. In browsers that do not support it, the form will still function normally, but the inputs will simply not receive the custom autofill highlighting. Users will still be able to successfully complete the form. No additional JavaScript fallback should be used.diff --git a/skills/modern-web/guides/forms/autofill-payment-form.md b/skills/modern-web/guides/forms/autofill-payment-form.mdnew file mode 100644index 0000000..5e0a8af--- /dev/null+++ b/skills/modern-web/guides/forms/autofill-payment-form.md@@ -0,0 +1,120 @@+# Build a payment form that follows best practice++Payment forms are the single most critical part of the checkout process. Poor payment form design is a common cause of shopping cart abandonment.++Create a form that makes it as easy as possible for users to enter payment details on desktop and mobile. Ensure the form makes the most of built-in browser features for autofill, validation and data entry constraints.++## How to implement++Outlined below are the most important guidelines for building successful payment forms.++### Use meaningful, valid HTML++Make the most of the elements and attributes built for creating forms:++- `<form>`, `<input>`, `<label>`, and `<button>`+- `type`, `autocomplete`, and `inputmode`++These enable built-in browser functionality, improve accessibility, and add meaning to markup.++### Use the <label> element to label form fields for data entry++To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a label with an input by giving the label's `for` attribute the same value as the input's `id`.++### Make the most of HTML attributes++Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.++Always use `type="email"` for email addresses and `type="tel"` for phone numbers.++```html+<!-- type="email"/"tel" gives mobile users the right keyboard and enables built-in validation -->+<input type="email" id="email" name="email" autocomplete="email" required>+<input type="tel" id="phone" name="phone" autocomplete="tel">+```++Every `<input>`, `<select>`, and `<textarea>` element SHOULD have an appropriate `autocomplete` attribute, to improve accessibility and help users avoid re-entering data.++### Make buttons helpful++Use `<button>` for buttons. You can also use `<input type="submit">`, but don't use a `div` or some other random element acting as a button. Button elements provide accessible behaviour, built-in form submission functionality, and can easily be styled.++Give each form submit button a value that says what it does. For each step towards checkout, use a descriptive call-to-action that shows progress and makes the next step obvious. For example, label the submit button on your delivery address form **Proceed to Payment** rather than **Continue** or **Save**.++### Use a single name input where possible++Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.++Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.++### Allow for a variety of address formats++When adding form fields for an address in a payment form, be aware of the variety of address formats, even within a single country. Do not make assumptions about "normal" addresses.++If possible within your data requirements, consider using a single `<textarea>` element for address. This is the most flexible option for a variety of local and international address formats.++### Use autocomplete for billing address++By default, set the billing address to be the same as the delivery address. Reduce visual clutter by providing a link to edit the billing address (or use summary and details elements) rather than displaying the billing address in a form.++Use appropriate autocomplete values for the billing address, just as you do for shipping address, so the user doesn't have to enter data more than once. Add a prefix word to autocomplete attributes if you have different values for inputs with the same name in different sections. For example:++```+<input autocomplete="shipping address-line-1" ...>+...+<input autocomplete="billing address-line-1" ...>+```++### Show checkout progress++For each step towards payment, use page headings and descriptive button values that make it clear what needs to be done now, and what checkout step is next.++Use the `enterkeyhint` attribute on form inputs to set the mobile keyboard enter key label. For example, use `enterkeyhint="previous"` and `enterkeyhint="next"` within a multi-page form, `enterkeyhint="done"` for the final input in the form, and `enterkeyhint="search"` for a search input.++### Help users avoid re-entering payment data++Make sure to add appropriate `autocomplete` values in payment card forms. Without autocomplete, users may keep a physical record of payment card details or store them insecurely.++```html+<!-- cc-number tells autofill this is a card number, not a generic number field -->+<!-- inputmode="numeric" gives a numeric keyboard without the increment/decrement spinner -->+<!-- DO NOT use type="number" — it adds increment/decrement controls and strips leading zeros -->+<input id="cc-number" name="cc-number" type="text" autocomplete="cc-number"+ inputmode="numeric" maxlength="19" pattern="[\d ]{13,19}" required>++<!-- cc-name autofills with the name exactly as it appears on the card; Unicode pattern allows international names -->+<input id="cc-name" name="cc-name" type="text" autocomplete="cc-name"+ maxlength="50" pattern="[\p{L} \-\.]+" required>++<!-- cc-exp autofills the full expiry date as MM/YY -->+<input id="cc-exp" name="cc-exp" type="text" autocomplete="cc-exp"+ placeholder="MM/YY" maxlength="5" required>++<!-- cc-csc autofills the security code; DO NOT use type="password" here -->+<input id="cc-csc" name="cc-csc" type="text" autocomplete="cc-csc"+ inputmode="numeric" maxlength="4" pattern="[0-9]{3,4}" required>+```++### Use a single input for payment card and phone numbers++For payment card and phone numbers use a single input: don't split the number into parts. That makes it easier for users to enter data, makes validation simpler, and enables browsers to autofill. Consider doing the same for other numeric data such as PIN and bank codes.++### Validate carefully++You should validate data entry both in realtime and before form submission. One way to do this is by adding a pattern attribute to a payment card input. If the user attempts to submit the payment form with an invalid value, the browser displays a warning message and sets focus on the input.++However, your pattern regular expression must be flexible enough to handle the range of payment card number lengths: from 14 digits (or possibly less) to 20 (or more). Card security codes (also known as CSC, CVC, CVV, or other names) consist of 3 or 4 digits.++Allow users to include spaces when they're entering a new payment card number, since this is how numbers are displayed on physical cards. That's friendlier to the user (you won't have to tell them "they did something wrong"), less likely to interrupt conversion flow, and it's straightforward to remove spaces in numbers before processing.++### Help save users from accidentally missing data fields++Add the `required` attribute to mandatory fields. Modern browsers automatically prompt and set focus for missing data.++### Fallback strategies++Baseline status for enterkeyhint: Widely available. It's been Baseline since 2021-11-02.+Baseline status for Email, telephone, and URL <input> types: Widely available. It's been Baseline since 2015-07-29.+Baseline status for inputmode: Widely available. It's been Baseline since 2021-12-07.++Autofill is a progressive enhancement. In browsers that do not support autofill, users will simply need to manually enter their payment details. The semantic HTML constraints (such as `type`, `inputmode`, `pattern`, and `required`) will still function appropriately to validate user input and provide the correct virtual keyboards.diff --git a/skills/modern-web/guides/forms/autofill-sign-in-form.md b/skills/modern-web/guides/forms/autofill-sign-in-form.mdnew file mode 100644index 0000000..1b796fd--- /dev/null+++ b/skills/modern-web/guides/forms/autofill-sign-in-form.md@@ -0,0 +1,133 @@+# Build a sign-in form that follows best practice++Use cross-platform browser features to build sign-in forms that are secure, accessible and easy to use.++If users ever need to sign in to your site, then good sign-in form design is critical. This is especially true for people on poor connections, on mobile, in a hurry, or under stress. Poorly designed sign-in forms get high bounce rates. Each bounce could mean a lost customer and a disgruntled user—not just a missed sign-in opportunity.++## How to implement++Outlined below are the most important guidelines for building successful sign-in forms.++### Use meaningful, valid HTML++Make the most of the elements and attributes built for creating forms:++- `<form>`, `<input>`, `<label>`, and `<button>`+- `type`, `autocomplete`, and `inputmode`++These enable built-in browser functionality, improve accessibility, and add meaning to markup.++### Use the <label> element to label form fields for data entry++To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a label with an input by giving the label's `for` attribute the same value as the input's `id`.++### Make the most of HTML attributes++Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.++Always use `type="email"` for email addresses and `type="tel"` for phone numbers.++Every `<input>`, `<select>`, and `<textarea>` element SHOULD have an appropriate `autocomplete` attribute, to improve accessibility and help users avoid re-entering data.++### Make buttons helpful++Use `<button>` for buttons. You can also use `<input type="submit">`, but don't use a `div` or some other random element acting as a button. Button elements provide accessible behaviour, built-in form submission functionality, and can easily be styled.++Give each form submit button a value that says what it does. Use a clear, recognizable label. For example, use **Sign In** rather than **Continue** or **Submit**.++### Use a single name input where possible++Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.++Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.++### Show sign-in progress++For each step towards sign-in, use page headings and descriptive button values that make it clear what needs to be done now, and what the next step is.++Use the `enterkeyhint` attribute on form inputs to set the mobile keyboard enter key label. For example, use `enterkeyhint="previous"` and `enterkeyhint="next"` within a multi-page form, `enterkeyhint="done"` for the final input in the form, and `enterkeyhint="search"` for a search input.++### Help users avoid re-entering sign-in data++Make sure to add appropriate `autocomplete` values in sign-in forms.++This enables browsers to help users by securely storing sign-in details and correctly entering form data. Without autocomplete, users may be more likely to keep a physical record of sign-in details, or store sign-in data insecurely on their device.++### Validate carefully++Validate data entry both in realtime and before form submission. Use `type="email"` for email inputs — the browser will validate the format automatically. Add the `required` attribute to mandatory fields to prevent empty submissions.++### Put sign-in in its own <form> element++Always use the `<form>` element when you're getting users to enter data++Don't wrap inputs in a `<div>` and handle input data submission purely with JavaScript. It's generally better to use a `<form>` element. This makes your site accessible to screenreaders and other assistive devices, enables a range of built-in browser features, makes it simpler to build basic functional sign-in for older browsers, and can still work even if JavaScript fails.++### Don't double up inputs++Some sites force users to enter emails or passwords twice. That might reduce errors for a few users, but causes extra work for all users, and increases abandonment rates. Asking twice also makes no sense where browsers autofill email addresses or suggest strong passwords. It's better to enable users to confirm their email address (you'll need to do that anyway) and make it easy for them to reset their password if necessary.++### Keep passwords private—but enable users to see them if they want++Passwords inputs should have `type="password"` to hide password text and help the browser understand that the input is for passwords. (Note that browsers use a variety of techniques to understand input roles and decide whether or not to offer to save passwords.)++You should add a **Show password** toggle to enable users to check the text they've entered—and don't forget to add a **Forgot password** link.++### Give mobile users the right keyboard++Use `<input type="email">` to give mobile users an appropriate keyboard and enable basic built-in email address validation by the browser… no JavaScript required!++If you need to use a telephone number instead of an email address, `<input type="tel">` enables a telephone keypad on mobile. You can also use the `inputmode` attribute where necessary: `inputmode="numeric"` is ideal for PIN numbers.++### Prevent mobile keyboard from obstructing the Sign in button++If you're not careful, mobile keyboards may cover your form or, worse, partially obstruct the Sign in button. Users may give up before realizing what has happened.++Where possible, avoid this by displaying only the email (or phone) and password inputs and Sign in button at the top of your sign-in page. Put other content underneath.++### Help users to avoid re-entering data++You can help browsers store data correctly and autofill inputs, so users don't have to remember to enter email and password values. This is particularly important on mobile, and crucial for email inputs, which get high abandonment rates. There are two parts to this:++1. The `autocomplete`, `name`, `id`, and `type` attributes help browsers understand the role of inputs in order to store data that can later be used for autofill. To allow data to be stored for autofill, modern browsers also require inputs to have a stable `name` or `id` value (not randomly generated on each page load or site deployment), and to be in a `<form>` element with a `submit` button.+1. The `autocomplete` attribute helps browsers correctly autofill inputs using stored data.++For email inputs use `autocomplete="username"`, since `username` is recognized by password managers in modern browsers—even though you should use `type="email"` and you may want to use `id="email"` and `name="email"`. For password inputs, use the appropriate `autocomplete` and `id` values to help browsers differentiate between new and current passwords.++### Use autocomplete="current-password" and id="current-password" for an existing password++MANDATORY: Use `autocomplete="current-password"` and `id="current-password"` for the password input in a sign-in form. This tells the browser that you want it to use the current password that it has stored for the site.++For a sign-in form:++```+<input type="password" autocomplete="current-password" id="current-password" …>+```++### Enable the browser to suggest a strong password++Modern browsers use heuristics to decide when to show the password manager UI and suggest a strong password.++Built-in browser password generators mean users and developers don't need to work out what a "strong password" is. Since browsers can securely store passwords and autofill them as necessary, there's no need for users to remember or enter passwords. Encouraging users to take advantage of built-in browser password generators also means they're more likely to use a unique, strong password on your site, and less likely to reuse a password that could be compromised elsewhere.++### Help save users from accidentally missing inputs++MANDATORY: Add the `required` attribute to both email and password fields. Modern browsers automatically prompt and set focus for missing data.++```html+<input type="email" id="email" name="email" autocomplete="username" required>+<input type="password" id="password" name="password" autocomplete="current-password" required>+```++### Allow password pasting++Some sites don't allow text to be pasted into password inputs.++Disallowing password pasting annoys users, encourages passwords that are memorable (and therefore may be easier to compromise) and, according to organizations such as the UK National Cyber Security Centre, may actually reduce security. Users only become aware that pasting is disallowed after they try to paste their password, so disallowing password pasting doesn't avoid clipboard vulnerabilities.++### Fallback strategies++Baseline status for Email, telephone, and URL <input> types: Widely available. It's been Baseline since 2015-07-29.+Baseline status for inputmode: Widely available. It's been Baseline since 2021-12-07.++Autofill is a progressive enhancement. In browsers that do not support autofill, users will simply need to manually enter their sign-in credentials. The semantic HTML constraints (such as `type`, `inputmode`, and `required`) will still function appropriately to validate user input and provide the correct virtual keyboards.diff --git a/skills/modern-web/guides/forms/autofill-sign-up-form.md b/skills/modern-web/guides/forms/autofill-sign-up-form.mdnew file mode 100644index 0000000..ebae9dc--- /dev/null+++ b/skills/modern-web/guides/forms/autofill-sign-up-form.md@@ -0,0 +1,143 @@+# Build a sign-up form that follows best practice++Use cross-platform browser features to build sign-up forms that are secure, accessible and easy to use.++If users ever need to sign up to your site, then good sign-up form design is critical. This is especially true for people on poor connections, on mobile, in a hurry, or under stress. Poorly designed sign-up forms get high bounce rates. Each bounce could mean a lost customer and a disgruntled user—not just a missed sign-up opportunity.++## How to implement++Outlined below are the most important guidelines for building successful sign-up forms.++### Use meaningful, valid HTML++Make the most of the elements and attributes built for creating forms:++- `<form>`, `<input>`, `<label>`, and `<button>`+- `type`, `autocomplete`, and `inputmode`++These enable built-in browser functionality, improve accessibility, and add meaning to markup.++### Use the <label> element to label form fields for data entry++To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a label with an input by giving the label's `for` attribute the same value as the input's `id`.++### Make the most of HTML attributes++Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.++Always use `type="email"` for email addresses and `type="tel"` for phone numbers.++Every `<input>`, `<select>`, and `<textarea>` element SHOULD have an appropriate `autocomplete` attribute, to improve accessibility and help users avoid re-entering data.++### Make buttons helpful++Use `<button>` for buttons. You can also use `<input type="submit">`, but don't use a `div` or some other random element acting as a button. Button elements provide accessible behaviour, built-in form submission functionality, and can easily be styled.++Give each form submit button a value that says what it does. Use a clear, recognizable label. For example, use **Create account** or **Sign up** rather than **Continue** or **Submit**.++### Use a single name input where possible++Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.++Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.++### Show sign-up progress++For each step towards sign-up, use page headings and descriptive button values that make it clear what needs to be done now, and what the next step is.++Use the `enterkeyhint` attribute on form inputs to set the mobile keyboard enter key label. For example, use `enterkeyhint="previous"` and `enterkeyhint="next"` within a multi-page form, `enterkeyhint="done"` for the final input in the form, and `enterkeyhint="search"` for a search input.++### Help users avoid re-entering sign-up data++Make sure to add appropriate `autocomplete` values in sign-up forms.++This enables browsers to help users by securely storing sign-up details and correctly entering form data. Without autocomplete, users may be more likely to keep a physical record of sign-up details, or store sign-up data insecurely on their device.++### Validate carefully++Validate data entry both in realtime and before form submission. Use `type="email"` for email inputs — the browser will validate the format automatically. For passwords, use a `pattern` attribute to enforce strength requirements and provide clear error messages when validation fails. Add the `required` attribute to mandatory fields to prevent empty submissions.++### Put sign-up in its own <form> element++Always use the `<form>` element when you're getting users to enter data++Don't wrap inputs in a `<div>` and handle input data submission purely with JavaScript. It's generally better to use a `<form>` element. This makes your site accessible to screenreaders and other assistive devices, enables a range of built-in browser features, makes it simpler to build basic functional sign-up for older browsers, and can still work even if JavaScript fails.++### Don't double up inputs++Some sites force users to enter emails or passwords twice. That might reduce errors for a few users, but causes extra work for all users, and increases abandonment rates. Asking twice also makes no sense where browsers autofill email addresses or suggest strong passwords. It's better to enable users to confirm their email address (you'll need to do that anyway) and make it easy for them to reset their password if necessary.++### Keep passwords private—but enable users to see them if they want++Passwords inputs should have `type="password"` to hide password text and help the browser understand that the input is for passwords. (Note that browsers use a variety of techniques to understand input roles and decide whether or not to offer to save passwords.)++You should add a **Show password** toggle to enable users to check the text they've entered—and don't forget to add a **Forgot password** link.++### Give mobile users the right keyboard++Use `<input type="email">` to give mobile users an appropriate keyboard and enable basic built-in email address validation by the browser… no JavaScript required!++If you need to use a telephone number instead of an email address, `<input type="tel">` enables a telephone keypad on mobile. You can also use the `inputmode` attribute where necessary: `inputmode="numeric"` is ideal for PIN numbers.++### Prevent mobile keyboard from obstructing the Sign up button++If you're not careful, mobile keyboards may cover your form or, worse, partially obstruct the Sign up button. Users may give up before realizing what has happened.++Where possible, avoid this by displaying only the email (or phone) and password inputs and Sign up button at the top of your sign-up page. Put other content underneath.++### Help users to avoid re-entering data++You can help browsers store data correctly and autofill inputs, so users don't have to remember to enter email and password values. This is particularly important on mobile, and crucial for email inputs, which get high abandonment rates. There are two parts to this:++1. The `autocomplete`, `name`, `id`, and `type` attributes help browsers understand the role of inputs in order to store data that can later be used for autofill. To allow data to be stored for autofill, modern browsers also require inputs to have a stable `name` or `id` value (not randomly generated on each page load or site deployment), and to be in a `<form>` element with a `submit` button.+1. The `autocomplete` attribute helps browsers correctly autofill inputs using stored data.++For email inputs use `autocomplete="username"`, since `username` is recognized by password managers in modern browsers—even though you should use `type="email"` and you may want to use `id="email"` and `name="email"`. For password inputs, use the appropriate `autocomplete` and `id` values to help browsers differentiate between new and current passwords.++### Use autocomplete="new-password" and id="new-password" for a new password++MANDATORY: For a sign-up form, use `autocomplete="new-password"`.++```html+<!-- new-password prevents password managers from auto-filling an existing password into this field -->+<input type="password" id="new-password" name="new-password" autocomplete="new-password" required>+```++### Enable the browser to suggest a strong password++Modern browsers use heuristics to decide when to show the password manager UI and suggest a strong password.++Built-in browser password generators mean users and developers don't need to work out what a "strong password" is. Since browsers can securely store passwords and autofill them as necessary, there's no need for users to remember or enter passwords. Encouraging users to take advantage of built-in browser password generators also means they're more likely to use a unique, strong password on your site, and less likely to reuse a password that could be compromised elsewhere.++### Help save users from accidentally missing inputs++Add the `required` attribute to both email and password fields. Modern browsers automatically prompt and set focus for missing data.++### Allow password pasting++Some sites don't allow text to be pasted into password inputs.++Disallowing password pasting annoys users, encourages passwords that are memorable (and therefore may be easier to compromise) and, according to organizations such as the UK National Cyber Security Centre, may actually reduce security. Users only become aware that pasting is disallowed after they try to paste their password, so disallowing password pasting doesn't avoid clipboard vulnerabilities.++### Offer third-party login++Many users prefer to sign in to websites using an email address and password sign-up form. However, you should also enable users to sign in using a third-party identity provider, also known as federated login.++This approach has several advantages. For users who create an account using federated login, you don't need to ask for, communicate, or store passwords.++You may also be able to access additional verified profile information from federated login, such as an email address—which means the user doesn't have to enter that data and you don't need to do the verification yourself. Federated login can also make it much easier for users when they get a new device.++### Take care with usernames++Don't insist on a username unless (or until) you need one. Enable users to sign up and sign in with only an email address (or telephone number) and password—or federated login if they prefer. Don't force them to choose and remember a username.++If your site does require usernames, don't impose unreasonable rules on them, and don't stop users from updating their username. On your backend you should generate a unique ID for every user account, not an identifier based on personal data such as username.++Also make sure to use `autocomplete="username"` for usernames.++### Fallback strategies++Baseline status for Email, telephone, and URL <input> types: Widely available. It's been Baseline since 2015-07-29.+Baseline status for inputmode: Widely available. It's been Baseline since 2021-12-07.++Autofill is a progressive enhancement. In browsers that do not support autofill, users will simply need to manually enter their sign-up credentials. The semantic HTML constraints (such as `type`, `inputmode`, and `required`) will still function appropriately to validate user input and provide the correct virtual keyboards.diff --git a/skills/modern-web/guides/forms/branded-select-styling.md b/skills/modern-web/guides/forms/branded-select-styling.mdnew file mode 100644index 0000000..7ccdbf3--- /dev/null+++ b/skills/modern-web/guides/forms/branded-select-styling.md@@ -0,0 +1,109 @@+# Branded Select Styling++The customizable select API offers a declarative, CSS-driven way to style `<select>` elements to perfectly match your brand's design system. By opting into `appearance: base-select`, you gain access to the internal shadow DOM of the select element, allowing you to style the button, the options picker list, the arrow icon, and the checkmark indicator using standard CSS properties.++Previously, achieving a fully branded select required rebuilding the control from scratch with JavaScript, which often broke accessibility, keyboard navigation, and native form integration. With `appearance: base-select`, you get a custom look while the browser handles focus management, top-layer rendering, and accessibility bindings.++## How to Implement++To implement branded select styling:++1. **Opt-in to customization:** Apply `appearance: base-select` to both the `<select>` element and the `::picker(select)` pseudo-element (which targets the drop-down list of options).+2. **Structure the custom button (Optional):** Define a `<button>` element directly inside the `<select>` to replace the default trigger. Use the `<selectedcontent>` element inside this button to represent the text or content of the currently selected option.+3. **Style the Picker List:** Use the `::picker(select)` pseudo-element to apply typography, background colors, borders, and shadows to the dropdown list. The browser renders this in the top-layer, making `z-index` conflicts a thing of the past.+4. **Style Internal Icons:**+ - Use `select::picker-icon` to style or replace the arrow icon.+ - Use `option::checkmark` to style the checkmark indicator next to the active option.+5. **Style Options:** Apply styles to `<option>` elements for hover states, padding, and layout.++## Example Code: Branded Courier Select++The following example demonstrates a custom select styled with a monospace font and dashed borders to match a specific "parcel" brand aesthetic.++```css+/* Enable customization for the select and its picker */+.brand-select,+.brand-select::picker(select) {+ appearance: base-select;+}++/* Style the visible trigger button */+.brand-select {+ font-family: 'Courier New', monospace;+ background-color: #fffaf0;+ color: #8b4513;+ border: 2px dashed #8b4513;+ border-radius: 4px;+ padding: 0.75rem;+ font-size: 1rem;+ cursor: pointer;+}++/* Style the dropdown options list */+.brand-select::picker(select) {+ font-family: 'Courier New', monospace;+ background-color: #fffaf0;+ border: 2px dashed #8b4513;+ border-radius: 4px;+ padding: 0.5rem;+}++/* Customize internal part colors to match text */+.brand-select::picker-icon {+ color: #8b4513;+}++.brand-select option::checkmark {+ color: #8b4513;+}++/* Style individual options and hover effects */+.brand-select option {+ padding: 0.5rem;+ border-radius: 4px;+ color: #8b4513;+ cursor: pointer;+}++.brand-select option:hover {+ background-color: #fdf5e6;+}+```++```html+<label for="preferences">Select shipping preference</label>+<select class="brand-select" id="preferences" name="preferences">+ <button>+ <selectedcontent></selectedcontent>+ </button>+ <option value="standard">Standard Shipping</option>+ <option value="express" selected>Express Shipping</option>+ <option value="overnight">Overnight Delivery</option>+</select>+```++## Strategic Implementation & Best Practices++- **DO** use `appearance: base-select` when your design system requires high-fidelity, visual consistency across all form controls that cannot be achieved with standard cross-browser select overrides.+- **DO NOT** use this if you rely on the operating system's native picker experience (e.g., the standard scroll wheel picker on iOS devices). Opting into `base-select` opts out of native mobile UI controls in favor of web-rendered top-layer menus.+- **DO** verify that color contrast meets WCAG standards. The customizable picker allows you to set ad-hoc colors, but you are responsible for ensuring text remains legible against custom backgrounds.+- **DO** test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.+- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.++## Fallback strategies++Customizable <select> has limited availability.++For browsers that do not yet support `appearance: base-select`, the `<select>` element degrades gracefully to a standard operating system dropdown.++- **Non-Text Content Ignored**: Older browsers strip HTML tags (like `<svg>` or `<div>`) inside `<option>` tags and render only the text nodes. Ensure the text content of the `<option>` is readable and meaningful on its own.+- **HTML Structure Handling**: Standard parsers may ignore the `<button>` and `<selectedcontent>` tags inside `<select>` or treat them as invalid. No heavy JavaScript polyfills are strictly required for progressive enhancement if you view standard text as a readable fallback.++```javascript+document.addEventListener("DOMContentLoaded", () => {+ // Check if browser supports base-select value+ if (!CSS.supports("appearance", "base-select")) {+ console.log("Custom select overrides are not supported natively.");+ }+});+```\ No newline at end of filediff --git a/skills/modern-web/guides/forms/custom-select-picker-layouts.md b/skills/modern-web/guides/forms/custom-select-picker-layouts.mdnew file mode 100644index 0000000..1643c2a--- /dev/null+++ b/skills/modern-web/guides/forms/custom-select-picker-layouts.md@@ -0,0 +1,95 @@+# Custom Select Picker Layouts++"Custom Select Picker Layouts" allow developers to break away from the traditional vertical list of options in a `<select>` dropdown. Using `appearance: base-select` and the `::picker(select)` pseudo-element, you can style the options list using modern CSS layout techniques like Grid or Flexbox. This is ideal for color pickers, emoji selectors, or product variants where a visual menu is more effective than a list.++The CSS property `appearance: base-select` unlocks the ability to style the internal parts of a `<select>` element. By targeting `select::picker(select)`, you can apply `display: grid` and position options in columns, creating a rich visual experience without custom JavaScript.++## How to Implement++To implement a custom select picker layout:++1. **Activate Base Styling:** Apply `appearance: base-select` to both the `<select>` element and its internal picker pseudo-element `select::picker(select)`.+2. **Style the Picker Container:** Target `select::picker(select)` and apply `display: grid` (or `display: flex`). Define columns and gaps as you would for any container.+3. **Style Options:** Target the `<option>` elements to style them as grid items or cards. You can add images, SVGs, or complex layouts inside them.+4. **Customize the Trigger (Optional):** Use `<selectedcontent>` inside a `<button>` to render rich content for the selected value.++## Example Code: Custom Grid Picker++```html+<label for="weather-picker">Select weather</label>+<select class="grid-picker" name="weather" id="weather-picker">+ <button>+ <selectedcontent></selectedcontent>+ </button>+ <option value="sunny">+ <span class="icon">☀️</span>+ <span class="label">Sunny</span>+ </option>+ <option value="cloudy">+ <span class="icon">☁️</span>+ <span class="label">Cloudy</span>+ </option>+ <!-- More options... -->+</select>+```++```css+/* Activate the customizable select state */+.grid-picker,+.grid-picker::picker(select) {+ appearance: base-select;+}++/* Style the dropdown list as a grid */+.grid-picker::picker(select) {+ display: grid;+ grid-template-columns: repeat(2, 1fr); /* 2 columns */+ gap: 10px;+ padding: 15px;+ background: white;+ border: 1px solid #ccc;+ border-radius: 8px;+}++/* Style options as grid cards */+.grid-picker option {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 15px;+ border: 1px solid #eee;+ border-radius: 6px;+}++.grid-picker option:checked {+ border-color: #007bff;+ background-color: #f0f7ff;+}+```++## Strategic Implementation & Best Practices++- **DO** use `appearance: base-select` when you need to change the visual layout of options from a standard list to a 2D grid or custom flex flow.+- **DO NOT** assume the styles apply to all browsers equally yet; verify support and provide a fallback.+- **DO NOT** confuse visual layout with keyboard navigation. Standard select uses linear navigation. If you arrange options in a grid, ensure visual order matches DOM order so tab/arrow navigation makes sense.+- **DO** use `<selectedcontent>` if you want the trigger button to show images or icons from the selected option automatically.+- **DO** use standard `value` attributes on options to ensure form submission works exactly as before.+- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.++## Fallback Strategy++For browsers that do not yet support `appearance: base-select`, the select will degrade gracefully to a standard `<select>` element. The grid styles will be ignored, but the select will remain functional.++If the grid layout is critical and must be preserved, use a feature detection check and a JavaScript fallback (or use a framework component).++```javascript+document.addEventListener("DOMContentLoaded", () => {+ if (!CSS.supports("appearance", "base-select")) {+ console.log("Custom select layout not supported. Falling back to native UI.");+ }+});+```++- **Non-Text Content Ignored**: Older browsers strip HTML tags (like `<svg>` or `<div>`) inside `<option>` tags and render only the text nodes. Ensure the text content of the `<option>` is readable and meaningful on its own.+- **HTML Structure Handling**: Standard parsers may ignore the `<button>` and `<selectedcontent>` tags inside `<select>` or treat them as invalid. No heavy JavaScript polyfills are strictly required for progressive enhancement if you view standard text as a readable fallback.\ No newline at end of filediff --git a/skills/modern-web/guides/forms/form-fields-automatically-fit-contents.md b/skills/modern-web/guides/forms/form-fields-automatically-fit-contents.mdnew file mode 100644index 0000000..8ad76e8--- /dev/null+++ b/skills/modern-web/guides/forms/form-fields-automatically-fit-contents.md@@ -0,0 +1,119 @@+By default, form controls like `<input>`, `<textarea>`, and `<select>` have fixed dimensions. Their sizes remain constant, regardless of the amount of content the user enters or selects.++To allow these controls to automatically shrink or grow to fit their content (including placeholders), use the `field-sizing: content` CSS property.++### Auto-sizing form controls++Setting `field-sizing: content` on inputs, selects, or textareas allows them to resize dynamically as the user types or selects options. However, you must account for inherited styling, layout defaults, and minimum/maximum constraints to ensure a robust user experience.++To prevent layout issues, it is recommended to set both `min-inline-size` (or `min-width`) and `max-inline-size` (or `max-width`) alongside `field-sizing: content` on text inputs. A minimum size prevents the input from collapsing to a width of zero when empty (making it unclickable), and a maximum size ensures it doesn't expand indefinitely and break the page layout.++For textareas, allowing horizontal auto-sizing can cause a jarring UX (e.g., a textarea with a long placeholder will abruptly shrink horizontally when the user types a single character). To prevent this, apply an explicit width (like `width: 100%`) to the textarea. This forces the textarea to maintain a stable horizontal width while still auto-sizing vertically as content wraps.++It is recommended to set a `max-inline-size` (or `max-width`) on `<select>` elements using `field-sizing: content` to ensure that extremely long selected options do not break the page layout.++```css+/* Applies horizontal auto-sizing to inputs */+input {+ /* Instructs the element to size itself to fit its content */+ field-sizing: content;++ /* Reset explicit width if inherited from global styles */+ width: auto;++ /* Prevents the input from collapsing and disappearing when empty */+ min-inline-size: 15ch;++ /* Prevents infinite horizontal growth */+ max-inline-size: 50ch;+}++textarea {+ /* Instructs the element to size itself to fit its content */+ field-sizing: content;++ /* Reset explicit height if inherited from global styles */+ height: auto;++ /* Use a fixed width to prevent jarring horizontal shifts when replacing a long placeholder */+ width: 50ch; /* or 100% depending on your layout */++ /* Sets a reasonable minimum height (e.g., 3 lines) for empty textareas */+ min-block-size: 3lh;++ /* Prevents infinite vertical growth. Once a textarea hits this */+ /* height, it will stop growing and show a vertical scrollbar. */+ max-block-size: 10lh;+}++select {+ /* Sizes the select element to fit the active option only */+ field-sizing: content;++ /* Prevents the dropdown from expanding infinitely and breaking the layout */+ max-inline-size: 50ch;+}+```++IMPORTANT: Explicit `width` and `height` properties override `field-sizing: content` on all form controls. If your project's global CSS sets inputs, selects, or textareas to `width: 100%`, you must explicitly reset them to `width: auto` (or `width: fit-content`) on the elements using `field-sizing: content` for auto-sizing to work. Conversely, you should explicitly set `height: auto` on textareas if a fixed height was previously set globally.++IMPORTANT: Grid and Flexbox layouts often implicitly stretch their children to fill available space. If any form control using `field-sizing: content` refuses to shrink, check its container's alignment properties and apply `align-self: start` or `justify-self: start` to the form control to override the stretching.++### Fallback strategies++field-sizing has limited availability.++`field-sizing` should be treated as a progressive enhancement. In browsers that do not support the property, form controls gracefully degrade back to their default, fixed sizing behavior. Users will simply experience standard scrolling for overflowing content inside fixed-size inputs and textareas.++If dynamically growing fields are absolutely required for older browsers, you must use feature detection and a complex workaround. The most robust fallback for textareas uses a CSS Grid trick where a hidden pseudo-element mirrors the user's input in real-time, forcing the grid container (and the textarea inside it) to expand.++```html+<!-- The textarea is wrapped in a container that will mirror its value -->+<div class="growable-textarea" data-replicated-value="">+ <textarea></textarea>+</div>+```++```javascript+// Only attach the fallback event listeners if field-sizing is unsupported+if (!CSS.supports('field-sizing', 'content')) {+ document.querySelectorAll('.growable-textarea > textarea').forEach(textarea => {+ textarea.addEventListener('input', () => {+ textarea.parentNode.dataset.replicatedValue = textarea.value;+ });+ });+}+```++```css+/* Only apply the fallback if field-sizing is NOT supported */+@supports not (field-sizing: content) {+ .growable-textarea {+ display: grid;+ }++ /* The pseudo-element and textarea must share the exact same cell, font, and padding */+ .growable-textarea::after,+ .growable-textarea > textarea {+ grid-area: 1 / 1 / 2 / 2;+ font: inherit;+ padding: 0.5rem;+ border: 1px solid #999;+ }++ /* The pseudo-element renders the copied text invisibly to stretch the grid */+ .growable-textarea::after {+ /* The space is necessary for trailing empty lines to be rendered */+ content: attr(data-replicated-value) " ";+ white-space: pre-wrap;+ visibility: hidden;+ }++ .growable-textarea > textarea {+ resize: none;+ overflow: hidden;+ }+}+```++Given the complexity of duplicating styles and synchronizing state across DOM nodes for every form control, relying on the default fallback behavior of fixed inputs is the recommended approach for most applications unless dynamic sizing is critical to the user experience.\ No newline at end of filediff --git a/skills/modern-web/guides/forms/required-field-feedback.md b/skills/modern-web/guides/forms/required-field-feedback.mdnew file mode 100644index 0000000..276c76d--- /dev/null+++ b/skills/modern-web/guides/forms/required-field-feedback.md@@ -0,0 +1,173 @@+# Required Field Feedback++## The Problem+Marking required fields with an error state immediately upon page load can be confusing. Ideally, a required field should only look "invalid" if the user has attempted to fill it out and failed.++## The Solution+The `:user-invalid` pseudo-class solves this perfectly. For a required field, it will not match on page load. It will only match if:+1. The user interacts with the field (e.g., types a character and deletes it) and then leaves it (blur), leaving it empty.+2. The user attempts to submit the form while the field is empty.++### Implementation Strategy++1. **HTML Constraint**: Add the `required` attribute to your inputs.+2. **Visual Feedback**: Use `:user-invalid` to style the border red and show a "Required" helper text.+3. **Timing**: Rely on the browser's native timing for visual feedback. You don't need `onBlur` handlers to add a `touched` class anymore, though some JavaScript is still needed to sync ARIA attributes (see below).++## Implementation Guide++### 1. HTML Structure+```html+<form>+ <div class="field">+ <label for="full-name">Full Name</label>+ <input+ type="text"+ id="full-name"+ name="full-name"+ required+ aria-errormessage="name-error"+ >+ <div id="name-error" class="error-msg">+ This field is required.+ </div>+ </div>+</form>+```++### 2. CSS+```css+.error-msg {+ display: none;+ color: #d93025;+ font-size: 0.875rem;+ margin-top: 0.25rem;+}++/*+ Only highlight empty required fields AFTER the user visits them.+*/+input:user-invalid {+ border-color: #d93025;+ background-color: #fce8e6;+}++input:user-invalid + .error-msg {+ display: block;+}++/* Optional: Subtle indicator for required fields that are valid */+input:required:user-valid {+ border-color: #188038;+ border-width: 2px;+}+```++## Fallbacking & Browser Support++The `:user-invalid` pseudo-class is widely supported (Baseline 2023), but if you need to support older browsers, you must ensure consistency of the implementation.++### CSS for Fallback+```css+input:user-invalid,+input.user-invalid-fallback {+ border-color: #d93025;+ background-color: #fce8e6;+}++input:user-invalid + .error-msg,+input.user-invalid-fallback + .error-msg {+ display: block;+}+```++### JavaScript Fallback++DO: Use a reusable utility that tracks interaction state using a `WeakMap`. This avoids polluting the DOM with "dirty" classes or data attributes.++```javascript+const UserInvalidFallback = (() => {+ const dirtyState = new WeakMap();++ const updateState = (input) => {+ const isValid = input.checkValidity();++ // Update both visual and ARIA state+ input.classList.toggle('user-invalid-fallback', !isValid);+ input.classList.toggle('user-valid-fallback', isValid);++ if (!isValid) {+ input.setAttribute('aria-invalid', 'true');+ } else {+ input.removeAttribute('aria-invalid');+ }+ };++ const handleEvent = (event) => {+ const input = event.target;++ if (event.type === 'reset') {+ const controls = input.elements || [];+ for (const control of controls) {+ dirtyState.delete(control);+ control.classList.remove('user-invalid-fallback');+ control.classList.remove('user-valid-fallback');+ control.removeAttribute('aria-invalid');+ }+ return;+ }++ if (!input.checkValidity) return;++ if (event.type === 'input' || event.type === 'change') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasInteracted = true;+ dirtyState.set(input, state);+ if (state.hasBlurred) {+ updateState(input);+ }+ } else if (event.type === 'blur') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasBlurred = true;+ dirtyState.set(input, state);+ if (state.hasInteracted) {+ updateState(input);+ }+ }+ };++ const init = (root = document) => {+ if (CSS.supports('selector(:user-invalid)')) return;++ root.addEventListener('blur', handleEvent, true); // Capture phase+ root.addEventListener('input', handleEvent);+ root.addEventListener('change', handleEvent);+ root.addEventListener('reset', handleEvent, true); // Capture resets+ };++ return { init };+})();++// Initialize for a specific form+const form = document.querySelector('#demo-form');+UserInvalidFallback.init(form);+```++## Other Considerations++1. **Asterisks**: It is still best practice to indicate required fields visually (e.g., with an asterisk `*`) in the label, so users know what to expect *before* they interact.+2. **Submit Buttons**: Unlike `disabled` buttons, keep your submit button enabled. If the user clicks it, the browser will automatically trigger `:user-invalid` on all empty required fields and focus the first one. This is excellent for accessibility and UX.+3. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:++```javascript+// Sync aria-invalid with the CSS :user-invalid state+const syncAria = (el) => {+ el.toggleAttribute?.('aria-invalid', el.matches(':user-invalid'));+};++// Update on blur (to show error) and input (to clear it)+document.addEventListener('blur', (e) => syncAria(e.target), true);+document.addEventListener('input', (e) => {+ if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);+});+```diff --git a/skills/modern-web/guides/forms/rich-media-picker.md b/skills/modern-web/guides/forms/rich-media-picker.mdnew file mode 100644index 0000000..325f44d--- /dev/null+++ b/skills/modern-web/guides/forms/rich-media-picker.md@@ -0,0 +1,107 @@+# Rich Media Picker (Customizable Select)++The native `<select>` element was historically difficult to style and could only contain plain text options. The `appearance: base-select` property offers a declarative, CSS-only way to opt into a customizable state for the `<select>` element. This allows developers to include rich HTML content—such as images, SVGs, and complex layouts—inside `<option>` elements, while retaining native keyboard accessibility and form integration. Use this pattern to replace heavy, custom-built select components with standard, native elements.++## How to Implement++To implement a rich media picker using the Customizable Select API:++1. **Opt-in to base styles**: Apply `appearance: base-select` to both the `<select>` element and its internal picker using the `::picker(select)` pseudo-element. This changes the browser's HTML parser for the contents inside the `<select>`.+2. **Define the Button Content**: Use standard `<button>` and `<selectedcontent>` elements inside the `<select>` to define what is shown when the picker is closed. The `<selectedcontent>` element automatically mirrors the content of the selected option. This is required if you want to display the currently selected rich content in the button.+3. **Use Rich Content inside Options**: You can now place images, SVGs, and other HTML tags inside `<option>` tags. Prior to this API, the browser would strip tags from `<option>` tags and render only plain text.+4. **Style the Popover**: Style the dropped-down options list by targeting the `::picker(select)` pseudo-element. It renders in the top layer, meaning you don't need to fight with `z-index`. Options are positioned using the Anchor Positioning API natively.++## Example Code: Rich Role Picker++```html+<label for="role-picker">Select your role</label>+<select class="custom-select" name="role" id="role-picker">+ <button>+ <selectedcontent></selectedcontent> <!-- Mirrors the selected option's content automatically so you do not need JS to update the button -->+ </button>++ <option value="frontend">+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">+ <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>+ </svg>+ <div class="option-text">+ <span class="option-title">Frontend Developer</span>+ <span class="option-desc">React, Vue, CSS</span>+ </div>+ </option>++ <option value="backend">+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">+ <rect x="2" y="12" width="20" height="14" rx="2" ry="2"></rect>+ </svg>+ <div class="option-text">+ <span class="option-title">Backend Developer</span>+ <span class="option-desc">Node.js, Python</span>+ </div>+ </option>+</select>+```++```css+select.custom-select,+select.custom-select::picker(select) {+ appearance: base-select; /* MUST opt-in both the select and its picker to enable the customizable state, otherwise browser standard rendering applies */+}++select.custom-select {+ display: flex;+ align-items: center;+ justify-content: space-between;+ width: 100%;+ padding: 12px;+ background-color: #1e293b;+ border: 1px solid #334155;+ border-radius: 8px;+ color: #f1f5f9;+ cursor: pointer;+}++select.custom-select::picker(select) {+ background-color: #0f172a;+ border: 1px solid #334155;+ border-radius: 8px;+ padding: 8px;+ box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5);+ width: anchor-size(width); /* Uses Anchor Positioning API to keep the dropdown precisely aligned to the button trigger width */+}++select.custom-select option {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 10px;+ border-radius: 4px;+ cursor: pointer;+}++select.custom-select option:hover {+ background-color: #1e293b;+}++/* Remove standard OS checkmark for base-select */+select.custom-select option::before {+ display: none;+}+```++## Strategic Implementation & Best Practices++- **DO** use `appearance: base-select` when you need complex options layouts (icons, descriptions, images) that was previously only possible with heavy JavaScript UI frameworks.+- **DO NOT** use ad-hoc elements if you notice performance lags; the browser handles native keyboard focus natively.+- **DO** account for top-layer rendering. The picker renders in the top-layer, meaning it overrides relative `z-index` of page content.+- **DO** hide secondary details (like descriptions) in the button state if they take too much space, by styling `.custom-select selectedcontent .option-desc { display: none; }`.+- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.++## Fallback Strategies++Customizable <select> has limited availability.++For browsers that do not yet support `appearance: base-select`, the `<select>` element degrades gracefully to a standard operating system dropdown.++- **Non-Text Content Ignored**: Older browsers strip HTML tags (like `<svg>` or `<div>`) inside `<option>` tags and render only the text nodes. Ensure the text content of the `<option>` is readable and meaningful on its own.+- **HTML Structure Handling**: Standard parsers may ignore the `<button>` and `<selectedcontent>` tags inside `<select>` or treat them as invalid. No heavy JavaScript polyfills are strictly required for progressive enhancement if you view standard text as a readable fallback.diff --git a/skills/modern-web/guides/forms/select-menu-interaction.md b/skills/modern-web/guides/forms/select-menu-interaction.mdnew file mode 100644index 0000000..1ab9ba3--- /dev/null+++ b/skills/modern-web/guides/forms/select-menu-interaction.md@@ -0,0 +1,175 @@+# Select Menu Interaction++## The Problem+For mandatory dropdowns (e.g., "Choose a Country"), standard validation flags the field as invalid immediately if the default option has an empty value. This can create visual noise. We want to show the error only if the user opens the menu and closes it without choosing an option, or attempts to submit the form.++## The Solution+The `:user-invalid` pseudo-class works seamlessly with `<select>` elements. It respects the user's interaction flow: simply loading the page or focusing/blurring without making a change doesn't count as an interaction, so the field stays neutral until they actively attempt a selection.++### Implementation Strategy++1. **HTML Constraint**: Use a `<select>` with `required`. The first option should have `value=""` and ideally be disabled/hidden to force a valid choice.+2. **Visual Feedback**: Use `:user-invalid` to style the select box border.+3. **Timing**: The browser considers the field "interacted" if the user changes the value (even back to the default invalid state) before they blur the control, or upon form submission.++## Implementation Guide++### 1. HTML Structure+The "placeholder" option is key here.++```html+<form>+ <div class="field">+ <label for="country">Country</label>+ <select+ id="country"+ name="country"+ required+ aria-errormessage="country-error"+ >+ <option value="" disabled selected>Select a country...</option>+ <option value="us">United States</option>+ <option value="ca">Canada</option>+ <option value="uk">United Kingdom</option>+ </select>+ <div id="country-error" class="error-msg">+ Please select a country.+ </div>+ </div>+</form>+```++### 2. CSS+```css+.error-msg {+ display: none;+ color: #d93025;+ font-size: 0.875rem;+ margin-top: 0.25rem;+}++/*+ Only show error after the user visits the select menu.+*/+select:user-invalid {+ border-color: #d93025;+ background-color: #fce8e6;+}++select:user-invalid + .error-msg {+ display: block;+}++select:user-valid {+ border-color: #188038;+}+```++## Fallbacking & Browser Support++The `:user-invalid` pseudo-class is widely supported (Baseline 2023), but if you need to support older browsers, you must ensure consistency of the implementation.++### CSS for Fallback+```css+select:user-invalid,+select.user-invalid-fallback {+ border-color: #d93025;+ background-color: #fce8e6;+}++select:user-invalid + .error-msg,+select.user-invalid-fallback + .error-msg {+ display: block;+}+```++### JavaScript Fallback++DO: Use a reusable utility that tracks interaction state using a `WeakMap`. This avoids polluting the DOM with "dirty" classes or data attributes.++```javascript+const UserInvalidFallback = (() => {+ const dirtyState = new WeakMap();++ const updateState = (input) => {+ const isValid = input.checkValidity();++ // Update both visual and ARIA state+ input.classList.toggle('user-invalid-fallback', !isValid);+ input.classList.toggle('user-valid-fallback', isValid);++ if (!isValid) {+ input.setAttribute('aria-invalid', 'true');+ } else {+ input.removeAttribute('aria-invalid');+ }+ };++ const handleEvent = (event) => {+ const input = event.target;++ if (event.type === 'reset') {+ const controls = input.elements || [];+ for (const control of controls) {+ dirtyState.delete(control);+ control.classList.remove('user-invalid-fallback');+ control.classList.remove('user-valid-fallback');+ control.removeAttribute('aria-invalid');+ }+ return;+ }++ if (!input.checkValidity) return;++ if (event.type === 'input' || event.type === 'change') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasInteracted = true;+ dirtyState.set(input, state);+ if (state.hasBlurred) {+ updateState(input);+ }+ } else if (event.type === 'blur') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasBlurred = true;+ dirtyState.set(input, state);+ if (state.hasInteracted) {+ updateState(input);+ }+ }+ };++ const init = (root = document) => {+ if (CSS.supports('selector(:user-invalid)')) return;++ root.addEventListener('blur', handleEvent, true); // Capture phase+ root.addEventListener('input', handleEvent);+ root.addEventListener('change', handleEvent);+ root.addEventListener('reset', handleEvent, true); // Capture resets+ };++ return { init };+})();++// Initialize for a specific form+const form = document.querySelector('#demo-form');+UserInvalidFallback.init(form);+```+++## Other Considerations++1. **Mobile behavior**: On mobile devices, "blur" might happen differently depending on the OS picker. Testing on actual devices is recommended.+2. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:++```javascript+// Sync aria-invalid with the CSS :user-invalid state+const syncAria = (el) => {+ el.toggleAttribute?.('aria-invalid', el.matches(':user-invalid'));+};++// Update on blur (to show error) and input (to clear it)+document.addEventListener('blur', (e) => syncAria(e.target), true);+document.addEventListener('input', (e) => {+ if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);+});+```diff --git a/skills/modern-web/guides/forms/validate-input-after-interaction.md b/skills/modern-web/guides/forms/validate-input-after-interaction.mdnew file mode 100644index 0000000..424cfa8--- /dev/null+++ b/skills/modern-web/guides/forms/validate-input-after-interaction.md@@ -0,0 +1,258 @@+# Validate Input After Interaction++## The Problem++Displaying validation errors the moment a user focuses on a field and starts typing is premature and distracting. For example, as a user types an email address (e.g., "user@gm") or a password with complex requirements, the field is technically invalid until completion. Standard `:invalid` styling results in an error state appearing immediately, frustrating the user.++## The Solution++The `:user-invalid` pseudo-class allows you to defer the error state until the user has "committed" to a value (by blurring the field) or attempted to submit the form. This ensures validation feedback is provided only after the user has finished interacting with the field.++### Implementation Strategy++1. **HTML Constraint**: DO use standard HTML5 attributes like `type="email"`, `pattern`, and `required` to trigger the browser's built-in validation logic.+2. **Visual Feedback**: DO use `:user-invalid` to apply error styling only after interaction.+3. **Positive Reinforcement**: DO optionally use `:user-valid` to give a green "success" indicator once the requirements are met.+4. **Graceful Recovery**: As soon as the user corrects the input to a valid format, `:user-invalid` stops matching, removing the error state immediately.++## Implementation Guide++### Use Case 1: Email Validation++MANDATORY: Rely on standard HTML5 attributes for email fields. The error message is hidden by default and only revealed when the browser determines the user has left the field in an invalid state.++```html+<form>+ <div class="field">+ <label for="email">Email Address</label>+ <!-- DO: Use standard HTML validation attributes like type="email" and required -->+ <input+ type="email"+ id="email"+ name="email"+ required+ autocomplete="email"+ placeholder="[email protected]"+ aria-errormessage="email-error"+ >+ <div id="email-error" class="error-msg">+ Please enter a valid email address (e.g. [email protected]).+ </div>+ </div>+</form>+```++```css+.error-msg {+ display: none;+ color: #d93025;+ font-size: 0.875rem;+ margin-top: 0.25rem;+}++/*+ DO: Only show error styles after user interaction.+ This prevents the "angry red border" on page load.+*/+input:user-invalid {+ border-color: #d93025;+ background-color: #fce8e6;+}++/* DO: Reveal the error message using the adjacent sibling selector */+input:user-invalid + .error-msg {+ display: block;+}++/* DO: Optionally provide a green success state on :user-valid */+input:user-valid {+ border-color: #188038;+}+```++### Use Case 2: Password Complexity++MANDATORY: Define the complexity rule using a Regex Lookahead pattern in the `pattern` attribute. The rules list is shown to guide the user, and highlighted if there's an error.++```html+<form>+ <div class="field">+ <label for="password">New Password</label>+ <!-- DO: Use pattern and minlength for complex password validation+ DO: Match all constraints with lookaheads via pattern attribute+ (?=.*\d) : Must contain at least one digit+ (?=.*[a-z]) : Must contain at least one lowercase letter+ (?=.*[A-Z]) : Must contain at least one uppercase letter+ (?=.*[\W_]) : Must contain at least one special char+ .{8,} : Must be at least 8 chars long+ -->+ <input+ type="password"+ id="password"+ autocomplete="new-password"+ required+ pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,}"+ minlength="8"+ aria-describedby="password-rules"+ >+ <!-- DO NOT: Hide the rules initially. Users need them to know what to type. -->+ <ul id="password-rules" class="rules-list">+ <li>At least 8 characters</li>+ <li>One uppercase letter</li>+ <li>One number</li>+ <li>One special character</li>+ </ul>+ </div>+</form>+```++```css+/* DO: State the default styling as neutral */+.rules-list { color: #5f6368; }++/* DO: Show invalid state (After interaction): Error */+input:user-invalid {+ border-color: #d93025;+ background-color: #fce8e6;+}++/* DO: Highlight rules list when error is shown */+input:user-invalid + .rules-list {+ color: #d93025;+}++/* DO: Add success indications for :user-valid state */+input:user-valid {+ border-color: #188038;+}+/* DO: Hide rules or turn them green once satisfied */+input:user-valid + .rules-list {+ display: none;+}+```++## Fallbacking & Browser Support++The `:user-invalid` pseudo-class is widely supported (Baseline 2023), but if you need to support older browsers, you must ensure consistency of the implementation.++### CSS for Fallback+DO: Ensure your fallback class shares the native styles. Group your selectors to ensure consistent styling.++```css+/* DO: Ensure native and fallback class share the same styles */+input:user-invalid,+input.user-invalid-fallback {+ border-color: #d93025;+ background-color: #fce8e6;+}++/* DO: Ensure the fallback triggers error messages equally */+input:user-invalid + .error-msg,+input.user-invalid-fallback + .error-msg {+ display: block;+}++/* DO: Ensure the fallback highlights rule lists equally */+input:user-invalid + .rules-list,+input.user-invalid-fallback + .rules-list {+ color: #d93025;+}+```++### JavaScript Fallback++DO: Use a reusable utility that tracks interaction state using a `WeakMap`. This avoids polluting the DOM with "dirty" classes or data attributes.++```javascript+/* DO: Keep state in a WeakMap for automatic cleanup */+const UserInvalidFallback = (() => {+ const dirtyState = new WeakMap();++ const updateState = (input) => {+ const isValid = input.checkValidity();++ // DO: Update both visual and ARIA state+ input.classList.toggle('user-invalid-fallback', !isValid);+ input.classList.toggle('user-valid-fallback', isValid);++ if (!isValid) {+ input.setAttribute('aria-invalid', 'true');+ } else {+ input.removeAttribute('aria-invalid');+ }+ };++ const handleEvent = (event) => {+ const input = event.target;++ if (event.type === 'reset') {+ const controls = input.elements || [];+ for (const control of controls) {+ dirtyState.delete(control);+ /* DO: Clean up dirty states whenever the form is reset */+ control.classList.remove('user-invalid-fallback');+ control.classList.remove('user-valid-fallback');+ control.removeAttribute('aria-invalid');+ }+ return;+ }++ if (!input.checkValidity) return;++ if (event.type === 'input' || event.type === 'change') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasInteracted = true;+ dirtyState.set(input, state);+ if (state.hasBlurred) {+ updateState(input);+ }+ } else if (event.type === 'blur') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasBlurred = true;+ dirtyState.set(input, state);+ if (state.hasInteracted) {+ updateState(input);+ }+ }+ };++ const init = (root = document) => {+ /* DO: Short-circuit initialization if CSS natively supported */+ if (CSS.supports('selector(:user-invalid)')) return;++ root.addEventListener('blur', handleEvent, true); // DO: Use Capture phase for blur+ root.addEventListener('input', handleEvent);+ root.addEventListener('change', handleEvent);+ root.addEventListener('reset', handleEvent, true); // DO: Capture resets+ };++ return { init };+})();++// DO: Initialize for a specific form container+const form = document.querySelector('#demo-form');+UserInvalidFallback.init(form);+```++## Other Considerations++1. **Accessibility**:+ * MANDATORY: Use `aria-describedby` to link the rules list to the input.+ * DO NOT: Hide rules lists entirely until the input is valid; users need to know what to type!+2. **Pattern Attribute Limits**: MANDATORY: The `pattern` attribute performs a full match (implied `^...$`). Ensure your password regex accounts for the entire string.+3. **Validation Strictness**: DO note that the browser's default `type="email"` validation is quite permissive (e.g., `user@localserver` might pass). If you need stricter validation, you may need to use a more robust validation library or a custom validation function alongside `type="email"`.+4. **Focus Management**: MANDATORY: If a user submits the form with an invalid field, the browser will automatically focus the first invalid field. Your `:user-invalid` styles will apply immediately because a submission attempt counts as an interaction.+5. **Consistent ARIA Experience**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:++```javascript+// Sync aria-invalid with the CSS :user-invalid state+const syncAria = (el) => {+ el.toggleAttribute?.('aria-invalid', el.matches(':user-invalid'));+};++// Update on blur (to show error) and input (to clear it)+document.addEventListener('blur', (e) => syncAria(e.target), true);+document.addEventListener('input', (e) => {+ if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);+});+```diff --git a/skills/modern-web/guides/performance/batch-analytics-events.md b/skills/modern-web/guides/performance/batch-analytics-events.mdnew file mode 100644index 0000000..7520f27--- /dev/null+++ b/skills/modern-web/guides/performance/batch-analytics-events.md@@ -0,0 +1,152 @@+# Debounce and batch multiple analytics events++Most analytics and telemetry data is low priority and you can safely defer sending it until the user leaves the page. The exception to this is if you need to deliver real-time updates, in which case timeliness matters.++The optimal way to provide real-time analytics updates, while still minimizing beacons, is to use `fetchLater()` with the `activateAfter` configuration option. This allows you to effectively debounce and batch all analytics events that occur within a given time window into a single beacon, that is reliably sent even if the user leaves the page before the timeout expires.++## How to implement++1. **Schedule the request:** As soon as any relevant analytics data is available, call `fetchLater()` with your data payload and pass an `activateAfter` value. This queues the data to be sent after that amount of time passes, or if the user leaves the page beforehand.++2. **Batch multiple events together:** If a new analytics event occurs before the `activateAfter` timeout expires, abort the previously scheduled request and call `fetchLater()` again (with the same `activateAfter` value) with the full event queue in a single payload.++3. **Reset the event queue when the timeout expires:** If a new analytics event occurs after the scheduled beacon has successfully sent (i.e. the `fetchLater()` result's `activated` value is `true`), reset the event queue.++3. **Let the browser handle the rest:** If the user navigates away or closes the tab before the `activateAfter` timeout expires, the browser will still reliably send the payload from your most recent `fetchLater()` call.++## Example code++This code tracks all `load` and `click` events on a page, and batches together all events that occur within a 10-second timeout.++```javascript+// Replace with your analytics endpoint.+const ANALYTICS_ENDPOINT = '/path/to/analytics/endpoint';++// Replace with a time window of your choice. All analytics events that+// occur within this time window will be batched together.+const BATCH_WINDOW = 10 * 1000;++// The maximum number of events to batch. Pick a number that is unlikely+// to overflow the fetchLater() quota for the page.+const MAX_QUEUE_SIZE = 100;++const eventQueue = [];+let fetchLaterResult;+let fetchLaterController;++function trackEvent(eventData) {+ // If the previously queued beacon has already been sent, or if the+ // max queue size has been met, reset the queue.+ if (fetchLaterResult?.activated || eventQueue.length > MAX_QUEUE_SIZE) {+ fetchLaterController = null;+ fetchLaterResult = null;+ eventQueue.length = 0;+ }++ eventQueue.push(eventData);++ // Abort any pending beacons before creating a new one.+ if (fetchLaterController) {+ fetchLaterController.abort();+ }+ fetchLaterController = new AbortController();++ // Schedule a fetch for the events to be sent when the batch window expires.+ // IMPORTANT: wrap the call in a try/catch to handle quota errors.+ try {+ fetchLaterResult = fetchLater(ANALYTICS_ENDPOINT, {+ method: 'POST',+ headers: {'content-type': 'application/json'},+ body: JSON.stringify(eventQueue),+ signal: fetchLaterController.signal,+ activateAfter: BATCH_WINDOW,+ });+ } catch (error) {+ // Handle errors as needed.+ }+}++// Track page loads.+window.addEventListener('load', () => {+ trackEvent({type: 'page_load'});+});++// Track click events.+window.addEventListener('click', (event) => {+ trackEvent({type: 'click', target: serializeElement(event.target)});+});+```++## Best Practices++- **DO** use `fetchLater()` with the `activateAfter` option set to batch multiple analytics events that occur within close proximity of each other.+- **DO** use an `AbortController` to cancel the pending fetch in cases where a new analytics event occurs.+- **DO** check to ensure you do not batch too many events together and exceed the `fetchLater()` quota (currently roughly 64KB per origin).+- **DO** wrap calls to `fetchLater()` in a `try/catch` to handle quota errors.+- **DO** feature detect the presence of `fetchLater()` on `globalThis` and implement a fallback strategy for browsers that don't support the API.+- **DO NOT** use a `ReadableStream` object for the request body, as that will error.++## Browser support and fallback strategies++fetchLater has limited availability.. Therefore, a fallback strategy is typically required.++However, given the improved reliability and performance benefits of this API, `fetchLater()` should be used if the browser supports it.++### `fetchLater()` polyfill++Use the following minimal `fetchLater()` polyfill, which implements the API as closely as possible in unsupporting browsers.++The only notable behavior difference with this polyfill is instead of sending the payload when the user leaves the page, it sends it whenever the page's `visibilityState` changes to "hidden", since this is the most reliable end-of-session signal that's widely available today.++```js+globalThis.fetchLater ??= function fetchLater(url, init = {}) {+ let timeoutHandle;+ let activated = false;++ function sendNow() {+ if (!(init.signal && init.signal.aborted)) {+ // Use fetch keepalive if the browser supports it or if custom fetch+ // parameters are specified (e.g. custom headers or methods).+ // Otherwise fall back to `navigator.sendBeacon()`.+ if (+ 'keepalive' in Request.prototype ||+ init.method !== 'POST' ||+ init.headers+ ) {+ fetch(url, Object.assign({}, init, {keepalive: true}));+ activated = true;+ } else {+ activated = navigator.sendBeacon(url, init.body);+ }+ }+ destroy();+ }++ function destroy() {+ document.removeEventListener('visibilitychange', sendNow);+ clearTimeout(timeoutHandle);+ }++ if (document.visibilityState === 'hidden') {+ // If the beacon was created while the page is already hidden, send data+ // ASAP but wait until the next microtask to allow all sync code to run.+ queueMicrotask(sendNow);+ } else {+ document.addEventListener('visibilitychange', sendNow);++ if (typeof init.activateAfter === 'number' && init.activateAfter >= 0) {+ timeoutHandle = setTimeout(sendNow, init.activateAfter);+ }+ }++ if (init.signal) {+ init.signal.addEventListener('abort', destroy);+ }++ return {+ get activated() {+ return activated;+ },+ };+};+```diff --git a/skills/modern-web/guides/performance/break-up-long-tasks.md b/skills/modern-web/guides/performance/break-up-long-tasks.mdnew file mode 100644index 0000000..cb0aef0--- /dev/null+++ b/skills/modern-web/guides/performance/break-up-long-tasks.md@@ -0,0 +1,58 @@+Heavy computations or long loops can block the main thread, causing the page to become unresponsive. To prevent this, you should yield control back to the browser periodically. The `scheduler.yield()` API allows you to pause a long task and let the browser handle user input or rendering before continuing.++### Breaking up long tasks++Use `scheduler.yield()` inside async functions to break up work.++```javascript+async function processLargeArray(items) {+ // DO: Set a time-based deadline 50 milliseconds into the future. 50+ // milliseconds is the boundary for when a task becomes a long task.+ let deadline = performance.now() + 50; // 50ms budget++ for (const item of items) {+ // Process the item+ processItem(item);++ // MANDATORY: Yield to the main thread periodically to keep the UI+ // responsive. This can be done by checking if the deadline set earlier+ // has been exceeded. When it has been, yield, then reset the deadline+ // another 50 milliseconds into the future.+ if (performance.now() >= deadline) {+ await scheduler.yield();+ deadline = performance.now() + 50;+ }+ }+}+```++### Fallback strategies++Scheduler API has limited availability.++Some browsers may not support the `scheduler` API. You MUST implement a fallback using `setTimeout` to ensure code executes without breaking.++#### Fallback for `scheduler.yield()`++```javascript+async function processLargeArrayWithFallback(items) {+ // DO: Set a time-based deadline 50 milliseconds into the future.+ let deadline = performance.now() + 50;++ for (const item of items) {+ processItem(item);++ // MANDATORY: Yield to the main thread periodically to keep the UI responsive.+ if (performance.now() >= deadline) {+ // DO: Feature detect scheduler.yield+ if ('scheduler' in window && 'yield' in window.scheduler) {+ await scheduler.yield();+ } else {+ // DO: Fallback to setTimeout for older browsers+ await new Promise(resolve => setTimeout(resolve, 0));+ }+ deadline = performance.now() + 50;+ }+ }+}+```diff --git a/skills/modern-web/guides/performance/calculate-total-foreground-time.md b/skills/modern-web/guides/performance/calculate-total-foreground-time.mdnew file mode 100644index 0000000..f5ad378--- /dev/null+++ b/skills/modern-web/guides/performance/calculate-total-foreground-time.md@@ -0,0 +1,64 @@+This guide details how to accurately calculate the total time a user spends actively viewing a page. Traditional metrics like time-on-page often incorrectly include time spent with the tab in the background. By using the `VisibilityStateEntry` API, you can measure only the "foreground time," providing a better metric of user engagement.++### Implementing foreground time calculation++The `PerformanceTimeline` API exposes visibility state changes as performance entries. Rather than reacting to `visibilitychange` events and manually accumulating time throughout a session, you can query the entire visibility history at any time.++MANDATORY: You must query the `visibility-state` performance entries to calculate the true foreground time.++```javascript+/**+ * Calculates total time the page was in the visible state.+ *+ * @returns {number} Total foreground time in milliseconds.+ */+function getTotalForegroundTime() {+ // MANDATORY: Query the visibility-state entries from the performance timeline.+ const entries = performance.getEntriesByType('visibility-state');++ // Fallback: If the browser does not support VisibilityStateEntry,+ // the API will gracefully return an empty array.+ if (entries.length === 0) {+ // Return total time since navigation start as a fallback.+ return performance.now();+ }++ let totalForegroundTime = 0;++ for (let i = 0; i < entries.length; i++) {+ // Only calculate duration for periods where the state was 'visible'+ if (entries[i].name === 'visible') {+ const start = entries[i].startTime;++ // The end time is the start time of the next state change,+ // or the current time if this is the final entry.+ const end = i + 1 < entries.length+ ? entries[i + 1].startTime+ : performance.now();++ totalForegroundTime += (end - start);+ }+ }++ return totalForegroundTime;+}+```++### Fallback strategies++Page visibility state has limited availability.++The `VisibilityStateEntry` API has limited availability and is currently unsupported in several major browsers.++Because `performance.getEntriesByType('visibility-state')` will return an empty array in browsers that do not support it, feature detection is straightforward and built directly into the execution flow. You must always check if the returned array is empty before attempting to calculate foreground time.++If it is empty, the recommended fallback strategy is to gracefully degrade to standard time-on-page analytics by returning `performance.now()`. This represents the total time elapsed since the page was loaded, ensuring a valid duration is still recorded without throwing runtime errors.++```javascript+const entries = performance.getEntriesByType('visibility-state');++// Empty array means unsupported+if (entries.length === 0) {+ return performance.now(); // Fallback+}+```diff --git a/skills/modern-web/guides/performance/conditional-async-dependencies.md b/skills/modern-web/guides/performance/conditional-async-dependencies.mdnew file mode 100644index 0000000..645a72c--- /dev/null+++ b/skills/modern-web/guides/performance/conditional-async-dependencies.md@@ -0,0 +1,69 @@+Top-level `await` allows modules to act as asynchronous functions, meaning they can pause module execution to await promises. This is extremely useful for conditionally loading async dependencies—like polyfills or heavy secondary libraries—only when required by the browser.++By utilizing top-level await, you can encapsulate the conditional loading logic inside a single module, effectively preventing downstream consumer modules from executing until the dependency is fully loaded and ready.++### Conditional polyfill pattern++While top-level `await` can be used to conditionally load any async dependency that's a module, a good use of the conditional depenency loading pattern is to conditionally load polyfills for browsers that don't support a specific feature. This approach encapsulates feature detection and the dynamic import inside a single dependency module.++In the following case, the `popover` attribute polyfill is conditionally loaded if it isn't present on `HTMLElement.prototype`:++```javascript+// conditionally-load-polyfill.js++// Check if the feature is missing before doing work.+// MANDATORY: Prefer checking HTMLElement.prototype over window or document+// when checking for a global DOM attribute or property like popover.+if (!('popover' in HTMLElement.prototype)) {+ // Use top-level await to pause the execution of any module that imports this file+ // until the polyfill finishes downloading and executing.+ await import('/path/to/popover-polyfill.js');+}++// Export a marker if needed by your application+export const polyfillLoaded = true;+```++```javascript+// main.js++// MANDATORY: Because conditionally-load-polyfill.js uses top-level await,+// this import will block execution of main.js until the polyfill is ready.+import './conditionally-load-polyfill.js';++// Now it is safe to use the feature (e.g., showing a popover)+const myPopover = document.getElementById('my-popover');+if (myPopover) {+ myPopover.showPopover();+}+```++### Avoiding the Safari top-level `await` bug++**MANDATORY:** You must structure your imports carefully to avoid a bug where top-level await doesn't behave as expected in Webkit, which occurs when multiple modules *simultaneously* import a module that contains a top-level `await`:++```javascript+// DO NOT do this: importing the top-level await module from multiple sibling modules+// simultaneously will crash in Safari.+//+// a.js: import './conditionally-load-polyfill.js';+// b.js: import './conditionally-load-polyfill.js';+// main.js: import './a.js'; import './b.js'; // CRASH!++// INSTEAD, guarantee a single entry point:+// Import the top-level await module ONCE at the very top of your application tree.+import './conditionally-load-polyfill.js';++// Then import the rest of your application code, ensuring the await resolves first.+import './app.js';+```++### Fallback strategies++Top-level await has limited availability.++Top-level `await` has been supported in all major browsers since 2021 (Chrome 89, Firefox 89, Safari 15). Because of this broad support, **you do not need to implement a fallback strategy for modern web applications.**++As long as you follow the guidance in the previous section to **avoid the Safari execution order bug**, you can safely rely on top-level `await` directly to manage your async dependencies.++You only need to avoid top-level `await` and fall back to standard asynchronous functions or dynamic `import()` orchestration if your application is explicitly required to support legacy browsers released before 2021.diff --git a/skills/modern-web/guides/performance/defer-rendering-heavy-content.md b/skills/modern-web/guides/performance/defer-rendering-heavy-content.mdnew file mode 100644index 0000000..7680b1f--- /dev/null+++ b/skills/modern-web/guides/performance/defer-rendering-heavy-content.md@@ -0,0 +1,146 @@+# Defer rendering heavy content++Web pages with extensive content—such as infinite scrolls, complex dashboards, or dense articles can suffer from slow initial rendering and sluggish interactions. Modern web technologies allow you to defer the rendering workload for content that is not immediately visible, significantly boosting performance without breaking accessibility or user expectations.++To optimize rendering, you can utilize the CSS `content-visibility` property and the HTML `hidden="until-found"` attribute. While both aid performance, they serve distinct use cases.++## When to use which++| Scenario / Example | Feature Applied | Performance Benefit |+| :--- | :--- | :--- |+| **1. Below the fold** (Delay initial load) | **`content-visibility: auto`** | Browser automatically offloads layout/paint workload until the container scrolls close to view, keeping standard page load speed frictionless. |+| **2. Toggle State** (Fast view switching) | **`content-visibility: hidden`** | Skips layout calculations for hidden divs but preserves style containment state, allowing for instantaneous toggling without structural shifts (superior to `display: none`). |+| **3. Searchable & Deferred** (Collapsible specs/FAQ) | **`hidden="until-found"`** | Same benefits as previous, defers load-time rendering fully, but remains searchable via native Find-in-page. The browser automatically unhides and scrolls to the target on match. |++## How to implement `content-visibility: auto`++### Choosing off-screen content++**MANDATORY**: You MUST carefully identify which elements receive `content-visibility: auto`.+- **DO** target large, self-contained layout blocks that are strictly **below the initial fold** (e.g., card items in an infinite feed, trailing comments, or bottom-heavy layout sections).+- **DO NOT** apply this property to elements within the initial, above-the-fold viewport. Doing so forces the browser to evaluate visibility boundaries before rendering, which paradoxically delays critical page load performance.+- **DO** target elements with deep or complex internal DOM structures to maximize rendering cost savings.++### Implementation steps++1. **MANDATORY**: Identify heavy sections that are confirmed to be off-screen on initial load.+2. **MANDATORY**: Apply `content-visibility: auto` to each of these off-screen elements.+3. **MANDATORY**: Provide an estimated layout structure size using `contain-intrinsic-size` on each element.++### How to use `contain-intrinsic-size`++**MANDATORY**: You MUST pair `content-visibility: auto` with `contain-intrinsic-size`. Failure to do so forces the browser to collapse the element to a 0px height when off-screen, causing severe layout shifting and scrollbar jumping as the user scrolls.++The `contain-intrinsic-size` CSS shorthand property acts as a placeholder dimension. Using the `auto` keyword enables the browser to "remember" the exact size once the element is finally rendered, using that calculated size over the placeholder if the element goes off-screen again.++### Example code++```css+/* DO ONLY apply this class to items OUTSIDE the initial layout viewport */+.heavy-section-deferred {+ /* MANDATORY: Skips rendering calculations when off-screen */+ content-visibility: auto;++ /* Mandatory: Provide an estimated size to prevent layouts shifts.+ - 'auto' is optional and enables the browser to remember the actual size+ once rendered. It must be paired with a <length> value to be used for+ the first render.+ - 'none' tells the browser not to apply any intrinsic width to this element.+ It can be used for either the height or the width value.+ - '150px' is the estimated height of this element. This can be any valid+ CSS <length> value.+ */+ contain-intrinsic-size: auto none auto 150px;+}+```++## How to implement `content-visibility: hidden`++1. **Identify heavy sections:** Locate layout blocks that are initially hidden (e.g., extra rows in a large data table).+2. **Apply CSS:** Add `content-visibility: hidden` to the element.+3. **Reveal the element:** When the element should be revealed, change the `content-visibility` property to `visible` or `auto`.++### Example code++```css+.cached-view {+ /* Hides content but caches rendering state */+ content-visibility: hidden;+}++.cached-view.is-active {+ content-visibility: visible;+}+```++Because `content-visibility: hidden` excludes the element and its children from the accessibility tree and find-in-page search, **DO NOT** use it if the content must remain discoverable while hidden. For searchable hidden content, use `hidden="until-found"`.++## How to implement `hidden="until-found"`++The `hidden="until-found"` attribute forces the browser to apply an internal `content-visibility: hidden` rule. This hides content until a user utilizes "Find in page" or navigates via document fragments directly into the container.++1. **Identify heavy sections:** Locate layout blocks that are initially hidden (e.g., extra rows in a large data table).+2. **Apply the attribute:** Add `hidden="until-found"` directly onto the collapsible container element.+3. **Handle state synchronization:** If reveal states require DOM updates (such as toggling an aria-expanded attribute or rotating a chevron icon), use the `beforematch` event listener.++### Example code++```html+<div class="heavy-section" hidden="until-found">+ <p>Heavy content.</p>+</div>+```++```javascript+// Optional: Handle state synchronization+const heavySection = document.querySelector('.heavy-section');++heavySection.addEventListener('beforematch', (event) => {+ // Logic to execute immediately before the browser reveals the match+});+```++## Best Practices++- **DO** use `contain-intrinsic-size` with `content-visibility: auto`. Failure to do so forces height recalculations on scroll, causing viewport layout jumping or visual glitches.+- **DO NOT** apply `content-visibility: auto` to elements inside the initial fold viewport, as this delays critical page rendering.+- **DO NOT** apply standard `display: none` or `visibility: hidden` to elements designed to use `hidden="until-found"`, as this permanently excludes them from search discovery.+- **DO** verify that `hidden="until-found"` handles interactive states gracefully on trigger.++## Fallback strategies++### `content-visibility` fallback++Baseline status for content-visibility: Newly available. It's been Baseline since 2025-09-15.++When `content-visibility` is not supported it will be ignored by the browser. In most cases `content-visibility: auto` will not need a fallback, though without it performance gains will be lost. An unsupported browser will leave `content-visibility: hidden` elements completely visible. Use feature detection to implement a fallback.++```css+/* Default for everyone */+.inactive {+ display: none;+}++/* Modern Browsers only */+@supports (content-visibility: hidden) {+ .inactive {+ display: block; /* Turn the layout box back on */+ content-visibility: hidden;+ }+}+```++### `hidden="until-found"` fallback++hidden="until-found" has limited availability.++When `hidden="until-found"` is not supported elements will remain hidden. Use feature detection targeting `onbeforematch` and extract or reveal content accordingly. Feature detection MUST check for the existence of `onbeforematch` in `HTMLElement.prototype`.++```javascript+if (!('onbeforematch' in HTMLElement.prototype)) {+ document.querySelectorAll('[hidden="until-found"]').forEach(el => {+ // Unsupported browsers show content to maintain searchability+ el.removeAttribute('hidden');+ });+}+```diff --git a/skills/modern-web/guides/performance/deprioritize-background-fetches.md b/skills/modern-web/guides/performance/deprioritize-background-fetches.mdnew file mode 100644index 0000000..91fdbd1--- /dev/null+++ b/skills/modern-web/guides/performance/deprioritize-background-fetches.md@@ -0,0 +1,36 @@+# Deprioritize background fetches++When a page performs multiple simultaneous network requests, they often compete for the same bandwidth. Non-critical data such as analytics, logging, or background synchronization should be deprioritized so that user-initiated or critical data fetches can complete more quickly.++## How to implement++1. **Identify background requests**: Determine which `fetch()` calls are for non-essential data that doesn't impact the immediate user experience.+2. **Apply fetch priority**: Add the `priority: 'low'` option to the `fetch()` initialization object.++## Example code++```javascript+// Use high priority (default) for critical UI updates+const criticalData = await fetch('/api/data');++// Explicitly deprioritize background analytics+fetch('/api/analytics', {+ method: 'POST',+ body: JSON.stringify(eventData),+ // Lower the priority to prevent network contention+ priority: 'low'+});+```++## Best practices++- **DO** use `priority: 'low'` for analytics, beacons, or telemetry data that isn't required for the current view.+- **DO** use `priority: 'low'` for "prefetching" data that the user *might* need later, ensuring it doesn't slow down what they need *now*.+- **DO NOT** use `priority: 'low'` for fetches that are critical to the user experience.+- **DO NOT** use the deprecated `importance` key in the fetch options object. The correct key is `priority`.++## Fallback strategy++Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.++The `priority` option in the Fetch API is a progressive enhancement. Browsers that do not support it will ignore the option and treat the request with default priority. No explicit feature detection or fallback logic is required for basic usage.diff --git a/skills/modern-web/guides/performance/full-session-analytics.md b/skills/modern-web/guides/performance/full-session-analytics.mdnew file mode 100644index 0000000..02e270e--- /dev/null+++ b/skills/modern-web/guides/performance/full-session-analytics.md@@ -0,0 +1,133 @@+# Reliably measure full-session analytics and telemetry++To reliably analytics and telemetry data that covers the entirety of a user's visit to a web page (not just until page load) use the `fetchLater()` API.++The `fetchLater()` API is the most reliably way to send data to a server in cases where a response is not required and delivery timing is not urgent, which applies to data such as user analytics, telemetry, error tracking, and performance metrics like Core Web Vitals.++Older technique like creating an `<img>` pixel in an `unload` event listener are notoriously unreliably (especially on mobile) and can negatively impact performance (by making pages ineligible for bfcache).++## How to implement++1. **Schedule the request:** As soon as relevant data is available, call `fetchLater()` with your data payload. This queues the data to be sent later.++2. **Update the payload as needed:** If the user generates more data or the state changes, abort the previously scheduled request and call `fetchLater()` again with the fully updated snapshot.++3. **Let the browser handle the rest:** When the user navigates away or closes the tab, the browser will reliably send the payload from your most recent `fetchLater()` call.++## Example code++This code measures the session duration of a user's visit to a page using `fetchLater()` to queue a new beacon every 10 seconds with the updated session duration.++```javascript+const ANALYTICS_ENDPOINT = '/path/to/analytics/endpoint';++const sessionData = {+ duration: 0,+ id: crypto.randomUUID(),+};++let fetchLaterController = null;++function queueBeacon() {+ // Abort any pending beacons before creating a new one.+ if (fetchLaterController) {+ fetchLaterController.abort();+ }+ fetchLaterController = new AbortController();++ // Update session duration to the current page time.+ sessionData.duration = performance.now();++ // Schedule a fetch for the data payload to be sent later.+ // IMPORTANT: wrap the call in a try/catch to handle quota errors.+ try {+ fetchLater(ANALYTICS_ENDPOINT, {+ method: 'POST',+ headers: {'content-type': 'application/json'},+ body: JSON.stringify(sessionData),+ signal: fetchLaterController.signal,+ });+ } catch (error) {+ // Handle errors as needed.+ }+}++// Update the session data and queue a new beacon every 10 seconds.+setInterval(queueBeacon, 10000);+```++## Best Practices++- **DO** use `fetchLater()` to send data to a server in any situation where a response is not necessary, and it's not critical that the data is sent immediately.+- **DO** use an `AbortController` to cancel the pending fetch in cases where the data may need to be updated before the user leaves the page+- **DO** minimum the payload size to avoid exceeding the quota (currently roughly 64KB per origin).+- **DO** wrap calls to `fetchLater()` in a `try/catch` to handle quota errors.+- **DO** feature detect the presence of `fetchLater()` on `globalThis` and implement a fallback strategy for browsers that don't support the API.+- **DO NOT** use a `ReadableStream` object for the request body, as that will error.++## Browser support and fallback strategies++fetchLater has limited availability.++A fallback strategy is required if `fetchLater()` doesn't meet your Baseline target. However, given the improved reliability and performance benefits of this API, `fetchLater()` should be used if the browser supports it.++The recommended fallback strategy is to use the polyfill below, which internally handles unsupporting browsers using `fetch()` with `keepalive` or `navigator.sendBeacon()`. Your own code MUST call `fetchLater()` directly — never call `fetch()`, `sendBeacon()`, or other beacon APIs yourself.++### `fetchLater()` polyfill++Use the following minimal `fetchLater()` polyfill, which implements the API as closely as possible in unsupporting browsers.++The only notable behavior difference with this polyfill is that it uses `visibilitychange` to detect when the user leaves, rather than relying on the browser's native unload handling. This is an internal implementation detail — your code does not need to listen for `visibilitychange` or any other page lifecycle events. Just call `fetchLater()` and the polyfill handles delivery.++```js+globalThis.fetchLater ??= function fetchLater(url, init = {}) {+ let timeoutHandle;+ let activated = false;++ function sendNow() {+ if (!(init.signal && init.signal.aborted)) {+ // Use fetch keepalive if the browser supports it or if custom fetch+ // parameters are specified (e.g. custom headers or methods).+ // Otherwise fall back to `navigator.sendBeacon()`.+ if (+ 'keepalive' in Request.prototype ||+ init.method !== 'POST' ||+ init.headers+ ) {+ fetch(url, Object.assign({}, init, {keepalive: true}));+ activated = true;+ } else {+ activated = navigator.sendBeacon(url, init.body);+ }+ }+ destroy();+ }++ function destroy() {+ document.removeEventListener('visibilitychange', sendNow);+ clearTimeout(timeoutHandle);+ }++ if (document.visibilityState === 'hidden') {+ // If the beacon was created while the page is already hidden, send data+ // ASAP but wait until the next microtask to allow all sync code to run.+ queueMicrotask(sendNow);+ } else {+ document.addEventListener('visibilitychange', sendNow);++ if (typeof init.activateAfter === 'number' && init.activateAfter >= 0) {+ timeoutHandle = setTimeout(sendNow, init.activateAfter);+ }+ }++ if (init.signal) {+ init.signal.addEventListener('abort', destroy);+ }++ return {+ get activated() {+ return activated;+ },+ };+};+```diff --git a/skills/modern-web/guides/performance/identify-heavy-scripts.md b/skills/modern-web/guides/performance/identify-heavy-scripts.mdnew file mode 100644index 0000000..0377614--- /dev/null+++ b/skills/modern-web/guides/performance/identify-heavy-scripts.md@@ -0,0 +1,67 @@+# Identify heavy-running JavaScript++Heavy-running JavaScript can have a detrimental effect on both page load performance and interactivity. Modern web applications are more heavily reliant on JavaScript than ever before, from multiple sources. These include the application code itself (and the framework code it relies on), as well as third-party scripts that add functionality like chat widgets and video players. Behind-the-scenes analytics and marketing scripts are also common contributors that are all too easy to forget.++Identifying root causes of an unresponsive web page can be tricky with certain expertise required to run web performance tracing or profiling and how to interpret the results. Additionally field data is often very different to lab data, which only replicates a small subset of real user scenarios. This can make it difficult to identify the root causes of poor performance, especially for interactions.++The Long Animation Frames API is a lightweight API that can be used to identify heavy-running JavaScript in the field. A heavy-running script can be either a single long-running script, or a script that runs multiple times during the page lifecycle.++## How to implement++Long animation frames are monitored using the `PerformanceObserver` interface. It emits a `long-animation-frame` entry when an animation frame takes longer than 50ms to render. The entry contains information about the long animation frame, including the duration of the frame and the scripts that were executed during the frame.++The `long-animation-frame` entry contains a `scripts` property which is an array of `PerformanceScript` objects. Each `PerformanceScript` object contains information about the script that was executed during the long animation frame, including the `sourceURL` and `duration` of the script.++### Example of identifying the longest running scripts that contribute to long animation frames++```javascript+// Accumulate all script entries across the page lifecycle so no+// data is lost between observer callbacks.+const allScripts = [];++const observer = new PerformanceObserver(list => {+ // Collect all script entries across frames to find the biggest offenders.+ allScripts.push(...list.getEntries().flatMap(entry => entry.scripts));++ // Group by sourceURL so you can identify which scripts contribute+ // the most total time, even if each individual invocation is short.+ const scriptSource = [...new Set(allScripts.map(script => script.sourceURL))];+ const scriptsBySource = scriptSource.map(sourceURL => ([sourceURL,+ allScripts.filter(script => script.sourceURL === sourceURL)+ ]));+ const processedScripts = scriptsBySource.map(([sourceURL, scripts]) => ({+ sourceURL,+ count: scripts.length,+ totalDuration: scripts.reduce((subtotal, script) => subtotal + script.duration, 0)+ }));++ // Only include scripts above a certain threshold to reduce noise.+ const heavyScripts = processedScripts.filter(script => {+ return script.totalDuration > 100;+ });++ // Sort by total duration so the worst offenders appear first,+ // making it easier to prioritize optimization efforts.+ heavyScripts.sort((a, b) => b.totalDuration - a.totalDuration);++ // Log to the console for local debugging. In production, replace+ // this with a call to send the data to your analytics service.+ console.table(heavyScripts);+});++// Use buffered: true to capture any long frames that occurred before+// this observer was registered.+observer.observe({type: 'long-animation-frame', buffered: true});+```++## Best Practices++- **DO** prefer the Long Animation Frames API over alternatives like the JS Self-Profiling API, which carries higher runtime overhead.+- **DO** summarize the key information as the Long Animation Frames API contains a lot of detail.+- **DO** send the required information to an analytics service in production.++## Browser support and fallback strategies++Long animation frames has limited availability..++The Long Animation Frames API is ignored by browsers that do not support it, so it can be safely used without fallbacks. In most cases the performance opportunities it identifies will apply to other browsers as well.diff --git a/skills/modern-web/guides/performance/identify-inp-causes.md b/skills/modern-web/guides/performance/identify-inp-causes.mdnew file mode 100644index 0000000..e719961--- /dev/null+++ b/skills/modern-web/guides/performance/identify-inp-causes.md@@ -0,0 +1,57 @@+# Identify causes of poor INP++Poor responsiveness to interactions leads to a poor impression of a page being slow or even completely broken. Interaction to Next Paint (INP) is a metric based on the Event Timing API. It measures the worst interaction (minus some outliers) as a measure of the page's responsiveness.++Identifying root causes of an unresponsive web page can be tricky especially as it depends on user interactions and environmental conditions such as device capabilities and network conditions. This makes it even more difficult to diagnose compared to a more repeatable and predictable scenario like page load. Lab data only replicates a small subset of real user scenarios so measuring the causes of slow INP in the field is essential.++A full performance trace using the JS Self-Profiling API is a heavyweight solution that is liable to cause performance problems. The Long Animation Frames API is a lightweight API that can be used to identify slow running JavaScript in the field for INP interactions.++## How to implement++Calculating INP from the raw Event Timing API is complicated and has several nuances. You are advised to use a RUM tool or library to gather this data.++`web-vitals` is an open-source library from Google that calculates the Core Web Vitals including INP, and also includes long animation frame data for the INP interaction.++### Get Long Animation Frame data for INP interactions using web-vitals library++The [`web-vitals` library](https://github.com/GoogleChrome/web-vitals) is a tiny library used to measure Core Web Vitals and other performance metrics. The `onINP()` function can be used to identify the slowest interaction and includes information about the scripts that were executed during the interaction using the Long Animation Frames API.++```javascript+// Use the attribution build to get Long Animation Frame data+// alongside the INP metric value.+import { onINP } from 'web-vitals/attribution';++onINP((metric) => {+ // Beacon script attribution for the longest script during the INP+ // interaction, so you can identify the root cause in production.+ navigator.sendBeacon(+ '/analytics',+ JSON.stringify({+ name: 'INP',+ value: metric.value,+ // These fields identify which script function was responsible+ // for the longest processing during the INP interaction.+ invokerType: metric.attribution.longestScript.entry?.invokerType,+ sourceURL: metric.attribution.longestScript.entry?.sourceURL,+ sourceFunctionName: metric.attribution.longestScript.entry?.sourceFunctionName,+ sourceCharPosition: metric.attribution.longestScript.entry?.sourceCharPosition,+ // subpart indicates which phase (input delay, processing, or+ // presentation delay) the longest script overlapped with most.+ subpart: metric.attribution.longestScript.subpart,+ intersectingDuration: metric.attribution.longestScript.intersectingDuration+ })+ );+});+```++## Best Practices++- **DO** prefer the Long Animation Frames API over alternatives like the JS Self-Profiling API, which carries higher runtime overhead.+- **DO** use the `web-vitals` library if no other RUM solution is in place. It can identify the INP interaction and includes information about the scripts that were executed during the interaction (using the Long Animation Frames API).+- **DO** beacon back the required information to an analytics service rather than just log it locally.++## Browser support and fallback strategies++Long animation frames has limited availability..++The Long Animation Frames API is ignored by browsers that do not support it, so it can be safely used without fallbacks. In most cases the performance opportunities it identifies will apply to other browsers as well.diff --git a/skills/modern-web/guides/performance/improve-next-page-load-performance.md b/skills/modern-web/guides/performance/improve-next-page-load-performance.mdnew file mode 100644index 0000000..08ec9b3--- /dev/null+++ b/skills/modern-web/guides/performance/improve-next-page-load-performance.md@@ -0,0 +1,119 @@+# Improve next page load performance++One of the most effective ways to improve page load performance for users navigating a site is to initiate loading the next page they're about to visit *before* they visit it. This can be done through a technique called speculative loading using the Speculation Rules API.++## How it works++Speculative loading works by using JSON-based speculation rules to tell the browser about links that can be prefetched or prerendered improving page load performance when user clicks on them.++The rules can either be a hardcoded list of URLs a `urls` key (known as a list rule), or with a `where` key containing a set of href and CSS selectors used to find links on the page (known as a `document` rule).++Rules can also include an optional `eagerness` property that specifies when the page should be prefetched or prerendered. The `eagerness` property can be set to `immediate`, `eager`, `moderate`, or `conservative`. `immediate` speculates as soon as possible, while the others wait for user signals such as hovering for a short period, for a longer period, or starting to click on the page respectively.++Rules can be combined with different eagerness settings to prefetch eagerly and then prerender when the user interacts more.++## When to use it++Speculative loading is especially useful for static pages, where the content is not likely to change often, and where pages are cheaper to produce—especially if cached at the edge. It can also be used for dynamic pages, but it is important to be careful about the potential for stale content.++Speculative loading is typically used for same-origin links, though more advanced options allow for some cross-origin speculation. This guide concentrates on the more-common same-origin use case.++More eager speculative loading is a good choice for pages that are likely to be visited next, such as a headline article or the next page in a stepped process like a learning a course.++Less eager speculative loading is a good choice when it is less obvious what the user will do next, when there are many links on the page, each equally likely to be visited. By waiting for more signals, such as hovering, or starting to click on the page, you can get a head-start on the next page and improve the user experience, even if it is not fully prefetched or prerendered.++Similarly, prefetch is a more conservative choice than prerender, using less resources (on both the client and the server side) but providing less benefit to the user. It is a good choice for initial implementation, expanding to prerender later when the developer explicitly requests it.++## How to use it++Speculation rules have a JSON-based format and can be included in a `<script type="speculationrules">` tag. The rules can be included in the `<head>` or `<body>` of the document, or can be dynamically added using JavaScript.++A `tag` can also be used, either at a global level or on a per-rule basis. When set, this tag will be included in the `Sec-Speculation-Tags` header, and allows you to identify server-side which speculations were made.++### Example of a simple URL list rule for prefetching predefined URLs++```html+<script type="speculationrules">+ {+ "tag": "product-page-speculations",+ "prefetch": [+ {+ "urls": ["/product/1", "/product/2", "/product/3"]+ }+ ]+ }+</script>+```++### Example of a simple document rule for prerendering all same-origin links on a page++```html+<script type="speculationrules">+ {+ "tag": "all-links-speculations",+ "prerender": [{+ "where": { "href_matches": "/*" }+ }]+ }+</script>+```++### Example of a complex document rule for prerendering links with exclusions for interactive sites++```html+<script type="speculationrules">+ {+ "tag": "speculations-with-exclusions",+ "prerender": [{+ "where": {+ "and": [+ { "href_matches": "/*" },+ { "not": {"href_matches": "/wp-admin"}},+ { "not": {"href_matches": "/*\\?*(^|&)add-to-cart=*"}},+ { "not": {"selector_matches": ".do-not-prerender"}},+ { "not": {"selector_matches": "[rel~=nofollow]"}}+ ]+ }+ }]+ }+</script>+```++### Example of a mixed rule set++This example shows a rule set that prefetches all links eagerly, and then goes further than this to prerender those same links when it gets more signals with `moderate` eagerness.++```html+<script type="speculationrules">+ {+ "prefetch": [{+ "tag": "prefetch-speculations",+ "where": { "href_matches": "/*" },+ "eagerness": "eager"+ }],+ "prerender": [{+ "tag": "prerender-speculations",+ "where": { "href_matches": "/*" },+ "eagerness": "moderate"+ }]+ }+</script>+```++## Best Practices++- **DO** use speculation rules to prefetch and prerender pages that the user is likely to visit next.+- **DO** use speculation rules for static sites, where the content is not likely to change often, and where pages are cheaper to produce—especially if cached at the edge.+- **DO** take more care when using speculation rules for dynamic pages, where the content is more likely to change often, may become out of date, and where pages are more expensive to produce.+- **DO** prefer document rules over list rules, as they are more flexible, allow the same rule to be shared across multiple pages, and can be used to prefetch and prerender pages that are not known in advance.+- **DO** consider the trade-offs between prefetch and prerender, and choose the appropriate one for your use case. Prerender is more expensive than prefetch and can cause more unintended side effects in complex applications that display dynamic state, but provides a better user experience. Ask the developer for their preference if unsure.+- **DO** consider the trade-offs between the different `eagerness` levels, and choose the appropriate one for your use case. More eager speculation provides a better user experience but uses more resources and can cause more unintended side effects in complex applications that display dynamic state. Ask the developer for their preference if unsure.+- **DO NOT** overuse speculation rules, for example, to speculate every link on the page. Browsers have limits (2 speculations for non-eager speculations). `immediate` should only be used for a very small number of links.+- **DO NOT** speculate URLs that likely trigger state changes, like `/logout` or `/add-to-cart`, and explicitly exclude them from your speculation rules if they are likely to be included in document rules.+- **DO NOT** use speculation rules on Single Page Applications (SPAs). Speculation rules are designed for multi-page applications (MPAs) where the browser navigates to a new document on each navigation. In SPAs, the browser does not navigate to a new document on each navigation, so speculation rules will not work as expected.++## Browser support and fallback strategies++Speculative loading is a new feature, and as such, is not supported in all modern browsers (Baseline limited availability).++However, speculative loading is a progressive enhancement. It is perfectly safe to use as an enhancement, and is highly recommended given the potential performance benefits. If a browser does not support speculation rules, it will simply ignore them.diff --git a/skills/modern-web/guides/performance/optimize-image-priority.md b/skills/modern-web/guides/performance/optimize-image-priority.mdnew file mode 100644index 0000000..c390d28--- /dev/null+++ b/skills/modern-web/guides/performance/optimize-image-priority.md@@ -0,0 +1,60 @@+# Optimize image priority++Browsers use heuristics to assign loading priorities to images, but these defaults may not always align with your page's Largest Contentful Paint (LCP). Using `fetchpriority` on an `<img>` element allows you to explicitly signal an image's importance to the browser, ensuring critical images load faster while non-essential ones don't compete for bandwidth.++## How to implement++1. **Identify the LCP image**: Determine which image is the most likely candidate for the Largest Contentful Paint (usually the hero image at the top of the page).+2. **Elevate LCP priority**: Add `fetchpriority="high"` to the `<img>` element for the LCP candidate.+3. **Deprioritize non-critical images**: For images that are part of a secondary UI or are only revealed after user interaction (like mega menus, modals, or off-screen carousel slides), add `fetchpriority="low"`.+4. **Optimize lazy loading**: Never use `loading="lazy"` on the LCP image. For standard below-the-fold images, `loading="lazy"` is sufficient to defer the request until the user scrolls near them. Avoid adding `fetchpriority="low"` to these images, as you want them to load at normal priority once the user scrolls to them. Reserve `fetchpriority="low"` for images that are technically "above the fold" but not initially visible (e.g., hidden carousel slides or mega menus). For these hidden images, it is acceptable to use `loading="lazy"` as well; the browser will handle the request timing while respecting the low priority.+5. **Prefer default priorities**: If an image should have normal loading priority, omit the `fetchpriority` attribute entirely rather than setting it to `auto`. This is a stylistic convention to keep your HTML cleaner while relying on the browser's native heuristics.++## Example code++```html+<!-- Elevate priority for the LCP image -->+<img src="/images/hero-lcp.jpg"+ alt="Main Banner"+ fetchpriority="high"+ width="800" height="400">++<!-- Deprioritize initially hidden images above the fold -->+<img src="/images/gallery-alt.jpg"+ alt="Gallery Image"+ fetchpriority="low"+ width="400" height="300">++<!-- Deprioritize images revealed only after user interaction -->+<img src="/images/mega-menu-promo.jpg"+ alt="Special Offer"+ fetchpriority="low"+ width="300" height="150">++<!-- Use lazy loading ALONE for standard below-the-fold images -->+<img src="/images/footer-logo.png"+ alt="Footer Logo"+ loading="lazy"+ width="120" height="60">++<!-- Omit fetchpriority for images with standard priority -->+<img src="/images/standard-image.jpg"+ alt="Standard Image"+ width="400" height="300">+```++## Best practices++- **MANDATORY**: Always apply `fetchpriority="high"` to the LCP image.+- **MANDATORY**: Only use `fetchpriority="high"` on at most 1-2 critical images to avoid network contention and diluting the priority boost.+- **MANDATORY**: Use `fetchpriority="low"` for images that are technically "above the fold" but initially hidden (e.g., hidden carousel slides, mega menu images).+- **MANDATORY**: **Do not** use `fetchpriority="low"` on standard below-the-fold images that are already using `loading="lazy"`. These images should load at normal priority once they enter the viewport.+- **RECOMMENDED**: Avoid using `fetchpriority="auto"`. If you want the default priority, omit the attribute entirely to keep your HTML clean.+- **DO NOT** combine `fetchpriority="high"` with `loading="lazy"` for the LCP image.+- **DO NOT** use the deprecated `importance` attribute. It has been replaced by `fetchpriority` and is not supported by any browser.++## Fallback strategy++Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.++The `fetchpriority` attribute is a progressive enhancement for the `<img>` element. If a browser does not support it, the attribute is ignored, and the browser uses its default priority heuristics.diff --git a/skills/modern-web/guides/performance/optimize-preload-priority.md b/skills/modern-web/guides/performance/optimize-preload-priority.mdnew file mode 100644index 0000000..b7a86da--- /dev/null+++ b/skills/modern-web/guides/performance/optimize-preload-priority.md@@ -0,0 +1,40 @@+# Optimize preload priority++Preloading resources with `<link rel="preload">` signals to the browser that a resource will be needed soon. However, preloads inherit the default priority for the resource type and for images in particular this is low. Using `fetchpriority` allows you to refine this relative priority, in particular ensuring image preloads are preloaded with a high priority allowing them to start earlier and use get more bandwidth resources.++## How to implement++1. **Identify preload candidates**: Find resources that are not discovered early by the browser (e.g., video poster images or background images in CSS) but are essential for the page's appearance.+2. **Elevate critical image preloads**: For the LCP image or other critical images that are not prioritized by default, use `<link rel="preload" fetchpriority="high">` to ensure they are prioritized above other preloads. Note that fonts are already high priority by default.+3. **Deprioritize non-critical preloads**: For resources that aren't critical for the initial render (e.g., a background video or secondary fonts), use `<link rel="preload" fetchpriority="low">`.+4. **Coordinate with resource types**: Note that different `as` types have different default priorities; use `fetchpriority` to override these defaults when necessary.++## Example code++```html+<!-- Elevate priority for a video poster image that acts as the LCP candidate -->+<link rel="preload" href="/images/video-poster.jpg" as="image" fetchpriority="high">++<!-- Elevate priority for a critical LCP image that is hidden in CSS -->+<link rel="preload" href="/images/hero-background.jpg" as="image" fetchpriority="high">++<!-- Deprioritize a secondary font to avoid network contention -->+<link rel="preload" href="/fonts/secondary-font.woff2" as="font" type="font/woff2" fetchpriority="low" crossorigin>+```++## Best Practices++- **MANDATORY**: Only use `fetchpriority="high"` on at most 1-2 critical image preloads to avoid network contention and diluting the priority boost.+- **MANDATORY**: Use `fetchpriority="high"` on Largest Contentful Paint (LCP) images.+- **DO**: Limit the total number of preloads on a page to at most 2 images and 2-3 essential fonts to prevent bandwidth contention.+- **DO** use `fetchpriority="low"` for preloads that you want the browser to start early but not at the expense of critical resources (especially non-critical fonts).+- **DO** specify the `as` attribute correctly to ensure the preload will be used.+- **DO** prefer making critical resources (like LCP images) statically discoverable in HTML via `<img>` tags rather than relying on preloads for background images.+- **DO** ensure that font preloads always have the `crossorigin` attribute (even if same-origin).+- **DO NOT** use the deprecated `importance` attribute. It has been replaced by `fetchpriority`.++## Fallback strategy++Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.++The `fetchpriority` attribute on `<link rel="preload">` is a progressive enhancement. Browsers that do not support it will still preload the resource using their default priority for that resource type. To ensure compatibility, always provide correct `as` and `type` attributes.diff --git a/skills/modern-web/guides/performance/optimize-script-priority.md b/skills/modern-web/guides/performance/optimize-script-priority.mdnew file mode 100644index 0000000..0db018d--- /dev/null+++ b/skills/modern-web/guides/performance/optimize-script-priority.md@@ -0,0 +1,37 @@+# Optimize script priority++Browsers assign default priorities to scripts based on where they appear in the document and whether they have attributes like `async` or `defer`. Using `fetchpriority` gives developers explicit control to ensure critical scripts load first, while non-essential scripts stay out of the way.++## How to implement++1. **Identify critical scripts**: Determine which scripts are essential for the page's core functionality or initial user interaction.+2. **Elevate critical async scripts**: For critical scripts loaded with `async` or `defer`, add the `fetchpriority="high"` attribute to ensure they are prioritized during the discovery phase.+3. **Deprioritize non-essential scripts**: For scripts that are not needed immediately (e.g., analytics, ads, or below-the-fold widgets), add `fetchpriority="low"` and ensure they have a `async`, `defer`, or `module` attribute to avoid blocking.+4. **Sequence parser-blocking scripts**: Use `fetchpriority="low"` on parser-blocking scripts at the end of the body to prevent them from contending for bandwidth with more critical resources.++## Example code++```html+<!-- Elevate the priority of the critical app logic -->+<script src="/js/app.js" async fetchpriority="high"></script>++<!-- Deprioritize non-essential tracking scripts -->+<script src="/js/tracker.js" async fetchpriority="low"></script>++<!-- Deprioritize late-body scripts to favor critical images or CSS -->+<script src="/js/legacy-widgets.js" fetchpriority="low"></script>+```++## Best Practices++- **MANDATORY**: Only use `fetchpriority="high"` on at most 1-2 critical scripts to avoid network contention and diluting the priority boost.+- **DO** use `fetchpriority="high"` specifically for `async` scripts that are known to be critical for Interaction to Next Paint (INP).+- **DO** deprioritize scripts that are not required for the initial user experience using `fetchpriority="low"`.+- **DO NOT** use `fetchpriority` on every script tag; it should only be used to change the browser's default heuristic when it is known to be sub-optimal.+- **DO NOT** use the deprecated `importance` attribute. It has been replaced by `fetchpriority`.++## Fallback strategy++Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.++The `fetchpriority` attribute is a progressive enhancement. Browsers that do not support it will ignore the attribute and use their internal scheduling logic without error. No explicit feature detection or fallback logic is required for basic usage.diff --git a/skills/modern-web/guides/performance/resolution-optimized-pseudo-elements.md b/skills/modern-web/guides/performance/resolution-optimized-pseudo-elements.mdnew file mode 100644index 0000000..636b751--- /dev/null+++ b/skills/modern-web/guides/performance/resolution-optimized-pseudo-elements.md@@ -0,0 +1,46 @@+Using resolution-optimized images in CSS pseudo-elements (like `::before` or `::after`) allows you to add decorative icons or structural graphics without cluttering your HTML with extra DOM nodes. By combining pseudo-elements with the `image-set()` CSS function, you can provide the browser with multiple formats (such as AVIF or WebP) and resolutions (like `1x` and `2x`). The browser will automatically choose the most optimal image for the user's device capabilities.++### Implementation++You can use the `image-set()` function directly within the `content` property of a pseudo-element, or within its `background-image` property (while setting `content: ""`). Note that while providing both the image format via `type()` and the resolution (like `1x` or `2x`) yields the best results, both of these arguments are optional.++```css+.icon-button::before {+ /* Using image-set directly in the content property */+ /* MANDATORY: Always order your formats from most optimized (AVIF) to least optimized (JPEG/PNG).+ The browser will stop at the first supported format. */+ content: image-set(+ url("icon.avif") type("image/avif") 1x,+ url("icon-2x.avif") type("image/avif") 2x,+ url("icon.webp") type("image/webp") 1x,+ url("icon-2x.webp") type("image/webp") 2x,+ url("icon.png") type("image/png") 1x,+ url("icon-2x.png") type("image/png") 2x+ );++ display: inline-block;+ margin-right: 8px;+ vertical-align: middle;+}+```++### Fallback strategies++Baseline status for image-set(): Widely available. It's been Baseline since 2023-09-18.++For older browsers that do not support the `image-set()` function, you **MUST** provide a standard image declaration *before* the `image-set()` rule. This progressive enhancement strategy relies on CSS's cascading nature: unsupported rules are ignored.++```css+.icon-button::before {+ /* MANDATORY: Fallback for browsers that do not support image-set() */+ content: url("icon.png");++ /* Modern browsers will apply this and override the fallback */+ content: image-set(+ url("icon.avif") type("image/avif") 1x,+ url("icon-2x.avif") type("image/avif") 2x,+ url("icon.png") type("image/png") 1x,+ url("icon-2x.png") type("image/png") 2x+ );+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/performance/schedule-tasks-by-priority.md b/skills/modern-web/guides/performance/schedule-tasks-by-priority.mdnew file mode 100644index 0000000..e0be384--- /dev/null+++ b/skills/modern-web/guides/performance/schedule-tasks-by-priority.md@@ -0,0 +1,57 @@+When building complex web applications, tasks have different levels of urgency. Completing tasks for the current view is more important than sending analytics or prefetching assets. The Prioritized Task Scheduling API allows you to schedule work with specific priorities, ensuring the browser remains responsive to user input.++### Scheduling tasks by priority++Use `scheduler.postTask()` to schedule tasks with one of three priorities:+- `user-blocking`: Tasks that block user interaction (e.g., input handling, critical rendering).+- `user-visible`: Tasks visible to the user but not blocking (default).+- `background`: Tasks that are not time-critical (e.g., analytics, prefetching).++```javascript+// Schedule a high-priority task that blocks user interaction+scheduler.postTask(() => {+ // DO: Handle critical updates that impact user interaction+ handleCriticalUpdate();+}, { priority: 'user-blocking' });++// Schedule a default priority task+scheduler.postTask(() => {+ // DO: Render non-critical content that is visible to the user+ renderSecondaryContent();+}); // Defaults to 'user-visible'++// Schedule a low-priority background task+scheduler.postTask(() => {+ // DO: Perform heavy background work that is not time-critical+ sendAnalytics();+}, { priority: 'background' });+```++### Fallback strategies++Scheduler API has limited availability.++To support browsers that do not have the Prioritized Task Scheduling API, you must use a polyfill to maintain task prioritization.++```javascript+// Feature detect the scheduler API+if (!('scheduler' in window && 'postTask' in window.scheduler)) {+ // DO: Conditionally load the polyfill for browsers that need it+ const script = document.createElement('script');+ script.src = 'https://unpkg.com/scheduler-polyfill';+ script.onload = () => {+ // Polyfill is loaded and ready to use+ runScheduledTasks();+ };+ document.head.appendChild(script);+} else {+ runScheduledTasks();+}++function runScheduledTasks() {+ // Now safe to use scheduler.postTask in all browsers+ scheduler.postTask(() => {+ console.log('Task with priority support');+ }, { priority: 'background' });+}+```diff --git a/skills/modern-web/guides/performance/sequence-distributed-events.md b/skills/modern-web/guides/performance/sequence-distributed-events.mdnew file mode 100644index 0000000..1f4aa5f--- /dev/null+++ b/skills/modern-web/guides/performance/sequence-distributed-events.md@@ -0,0 +1,74 @@+# Sequencing Distributed Events++High-frequency tracing and event logging in distributed systems require precise timestamps to ensure correct causal ordering. Standard JavaScript `Date.now()` provides millisecond resolution, which can lead to timestamp collisions when multiple events occur within the same millisecond.++The `Temporal` API, specifically `Temporal.Instant`, provides nanosecond-resolution timestamps, enabling precise sequencing of events without collisions.++## How to Implement++To sequence high-frequency events using `Temporal`:++1. **Capture exact timestamps**: Use `Temporal.Now.instant()` to get the current exact time with nanosecond precision.+2. **Sort events chronologically**: Use `Temporal.Instant.compare(a, b)` to sort event objects. This method resolves ordering differences up to the nanosecond level.+3. **Calculate delays**: Use `Temporal.Instant.prototype.since(other)` to find the precise duration between events.+4. **Serialize for transmission**: Use `Temporal.Instant.prototype.toString()` to convert the timestamp to a standard ISO-8601 string for logging or network transmission.++## Example Code: High-Frequency Event Sequencing++```javascript+// 1. Capture timestamps for incoming events+function recordEvent(eventType, nodeId) {+ return {+ nodeId,+ eventType,+ timestamp: Temporal.Now.instant() // Nanosecond resolution+ };+}++// 2. Sort events chronologically+function sequenceEvents(events) {+ // Always use Temporal.Instant.compare for sorting instants+ return [...events].sort((a, b) => Temporal.Instant.compare(a.timestamp, b.timestamp));+}++// 3. Calculate delays between events+function analyzeTelemetry(sortedEvents) {+ for (let i = 1; i < sortedEvents.length; i++) {+ const prev = sortedEvents[i - 1];+ const curr = sortedEvents[i];++ // Calculate difference in nanoseconds+ const duration = curr.timestamp.since(prev.timestamp);+ const nsDiff = duration.total('nanoseconds');++ console.log(`Delay between Event ${prev.eventType} and Event ${curr.eventType}: ${nsDiff}ns`);+ }+}+```++## Strategic Implementation & Best Practices++- **DO** use `Temporal.Now.instant()` for server-side tracing or client-side telemetry where millisecond precision is insufficient (e.g., microsecond profiling).+- **DO NOT** use `Date.now()` if you require stable sorting of events that happen back-to-back.+- **DO NOT** use `Temporal.Instant` for wall-clock time display unless you pair it with a time zone (use `Temporal.ZonedDateTime` for localized display).+- **DO** verify that the environment supports `Temporal` before using it natively or providing a fallback.++## Fallback strategies++Temporal has limited availability.++For environments without native support, use a standards-compliant polyfill such as `@js-temporal/polyfill`. Load it conditionally to avoid bloating the payload for modern clients. Note that `@js-temporal/polyfill` does not automatically install a global `Temporal` object, so you must explicitly assign it if you need it globally.++```javascript+(async () => {+ // Check for native support+ if (typeof Temporal === 'undefined') {+ // Dynamically load polyfill using an ESM-compatible CDN+ const module = await import('https://esm.sh/@js-temporal/polyfill');+ // The polyfill does not auto-install globally, so we must assign it+ globalThis.Temporal = module.Temporal;+ }++ // Proceed with application logic+})();+```diff --git a/skills/modern-web/guides/user-experience/adapt-scrollbar-to-contrast-preferences.md b/skills/modern-web/guides/user-experience/adapt-scrollbar-to-contrast-preferences.mdnew file mode 100644index 0000000..faf0b0a--- /dev/null+++ b/skills/modern-web/guides/user-experience/adapt-scrollbar-to-contrast-preferences.md@@ -0,0 +1,61 @@+# Adapt scrollbar to high-contrast preferences++Users who enable high-contrast modes in their operating system or browser expect UI elements (like scrollbars) to be extremely legible, often relying on stark foreground-background separation rather than subtle grays or theme colors.++This guide provides optional instructions on how to use the `@media (prefers-contrast: more)` CSS media feature to enforce high-contrast scrollbar styling.++## Enhance Legibility++When customizing scrollbars with `scrollbar-color` or custom variables, you can provide an explicit override for high-contrast modes. This is especially helpful if your primary application theme uses low-contrast scrollbars for aesthetic reasons.++OPTIONAL: Use a `@media (prefers-contrast: more)` block to define dark, distinct colors for the thumb and track.++```css+/* Define default standard colors as variables */+.scroller {+ --scrollbar-thumb: #bbb;+ --scrollbar-track: #f1f1f1;++ scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);+ scrollbar-width: thin;+ scrollbar-gutter: stable;+}++/* OPTIONAL: Provide clear, high-contrast overrides */+@media (prefers-contrast: more) {+ .scroller {+ /* Use extremely distinct colors like solid black against white */+ --scrollbar-thumb: #000000;+ --scrollbar-track: #ffffff;+ }+}+```++IMPORTANT: Do NOT animate or transition `scrollbar-color`. A [WebKit bug](https://bugs.webkit.org/show_bug.cgi?id=311752) causes the scrollbar to flicker every time `scrollbar-color` changes.++## Fallbacks & Browser Support++Baseline status for scrollbar-color: Newly available. It's been Baseline since 2025-12-12.++If you are using legacy WebKit pseudo-elements to ensure custom colored scrollbars on older versions of Safari/Chrome, the variable assignments from the media query above will automatically cascade to the fallback.++OPTIONAL: If the user's Baseline target is "Baseline Widely Available" or earlier, you SHOULD ensure you provide the legacy fallback code block securely isolated behind `@supports not (scrollbar-color: auto)`.++```css+/* Legacy fallback for WebKit/Blink browsers */+@supports not (scrollbar-color: auto) {+ .scroller::-webkit-scrollbar {+ width: 12px;+ height: 12px;+ }+ .scroller::-webkit-scrollbar-thumb {+ /* Will inherit the high-contrast #000000 */+ background: var(--scrollbar-thumb);+ border: 3px solid var(--scrollbar-track);+ }+ .scroller::-webkit-scrollbar-track {+ /* Will inherit the high-contrast #ffffff */+ background: var(--scrollbar-track);+ }+}+```diff --git a/skills/modern-web/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.md b/skills/modern-web/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.mdnew file mode 100644index 0000000..c2eb8e4--- /dev/null+++ b/skills/modern-web/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.md@@ -0,0 +1,77 @@+# Adapt scrollbar to light/dark preferences++Users expect UI components, including scrollbars, to match the color scheme (light or dark mode) chosen in their operating system settings. The most essential step to achieving this is utilizing the `color-scheme` property. If you choose to apply explicit custom colors, you can use the `@media (prefers-color-scheme: dark)` CSS media feature to modify those colors dynamically.++## 1. System Default Adaptation++The simplest and most robust way to ensure the scrollbar adapts to the user's light/dark mode preference is to let the browser handle it via the `color-scheme` property. When a dark color scheme is enabled, the browser will automatically render its dark-variant scrollbar.++MANDATORY: Define `color-scheme` on the `:root` pseudo-class.++```css+:root {+ /* DO: Declare support for both light and dark systems */+ color-scheme: light dark;+}+```++## 2. Custom Color Adaptation++If you are using `scrollbar-color` or the non-standard `::-webkit-scrollbar` pseudo-elements to explicitly define custom scrollbar colors, you MUST ensure these colors are legible and appropriate in both light and dark modes.++MANDATORY: Use CSS custom properties (variables) to define your colors and update them within a `prefers-color-scheme` media query to avoid repetition.++```css+/* DO: Define light mode colors as variables */+.scroller {+ --scrollbar-thumb: #bbb;+ --scrollbar-track: #f1f1f1;++ /* DO: Apply standard property natively */+ scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);+ /* DO: Must define width to force macOS to apply the custom colors */+ scrollbar-width: thin;+ /* DO: Force the track background to be visible on macOS */+ scrollbar-gutter: stable;+}++/* DO: Override variables for dark mode */+@media (prefers-color-scheme: dark) {+ .scroller {+ --scrollbar-thumb: #555555;+ --scrollbar-track: #222222;+ }+}+```++IMPORTANT: Do NOT animate or transition `scrollbar-color`. A [WebKit bug](https://bugs.webkit.org/show_bug.cgi?id=311752) causes the scrollbar to flicker every time `scrollbar-color` changes.++## Fallbacks & Browser Support++Baseline status for scrollbar-color: Newly available. It's been Baseline since 2025-12-12.++MANDATORY: If the user's Baseline target is "Baseline Widely Available" or earlier, you SHOULD include the non-standard `::-webkit-scrollbar` pseudo-elements as fallbacks.+MANDATORY: To prevent conflicts between standard properties and legacy WebKit selectors in browsers that support both natively (like modern Chrome), you MUST wrap legacy WebKit fallbacks in an `@supports not (scrollbar-color: auto)` block.+MANDATORY: On macOS, `scrollbar-color` (standard) and `::-webkit-scrollbar` (legacy) properties are ignored by default because macOS uses native "overlay" scrollbars. You MUST pair custom colors with `scrollbar-width` (e.g., `thin` or `auto`) to force macOS to render them.+MANDATORY: Even with `scrollbar-width` applied, macOS overlay scrollbars render the track (gutter) as transparent by default. If your design requires a visible track background color on MacOS, you MUST apply `scrollbar-gutter: stable;` to the scrollable container, but note that it only appears after the user hovers over the scrollbar.++++```css+/* Legacy fallback for WebKit/Blink browsers */+@supports not (scrollbar-color: auto) {+ .scroller::-webkit-scrollbar {+ /* DO: Must define base size in WebKit for custom colors to be visual */+ width: 12px;+ height: 12px;+ }+ .scroller::-webkit-scrollbar-thumb {+ /* DO: Apply the thumb variable */+ background: var(--scrollbar-thumb);+ }+ .scroller::-webkit-scrollbar-track {+ /* DO: Apply the track variable */+ background: var(--scrollbar-track);+ }+}+```diff --git a/skills/modern-web/guides/user-experience/anchor-positioning-tab-underline.md b/skills/modern-web/guides/user-experience/anchor-positioning-tab-underline.mdnew file mode 100644index 0000000..71f9a6e--- /dev/null+++ b/skills/modern-web/guides/user-experience/anchor-positioning-tab-underline.md@@ -0,0 +1,81 @@+In a tab menu, you should provide visual hints to users about what page they are on. One option is by underlining the tab. With anchor positioning, you can create a smooth animation between the positions of the underline. This does not work when changing the active tab loads a new web page.++You can also use this effect to add an animated dot to indicate the active tab in a vertical tab bar.++Create the underline using a `::before` pseudo-element on the `<ul>` that contains the `<li>` elements. **Using a pseudo-element is the preferred approach as it keeps the DOM clean and avoids adding extra elements for purely decorative effects.**++```css+ul::before {+ /* Use a pseudo-element on the container to represent the animated indicator */+ content: '';+}+```++Make the active list item an anchor by adding the `anchor-name` property, which has a value that starts with `--`.++```css+li.active {+ /* Make a unique anchor-name for the active element. */+ anchor-name: --active;+}+```++Tether the underline to the active item anchor with a `position-anchor` that matches the `anchor-name` on the anchor, and making it `position: absolute`.++```css+ul::before {+ /* Tether the underline to the active element. */+ position: absolute;+ position-anchor: --active;+}+```++Position the underline relative to the anchor using the inset properties and `anchor()` functions.++```css+ul::before {+ /* DO NOT use position-area, which can not be transitioned. */+ /* Use calc() to offset the top slightly */+ inset-block-start: calc(anchor(bottom) + .1lh);+ inset-inline-start: anchor(left);+ inset-inline-end: anchor(right);+}+```++Add a height and other visual styles.++```css+ul::before {+ /* Apply your project's styles for the indicator */+ block-size: .25lh;+ background: red;+}+```++Finally, add a transition on the `inset` properties.++```css+ul::before {+ @media (prefers-reduced-motion: no-preference) {+ /* MANDATORY: The transition must be wrapped in a prefers-reduced-motion media query to respect user preferences. */+ transition: inset .2s;+ }+}+```++This is only a visual indicator, and must not be a replacement for setting the appropriate `aria-current="page"` or `aria-selected` aria values.++### Fallback strategies++Anchor positioning has limited availability.++If anchor positioning is not supported in the browser, use a `border-bottom` to add an underline. It will not be animated.++```css+ul li.active {+ @supports not (position-anchor: auto) {+ /* Choose a color appropriate to the app theme. */+ border-bottom: .25lh var(--primary) solid;+ }+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/animate-element-entry-exit.md b/skills/modern-web/guides/user-experience/animate-element-entry-exit.mdnew file mode 100644index 0000000..719972f--- /dev/null+++ b/skills/modern-web/guides/user-experience/animate-element-entry-exit.md@@ -0,0 +1,130 @@+In the past, CSS transitions could not animate elements when they were first added to the DOM or when their `display` property changed from `none`. The `@starting-style` at-rule and `transition-behavior: allow-discrete` provide a declarative way to create smooth entry and exit animations.++## Implementation++### 1. Animating `display: none` Toggles++To animate an element when toggling its visibility via an attribute (e.g., `hidden` with `display: none`):++1. **Define the visible state**: Set the final property values (e.g., `opacity: 1`) on the base class.+2. **Define the entry starting state**: Use `@starting-style` to specify the values to transition *from* when the element becomes visible.+3. **Enable discrete transitions**: Include `display` in the `transition` property and use `transition-behavior: allow-discrete`.+4. **Define the exit state**: Set the target values in the `hidden` attribute.++```css+.card {+ display: block;+ opacity: 1;+ translate: 0;+ /* MANDATORY: Use transition-behavior: allow-discrete for display transition */+ transition:+ display 0.4s,+ opacity 0.4s ease-out,+ translate 0.4s ease-out;+ transition-behavior: allow-discrete;+}++/* Entry animation: transition FROM these values when first rendered */+@starting-style {+ .card {+ opacity: 0;+ translate: 0 -20px;+ }+}++/* Exit animation: transition TO these values when hidden */+.card:where(.hidden, [hidden]) {+ display: none;+ opacity: 0;+ translate: 0 -20px;+}++/* Respect user preference for reduced motion */+@media (prefers-reduced-motion: reduce) {+ .card {+ /* Disable movement and shorten duration for a simple fade */+ translate: none;+ transition-duration: 0.1s;+ }++ @starting-style {+ .card {+ translate: none;+ }+ }++ .card:where(.hidden, [hidden]) {+ translate: none;+ }+}+```++### 2. Animating DOM Insertion and Removal++For elements added via `appendChild()` or removed via `remove()`:++- **Entry**: Use `@starting-style` as shown above. The browser will automatically detect the style change from "nothing" to the element's initial styles and trigger the transition from the `@starting-style` values.+- **Removal**: Since `element.remove()` is instantaneous and doesn't trigger a CSS transition on its own, you must trigger the exit transition first (e.g., by adding a class) and wait for it to finish before removing the node from the DOM.++```javascript+// Trigger exit transition+element.setAttribute('hidden', true);++// 2. Wait for all active transitions/animations to finish,+// with a failsafe timeout in case an animation never ends (e.g. for looping animations)+const animations = element.getAnimations();+if (animations.length > 0) {+ await Promise.race([+ // Promise.allSettled ensures we wait even if some animations fail+ Promise.allSettled(animations.map(a => a.finished)),+ new Promise(r => setTimeout(r, 2000))+ ]);+}++// 3. Finally remove the node from the DOM+element.remove();+```++## Constraints & Accessibility++- **MANDATORY**: Use `transition-behavior: allow-discrete` when transitioning `display`. Without it, the element will instantly disappear during exit.+- **DO NOT** use `allow-discrete` in the `transition` shorthand — it will make older browsers ignore the entire `transition` declaration. Except in use cases where that is desirable, use a separate `transition-behavior: allow-discrete` declaration.+- **MANDATORY**: Use `@starting-style` for entry animations. Browsers skip transitions on an element's first style update (initial render or `display: none` change) unless this is provided.+- **DO**: Include `overlay` in the `transition` list if animating top-layer elements like `<dialog>` or `popover` to ensure they stay in the top layer during the exit animation.+- **DO**: Respect user preferences for reduced motion using the `prefers-reduced-motion` media query.+- **DO NOT**: Rely on `@starting-style` for exit animations; it only defines the *starting* point for an entry transition. Exit animations are defined by the transition to the hidden state.++## Fallback strategies++Baseline status for @starting-style: Newly available. It's been Baseline since 2024-08-06.++For browsers that do not support these features, elements will toggle `display: none` instantly. You can detect support in JavaScript using `CSS.supports()` to conditionally apply manual animation logic.++```javascript+// Detect support for discrete transitions and starting-style+const supportsModernTransitions =+ window.CSS &&+ CSS.supports('transition-behavior', 'allow-discrete');++if (!supportsModernTransitions) {+ // Implement manual JS-based fallback for entry/exit+}+```++### Manual Entry Animation (JS Fallback)++```javascript+// To show:+el.style.display = '';+requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ el.classList.remove('hidden');+ });+});++// To hide:+el.setAttribute('hidden', true);+el.addEventListener('transitionend', () => {+ if (el.classList.contains('hidden')) el.style.display = 'none';+}, { once: true });+```diff --git a/skills/modern-web/guides/user-experience/animate-to-intrinsic-sizes.md b/skills/modern-web/guides/user-experience/animate-to-intrinsic-sizes.mdnew file mode 100644index 0000000..243fc05--- /dev/null+++ b/skills/modern-web/guides/user-experience/animate-to-intrinsic-sizes.md@@ -0,0 +1,97 @@+# Animate to Intrinsic Sizes++Animating elements to dynamic sizes like `block-size: auto` or `inline-size: max-content` has historically required JavaScript or fragile "max-height" hacks. The `interpolate-size` property and `calc-size()` function allow the browser to natively interpolate between fixed lengths and intrinsic sizing keywords.++## Implementation steps++1. **Opt-in to keyword interpolation**: Apply `interpolate-size: allow-keywords` to a parent element (typically `:root`) to enable transitions for properties using intrinsic keywords.+2. **Define the transition**: Set a `transition` for the sizing property (e.g., `block-size`, `inline-size`) on the target element.+3. **Use intrinsic keywords**: Change the sizing property to a supported intrinsic keyword—`auto`, `min-content`, `max-content`, `fit-content`, or (for flex-basis) `content`—during an interaction (e.g., `:hover` or a state class).+4. **Perform calculations (Optional)**: Use `calc-size()` if you need to perform math on an intrinsic size (e.g., `auto + 2rem`). `calc-size()` also supports the `any` keyword for basis-agnostic calculations.++## Example: Generic Expansion Pattern++You can apply this pattern to any container (like a "Show More" section or a navigation menu) to transition between a restricted height and the element's natural size.++```css+/* Opt-in globally for all children */+:root {+ /* MANDATORY: Transitions to intrinsic keywords are disabled by default for compatibility */+ interpolate-size: allow-keywords;+}++.expandable-container {+ /* 1. Define a fixed initial size (or 0) and hide overflow */+ block-size: 100px;+ overflow: hidden;++ /* 2. Transition the sizing property */+ transition: block-size 0.4s ease-out;+}++.expandable-container.is-expanded {+ /* 3. Smoothly animate to the intrinsic natural height */+ block-size: auto;+}+```++## Example: Calculated Intrinsic Inline-Size++```css+.badge {+ inline-size: 40px;+ overflow: hidden;+ white-space: nowrap;+ transition: inline-size 0.3s ease;+}++.badge:hover {+ /* calc-size(basis, calculation) */+ /* 'size' refers to the evaluated basis (max-content in this case) */+ inline-size: calc-size(max-content, size + 20px);+}+```++## Example: Transition from Intrinsic to Fixed++You can also animate in the opposite direction—starting from a natural size and collapsing to a specific length. This is useful for "dismissible" components.++```css+.collapsible-alert {+ /* 1. Start with the natural content height */+ block-size: auto;+ overflow: hidden;+ transition: block-size 0.5s ease-in-out, opacity 0.5s ease;+}++.collapsible-alert.is-dismissed {+ /* 2. Smoothly collapse to zero */+ block-size: 0;+ opacity: 0;+ pointer-events: none;+}+```++## Key constraints++* **Keyword-to-Keyword Restriction**: You cannot animate between two different keywords directly (e.g., from `min-content` to `max-content`). One end of the transition must be a fixed length or percentage (e.g., `0` to `auto`).+* **Calc-size Syntax**: Inside `calc-size()`, you cannot mix different intrinsic keywords in the same expression. The first argument (the basis) defines what `size` represents.+* **Opt-in Requirement**: Transitions to intrinsic keywords are disabled by default (`numeric-only`) to maintain backward compatibility. You must apply `interpolate-size: allow-keywords` to the element or an ancestor. `calc-size()` acts as a per-property override, automatically enabling interpolation whenever it is used.++## Fallback strategies++interpolate-size has limited availability.+calc-size() has limited availability.++`interpolate-size` and `calc-size()` are progressive enhancements. Browsers that do not support them will perform an instant jump to the target size.++* **Graceful Degradation**: For simple `block-size: auto` transitions, standard browsers will simply toggle the size instantly, which is functional but less polished.+* **Manual keyword fallbacks**: When using `calc-size()`, always provide a standard keyword fallback for older browsers, as they will discard the entire `calc-size()` declaration.++```css+.card {+ block-size: auto; /* Fallback for older browsers */+ block-size: calc-size(auto, size); /* Modern browsers use this */+ transition: block-size 0.3s ease;+}+```diff --git a/skills/modern-web/guides/user-experience/browser-ui-color-theme.md b/skills/modern-web/guides/user-experience/browser-ui-color-theme.mdnew file mode 100644index 0000000..1992041--- /dev/null+++ b/skills/modern-web/guides/user-experience/browser-ui-color-theme.md@@ -0,0 +1,50 @@+# Browser UI color theme++The `color-scheme` property indicates which color schemes (such as light or dark) your page supports. This informs the browser that it can automatically theme native UI elements—like scrollbars, form controls, and the default canvas background—to match your site's design and help minimize white flashes during initial loading.++## Implementation++### 1. Declare supported schemes in HTML+MANDATORY: To help prevent a "flash of un-themed content" (FOUC), place a `<meta>` tag in your `<head>` to ensure the browser knows which themes you support before it even starts rendering. While this `<meta>` tag helps to avoid FOUC by setting the initial canvas color early, it may not completely eliminate flashes in all browsers or loading conditions.++```html+<!-- MANDATORY: Declare support for both light and dark themes -->+<meta name="color-scheme" content="light dark">+```++### 2. Apply theme to CSS :root or html+MANDATORY: Apply the `color-scheme` property to the `html` element or the `:root` pseudo-class. Browsers specifically look to the root element to determine the theme for the entire viewport—including the root scrollbars and the initial "canvas" background. If applied only to the `body`, these global UI surfaces may remain in light mode because the `body` does not control the window's rendering context.++```css+/* MANDATORY: Apply to :root or html for viewport-wide theming */+:root {+ /* MANDATORY: Automatically adapt native UI to user system preferences */+ color-scheme: light dark;+}+```++### 3. Component-Specific Overrides+You can override the global theme for specific elements. This is useful for "dark mode" sections within a light-themed site (e.g., a dark sidebar or a code editor).++```css+.dark-sidebar {+ /* Force this element and its children to use dark themed UI */+ color-scheme: dark;+ background-color: #111;+ color: #eee;+}+```++## Best Practices+- **System Colors**: Use system color keywords like `Canvas` (background) and `CanvasText` (text) for your custom components when you want them to match the browser's native themed surfaces exactly. This is ideal for ensuring consistency between your content and the browser's UI (like scrollbars) while automatically respecting OS-level accessibility features like High Contrast mode.+- **Respect User Preference**: **MANDATORY**: Avoid forcing a single theme on the overall page. While specific components (like a code editor) may benefit from a fixed theme, the main application should respect the user's system preference and ideally provide a manual toggle to allow users to choose between light, dark, or system-default modes.+- **Forcing a Theme**: Use a single value like `color-scheme: dark` or `color-scheme: light` ONLY for specific sections of your site (like a code editor or a video player) that must remain in one theme. Avoid applying this to the root element unless it's the result of an explicit user selection via a theme toggle.+- **Opting out of Auto-Dark Mode**: Use `color-scheme: only light` to prevent browsers (particularly on mobile) from automatically inverting your colors if you haven't yet implemented a dedicated dark theme.++## Fallback strategies++Baseline status for color-scheme: Widely available. It's been Baseline since 2022-02-03.++- **Progressive Enhancement**: Browsers that do not support `color-scheme` will simply ignore the property and use their default light-mode UI.+- **Manual Dark Mode Styling**: For older browsers, continue to use `prefers-color-scheme` media queries to provide custom styles for your own components.+- **Custom Scrollbars**: If you need consistent scrollbar styling across all modern browsers, use the `scrollbar-color` property. For older WebKit-based browsers that do not support the standard property, continue to use the non-standard `::-webkit-scrollbar` pseudo-elements.diff --git a/skills/modern-web/guides/user-experience/calculate-event-differentials.md b/skills/modern-web/guides/user-experience/calculate-event-differentials.mdnew file mode 100644index 0000000..9428abb--- /dev/null+++ b/skills/modern-web/guides/user-experience/calculate-event-differentials.md@@ -0,0 +1,84 @@+# Calculating Event Differentials with Temporal++Calculating the time elapsed between events (such as trial expirations, subscription durations, or prorated costs) has historically been difficult with the legacy `Date` object due to complexities with time zones, daylight saving time (DST), and inconsistent parsing.++The `Temporal` API provides a modern, robust solution for date and time arithmetic. Specifically, `Temporal.ZonedDateTime` and `Temporal.Duration` enable exact, DST-safe calculations of time differences.++## How to Implement++To calculate differentials between two events:++1. **Obtain ZonedDateTime objects**: Convert your inputs (dates and times) into `Temporal.ZonedDateTime` objects. This ensures calculations are time-zone aware.+2. **Calculate active time with `.since()`**: Use `currentZonedDateTime.since(startZonedDateTime)` to find the time elapsed since a start event.+3. **Calculate remaining time with `.until()`**: Use `currentZonedDateTime.until(endZonedDateTime)` to find the time remaining until a future event.+4. **Control precision with options**: Use `largestUnit`, `smallestUnit`, and `roundingMode` to control how the resulting duration is balanced and rounded.++### Example: Trial Expiration Calculation++```javascript+// 1. Get current time point in the system time zone+const now = Temporal.Now.zonedDateTimeISO();+const tz = now.timeZoneId;++// 2. Parse inputs (assuming ISO strings from form inputs)+const startDateStr = "2025-01-01";+const startTimeStr = "12:00:00";+const endDateStr = "2025-01-31";+const endTimeStr = "12:00:00";++const startDate = Temporal.PlainDate.from(startDateStr);+const startTime = Temporal.PlainTime.from(startTimeStr);+const start = startDate.toPlainDateTime(startTime).toZonedDateTime(tz);++const endDate = Temporal.PlainDate.from(endDateStr);+const endTime = Temporal.PlainTime.from(endTimeStr);+const end = endDate.toPlainDateTime(endTime).toZonedDateTime(tz);++// 3. Calculate difference using .since() and .until()+// By default, units larger than hours might not wrap automatically.+// Use largestUnit to ensure differences are expressed in larger units if applicable.+const timeActive = now.since(start, { largestUnit: 'year' });+const timeRemaining = now.until(end, { largestUnit: 'year' });++console.log(`Active: ${timeActive.days} days, ${timeActive.hours} hours`);+console.log(`Remaining: ${timeRemaining.days} days, ${timeRemaining.hours} hours`);++// 4. Compare dates+const isExpired = Temporal.ZonedDateTime.compare(now, end) > 0;+if (isExpired) {+ console.log("Subscription is expired.");+}+```++## Strategic Implementation & Best Practices++- **DO** use `Temporal.ZonedDateTime` for calculations involving real-world events that occur in specific time zones (like subscription renewals or event scheduling).+- **DO** use `largestUnit` to specify the largest unit you want in the result (e.g., `'year'` or `'month'`). If you omit it, it defaults to `'auto'` which might not always sum up to years/months as expected for human-readable durations.+- **DO** use `.since()` when calculating time elapsed *since* a past event (e.g., `now.since(start)`), and `.until()` for time remaining *until* a future event (e.g., `now.until(end)`).+- **DO NOT** modify instances directly; `Temporal` objects are **immutable**. Operations like `add()`, `subtract()`, or `with()` return a *new* instance.+- **DO** use `Temporal.ZonedDateTime.compare` to check if one time point is after another. It returns `1` if the first is after the second, `-1` if before, and `0` if equal.++## Fallback Strategy++Temporal has limited availability.++For browsers that do not yet support the native `Temporal` API, use feature detection and a polyfill. The standard reference polyfill is `@js-temporal/polyfill`.++```javascript+// Check if Temporal is supported natively+(async () => {+ if (typeof Temporal === 'undefined') {+ // Load the polyfill conditionally+ const module = await import("https://esm.sh/@js-temporal/polyfill");+ globalThis.Temporal = module.Temporal;+ // Extend Date.prototype if needed+ Date.prototype.toTemporalInstant = module.toTemporalInstant;+ initializeApp();+ }+})();++function initializeApp() {+ const now = Temporal.Now.zonedDateTimeISO();+ console.log(now.toString());+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/calculate-with-intrinsic-sizes.md b/skills/modern-web/guides/user-experience/calculate-with-intrinsic-sizes.mdnew file mode 100644index 0000000..72a47f9--- /dev/null+++ b/skills/modern-web/guides/user-experience/calculate-with-intrinsic-sizes.md@@ -0,0 +1,192 @@+`calc-size()` is a CSS function for performing mathematical operations on intrinsic sizing keywords like `auto`, `min-content`, and `fit-content`. **MANDATORY**: Use `calc-size()` only when you need to modify an intrinsic size with a calculation or constraint; for simple keyword-based animations (e.g., `0` to `auto`), you must use `interpolate-size: allow-keywords`.++## Implementation Steps++1. **Identify the Intrinsic Basis**: Determine which intrinsic keyword (`auto`, `min-content`, etc.) should form the base of your calculation.+2. **Define Constraints**: Use CSS math functions like `clamp()`, `min()`, or `max()` within the second argument to enforce design constraints on the intrinsic size.+3. **MANDATORY: Provide a Fallback**: Always declare a standard sizing keyword or length immediately before the property using `calc-size()` to ensure the layout remains functional in unsupported browsers.+4. **Apply Logical Properties**: Default to using logical properties like `inline-size` or `block-size` to ensure the calculations respect the document's writing mode.+5. **Optional: Progressive Enhancement**: Wrap complex layout logic or animations in a `@supports (inline-size: calc-size(auto, size + 0px))` block to deliver advanced features only to capable browsers.++## Basic Syntax++```css+/* calc-size(<calc-size-basis>, <calc-sum>) — mathematical operations on intrinsic sizing keywords */+.element {+ /* MANDATORY: Always provide a fallback for browsers that do not support calc-size() */+ inline-size: min-content;++ /* DO: Use calc-size to modify an intrinsic basis with a calculation or function */+ inline-size: calc-size(min-content, size + 2rem);+}+```++### Valid Basis Arguments (`<calc-size-basis>`)+The first argument defines the "base" size for the calculation.++**Standard Keywords:**+- `auto`: The default sizing for the element.+- `min-content`: The smallest size the element can take without overflowing.+- `max-content`: The size the element takes to fit all content on one line.+- `fit-content`: Equivalent to `clamp(min-content, auto, max-content)`.+- `content`: Only valid when `calc-size()` is used within the `flex-basis` property.++**Special Arguments:**+- `any`: A generic basis used when the specific intrinsic type is unknown or when nesting calculations.+- Nested `calc-size()`: Allows for multi-step or conditional calculations.+- `<calc-sum>`: A specific length, percentage, or mathematical expression (e.g., `100px` or `20%`). When a fixed value is used as the basis, the **`size` keyword is still available** (but only within the second argument) and represents the resolved value of that basis.++**MANDATORY**: The `size` keyword is **not valid** within the first argument (`<calc-size-basis>`) itself. It is a local variable that only exists to refer back to the basis from within the second argument (`<calc-sum>`).++### Valid Calculation Arguments (`<calc-sum>`)+The second argument is the mathematical expression.+- It typically uses the `size` keyword to refer to the value of the basis.+- While the `size` keyword is technically optional, omitting it means the calculation will resolve to a fixed value, ignoring the basis entirely.+- It can include standard math operators (`+`, `-`, `*`, `/`).+- It can include CSS math functions like `clamp()`, `min()`, `max()`, and `round()`.+- **MANDATORY**: `calc-size()` only allows a **single** intrinsic size value (the basis) in each calculation. You cannot mix intrinsic sizing keywords in the same `calc-size()` call.++## Use Cases++### Animating to and from Intrinsic Sizes+By default, browsers cannot interpolate between a length (e.g., `0px`) and an intrinsic keyword (e.g., `auto`). Wrapping the keyword in `calc-size()` makes it an interpolatable value.++#### Choosing the Right Tool for Animations+- **MANDATORY: Use `interpolate-size: allow-keywords`**: For simple animations to or from intrinsic sizes (e.g., `height: 0` to `height: auto`) without any mathematical modifications. This is the required approach for simple keyword interpolation and should ideally be applied globally via `:root`.++ ```css+ :root {+ /* Best practice: Enable keyword interpolation globally */+ interpolate-size: allow-keywords;+ }++ .item {+ height: 0;+ transition: height 0.3s ease;+ }++ .item.open {+ /* Simple interpolation from 0 to auto now works without calc-size() */+ height: auto;+ }+ ```++- **Use `calc-size()`**: ONLY when you need to perform mathematical calculations on an intrinsic size during a transition (e.g., adding padding or clamping the size).++```css+.accordion-content {+ display: block;+ overflow: hidden;+ /* MANDATORY: Fallback value for closed state */+ block-size: 0;+ transition: block-size 0.3s ease-out;+}++.accordion-content.open {+ /* MANDATORY: Fallback value for open state */+ block-size: auto;++ /*+ DO: Use calc-size(auto, ...) to enable animation from 0 to the element's+ intrinsic size while doing a calculation (in this case, adding a space of 2rem).+ */+ block-size: calc-size(auto, size + 2rem);+}+```++**MANDATORY**: Interpolation between two intrinsic sizing keywords is not possible directly. One end of the transition must be a length or a percentage.++#### Respecting User Motion Preferences+Animations that change the size of large layout areas can be particularly disruptive for users with vestibular disorders. **MANDATORY**: Always respect user motion preferences by using the `prefers-reduced-motion` media query to simplify or minimize non-essential animations. Common strategies include disabling motion entirely, reducing duration, or replacing layout shifts with subtle opacity transitions.++```css+.accordion-content {+ opacity: 0;+ transition: block-size 0.3s ease, opacity 0.3s ease;+}++.accordion-content.open {+ opacity: 1;+}++@media (prefers-reduced-motion: reduce) {+ .accordion-content {+ /*+ EXAMPLE: Replacing disruptive layout animations with a subtle fade-in.+ Setting the block-size instantly and transitioning opacity+ provides a clear state change without large-scale motion.+ */+ transition: opacity 1.5s ease;+ }++ .accordion-content.open {+ /* Jump the size instantly */+ block-size: auto;+ }+}+```+++### Applying Constraints to Intrinsic Sizes+You can use `calc-size()` with any CSS math function—such as `min()`, `max()`, `clamp()`, or `round()`—to ensure an element's intrinsic size remains within design boundaries.++```css+.dynamic-container {+ /* MANDATORY: Always provide a fallback for browsers that do not support calc-size() */+ inline-size: fit-content;++ /*+ DO: Establish a dynamic size based on content, while:+ 1. Enforcing boundaries using CSS math functions (min, clamp, etc.)+ 2. Modifying the intrinsic size with fixed or relative offsets+ */+ inline-size: calc-size(fit-content, min(size + var(--extra-space), var(--max-allowed)));+}+```++## Critical Considerations++- **Percentage Pitfalls**: Percentages inside the `<calc-sum>` are resolved against the **container's size**, not the `size` keyword. For example, `calc-size(auto, size + 10%)` adds 10% of the *parent's* width to the element's `auto` width, which may lead to unexpected results or overflows.+- **Calculations requirement**: **MANDATORY**: Use `interpolate-size: allow-keywords` instead of `calc-size()` for simple animations (e.g., `0` to `auto`). `calc-size()` should only be used when the layout requires dynamic mathematical adjustments to the intrinsic base.+- **Performance Note**: Animating box model properties like `inline-size` or `block-size` triggers layout recalculations, which can be expensive. Use `calc-size()` animations primarily for layout-critical elements where non-layout alternatives are insufficient.++## Fallback strategies++calc-size() has limited availability.+interpolate-size has limited availability.++`calc-size()` and `interpolate-size` are **progressive enhancements**. In browsers that do not support them, the properties will be ignored and the layout will remain functional, though animations to intrinsic keywords will jump instead of transitioning. Always provide a standard keyword or length as a fallback.++```css+.element {+ /* Fallback for browsers that don't support calc-size() */+ inline-size: fit-content;+ /* Modern browsers will override the fallback */+ inline-size: calc-size(fit-content, size + 2rem);+}+```++### Animation and Transition Fallbacks+In browsers without support for `calc-size()` or `interpolate-size`, transitions involving intrinsic sizing keywords will fail to interpolate.++- **Graceful Degradation**: The default fallback is an "instant jump" between states (e.g., from `0` to `auto`). This is often acceptable as the layout remains functional.+- **Enhanced Experience**: Use `@supports` to apply complex layout logic or additional styling that only makes sense when smooth intrinsic animations are possible.+- **Avoid JS-based measurements**: While you could use JavaScript to measure elements and manually animate their dimensions, this is often unnecessary and can lead to layout thrashing. Relying on the native "instant jump" is the recommended fallback for modern web applications.++For animations, the fallback experience will be an instant jump to the final size. To detect support in CSS or JavaScript:++```css+/* CSS Feature Detection */+@supports (inline-size: calc-size(auto, size + 0px)) {+ .element {+ /* Apply advanced logic only when supported */+ }+}+```++```javascript+/* JavaScript Feature Detection */+if (CSS.supports('inline-size', 'calc-size(auto, size + 0px)')) {+ // Apply advanced sizing or animations+}+```diff --git a/skills/modern-web/guides/user-experience/capture-location-agnostic-data.md b/skills/modern-web/guides/user-experience/capture-location-agnostic-data.mdnew file mode 100644index 0000000..ef1863f--- /dev/null+++ b/skills/modern-web/guides/user-experience/capture-location-agnostic-data.md@@ -0,0 +1,64 @@+# Capturing Location-Agnostic Data with Temporal++Recording chronological data that should remain identical regardless of the viewer's location (such as birthdates, recurring alarms, or national holidays) has historically been error-prone with the legacy `Date` object. Because `Date` objects always represent a specific instant in time and are tied to a time zone, saving a date like "1990-01-01" can result in users in different time zones seeing "1989-12-31" due to offset shifts.++The `Temporal` API introduces "Plain" types—such as `Temporal.PlainDate` and `Temporal.PlainTime`—which have no concept of a time zone. These types represent calendar dates and wall-clock times exactly as you would read them off a calendar or a clock, making them ideal for location-agnostic data.++## How to Implement++To capture and display location-agnostic data:++1. **Use `Temporal.PlainDate` for dates**: For data like birthdates or holidays, use `Temporal.PlainDate.from()` to create an instance from an ISO 8601 string or an object.+2. **Use `Temporal.PlainTime` for times**: For data like a daily alarm or a preferred lunch time, use `Temporal.PlainTime.from()`.+3. **Display without conversion**: Since these objects are time-zone unaware, they will display the same values regardless of the user's local time zone.++### Example: Capturing a Birthdate++```javascript+// 1. Parse a date string from an input (e.g., "1990-01-01")+const birthdateStr = "1990-01-01";+const plainDate = Temporal.PlainDate.from(birthdateStr);++// 2. Display the date+// This will output "01/01/1990" (or equivalent) in any time zone+console.log(plainDate.toLocaleString('en-GB'));++// 3. Compare with standard Date (which might drift)+const dateObj = new Date("1990-01-01T00:00:00Z");+// In a UTC-5 time zone, this might print "31/12/1989"+console.log(new Intl.DateTimeFormat('en-GB', { timeZone: 'America/New_York' }).format(dateObj));+```++## Strategic Implementation & Best Practices++- **DO** use `Temporal.PlainDate` for "calendar dates" like birthdates, anniversaries, and holidays where the specific time of day or time zone is irrelevant.+- **DO** use `Temporal.PlainTime` for "wall-clock times" like a daily reminder at 9:00 AM, where the time should be 9:00 AM in whatever time zone the user happens to be in.+- **DO NOT** use Plain types if you need to represent a specific moment in physical time (an "instant"). Use `Temporal.Instant` or `Temporal.ZonedDateTime` for logs, event timestamps, or anything requiring time zone awareness.+- **DO** remember that `Temporal` objects are **immutable**. Methods like `add()` or `with()` return a new instance rather than modifying the original.++## Fallback Strategy++Temporal has limited availability.++For browsers that do not yet support the native `Temporal` API, you should use feature detection and load a polyfill. The standard reference polyfill is `@js-temporal/polyfill`.++Note that the polyfill does not automatically assign the `Temporal` object to the global scope to avoid conflicts. You must manually assign it if your code relies on the global `Temporal` object.++```javascript+// Check if Temporal is supported natively+(async () => {+ if (typeof Temporal === 'undefined') {+ // Load the polyfill conditionally+ const module = await import("https://esm.sh/@js-temporal/polyfill");+ globalThis.Temporal = module.Temporal;+ // Extend Date.prototype if needed+ Date.prototype.toTemporalInstant = module.toTemporalInstant;+ initializeApp();+ }+})();++function initializeApp() {+ const plainDate = Temporal.PlainDate.from("1990-01-01");+ console.log("App initialized with PlainDate:", plainDate.toString());+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/carousel-slide-effects.md b/skills/modern-web/guides/user-experience/carousel-slide-effects.mdnew file mode 100644index 0000000..8181e1c--- /dev/null+++ b/skills/modern-web/guides/user-experience/carousel-slide-effects.md@@ -0,0 +1,185 @@+# Build Carousel Slide Effects++Carousel slide effects are a great way to add visual interest to a carousel. As the user scrolls through the slides, each slide can animate as it enters, centers, and exits the scrollport. For example, the slides can fade in and out, rotate, or scale in size. This creates a dynamic and engaging user experience. Unlike simple entry/exit animations, this effect uses a single, continuous animation to control the slide's appearance across the entire scrollport.++## How to implement++Here’s how to create carousel slide effects:++1. **Create a scroller:** This element will act as the container for your carousel slides. In this example it uses `overflow-x: scroll` to allow horizontal scrolling.++ ```html+ <ul class="scroller">+ <li class="entry">1</li>+ <li class="entry">2</li>+ <li class="entry">3</li>+ …+ </ul>+ ```++ ```css+ .scroller {+ overflow-x: scroll;+ }+ ```++2. **Define the animation:** Create a CSS animation that defines the different states of your slides as they traverse the scrollport. You can define keyframes for any part of the animation. For example, you can define a state for when the slides are in the center of the scrollport by including a `50%` keyframe. In this example, the `scale` property makes the slides grow as they approach the center and shrink as they move away.++ ```css+ @keyframes animate {+ 0% {+ scale: 0.5;+ }+ 50% {+ scale: 1;+ }+ 100% {+ scale: 0.5;+ }+ }+ ```++3. **Apply the animation and `view-timeline`:** Attach the animation to the carousel slides and link it to a `view-timeline` that tracks the element as it scrolls through the container.++ ```css+ .scroller > * {+ animation: animate auto linear both;+ animation-timeline: view(inline);+ }+ ```++ By default, `view()` tracks the element on the `block` axis. If you need to track it on the `inline` axis, you can use `view(inline)`.++## Example code++This code animates the carousel items of a horizontal scroller on scroll using an **anonymous view-timeline**:++```css+@keyframes animate {+ 0% {+ scale: 0.5;+ }++ 50% {+ scale: 1;+ }++ 100% {+ scale: 0.5;+ }+}++.scroller > * {+ /* Applies the animation using an `auto` duration */+ animation: animate auto linear both;+ /* Sets the animation timeline to use an anonymous view progress timeline, tracking the element's progress through the scroller on the inline axis */+ animation-timeline: view(inline);+}+```++This code animates the carousel items of a horizontal scroller on scroll using a **named view-timeline**:++```css+@keyframes animate {+ 0% {+ scale: 0.5;+ }++ 50% {+ scale: 1;+ }++ 100% {+ scale: 0.5;+ }+}++/* This creates a named view-timeline on each carousel item. The timeline is used to drive the animation that is applied on the same element. */+.scroller > * {+ /* Applies the animation using an `auto` duration */+ animation: animate auto linear both;+ /* Defines a named view progress timeline, tracking the element's progress through the scroller on the inline axis */+ view-timeline: --item inline;+ /* Sets the animation timeline to use the named view progress timeline defined above */+ animation-timeline: --item;+}+```++## Best Practices++When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:++- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: view()) and (animation-range: entry))` to check for support and provide a fallback for browsers that don't support it.+ - The `(animation-range: entry)` check **MUST** be included here, to filter out browsers with only partial support.+ - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.+ - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.+- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.+- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.+- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.++Prefer a named `view-timeline` when multiple DOM elements need to animate based on the same timeline, or when you need to animate children of the element that has the `view-timeline` defined on it. If the element that you animate is also the element that defines the `view-timeline`, you can use an anonymous view-timeline using `view()`.++When using the `view()` function to create a scroll-driven animation:++- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view(block)` or `view(inline)`.++When using the `view-timeline` property to create a scroll-driven animation:++- **DO** use a CSS `<dashed-ident>` for the name (e.g. `view-timeline: --my-custom-name`)+- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view-timeline-axis`.+- **DO** make sure the scope of the lookup works: When the element that is declaring the `view-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `view-timeline`’s name by using `timeline-scope` on a shared ancestor.++## Browser support and fallback strategies++Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.++For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).++In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.++Note that not every effect can be recreated using the fallbacks approach.++For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses the Web Animations API (`Element.animate()`) to create a paused animation for each item in the carousel. It then listens to the `scroll` event on the scroller and updates the `currentTime` of each animation based on the item's scroll progress within the scroller.++```js+// Fallback for browsers that don't support scroll-driven animations+if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {+ const scroller = document.querySelector('.scroller');+ const entries = document.querySelectorAll('.entry');++ // Create a map to store animations+ const animations = new Map();++ entries.forEach(entry => {+ const animation = entry.animate(+ {+ scale: ['0.5', '1', '0.5']+ },+ {+ duration: 1, // We'll control the time ourselves+ fill: 'both'+ }+ );+ animation.pause();+ animations.set(entry, animation);+ });++ // Update animations on scroll+ const tick = () => {+ const scrollerRect = scroller.getBoundingClientRect();++ entries.forEach(entry => {+ const animation = animations.get(entry);+ if (!animation) return;++ const entryRect = entry.getBoundingClientRect();+ const progress = (entryRect.left + entryRect.width / 2 - scrollerRect.left) / scrollerRect.width;++ animation.currentTime = progress;+ });+ };++ scroller.addEventListener('scroll', tick);+ tick();+}+```diff --git a/skills/modern-web/guides/user-experience/child-state-based-styling.md b/skills/modern-web/guides/user-experience/child-state-based-styling.mdnew file mode 100644index 0000000..abd9a4a--- /dev/null+++ b/skills/modern-web/guides/user-experience/child-state-based-styling.md@@ -0,0 +1,100 @@+Historically, CSS selectors could only traverse downwards—you could style a child based on its parent, but not a parent based on its child. The `:has()` pseudo-class changes this, allowing you to conditionally style a container element depending on the presence or state of its descendants.++By combining `:has()` with state pseudo-classes (like `:checked`, `:focus`, `:valid`, `:invalid`, or `:not()`), you can build complex, interactive UI components entirely in CSS, without needing JavaScript to toggle "modifier" classes (like `.is-active` or `.has-error`) on parent elements.++This is particularly useful for components that need to respond to internal interactions, such as a localized theme toggle reacting to a checkbox (`:checked`), a form group highlighting an error (`:invalid`), or a card elevating when a child link is focused (`:focus-within`).++### Implementing state-based container styling++**MANDATORY**: You must use the `:has()` selector on the container element to detect the specific state (e.g., `:checked`, `:focus`, `:invalid`) of its interactive child element.++To build a component that changes its styling based on a child's state:++1. **Define the default styling**: Set CSS variables on the container to define its base state.+2. **Apply state-based overrides**: Target the container with `:has([child-selector]:[state])` and redefine the CSS variables for the active or alternate state.++*Example: A component that changes theme based on a child toggle.*++```css+/* 1. Define the default state on the component container */+.theme-card {+ /* Using custom properties makes state-switching cleaner */+ --card-bg: #ffffff;+ --card-text: #333333;+ --card-border: #cccccc;++ background-color: var(--card-bg);+ color: var(--card-text);+ border: 1px solid var(--card-border);++ /* Use a transition for smooth state changes */+ transition: background-color 0.3s, color 0.3s;+}++/* 2. Apply styles when the child enters the specific state */+/* MANDATORY: Target the container and use :has() to check the descendant's state */+.theme-card:has(.theme-toggle:checked) {+ /* Override the properties for the active or alternate state */+ --card-bg: #222222;+ --card-text: #f0f0f0;+ --card-border: #555555;+}+/* You can also combine :has() and :not() to target specific negative states */+/* This selects a card that DOES NOT have a toggle in the checked state */+.theme-card:not(:has(.theme-toggle:checked)) {+ /* Optional: Explicit styles for the unchecked state if needed */+}+```++```html+<!-- The container element that receives the styling -->+<div class="theme-card">+ <!-- The child element whose state controls the parent -->+ <label>+ <input type="checkbox" class="theme-toggle">+ Enable Dark Mode+ </label>++ <h2>Card Title</h2>+ <p>The style of this entire card is controlled by the checkbox above.</p>+</div>+```++**Performance tip**: When using `:has()`, scope the selector to the most specific container possible (like `.theme-card`). Avoid anchoring it to very high-level elements like `body:has(...)` if the styling changes are localized, as broad `:has()` queries can trigger more layout recalculations.++### Fallback strategies++Baseline status for :has(): Newly available. It's been Baseline since 2023-12-19.++If the state-based styling is critical to the user experience or page layout, you must provide a fallback for browsers that do not support the `:has()` selector. For purely decorative effects, `:has()` can be used as a progressive enhancement without a fallback.++**MANDATORY**: When implementing a fallback for critical features, you must use `@supports not selector(:has(*))` in your CSS to define a traditional class-based fallback. If the critical state change relies on user interaction, you must also use a small inline script with `CSS.supports()` to toggle that class based on the equivalent JavaScript event (e.g., `change`, `focus`, `blur`) representing the state change.++```css+/* Fallback CSS for older browsers */+/* We check if the browser DOES NOT support the :has() selector */+@supports not selector(:has(*)) {+ /* Define a traditional modifier class that applies the exact same overrides */+ .theme-card.is-active {+ --card-bg: #222222;+ --card-text: #f0f0f0;+ --card-border: #555555;+ }+}+```++```javascript+/* Fallback JavaScript for older browsers */+/* Check for support before running the script to avoid unnecessary work in modern browsers */+if (!CSS.supports('selector(:has(*))')) {+ const toggle = document.querySelector('.theme-toggle');+ const card = document.querySelector('.theme-card');++ if (toggle && card) {+ // Manually toggle the fallback class when the input state changes+ toggle.addEventListener('change', (e) => {+ card.classList.toggle('is-active', e.target.checked);+ });+ }+}+```diff --git a/skills/modern-web/guides/user-experience/component-specific-light-dark-theme.md b/skills/modern-web/guides/user-experience/component-specific-light-dark-theme.mdnew file mode 100644index 0000000..7d83f50--- /dev/null+++ b/skills/modern-web/guides/user-experience/component-specific-light-dark-theme.md@@ -0,0 +1,110 @@+# Component-Specific Light/Dark Themes++The `light-dark()` function allows you to define two colors for a single property, which the browser automatically switches based on the current `color-scheme`. By scoping both the `light-dark()` variables and the `color-scheme` property to a specific component, you can create UI elements that can be independently forced into light or dark mode, regardless of the user's global system preference.++## Implementation steps++1. **MANDATORY: Enable `color-scheme` support.** The `light-dark()` function only resolves if the element (or an ancestor) has an explicit `color-scheme` value of `light`, `dark`, or `light dark`.++ ```css+ :root {+ /*+ MANDATORY: Enable system-wide support for both themes.+ Without this, the browser will not know how to resolve light-dark().+ */+ color-scheme: light dark;+ }+ ```++2. **Define semantic variables or properties using `light-dark()`.** Use the `light-dark(light-color, dark-color)` syntax.++ ```css+ .themed-card {+ /*+ DO: Use semantic variables to define theme-aware colors.+ The first argument is used when color-scheme is 'light'.+ The second argument is used when color-scheme is 'dark'.+ */+ --card-bg: light-dark(#ffffff, #2d2e31);+ --card-text: light-dark(#202124, #f8f9fa);++ background-color: var(--card-bg);+ color: var(--card-text);+ padding: 1.5rem;+ border-radius: 8px;+ }+ ```++3. **Create theme overrides.** You can force a component instance into a specific theme by setting its `color-scheme` property using any valid CSS selector (classes, data attributes, etc.). This overrides the inherited system preference for that specific subtree.++ ```css+ /*+ DO: Use color-scheme to force a specific theme on a component.+ You can use classes, data attributes, or any other selector.+ */++ /* Using classes */+ .themed-card.force-light {+ color-scheme: light;+ }++ /* Using data attributes (often preferred for state) */+ .themed-card[data-theme="dark"] {+ color-scheme: dark;+ }+ ```++## Critical Considerations++- **Supported Types**: Currently, `light-dark()` is only used for color values. It cannot be used for lengths, numbers, or other non-color types (e.g., `padding`, `font-size`, `opacity`).+- **MANDATORY: Two Arguments**: The function must always have exactly two arguments.++```css+/*+ DO NOT: Attempt to use light-dark() for non-color properties like padding.+ This will result in an invalid property value.+*/+.themed-card {+ padding: light-dark(10px, 20px);+}+```++## Fallback strategies++Baseline status for light-dark(): Newly available. It's been Baseline since 2024-05-13.+Baseline status for color-scheme: Widely available. It's been Baseline since 2022-02-03.++### Color Fallbacks+For browsers that do not support `light-dark()` or the `color-scheme` property, provide a fallback using `@media (prefers-color-scheme: dark)` or manual variable overrides.++```css+.themed-card {+ /*+ MANDATORY: Define base fallback colors for browsers without light-dark().+ Default to light mode values.+ */+ --card-bg: #ffffff;+ --card-text: #202124;+}++/*+ DO: Update variables based on system preference for older browsers.+*/+@media (prefers-color-scheme: dark) {+ .themed-card {+ --card-bg: #2d2e31;+ --card-text: #f8f9fa;+ }+}++/*+ DO: Use @supports to provide progressive enhancement for light-dark().+ This ensures that per-component overrides (via color-scheme) work where supported.+*/+@supports (color: light-dark(white, black)) {+ .themed-card {+ --card-bg: light-dark(#ffffff, #2d2e31);+ --card-text: light-dark(#202124, #f8f9fa);+ }+}+```diff --git a/skills/modern-web/guides/user-experience/consistent-cross-document-transitions.md b/skills/modern-web/guides/user-experience/consistent-cross-document-transitions.mdnew file mode 100644index 0000000..e4f78fb--- /dev/null+++ b/skills/modern-web/guides/user-experience/consistent-cross-document-transitions.md@@ -0,0 +1,216 @@+# Consistent Cross-Document Transitions++## The Problem++Cross-document view transitions animate elements between two pages during a same-origin navigation. The browser captures a snapshot of the old page, navigates, then animates from the snapshot to the new page. If the new page has not finished loading critical resources — stylesheets, layout scripts, or key DOM elements — the transition animates to an incomplete or unstyled state. This causes visual glitches such as elements morphing to wrong positions, content reflowing mid-animation, or fallback fonts flashing to web fonts after the transition completes.++## The Solution++Use `blocking="render"` on critical `<link>` and `<script>` elements in the new page's `<head>`, and use `<link rel="expect">` to block rendering until specific DOM elements have been parsed. This ensures the browser does not begin the view transition animation until the new page's visual state is stable. The browser continues parsing the HTML in the background — only painting is deferred.++### Implementation Strategy++1. **MANDATORY:** Opt in to cross-document view transitions with the `@view-transition` CSS at-rule on both pages.+2. **MANDATORY:** Ensure critical stylesheets are in the `<head>`. Stylesheets in the `<head>` are render-blocking by default. Dynamically injected stylesheets require explicit `blocking="render"`.+3. **DO** use `blocking="render"` on `<script>` elements that must execute before the transition animates (e.g., scripts that apply a theme or affect the layout).+4. **DO** use `<link rel="expect" href="#element-id" blocking="render">` to block rendering until above-the-fold content has been parsed. This applies to all transition types: full-page cross-fades (to avoid animating to a blank page), morph animations (to ensure named elements exist in the DOM), and script-dependent layouts (to ensure styled content is parsed).+5. **DO NOT** block rendering on non-critical content. Only block on resources and elements that affect the initial viewport. Blocking on too much content delays the transition and degrades perceived performance.++## Implementation Guide++### Step 1: Opt in to Cross-Document View Transitions++MANDATORY: Both the source and destination pages must include the `@view-transition` at-rule. Without this, no cross-document transition occurs.++```css+/*+ MANDATORY: Include this rule in every page that participates+ in cross-document view transitions.+ `navigation: auto` enables transitions for standard navigations+ (link clicks, form submissions, back/forward).+*/+@view-transition {+ navigation: auto;+}+```++### Step 2: Block Rendering Until Critical Scripts Execute++If a non-blocking script in the `<head>` must run before the transition animates (e.g., to apply a theme class or affect the layout), mark it with `blocking="render"`. Without this, `async`, `defer`, or `type="module"` scripts may execute after the transition has already started.++```html+<head>+ <!--+ DO: Mark layout-critical scripts with blocking="render".+ -->+ <script type=module blocking="render">+ // Example: apply a stored theme before the page renders,+ // so the transition snapshot reflects the correct theme.+ document.documentElement.dataset.theme =+ localStorage.getItem('theme') || 'light';+ </script>+</head>+```++### Step 3: Block Rendering Until Key DOM Elements Are Parsed++Stylesheets and `blocking="render"` scripts in the `<head>` only guarantee that the `<head>` has been fully processed. They do **not** wait for any `<body>` content to be parsed. Without additional blocking, the browser may take the new-page snapshot before above-the-fold elements exist in the DOM — resulting in a transition that animates to a blank or partially rendered page.++`<link rel="expect">` solves this by blocking rendering until a specific element (identified by its `id`) has been parsed. The `href` value must be a fragment identifier (e.g., `#hero`) matching the target element's `id` attribute. Once that element's closing tag is parsed, the render block is released.++**DO** use `<link rel="expect">` in all of the following scenarios:++#### Use Case 1: Full-Page Cross-Fade++Even when no individual elements have a `view-transition-name`, the default `root` transition cross-fades the entire page. If the new page's snapshot is taken before above-the-fold content is parsed, the cross-fade animates from the old page to a blank or incomplete page. Block rendering on an element that marks the end of the visible above-the-fold content.++```html+<head>+ <link rel="stylesheet" href="/css/styles.css">++ <!--+ DO: Block rendering until the main content area is parsed,+ even for a simple cross-fade. Without this, the browser may+ snapshot the page before visible content exists in the DOM,+ causing the cross-fade to reveal a blank or partial page.+ -->+ <link rel="expect" href="#main-content" blocking="render">+</head>+<body>+ <header>...</header>+ <main id="main-content">+ <h1>Page Title</h1>+ <p>Above-the-fold content the user should see immediately.</p>+ </main>+ <!-- Content below the fold does NOT need to be blocked on -->+ <section>...</section>+</body>+```++#### Use Case 2: Morph Animations Between Specific Elements++When elements on both pages share a `view-transition-name`, the browser morphs them smoothly across the navigation. If the target element has not been parsed when the transition starts, the browser cannot find it — the morph degrades to separate exit and entry animations. Block rendering until the element with the `view-transition-name` has been parsed.++```html+<head>+ <link rel="stylesheet" href="/css/styles.css">++ <!--+ DO: Block rendering until the element participating in the+ morph animation has been parsed. Without this, the browser+ may start the transition before #hero exists, causing the+ morph to degrade to a fade-out/fade-in.+ -->+ <link rel="expect" href="#hero" blocking="render">++ <!--+ When multiple blocking="render" resources are present,+ rendering is blocked until ALL of them are satisfied.+ Here, the browser waits for both the script to execute+ AND the #hero element to be parsed — whichever comes last.+ -->+ <script async blocking="render" src="/js/transition-setup.js"></script>+</head>+<body>+ <header>...</header>+ <section id="hero">+ <h1 style="view-transition-name: page-title">Product Name</h1>+ <img style="view-transition-name: hero-image" src="/img/product.webp" alt="Product">+ </section>+</body>+```++### Step 4: Use Media Queries for Responsive Render Blocking++Different viewport sizes may show different amounts of content above the fold. Use the `media` attribute on `<link rel="expect">` to block rendering only for the content visible at a given viewport width.++```html+<head>+ <!--+ DO: Use media queries to conditionally block rendering.+ On wide screens, both the hero and the sidebar are visible,+ so block until both are parsed. On narrow screens, only the+ hero is visible initially.+ -->+ <link+ rel="expect"+ href="#hero"+ blocking="render"+ media="screen and (width <= 768px)"+ >+ <link+ rel="expect"+ href="#sidebar"+ blocking="render"+ media="screen and (width > 768px)"+ >+</head>+```++### Step 5: Use pagereveal for Context-Dependent Transitions (Optional)++The `pagereveal` event is **not required** for the core render-blocking strategy. It is only needed when `view-transition-name` values must be assigned dynamically based on where the user navigated from — for example, morphing a specific list item to a detail page heading.++If `view-transition-name` values are assigned statically in CSS, or if you are only using the default full-page cross-fade, skip this step entirely.++```html+<head>+ <!--+ MANDATORY: The pagereveal listener must be registered before+ the page renders. Use an async script with blocking="render"+ so the listener is registered early without blocking parsing.+ If the listener is registered too late (e.g., in a deferred+ script), the event may have already fired.+ -->+ <script async blocking="render" src="/js/transition-setup.js"></script>+</head>+```++```javascript+// transition-setup.js+window.addEventListener('pagereveal', async (event) => {+ if (!event.viewTransition) return;++ const from = navigation.activation?.from;+ if (!from) return;++ const fromUrl = new URL(from.url);++ // DO: Assign view-transition-name based on navigation context.+ // This enables a morph animation from the product card on the+ // list page to the heading on the detail page.+ if (fromUrl.pathname === '/products/') {+ const heading = document.querySelector('main h1');+ if (heading) {+ heading.style.viewTransitionName = 'product-title';+ }++ // MANDATORY: Remove the temporary name after the transition+ // finishes. Stale names interfere with subsequent navigations+ // and prevent the page from entering the bfcache.+ await event.viewTransition.finished;+ heading.style.viewTransitionName = '';+ }+});+```++## Best Practices++- **DO** assign `view-transition-name` via CSS whenever possible. Reserve JavaScript assignment (via `pagereveal`) for cases where the name depends on navigation context.+- **DO** keep render-blocking scripts small and fast. The browser has a built-in timeout (around 4 seconds), after which the transition is skipped entirely with a `TimeoutError`.+- **DO NOT** use `<link rel="expect">` to block on elements deep in the page that are not visible in the initial viewport. This delays the transition without visual benefit.+- **DO NOT** assign the same `view-transition-name` to multiple elements on the same page. Duplicate names cause the entire transition to be skipped.++## Fallback Strategies++Cross-document view transitions has limited availability.++Cross-document view transitions are an excellent candidate for progressive enhancement. In browsers that do not support them, the `@view-transition` rule is ignored and standard same-origin navigations occurs exactly as they would without the feature. Supporting browsers get smooth transitions; all others get standard navigation. Limited browser support is not a reason to avoid adoption.++All browsers that support cross-document view transitions also support `blocking="render"` and `<link rel="expect">`, so no separate fallback is needed for the render-blocking features described in this guide.++## Other Considerations++1. **Performance Impact**: Every render-blocking resource delays the view transition animation start. Minimize the number of render-blocking scripts and use `<link rel="expect">` only for elements that are above the fold. Prerender destination pages using the Speculation Rules API to eliminate loading delays entirely.+2. **Timeout Behavior**: If the combined render-blocking time exceeds approximately 4 seconds, the browser skips the transition with a `TimeoutError`. Ensure critical resources load well within this window.+3. **bfcache Compatibility**: Temporary `view-transition-name` assignments that are not cleaned up after the transition can prevent the page from entering the bfcache. Always remove dynamically assigned names in the `finished` callback.diff --git a/skills/modern-web/guides/user-experience/content-based-styling.md b/skills/modern-web/guides/user-experience/content-based-styling.mdnew file mode 100644index 0000000..42e116b--- /dev/null+++ b/skills/modern-web/guides/user-experience/content-based-styling.md@@ -0,0 +1,116 @@+Historically, applying different layouts to a component based on its content required either JavaScript or conditional logic in your HTML templating language to inject modifier classes (like `.card--has-image` or `.card--text-only`).++The `:has()` pseudo-class eliminates this need by acting as a parent selector. It allows you to conditionally style a container element based on the presence or absence of specific descendant elements.++Using `:has()`, you can easily define distinct layout variations entirely in CSS based on a component's actual DOM content. You can also optionally combine it with `:not()` to explicitly target the *absence* of content to define default layouts.++### Implementing content-based container styling++**MANDATORY**: You must use the `:has()` selector on the container element to detect the presence of specific child content.++To build a component that changes its layout based on its content:++1. **Define the default styling**: Apply the base layout styles to the container element (e.g., a simple single-column stack).+2. **Apply content-based overrides**: Target the container with `:has([child-selector])` and apply the new layout styles for when that content is present (e.g., a multi-column grid).++*Example: A card component that switches to a side-by-side layout if an image is present.*++```css+/* 1. Define the default state on the component container */+/* This applies when there is NO image */+.article-card {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ padding: 1.5rem;+ border: 1px solid #ccc;+ border-radius: 8px;+}++/* 2. Apply styles when a specific child element is present */+/* MANDATORY: Target the container and use :has() to check for the descendant */+.article-card:has(img) {+ /* Change the layout to a row if an image exists */+ flex-direction: row;+ align-items: center;+}++/* Optional: Style the image itself (no :has() needed here) */+.article-card img {+ width: 150px;+ height: auto;+ border-radius: 4px;+}++/* You can also combine :has() and :not() to explicitly target the ABSENCE of content */+/* This selects a card that DOES NOT have an image */+.article-card:not(:has(img)) {+ /* E.g., apply a different background color for text-only cards */+ background-color: #f9f9f9;+}+```++```html+<!-- A card WITH an image (will use row layout) -->+<article class="article-card">+ <img src="thumbnail.jpg" alt="Article thumbnail" />+ <div class="content">+ <h2>Card With Image</h2>+ <p>This card lays out its content horizontally.</p>+ </div>+</article>++<!-- A card WITHOUT an image (will use default column layout) -->+<article class="article-card">+ <div class="content">+ <h2>Text-Only Card</h2>+ <p>This card lays out its content vertically, and gets its background color from the :not(:has()) rule.</p>+ </div>+</article>+```++**Performance tip**: When using `:has()`, scope the selector to the most specific component container possible (like `.article-card`). Avoid anchoring it to very high-level elements like `body:has(img)` if the styling changes are highly localized, as broad `:has()` queries can trigger more layout recalculations.++### Fallback strategies++Baseline status for :has(): Newly available. It's been Baseline since 2023-12-19.++If the content-based layout styling is critical to the user experience or page design, you must provide a fallback for browsers that do not support the `:has()` selector. For purely decorative effects, `:has()` can be used as a progressive enhancement without a fallback.++**MANDATORY**: When implementing a fallback for critical layouts, you must use `@supports not selector(:has(*))` in your CSS to define a traditional class-based fallback (e.g., `.has-image`).++Unlike interactive state-based styling, content presence is typically known at render time. The most robust fallback is to have your server-side templating engine (or static site generator) inject a class like `.has-image` onto the container if the child element (like an image) exists in the data.++If server-side rendering is not an option, you must use a small script with `CSS.supports()` to detect the content and append the class on load or after dynamic content injection.++```css+/* Fallback CSS for older browsers */+/* We check if the browser DOES NOT support the :has() selector */+@supports not selector(:has(*)) {+ /* Define a traditional modifier class that applies the exact same layout overrides */+ .article-card.has-image {+ flex-direction: row;+ align-items: center;+ }++ .article-card:not(.has-image) {+ background-color: #f9f9f9;+ }+}+```++```javascript+/* Fallback JavaScript for older browsers (if not using SSR to add the class) */+/* Check for support before running the script to avoid unnecessary work in modern browsers */+if (!CSS.supports('selector(:has(*))')) {+ // Find all components that need checking+ const cards = document.querySelectorAll('.article-card');++ cards.forEach(card => {+ // If the critical content exists, manually add the fallback class+ if (card.querySelector('img')) {+ card.classList.add('has-image');+ }+ });+}+```diff --git a/skills/modern-web/guides/user-experience/coordinate-global-events.md b/skills/modern-web/guides/user-experience/coordinate-global-events.mdnew file mode 100644index 0000000..21e1b4e--- /dev/null+++ b/skills/modern-web/guides/user-experience/coordinate-global-events.md@@ -0,0 +1,77 @@+# Coordinating Global Events with Temporal++Scheduling events across different time zones is notoriously difficult with the legacy `Date` object, especially around Daylight Saving Time (DST) transitions when hours can be skipped or repeated.++The `Temporal` API provides `Temporal.ZonedDateTime` to represent a date and time in a specific time zone, handling DST transitions automatically and predictably.++## How to Implement++To coordinate global events and handle potential DST conflicts:++1. **MANDATORY:** **Create a ZonedDateTime**: Use `Temporal.ZonedDateTime.from()` to create a time-zone-aware date-time object.+2. **MANDATORY:** **Handle Ambiguity**: Use the `disambiguation` option to control behavior when a time is ambiguous or does not exist (e.g., during clock changes).+3. **MANDATORY:** **Convert Time Zones**: Use `.withTimeZone()` to see the equivalent time in another location.++### Example: Scheduling and Conflict Detection++```javascript+// 1. Define the event time and target time zone+const date = "2025-03-09";+const time = "02:30"; // This time is skipped in New York during Spring Forward+const timeZone = "America/New_York";+const inputStr = `${date}T${time}[${timeZone}]`;++// 2. Detect conflicts using 'reject'+let hasConflict = false;+try {+ // 'reject' throws RangeError if the time is ambiguous or does not exist+ Temporal.ZonedDateTime.from(inputStr, { disambiguation: 'reject' });+} catch (e) {+ if (e instanceof RangeError) {+ hasConflict = true;+ console.log("This time falls in a DST transition gap or overlap.");+ }+}++// 3. Resolve the time safely using 'compatible' (default)+// 'compatible' will resolve to a valid time even if skipped or repeated+const hostTime = Temporal.ZonedDateTime.from(inputStr, { disambiguation: 'compatible' });+console.log(`Resolved time: ${hostTime.toString()}`);++// 4. Convert to another time zone (e.g., Tokyo)+const tokyoTime = hostTime.withTimeZone("Asia/Tokyo");+console.log(`Tokyo time: ${tokyoTime.toString()}`);+```++## Strategic Implementation & Best Practices++- **DO** use `Temporal.ZonedDateTime` for events that are bound to a specific geographical location (like a meeting in a specific city).+- **DO** use `disambiguation: 'reject'` if you need to detect and warn users about scheduling conflicts during DST transitions.+- **DO** use `disambiguation: 'compatible'` (the default) when you want the system to automatically pick a sensible time when conflicts occur.+- **DO NOT** use `Temporal.PlainDateTime` for global events, as it does not carry time zone information and cannot account for DST changes.+- **DO** use `.withTimeZone()` to calculate the equivalent time in other locations without mutating the original object (Temporal objects are immutable).++### Fallback strategies++Temporal has limited availability.++For environments without native `Temporal` support, you must conditionally load the `@js-temporal/polyfill`.++```javascript+// Check if Temporal is supported natively+(async () => {+ if (typeof Temporal === 'undefined') {+ // Load the polyfill conditionally+ const module = await import("https://esm.sh/@js-temporal/polyfill");+ globalThis.Temporal = module.Temporal;+ // Extend Date.prototype if needed+ Date.prototype.toTemporalInstant = module.toTemporalInstant;+ initializeApp();+ }+})();++function initializeApp() {+ // Your app logic here+ console.log("Temporal is ready:", typeof Temporal);+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/cross-document-transitions.md b/skills/modern-web/guides/user-experience/cross-document-transitions.mdnew file mode 100644index 0000000..3f1d0bf--- /dev/null+++ b/skills/modern-web/guides/user-experience/cross-document-transitions.md@@ -0,0 +1,123 @@+Cross-document view transitions allow you to create smooth, app-like transitions between different pages of a Multi-Page Application (MPA). By default, the browser performs a cross-fade, but you can customize this to match your site's aesthetic.++### Implementation Steps++#### 1. Opt-in to Cross-Document View Transitions++Both the source and destination pages must opt-in to view transitions for the browser to trigger them on navigation.++```css+/* Respect user's preference for reduced motion */+@media (prefers-reduced-motion: no-preference) {+ /* Add to a global stylesheet shared by both pages */+ @view-transition {+ /* Enables transitions for same-origin navigations */+ navigation: auto;+ }+}+```++#### 2. Customize Transition Animations (Optional)++You can target the old and new states of the transition using pseudo-elements to create effects like slides or reveals.++```css+/* Customizing the outgoing page animation */+::view-transition-old(root) {+ /* Move the old page out to the left */+ animation: 0.4s ease-in both slide-out;+}++/* Customizing the incoming page animation */+::view-transition-new(root) {+ /* Move the new page in from the right */+ animation: 0.4s ease-out both slide-in;+}++@keyframes slide-out {+ to { transform: translateX(-20%); opacity: 0; }+}++@keyframes slide-in {+ from { transform: translateX(100%); }+}+```++#### 3. Create Directional Transitions (Optional)++You may want different transition effects depending on the pages you are navigating between. For instance, when navigating from a home page to a contact page, you may want the effect of new content coming from the right. When navigating back to the home page, it wouldn't make sense to have the same effect.++If the page you are navigating to will always have the same transition type, regardless of how you get to the page, you can specify it with `types` in the `@view-transition` rule.++```css+@media (prefers-reduced-motion: no-preference) {+ @view-transition {+ navigation: auto;+ /* Specify the types of view transitions that will always be used on this page. */+ types: previous;+ }+}+```++You can also conditionally specify transition types inside of an event listener for `pagereveal`.++```js+window.addEventListener("pagereveal", async (e) => {+ if (e.viewTransition && window.navigation?.activation) {+ // Use application-specific logic to compute a transition type+ const transitionType = yourTransitionTypeLogic(navigation.activation.from, navigation.activation.entry);+ e.viewTransition.types.add(transitionType);+ }+});+```++Then, use the `:active-view-transition-type()` pseudo selector to apply the different animations for each type.++```css+:active-view-transition-type(next) {+ &::view-transition-old(root) {+ animation-name: slide-out-next;+ }++ &::view-transition-new(root) {+ animation-name: slide-in-next;+ }+}+:active-view-transition-type(previous) {+ &::view-transition-old(root) {+ animation-name: slide-out-previous;+ }++ &::view-transition-new(root) {+ animation-name: slide-in-previous;+ }+}+```++### Fallback strategies++Baseline status for View transitions: Newly available. It's been Baseline since 2025-10-14.++Cross-document view transitions has limited availability.++If a browser does not support view transitions, or cross-document view transitions, it will perform a standard instant page navigation. Cross-document view transitions are a progressive enhancement; the core functionality of the site remains unaffected.++To check for support in JavaScript:++```javascript+if ('onpagereveal' in window) {+ // Browser supports cross-document view transitions+}+```++Baseline status for Navigation API: Newly available. It's been Baseline since 2026-01-13.++If a browser does not support the Navigation API, you will not be able to use it to determine a transition type. Use an alternate method for determining the transition type, or provide a fallback transition type. Otherwise, the browser will perform a standard instant page navigation.++To check for support in JavaScript:++```javascript+if (window.navigation?.activation) {+ // Browser supports the Navigation API+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/customize-scrollbar-color-and-thickness.md b/skills/modern-web/guides/user-experience/customize-scrollbar-color-and-thickness.mdnew file mode 100644index 0000000..44fd7e4--- /dev/null+++ b/skills/modern-web/guides/user-experience/customize-scrollbar-color-and-thickness.md@@ -0,0 +1,75 @@+# Customize the color or thickness of a scrollbar++You can customize the appearance of scrollbars using the standard CSS properties `scrollbar-color` and `scrollbar-width`.++* **`scrollbar-color`**: Accepts two `<color>` values. The first applies to the thumb (the moving part), and the second to the track (the fixed background).+* **`scrollbar-width`**: Accepts `auto` (default), `thin` (a thinner variant), or `none` (hides the scrollbar completely while maintaining scrollability).++## Apply `scrollbar-color` and `scrollbar-width`++MANDATORY: Use `scrollbar-color` and `scrollbar-width` on the scrollable container.++```css+.scroller {+ /* Specify thumb color first, then track color for modern browsers */+ scrollbar-color: hotpink blue;+ /* Apply standard width property natively */+ scrollbar-width: thin;+ /* Force the track background to be visible on macOS */+ scrollbar-gutter: stable;+}++.scroller-hidden {+ /* Use none to hide scrollbar but keep scrollability */+ scrollbar-width: none;+}+```++IMPORTANT: On macOS, the `scrollbar-color` (standard) and `::-webkit-scrollbar` (legacy) properties are ignored by default because macOS uses native "overlay" scrollbars. Therefore, you MUST apply `scrollbar-width` (e.g., `thin` or `auto`) to force macOS to render custom colors.++IMPORTANT: Do NOT animate or transition `scrollbar-color`. A [WebKit bug](https://bugs.webkit.org/show_bug.cgi?id=311752) causes the scrollbar to flicker every time `scrollbar-color` changes.++## Fallback strategies++Baseline status for scrollbar-color: Newly available. It's been Baseline since 2025-12-12.++Baseline status for scrollbar-width: Newly available. It's been Baseline since 2024-12-11.++If the user's Baseline target (or Widely available, if unavailable) does not support any of the required features, the following fallback strategies MUST be used.++Include the non-standard `::-webkit-scrollbar` pseudo-elements as fallbacks.++To prevent conflicts between standard properties and legacy WebKit selectors in browsers that support both natively (like modern Chrome), you MUST wrap legacy WebKit fallbacks in an `@supports not (scrollbar-color: auto)` block.++```css+.scroller {+ /* Apply standard properties natively */+ scrollbar-color: hotpink blue;+ scrollbar-width: thin;+ /* Force the track background to be visible on macOS */+ scrollbar-gutter: stable;+}++/* Legacy fallback for WebKit/Blink browsers */+@supports not (scrollbar-color: auto) {+ .scroller::-webkit-scrollbar {+ /* Must define base size in WebKit for custom colors to be visual */+ width: 12px;+ height: 12px;+ }+ .scroller::-webkit-scrollbar-thumb {+ /* Use background to color the thumb */+ background: hotpink;+ border-radius: 6px;+ }+ .scroller::-webkit-scrollbar-track {+ /* Use background to color the track */+ background: blue;+ }++ .scroller-hidden::-webkit-scrollbar {+ display: none;+ width: 0;+ }+}+```diff --git a/skills/modern-web/guides/user-experience/declarative-button-actions.md b/skills/modern-web/guides/user-experience/declarative-button-actions.mdnew file mode 100644index 0000000..b32eca7--- /dev/null+++ b/skills/modern-web/guides/user-experience/declarative-button-actions.md@@ -0,0 +1,131 @@+# Declarative Button Actions+The Invoker Commands API allows buttons to trigger actions on target elements declaratively using HTML attributes. This approach reduces the need for manual event listeners and ensures interactivity as soon as the HTML is parsed.++For custom, application-specific actions, you can define your own command names. Custom commands must be prefixed with a double dash (`--`) to avoid collisions with future built-in browser commands.++## Implementation steps++1. **Define the target element**: Identify the element that will respond to the action. It must have a unique `id`.+2. **Configure the invoker button**: Use the `commandfor` attribute to point to the target's `id`, and the `command` attribute to specify the custom command name (prefixed with `--`).+3. **Handle the command event**: Attach a `command` event listener to the `document` (or a common parent). This ensures that the event is captured even if it is dispatched by a polyfill or from a child element. The event object contains a `command` property and a `target` property (referring to the element identified by `commandfor`).++## Example: Custom Animation Controls++```html+<!-- The target element that will respond to custom commands -->+<div id="action-target" class="target">+ Action Target+</div>++<!-- Buttons declaratively linked to the target element -->+<!-- Each button sends a unique custom command starting with '--' -->+<button commandfor="action-target" command="--spin">+ Spin+</button>++<button commandfor="action-target" command="--grow">+ Grow+</button>++<button commandfor="action-target" command="--reset">+ Reset All+</button>++<script>+ // Listen for the 'command' event globally (or on a stable parent)+ document.addEventListener('command', (event) => {+ // Robustly handle both native API and manual/polyfill fallbacks+ const command = event.command || event.detail?.command;+ const target = event.target;++ // Only process commands for our specific target+ if (target.id !== 'action-target') return;++ // Custom commands are checked to identify the requested action+ if (command === '--spin') {+ target.classList.toggle('is-spun');+ } else if (command === '--grow') {+ target.classList.toggle('is-grown');+ } else if (command === '--reset') {+ // Clear all custom classes to return to initial state+ target.classList.remove('is-spun', 'is-grown');+ }+ });+</script>+```++## Key constraints++* **Prefix custom commands**: MANDATORY: All custom command names must start with `--` (e.g., `command="--my-action"`).+* **Targeting**: The `commandfor` attribute must match the `id` of an element in the same document tree.++## Fallback strategies++Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.++If the Invoker Commands API is not supported, the `command` event will not fire. For full support across all modern browsers, it is recommended to use the invokers-polyfill from https://github.com/keithamus/invokers-polyfill via `npm install` or CDN.++This polyfill fully supports custom actions (starting with `--`) and dispatches the `command` event exactly like the native API.++### Dynamic Import (Performance Optimization)++For the best performance, you should only load the polyfill if the browser doesn't support the API natively. This saves bandwidth and reduces script execution time for users on modern browsers.++```javascript+// Check for native support first+const hasNativeSupport = 'commandForElement' in HTMLButtonElement.prototype;++if (!hasNativeSupport) {+ // Dynamically import the polyfill only when needed+ try {+ await import('https://cdn.jsdelivr.net/npm/invokers-polyfill@latest/dist/index.min.js');+ console.log('Invoker Commands polyfill loaded');+ } catch (err) {+ console.error('Error loading fallback:', err);+ }+}+```++### Manual fallback (Traditional pattern)++If you prefer not to use a polyfill, you can use a combination of **event delegation** to dispatch events and a **command registry** to handle the actions. This is a common architectural pattern in traditional JavaScript development that remains highly efficient and scalable.++```javascript+// 1. Define a registry of requested actions for cleaner logic+const commandRegistry = {+ '--spin': (target) => target.classList.toggle('is-spun'),+ '--grow': (target) => target.classList.toggle('is-grown'),+ '--reset': (target) => target.classList.remove('is-spun', 'is-grown'),+};++const supportsInvokers = 'commandForElement' in HTMLButtonElement.prototype;++// 2. The fallback: Dispatch events manually if native support is missing+if (!supportsInvokers) {+ document.addEventListener('click', (event) => {+ const button = event.target.closest('button[commandfor]');+ if (!button) return;++ const target = document.getElementById(button.getAttribute('commandfor'));+ const command = button.getAttribute('command');++ if (target && command) {+ target.dispatchEvent(new CustomEvent('command', {+ bubbles: true,+ detail: { command }+ }));+ }+ });+}++// 3. The unified listener: Uses the registry to execute the requested action+document.addEventListener('command', (event) => {+ const command = event.command || event.detail?.command;+ const target = event.target;+ const action = commandRegistry[command];++ if (action && target.id === 'action-target') {+ action(target);+ }+});+```diff --git a/skills/modern-web/guides/user-experience/declarative-dialog-popover-control.md b/skills/modern-web/guides/user-experience/declarative-dialog-popover-control.mdnew file mode 100644index 0000000..66c37b8--- /dev/null+++ b/skills/modern-web/guides/user-experience/declarative-dialog-popover-control.md@@ -0,0 +1,143 @@+# Overview++Use the Invoker Commands API to toggle the visibility of `<dialog>` and `[popover]` elements directly from HTML buttons, eliminating the need for custom JavaScript event listeners.++By applying the `commandfor` (target ID) and `command` (action) attributes to a `<button>`, the browser automatically handles open/close state changes, focus management, and accessibility bindings (such as `aria-expanded`). This declarative approach is recommended because it removes brittle boilerplate code, ensures interactions are functional immediately upon HTML parsing, and guarantees a robust, natively accessible user experience.++## Implementing Declarative Popovers++Popovers can be toggled open and closed using a single button.++```html+<!-- MANDATORY: The commandfor attribute links the invoker to the ID of the target element so the browser knows what to control. -->+<!-- MANDATORY: The command attribute specifies the action to perform. Use 'toggle-popover' to handle both open and close states automatically. -->+<button commandfor="my-popover" command="toggle-popover">+ Toggle Popover+</button>++<!-- MANDATORY: The target element must have the popover attribute to be controlled as a popover. -->+<div id="my-popover" popover>+ <p>Popover content goes here.</p>+</div>+```++If you need to control opening and closing with separate buttons, you can use the `show-popover` and `hide-popover` commands.++```html+<!-- MANDATORY: Use 'show-popover' to explicitly open the popover. It will not close the popover if clicked again. -->+<button commandfor="my-explicit-popover" command="show-popover">+ Show Popover+</button>++<div id="my-explicit-popover" popover>+ <p>This popover is explicitly opened and closed by separate buttons.</p>++ <!-- MANDATORY: Use 'hide-popover' to explicitly close the targeted popover. -->+ <button commandfor="my-explicit-popover" command="hide-popover">+ Hide Popover+ </button>+</div>+```++## Implementing Declarative Modal Dialogs++Unlike popovers, modal dialogs typically use separate buttons for opening and closing. Use the `show-modal` command specifically when you need to open a dialog as a modal.++```html+<!-- MANDATORY: Use command="show-modal" to trigger the dialog as a modal, trapping focus and preventing interaction with the rest of the page. -->+<!-- MANDATORY: The commandfor attribute connects this button to the dialog ID. -->+<button commandfor="confirm-dialog" command="show-modal">+ Open Confirmation+</button>++<dialog id="confirm-dialog">+ <p>Are you sure you want to proceed?</p>++ <!-- MANDATORY: Use command="close" to dismiss the dialog safely. -->+ <button commandfor="confirm-dialog" command="close">+ Cancel+ </button>+</dialog>+```++## Fallback strategies++Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.+Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.++Because Invoker Commands and Popovers are not yet universally supported, you MUST use polyfills as fallbacks for older browsers.++### Polyfilling Invoker Commands++MANDATORY: Feature detect support by checking for the `commandForElement` property on the `HTMLButtonElement` prototype. Do NOT check the window or document object. You MUST dynamically import the polyfill only when the native feature is missing. DO NOT unconditionally load the polyfill.++**Option 1: Using a package manager (e.g., npm)**+Install the polyfill in your project (`npm install invokers-polyfill`).++```javascript+// MANDATORY: Feature detect 'commandForElement' on HTMLButtonElement.prototype.+// Conditionally load the invokers-polyfill only in browsers lacking native support.+if (!('commandForElement' in HTMLButtonElement.prototype)) {+ import('invokers-polyfill');+}+```++**Option 2: Manual installation without npm**+If you are not using a package manager, dynamically import the polyfill directly from a CDN (such as unpkg) inside a `<script type="module">`.++```html+<script type="module">+ // MANDATORY: Feature detect 'commandForElement' on HTMLButtonElement.prototype.+ // Conditionally load the invokers-polyfill from a CDN only in browsers lacking native support.+ if (!('commandForElement' in HTMLButtonElement.prototype)) {+ import('https://unpkg.com/invokers-polyfill@latest/invoker.min.js');+ }+</script>+```++**Invokers Polyfill Limitations**+Unlike the native Invoker Commands API, `invokers-polyfill` does not automatically handle ARIA attributes (such as `aria-expanded`) on the command button.++MANDATORY: You MUST manually manage these ARIA states to ensure your site remains fully accessible to screen readers in browsers relying on the polyfill.++### Polyfilling the Popover Attribute++To support the `popover` attribute in older browsers, use the `@oddbird/popover-polyfill`.++MANDATORY: Feature detect popover support by checking for the `popover` property on the `HTMLElement` prototype. Conditionally initialize the polyfill only if native support is missing.++**Option 1: Using a package manager**+Install the package (`npm install @oddbird/popover-polyfill`).++```javascript+// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.+if (!('popover' in HTMLElement.prototype)) {+ import('@oddbird/popover-polyfill/fn').then(({ apply }) => {+ apply();+ });+}+```++**Option 2: Manual installation without npm**+If you are not using a package manager, dynamically import the polyfill directly from a CDN (such as unpkg) inside a `<script type="module">`.++```html+<script type="module">+ // MANDATORY: Feature detect 'popover' on HTMLElement.prototype.+ // Conditionally load the popover-polyfill from a CDN only in browsers lacking native support.+ if (!('popover' in HTMLElement.prototype)) {+ import('https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover-fn.js').then(({ apply }) => {+ apply();+ });+ }+</script>+```++**Popover Polyfill Limitations & Styling Caveats**+MANDATORY: Use `:is()` or `:where()` to combine `:popover-open` with the corresponding polyfill class, otherwise browsers that do not support `:popover-open` will throw away the entire rule.++```css+[popover]:is(:popover-open, .\:popover-open) {+ display: block;+}+```diff --git a/skills/modern-web/guides/user-experience/deliver-optimized-decorative-images.md b/skills/modern-web/guides/user-experience/deliver-optimized-decorative-images.mdnew file mode 100644index 0000000..5e2ea8a--- /dev/null+++ b/skills/modern-web/guides/user-experience/deliver-optimized-decorative-images.md@@ -0,0 +1,48 @@+Delivering optimized decorative images via CSS improves perceived performance without sacrificing visual quality. By using the `image-set()` CSS function, you can provide the browser with multiple options for a single background or mask image. You can specify modern formats (like AVIF or WebP) alongside different resolutions (like `1x` and `2x`). The browser will dynamically select the smallest compatible image that provides the appropriate pixel density for the user's device.++**CAUTION**: If the image is likely to be the Largest Contentful Paint (LCP) element (e.g., a large hero banner), be aware that images referenced in CSS via image-set() are not discoverable by the browser's preload scanner. This can significantly delay image loading and harm LCP. For LCP candidates, consider using a standard HTML <img> or <picture> tag instead or alternatively, preloading the image as well using `<link rel=preload>` option with a `media` attribute.++### Implementation++The `image-set()` function is used anywhere CSS expects an `<image>` value, most commonly in `background-image`, `content`, or `mask-image`. Note that while providing both the image format via `type()` and the resolution (like `1x` or `2x`) yields the best results, both of these arguments are optional.++```css+.gallery-item {+ /* Provide multiple resolutions and formats using image-set() */+ /* MANDATORY: Always order your formats from most optimized (AVIF) to least optimized (JPEG/PNG).+ The browser will stop at the first supported format. */+ background-image: image-set(+ url("gallery.avif") type("image/avif") 1x,+ url("gallery-2x.avif") type("image/avif") 2x,+ url("gallery.webp") type("image/webp") 1x,+ url("gallery-2x.webp") type("image/webp") 2x,+ url("gallery.jpg") type("image/jpeg") 1x,+ url("gallery-2x.jpg") type("image/jpeg") 2x+ );++ /* Standard decorative properties */+ background-size: cover;+ background-position: center;+}+```++### Fallback strategies++Baseline status for image-set(): Widely available. It's been Baseline since 2023-09-18.++For older browsers that do not support the `image-set()` function, you **MUST** provide a standard image declaration *before* the `image-set()` rule. This progressive enhancement strategy relies on CSS's cascading nature: unsupported rules are ignored.++```css+.gallery-item {+ /* MANDATORY: Fallback for browsers that do not support image-set() */+ background-image: url("gallery.jpg");++ /* Modern browsers will apply this and override the fallback */+ background-image: image-set(+ url("gallery.avif") type("image/avif") 1x,+ url("gallery-2x.avif") type("image/avif") 2x,+ url("gallery.jpg") type("image/jpeg") 1x,+ url("gallery-2x.jpg") type("image/jpeg") 2x+ );+}+```diff --git a/skills/modern-web/guides/user-experience/directional-navigation-transitions.md b/skills/modern-web/guides/user-experience/directional-navigation-transitions.mdnew file mode 100644index 0000000..034a453--- /dev/null+++ b/skills/modern-web/guides/user-experience/directional-navigation-transitions.md@@ -0,0 +1,123 @@+Single Page Applications (SPAs) provide the appearance of navigation by replacing the content of the page without navigating to a new page. By default, the content is simply replaced, without any transitions. Directional transitions can visually reinforce a spatial relationship between views.++By sliding new content in from the direction the user is moving you create a mental map of the application structure. For instance, a product site may show a transition to the right for "forward," and to the left for "back", or a slideshow may transition up and down to show next and previous slides.++### Implementation Steps++1. **Detect Navigation Direction**: Determine if the user is moving "forward" or "backward" in the application flow. How you detect the direction depends on your use case.+2. **Trigger Transition with Types**: Pass the direction in a `types` array to `document.startViewTransition()` to categorize the transition.+3. **Define Directional Animations with CSS**: Use the `:active-view-transition-type()` pseudo-class to apply specific animations based on the navigation type.++### Defining Keyframes++Define sliding animations to and from each direction. For best performance, animate position changes using the `transform` property or the individual transform properties, `scale`, `rotate`, and `translate`. `opacity` is generally performant as well, but avoid animating other CSS properties without first verifying that they don't trigger layout or painting.++```css+/* Slide an element out to the left */+@keyframes slide-to-left {+ /* Mandatory: animate `transform` instead of inset properties for better performance. */+ to { transform: translateX(-100%); }+}++/* Slide an element in from the right */+@keyframes slide-from-right {+ from { transform: translateX(100%); }+}++/* Slide an element out to the right */+@keyframes slide-to-right {+ to { transform: translateX(100%); }+}++/* Slide an element in from the left */+@keyframes slide-from-left {+ from { transform: translateX(-100%); }+}+```++### Set up shared animation settings++Use the `::view-transition-group(root)` selector to apply animation settings that are shared across all transitions.++```css+::view-transition-group(root){+ animation: 0.4s ease-in-out both;+}+```++### Applying Directional Animations++Use the `active-view-transition-type` pseudo-class to target the transition views specifically when the "forward" or "backward" type is active.++```css+/* MANDATORY: Apply forward animations when the 'forward' type is active */+html:active-view-transition-type(forward)::view-transition-old(root) {+ animation-name: slide-to-left;+}+html:active-view-transition-type(forward)::view-transition-new(root) {+ animation-name: slide-from-right;+}++/* MANDATORY: Apply backward animations when the 'backward' type is active */+html:active-view-transition-type(backward)::view-transition-old(root) {+ animation-name: slide-to-right;+}+html:active-view-transition-type(backward)::view-transition-new(root) {+ animation-name: slide-from-left;+}+```++### Triggering the Transition++When navigating, pass the appropriate type to the `startViewTransition` method.++```javascript+const transitionType = yourTransitionTypeLogic();+const updateDOM = yourUpdateDOMLogic();++document.startViewTransition({+ update: updateDOM,+ types: [transitionType] // Matches the CSS :active-view-transition-type() selectors+});+```+++### Accessibility++Always respect user preferences for reduced motion by disabling or simplifying animations.++```css+@media (prefers-reduced-motion: reduce) {+ ::view-transition-group(root) {+ animation: none !important;+ }+}+```++### Fallback strategies++Baseline status for View transitions: Newly available. It's been Baseline since 2025-10-14.+Baseline status for Active view transition: Newly available. It's been Baseline since 2026-01-13.++The View Transitions API is a progressive enhancement. In unsupported browsers, `document.startViewTransition` will be `undefined`. You must wrap your navigation logic in a feature detection check to ensure the DOM update still occurs immediately without animation, as shown in this helper function.++```javascript+/**+ * Navigates to a new view with a directional transition.+ * @param {Function} updateDOM - Callback to update the DOM state.+ * @param {string} direction - Either 'forward' or 'backward'.+ */+function navigate(updateDOM, direction) {+ // Feature detect for browsers that do not support View Transitions+ if (!document.startViewTransition) {+ updateDOM();+ return;+ }++ // Start transition with the specific navigation type+ document.startViewTransition({+ update: updateDOM,+ types: [direction] // Matches the CSS :active-view-transition-type() selectors+ });+}+```diff --git a/skills/modern-web/guides/user-experience/dynamic-sibling-animations.md b/skills/modern-web/guides/user-experience/dynamic-sibling-animations.mdnew file mode 100644index 0000000..653d1a8--- /dev/null+++ b/skills/modern-web/guides/user-experience/dynamic-sibling-animations.md@@ -0,0 +1,52 @@+# Creating a stagger animation++Stagger animations provide an interesting effect where multiple ordered elements animate sequentially with a slight delay between each, rather than all animating at once. This technique is often used in lists, galleries, or navigation menus to guide the user's eye and add a polished, rhythmic feel to interactions.++## Stagger animations with `sibling-index()`++Use the `sibling-index()` property on the `animation-delay` property so that the animation on each element is offset by a number proportionate to their position in their parent. The `sibling-index()` function returns an integer, so it must be multiplied by a time unit to convert it to a time.++```css+#stagger-list > .item {+ --stagger-time: 0.1s;+ /* Define the animation first */+ animation: fade-in 0.4s;+ /* Set the `animation-delay` to a time multipled by the `sibling-index()` */+ animation-delay: calc(sibling-index() * var(--stagger-time))+}+```++**MANDATORY:** Respect user preferences by disabling the animation for users who prefer reduced motion.++```css+@media (prefers-reduced-motion: reduce){+ /* Disable animation for users who prefer reduced motion. */+ #stagger-list > .item {+ animation: none;+ }+}+```++## Fallback strategies++sibling-count() and sibling-index() has limited availability.++Test for support for `sibling-index()` using CSS with `@supports (animation-delay: calc(sibling-index() * 0.1s)){}` or JavaScript with `!CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')`.++To support stagger animations in older browsers, use JavaScript to add a `--sibling-index` custom property to each sibling element. MANDATORY: wrap this in a `CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')` test to avoid running unneeded JavaScript.++```js+if(!CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')){+ const staggerList = document.getElementById('stagger-list');+ [...staggerList.children].forEach((el, index)=>el.style.setProperty('--sibling-index', index + 1));+}+```++Add an `animation-delay` declaration that uses the `--sibling-index` custom property. It must be before the `animation-delay` declaration that uses the `sibling-index()` function. This does not need to be wrapped in `@supports` - older browsers will not parse the second declaration and will use the first declaration.++```css+#stagger-list > .item {+ animation-delay: calc(var(--sibling-index) * var(--stagger-time));+ animation-delay: calc(sibling-index() * var(--stagger-time));+}+```diff --git a/skills/modern-web/guides/user-experience/dynamic-sibling-styling.md b/skills/modern-web/guides/user-experience/dynamic-sibling-styling.mdnew file mode 100644index 0000000..07ef8b1--- /dev/null+++ b/skills/modern-web/guides/user-experience/dynamic-sibling-styling.md@@ -0,0 +1,96 @@+# Styling siblings based on count and index++Historically, applying unique styles to each sibling in a list required complex `:nth-child` loops or JavaScript to inject inline styles. Modern CSS provides `sibling-index()` and `sibling-count()` to perform these calculations directly in your stylesheet, enabling dynamic layouts and color systems that automatically adapt as elements are added or removed.++## Dynamic color systems++You can create a color spectrum across a group of siblings by calculating a unique hue or lightness value for each child. This ensures a consistent gradient effect regardless of the number of items.++```css+.swatch {+ /* Calculate hue by dividing the full 360deg circle by total siblings */+ /* and multiplying by the current element's 1-based index */+ background-color: hsl(+ calc(360deg / sibling-count() * sibling-index()),+ 70%,+ 50%+ );+}+```++## Symmetrical layout and fan effects++To create symmetrical effects (like a "fan" or centering items), use the total count to find the midpoint of the list.++```css+.card {+ /* Find the center index (e.g., 3 if there are 5 siblings) */+ --center: calc((sibling-count() + 1) / 2);++ /* Rotate items away from the center: negative for left, positive for right */+ /* center element gets 0deg rotation */+ transform: rotate(calc(10deg * (sibling-index() - var(--center))));+}+```++## Circular and complex positioning++By combining these functions with CSS trigonometry (`sin()`, `cos()`), you can place elements in a perfect circle without any manual coordinates.++```css+.orb {+ /* Calculate the angle for this item's position on a 360deg circle */+ --angle: calc(360deg / sibling-count() * sibling-index());+ --radius: 150px;++ /* Set the pre-transformed position for all items to be centered */+ position: absolute;+ place-self: center;+++ /* Position each element around the parent center */+ transform: translate(+ calc(cos(var(--angle)) * var(--radius)),+ calc(sin(var(--angle)) * var(--radius))+ );+}+```++### Fallback strategies++sibling-count() and sibling-index() has limited availability.++If `sibling-index()` and `sibling-count()` are not supported, provide a fallback by injecting CSS custom properties via JavaScript. **MANDATORY:** Use feature detection with `CSS.supports()` to ensure the script only runs when necessary.++```js+/* MANDATORY: Check for native support before applying fallback */+if (!CSS.supports('top: calc(sibling-index() * 1px)')) {+ const items = document.querySelectorAll('.item');+ items.forEach((item, index) => {+ /* MANDATORY: Injected index must be 1-based to match native function */+ item.style.setProperty('--sibling-index', index + 1);+ item.style.setProperty('--sibling-count', items.length);+ });+}+```++In your CSS, use these variables as a base and override them with native functions inside an `@supports` block. **MANDATORY:** You MUST wrap the native function overrides in `@supports` to ensure the variables remain valid in older browsers.++```css+.item {+ /* 1. Set base values using variables (from JS fallback) */+ --index: var(--sibling-index);+ --count: var(--sibling-count);++ /* 2. Use the computed variables - replace this with your implementation-specific styles */+ background-color: hsl(calc(360deg / var(--count) * var(--index)), 70%, 50%);+}++@supports (top: calc(sibling-index() * 1px)) {+ .item {+ /* 3. Override with native functions ONLY if supported */+ --index: sibling-index();+ --count: sibling-count();+ }+}+```diff --git a/skills/modern-web/guides/user-experience/flicker-free-client-side-ab-testing.md b/skills/modern-web/guides/user-experience/flicker-free-client-side-ab-testing.mdnew file mode 100644index 0000000..8fbb447--- /dev/null+++ b/skills/modern-web/guides/user-experience/flicker-free-client-side-ab-testing.md@@ -0,0 +1,166 @@+# Flicker-Free Client-Side A/B Testing++## The Problem++Client-side A/B testing tools work by loading a script that modifies the DOM after the browser has already begun constructing the page. Without intervention, the user briefly sees the original content before it flickers or flashes to the experiment variant. Testing platforms have historically worked around this with "anti-flicker snippets" that hide the entire page with `opacity: 0` until the experiment script finishes or an arbitrary timeout (typically 4 seconds) elapses. This approach sacrifices progressive rendering, allows accidental clicks on invisible content, and introduces unnecessary paint cycles.++## The Solution++The `blocking=render` attribute allows a `<script>` or `<link>` element placed in the `<head>` to block rendering—but not parsing—until the resource has been fetched and executed. This gives experimentation scripts the same render-blocking behavior that stylesheets have by default, ensuring the browser never paints the page until the experiment variant has been applied. No opacity hacks, no arbitrary timeouts, and no flicker.++### Implementation Strategy++1. **MANDATORY:** Place the experimentation script in the document `<head>` and add `blocking="render"`.+2. **MANDATORY:** Ensure the script either has `type="module"` (preferred for inline scripts) or `async` (preferred for external scripts with a `src` value).+3. **DO** keep the experimentation script small and fast. Because rendering is blocked until the script executes, a large or slow script directly delays first paint.+4. **DO NOT** use `blocking="render"` on scripts that do not need to run before first paint. It is intended only for scripts whose output must be visible in the initial render.+5. **DO NOT** apply `blocking="render"` to scripts outside the `<head>`. Only scripts in the `<head>` can block rendering.++## Implementation Guide++### Basic Setup++MANDATORY: Load the experimentation script with both `async` and `blocking="render"`. The `async` attribute ensures the script does not block HTML parsing (the browser continues building the DOM while fetching the script). The `blocking="render"` attribute ensures the browser does not paint anything until the script has executed.++```html+<head>+ <!--+ MANDATORY: Both `async` and `blocking="render"` are required.+ - `async`: Prevents parser-blocking, so the DOM is built in parallel.+ - `blocking="render"`: Holds rendering until the script executes,+ ensuring experiment changes are applied before the user sees anything.+ -->+ <script+ src="https://cdn.example.com/experiment-sdk.js"+ async+ blocking="render"+ ></script>+</head>+```++### Loading Experiment-Specific Styles++If the experiment requires a variant stylesheet, use `blocking="render"` on the `<link>` element. Stylesheets in the `<head>` already block rendering by default, but dynamically injected stylesheets or those added via script do not. Use `blocking="render"` explicitly when the stylesheet is added dynamically or when you want to be explicit about the intent.++```html+<head>+ <!--+ DO: Use blocking="render" on experiment stylesheets that are+ dynamically inserted or conditionally loaded by the experiment SDK.+ This ensures variant styles are applied before first paint.+ -->+ <link+ rel="stylesheet"+ href="https://cdn.example.com/experiment-variant-b.css"+ blocking="render"+ >+</head>+```++### Inline Experiment Script++If the experiment logic is lightweight enough to inline, use an inline module script with `blocking="render"`. This is useful when the experiment logic fetches a configuration and applies DOM changes directly.++```html+<head>+ <!--+ DO: Use an inline module script when the experiment logic is small.+ Module scripts are deferred by default (non-parser-blocking),+ and blocking="render" ensures rendering waits for execution.+ -->+ <script type="module" blocking="render">+ // Fetch the experiment configuration from your testing platform.+ const config = await fetch('/api/experiment?id=homepage-cta')+ .then(res => res.json());++ // Apply the variant by setting a data attribute on <html>.+ // CSS rules keyed to this attribute will style the variant.+ document.documentElement.dataset.variant = config.variant;+ </script>++ <style>+ /* Default styles (control group) */+ .cta-button {+ background-color: blue;+ }++ /* Variant B styles, activated by the data attribute */+ [data-variant="b"] .cta-button {+ background-color: green;+ }+ </style>+</head>+```++## Best Practices++- **MANDATORY:** The experimentation script MUST execute quickly. A slow script delays all rendering. Set a performance budget (e.g., under 100ms execution time) for the render-blocking script.+- **DO** split heavy experiment logic from the render-blocking script. Load a small, render-blocking stub that applies the variant, then load heavier tracking or analytics scripts separately with `async` or `defer` (without `blocking="render"`).+- **DO** use a data attribute on `<html>` or `<body>` to signal the active variant, and use CSS selectors keyed to that attribute for variant styling. This avoids direct DOM manipulation in the render-blocking script.+- **DO NOT** use `blocking="render"` on analytics, tracking, or other non-visual scripts. Only scripts that must change what the user sees on first paint should block rendering.+- **DO NOT** combine `blocking="render"` with legacy anti-flicker snippets. They solve the same problem; using both creates unnecessary delays.++## Fallback Strategies++blocking="render" has limited availability.++The `blocking` attribute is not supported in all browsers. In browsers that do not support it, the attribute is ignored and the script loads with its default behavior (`async` in the examples above), which may result in flicker. A fallback is required to prevent flicker in unsupported browsers.++### Fallback: Anti-Flicker Snippet++DO: Use a lightweight anti-flicker snippet as a fallback only when `blocking="render"` is not supported. Feature-detect support and skip the fallback in browsers that handle it natively.++```html+<head>+ <!--+ DO: Load the experiment script with blocking="render" for+ browsers that support it. This is the preferred approach.+ -->+ <script+ src="https://cdn.example.com/experiment-sdk.js"+ async+ blocking="render"+ ></script>++ <script>+ // DO: Only apply the anti-flicker fallback in browsers+ // that do not support blocking="render".+ if (!Object.hasOwn(HTMLScriptElement.prototype, 'blocking')) {+ // Hide the page until the experiment script runs.+ document.documentElement.classList.add('ab-loading');++ // DO: Set a timeout to reveal the page if the experiment+ // script takes too long. This prevents an indefinitely+ // blank page on slow connections. Adjust the timeout+ // to match your experiment SDK's expected load time.+ setTimeout(() => {+ document.documentElement.classList.remove('ab-loading');+ }, 4000);+ }+ </script>++ <style>+ /*+ DO: Use opacity to hide content during experiment loading.+ This is only applied when blocking="render" is unsupported.+ */+ .ab-loading {+ opacity: 0 !important;+ }+ </style>+</head>+```++```javascript+// DO: In your experiment SDK's initialization callback,+// remove the fallback class to reveal the page.+function onExperimentReady() {+ document.documentElement.classList.remove('ab-loading');+}+```++## Other Considerations++1. **Performance Impact**: `blocking="render"` trades first-paint speed for visual correctness. Monitor Largest Contentful Paint (LCP) and First Contentful Paint (FCP) to ensure the experimentation script is not adding excessive delay.+2. **Third-Party Script Reliability**: If the experiment SDK is hosted on a third-party CDN, a CDN outage could block rendering entirely. The browser applies its own timeout heuristics (which may be longer than 4 seconds), but there is no developer-controlled timeout for `blocking="render"`. Ensure the third-party provider has strong uptime guarantees.+3. **Server-Side Alternatives**: For performance-critical pages, consider server-side A/B testing (where the server renders the correct variant directly) instead of client-side testing. Server-side approaches eliminate flicker entirely without any render-blocking cost. Use client-side `blocking="render"` only when server-side testing is not feasible.diff --git a/skills/modern-web/guides/user-experience/format-human-readable-durations.md b/skills/modern-web/guides/user-experience/format-human-readable-durations.mdnew file mode 100644index 0000000..39b7369--- /dev/null+++ b/skills/modern-web/guides/user-experience/format-human-readable-durations.md@@ -0,0 +1,86 @@+# Formatting Human-Readable Durations with Temporal++Presenting elapsed time or durations to users in a readable format (e.g., "1 hour and 30 minutes") has historically required manual math or external libraries. The `Temporal` API's `Temporal.Duration` class simplifies this by providing structured duration objects and powerful "balancing" capabilities via the `round()` method.++## How to Implement++To format a duration:++1. (**MANDATORY**) **Create a Duration**: Use `Temporal.Duration.from()` to create a duration object from a set of units.+2. (**OPTIONAL**) **Apply Balancing**: Use the `round()` method with the `largestUnit` option to control how units are balanced. For example, to convert 90 minutes into hours and minutes, or to keep it as total minutes.+3. (**MANDATORY**) **Build the Display String**: Access the specific unit properties (like `.hours`, `.minutes`) to construct the human-readable string manually, or **(Recommended)** use `Intl.DurationFormat` for a localized, automatic approach.++### Example: Balancing and Localized Formatting++```javascript+// 1. Create a duration (e.g., from user input)+const duration = Temporal.Duration.from({ minutes: 90 });++// 2. Balance to hours (converts 90 minutes to 1 hour and 30 minutes)+const balanced = duration.round({ largestUnit: 'hours' });++// 3. Format using Intl.DurationFormat (Handles pluralization automatically)+const formatter = new Intl.DurationFormat('en', { style: 'long' });+console.log(formatter.format(balanced));+// Note: Output may vary by browser (e.g., "1 hour and 30 minutes" or "1 hour, 30 minutes")+```++### Best Practices++* **DO** use `Temporal.Duration.round()` with `largestUnit` to control the display strategy (detailed breakdown vs total count).+* **DO** use `Intl.DurationFormat` for localized string formatting and automatic pluralization, or fall back to manual construction if not supported.+* **DO NOT** rely on `Temporal.Duration.prototype.toString()` for user-facing text; it returns ISO 8601 strings (e.g., `PT1H30M`).+* **DO** use feature detection and a polyfill for environments lacking native support.++## Fallback strategies++### Temporal++Temporal has limited availability.++For environments without native `Temporal` support, you must conditionally load the `@js-temporal/polyfill`.++```javascript+// Check if Temporal is supported natively+(async () => {+ if (typeof Temporal === 'undefined') {+ // Load the polyfill conditionally+ const module = await import("https://esm.sh/@js-temporal/polyfill");+ globalThis.Temporal = module.Temporal;+ // Extend Date.prototype if needed+ Date.prototype.toTemporalInstant = module.toTemporalInstant;+ initializeApp();+ }+})();++function initializeApp() {+ // App logic here+}+```++### Intl.DurationFormat++Baseline status for Intl.DurationFormat: Newly available. It's been Baseline since 2025-03-04.++If `Intl.DurationFormat` is not supported, you should feature-detect it and fall back to manual string construction by extracting the balanced duration properties.++* **Guidance:** Use `typeof Intl.DurationFormat !== 'undefined'` to check for support. If unsupported, extract properties like `.hours` and `.minutes` from the balanced `Temporal.Duration` object and combine them, handling pluralization properly.++```javascript+// 3. Format the display string++if (typeof Intl.DurationFormat !== 'undefined') {+ // Use recommended Intl API if available+ const formatter = new Intl.DurationFormat('en', { style: 'long' });+ console.log(formatter.format(balanced));+} else {+ // Fallback manual formatting (assuming duration is already balanced)+ const h = balanced.hours;+ const m = balanced.minutes;++ const hoursStr = `${h} hour${h === 1 ? '' : 's'}`;+ const minutesStr = `${m} minute${m === 1 ? '' : 's'}`;++ console.log(`${hoursStr} and ${minutesStr}`);+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/improve-body-text-layout-and-legibility.md b/skills/modern-web/guides/user-experience/improve-body-text-layout-and-legibility.mdnew file mode 100644index 0000000..a8477a5--- /dev/null+++ b/skills/modern-web/guides/user-experience/improve-body-text-layout-and-legibility.md@@ -0,0 +1,47 @@+# Improve Body Text Layout and Legibility++The `text-wrap: pretty` CSS property allows you to improve the typographic quality of body text by enabling a more sophisticated wrapping algorithm. It is specifically designed to prevent "orphans" (single words on the last line of a paragraph) and create a more pleasing visual "rag" for long blocks of text.++## Implementation steps++1. **Identify long-form text elements**: Select elements potentially containing long runs of text where orphaned words (runts) or poor line breaks are most noticeable. This includes the following elements:+ - `<p>`+ - `<blockquote>`+ - `<li>`+ - Any other element potentially containing long runs of text.+2. **Apply pretty wrapping**: Use `text-wrap: pretty` to enable an optimized algorithm that evaluates the last few lines of a paragraph to find the best break points.++## Example: Optimizing Body Copy++```css+/* Apply to paragraphs to prevent orphaned words */+p {+ /* MANDATORY: Enable pretty line-breaking logic */+ text-wrap: pretty; /* Prioritizes typographic beauty for body copy */+}++/* Also effective for other multi-line text elements */+blockquote, li, .pretty-text {+ /* MANDATORY: Enable pretty line-breaking logic */+ text-wrap: pretty;+}+```++## Key constraints++* **Performance vs. Quality**: MANDATORY: `text-wrap: pretty` is more computationally expensive than the default `wrap` (greedy) algorithm because it evaluates multiple lines (typically the last four) to optimize the break points. Avoid applying it globally to every element if your page has an extreme amount of text content.+* **Best for multi-line text**: The benefits of `pretty` are most apparent in paragraphs of three or more lines. It has little to no effect on short, single-line text.+* **Browser-specific behavior**: Be aware that implementation details vary. Chromium-based browsers typically focus on the last four lines, while other engines may evaluate the entire paragraph.++## Fallback strategies++text-wrap: pretty has limited availability.++`text-wrap: pretty` is a progressive enhancement. Browsers that do not support the property will simply ignore it and fall back to the default wrapping behavior. This ensures that your content remains perfectly readable across all browsers while providing a superior experience to those that support it.++```css+/* No @supports block is needed for progressive enhancement */+p {+ text-wrap: pretty; /* Supported browsers will prevent orphans; others will ignore this line */+}+```diff --git a/skills/modern-web/guides/user-experience/improve-heading-text-layout-and-legibility.md b/skills/modern-web/guides/user-experience/improve-heading-text-layout-and-legibility.mdnew file mode 100644index 0000000..e1f6052--- /dev/null+++ b/skills/modern-web/guides/user-experience/improve-heading-text-layout-and-legibility.md@@ -0,0 +1,27 @@+To improve the legibility and aesthetic appeal of short text blocks like headings, use `text-wrap: balance`. This property instructs the browser to distribute text as evenly as possible across lines, creating a more symmetrical appearance and preventing "widows" (a single word on the last line).++### Implementation++Apply `text-wrap: balance` specifically to short, multi-line elements such as headings (`h1`-`h6`), subheadings, or blockquotes.++```css+/* Target specific heading elements for balanced wrapping */+h1, h2, h3, .balanced-heading {+ /* MANDATORY: Enables balanced line-breaking logic */+ text-wrap: balance;+}+```++### Critical Constraints and Performance++* **Line Limit:** Browsers impose a limit on the number of lines they will attempt to balance to maintain performance (typically **6 lines** in Chromium and **10 lines** in Firefox). If the text exceeds this limit, the browser reverts to standard `wrap` behavior.+* **Targeted Application:** DO NOT apply `text-wrap: balance` globally (e.g., `* { text-wrap: balance; }`). The iterative "binary search" algorithm used by browsers is computationally expensive. Limit its use to specific, short text elements.+* **Interaction with Width:** `text-wrap: balance` does not change the container's width (`inline-size`). It only affects how text wraps *within* that width. This can leave empty space at the end of the container, which may affect layouts relying on full-width text blocks.++### Fallback strategies++Baseline status for text-wrap: balance: Newly available. It's been Baseline since 2024-05-13.++In browsers that do not support `text-wrap: balance`, the property is ignored, and the text will wrap using the default `wrap` behavior. This is a progressive enhancement that gracefully degrades to standard typography.++For critical layouts where manual control is required as a fallback, you can use traditional techniques like `<wbr>` (word break opportunity) or ` ` (non-breaking space) to influence line breaks, though these are less flexible than the native CSS property.diff --git a/skills/modern-web/guides/user-experience/individual-transform-properties.md b/skills/modern-web/guides/user-experience/individual-transform-properties.mdnew file mode 100644index 0000000..8d5300d--- /dev/null+++ b/skills/modern-web/guides/user-experience/individual-transform-properties.md@@ -0,0 +1,91 @@+The `transform` property allows you to apply multiple transformations in a specified order, but any changes to a single transformation require re-specifying the entire transformation chain. This makes it tricky to animate or transition a single transformation.++The individual CSS transform properties (`translate`, `rotate`, and `scale`) allow you to apply transformations independently of the `transform` property. This approach makes it simpler to override a single transformation, for instance on `:hover`.++### Key Implementation Details++Individual transform properties are always applied in a **fixed order**, regardless of their order in your CSS:+1. `translate`+2. `rotate`+3. `scale`+4. `transform` (applied last)++If you require a different order (e.g., scaling *before* rotating), you must continue using the `transform` property functions.++Transform functions do not override the individual transform properties. In other words, `scale: 2; transform: scale(3);` will first scale by 2x, then again by 3x, for a total of 6x.++### Preventing Unexpected Changes in Stacking Contexts and Containing Blocks++The `transform` property and individual transform properties impact the layout and rendering of the page and may cause unexpected behavior with the z-index or anchor positioning. MANDATORY: If an element may have a transform applied as part of a state change like `:hover`, or a transition or animation, apply an identity transformation to the base element. This ensures that the element's stacking context and containment do not change when a transform is applied.++```css+.element{+ /* MANDATORY: Apply identity transformations for properties that will+ change on state changes (like :hover). This prevents unexpected layout+ or z-index shifts caused by creating a new stacking context only on hover. */+ translate: 0px;+ rotate: 0deg;+ scale: 1;+}+.element:hover{+ translate: 10px 10px;+ rotate: 20deg;+ scale: 0.8;+}+```++### Independent Animation and Transitions++The primary benefit is the ability to define overlapping animations or transitions that target different properties without conflict.++```css+.card {+ /* Define independent animations that don't overwrite each other */+ animation: float 3s infinite ease-in-out;++ /* Transition only the scale property for hover states */+ transition: scale 0.3s ease;++ /* Establish the base scale to prevent a sudden stacking context shift when transitioning on hover. */+ scale: 1;+}++.card:hover {+ /* Only the scale changes; the 'float' animation (translate) continues uninterrupted */+ scale: 1.05;+}++@keyframes float {+ 0%, 100% { translate: 0 0; }+ 50% { translate: 0 -10px; }+}+```++### Fallback strategies++Baseline status for Individual transform properties: Widely available. It's been Baseline since 2022-08-05.++For browsers that do not support individual transform properties, use the traditional `transform` property. Note that this requires re-declaring the entire transform stack if you want to modify one part in a different state.++```css+.element {+ /* Base transform */+ transform: translate(100px, 0) rotate(45deg);+ /* Specify the identity for the scale property. */+ scale: 1;+}++@supports not (translate: 0px) {+ .element:hover {+ /* Fallback: Must repeat translate and rotate even if only scale changes */+ transform: translate(100px, 0) rotate(45deg) scale(1.1);+ }+}++@supports (translate: 0px) {+ .element:hover {+ /* Modern: Only declare the change */+ scale: 1.1;+ }+}+```diff --git a/skills/modern-web/guides/user-experience/interactive-content-reveal.md b/skills/modern-web/guides/user-experience/interactive-content-reveal.mdnew file mode 100644index 0000000..02bbff4--- /dev/null+++ b/skills/modern-web/guides/user-experience/interactive-content-reveal.md@@ -0,0 +1,116 @@+Add performant, interactive reveal effects to your site with CSS masks and registered custom properties. By using a radial gradient as a mask and registering its stop values, we can smoothly transition the entry and exit, while following a user's pointer with minimal JavaScript.++## Implementation++### 1. Register Custom Properties+To enable smooth interpolation of gradient stop values, you must register the variables using `@property`. This informs the browser's engine about the data type, allowing it to transition between values during updates.++```css+/* Register the spotlight inner and outer sizes to enable interpolation */+ @property --inner-size{+ syntax: "<length-percentage>";+ inherits: true;+ initial-value: 0px;+}+@property --outer-size{+ syntax: "<length-percentage>";+ inherits: true;+ initial-value: 0px;+}+```++The custom properties tracking the pointer position do not need to be transitioned, so it is not required to register them.++### 2. Define the Masking Layer+Apply the `mask-image` to the element you want to reveal. Use a `radial-gradient` that references the registered properties.++```css+.reveal-layer {+ /* Only transition the size properties, NOT the position variables */+ transition: --inner-size 0.2s ease-in-out, --outer-size 0.2s ease-in-out;++ /* The spotlight is defined by the transparent center of the mask */+ mask-image: radial-gradient(+ circle at var(--mouse-x) var(--mouse-y),+ black var(--inner-size, 0%),+ transparent var(--outer-size, 0%)+ );++ /* Ensure the mask doesn't repeat if the element is large */+ mask-repeat: no-repeat;++ /* Make the mask layer non-interactive */+ pointer-events: none;+}++/* Update the gradients stops on interaction */+.reveal-layer:hover {+ --inner-size: 100px;+ --outer-size: 120px;+}+```++### 3. Update Coordinates with JavaScript+Track the pointer position and update the CSS variables. Because the properties are registered and have a `transition` defined, the spotlight will move smoothly even if the pointer events are infrequent.++```javascript+const container = document.querySelector('.container');+// Store the container's bounding rect+let rect = container.getBoundingClientRect();+// Update the rect when the container is resized+const resizeObserver = new ResizeObserver(()=>{+ rect = container.getBoundingClientRect();+})+resizeObserver.observe(container);++container.addEventListener('pointermove', (e) => {+ // Calculate position as a percentage of the container.+ const x = ((e.clientX - rect.left) / rect.width) * 100;+ const y = ((e.clientY - rect.top) / rect.height) * 100;++ // Update the registered properties+ container.style.setProperty('--mouse-x', `${x}%`);+ container.style.setProperty('--mouse-y', `${y}%`);+});+```++### 4. Accessibility and Interaction+MANDATORY: Ensure the reveal effect does not interfere with content accessibility. Avoid using this effect for revealing essential content.++* **Pointer Events:** If the reveal layer is an overlay, set `pointer-events: none` to allow users to interact with buttons or links underneath.+* **Non-Pointer Inputs:** Consider disabling the effect for users without a pointer using the `@media (pointer: none)` media query, especially if the revealed content is critical.+* **Reduced Motion:** Respect user preferences for reduced motion by disabling transitions or the effect entirely.++```css+@media (prefers-reduced-motion: reduce) {+ .reveal-layer {+ transition: none;+ }+}+```++## Fallback strategies++Baseline status for Registered custom properties: Newly available. It's been Baseline since 2024-07-09.++### Non-registered Property Fallback+Browsers that support `mask-image` but not `@property` will still show the spotlight, but the movement will jump between on and off states because they cannot interpolate values inside a `radial-gradient`. Provide fallback values when using `var()`.++```css+.reveal-layer {+ mask-image: radial-gradient(+ circle at var(--mouse-x) var(--mouse-y),+ /* Use fallback values when using the `var()` function for browsers that don't get an initial value from the @property registration. */+ black var(--inner-size, 0%),+ transparent var(--outer-size, 0%)+ );+}+```++Baseline status for Masks: Newly available. It's been Baseline since 2023-12-07.++### Basic Mask Support++For browsers that do not support CSS masking at all:+1. **Prefixed property:** Use the `-webkit-mask-image` prefixed property for broader browser support.+2. **Progressive Enhancement:** Design the base state of the UI to be fully functional and legible without the reveal effect. This is useful when the effect is only adds visual flair, and not a requirement for reading content.diff --git a/skills/modern-web/guides/user-experience/interest-triggered-action-previews.md b/skills/modern-web/guides/user-experience/interest-triggered-action-previews.mdnew file mode 100644index 0000000..66bda5b--- /dev/null+++ b/skills/modern-web/guides/user-experience/interest-triggered-action-previews.md@@ -0,0 +1,74 @@+It can be beneficial to provide users a preview of their actions before they commit to them. Interest invokers are an experimental web platform feature that provides a declarative-based way of creating interest relationships between an interest source (i.e. a button or a link) and an interest target. Once the declarative relationship has been established there are a number of methods a developer can respond to based on interest and loss of interest using both CSS and JavaScript. For this use case, we can leverage the `interest` and `loseinterest` events to preview various effects for an interest target.++## How to implement++An interest relationship is created by setting the `interestfor` attribute on a button or link (i.e. the interest source). The attribute takes an ID reference to another element (i.e. the interest target). Interest invokers or sources can only have a single interest target, but an interest target can have multiple interest invokers.++```html+<!-- MANDATORY: interest relationships must be established with the `interestfor` attribute on a button or a link -->+<button interestfor="interestingElement" data-effect="A">Some effect</button>+<button interestfor="interestingElement" data-effect="B">Some other effect</button>+<div id="interestingElement">Something interesting</div>+```++For the sake of this use case, we can leverage the `interest` and `loseinterest` events to preview various effects for an interest target. Both of these events are `InterestEvent`s which has a `source` property which is the source of the interest (i.e. the element with the `interestfor` attribute).++```javascript+interestingElement.addEventListener("interest", event => {+ // Apply the preview based on `event.source`+ event.target.dataset.preview = event.source.dataset.effect;+});++interestingElement.addEventListener("loseinterest", event => {+ // Unapply the preview+ delete event.target.dataset.preview;+});+```++Active interest sources and targets can be selected with CSS using the `:interest-source` and `:interest-target` pseudo-selectors respectively.++```css+/* Styles to apply when the effect is being previewed */+:interest-source {}+:interest-target {}+```++The start and end delay for an interest invoker (i.e. the element with the `interestfor` attribute) can be set with the `interest-delay-start` and `interest-delay-end` CSS properties or the shorthand `interest-delay` property.++```css+[interestfor] {+ interest-delay-start: 0.2s;+ interest-delay-end: 0.1s;+}+```++### Fallback strategies++Interest invokers has limited availability.++Interest invokers must be conditionally polyfilled with the `interestfor` polyfill, available at https://github.com/mfreed7/interestfor or on NPM. Do prefer bundling the polyfill over using the CDN.++```html+<script type="module">+ if(!HTMLButtonElement.prototype.hasOwnProperty("interestForElement")){+ // CDN link only used for example, prefer bundling.+ await import("https://unpkg.com/interestfor@latest");+ }+</script>+```++When using the polyfill the CSS API changes slightly for the `:interest-source` and `:interest-target` pseudo-classes, as well as, the `interest-delay`, `interest-delay-start`, and `interest-delay-end` properties:++```css+/* Styles to apply when the effect is being previewed */+:is(:interest-source, .interest-source) {}+:is(:interest-target, .interest-target) {}++/* Adjust the start and end delay for interest invokers */+[interestfor] {+ --interest-delay-start: 0.2ms;+ interest-delay-start: 0.2ms;+ --interest-delay-end: 0.1ms;+ interest-delay-end: 0.1ms;+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/interest-triggered-tooltips.md b/skills/modern-web/guides/user-experience/interest-triggered-tooltips.mdnew file mode 100644index 0000000..51e616e--- /dev/null+++ b/skills/modern-web/guides/user-experience/interest-triggered-tooltips.md@@ -0,0 +1,112 @@+# Show a tooltip when hovering++Users expect to see additional related information without completely changing their context. Showing a tooltip when a user is interested in more information can be useful to provide definitions for a term, clarifying the action an icon-only button will take, or provide additional form field guidance.++## Creating the tooltip++You can create a popover with the required behavior by adding the `popover="hint"` attribute to a `<div>` or other semantically appropriate element. When the user opens the tooltip, this hides other `popover="hint"` tooltips, but doesn't hide `auto` or `manual` tooltips. It also handles dismissing nested tooltips.++It also provides light dismiss behavior, so when a user clicks or otherwise focuses outside of the popover, the popover is dismissed.++The tooltip element must have an `id` attribute with a unique value:++```html+<!-- MANDATORY: The tooltip container `<div>` must have a `popover` attribute.+ the value of `"hint"` ensures it can be "light dismissed". -->+<div popover="hint" id="tooltip">Tooltip content</div>+```++A user expresses interest in the additional information by hovering or focusing on an `<a>` or `<button>` element. The element must have an `interestfor` attribute that matches the `id` attribute of the tooltip.++```html+<!-- The `interestfor` attribute can be applied to a `<button>` element: -->+<button interestfor="tooltip">Tooltip trigger</button>++<!-- The `interestfor` attribute can also be applied to an `<a>` element: -->+<a interestfor="tooltip" href="">Tooltip trigger</a>+```++The trigger must have a visual indicator to indicate that there is additional information available by interacting with the trigger.++### Positioning the tooltip++The tooltip can be positioned using anchor positioning. When the tooltip is opened using `interestfor`, the trigger becomes an implicit anchor for the tooltip, meaning you don't have to add `anchor-name` or `position-anchor` CSS properties. However, to support browsers without anchor positioning you must use the anchor positioning polyfill, which has several limitations for popovers. **MANDATORY:** Implicit anchors are NOT supported by the polyfill, so YOU MUST explicitly set an `anchor-name` on the trigger and `position-anchor` on the popover.+++```css+/* MANDATORY: use explicit anchor names for compatibility with the polyfill */+button[interestfor="tooltip-dom"] {+ anchor-name: --tooltip-dom;+}+#tooltip-dom {+ position-anchor: --tooltip-dom;+}+```++Also, the polyfill does not support `position-area` on popovers, so **MANDATORY:** DO position using `anchor()` functions, and **YOU MUST** include a `position-try` fallback (e.g. `flip-block` or `flip-inline`).++```css+[popover]{+ /* MANDATORY: use anchor functions and a position-try fallback for the polyfill */+ top: anchor(bottom);+ left: anchor(center);+ position-try: flip-block;+ margin: unset;+}+```+++### Fallback strategies++Interest invokers has limited availability.++Interest invokers must be conditionally polyfilled with the `interestfor` polyfill, available at https://github.com/mfreed7/interestfor or on NPM. Do prefer bundling the polyfill over using the CDN.++```html+<script type="module">+ if(!HTMLButtonElement.prototype.hasOwnProperty("interestForElement")){+ // CDN link only used for example, prefer bundling.+ await import("https://unpkg.com/interestfor@latest");+ }+</script>+```++Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.+popover="hint" has limited availability.++Popover and popover hint must conditionally be polyfilled with the `@oddbird/popover-polyfill` polyfill. The hint behavior will not be polyfilled in browsers that support `popover` but not `popover="hint"`. For those browsers, a tooltip opened via focus may stay open when a second tooltip opened via hover.++```html+<script type="module">+ if(!HTMLElement.prototype.hasOwnProperty("popover")){+ await import("https://unpkg.com/@oddbird/popover-polyfill@latest");+ }+</script>+```++Anchor positioning has limited availability.++**MANDATORY:** To support browsers without anchor positioning, you MUST use the `@oddbird/css-anchor-positioning` polyfill. It does not support implicit anchors, so you MUST add anchor names to the trigger. Additionally, `position-area` is not supported on popovers by the polyfill, so you MUST use `anchor()` on the desired insets.++```html+<!-- MANDATORY: Conditionally install the anchor positioning polyfill -->+<script type="module">+ if (!("anchorName" in document.documentElement.style)) {+ await import("https://unpkg.com/@oddbird/css-anchor-positioning");+ }+</script>+```++```css+button[interestfor="tooltip-attrs"] {+ /* MANDATORY: Each trigger and popover pair must have a unique anchor name, referenced by `anchor-name` on the trigger and `position-anchor` on the popover. */+ anchor-name: --tooltip-attrs;+}+#tooltip-attrs {+ position-anchor: --tooltip-attrs;+ /* If using the anchor positioning polyfill with a popover, DO use `anchor()` functions, and not `position-area. */+ top: anchor(bottom);+ left: anchor(right);+ margin: unset;+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/light-dismiss-a-dialog.md b/skills/modern-web/guides/user-experience/light-dismiss-a-dialog.mdnew file mode 100644index 0000000..ed1d9b9--- /dev/null+++ b/skills/modern-web/guides/user-experience/light-dismiss-a-dialog.md@@ -0,0 +1,82 @@+Modern modal dialogs often support "light-dismiss," allowing users to close a dialog by clicking or tapping the backdrop (the area outside the dialog). The `closedby` attribute provides a declarative way to enable this behavior without custom JavaScript.++## Implementation++To enable light-dismiss:++1. Add `closedby="any"` to the `<dialog>` element.+2. Open the dialog using `dialog.showModal()`.++### Attribute Values++- `any`: Enables light-dismiss (clicking the backdrop), "close requests" (the `Esc` key), and developer mechanisms (e.g., `dialog.close()`).+- `closerequest`: Enables "close requests" and developer mechanisms only. This is the default for modal dialogs.+- `none`: Only developer mechanisms can close the dialog.++### Styling the Backdrop+When a dialog is opened as a modal using `showModal()`, the browser generates a `::backdrop` pseudo-element. This backdrop covers the entire viewport and sits directly behind the dialog.++```css+/* Style the backdrop to indicate the dialog is modal */+dialog::backdrop {+ background-color: rgba(0, 0, 0, 0.5);+ backdrop-filter: blur(2px); /* Optional: add blur for modern browsers */+}+```++## Example++```html+<!-- MANDATORY: Use closedby="any" to enable light-dismiss behavior -->+<dialog id="myDialog" closedby="any" aria-labelledby="dialogTitle">+ <form method="dialog">+ <h2 id="dialogTitle">Feedback</h2>+ <p>Click outside this box or press Esc to dismiss.</p>+ <button type="submit">Close</button>+ </form>+</dialog>++<button onclick="document.getElementById('myDialog').showModal()">Open Dialog</button>+```++## Constraints & Accessibility++- **MANDATORY**: Use `closedby="any"` to enable light-dismiss declaratively.+- **MANDATORY**: Always open modal dialogs with `showModal()`. This ensures the dialog is in the top layer, focus is trapped, and the `Esc` key is handled.+- **DO**: Use `aria-labelledby` or `aria-label` to provide an accessible name for the dialog.+- **DO NOT**: Use `closedby` for non-modal dialogs (opened with `show()`), as they do not have a backdrop and won't trigger light-dismiss.+- **DO NOT**: Use the `click` event for critical logic that should happen *before* closing; instead, listen for the `close` or `cancel` events.++## Fallback strategies++<dialog closedby> has limited availability.++**MANDATORY**: For browsers that do not yet support `closedby`, you **must** implement a fallback for light-dismiss by checking if a click occurred outside the dialog content's boundaries using the following script:++```javascript+const dialog = document.querySelector('dialog');++// Fallback for browsers without closedby support+if (!('closedBy' in HTMLDialogElement.prototype)) {+ dialog.addEventListener('click', (event) => {+ // 1. When clicking the backdrop, the event target is the dialog element itself.+ // Ignore clicks where the target is a child element inside the dialog.+ if (event.target !== dialog) return;++ // 2. Check if the click coordinates fall within the dialog's content box.+ // This distinguishes between a click on the backdrop vs a click on the dialog's background/padding.+ const rect = dialog.getBoundingClientRect();+ const isDialogContent = (+ rect.top <= event.clientY &&+ event.clientY <= rect.top + rect.height &&+ rect.left <= event.clientX &&+ event.clientX <= rect.left + rect.width+ );++ if (isDialogContent) return;++ // 3. Since the click was outside the content area (on the backdrop), manually close the dialog.+ dialog.close();+ });+}+```diff --git a/skills/modern-web/guides/user-experience/light-dismiss-content-overlay.md b/skills/modern-web/guides/user-experience/light-dismiss-content-overlay.mdnew file mode 100644index 0000000..7369246--- /dev/null+++ b/skills/modern-web/guides/user-experience/light-dismiss-content-overlay.md@@ -0,0 +1,162 @@+# Creating Swipeable Layered Navigation++Modern mobile navigation requires a "swipe to close" gesture. While the native `popover` API handles Top Layer promotion and accessibility well, it doesn't natively support swipe gestures.++We can achieve the best of both worlds by combining `popover="manual"` with a CSS Scroll Snap container, and inerting the page with JavaScript.++### Core Concept++1. **The Popover:** Acts as the top-layer container. Use `popover="manual"` to fully control its visibility and lifecycle. While `popover="auto"` provides native light dismissal, it actively conflicts with this scroll-snap gesture pattern (native backdrop clicks fail due to the element's 100vw bounding box, and native `Escape` dismissal instantly hides the menu abruptly without animation).+2. **The Scroll Container:** Inside the popover, we create a horizontally scrolling container with `scroll-snap-type: x mandatory`.+3. **The Drawer & Ghost:**+ - The **Drawer** is the first snap point (visible when scrolled to 0).+ - A **Ghost Element** (spacer) is the second snap point (visible when scrolled to the menu width).+4. **The Backdrop:** Use the native `::backdrop` pseudo-element for the dimmed background. By linking its opacity to the scroll position using CSS custom properties via a `scroll` event listener, the fade feels fully organic with the swipe gesture.+5. **Gesture Logic:** "Swiping left" naturally scrolls the container from the Drawer (0) to the Ghost (Width). This feels like pushing the menu away.++### Implementation Guidelines++* Use `popover="manual"` to ensure the menu appears above all other content (Top Layer), avoiding the strict native dismiss logic of `auto`.+* Rely on CSS Scroll Snap for gesture physics. It provides a native, smooth 1:1 touch response.+* Use the `scrollend` event (or a scroll polling fallback) to synchronize the JavaScript state (open/closed) with the physical scroll position.+* Tie the `::backdrop` opacity directly to the scroll position via CSS custom properties. It maps exactly 1-to-1 without artificial delays.+* **MANDATORY**: Manually manage the `inert` attribute on your main content. When the menu is open, the main content MUST be inert. When closed (scrolled away), it must be interactive.+* Manually handle backdrop clicks and the `Escape` key. Because we use `popover="manual"`, you must provide the logic to trigger the smooth scroll-out animation when the user intentionally dismisses the menu outside of swiping.++### Recommended Implementation++Here is a minimal example showing how to combine Popover and Scroll Snap for swipeable overlays.++**HTML Structure:**+```html+<!-- MANDATORY: Use popover="manual" to control lifecycle and avoid conflicts with gestures -->+<div id="swipe-overlay" popover="manual">+ <!-- The actual menu/drawer -->+ <nav class="drawer" id="side-nav">+ <!-- Menu items go here -->+ <button class="close-btn">Close</button>+ </nav>+ <!-- A ghost spacer is needed as the second snap point. You can use a real element or a pseudo-element like ::after -->+</div>+```++**Key CSS:**+```css+#swipe-overlay {+ border: none;+ padding: 0;+ margin: 0;+ width: 100vw;+ height: 100vh;+ background: transparent;++ /* Enable horizontal scroll snap */+ overflow-x: auto;+ scroll-snap-type: x mandatory;+ overscroll-behavior-x: contain;+ scroll-behavior: smooth;+}++#swipe-overlay:popover-open {+ display: flex;+}++.drawer {+ width: 280px; /* Or any width less than 100vw */+ height: 100%;+ flex-shrink: 0;+ scroll-snap-align: start; /* Snap point 1 (Open) */+}++/* Ghost Spacer using pseudo-element */+#swipe-overlay::after {+ content: '';+ flex: 0 0 100vw;+ height: 100%;+ scroll-snap-align: start; /* Snap point 2 (Closed) */+}++/* Link backdrop opacity to a CSS variable */+#swipe-overlay::backdrop {+ background-color: rgba(0, 0, 0, var(--backdrop-alpha, 0));+}+```++**Key JavaScript:**+```javascript+const overlay = document.getElementById('swipe-overlay');+const nav = document.getElementById('side-nav');+const main = document.getElementById('main-content');+let isAnimating = false;++function openMenu() {+ overlay.showPopover();+ // Snap to ghost spacer initially to animate in+ overlay.scrollTo({ left: nav.offsetWidth, behavior: 'instant' });+ main.setAttribute('inert', '');+ isAnimating = true;++ // Force layout and animate to drawer open position+ requestAnimationFrame(() => {+ overlay.scrollTo({ left: 0, behavior: 'smooth' });+ setTimeout(() => isAnimating = false, 500);+ });+}++function closeMenu() {+ // Animate to ghost spacer, triggering scrollend to hide popover+ overlay.scrollTo({ left: nav.offsetWidth, behavior: 'smooth' });+}++// Live Backdrop Update (Immediate feedback during swipe)+overlay.addEventListener('scroll', () => {+ const width = nav.offsetWidth;+ // Calculate how far we have scrolled relative to the menu width+ const fraction = 1 - (overlay.scrollLeft / width);+ // Map this to a backdrop opacity (max 0.4 in this example)+ overlay.style.setProperty('--backdrop-alpha', Math.max(0, fraction * 0.4));+}, { passive: true }); // Passive listener for performance++// Handle gestures completing+overlay.addEventListener('scrollend', () => {+ if (isAnimating) return; // Prevent early closure during opening animation++ const width = nav.offsetWidth;+ // If we scrolled past half the width, close the menu+ if (overlay.scrollLeft > (width / 2)) {+ if (overlay.matches(':popover-open')) {+ overlay.hidePopover();+ }+ main.removeAttribute('inert');+ } else {+ // Otherwise keep it open and ensure main content is inert+ main.setAttribute('inert', '');+ }+});+```++### Fallback strategies++#### popover++Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.++The Popover API is not supported in older browsers. Without it, the menu cannot be promoted to the Top Layer, which means it won't naturally sit above all other page content and won't receive the `::backdrop` pseudo-element.++* **Guidance:** For browsers that do not support `popover`, fall back to a `<div>` positioned with `position: fixed` and a high `z-index`. Manually manage focus trapping and the backdrop overlay using JavaScript. Replace any `::backdrop` styles with a separate fixed-position overlay element and toggle visibility using a class. Check support with `'popover' in HTMLElement.prototype`.++#### scroll-snap++Baseline status for Scroll snap: Widely available. It's been Baseline since 2020-01-15.++CSS Scroll Snap is widely supported, but in environments where it is absent, the scroll container will still function — the drawer will open and close — but the snap-to-position physics will be missing, leaving the menu in an indeterminate in-between position after a swipe.++* **Guidance:** Listen for the `scrollend` event and programmatically snap the container to the nearest position (0 or the full drawer width) using `scrollTo({ left: targetX, behavior: 'smooth' })` if `scroll-snap-type` is not supported. Detect support with `CSS.supports('scroll-snap-type', 'x mandatory')`.++#### inert++Baseline status for inert: Widely available. It's been Baseline since 2023-04-11.++The `inert` attribute is broadly supported in modern browsers. In browsers that do not support it, the main page content will remain interactive while the menu is open, creating a keyboard trap and accessibility issue.++* **Guidance:** Use the `inert` polyfill to replicate the behavior in unsupported browsers. Conditionally load it only when needed: `if (!('inert' in HTMLElement.prototype)) { await import('path/to/inert-polyfill.js'); }`. As a manual fallback, set `aria-hidden="true"` on the main content and apply `tabindex="-1"` to all focusable descendants while the menu is open, reversing both on close.diff --git a/skills/modern-web/guides/user-experience/manage-recurring-intervals.md b/skills/modern-web/guides/user-experience/manage-recurring-intervals.mdnew file mode 100644index 0000000..186239d--- /dev/null+++ b/skills/modern-web/guides/user-experience/manage-recurring-intervals.md@@ -0,0 +1,71 @@+# Managing Recurring Intervals with Temporal++Calculating recurring intervals, such as subscription billing cycles or payroll periods, has historically been error-prone with the legacy `Date` object. Adding a month to a date like January 31st is ambiguous (should it be February 28th/29th or March 3rd?).++The `Temporal` API provides a clean solution with `Temporal.PlainDate` and its `.add()` method, which handles month-end transitions predictably using configurable overflow strategies.++## How to Implement++1. **MANDATORY:** **Parse the starting date**: Use `Temporal.PlainDate.from()` to create a date object.+2. **MANDATORY:** **Add the duration**: Use the `.add()` method with a duration object (e.g., `{ months: 1 }`).+3. **OPTIONAL:** **Specify overflow behavior**: Use the `overflow` option to control how invalid dates (like Feb 31) are handled.+ - `'constrain'` (default): Clamps to the last valid day of the month.+ - `'reject'`: Throws a `RangeError`.++### Example: Subscription Billing Cycle++```javascript+// 1. Parse the start date (e.g., billing starts on Jan 31st)+const startDate = Temporal.PlainDate.from('2024-01-31');++// 2. Add 1 month with default 'constrain' overflow+// Jan 31 + 1 month -> Feb 29 (2024 is a leap year)+const nextBillingDate = startDate.add({ months: 1 });+console.log(`Next billing: ${nextBillingDate.toString()}`); // 2024-02-29++// 3. Add 1 month to Feb 29+// Feb 29 + 1 month -> Mar 29+// Note: Day is preserved if valid, otherwise constrained.+const thirdBillingDate = nextBillingDate.add({ months: 1 });+console.log(`Third billing: ${thirdBillingDate.toString()}`); // 2024-03-29++// Example with 'reject' strategy+try {+ // Jan 31 + 1 month with 'reject' throws because Feb 31 is invalid+ const invalidDate = startDate.add({ months: 1 }, { overflow: 'reject' });+} catch (e) {+ console.log("Caught expected error:", e.name); // RangeError+}+```++## Strategic Implementation & Best Practices++- **DO** use `Temporal.PlainDate` for calculations that do not depend on specific times or time zones (like calendar dates or billing cycles).+- **DO** understand the default `constrain` behavior. It is usually what users expect for billing (e.g., Jan 31 -> Feb 28/29 -> Mar 28/29).+- **DO NOT** modify instances directly; `Temporal` objects are **immutable**. Operations return a new instance.+- **DO** use `overflow: 'reject'` if you need to enforce that the resulting date must exist in the calendar and handle failures explicitly.++### Fallback strategies++Temporal has limited availability.++For browsers that do not yet support the native `Temporal` API, use feature detection and a polyfill. The standard reference polyfill is `@js-temporal/polyfill`.++```javascript+// Check if Temporal is supported natively+(async () => {+ if (typeof Temporal === 'undefined') {+ // Load the polyfill conditionally+ const module = await import("https://esm.sh/@js-temporal/polyfill");+ globalThis.Temporal = module.Temporal;+ // Extend Date.prototype if needed+ Date.prototype.toTemporalInstant = module.toTemporalInstant;+ initializeApp();+ }+})();++function initializeApp() {+ const date = Temporal.PlainDate.from('2024-01-31');+ console.log(date.add({ months: 1 }).toString());+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/model-partial-time-concepts.md b/skills/modern-web/guides/user-experience/model-partial-time-concepts.mdnew file mode 100644index 0000000..8294c38--- /dev/null+++ b/skills/modern-web/guides/user-experience/model-partial-time-concepts.md@@ -0,0 +1,96 @@+# Modeling Partial Time Concepts with Temporal++Modeling date concepts that lack a full calendar date—such as credit card expirations, annual renewals, or daily alarms—has historically been error-prone with the legacy `Date` object. Developers often resort to using arbitrary days (like the 1st of the month) or parsing strings, leading to "day leakage" or incorrect calculations due to leap years and varying month lengths.++The `Temporal` API provides dedicated types for these partial concepts: `Temporal.PlainYearMonth`, `Temporal.PlainMonthDay`, and `Temporal.PlainTime`. These types ensure precision and avoid leaking irrelevant date components.++## Implementation Examples++### Monthly Expirations (Credit Cards, Billing Cycles)+Use `Temporal.PlainYearMonth` to represent a year and a month.++```javascript+// Create a PlainYearMonth from values+// Use explicit calendar to avoid mismatch issues in polyfill environments+const expiry = Temporal.PlainYearMonth.from({ year: 2027, month: 12, calendar: 'iso8601' });++// Get the current year/month+const currentMonth = Temporal.Now.plainDateISO().toPlainYearMonth();++// Calculate duration until expiry+// largestUnit ensures the difference is expressed in years if applicable+const duration = currentMonth.until(expiry, { largestUnit: 'years' });++if (duration.sign < 0) {+ console.log("Expired");+} else if (duration.sign === 0) {+ console.log("Expires this month");+} else {+ console.log(`Expires in ${duration.years} years and ${duration.months} months`);+}+```++### Annual Recurring Dates (Birthdays, Renewals)+Use `Temporal.PlainMonthDay` to represent a month and a day without a year.++```javascript+// Create a PlainMonthDay for an annual event+// Include explicit calendar for polyfill safety+const birthday = Temporal.PlainMonthDay.from({ month: 10, day: 31, calendar: 'iso8601' });++// Check if it matches today's date components+const today = Temporal.Now.plainDateISO();+const isBirthdayToday = birthday.equals(today.toPlainMonthDay());++// To perform arithmetic (like days until next occurrence), convert to a full PlainDate+// by providing a specific year.+const birthdayThisYear = birthday.toPlainDate({ year: today.year });+```++### Wall-Clock Time (Alarms, Store Hours)+Use `Temporal.PlainTime` to represent a time of day without a date.++```javascript+// Create a PlainTime from a string+const alarmTime = Temporal.PlainTime.from("08:00:00");++// Add a duration to a PlainTime+const snoozedTime = alarmTime.add({ minutes: 10 });++console.log(`Original alarm: ${alarmTime.toString()}`);+console.log(`Snoozed alarm: ${snoozedTime.toString()}`);+```++## Strategic Implementation & Best Practices++- **DO** use `Temporal.PlainYearMonth` for values that only specify a month and year (like credit card expiry) to avoid leaking arbitrary day values.+- **DO** use `Temporal.PlainMonthDay` for annual events that ignore the year (like birthdays or anniversaries).+- **DO** use `Temporal.PlainTime` for daily schedules or alarms that are independent of the date.+- **DO NOT** try to perform arithmetic directly on `PlainMonthDay`. Convert it to a `PlainDate` first by providing a year, as the length of months varies by year.+- **DO** use explicit calendar properties (like `calendar: 'iso8601'`) when creating instances from objects to ensure safety across polyfill implementations.++## Fallback Strategy++Temporal has limited availability.++For environments without native `Temporal` support, use feature detection and load the `@js-temporal/polyfill`.++```javascript+// Check if Temporal is supported natively+(async () => {+ if (typeof Temporal === 'undefined') {+ // Load the polyfill conditionally+ const module = await import("https://esm.sh/@js-temporal/polyfill");+ globalThis.Temporal = module.Temporal;+ // Extend Date.prototype if needed+ Date.prototype.toTemporalInstant = module.toTemporalInstant;+ initializeApp();+ }+})();++function initializeApp() {+ // Application logic using Temporal+ const time = Temporal.PlainTime.from("12:00:00");+ console.log(`Initialized at ${time.toString()}`);+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/move-dom-element-without-losing-state.md b/skills/modern-web/guides/user-experience/move-dom-element-without-losing-state.mdnew file mode 100644index 0000000..c650206--- /dev/null+++ b/skills/modern-web/guides/user-experience/move-dom-element-without-losing-state.md@@ -0,0 +1,55 @@+When reparenting DOM elements using traditional methods like `appendChild()` or `insertBefore()`, the browser implicitly removes the element from the DOM and then inserts it into its new location. This "remove and insert" operation resets many internal states, causing `<iframe>` elements to reload, CSS animations to restart, and input fields to lose focus.++To move an element while preserving its state, use the `moveBefore()` API. This method performs an atomic move, completely bypassing the removal and insertion steps.++### Moving an element with state++Use `moveBefore()` exactly as you would use `insertBefore()`. It requires two arguments: the node to move, and a reference node to insert before (or `null` to append to the end of the new parent).++```javascript+const newParent = document.getElementById('new-parent');+const elementWithState = document.getElementById('iframe-or-focused-input');++// MANDATORY: Use moveBefore to preserve state.+// Passing null as the second argument appends the element to the end of newParent.+newParent.moveBefore(elementWithState, null);+```++### Moving custom elements (Web Components)++If you are moving custom elements using `moveBefore()`, their `connectedCallback` and `disconnectedCallback` lifecycle methods will **not** be fired.++If your custom element needs to perform specific logic when moved, implement the `connectedMoveCallback()` method inside the custom element definition.++```javascript+class MyCustomElement extends HTMLElement {+ connectedCallback() {+ // Runs on initial insertion.+ }++ connectedMoveCallback() {+ // Runs when the element is moved via moveBefore().+ // Use this to update state that depends on the new DOM location.+ }+}+```++### Fallback strategies++moveBefore() has limited availability.++Since `moveBefore()` is a progressive enhancement, you MUST use feature detection before calling it, falling back to traditional `insertBefore()` or `appendChild()` operations for older browsers.++```javascript+const targetParent = document.getElementById('target-container');+const nodeToMove = document.getElementById('moving-element');++// Check if moveBefore is supported on the Element prototype+if ('moveBefore' in Element.prototype) {+ targetParent.moveBefore(nodeToMove, null);+} else {+ // Fallback: traditional move.+ // Note: This WILL reset <iframe>, animation, and focus state in unsupported browsers.+ targetParent.insertBefore(nodeToMove, null);+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/parallax-scroll-effects.md b/skills/modern-web/guides/user-experience/parallax-scroll-effects.mdnew file mode 100644index 0000000..412fa4f--- /dev/null+++ b/skills/modern-web/guides/user-experience/parallax-scroll-effects.md@@ -0,0 +1,228 @@+# Build a Parallax Effect on Scroll++A parallax effect on scroll is a visual technique where different layers of content move at varying speeds as the user scrolls down a page. This creates an illusion of depth, with foreground elements appearing to move faster than the background elements, resulting in an engaging and immersive browsing experience. This effect is best achieved using CSS Scroll-Driven Animations, which allow you to link animations to the scroll position of a container.++## How to implement++Here’s how to create a basic parallax effect:++1. **Create a wrapper element:** This element simply groups all the layers of the parallax effect together. It is not the scrollable element, so its overflow should be clipped. Also give it a `height` that matches the height of one of the layers of the parallax effect.++ ```html+ <div class="wrapper">+ …+ </div>+ ```++ ```css+ .wrapper {+ overflow: clip;+ height: 100vh; /* Height of one of the layers of the parallax */+ }+ ```++2. **Declare the layers:** Inside the wrapper, add the individual layers that will move at different speeds.++ ```html+ <div class="wrapper">+ <div class="layer">LAYER 0</div>+ <div class="layer">LAYER 1</div>+ <div class="layer">LAYER 2</div>+ …+ </div>+ ```++3. **Add a translate animation:** Define a CSS animation that changes the `transform` property of the layers. For a parallax effect, you'll typically use `translateY` to move the layers vertically.++ ```css+ @keyframes parallax {+ from {+ transform: translateY(700px);+ }+ }+ ```++4. **Set up the `view-timeline`:** To link the animation to the scroll position, create a `view-timeline` on the wrapper element and then apply it to the layers.++ ```css+ .wrapper {+ view-timeline: --wrapper;+ }++ .layer {+ animation: parallax linear both;+ animation-timeline: --wrapper;+ }+ ```++5. **Stagger the animations:** To make the layers move at different speeds, you can use one of two main approaches: **staggering in the keyframes**, or **staggering the `animation-range`**.++ Both of these approaches can use hardcoded values, or can use the `sibling-index()`/`sibling-count()` implementation. The hardcoded values are easiest and also useful when having only a limited amount of layers. The `sibling-index()`/`sibling-count()` implementation is handy when you have many layers.++ * **Staggering in the keyframes:**++ Using **hardcoded values**, you can define a custom property for each layer to manually control its parallax offset.++ ```css+ .layer:nth-child(1) { --offset: 100px; }+ .layer:nth-child(2) { --offset: 200px; }+ .layer:nth-child(3) { --offset: 300px; }++ @keyframes parallax {+ from {+ transform: translateY(var(--offset));+ }+ }+ ```++ Using **`sibling-index()`**, let the `sibling-index()` function return the index of a child element amongst its siblings to automatically calculate the staggered effect.++ ```css+ @keyframes parallax {+ from {+ transform: translateY(calc(100px * sibling-index()));+ }+ }+ ```++ * **Staggering the `animation-range`:**++ Using **hardcoded values**, you can explicitly define the boundaries of the `animation-range` on each layer individually.++ ```css+ .layer:nth-child(1) { animation-range: entry 25% exit 50%; }+ .layer:nth-child(2) { animation-range: entry 25% exit 75%; }+ .layer:nth-child(3) { animation-range: entry 25% exit 100%; }+ ```++ Using **`sibling-index()` and `sibling-count()`**, you can calculate the range mathematically based on the total number of layers (`sibling-count()`).++ ```css+ .layer {+ animation-range: entry 25% exit calc(100% / sibling-count() * sibling-index());+ }+ ```++## Example code++```css+@keyframes parallax {+ from {+ transform: translateY(calc(100px * sibling-index()));+ }+}++.wrapper {+ view-timeline: --wrapper;+}++.layer {+ animation: parallax linear both;+ animation-timeline: --wrapper;+}++@media (prefers-reduced-motion: reduce) {+ .layer {+ animation: none;+ }+}+```++Alternatively, you can use the `animation-range` property to achieve a similar effect:++```css+@keyframes parallax {+ from {+ transform: translateY(700px);+ }+}++.wrapper {+ view-timeline: --wrapper;+}++.layer {+ animation: parallax linear both;+ animation-timeline: --wrapper;+ animation-range: entry 25% exit calc(100% / sibling-count() * sibling-index());+}++@media (prefers-reduced-motion: reduce) {+ .layer {+ animation: none;+ }+}+```++## Best Practices++When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:++- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: view()) and (animation-range: entry))` to check for support and provide a fallback for browsers that don't support it.+ - The `(animation-range: entry)` check **MUST** be included here, to filter out browsers with only partial support.+ - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.+ - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.+- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.+- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.+- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.++As for setting the `animation-range`:++- **DO** give all layers the same start offset, e.g. `entry 25%`+- **DO** give all layers a different end offset that uses `sibling-count()` and `sibling-index()` to distribute the offsets, e.g. `exit calc(100% / sibling-count() * sibling-index())`.+++## Browser support and fallback strategies++Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.++For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).++In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.++Note that not every effect can be recreated using the fallbacks approach.++For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of the `.wrapper` element and updates the `transform` property of the layers based on the scroll position.++```js+// Fallback for browsers that don't support scroll-driven animations+if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {+ const wrapper = document.querySelector('.wrapper');+ const layers = document.querySelectorAll('.layer');++ const observer = new IntersectionObserver((entries) => {+ entries.forEach(entry => {+ if (entry.isIntersecting) {+ window.addEventListener('scroll', onScroll);+ } else {+ window.removeEventListener('scroll', onScroll);+ }+ });+ }, { threshold: 0 });++ observer.observe(wrapper);++ function onScroll() {+ const scrollY = window.scrollY;+ const wrapperRect = wrapper.getBoundingClientRect();+ const wrapperTop = wrapperRect.top + scrollY;+ const wrapperHeight = wrapperRect.height;+ const windowHeight = window.innerHeight;++ if (scrollY >= wrapperTop - windowHeight && scrollY <= wrapperTop + wrapperHeight) {+ const scrollPercent = (scrollY - (wrapperTop - windowHeight)) / (wrapperHeight + windowHeight);++ layers.forEach((layer, index) => {+ // This matches the effect as defined in the CSS example above.+ // Customize this further if needed.+ const initialTranslateY = 100 * index;+ const translateY = initialTranslateY * (1 - scrollPercent);+ layer.style.transform = `translateY(${translateY}px)`;+ });+ }+ }++ // Trigger onScroll once to set initial positions+ onScroll();+}+```diff --git a/skills/modern-web/guides/user-experience/persistent-app-tours.md b/skills/modern-web/guides/user-experience/persistent-app-tours.mdnew file mode 100644index 0000000..e0d606f--- /dev/null+++ b/skills/modern-web/guides/user-experience/persistent-app-tours.md@@ -0,0 +1,106 @@+# Creating Persistent App Tours++Onboarding tours require overlays that persist while users interact with the highlighted features. Unlike auto popovers, manual popovers do not close when the user clicks elsewhere on the page. Combining `popover="manual"` with CSS Anchor Positioning allows you to create non-modal, tethered tour steps.++### Recommended Implementation++#### HTML+```html+<div id="feature-target">Highlight this feature</div>++<div id="tour-step" popover="manual">+ <h3>Step 1</h3>+ <p>Learn how to use this feature.</p>+ <button popovertarget="tour-step" popovertargetaction="hide">Got it</button>+</div>+```++#### CSS+```css+#feature-target {+ anchor-name: --feature-target;+}++#tour-step {+ popover: manual;+ position-anchor: --feature-target;+ position-area: right center;+ inset: auto;+ margin: 1rem;+ padding: 1rem;+ border: 1px solid blue;+ border-radius: 0.5rem;+ background: aliceblue;+}+```++#### JavaScript+```javascript+document.getElementById('tour-step').showPopover();+```++### Implementation Guidelines++* **MANDATORY:** Use `popover="manual"` to prevent the tour step from closing accidentally during user interaction.+* **DO** use CSS Anchor Positioning to tether the tour step to the specific feature being explained.+* **DO** provide an explicit "Close" or "Next" button within the popover that uses `popovertargetaction="hide"`.++### Fallback strategies++#### popover++Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.++If the browser does not support Popover, use the `@oddbird/popover-polyfill`:++```html+<script type="module">+ if (!HTMLElement.prototype.hasOwnProperty('popover')) {+ await import('https://unpkg.com/@oddbird/popover-polyfill');+ }+</script>+```++Alternatively, for legacy support without a polyfill, use `position: fixed` and manually calculate coordinates via JavaScript `getBoundingClientRect()`.++#### anchor-positioning++Anchor positioning has limited availability.++To support browsers without anchor positioning, you can choose between using a polyfill or a pure CSS fallback.++##### Option 1: Polyfill Fallback+The `@oddbird/css-anchor-positioning` polyfill can be used to emulate anchor positioning. It does not support implicit anchors, so you MUST add explicit anchor names to the trigger. Additionally, `position-area` is not supported on popovers by the polyfill, so you MUST use `anchor()` on the desired insets instead of `position-area`.++```html+<script type="module">+ if (!CSS.supports('anchor-name: --foo')) {+ await import("https://unpkg.com/@oddbird/css-anchor-positioning");+ }+</script>+```++```css+#tour-step {+ /* If using the anchor positioning polyfill with a popover, DO use `anchor()` functions instead of `position-area`. */+ left: anchor(right);+ top: anchor(top);+}+```++##### Option 2: Non-Polyfill CSS Fallback+If you prefer not to use a polyfill, you can default the tooltip to a fixed position at the bottom of the viewport using `@supports not`.++```css+@supports not (anchor-name: --foo) {+ #tour-step {+ position: fixed;+ bottom: 0;+ left: 0;+ right: 0;+ width: 100%;+ margin: 0;+ border-radius: 0;+ }+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/persistent-toast-notifications.md b/skills/modern-web/guides/user-experience/persistent-toast-notifications.mdnew file mode 100644index 0000000..51d8492--- /dev/null+++ b/skills/modern-web/guides/user-experience/persistent-toast-notifications.md@@ -0,0 +1,30 @@+# Creating Toast Notifications++Toast notifications are transient status messages. Unlike menus, they should not close when a user interacts with other parts of the page. The popover="manual" state is ideal because it lacks "light-dismiss" behavior and allows multiple notifications to coexist.++### Implementation Guidelines++* **MANDATORY:** Use popover="manual" so the notification stays visible until explicitly closed or timed out by a script.+* **DO** use a container to manage the stacking of multiple toasts. Since popovers in the Top Layer ignore parent z-index, you must position them individually or within a common layout group.+* **DO** use sibling-index() to add margin between toast notifications so that items lower in the stack are visible.+* **DO** provide an explicit "Close" button within the toast using popovertargetaction="hide".+* **DO** use JavaScript for auto-dismissal timers (e.g., calling hidePopover() after 3000ms).+* **DO** utilize transition-behavior: allow-discrete to animate the entry and exit from the Top Layer.++### Fallback Strategies++#### popover++* **Guidance:** Use the [Popover Polyfill](https://github.com/oddbird/popover-polyfill). For legacy browsers, fall back to a fixed-position div with a high z-index.++#### sibling-index()++* **Guidance:** If sibling-index() is not supported, use the `+` operator to add margin manually. I.e. `popover + popover { margin-top: 1rem }`++#### anchor-positioning++* **Guidance:** Use the [CSS Anchor Positioning Polyfill](https://github.com/oddbird/css-anchor-positioning). For a non-polyfill fallback, default the tooltip to a fixed position at the bottom of the viewport using `@supports not (anchor-name: --foo)`.++#### transition-behavior++* **Guidance:** If transition-behavior is not supported, use JavaScript to add animation via classes as the toast element transitions in and out.\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/persistent-top-layer-ui.md b/skills/modern-web/guides/user-experience/persistent-top-layer-ui.mdnew file mode 100644index 0000000..318a1d7--- /dev/null+++ b/skills/modern-web/guides/user-experience/persistent-top-layer-ui.md@@ -0,0 +1,46 @@+When moving an open `<dialog>`, `popover`, or fullscreen element in the DOM using traditional methods like `appendChild()` or `insertBefore()`, the browser implicitly removes the element from the DOM and re-inserts it. This removal resets the state, causing open modals, popovers, and fullscreen elements to close abruptly.++To reparent top-layer elements without interrupting the user experience or closing them, use the atomic `moveBefore()` API instead.++### Reparenting open top-layer elements++`moveBefore()` takes two arguments: the node to move, and a reference node to insert before (or `null` to append to the end of the new parent).++```javascript+const newParent = document.getElementById('new-container');+const dialogElement = document.getElementById('my-dialog');++// MANDATORY: Use moveBefore to ensure the <dialog> or popover stays open.+// Passing null appends it to the end of newParent.+newParent.moveBefore(dialogElement, null);+```++### Fallback strategies++moveBefore() has limited availability.++Since `moveBefore()` is a progressive enhancement, you MUST use feature detection before calling it. For older browsers, you will have to fallback to traditional reparenting.++**MANDATORY**: For `<dialog>` elements in unsupported browsers, the traditional move will close the dialog. If you need it to remain open, you must manually re-open it after the move.++```javascript+const targetParent = document.getElementById('target-container');+const popoverOrDialog = document.getElementById('my-top-layer-element');++// Check if moveBefore is supported+if ('moveBefore' in Element.prototype) {+ targetParent.moveBefore(popoverOrDialog, null);+} else {+ // Fallback: traditional move.+ // Note: This WILL close <dialog>, popover, and fullscreen elements.+ const wasOpen = popoverOrDialog.hasAttribute('open') || popoverOrDialog.matches(':popover-open');+ targetParent.insertBefore(popoverOrDialog, null);++ // Manually restore state if possible+ if (wasOpen && typeof popoverOrDialog.showModal === 'function') {+ popoverOrDialog.showModal();+ } else if (wasOpen && typeof popoverOrDialog.showPopover === 'function') {+ popoverOrDialog.showPopover();+ }+}+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/physics-based-easing.md b/skills/modern-web/guides/user-experience/physics-based-easing.mdnew file mode 100644index 0000000..1e307ff--- /dev/null+++ b/skills/modern-web/guides/user-experience/physics-based-easing.md@@ -0,0 +1,117 @@+Traditional CSS easing functions like `ease-in` or `cubic-bezier()` are limited to simple curves, making it impossible to create complex physics-based effects like bounces or springs. The `linear()` timing function solves this by allowing you to provide a series of stops that can approximate complex curves. Transitions and animations are interpolated based on straight lines between the stops, but within enough stops, it can appear smooth.++### Implementation Steps++1. **Generate the curve stops:**+ Manually plotting dozens of points for a spring or bounce is impractical. Use a timing function from an external library, or use a tool to convert an existing JavaScript easing function or an SVG path into the `linear()` syntax. Optional: store these timing functions as CSS custom properties for reuse throughout your site.+2. **Define the timing function:**+ Apply the generated stops to the `transition-timing-function` or `animation-timing-function` property, or through the `transition` or `animation` shorthands.+3. **Adjust the duration:**+ Unlike JavaScript physics engines where duration is derived from physical properties (mass, stiffness), CSS still requires a fixed `duration`. You may need to adjust the duration to get the intended effect.++### Example: Spring Easing++This example shows how to use a custom `linear()` function to create a spring effect that overshoots the target value before settling.++```css+.spring {+ /* Define the physics-based easing as a reusable variable */+ --spring-easing: linear(0, 0.016 0.5%, 0.06 1%, 0.226 2%, 1.116 5.4%, 1.375 6.6%, 1.527 7.7%, 1.565 8.2%, 1.585 8.8%, 1.581 9.3%, 1.559 9.8%, 1.458 10.9%, 0.937 14.3%, 0.784 15.5%, 0.693 16.6%, 0.67 17.1%, 0.657 17.7%, 0.671 18.7%, 0.729 19.8%, 1.042 23.3%, 1.13 24.5%, 1.182 25.6%, 1.201 26.7%, 1.192 27.7%, 1.156 28.8%, 0.977 32.2%, 0.925 33.4%, 0.894 34.5%, 0.882 35.6%, 0.887 36.6%, 0.907 37.7%, 1.045 42.4%, 1.069 44.5%, 1.059 46.3%, 0.979 50.9%, 0.96 53.4%, 0.966 55.3%, 1.013 59.9%, 1.024 62.3%, 0.986 71.2%, 1.008 79.9%, 0.995 88.9%, 1);+++ /* Apply the easing with a duration that fits the spring's complexity */+ /* MANDATORY: Always include a duration; linear() does not calculate it automatically */+ transition: scale 0.8s var(--spring-easing);+}++.spring:hover {+ scale: 1.2;+}+```+### Example: Bounce Easing++This example shows how to use a custom `linear()` function to create a bounce effect.++```css+.bounce {+ /* Define the physics-based easing as a reusable variable */+ --bounce-easing: linear(0, 0.214 14.7%, 0.386 23.7%, 0.598 31.9%, 0.999 44.7%, 0.807 52.6%, 0.762 56%, 0.747 59.4%, 0.758 62.4%, 0.793 65.6%, 0.999 77.4%, 0.961 81.2%, 0.949 84.8%, 0.956 88%, 0.993 95.5%, 1);+++ /* Apply the easing with a duration that fits the bounce's complexity */+ /* MANDATORY: Always include a duration; linear() does not calculate it automatically */+ transition: scale 0.4s var(--bounce-easing);+}++.bounce:hover {+ scale: 1.2;+}+```++### Key Considerations++* **Performance:** For the smoothest physics-based animations, apply `linear()` to properties that run on a separate thread, such as `transform` and `opacity`.+* **Precision vs. Payload:** While more stops result in a smoother curve, they also increase the size of your CSS. Most generators allow you to "simplify" the curve to find the optimal balance between smoothness and code size.+* **Avoid Opacity for Bounces:** Applying bounce easings to `opacity` can cause visually jarring flickering if the value overshoots below 0 or above 1.+* **Accessibility:** Complex physics-based animations can be distracting or cause motion sensitivity for some users. Always respect user preferences by reducing or disabling these animations.++```css+@media (prefers-reduced-motion: reduce) {+ .element {+ transition: none;+ }+}+```++### Fallback strategies++Baseline status for linear() easing: Newly available. It's been Baseline since 2023-12-11.++#### CSS Fallback+For browsers that do not support `linear()`, provide a standard easing function as a fallback. The browser will ignore the `linear()` value if it doesn't recognize it, falling back to the previous valid declaration.++```css+.element {+ /* Fallback for older browsers (standard smooth exit) */+ transition: transform 0.8s ease-out;++ /* Modern browsers will override with the physics-based easing */+ transition-timing-function: linear(0, 1.1, 0.95, 1.02, 1);+}+```++#### JavaScript Library Fallback (Motion/GSAP)++Optional: If a high-fidelity physics animation is critical even in older browsers, use a JavaScript library like **Motion** (motion.dev) or **GSAP** (greensock.com) to handle the animation when `linear()` is unsupported.++1. **Detect support:** Use `CSS.supports()` to check if the browser handles the `linear()` function.+2. **Conditionally load/apply:** If unsupported, use the library's spring or bounce implementation.++```javascript+/* Detect if the browser supports the linear() function */+const supportsLinearEasing = window.CSS && CSS.supports('animation-timing-function', 'linear(0, 1)');++if (!supportsLinearEasing) {+ /*+ Example using Motion (motion.dev) for a spring fallback.+ This should only be initialized if native CSS support is missing.+ */+ import("https://cdn.jsdelivr.net/npm/motion@latest/dist/motion.js").then(({ animate, spring }) => {+ animate(".element", { transform: "scale(1.2)" }, {+ easing: spring({ stiffness: 100, damping: 10 })+ });+ });+}+```++You can also use `@supports` in CSS for more explicit feature detection:++```css+@supports not (animation-timing-function: linear(0, 1)) {+ .element {+ /* Alternative experience for unsupported browsers */+ transition-duration: 0.4s;+ transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1);+ }+}+```diff --git a/skills/modern-web/guides/user-experience/platform-controls-dismiss-dialog.md b/skills/modern-web/guides/user-experience/platform-controls-dismiss-dialog.mdnew file mode 100644index 0000000..4fbbffe--- /dev/null+++ b/skills/modern-web/guides/user-experience/platform-controls-dismiss-dialog.md@@ -0,0 +1,36 @@+When a modal dialog is open, users expect to use familiar controls to dismiss them: pressing the <kbd>Esc</kbd> key on a keyboard, using the back button or gesture on mobile platforms, or a dismiss gesture with assistive technologies.++When the `<dialog>` element was first introduced, it could be dismissed with the <kbd>Esc</kbd> key, but not other platform controls such as a back button/gesture on mobile. With the addition of the `closedby` attribute for `<dialog>` elements, the extended behavior of responding to more platform-specific controls for close requests has been applied for `<dialog>` elements that are opened in a modal state (i.e. when opened imperatively with the `<dialog>` element’s `showModal()` method in JavaScript or declaratively with the `show-modal` invoker command). So, there is no specific change developers need to make if they are already using the `<dialog>` element.++```html+<!-- MANDATORY: must be opened with either `showModal()` with JavaScript or the `show-modal` command using declarative command invokers in order respond to close requests including platform-specific controls. -->+<dialog aria-labelledby="example">+ <h1 id="example">Example</h1>+ <p>Modal that can be dismissed with close requests.</p>+</dialog>+```++When opened in a modal state, a dialog without the `closedby` attribute responds to close requests the same as explicitly setting the `closedby` attribute to `closerequest`.++```html+<!-- This is unnecessary as it is the default behavior for modal dialogs -->+<dialog closedby="closerequest" aria-labelledby="example">+ <h1 id="example">Example</h1>+ <p>Modal that can be dismissed with close requests.</p>+</dialog>+```++If you also want “light dismiss” behavior, then you must set `closedby` to `any`:++```html+<dialog closedby="any" aria-labelledby="example">+ <h1 id="example">Example</h1>+ <p>Modal that can be dismissed with close requests and light dismiss.</p>+</dialog>+```++## Fallback strategies++<dialog closedby> has limited availability.++`<dialog>` elements opened in a modal state can already be dismissed with <kbd>Esc</kbd>, so there is no fallback necessary. There is no good way to implement close requests from mobile back button/gestures, so it is simpler to embrace this feature as a progressive enhancement, especially given that there are other inclusive means to dismiss the modal dialog. Similarly, light dismiss behavior for a `<dialog>` element using `closedby="any"` can be considered a progressive enhancement.\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/precise-text-alignment.md b/skills/modern-web/guides/user-experience/precise-text-alignment.mdnew file mode 100644index 0000000..38b3991--- /dev/null+++ b/skills/modern-web/guides/user-experience/precise-text-alignment.md@@ -0,0 +1,97 @@+# Precise Text Alignment++## The Problem++Browsers automatically add extra whitespace above and below text characters to accommodate line-height and font-specific metrics like ascenders and descenders. This "ghost space" makes it impossible to achieve pixel-perfect vertical alignment using standard CSS.++Common issues include:+- **Misaligned Icons**: Text appears visually lower or higher than an adjacent icon even when using `align-items: center`.+- **Inaccurate Padding**: A button with `padding: 12px` visually appears to have more space on top or bottom because of the font's internal leading.+- **Flush Alignment**: You cannot align the top of a capital letter exactly with the top of a container or an adjacent image without using "magic number" negative margins.++## The Solution++The `text-box-trim` and `text-box-edge` properties (shorthand `text-box`) allow you to trim this internal leading based on specific font metrics. By trimming the text box to the **cap-height** (top of capital letters) and the **alphabetic baseline** (bottom of most letters), you can ensure that the element's bounding box matches its visual content.++### Implementation Strategy++1. **MANDATORY**: Apply `text-box-trim: trim-both` (or the `text-box` shorthand) to the element containing the text.+2. **MANDATORY**: Specify which metrics to use for trimming with `text-box-edge`. For most UI alignment, use `cap alphabetic`.+3. **DO** use this to achieve visual vertical centering in flex or grid containers.+4. **DO** use it to ensure that your CSS `padding` values match the visual gap between the text and the container edge.+5. **DO NOT** use it on long-form body text where traditional line-spacing is necessary for readability. It is best suited for headings, buttons, and UI labels.++## Implementation Guide++### Use case 1: Trim internal leading for badges++Different fonts have different amounts of built-in spacing above and below the text. This can provide challenges in matching a design, or in visually centering text in a badge. When you want a container's padding to exactly hug the text, use `text-box: trim-both cap alphabetic`. This is especially useful for dense UI components like badges or tags. This allows the padding to start right at the text edge on all sides.++```css+.badge {+ padding: 10px;+ background: hotpink;+ border-radius: 10px;+ /*+ Trims the top to the cap-height and+ the bottom to the alphabetic baseline.+ */+ text-box: trim-both cap alphabetic;+}+```++### Use case 2: Center text with icons++When using Flexbox to align text and icons, the "ghost space" often makes the text look slightly off-center. Trimming the box ensures the layout engine uses the actual visible letter height for alignment.++```css+.button {+ display: inline-flex;+ align-items: center;+ gap: 8px;+}+/*+ text-box does NOT inherit, and must be applied directly to the text element.+*/+.button-text{+ /*+ The flex container now centers against the+ visible letters, not the invisible font box.+ */+ text-box: trim-both cap alphabetic;+}+```++### Use case 3: Align text flush with top edges++To align a heading perfectly with the top of an adjacent image or decorative element, use `trim-start cap alphabetic`. Even though the end will not be trimmed, the end edge must be defined.++```css+.hero {+ display: flex;+ align-items: flex-start;+}++h1 {+ /* MANDATORY: The bottom edge must also be defined, even though only the top is trimmed. */+ text-box: trim-start cap alphabetic;+}+```++## Best Practices++- **DO** use the `text-box` shorthand for conciseness: `text-box: <trim-direction> <edges>`.+- **DO** always specify both edges, even if only one edge is being trimmed (unless using the default `text` edge).+- **DO** combine with `line-height` for controlled spacing. Trimming removes the leading before the first and last line of text, but `line-height` still affects the distance between lines in multi-line text.+- **DO NOT** apply to every element. Use it only where precision alignment is a requirement.++### Fallback strategies++text-box has limited availability.++`text-box` is a progressive enhancement. In browsers that do not support it, the text will simply render with its default leading. Your layout will still be functional, though slightly less precise. No special fallback code is required as the properties are safely ignored by older browsers.++## Other Considerations++1. **Font Metrics**: Different fonts have different internal metrics. `cap alphabetic` is a reliable default, but some fonts or use cases may require `ex` (x-height) for better lowercase alignment.+2. **Multi-line Text**: Trimming applies to the first and last line of the block. Internal lines are not affected.diff --git a/skills/modern-web/guides/user-experience/prevent-text-wrapping.md b/skills/modern-web/guides/user-experience/prevent-text-wrapping.mdnew file mode 100644index 0000000..5943958--- /dev/null+++ b/skills/modern-web/guides/user-experience/prevent-text-wrapping.md@@ -0,0 +1,61 @@+# Prevent text wrapping++Modern CSS provides the `text-wrap` property to control how text breaks within its container. To ensure text stays on a single line and ignores container boundaries, use `text-wrap: nowrap`. This is the modern, more semantic replacement for `white-space: nowrap`.++Preventing text wrapping is useful for UI elements like navigation tabs, horizontal scrolling chips, or any scenario where a line break would break the layout or visual design.++## How to implement `text-wrap: nowrap`++### Basic Usage++To prevent any automatic line breaks, apply `text-wrap: nowrap` to the element containing the text.++1. **MANDATORY**: Apply `text-wrap: nowrap` to the target element.+2. **OPTIONAL**: Use an `overflow` property (such as `hidden`, `scroll`, or `auto`) to manage the resulting overflow.+3. **OPTIONAL**: Use `text-overflow: ellipsis` to provide a visual cue when text is truncated. Note: This requires `overflow: hidden`.++### Example code++```css+.no-wrap-text {+ /* MANDATORY: Prevents automatic line breaks */+ text-wrap: nowrap;++ /* OPTIONAL: Handles the overflow visually */+ overflow: hidden;+ text-overflow: ellipsis;++ /* OPTIONAL: Constrain width to force and handle overflow within this element */+ max-width: 200px;+}+```++### Specific Control with Longhands++The `text-wrap` property is a shorthand for `text-wrap-mode` (whether text wraps) and `text-wrap-style` (how it wraps). Since `text-wrap-style` is ignored when wrapping is disabled, you should generally stick to the `text-wrap` shorthand.++While the longhand `text-wrap-mode: nowrap` exists, the property name is currently considered a placeholder by the CSS Working Group and may change in the future.++```css+.granular-control {+ /* Modern longhand equivalent to white-space: nowrap */+ /* Preferred: text-wrap: nowrap; */+ text-wrap-mode: nowrap;+}+```++### Fallback strategies++Baseline status for text-wrap: Newly available. It's been Baseline since 2024-10-17.++For browsers that do not yet support `text-wrap`, use the legacy `white-space` property. Modern browsers treat `white-space` as a shorthand for setting both the `text-wrap-mode` and `white-space-collapse` properties.++```css+.no-wrap-with-fallback {+ /* Fallback for older browsers */+ white-space: nowrap;++ /* Modern standard */+ text-wrap: nowrap;+}+```diff --git a/skills/modern-web/guides/user-experience/pull-to-reveal.md b/skills/modern-web/guides/user-experience/pull-to-reveal.mdnew file mode 100644index 0000000..55004c0--- /dev/null+++ b/skills/modern-web/guides/user-experience/pull-to-reveal.md@@ -0,0 +1,81 @@+# Pull to Reveal++"Pull to reveal" is a UI pattern where content (such as a search bar or refresh control) is hidden above the top of a scrollable area on initial load, and the user can pull down (scroll up) to reveal it. This pattern is commonly used in mobile apps and web apps for search bars, filters, and other secondary controls that should be accessible but not immediately visible.++The CSS property `scroll-initial-target` offers a declarative, CSS-only way to implement this pattern. By setting `scroll-initial-target: nearest` on the main content element, the scroll container will render with the hidden content scrolled out of view. Previously, developers relied on JavaScript (`Element.scrollIntoView()`) or URL fragment identifiers (`#content-id`) to achieve this, both of which have limitations and are tricky to implement.++## How to Implement++To implement a pull-to-reveal pattern:++1. **Ensure a scroll container:** The target element must be inside a scroll container (an element with overflow that allows scrolling, such as `overflow: auto`). This can be any ancestor element, including the root `<html>` element.+2. **Define the hidden element:** Place the content you want to hide (e.g., a search bar) as the first descendant inside the scroll container. This element will be scrolled out of view on initial load.+3. **Define the main content:** Place the main content element immediately after the hidden element. This is the element the user should see first.+4. **Target the main content:** Apply `scroll-initial-target: nearest` to the main content element so the scroll container renders with it scrolled into view, hiding the element above it.+5. **Add scroll snapping:** To ensure the hidden element is always either fully visible or fully hidden (and doesn't rest in a partially-scrolled state), add `scroll-snap-type: y mandatory` to the scroll container and `scroll-snap-align: start` to both the hidden element and the main content element.++## Example Code: Pull to Reveal Search++```css+/**+ * ANCESTOR: Define the scroll container.+ * Scroll snapping ensures the search bar is always+ * either fully visible or fully hidden.+ */+.scroll-container {+ height: 100vh;+ overflow-y: auto;+ scroll-snap-type: y mandatory;+}++/**+ * HIDDEN ELEMENT: The search bar hidden above the fold on load.+ * It has scroll-snap-align so it snaps into place when pulled down.+ */+.search-bar {+ height: 60px;+ scroll-snap-align: start;+}++/**+ * MAIN CONTENT + TARGET: The element the user sees first.+ * scroll-snap-align makes it a valid snap point.+ * scroll-initial-target tells the browser to scroll here on+ * initial render, hiding the search bar above it.+ */+.main-content {+ scroll-snap-align: start;+ scroll-initial-target: nearest;+}+```++## Strategic Implementation & Best Practices++- **DO** use `scroll-initial-target: nearest` when you want to draw the user's attention to a specific part of a scrollable area upon load and intentionally hide peripheral UI units like a search bar at the very top.+- **DO NOT** confuse this with accessibility focus. This property only moves the **visual** viewport; it does not move the keyboard focus. You must manually manage `element.focus()` if the target is intended to be the starting point for keyboard users.+- **DO NOT** use this if you need a smooth "scrolling" animation on load; this property is discrete and sets the position instantly during the layout phase.+- **DO NOT** set `scroll-initial-target` on multiple elements within the same scrollable container. If multiple elements specify `scroll-initial-target: nearest`, the browser selects the one that appears first in the DOM tree order.+- **DO** account for the **Precedence Hierarchy**: A URL fragment (e.g., `example.com/#top`) and the container-level `scroll-start` property both take precedence over `scroll-initial-target`.++## Fallback Strategy++scroll-initial-target has limited availability.++For browsers that do not yet support the API, use a JavaScript fallback. Note that for pulling content to reveal, you want the main content to be bound to the `start` (top) of the container.++```javascript+/**+ * Progressive Enhancement Fallback+ */+document.addEventListener("DOMContentLoaded", () => {+ // Check for native CSS support+ if (!CSS.supports("scroll-initial-target", "nearest")) {+ const targetContent = document.querySelector('.main-content.target');+ if (targetContent) {+ // Use behavior: "instant" to mimic the native CSS behavior+ // 'block: start' should match your CSS 'scroll-snap-align' (or expected top position)+ targetContent.scrollIntoView({ behavior: 'instant', block: 'start' });+ }+ }+});+```diff --git a/skills/modern-web/guides/user-experience/scroll-entry-exit-effects.md b/skills/modern-web/guides/user-experience/scroll-entry-exit-effects.mdnew file mode 100644index 0000000..8f5e462--- /dev/null+++ b/skills/modern-web/guides/user-experience/scroll-entry-exit-effects.md@@ -0,0 +1,171 @@+# Add entry and exit effects to elements as they enter or exit the scrollport++Entry and exit effects are animations that are triggered when an element enters or leaves the viewport. This can be used to create engaging and dynamic user experiences. For example, you can use an entry effect to fade in an element as it scrolls into view, or an exit effect to scale it down as it scrolls out of view.++## How to implement++To add entry and exit effects to an element, you need to combine a few CSS properties. Here’s a step-by-step guide:++1. **Create separate `@keyframes` for the entry and exit animations.** The entry animation will be applied as the element enters the viewport, and the exit animation will be applied as it leaves.++ ```css+ @keyframes slide-in {+ from { transform: translateX(-100%); }+ }+ @keyframes slide-out {+ to { transform: translateX(100%); }+ }+ ```++2. **Attach the entry and exit keyframes to the element.** You can do this by defining multiple animations in the `animation` property.++ - Give the entry animation a `animation-fill-mode` of `forwards` so that it maintains its final state after the animation is complete.+ - Give the exit animation a `animation-fill-mode` of `backwards` so that it doesn't affect the element before it starts.++ ```css+ .animated-element {+ animation:+ slide-in 1s linear forwards,+ slide-out 1s linear backwards;+ }+ ```++3. **Create a View Timeline and link it to the animations.** A View Timeline is a type of timeline that is linked to the visibility of an element in the viewport. You can create one using the `view()` function and then apply it to your animations using the `animation-timeline` property.++ ```css+ .animated-element {+ animation-timeline: view();+ }+ ```++ By default, `view()` tracks the element on the `block` axis. If you need to track it on the `inline` axis, you can use `view(inline)`.++4. **Limit the animations to the `entry` and `exit` ranges.** The `animation-range` property allows you to specify which part of the timeline an animation should run on.++ - The `entry` range covers the time from when the element first enters the viewport until it is fully visible.+ - The `exit` range covers the time from when the element starts to leave the viewport until it is completely hidden.++ ```css+ .animated-element {+ animation-range: entry, exit;+ }+ ```++## Example code++This code animates the direct children of the scroller on scroll using an **anonymous view-timeline**:++```css+@media (prefers-reduced-motion: no-preference) {+ @supports ((animation-timeline: view()) and (animation-range: entry)) {+ @keyframes grow {+ from {+ scale: 0.5;+ }+ }+ @keyframes shrink {+ to {+ scale: 0.5;+ }+ }++ .scroller > * {+ animation:+ grow auto linear backwards,+ shrink auto linear forwards;+ animation-timeline: view(inline);+ animation-range: entry, exit;+ }+ }+}+```++As the elements enter the scrollport the `grow` animation is played, and as they leave the scrollport the `shrink` animation is played.++The following code has the same visual outcome, but animates the direct children of the scroller on scroll using an **named view-timeline**:++```css+@media (prefers-reduced-motion: no-preference) {+ @supports ((animation-timeline: view()) and (animation-range: entry)) {+ @keyframes grow {+ from {+ scale: 0.5;+ }+ }+ @keyframes shrink {+ to {+ scale: 0.5;+ }+ }++ .scroller > * {+ view-timeline: --tl inline;+ animation:+ grow auto linear backwards,+ shrink auto linear forwards;+ animation-timeline: --tl;+ animation-range: entry, exit;+ }+ }+}+```++## Best Practices++When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:++- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: view()) and (animation-range: entry))` to check for support and provide a fallback for browsers that don't support it.+ - The `(animation-range: entry)` check **MUST** be included here, to filter out browsers with only partial support.+ - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.+ - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.+- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.+- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.+- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` *after* it to prevent the shorthand from resetting the timeline.++When using the `view()` function to create a scroll-driven animation:++- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view(block)` or `view(inline)`.+- When the animation is not applied to the tracked subject itself, use a named view timeline.++When using the `view-timeline` property to create a scroll-driven animation:++- **DO** use a CSS `<dashed-ident>` for the name.+- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view-timeline-axis`.+- **DO** make sure the scope of the lookup works: When the element that is declaring the `view-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `view-timeline`’s name by using `timeline-scope` on a shared ancestor.++Prefer a named `view-timeline` when multiple elements or children of the tracked subject need to animate.++## Browser support and fallback strategies++Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.++For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).++In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.++Note that not every effect can be recreated using the fallbacks approach.++For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of the `.wrapper` element and updates the `transform` property of the layers based on the scroll position.++```html+<script>+ if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {+ const observer = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ // This matches the effect as defined in the CSS example above.+ // Customize this further if needed.+ entry.target.style.scale = 0.5 + entry.intersectionRatio * 0.5;+ }+ },+ {+ threshold: Array.from({ length: 101 }, (_, i) => i / 100),+ }+ );++ document.querySelectorAll('.scroller > *').forEach((el) => {+ observer.observe(el);+ });+ }+</script>+```diff --git a/skills/modern-web/guides/user-experience/scroll-progress-indicator.md b/skills/modern-web/guides/user-experience/scroll-progress-indicator.mdnew file mode 100644index 0000000..f7d531e--- /dev/null+++ b/skills/modern-web/guides/user-experience/scroll-progress-indicator.md@@ -0,0 +1,129 @@+# Build a Scroll Progress Indicator++A scroll progress indicator is a common user interface pattern that visually communicates the user's progress through a scrollable document or container. As the user scrolls, a visual element updates to reflect their position, providing a clear and intuitive sense of how much content has been viewed and how much remains.++## How to implement++To create a scroll progress indicator, you need two things:++1. An element to act as the progress bar. This element is typically `position: fixed` or `position: absolute` so that it stays in view while the user scrolls.+2. An animation that is linked to the scroll position.++Here’s how you can achieve this:++- First, create an HTML element that will serve as your progress bar. This element can be styled to your liking.+- Next, in your CSS, define a `@keyframes` animation that scales the progress bar. A common approach is to scale the element from `scaleX(0)` to `scaleX(1)`.+- Finally, apply this animation to your progress bar element and set its `animation-timeline` to a scroll-timeline. This tells the browser to drive the animation's progress based on the scroll position of the nearest ancestor scroller.++## Example code++This code grows the `#progress` element on scroll using an anonymous scroll-timeline, created by the `scroll()` function.++```css+@media (prefers-reduced-motion: no-preference) {+ @supports ((animation-timeline: scroll())) {+ @keyframes grow-progress {+ from { transform: scaleX(0); }+ to { transform: scaleX(1); }+ }++ #progress {+ position: fixed;+ left: 0; top: 0;+ width: 100%; height: 1em;+ background: red;++ transform-origin: 0 50%;+ animation: grow-progress auto linear;+ animation-timeline: scroll();+ }+ }+}+```++Because of its location in the DOM, the `scroll()` function will track its neareast ancestor scroller in the `block` direction, which here is the root scroller.++```html+<body>+ <div id="progress"></div>+</body>+```++This code grows the `#progress` element on scroll using a named scroll-timeline, created by the `scroll-timeline` property.++```css+@media (prefers-reduced-motion: no-preference) {+ @supports ((animation-timeline: scroll())) {+ @keyframes grow-progress {+ from { transform: scaleX(0); }+ to { transform: scaleX(1); }+ }++ :root {+ scroll-timeline: --tl block;+ }++ #progress {+ position: fixed;+ left: 0; top: 0;+ width: 100%; height: 1em;+ background: red;++ transform-origin: 0 50%;+ animation: grow-progress auto linear;+ animation-timeline: --tl;+ }+ }+}+```++## Best Practices++When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:++- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports (animation-timeline: scroll())` to check for support and provide a fallback for browsers that don't support it.+ - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.+ - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.+- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.+- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.+- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` *after* it to prevent the shorthand from resetting the timeline.++When using the `scroll()` function to create a scroll-driven animation:++- **OPTIONAL** be explicit about the scroller: When not targeting the nearest ancestor scroller, be explicit about which scroller you want to use with `scroll(root)` or `scroll(self)`.+ - When `root`, `nearest`, or `self` are not sufficient, use a named scroll-timeline.+- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `scroll(block)` or `scroll(inline)`.++When using the `scroll-timeline` property to create a scroll-driven animation:++- **DO** use a CSS `<dashed-ident>` for the name.+- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `scroll-timeline-axis`.+- **DO** make sure the scope of the lookup works: When the element that is declaring the `scroll-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `scroll-timeline`’s name by using `timeline-scope` on a shared ancestor.++## Browser support and fallback strategies++Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.++For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).++In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.++Note that not every effect can be recreated using the fallbacks approach.++For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses a scroll listener to track the scroll position of the root element and updates the `transform` property of the progress bar accordingly.++```html+<script>+ if (!CSS.supports('animation-timeline', 'scroll()')) {+ const progress = document.querySelector('#progress');++ window.addEventListener('scroll', () => {+ const scrollable = document.documentElement.scrollHeight - window.innerHeight;+ const scrolled = window.scrollY;+ const progressPercentage = (scrolled / scrollable);++ progress.style.transform = `scaleX(${progressPercentage})`;+ });+ }+</script>+```diff --git a/skills/modern-web/guides/user-experience/scroll-target-on-load.md b/skills/modern-web/guides/user-experience/scroll-target-on-load.mdnew file mode 100644index 0000000..b936963--- /dev/null+++ b/skills/modern-web/guides/user-experience/scroll-target-on-load.md@@ -0,0 +1,54 @@+# Set a scroll target for the initial render++The CSS property `scroll-initial-target` offers a declarative, CSS-only way to bring a specific descendant element into the visible area of its scroll container as soon as that container is rendered. Previously, developers relied on JavaScript (`Element.scrollIntoView()`) or URL fragment identifiers (`#item-id`), both of which have limitations and are tricky to implement.++## How to Implement++To implement this successfully:++1. **Ensure a scroll container:** The target element must be inside a scroll container (an element with overflow that allows scrolling, such as `overflow: auto`). This can be any ancestor element, including the root `<html>` element.+2. **Target the Item:** Apply `scroll-initial-target: nearest` to the specific descendant element you want to bring into view.++## Example Code: Vertical Media Feed++In this example, a feed starts scrolled to a specific "featured" item rather than the very top of the list.++```css+/**+ * TARGET: The item that should be visible on initial load.+ */+.item.target {+ scroll-initial-target: nearest;+}+```++## Strategic Implementation & Best Practices++- **DO** use `scroll-initial-target` for "middle-start" experiences, such as a calendar starting on the current day or a gallery starting on a specific image.+- **DO NOT** confuse this with accessibility focus. This property only moves the **visual** viewport; it does not move the keyboard focus. You must manually manage `element.focus()` if the target is intended to be the starting point for keyboard users.+- **DO NOT** use this if you need a smooth "scrolling" animation on load; this property is discrete and sets the position instantly during the layout phase.+- **DO NOT** set `scroll-initial-target` on multiple elements within the same scrollable container. If multiple elements specify `scroll-initial-target: nearest`, the browser selects the one that appears first in the DOM tree order.+- **DO** provide dimensions for media. Since the scroll position is calculated during initial layout, ensure images or videos have `aspect-ratio` or fixed `height`/`width` to prevent the target from shifting after the media loads.+- **DO** account for the **Precedence Hierarchy**: A URL fragment (e.g., `example.com/#top`) and the container-level `scroll-start` property both take precedence over `scroll-initial-target`.++## Fallback Strategy++scroll-initial-target has limited availability.++For browsers that do not yet support the API, use a JavaScript fallback. Use the `DOMContentLoaded` event to ensure the browser scrolls the element into view as soon as the HTML parsing completes, providing a faster experience than waiting for all images and resources to load. Alternatively, placing the script at the end of the `<body>` element is also acceptable and avoids the need for an event listener.++```javascript+/**+ * Progressive Enhancement Fallback+ */+document.addEventListener("DOMContentLoaded", () => {+ // Check for native CSS support+ if (!CSS.supports("scroll-initial-target", "nearest")) {+ const feedTarget = document.querySelector(".item.target");+ if (feedTarget) {+ // 'block: center' ensures the featured media is centered in view+ feedTarget.scrollIntoView({ behavior: "instant", block: "center" });+ }+ }+});+```diff --git a/skills/modern-web/guides/user-experience/scrollytelling.md b/skills/modern-web/guides/user-experience/scrollytelling.mdnew file mode 100644index 0000000..9272fdc--- /dev/null+++ b/skills/modern-web/guides/user-experience/scrollytelling.md@@ -0,0 +1,161 @@+# Scrollytelling++Scrollytelling is a popular technique used to create engaging and immersive web experiences. It involves animating elements on a page as the user scrolls, effectively telling a story or guiding the user through a narrative. With CSS Scroll-Driven Animations, you can create these effects directly in CSS, without needing to rely on JavaScript. The animations are controlled by the scroll position, not a time-based clock, which ensures they are always in sync with the user's scroll.++## How to implement++To create a scrollytelling experience, you need two sets of elements: one to track the scroll position and another to be animated.++First, define a named `view-timeline` on the elements you want to track. These will act as the drivers for your animations.++```css+#tracked {+ section:nth-child(1){ view-timeline: --tl-1 block; }+ section:nth-child(2){ view-timeline: --tl-2 block; }+ section:nth-child(3){ view-timeline: --tl-3 block; }+ section:nth-child(4){ view-timeline: --tl-4 block; }+ section:nth-child(5){ view-timeline: --tl-5 block; }+}+```++Next, apply animations to the elements you want to animate and link them to the timelines you just created using the `animation-timeline` property.++```css+#animated {+ section {+ animation: animate-in auto linear both, animate-out auto linear forwards;+ animation-range: entry 25% cover 50%, exit 50% exit 75%;+ }++ section:nth-child(1){ animation-timeline: --tl-1; }+ section:nth-child(2){ animation-timeline: --tl-2; }+ section:nth-child(3){ animation-timeline: --tl-3; }+ section:nth-child(4){ animation-timeline: --tl-4; }+ section:nth-child(5){ animation-timeline: --tl-5; }+}+```++For the `animation-timeline` to be able to reference the named timelines, they need to be in the same scope. You can use the `timeline-scope` property on a common ancestor to make the timelines available to all the elements that need them. The `:root` element is often a good choice for this.++```css+html {+ timeline-scope: --tl-1, --tl-2, --tl-3, --tl-4, --tl-5;+}+```++Finally, you can use the `animation-range` property to specify the exact range of the timeline during which the animation should run. This gives you fine-grained control over when the animations are triggered and how they progress.++```css+#animated section {+ animation-range: entry 25% cover 50%, exit 50% exit 75%;+}+```++## Example code++```css+html {+ timeline-scope: --tl-1, --tl-2, --tl-3, --tl-4, --tl-5;+}++#tracked {+ section:nth-child(1){ view-timeline: --tl-1 block; }+ section:nth-child(2){ view-timeline: --tl-2 block; }+ section:nth-child(3){ view-timeline: --tl-3 block; }+ section:nth-child(4){ view-timeline: --tl-4 block; }+ section:nth-child(5){ view-timeline: --tl-5 block; }+}++@keyframes animate-in {+ from { scale: 0.5; opacity: 0; transform: rotateY(-180deg); }+ to { transform: rotateY(0deg); }+}+@keyframes animate-out {+ to { translate: 100% 0; opacity: 0; }+}++#animated {+ section {+ animation: animate-in auto linear both, animate-out auto linear forwards;+ animation-range: entry 25% cover 50%, exit 50% exit 75%;+ backface-visibility: hidden;+ }++ section:nth-child(1){ animation-timeline: --tl-1; }+ section:nth-child(2){ animation-timeline: --tl-2; }+ section:nth-child(3){ animation-timeline: --tl-3; }+ section:nth-child(4){ animation-timeline: --tl-4; }+ section:nth-child(5){ animation-timeline: --tl-5; }+}+```++## Best Practices++When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:++- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: scroll()) and (animation-range: 0% 100%))` to check for support and provide a fallback for browsers that don't support it.+ - The `(animation-range: 0% 100%)` check **MUST** be included here, to filter out browsers with only partial support.+ - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.+ - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.+- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.+- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.+- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.++When using the `view-timeline` property to create a scroll-driven animation:++- **DO** use a CSS `<dashed-ident>` for the name.+- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view-timeline-axis`.+- **DO** make sure the scope of the lookup works: When the element that is declaring the `view-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `view-timeline`’s name by using `timeline-scope` on a shared ancestor.++## Browser support and fallback strategies++Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.++For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).++In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.++Note that not every effect can be recreated using the fallbacks approach.++For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of each `#tracked section` element and updates the `transform` property of the corresponding `#animated section` accordingly.++```js+const animatedSections = document.querySelectorAll('#animated section');++const observer = new IntersectionObserver((entries) => {+ entries.forEach(entry => {+ const sectionIndex = Array.from(document.querySelectorAll('#tracked section')).indexOf(entry.target);+ if (sectionIndex !== -1) {+ const animatedSection = animatedSections[sectionIndex];+ const ratio = entry.intersectionRatio;++ // Animate-in+ animatedSection.style.opacity = ratio;+ animatedSection.style.transform = `scale(${0.5 + ratio * 0.5}) rotateY(${-180 + ratio * 180}deg)`;++ // Animate-out+ if (ratio < 0.5) {+ animatedSection.style.translate = `${(0.5 - ratio) * 2 * 100}% 0`;+ } else {+ animatedSection.style.translate = '0 0';+ }+ }+ });+}, { threshold: Array.from({length: 101}, (_, i) => i / 100) });++document.querySelectorAll('#tracked section').forEach(section => {+ observer.observe(section);+});+```++And the accompanying CSS:++```css+#animated section {+ opacity: 0;+ transform: scale(0.5) rotateY(-180deg);+ backface-visibility: hidden;+}+```++This fallback provides a more accurate, scroll-driven animation for browsers that do not support the native CSS feature, ensuring a more consistent experience for all users. By using a series of thresholds for the `IntersectionObserver`, we can track the scroll position with more precision and create a smoother animation.\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/search-hidden-content.md b/skills/modern-web/guides/user-experience/search-hidden-content.mdnew file mode 100644index 0000000..9640fc1--- /dev/null+++ b/skills/modern-web/guides/user-experience/search-hidden-content.md@@ -0,0 +1,129 @@+# Search hidden content++Web interfaces often hide content from view to improve the user experience, save screen space, or increase page performance. Traditional methods like `display: none` or `visibility: hidden` work to hide content visually, but they also make that content completely inaccessible to screen readers and browser features like "Find in page".++To hide content visually but still allow it to be searchable by users and enable it to be deep linked to via URL fragments and "Scroll to Text Fragment" links, you can use either the HTML `<details>` element or the `hidden="until-found"` attribute. The `<details>` element is generally recommended as it's simpler to implement and maintain, but there are some more complex cases where `<details>` is not sufficient and `hidden="until-found"` is required.++For example:++- If you want full control over the styling of the show/hide mechanism.+- If the UI controls to show/hide the content are in another part of the DOM.+- If you don't want to support hiding the content after it's shown.++## How to implement++The `<details>` element has searchable and accessible text by default, and no special implementation is required. Prefer using `<details>` over `hidden="until-found"` if possible.++If you need to use `hidden="until-found"` instead, follow these instructions:++1. **Apply the attribute:** Add the `hidden="until-found"` HTML attribute directly to the elements containing the content that should be hidden from view.+2. **Synchronize UI state:** If the interface has related states that depend on the content's visibility (e.g., updating ARIA attributes, toggling open/close CSS classes, or rotating accordion icons):+ - You **MUST** add an event listener for the `beforematch` event.+ - Register the `beforematch` event listener directly on the element carrying the `hidden="until-found"` attribute. Since the event bubbles, you may alternatively use event delegation by registering a single listener on a parent element (such as a tab container) to manage multiple hidden sections at once.+ - Inside the event listener, execute the logic to synchronize related UI elements (such as closing other open tabs or changing the state of a toggle button).++## Example code++**Goal:** Render a hidden container where the content remains invisible to the user until they search for a word within that section.++### Using `<details>` element++```html+<details>+ <summary>Click to expand</summary>+ <p>This content is visually hidden.</p>+</details>+```++#### Mutually exclusive content (e.g. tabs)++When handling mutually exclusive regions, like tabs, use the native HTML `<details>` element with a shared `name` attribute.++```html+<div class="tab-container">+ <!-- The name attribute creates an exclusive accordion/tab group -->+ <details class="tab" name="my-tabs">+ <summary>Tab 1 (closed)</summary>+ <p>Tab 1 content</p>+ </details>++ <details class="tab" name="my-tabs" open>+ <summary>Tab 2 (open)</summary>+ <p>Tab 2 content</p>+ </details>++ <details class="tab" name="my-tabs">+ <summary>Tab 3 (closed)</summary>+ <p>Tab 3 content</p>+ </details>+</div>+```++### Using `hidden="until-found"` attribute++```html+<!-- The browser automatically removes hidden="until-found" upon a search match -->+<div class="hidden-container" hidden="until-found">+ <p>This content is visually hidden.</p>+</div>+```++#### Mutually exclusive content (e.g. tabs)++When handling mutually exclusive regions, like tabs, ensure only the matched tab becomes visible. Since the `beforematch` event bubbles, you can listen on a parent container to manage state before the browser reveals the matched content.++```html+<div class="tab-container">+ <div class="tab">+ <p>Tab 1 content (visible)</p>+ </div>++ <div class="tab" hidden="until-found">+ <p>Tab 2 content (hidden)</p>+ </div>++ <div class="tab" hidden="until-found">+ <p>Tab 3 content (hidden)</p>+ </div>+</div>+```++```javascript+const tabContainer = document.querySelector('.tab-container');++tabContainer.addEventListener('beforematch', () => {+ // Hide all tabs before the browser reveals the matched tab+ tabContainer.querySelectorAll('.tab').forEach((tab) => {+ tab.hidden = 'until-found';+ });+});+```++## Best practices for `hidden="until-found"`++- **DO** apply borders, padding, and backgrounds to nested child wrappers rather than directly to the element with the `hidden="until-found"` attribute. This prevents unintended layout shifts or visual remnants while the element is hidden.+- **DO NOT** apply `display: none`, `visibility: hidden`, or any associated `display` or `visibility` CSS properties directly to elements with the `hidden="until-found"` attribute. This breaks the native functionality and permanently hides the content from the search index.+- **DO NOT** use `hidden="until-found"` for sensitive information, internal data tokens, or irrelevant data that should not be exposed via search.+- **DO NOT** use `hidden="until-found"` as a replacement for "screen reader only" (.sr-only) text.++## Browser support and fallback strategies++The `<details>` element is Baseline Widely available, so a fallback strategy is not required.++The `hidden="until-found"` attribute is not yet Baseline Widely available, but it can be safely used with a fallback in unsupporting browsers. **DO NOT** avoid `hidden="until-found"` because of missing browser support, as its accessiblity benefits far outweigh the cost of implementing a fallback.++#### `hidden="until-found"` fallback++For standard UI elements like accordions or "Read more" sections, use JavaScript to feature-detect and show all content if the feature is unsupported.++```javascript+if (!('onbeforematch' in HTMLElement.prototype)) {+ // Expand all hidden content for unsupported browsers+ document.querySelectorAll('[hidden="until-found"]').forEach((el) => {+ el.removeAttribute('hidden');+ // MANDATORY: also update any aria references to this element.+ });+}+```++For mutually exclusive UI paradigms (like tabs where content shares the same visual region), the fallback should extract and display all content linearly below the main interactive area, using URL anchor fragments to allow users to navigate directly to the respective sections.diff --git a/skills/modern-web/guides/user-experience/shrinking-header-on-scroll.md b/skills/modern-web/guides/user-experience/shrinking-header-on-scroll.mdnew file mode 100644index 0000000..5ad4254--- /dev/null+++ b/skills/modern-web/guides/user-experience/shrinking-header-on-scroll.md@@ -0,0 +1,124 @@+# Shrinking headder on scroll++A shrinking header on scroll is a common UI pattern where a fixed header element at the top of the page smoothly transitions to a smaller size as the user scrolls down. This effect is often used to maximize screen real estate for the main content while keeping essential navigation or branding elements accessible. With CSS scroll-driven animations, this effect can be achieved in a declarative and performant way, by linking an animation to the scroll position of the document.++## How to implement++Here’s how to create a shrinking header on scroll:++1. **Create a fixed header:** Start with a header element that is fixed to the top of the page and has a predefined height.++ ```html+ <header>HEADER</header>+ ```++ ```css+ header {+ position: fixed;+ height: 200px;+ top: 0;+ left: 0;+ right: 0;+ }+ ```++2. **Define the shrink animation:** Create a CSS animation that changes the height of the header.++ ```css+ @keyframes shrink {+ to {+ height: 50px;+ }+ }+ ```++3. **Apply the animation and scroll timeline:** Attach the animation to the header and use the `scroll()` function to link it to the document’s scroll position.++ ```css+ header {+ animation: shrink auto linear both;+ animation-timeline: scroll(block root);+ }+ ```++4. **Set the `animation-range`:** Use the `animation-range` property to specify the scroll distance over which the animation should occur. For example, to shrink the header over the first 150 pixels of scrolling, you would use `animation-range: 0px 150px;`.++ ```css+ header {+ animation-range: 0px 150px;+ }+ ```++**Tip:** To prevent the content following the header from being obscured by it, add a `padding-top` to the `body` (or the main content container) that is equal to the initial height of the header.++**Tip:** To make sure the contents of the page scroll in sync with the shrinking header, set the `animation-range-end` to the difference between the start and end sizes. This ensures the animation completes precisely when the header reaches its final size. In this demo the header shrinks from `200px` to `50px`, so the `animation-range-end` is set to `150px`.++## Example code++```css+@keyframes shrink {+ to {+ height: 50px;+ }+}++header {+ animation: shrink auto linear both;+ animation-timeline: scroll(block root);+ animation-range: 0px 150px;+}+```++## Best Practices++When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:++- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: scroll()) and (animation-range: 0% 100%))` to check for support and provide a fallback for browsers that don't support it.+ - The `(animation-range: 0% 100%)` check **MUST** be included here, to filter out browsers with only partial support.+ - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.+ - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.+- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.+- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.+- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.++When using the `scroll()` function to create a scroll-driven animation:++- **OPTIONAL** be explicit about the scroller: When not targeting the nearest ancestor scroller, be explicit about which scroller you want to use with `scroll(root)` or `scroll(self)`.+ - When `root`, `nearest`, or `self` are not sufficient, use a named scroll-timeline.+- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `scroll(block)` or `scroll(inline)`.++As for this use case specifically:++- The element that you animate **MUST** not be `position: static` or `position: relative` when using percentages in the `animation-range`.+ - This is because those elements are considered “in-flow”. Shrinking those elements as you scroll, would shrink the total scroll distance, thereby affecting the computed value of — for example — `10%` into the scroll.++## Browser support and fallback strategies++Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.++For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).++In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.++Note that not every effect can be recreated using the fallbacks approach.++For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses a scroll listener to track the scroll position of the document over a distance of `150px` and updates the header's height accordingly.++```js+// Fallback for browsers that don't support scroll-driven animations+if (!CSS.supports('(animation-timeline: scroll()) and (animation-range: 0% 100%)')) {+ const header = document.querySelector('header');++ const initialHeight = 200;+ const finalHeight = 50;+ const scrollDistance = 150;++ window.addEventListener('scroll', () => {+ const scrollY = window.scrollY;+ const scrollPercent = Math.min(1, scrollY / scrollDistance);+ const newHeight = initialHeight - (initialHeight - finalHeight) * scrollPercent;++ header.style.height = `${newHeight}px`;+ });+}+```diff --git a/skills/modern-web/guides/user-experience/stabilize-reactive-state.md b/skills/modern-web/guides/user-experience/stabilize-reactive-state.mdnew file mode 100644index 0000000..f701d97--- /dev/null+++ b/skills/modern-web/guides/user-experience/stabilize-reactive-state.md@@ -0,0 +1,70 @@+# Stabilize Reactive State with Temporal++While some reactive systems (like [React](https://react.dev/)) rely strictly on reference equality to detect state changes, others (like [Vue](https://vuejs.org/) and [Svelte](https://svelte.dev/)) can track mutations to plain objects. However, for built-in objects like the legacy `Date` object, internal mutations (like `setHours()`) do not change the object's reference and are generally not tracked by any framework's default reactivity system. This leads to missed UI updates and hard-to-debug side effects.++The `Temporal` API solves this by providing immutable objects. Any operation that modifies a value (such as adding time or setting a field) returns a new instance with a new memory reference. This guarantees that state updates are always detected by reactive systems, ensuring UI stability.++## How to Implement++To stabilize reactive state using Temporal:++1. **Use Temporal types for state:** Store `Temporal` objects (like `Temporal.PlainDateTime` or `Temporal.PlainDate`) in your reactive state instead of legacy `Date` objects.+2. **Perform immutable updates:** When updating the state, use Temporal methods like `.add()`, `.subtract()`, or `.with()`. These methods return a new object.+3. **Pass the new reference to the state setter:** Use the newly created Temporal object to update your component state, triggering a reliable re-render.++## Example Code: Temporal vs Legacy Date in State++```javascript+// ❌ BAD: Mutating legacy Date breaks reactivity+let dateState = { deadline: new Date() };++function extendDeadlineBad() {+ // Mutates the object in place. Reference remains the same!+ dateState.deadline.setHours(dateState.deadline.getHours() + 1);++ // Frameworks will skip re-rendering because+ // prevState === nextState (same memory reference)+ updateState(dateState);+}++// ✅ GOOD: Temporal ensures immutability and reliable reactivity+let temporalState = { deadline: Temporal.Now.plainDateTimeISO() };++function extendDeadlineGood() {+ // Returns a new object with a new reference.+ const newDeadline = temporalState.deadline.add({ hours: 1 });++ // Create a new state object with the new Temporal reference+ temporalState = { deadline: newDeadline };++ // Frameworks will detect the reference change and re-render the UI+ updateState(temporalState);+}+```++## Strategic Implementation & Best Practices++- **DO** use `Temporal` for any date/time values stored in reactive state to benefit from its immutability.+- **DO** use the most specific Temporal type for your use case (e.g., `Temporal.PlainDate` if you only need the calendar date) to avoid unnecessary complexity.+- **DO NOT** mutate `Date` objects in place when they are part of a component's state.+- **DO** ensure you handle environments without native support by conditionally loading a polyfill.++### Fallback strategies++Temporal has limited availability.++Since the `Temporal` API is a newer feature and may not be supported in all browsers, you should feature-detect it and conditionally load a polyfill if needed.++```html+<!-- Conditionally load the Temporal polyfill only if not natively supported -->+<script>+ if (typeof Temporal === "undefined") {+ try {+ const module = await import("https://esm.sh/@js-temporal/polyfill");+ globalThis.Temporal = module.Temporal;+ } catch (e) {+ console.error("Failed to load Temporal polyfill:", e);+ }+ }+</script>+```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/style-parent-with-has.md b/skills/modern-web/guides/user-experience/style-parent-with-has.mdnew file mode 100644index 0000000..025a2fe--- /dev/null+++ b/skills/modern-web/guides/user-experience/style-parent-with-has.md@@ -0,0 +1,193 @@+# Style Parent with :has()++## The Problem+Often, an error state requires styling elements *outside* the input itself—for example, changing the color of a parent `fieldset` border, highlighting the `<label>`, or showing a global error icon in the card header. Historically, this required JavaScript to toggle classes on parent elements.++## The Solution+By combining `:has()` with `:user-invalid`, we can declaratively style any ancestor based on the validity state of a specific descendant. This keeps all presentation logic in CSS.++### Implementation Strategy++1. **Selector**: Use `.parent:has(:user-invalid)` to target the container.+2. **Scope**: Be specific to avoid performance issues. Target `.field-group` rather than `body`.+3. **Fallback**: Requires JS to toggle classes on the parent if `:has()` is not supported.++## Implementation Guide++### 1. HTML Structure+```html+<form>+ <div class="card-section">+ <div class="header">+ <h3>Profile Settings</h3>+ <span class="status-icon"></span>+ </div>++ <div class="field">+ <label for="username">Username</label>+ <input type="text" id="username" required>+ </div>+ </div>+</form>+```++### 2. CSS+```css+/* Default State */+.card-section {+ border: 1px solid #ccc;+ border-left: 4px solid #ccc;+}++/*+ Parent Styling Logic:+ If the card contains ANY user-invalid input, turn the whole card's edge red.+*/+.card-section:has(:user-invalid) {+ border-left-color: #d93025;+ background-color: #fff8f8;+}++/* Change the icon too */+.card-section:has(:user-invalid) .status-icon::after {+ content: "⚠️";+}+```++## Fallbacking & Browser Support++The `:user-invalid` pseudo-class is widely supported (Baseline 2023), but if you need to support older browsers, you must ensure consistency of the implementation.++### CSS for Fallback+We use a class `.has-error` on the parent to mimic the `:has()` behavior.++```css+/* Native */+.card-section:has(:user-invalid) {+ border-left-color: #d93025;+}++/* Fallback */+.card-section.has-error-fallback {+ border-left-color: #d93025;+}+```++### JavaScript Fallback++DO: Use a reusable utility that tracks interaction state using a `WeakMap`. This avoids polluting the DOM with "dirty" classes or data attributes.++```javascript+const UserInvalidFallback = (() => {+ const dirtyState = new WeakMap();++ const updateState = (input) => {+ const isValid = input.checkValidity();++ // Update both visual and ARIA state+ input.classList.toggle('user-invalid-fallback', !isValid);+ input.classList.toggle('user-valid-fallback', isValid);++ if (!isValid) {+ input.setAttribute('aria-invalid', 'true');+ } else {+ input.removeAttribute('aria-invalid');+ }+ };++ const handleEvent = (event) => {+ const input = event.target;++ if (event.type === 'reset') {+ const controls = input.elements || [];+ for (const control of controls) {+ dirtyState.delete(control);+ control.classList.remove('user-invalid-fallback');+ control.classList.remove('user-valid-fallback');+ control.removeAttribute('aria-invalid');+ }+ return;+ }++ if (!input.checkValidity) return;++ if (event.type === 'input' || event.type === 'change') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasInteracted = true;+ dirtyState.set(input, state);+ if (state.hasBlurred) {+ updateState(input);+ }+ } else if (event.type === 'blur') {+ const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };+ state.hasBlurred = true;+ dirtyState.set(input, state);+ if (state.hasInteracted) {+ updateState(input);+ }+ }+ };++ const init = (root = document) => {+ if (CSS.supports('selector(:user-invalid)')) return;++ root.addEventListener('blur', handleEvent, true); // Capture phase+ root.addEventListener('input', handleEvent);+ root.addEventListener('change', handleEvent);+ root.addEventListener('reset', handleEvent, true); // Capture resets+ };++ return { init };+})();++// 1. Initialize the generic fallback+const form = document.querySelector('#demo-form');+UserInvalidFallback.init(form);++// 2. Add specialized "parent styling" logic (Separate from fallback)+// Listen for changes to form validity after interaction+form.addEventListener('blur', (e) => {+ if (!e.target.matches('input, select, textarea')) return;++ // Find the container we want to style (sync with CSS)+ const container = e.target.closest('.card-section');+ if (!container) return;++ // Check if ANY fallbacked input in this container is invalid+ const hasError = container.querySelector('.user-invalid-fallback');+ container.classList.toggle('has-error-fallback', !!hasError);+}, true); // Capture phase to ensure we run after the fallback's blur listener++// Also handle input events for immediate cleanup+form.addEventListener('input', (e) => {+ const container = e.target.closest('.card-section');+ if (container) {+ const hasError = container.querySelector('.user-invalid-fallback');+ container.classList.toggle('has-error-fallback', !!hasError);+ }+});++// Handle form resets+form.addEventListener('reset', () => {+ form.querySelectorAll('.has-error-fallback').forEach(el => {+ el.classList.remove('has-error-fallback');+ });+});+```++## Other Considerations++1. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:++```javascript+// Sync aria-invalid with the CSS :user-invalid state+const syncAria = (el) => {+ el.toggleAttribute?.('aria-invalid', el.matches(':user-invalid'));+};++// Update on blur (to show error) and input (to clear it)+document.addEventListener('blur', (e) => syncAria(e.target), true);+document.addEventListener('input', (e) => {+ if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);+});+```diff --git a/skills/modern-web/guides/user-experience/support-global-calendar-systems.md b/skills/modern-web/guides/user-experience/support-global-calendar-systems.mdnew file mode 100644index 0000000..1260c03--- /dev/null+++ b/skills/modern-web/guides/user-experience/support-global-calendar-systems.md@@ -0,0 +1,105 @@+# Supporting Global Calendar Systems with Temporal++The traditional JavaScript `Date` object is based on a proleptic Gregorian calendar, making it challenging to build applications for users who rely on other calendar systems, such as the Islamic (lunar), Hebrew (lunisolar), or Chinese (lunisolar) calendars. Developers previously had to rely on complex third-party libraries or manual calculations to support these systems.++The `Temporal` API provides first-class support for multiple calendar systems. By associating a calendar identifier with date objects, Temporal handles the complex arithmetic and formatting required for different cultural contexts natively.++## How to Implement++To support global calendar systems using Temporal:++1. **Associate a Calendar (Mandatory):** When creating or converting a Temporal object (like `Temporal.PlainDate`), you must specify the desired calendar system using `withCalendar()` to perform calendar-sensitive operations.+2. **Use Stable Identifiers (Mandatory for Lunisolar Calendars):** You must use `monthCode` rather than the numeric `month` index to identify specific months across years in lunisolar calendars. Only use this for calendars that use leap months, such as the Hebrew and Chinese calendars.+3. **Respect Calendar Invariants (Mandatory):** When iterating through months or days, you must not assume fixed values (like 12 months in a year or 31 days in a month). Use properties like `monthsInYear` and `daysInMonth` to ensure your code works across all calendars.+4. **Use Calendar-Aware Comparisons (Mandatory):** When comparing dates within a specific calendar system, you must use `Temporal.PlainDate.compare()` instead of comparing year/month/day properties manually. This correctly handles chronological ordering within the calendar rules.++## Example Code: Converting and Iterating Calendars++```javascript+// 1. Helper to check calendar support+function isCalendarSupported(calendarId) {+ try {+ return Intl.supportedValuesOf('calendar').includes(calendarId);+ } catch {+ // Fallback for environments where supportedValuesOf is not available+ return false;+ }+}++// 2. Get current date in default ISO 8601 calendar+const isoDate = Temporal.Now.plainDateISO();++// 3. Convert to Hebrew calendar if supported+const calendarId = 'hebrew';+const targetDate = isCalendarSupported(calendarId)+ ? isoDate.withCalendar(calendarId)+ : isoDate; // Fallback to ISO if not supported++if (targetDate.calendar.id !== calendarId) {+ console.warn(`Calendar ${calendarId} not supported; falling back to ISO 8601`);+}++// 4. Log properties specific to the calendar+console.log(`Calendar: ${targetDate.calendar.id}`);+console.log(`Year: ${targetDate.year}`);+console.log(`Month Code: ${targetDate.monthCode}`); // Stable across leap years++// 5. Safely iterate through months in the current year+for (let m = 1; m <= targetDate.monthsInYear; m++) {+ console.log(`Month ${m} has ${targetDate.with({ month: m }).daysInMonth} days.`);+}++// 6. Compare dates within the same calendar+const today = Temporal.Now.plainDateISO().withCalendar(calendarId);+const comparison = Temporal.PlainDate.compare(targetDate, today);+const relative = comparison < 0 ? 'Past' : comparison > 0 ? 'Future' : 'Today';+console.log(`Timeline: ${relative}`);++// 7. Format for display using toLocaleString+const localizedDisplay = targetDate.toLocaleString('en-u-ca-hebrew', {+ day: 'numeric',+ month: 'long',+ year: 'numeric'+});+```++## Strategic Implementation & Best Practices++- **DO** use `monthsInYear` as the upper bound when looping through months, rather than assuming 12.+- **DO** use `monthCode` for identifying specific months in calendars that use leap months (e.g., Hebrew or Chinese), regardless of the year.+- **DO NOT** assume `date.month === 12` is the last month of the year. Use `date.month === date.monthsInYear`.+- **DO NOT** assume `inLeapYear === true` implies the year is only one day longer. In lunisolar calendars, it may add a full leap month.+- **DO** use `Temporal.PlainDate.compare()` when comparing two dates in a specific calendar system instead of comparing Year/Month/Day properties manually.+- **DO** use `toLocaleString()` to format dates for users instead of manual string concatenation.+- **DO** verify that the target calendar system is supported by the environment using `Intl.supportedValuesOf('calendar')` before creating calendar-specific Temporal objects.+- **DO** be aware that some calendars (like variants of the Islamic calendar) may rely on visual observation rather than fixed calculations. The `Temporal` API follows the environment's `Intl` implementation, which usually uses calculated approximations. For critical cultural or religious date calculations, verify with domain experts or use specialized libraries.+- **DO** account for era names when using calendars that use eras (e.g., Japanese, Buddhist), using `toLocaleString()`.++## Fallback Strategy++Temporal has limited availability.++For production use in browsers that do not support it natively, you must use a polyfill.++The recommended approach is to progressively enhance by checking for native support and dynamically loading a polyfill like `@js-temporal/polyfill` if needed.++```javascript+/**+ * Progressive Enhancement Fallback+ */+async function getTemporal() {+ if (typeof Temporal !== 'undefined') {+ return Temporal;+ }++ try {+ // Load polyfill dynamically from CDN+ const module = await import('https://esm.sh/@js-temporal/polyfill');+ globalThis.Temporal = module.Temporal;+ return module.Temporal;+ } catch (e) {+ console.error('Failed to load Temporal polyfill:', e);+ throw e;+ }+}+```diff --git a/skills/modern-web/guides/user-experience/visually-stable-font-fallbacks.md b/skills/modern-web/guides/user-experience/visually-stable-font-fallbacks.mdnew file mode 100644index 0000000..0b01512--- /dev/null+++ b/skills/modern-web/guides/user-experience/visually-stable-font-fallbacks.md@@ -0,0 +1,48 @@+When web fonts load, they often replace a fallback font that has different dimensions, even if both are set to the same `font-size`. This causes "layout shift" (Cumulative Layout Shift) and can make text illegible if the fallback's lowercase letters (x-height) are significantly different than the preferred font.++The `font-size-adjust` property solves this by normalizing the size of the font based on a specific metric (usually the x-height), ensuring that text occupies the same visual space regardless of which font is currently active.++## Implementation steps++### 1. Identify the aspect ratio of your preferred font+To normalize fallbacks, you need the "aspect value" (the ratio of lowercase letters to the font size) of your primary font.++* **Automatic discovery (Recommended):** Use the `from-font` keyword to let the browser extract the ratio from your primary web font.+* **Manual calculation:** If you know the specific value (e.g., 0.545 for Verdana), you can provide it directly for more precise control.++### 2. Apply font-size-adjust to the text container+Apply the property to the element or a parent container. This ensures that if the primary font fails to load or is in the process of loading, the fallback font is scaled to match the visual size of the primary font.++```css+.text-content {+ /* Define your font stack as usual */+ font-family: "MyWebFont", "Arial", sans-serif;+ font-size: 1rem;++ /* MANDATORY: Normalize the font size based on the primary font's x-height.+ This ensures that if 'Arial' is used as a fallback, it is scaled+ to match the x-height of 'MyWebFont'. */+ font-size-adjust: from-font;+}+```++### 3. (Optional) Adjust for specific metrics+While x-height is the default and most common, you can normalize by other metrics like `cap-height` (useful for all-caps headers) or `ch-width` (useful for monospaced fonts).++```css+h1 {+ /* Normalize based on the height of capital letters */+ font-size-adjust: cap-height from-font;+}+```++### 4. Verify visual stability+Ensure that the `font-size-adjust` value correctly aligns the fallback. You can test this by temporarily blocking the web font or adjusting the `font-family` declaration in your browser's DevTools and verifying that the text layout remains stable.++## Fallback strategies++Baseline status for font-size-adjust: Newly available. It's been Baseline since 2024-07-25.++In browsers that do not support `font-size-adjust`, the font will be rendered at its default scale. This may result in layout shifts or changes in readability during font swaps.++To mitigate this without `font-size-adjust`, you can use the `@font-face` descriptors `size-adjust`, `ascent-override`, and `descent-override` to manually tune fallback fonts, though these are more complex to calculate than a single `font-size-adjust` value.diff --git a/skills/modern-web/guides/user-experience/visually-stable-mixed-fonts.md b/skills/modern-web/guides/user-experience/visually-stable-mixed-fonts.mdnew file mode 100644index 0000000..2271c40--- /dev/null+++ b/skills/modern-web/guides/user-experience/visually-stable-mixed-fonts.md@@ -0,0 +1,60 @@+When mixing different font families, for instance when inserting inline code snippets, or switching out font families for different themes, differences in "x-height" (the height of lowercase letters) can make one font appear much smaller or larger than the other font. This can lead to poor legibility and layout shifts.++The `font-size-adjust` property allows you to normalize the visual size of text by adjusting the font size based on a specific font metric (usually the x-height).++### Implementation Steps++1. **MANDATORY**: Apply `font-size-adjust` to elements where font consistency is critical, such as containers using web fonts or blocks with mixed font families.+2. Use the `from-font` keyword on the element to automatically match font size in nested elements to the proportions of the primary font on the element.+3. Use a specific aspect ratio value to match font size when switching between fonts.++### Example: Normalizing x-height automatically++Using `from-font` is the most robust approach. It extracts the aspect ratio of the x-height from the first available font and applies it to fonts in child elements.++```css+.content-area {+ font-family: "MyCustomWebFont";+ /* Automatically extract and apply x-height ratio from MyCustomWebFont */+ font-size-adjust: from-font;+}+.content-area span{+ font-family: "MyOtherCustomWebFont"+}+```++### Example: Specifying a specific x-height++When the font to adjust is not a child of the font to base the size on, specify a value to adjust the x-height by.++```css+.theme{+ font-family: Verdana, sans-serif;+}+.theme.alternate{+ font-family: Times;+ /* Set to the aspect ratio (x-height / font-size) of the primary font */+ font-size-adjust: 0.51;+}+```++### Fallback strategies++Baseline status for font-size-adjust: Newly available. It's been Baseline since 2024-07-25.++In browsers that do not support `font-size-adjust`, fonts will render at their natural `font-size` value. To mitigate this without support:++- Use `@supports not (font-size-adjust: from-font)` to detect `font-size-adjust` support.+- Choose fonts with similar x-heights to your primary font.+- Apply specific `font-size` and `line-height` overrides for alternate and nested font families.++```css+/* Feature detection for font-size-adjust */+@supports not (font-size-adjust: from-font) {+ .content-area {+ /* Manual adjustment for browsers without support (if needed) */+ line-height: 1.6;+ font-size: 1.2rem;+ }+}+```diff --git a/skills/modern-web/guides/webmcp/agentic-forms.md b/skills/modern-web/guides/webmcp/agentic-forms.mdnew file mode 100644index 0000000..16c4bba--- /dev/null+++ b/skills/modern-web/guides/webmcp/agentic-forms.md@@ -0,0 +1,106 @@+The Declarative API transforms standard HTML `<form>` elements into WebMCP tools via attributes. The browser synthesizes a JSON Schema from the form inputs and handles agent interactions.++## Form Attributes++* `toolname`: Unique name for the tool.+* `tooldescription`: Purpose of the tool.+* `toolautosubmit`: (Optional) If present, the agent can submit the form without waiting for user interaction.+* `toolparamdescription`: (Optional) Provides a way to define a property description within the JSON Schema.+ * **Resolution Order**: The browser uses `toolparamdescription` if present. In its absence, it uses the `textContent` of the associated `<label>` (skipping labelable descendants). If no label exists, it falls back to the `aria-description`.+ * **Grouping (Fieldsets)**: To attach a description to a group of related elements (like `<input type="radio">` buttons), place `toolparamdescription` on the nearest parent `<fieldset>` element so it applies to the parameter group as a whole.++### Example++```html+<form toolname="search-cars"+ tooldescription="Perform a car make/model search"+ toolautosubmit>+ <label for="make">Vehicle Make</label>+ <input type="text" id="make" name="make" required>++ <label for="model">Vehicle Model</label>+ <input type="text" id="model" name="model" toolparamdescription="e.g., 330i, F-150" required>++ <button type="submit">Search</button>+</form>+```++## Handling Submissions in JavaScript++When an agent submits the form, the `SubmitEvent` includes `agentInvoked` (boolean) and `respondWith(promise)`.++```javascript+document.querySelector('form').addEventListener('submit', (event) => {+ event.preventDefault();++ // Validate the form+ const formValidationErrors = myFormIsValid();++ if (formValidationErrors.length > 0) {+ if (event.agentInvoked) {+ const errorString =+ 'Validation failed: ' ++ formValidationErrors+ .map((err) => `${err.field} (${err.message})`)+ .join(', ');++ event.respondWith(Promise.resolve(errorString));+ }+ return;+ }++ const resultPromise = performAsyncSearch(new FormData(event.target));++ // Return the result directly to the agent without navigation+ if (event.agentInvoked) {+ event.respondWith(resultPromise);+ }+});+```++## Lifecycle Events++The window emits events when agents start or stop interacting with a tool:++```javascript+window.addEventListener('toolactivated', ({ toolName }) => {+ console.log(`Tool "${toolName}" was activated by the agent.`);+});++window.addEventListener('toolcancel', ({ toolName }) => {+ console.log(`Tool "${toolName}" interaction was cancelled.`);+});+```++## Visual Feedback (CSS)++Use pseudo-classes to highlight forms when an agent interacts with them:++* `:tool-form-active`: Applied to the `<form>` element actively used by the agent.+* `:tool-submit-active`: Applied to the submit button when the browser pauses for user review (if `toolautosubmit` is omitted).++```css+form:tool-form-active {+ outline: 2px dashed blue;+ background-color: rgba(0, 0, 255, 0.05);+}++button:tool-submit-active {+ outline: 2px dashed red;+ animation: pulse 2s infinite;+}+```++## Form Suitability (When to Avoid)++The Declarative API is best for self-contained, standard forms. It is a poor choice in these scenarios:++* **Highly Dependent Fields**: Forms where inputs change options or visibility based on other inputs. The synthesized schema cannot express these dependencies well.+* **Custom UI Components**: Forms relying on non-standard inputs (e.g., canvas, rich text editors) that don't auto-serialize values.+* **Multi-Step Wizards**: Complex workflows requiring multiple form submissions. The Imperative API or standard DOM interaction is better suited here.++## Fallback strategies++Form-associated WebMCP attributes has limited availability.++The WebMCP Declarative API is safe to use in all browsers. Browsers that do not support WebMCP will ignore the `tool*` attributes, and the `<form>` will continue to function as a normal HTML form. No feature detection is required.diff --git a/skills/modern-web/guides/webmcp/agentic-javascript-tools.md b/skills/modern-web/guides/webmcp/agentic-javascript-tools.mdnew file mode 100644index 0000000..4e2f055--- /dev/null+++ b/skills/modern-web/guides/webmcp/agentic-javascript-tools.md@@ -0,0 +1,115 @@+The Imperative API uses `navigator.modelContext.registerTool()` to programmatically define JavaScript tools. This is ideal for Single Page Applications (SPAs) where tools need to be added or removed based on the current route or user state.++## Registration and Lifecycle++Tools are registered by passing a tool definition object and an optional options object containing an `AbortSignal`.++### Lifecycle Handling with `AbortController`++WebMCP does not provide an `unregisterTool()` method. To unregister a tool, you must pass an `AbortSignal` during registration and abort that signal when the tool is no longer needed.++```javascript+const controller = new AbortController();++navigator.modelContext.registerTool({+ name: "get_user_preferences",+ description: "Retrieves the user's saved preferences.",+ inputSchema: { type: "object", properties: {} },+ execute() {+ const prefs = localStorage.getItem("user_prefs");+ return prefs ? JSON.parse(prefs) : { theme: "light" };+ },+ annotations: { readOnlyHint: true }+}, { signal: controller.signal });++// To unregister the tool (e.g., on component unmount):+controller.abort();+```++## Defining Parameters++Parameters (params) are defined using the `inputSchema` property. This must be a **JSON Schema** object that describes the structured data the tool expects.++```javascript+navigator.modelContext.registerTool({+ name: "calculate_area",+ description: "Calculates the area of a rectangle.",+ inputSchema: {+ type: "object",+ properties: {+ width: { type: "number", description: "The width of the rectangle." },+ height: { type: "number", description: "The height of the rectangle." }+ },+ required: ["width", "height"]+ },+ execute(input) {+ // input is { width: 10, height: 20 }+ return input.width * input.height;+ },+ annotations: { readOnlyHint: true }+});+```++## Execution Patterns++### When to use `async execute`+Use `async` when the tool involves operations that return a Promise or take time to complete:+- **Network calls**: Fetching data from an API.+- **Asynchronous Storage**: Accessing IndexedDB.+- **External Events**: Waiting for a specific state change or animation to finish.++```javascript+async execute(input) {+ const response = await fetch(`/api/data/${input.id}`);+ return await response.json();+}+```++### When to use `execute` (Synchronous)+Use a standard synchronous function for immediate operations:+- **Pure logic**: Math, filtering, or sorting data already in memory.+- **Synchronous state**: Reading from `localStorage` or a synchronous state manager.++```javascript+execute(input) {+ return input.items.filter(item => item.active);+}+```++## Tool Factory Pattern++To pass context (like stores or application instances) to your tools, use factory functions.++```javascript+export function createInventoryTool(inventoryManager) {+ return {+ name: "get_inventory",+ description: "Lists items in the inventory.",+ inputSchema: { type: "object", properties: {} },+ execute() {+ return inventoryManager.getItems();+ },+ annotations: { readOnlyHint: true }+ };+}+```++## API Notes++* **annotations**: (Optional) A dictionary for tool metadata.+ * **readOnlyHint**: (Optional) Set to `true` if the tool does not modify any state and only reads data. This helps agents decide when it is safe to call the tool.+* **Return Format**: The `execute` function can return any value (object, array, string, number, boolean). Select a structure that best serves your specific use case while ensuring the content is optimized for the LLM to process. The output may encompass raw data, specific error logs, or direct instructions to influence the agent's next action.+* **Secure Context**: WebMCP requires HTTPS.+* **Deprecated/Removed**: `unregisterTool()`, `provideContext()`, and `clearContext()` are no longer supported.++## Fallback strategies++navigator.modelContext has limited availability.++The WebMCP Imperative API should be used with feature detection to ensure compatibility with browsers that do not yet support WebMCP.++```javascript+if ('modelContext' in navigator && 'registerTool' in navigator.modelContext) {+ // Register tools+}+```diff --git a/skills/modern-web/package.json b/skills/modern-web/package.jsonnew file mode 100644index 0000000..e341a23--- /dev/null+++ b/skills/modern-web/package.json@@ -0,0 +1,8 @@+{+ "name": "modern-web",+ "version": "1.0.0",+ "type": "module",+ "bin": {+ "modern-web": "./modern-web.mjs"+ }+}