Skip to content

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

Release v0.0.8

Paul Irish6a10756e8edd
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 927e123..333e22e 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -8,7 +8,7 @@
"name": "googlechrome-skills",
"source": "./",
"description": "Google Chrome's agent skills collection",
- "version": "0.0.7"
+ "version": "0.0.8"
}
]
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 8d41e9c..217eed1 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "googlechrome-skills",
"description": "Google Chrome's agent skills collection",
- "version": "0.0.7",
+ "version": "0.0.8",
"author": {
"name": "Google Chrome"
}
diff --git a/README.md b/README.md
index d797f49..2a99ce7 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.7`
+#### Skill Coverage in `v0.0.8`
<details>
<summary><strong>24 web features with implementation guidance from Chrome's experts</strong>: :autofill, :user-valid and :user-invalid, &lt;details>, &lt;link rel="preload">, AbortController and AbortSignal, color-scheme, content-visibility, Email, telephone, and URL &lt;input> types, enterkeyhint, Fetch, Fetch priority, fetchLater, field-sizing, hidden="until-found", inputmode, Long animation frames, Mutually exclusive &lt;details> elements, prefers-color-scheme media query, prefers-contrast media query, Registered custom properties, Scroll-driven animations, scrollbar-color, scrollbar-width, Speculation rules</summary>
diff --git a/bin/modern-web.mjs b/bin/modern-web.mjs
new file mode 100644
index 0000000..e0b5d45
--- /dev/null
+++ b/bin/modern-web.mjs
@@ -0,0 +1,451 @@
+#!/usr/bin/env node --experimental-strip-types
+
+// bin/modern-web.ts
+import { parseArgs } from "util";
+
+// lib/store.ts
+import lancedb from "@lancedb/lancedb";
+import path from "path";
+import fs from "fs";
+var DATA_DIR = path.resolve(import.meta.dirname, "../vector_store");
+var Store = class {
+ dbUrl;
+ constructor() {
+ this.dbUrl = DATA_DIR;
+ if (!fs.existsSync(this.dbUrl)) {
+ fs.mkdirSync(this.dbUrl, { recursive: true });
+ }
+ }
+ async getTable() {
+ const db = await lancedb.connect(this.dbUrl);
+ try {
+ return await db.openTable("use_cases");
+ } catch {
+ return null;
+ }
+ }
+ async upsert(data) {
+ const db = await lancedb.connect(this.dbUrl);
+ const tableNames = await db.tableNames();
+ if (tableNames.includes("use_cases")) {
+ await db.dropTable("use_cases");
+ }
+ await db.createTable("use_cases", data);
+ }
+ async search(queryVector, limit = 5, maxDistance = 1.5) {
+ const table = await this.getTable();
+ if (!table) {
+ return [];
+ }
+ const fetchLimit = limit * 3;
+ const results = await table.vectorSearch(queryVector).limit(fetchLimit).toArray();
+ const seenIds = /* @__PURE__ */ new Set();
+ const uniqueResults = [];
+ for (const r of results) {
+ const dist = r._distance;
+ if (dist === void 0 || dist > maxDistance) continue;
+ if (seenIds.has(r.id)) continue;
+ seenIds.add(r.id);
+ uniqueResults.push({
+ id: r.id,
+ description: r.description,
+ category: r.category,
+ featuresUsed: Array.from(r.featuresUsed),
+ distance: dist.toFixed(2)
+ });
+ if (uniqueResults.length >= limit) break;
+ }
+ return uniqueResults;
+ }
+};
+
+// mcp-server/lib/embedder.ts
+import { pipeline } from "@huggingface/transformers";
+var Embedder = class _Embedder {
+ static instance;
+ pipe = null;
+ modelName = "Xenova/all-MiniLM-L6-v2";
+ constructor(modelName) {
+ if (modelName) {
+ this.modelName = modelName;
+ }
+ }
+ static getInstance(modelName) {
+ if (!_Embedder.instance || modelName && _Embedder.instance.modelName !== modelName) {
+ _Embedder.instance = new _Embedder(modelName);
+ }
+ return _Embedder.instance;
+ }
+ async init() {
+ if (this.pipe) return;
+ let repo = this.modelName;
+ let dtype = "q8";
+ if (this.modelName.includes("@")) {
+ const parts = this.modelName.split("@");
+ repo = parts[0];
+ dtype = parts[1];
+ }
+ this.pipe = await pipeline("feature-extraction", repo, { dtype });
+ }
+ async embed(text) {
+ if (!this.pipe) await this.init();
+ if (!this.pipe) throw new Error("Failed to initialize embedding pipeline");
+ const output = await this.pipe(text, { pooling: "mean", normalize: true });
+ return Array.from(output.data);
+ }
+};
+
+// lib/logger.ts
+import { appendFileSync } from "fs";
+import path2 from "path";
+
+// ../constants.ts
+var MODERN_WEB_LOG_FILE = "modern-web.log";
+
+// lib/logger.ts
+function logToolResult(toolName, result) {
+ try {
+ const logDir = process.env.MODERN_WEB_LOG_DIR || process.cwd();
+ const logPath = path2.join(logDir, MODERN_WEB_LOG_FILE);
+ const logEntry = {
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ tool: toolName,
+ result
+ };
+ appendFileSync(logPath, JSON.stringify(logEntry) + "\n", "utf8");
+ } catch (err) {
+ console.error("Failed to log tool result:", err);
+ }
+}
+
+// lib/search.ts
+async function searchUseCases(query) {
+ const store = new Store();
+ const embedder = Embedder.getInstance();
+ const vector = await embedder.embed(query);
+ const results = await store.search(vector);
+ logToolResult("search_use_cases", results.map((r) => ({ id: r.id, distance: r.distance })));
+ return results;
+}
+
+// lib/practices.ts
+import { promises as fs2 } from "fs";
+import { existsSync } from "fs";
+import path3 from "path";
+
+// lib/use-cases.gen.ts
+var USE_CASES = [
+ {
+ "id": "accessible-error-announcement",
+ "description": "Synchronize programmatic accessibility states (like aria-invalid) with the visual :user-invalid state to ensure screen reader users receive error feedback only after interaction, mirroring the visual experience.",
+ "category": "accessibility",
+ "featuresUsed": [
+ ":user-valid and :user-invalid"
+ ]
+ },
+ {
+ "id": "autofill-address-form",
+ "description": "Build an address form with correct autocomplete attributes and autofill support.",
+ "category": "forms",
+ "featuresUsed": [
+ ":autofill"
+ ]
+ },
+ {
+ "id": "autofill-highlight-inputs",
+ "description": "Use CSS to highlight form fields that have been autofilled by the browser and not edited by the user.",
+ "category": "forms",
+ "featuresUsed": [
+ ":autofill"
+ ]
+ },
+ {
+ "id": "autofill-payment-form",
+ "description": "Build a payment form that collects card details with correct autocomplete values and autofill support.",
+ "category": "forms",
+ "featuresUsed": [
+ "enterkeyhint",
+ "Email, telephone, and URL <input> types",
+ "inputmode"
+ ]
+ },
+ {
+ "id": "autofill-sign-in-form",
+ "description": "Build a sign-in form with correct autocomplete values and autofill support.",
+ "category": "forms",
+ "featuresUsed": [
+ "Email, telephone, and URL <input> types",
+ "inputmode"
+ ]
+ },
+ {
+ "id": "autofill-sign-up-form",
+ "description": "Build a sign-up form with correct autocomplete values and autofill support.",
+ "category": "forms",
+ "featuresUsed": [
+ "Email, telephone, and URL <input> types",
+ "inputmode"
+ ]
+ },
+ {
+ "id": "form-fields-automatically-fit-contents",
+ "description": "Allow form fields to grow and shrink to fit the user input, e.g. as the user types or selects a different option. Apply maximum and minimum size limits to create dynamic and responsive form fields that conform with the page design.",
+ "category": "forms",
+ "featuresUsed": [
+ "field-sizing"
+ ]
+ },
+ {
+ "id": "required-field-feedback",
+ "description": "Provide error message for required form fields that were skipped or left empty *only* after user interaction, to avoid preemptive errors and ensure feedback is timely and contextually relevant to the user's flow.",
+ "category": "forms",
+ "featuresUsed": [
+ ":user-valid and :user-invalid"
+ ]
+ },
+ {
+ "id": "select-menu-interaction",
+ "description": "Validate that a non-default option has been chosen in a select menu only after the user has interacted with the control.",
+ "category": "forms",
+ "featuresUsed": [
+ ":user-valid and :user-invalid"
+ ]
+ },
+ {
+ "id": "validate-input-after-interaction",
+ "description": "Show form field validation feedback (e.g. password complexity or email format requirements) only after the user has finished their initial interaction, avoiding premature errors on page load or while the user is typing.",
+ "category": "forms",
+ "featuresUsed": [
+ ":user-valid and :user-invalid"
+ ]
+ },
+ {
+ "id": "batch-analytics-events",
+ "description": "Debounce and batch multiple analytics events together in a single beacon to minimize network contention and reduce server load, while still delivering real-time updates.",
+ "category": "performance",
+ "featuresUsed": [
+ "fetchLater",
+ "AbortController and AbortSignal"
+ ]
+ },
+ {
+ "id": "defer-rendering-heavy-content",
+ "description": "Reduce rendering times in content-heavy web pages (e.g. pages with long feeds, lots of articles, or complex dashboards), by deferring rendering for any content that is not immediately visible to the user.",
+ "category": "performance",
+ "featuresUsed": [
+ 'hidden="until-found"',
+ "content-visibility"
+ ]
+ },
+ {
+ "id": "deprioritize-background-fetches",
+ "description": "Deprioritize background data fetches made with the Fetch API to prevent network contention with user-initiated requests.",
+ "category": "performance",
+ "featuresUsed": [
+ "Fetch priority",
+ "Fetch"
+ ]
+ },
+ {
+ "id": "full-session-analytics",
+ "description": "Reliably track analytics, errors, and telemetry data across the user's entire page visit, and defer sending of the data until the user leaves the page.",
+ "category": "performance",
+ "featuresUsed": [
+ "fetchLater",
+ "AbortController and AbortSignal"
+ ]
+ },
+ {
+ "id": "identify-heavy-scripts",
+ "description": "Identify the scripts most responsible for long animation frames",
+ "category": "performance",
+ "featuresUsed": [
+ "Long animation frames"
+ ]
+ },
+ {
+ "id": "identify-inp-causes",
+ "description": "Identify slow running JavaScript that is impacting INP metric",
+ "category": "performance",
+ "featuresUsed": [
+ "Long animation frames"
+ ]
+ },
+ {
+ "id": "improve-next-page-load-performance",
+ "description": "Improve page load performance by prefetching or prerendering pages that the user is likely to visit next.",
+ "category": "performance",
+ "featuresUsed": [
+ "Speculation rules"
+ ]
+ },
+ {
+ "id": "optimize-image-priority",
+ "description": "Optimize the loading priority of Largest Contentful Paint (LCP) candidate images and deprioritize non-critical images to reduce critical resource load delays.",
+ "category": "performance",
+ "featuresUsed": [
+ "Fetch priority"
+ ]
+ },
+ {
+ "id": "optimize-preload-priority",
+ "description": "Optimize the relative priority of preloaded content to reduce critical resource load delays.",
+ "category": "performance",
+ "featuresUsed": [
+ "Fetch priority",
+ '<link rel="preload">'
+ ]
+ },
+ {
+ "id": "optimize-script-priority",
+ "description": "Optimize the loading priority of scripts by boosting critical asynchronous scripts and deprioritizing non-essential or late-body scripts to improve sequencing and reduce delays.",
+ "category": "performance",
+ "featuresUsed": [
+ "Fetch priority"
+ ]
+ },
+ {
+ "id": "adapt-scrollbar-to-contrast-preferences",
+ "description": "Enhance scrollbar visibility for users who prefer high-contrast interfaces",
+ "category": "user-experience",
+ "featuresUsed": [
+ "scrollbar-color",
+ "prefers-contrast media query"
+ ]
+ },
+ {
+ "id": "adapt-scrollbar-to-light-dark-preferences",
+ "description": "Ensure the scrollbar visually matches the user's operating system light/dark mode preference",
+ "category": "user-experience",
+ "featuresUsed": [
+ "scrollbar-color",
+ "color-scheme",
+ "prefers-color-scheme media query"
+ ]
+ },
+ {
+ "id": "animate-scrollbar-color-on-scroll",
+ "description": "Animate the scrollbar color dynamically as the user scrolls down the page",
+ "category": "user-experience",
+ "featuresUsed": [
+ "scrollbar-color",
+ "Scroll-driven animations",
+ "Registered custom properties"
+ ]
+ },
+ {
+ "id": "customize-scrollbar-color-and-thickness",
+ "description": "Customize the color or thickness of a scrollbar",
+ "category": "user-experience",
+ "featuresUsed": [
+ "scrollbar-color",
+ "scrollbar-width"
+ ]
+ },
+ {
+ "id": "search-hidden-content",
+ "description": 'Hide content from view using patterns such as accordions, tabs, and "Read more" sections, while ensuring the hidden text reveals itself during native "Find in page" searches, allows search engine indexing, supports URL fragment deep links, and maintains ARIA accessibility.',
+ "category": "user-experience",
+ "featuresUsed": [
+ "<details>",
+ "Mutually exclusive <details> elements",
+ 'hidden="until-found"'
+ ]
+ },
+ {
+ "id": "style-parent-with-has",
+ "description": "Style parent elements of a form field (e.g. labels or fieldsets) when the field is invalid.",
+ "category": "user-experience",
+ "featuresUsed": [
+ ":user-valid and :user-invalid"
+ ]
+ }
+];
+
+// lib/practices.ts
+async function getGuide(useCaseId) {
+ const useCase = USE_CASES.find((u) => u.id === useCaseId);
+ if (!useCase) return null;
+ const localDistPath = path3.resolve(import.meta.dirname, "../guides");
+ const guidesDir = existsSync(localDistPath) ? localDistPath : path3.resolve(import.meta.dirname, "../build/guides");
+ const filePath = path3.join(guidesDir, useCase.category, `${useCaseId}.md`);
+ try {
+ const content = await fs2.readFile(filePath, "utf-8");
+ return content;
+ } catch (error) {
+ if (error.code === "ENOENT") {
+ return null;
+ }
+ throw error;
+ }
+}
+
+// lib/retrieve.ts
+async function retrieveUseCase(useCaseId) {
+ const guide = await getGuide(useCaseId);
+ if (!guide) {
+ throw new Error(`No guide found for use case: ${useCaseId}`);
+ }
+ logToolResult("get_best_practices", [{ id: useCaseId }]);
+ return guide;
+}
+
+// bin/modern-web.ts
+var { values } = parseArgs({
+ args: process.argv.slice(2),
+ options: {
+ search: { type: "string", short: "s" },
+ retrieve: { type: "string", short: "r" },
+ help: { type: "boolean", short: "h" }
+ },
+ allowPositionals: false
+});
+function printUsage() {
+ console.log(`
+Usage: modern-web [options]
+
+Options:
+ -s, --search <query> Search use cases by query
+ -r, --retrieve <ids> Retrieve use case(s) by ID(s), comma-separated
+ -h, --help Show this help
+`);
+}
+async function main() {
+ if (values.help) {
+ printUsage();
+ process.exit(0);
+ }
+ if (values.search) {
+ try {
+ const results = await searchUseCases(values.search);
+ console.log(JSON.stringify(results, null, 2));
+ } catch (error) {
+ console.error("Search failed:", error);
+ process.exit(1);
+ }
+ } else if (values.retrieve) {
+ const ids = values.retrieve.split(",").map((id) => id.trim()).filter(Boolean);
+ if (ids.length === 0) {
+ console.error("No IDs provided for retrieve.");
+ process.exit(1);
+ }
+ for (const id of ids) {
+ try {
+ const guide = await retrieveUseCase(id);
+ console.log(`
+--- Guide for ${id} ---`);
+ console.log(guide);
+ } catch (error) {
+ console.error(`Retrieve failed for ${id}:`, error);
+ process.exit(1);
+ }
+ }
+ } else {
+ printUsage();
+ process.exit(1);
+ }
+}
+main().catch((err) => {
+ console.error("Execution failed:", err);
+ process.exit(1);
+});
diff --git a/gemini-extension.json b/gemini-extension.json
index a8f0a09..fbd141d 100644
--- a/gemini-extension.json
+++ b/gemini-extension.json
@@ -1,7 +1,7 @@
{
"name": "googlechrome-skills",
"description": "Google Chrome's web development agent skills.",
- "version": "0.0.7",
+ "version": "0.0.8",
"author": {
"name": "Google Chrome"
}
diff --git a/guides/accessibility/accessible-error-announcement.md b/guides/accessibility/accessible-error-announcement.md
new file mode 100644
index 0000000..6d011dc
--- /dev/null
+++ b/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/guides/forms/autofill-address-form.md b/guides/forms/autofill-address-form.md
new file mode 100644
index 0000000..cb33f63
--- /dev/null
+++ b/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 is Limited.
+
+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/guides/forms/autofill-highlight-inputs.md b/guides/forms/autofill-highlight-inputs.md
new file mode 100644
index 0000000..cba68bb
--- /dev/null
+++ b/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 is Limited.
+
+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/guides/forms/autofill-payment-form.md b/guides/forms/autofill-payment-form.md
new file mode 100644
index 0000000..76337ac
--- /dev/null
+++ b/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
+
+enterkeyhint is Widely. It's been Baseline since 2021-11-02.
+Email, telephone, and URL <input> types is Widely. It's been Baseline since 2015-07-29.
+inputmode is Widely. 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/guides/forms/autofill-sign-in-form.md b/guides/forms/autofill-sign-in-form.md
new file mode 100644
index 0000000..e40fb6b
--- /dev/null
+++ b/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
+
+Email, telephone, and URL <input> types is Widely. It's been Baseline since 2015-07-29.
+inputmode is Widely. 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/guides/forms/autofill-sign-up-form.md b/guides/forms/autofill-sign-up-form.md
new file mode 100644
index 0000000..4e6b9f8
--- /dev/null
+++ b/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
+
+Email, telephone, and URL <input> types is Widely. It's been Baseline since 2015-07-29.
+inputmode is Widely. 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/guides/forms/form-fields-automatically-fit-contents.md b/guides/forms/form-fields-automatically-fit-contents.md
new file mode 100644
index 0000000..2dd498d
--- /dev/null
+++ b/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 is Limited.
+
+`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 file
diff --git a/guides/forms/required-field-feedback.md b/guides/forms/required-field-feedback.md
new file mode 100644
index 0000000..276c76d
--- /dev/null
+++ b/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/guides/forms/select-menu-interaction.md b/guides/forms/select-menu-interaction.md
new file mode 100644
index 0000000..1ab9ba3
--- /dev/null
+++ b/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/guides/forms/validate-input-after-interaction.md b/guides/forms/validate-input-after-interaction.md
new file mode 100644
index 0000000..424cfa8
--- /dev/null
+++ b/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/guides/performance/batch-analytics-events.md b/guides/performance/batch-analytics-events.md
new file mode 100644
index 0000000..4607877
--- /dev/null
+++ b/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 is Limited.. 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/guides/performance/defer-rendering-heavy-content.md b/guides/performance/defer-rendering-heavy-content.md
new file mode 100644
index 0000000..171cb49
--- /dev/null
+++ b/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
+
+content-visibility is Newly. 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" is Limited.
+
+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/guides/performance/deprioritize-background-fetches.md b/guides/performance/deprioritize-background-fetches.md
new file mode 100644
index 0000000..afaa30b
--- /dev/null
+++ b/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
+
+Fetch priority is Newly. 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/guides/performance/full-session-analytics.md b/guides/performance/full-session-analytics.md
new file mode 100644
index 0000000..d34b29b
--- /dev/null
+++ b/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 is Limited.
+
+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/guides/performance/identify-heavy-scripts.md b/guides/performance/identify-heavy-scripts.md
new file mode 100644
index 0000000..9d6b74d
--- /dev/null
+++ b/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 is Limited..
+
+The Long Animation Frames API is not supported in all browsers, but other browsers do not have alternative APIs with similar functionality. Therefore, it should be used in supporting browsers without a fallback strategy. In most cases the performance opportunities it identifies will apply to other browsers as well.
diff --git a/guides/performance/identify-inp-causes.md b/guides/performance/identify-inp-causes.md
new file mode 100644
index 0000000..2e69fe0
--- /dev/null
+++ b/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 is Limited..
+
+The Long Animation Frames API is not supported in all browsers, but other browsers do not have alternative APIs with similar functionality. Therefore, it should be used in supporting browsers without a fallback strategy. In most cases the performance opportunities it identifies will apply to other browsers as well.
diff --git a/guides/performance/improve-next-page-load-performance.md b/guides/performance/improve-next-page-load-performance.md
new file mode 100644
index 0000000..08ec9b3
--- /dev/null
+++ b/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/guides/performance/optimize-image-priority.md b/guides/performance/optimize-image-priority.md
new file mode 100644
index 0000000..70bfa7a
--- /dev/null
+++ b/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
+
+Fetch priority is Newly. 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/guides/performance/optimize-preload-priority.md b/guides/performance/optimize-preload-priority.md
new file mode 100644
index 0000000..bc2f026
--- /dev/null
+++ b/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
+
+Fetch priority is Newly. 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/guides/performance/optimize-script-priority.md b/guides/performance/optimize-script-priority.md
new file mode 100644
index 0000000..4379544
--- /dev/null
+++ b/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
+
+Fetch priority is Newly. 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/guides/user-experience/adapt-scrollbar-to-contrast-preferences.md b/guides/user-experience/adapt-scrollbar-to-contrast-preferences.md
new file mode 100644
index 0000000..9834160
--- /dev/null
+++ b/guides/user-experience/adapt-scrollbar-to-contrast-preferences.md
@@ -0,0 +1,59 @@
+# 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;
+ }
+}
+```
+
+## Fallbacks & Browser Support
+
+scrollbar-color is Newly. 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/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.md b/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.md
new file mode 100644
index 0000000..01c90cb
--- /dev/null
+++ b/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.md
@@ -0,0 +1,75 @@
+# 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;
+ }
+}
+```
+
+## Fallbacks & Browser Support
+
+scrollbar-color is Newly. 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/guides/user-experience/animate-scrollbar-color-on-scroll.md b/guides/user-experience/animate-scrollbar-color-on-scroll.md
new file mode 100644
index 0000000..56a9b00
--- /dev/null
+++ b/guides/user-experience/animate-scrollbar-color-on-scroll.md
@@ -0,0 +1,67 @@
+# Animate scrollbar color on scroll
+
+Using CSS Scroll-Driven Animations, it is possible to create striking visual effects by dynamically changing the color of the scrollbar thumb based on the user's scroll position.
+
+Because the standard `scrollbar-color` property is mathematically defined as "discrete", it does not smoothly interpolate between two colors by default during a standard `@keyframes` animation. To achieve smooth scrolling transitions, you MUST use the CSS `@property` rule to register an interpolatable `<color>` variable.
+
+MANDATORY: You MUST clarify in your CSS output or documentation that this progressive enhancement strictly relies on browser support for **both** the `registered-custom-properties` and `scroll-driven-animations` Web Features. This technique is **not polyfillable**, even with a fallback. Browsers failing to support these modern standards will gracefully ignore the animation and render the default `initial-value` color state with no adverse layout effects.
+
+## 1. Register a custom Color Property
+
+MANDATORY: You MUST define a CSS `@property` with the `<color>` syntax so the browser knows how to smoothly transition the variable.
+
+```css
+/* DO: Register an interpolatable variable */
+@property --thumb-color {
+ syntax: '<color>';
+ inherits: true;
+ initial-value: hotpink;
+}
+```
+
+## 2. Define the Scroll Animation
+
+MANDATORY: Create a standard `@keyframes` animation block that alters the registered custom property, and apply it to the scrollable container using `animation-timeline: scroll(self)`.
+
+```css
+/* DO: Animate the custom property */
+@keyframes scrollbar-shift {
+ 0% { --thumb-color: hotpink; }
+ 50% { --thumb-color: purple; }
+ 100% { --thumb-color: blue; }
+}
+
+.scroller {
+ /* DO: Apply the standard colors using the variable, with a solid fallback color */
+ scrollbar-color: var(--thumb-color, hotpink) #f1f1f1;
+ scrollbar-width: thin;
+
+ /* DO: Bind the animation to the scroll position */
+ animation: scrollbar-shift linear;
+ animation-timeline: scroll(self);
+}
+```
+
+## 3. Fallbacks & Browser Support
+
+Scroll-driven animations is Limited.
+Registered custom properties is Newly. It's been Baseline since 2024-07-09.
+
+MANDATORY: This feature relies on the `registered-custom-properties` and `scroll-driven-animations` Web Features. These are modern standards without polyfills. If they are not available in the user's Baseline target (e.g., they target "Baseline Widely Available"), you MUST NOT use this animated feature and let the user know it cannot be supported on their target.
+MANDATORY: Pass the animated variable into the `::-webkit-scrollbar-thumb` background color securely isolated behind an `@supports not` block. You MUST include a static fallback color inside the `var()` function (e.g., `var(--thumb-color, hotpink)`) so the scrollbar remains visible on legacy WebKit browsers that do not support `@property`.
+
+```css
+/* Legacy fallback for WebKit/Blink browsers */
+@supports not (scrollbar-color: auto) {
+ .scroller::-webkit-scrollbar {
+ width: 12px;
+ }
+ .scroller::-webkit-scrollbar-track {
+ background: #f1f1f1;
+ }
+ .scroller::-webkit-scrollbar-thumb {
+ /* DO: Inherit and provide a solid fallback color for browsers without @property support */
+ background-color: var(--thumb-color, hotpink);
+ }
+}
+```
diff --git a/guides/user-experience/customize-scrollbar-color-and-thickness.md b/guides/user-experience/customize-scrollbar-color-and-thickness.md
new file mode 100644
index 0000000..232f92b
--- /dev/null
+++ b/guides/user-experience/customize-scrollbar-color-and-thickness.md
@@ -0,0 +1,73 @@
+# 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.
+
+## Fallback strategies
+
+scrollbar-color is Newly. It's been Baseline since 2025-12-12.
+
+scrollbar-width is Newly. 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/guides/user-experience/search-hidden-content.md b/guides/user-experience/search-hidden-content.md
new file mode 100644
index 0000000..9640fc1
--- /dev/null
+++ b/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/guides/user-experience/style-parent-with-has.md b/guides/user-experience/style-parent-with-has.md
new file mode 100644
index 0000000..025a2fe
--- /dev/null
+++ b/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/package.json b/package.json
index 02f8c3c..dd865d5 100644
--- a/package.json
+++ b/package.json
@@ -1,9 +1,9 @@
{
- "name": "skills-alpha",
+ "name": "modern-web",
"displayName": "Chrome Web Development Skills",
"private": true,
"description": "Curated collection of agent skills for modern web development.",
- "version": "0.0.7",
+ "version": "0.0.8",
"publisher": "GoogleChrome",
"engines": {
"vscode": "^1.90.0",
@@ -21,7 +21,7 @@
]
},
"bin": {
- "modern-web": "./skills/modern-web-use-cases/cli/serving/bin/modern-web.mjs"
+ "modern-web": "./bin/modern-web.mjs"
},
"dependencies": {
"@huggingface/transformers": "^3.8.1",