Keep your coding agent up to date with the latest web best practices
Release v0.0.68
github-actions[bot]3a9f5fc89e08
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 31bba63..eb84933 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -8,7 +8,7 @@"name": "modern-web-guidance","source": "./","description": "Google Chrome's agent skills collection",- "version": "0.0.67"+ "version": "0.0.68"}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 4666391..88ccef4 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "modern-web-guidance","description": "Google Chrome's agent skills collection",- "version": "0.0.67",+ "version": "0.0.68","author": {"name": "Google Chrome"}diff --git a/README.md b/README.mdindex f48cac6..50bd1d3 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.67`+#### Skill Coverage in `v0.0.68`<details><summary><strong>78 web features with implementation guidance from Chrome's experts</strong>: `::backdrop`, `:autofill`, `:has()`, `:not()`, `:user-valid and :user-invalid`, `@starting-style`, `<details>`, `<dialog closedby>`, `<dialog>`, `<link rel="expect">`, `<link rel="preload">`, `AbortController and AbortSignal`, `accent-color`, `Active view transition`, `Anchor positioning`, `blocking="render"`, `calc-size()`, `color-scheme`, `Container queries`, `content-visibility`, `Cross-document view transitions`, `Customizable <select>`, `Email, telephone, and URL <input> types`, `enterkeyhint`, `Fetch`, `Fetch priority`, `fetchLater`, `field-sizing`, `font-size-adjust`, `Form-associated WebMCP attributes`, `hidden="until-found"`, `image-set()`, `Individual transform properties`, `inert`, `inputmode`, `Interest invokers`, `interpolate-size`, `Intersection observer`, `Intl.DurationFormat`, `Invoker commands`, `Language detector`, `light-dark()`, `linear() easing`, `Long animation frames`, `Masks`, `moveBefore()`, `Mutually exclusive <details> elements`, `Navigation API`, `navigator.modelContext`, `overlay`, `Page visibility state`, `Popover`, `popover="hint"`, `prefers-color-scheme media query`, `prefers-contrast media query`, `prefers-reduced-motion media query`, `Registered custom properties`, `Scheduler API`, `Scroll snap`, `Scroll-driven animations`, `scroll-initial-target`, `scrollbar-color`, `scrollbar-width`, `scrollIntoView()`, `sibling-count() and sibling-index()`, `sin(), cos(), tan(), asin(), acos(), atan(), and atan2() (CSS)`, `Speculation rules`, `Summarizer`, `Temporal`, `text-box`, `text-wrap`, `text-wrap: balance`, `text-wrap: pretty`, `Top-level await`, `transition-behavior`, `Translator`, `View transitions`, `view-transition-class`</summary>diff --git a/gemini-extension.json b/gemini-extension.jsonindex 78153cd..2bb36a2 100644--- a/gemini-extension.json+++ b/gemini-extension.json@@ -1,7 +1,7 @@{"name": "modern-web-guidance","description": "Google Chrome's web development agent skills.",- "version": "0.0.67",+ "version": "0.0.68","author": {"name": "Google Chrome"}diff --git a/package.json b/package.jsonindex e3ea3b7..84c218f 100644--- a/package.json+++ b/package.json@@ -2,7 +2,7 @@"name": "modern-web-guidance","displayName": "Modern Web Guidance","description": "Curated collection of agent skills for modern web development.",- "version": "0.0.67",+ "version": "0.0.68","publisher": "GoogleChrome","engines": {"vscode": "^1.90.0",diff --git a/skills/modern-web/guides/forms/forms.md b/skills/modern-web/guides/forms/forms.mdnew file mode 100644index 0000000..67b0fe3--- /dev/null+++ b/skills/modern-web/guides/forms/forms.md@@ -0,0 +1,364 @@+## 1. Semantic Structure and Form Element++### Guidelines++- **DO** use the `<form>` element to wrap interactive controls for data collection.+- **DO** use `method="POST"` for sensitive data and mutations; use `method="GET"` for idempotent requests (e.g., search).+- **DO** specify the `action` attribute for the destination URL.+- **DO** specify a `name` attribute for every form control to identify data on submission.+- **DO** use semantic tags like `<button type="submit">`, `<textarea>`, and `<select>`.+- **DO** use `<fieldset>` and `<legend>` to group related controls.+- **DO** use actionable language on submit buttons (e.g., "Save changes").++- **DON'T** use `GET` for sensitive data (it exposes data in history/logs).+- **DON'T** use generic `<div>` or `<span>` for form controls.+- **DON'T** use `type="button"` for primary submission buttons.+- **DON'T** disable textarea resizing without alternate layout provisions.++### Code Example++```html+<form action="/search" method="GET">+ <fieldset>+ <legend>Search Preferences</legend>+ <label for="q">Query:</label>+ <input type="text" id="q" name="q" required>+ <button type="submit">Search</button>+ </fieldset>+</form>+```++### Selection Control Decision Matrix++| Options Count | Choice Type | Recommended Element | Usability & Accessibility Logic |+| :--- | :--- | :--- | :--- |+| **1–5** | Single (Exclusive) | `<input type="radio">` | **Zero-click scanning**: All choices are immediately visible. Faster scan time. |+| **6+** | Single (Exclusive) | `<select>` | **Space conservation**: Use only when vertical space is premium or the list is long. |+| **10+ / Dynamic** | Single (Exclusive) | `<input list="id">` (`<datalist>`) | **Fuzzy Search**: Prevents scrolling fatigue in massive sets (e.g., countries). |+| **Any** | Multi-select | `<input type="checkbox">` | **Standard semantics**: Native non-exclusive toggles. |++**Single-Sentence Mental Model**: "Expose mutually exclusive options as visible radio buttons when choices are fewer than six; use `<select>` only when space is constrained or the list is long."++## 2. Accessible Labeling and State++### Guidelines++- **DO** always associate `<label>` with its input using `for` and `id`.+- **DO** place labels above form controls to enable faster scanning.+- **DO** use visible labels; do not rely on `placeholder` alone.+- **DO** ensure the vertical margin between a label and its input is less than the margin between form groups (**Gestalt Proximity Rule**).+- **DO** use `aria-describedby` to link inputs with help text or error messages.+- **DO** define the `lang` attribute on `<html>` for proper device translation.+- **DO** use non-color visual cues (icons, text) to communicate state (don't rely on color alone).+- **DO** indicate clearly which fields are required.+- **DO** use `aria-live` for dynamic error announcements.++- **DON'T** use `placeholder` as a replacement for labels.+- **DON'T** use `aria-label` as the sole text description if translation is needed.+- **DON'T** disable focus outlines without providing a high-contrast alternative.++### Code Example++```html+<div class="field">+ <label for="username">Username:</label>+ <input type="text" id="username" name="username" aria-describedby="user-help" required>+ <span id="user-help" class="hint">3-12 characters.</span>+</div>++<style>+ input:focus-visible {+ outline: 3px solid #0b57d0;+ outline-offset: 2px;+ }+</style>+```++## 3. Autofill and Input Modes++### Guidelines++- **DO** use the `autocomplete` attribute to specify expected data (e.g., `email`, `tel`, `current-password`, `new-password`).+- **DO** use `inputmode` to optimize on-screen keyboards (e.g., `inputmode="numeric"` for PINs).+- **DO** use `enterkeyhint` to set the Enter key label (e.g., `next`, `done`).+- **DO** use single-field inputs for complex numbers (credit cards, phones) to help autofill.++- **DON'T** use `type="number"` for credit cards or ZIP codes (causes UI scroll issues and removes leading zeros).++### Code Example++```html+<label for="zip">ZIP Code:</label>+<input type="text" id="zip" name="zip" autocomplete="postal-code" inputmode="numeric" pattern="\d{5}">+```++## 4. Constraints and Validation++### Guidelines++- **DO** use native constraints: `required`, `minlength`, `maxlength`, `pattern`.+- **DO** use CSS pseudo-classes `:invalid:user-invalid` for non-intrusive styling.+- **DO** use the ValidityState API (`setCustomValidity`) for custom messaging.++- **DON'T** disable submit buttons to block validation; let users submit and highlight errors. However, **DO** disable the button *after* a valid submission is clicked to prevent double-posts.++### Code Example++```html+<label for="code">Activation Code (4 digits):</label>+<input type="text" id="code" name="code" required pattern="\d{4}">++<script>+ const input = document.getElementById('code');+ input.addEventListener('invalid', () => {+ input.setCustomValidity('Please enter exactly 4 digits.');+ });+ input.addEventListener('input', () => {+ input.setCustomValidity('');+ });+</script>+```++### Validation Event Timing Matrix++| Event Trigger | Phase | Action Allowed | UX / Accessibility Logic |+| :--- | :--- | :--- | :--- |+| **`input`** | Active Typing | **Clear** existing errors only. | **Non-intrusive**: Do not yell at the user before they finish typing. |+| **`blur` / `focusout`** | Exiting Field | **Run** check and show error. | **Contextual validation**: Validate once the user indicates they are "done" with a field. |+| **`submit`** | Final Attempt | **Block** and route focus. | **Final gatekeeper**: Intercepts bad payloads and forces screen reader focus to the summary. |++**Single-Sentence Mental Model**: "Validate on `blur` to avoid premature warnings while typing, and reset error states on `input` as soon as the user attempts a correction."++**Security vs UX Scale**: Client-side validation is for User Experience; Server-side validation is for Security. Never treat browser constraints as a data integrity defense.++## 5. Responsive Design and Typography++### Guidelines++- **DO** use single-column layouts for scanning.+- **DO** set `font-size` to at least `1rem` (16px) to prevent iOS zoom.+- **DO** expand clickable areas for mobile tap targets using padding tricks.+- **DO** ensure tap targets are at least `48px`.+- **DO** use units relative to root (`rem`) and unitless `line-height`.+- **DO** use CSS logical properties (e.g., `margin-inline-start`) for RTL support.++### Code Example++```css+.form-group {+ margin-block-end: 1.5rem;+}++/* Expand clickable tap area without layout shift */+label {+ display: inline-block;+ padding: 10px 0;+ margin: -10px 0;+}++input {+ font-size: 1rem;+ padding: 0.75rem;+ min-height: 48px;+ box-sizing: border-box;+}++@media (pointer: coarse) {+ input {+ min-height: 52px;+ }+}+```++## 6. Styling Form Controls++### Guidelines++- **DO** use `accent-color` for quick branding of native radios/checkboxes.+- **DO** use `appearance: none` for custom dropdown arrows without breaking semantics.+- **DO** ensure inputs are clearly visible with adequate border contrast (e.g., `#ccc` or darker on white backgrounds).+- **DO** hide inputs visually using `position: absolute; opacity: 0` (NOT `display: none`) to keep them accessible.++### Code Example++```html+<div class="checkbox-container">+ <input type="checkbox" id="sub" name="sub" class="visually-hidden">+ <label for="sub" class="checkbox-label">Subscribe</label>+</div>++<style>+ .visually-hidden {+ position: absolute;+ opacity: 0;+ width: 1rem;+ height: 1rem;+ z-index: 1;+ }+ .checkbox-label::before {+ content: "";+ display: inline-block;+ width: 1.25rem;+ height: 1.25rem;+ border: 2px solid #ccc;+ }+ input:focus-visible + .checkbox-label::before {+ outline: 2px solid #0b57d0;+ }+</style>+```++## 7. JavaScript and AJAX++### Guidelines++- **DO** prevent default navigation on form submit for AJAX (`e.preventDefault()`).+- **DO** use `ValidityState` interfaces for real-time validation checks.+- **DO** use `aria-expanded` and `aria-controls` for dynamic UI reveals.++- **DON'T** block page submission if JS fails; ensure server-side fallback.++### Code Example++```js+form.addEventListener('submit', (e) => {+ e.preventDefault();+ const data = new FormData(form);+ // fetch('/submit', { method: 'POST', body: data });+});+```++## 8. Identity, Payments, and Advanced Security++### Guidelines++- **DO** use `autocomplete="new-password"` for sign-up and `autocomplete="current-password"` for sign-in.+- **DO** allow pasting into password fields.+- **DO** provide a toggle capability allowing users to unmask password input.+- **DO** indicate exact amounts on pay buttons (e.g., "Pay $100").+- **DO** use `autocomplete="cc-number"`, `cc-exp`, `cc-csc`.+- **DO** use HTTPS for all pages.+- **DO** implement cryptographically secure anti-CSRF tokens for mutating actions (POST/PUT/DELETE).+- **DO** sanitize user input (e.g., via DOMPurify) before injecting it into the DOM to prevent XSS.+- **DO** implement spam protection (honeypots or reCAPTCHA) for open forms.++- **DON'T** utilize HTTP `GET` for endpoints executing state changes.+- **DON'T** use inline JavaScript (e.g., `onclick="..."`) directly within form markup to satisfy strict Content Security Policies (CSP).++### Code Example++```html+<form method="post">+ <input type="hidden" name="csrf_token" value="secure_token_abc123">++ <h1>Sign up</h1>++ <section>+ <label for="name">Full name</label>+ <input id="name" name="name" autocomplete="name" required pattern="[\p{L}\.\- ]+">+ </section>++ <section>+ <label for="email">Email</label>+ <input id="email" name="email" type="email" autocomplete="username" required>+ </section>++ <section>+ <label for="password">Password</label>+ <button id="toggle-password" type="button" aria-label="Show password as plain text. Warning: this will display your password on the screen.">Show password</button>+ <input id="password" name="password" type="password" autocomplete="new-password" minlength="8" aria-describedby="password-constraints" required>+ <div id="password-constraints">Eight or more characters.</div>+ </section>++ <button id="sign-up">Sign up</button>+</form>+```+++## 9. Address Collection++### Guidelines++- **DO** use a single field for names.+- **DO** use `autocomplete="street-address"`.+- If the site has users in different countries, **DO** use the `<textarea>` element for addresses, to accommodate different address formats in different geographical regions. If the form uses separate inputs for address parts (e.g. Street, City), **DO** use `autocomplete` values `address-line1`, `address-line2`, etc.+- **DO** make postal codes optional.++- **DON'T** split name inputs into rigid variables ("First", "Last") for global audiences.+- **DON'T** enforce Latin-only characters for names and usernames.++### Code Example++```html+<!-- Accessible Address Form with Autofill -->+<form action="/save-address" method="POST">+ <div class="form-group">+ <label for="full-name">Full name</label>+ <input type="text" id="full-name" name="full_name" maxlength="100" required autocomplete="name">+ </div>++ <div class="form-group">+ <label for="address">Address</label>+ <textarea id="address" name="address" required autocomplete="street-address" maxlength="300"></textarea>+ </div>++ <button type="submit">Save Address</button>+</form>+```+++## 10. Usability Testing and Analytics++### Guidelines++- **DO** test forms across multiple devices, browsers, and screen sizes.+- **DO** test keyboard-only navigation (using `Tab` and `Shift+Tab`) and verify visual focus.+- **DO** emulate various impairments (visual, motor) using browser tools.+- **DO** use analytics to monitor form completion rates and bounce points.+- **DO** track discrete events (e.g., field focus, click) to find micro-friction points.++- **DON'T** rely solely on automated tools (Lighthouse) for usability; test with real users.+- **DON'T** track sensitive personal data in standard event labels.++### Code Example++```html+<form action="/submit" method="POST" id="track-form">+ <label for="postal-code">ZIP or postal code</label>+ <input type="text" id="postal-code" name="postal-code" autocomplete="postal-code" maxlength="20" required>+ <button type="submit" id="submit-btn">Submit</button>+</form>++<script>+ const trackForm = document.getElementById('track-form');+ const trackBtn = document.getElementById('submit-btn');++ trackBtn.addEventListener('click', () => {+ console.log('Analytics Event: Submit clicked');+ });+</script>+```++## 11. Multi-Page Forms++### Guidelines++- **DO** clearly display progress through a multi-page form with clear labels and progress indicators.+- **DO** allow users to navigate backwards and forwards between pages.+- **DO** use context-specific `enterkeyhint` values (e.g., `"previous"`, `"next"`) to guide navigation via on-screen keyboards.+- **DO** design layouts so that the mobile keyboard does not obscure inputs or buttons (e.g., by placing them in the upper half of the viewport when focused or using CSS scroll-padding).++### Code Example++```html+<nav aria-label="Progress">+ <ol class="progress-tracker">+ <li class="step-done">Step 1: Account</li>+ <li class="step-active" aria-current="step">Step 2: Shipping</li>+ <li class="step-todo">Step 3: Payment</li>+ </ol>+</nav>++<button type="button" onclick="history.back()" enterkeyhint="previous">Previous</button>+<button type="submit" enterkeyhint="next">Next</button>+```diff --git a/skills/modern-web/guides/modern-web/modern-web.md b/skills/modern-web/guides/modern-web/modern-web.mdnew file mode 100644index 0000000..de9955c--- /dev/null+++ b/skills/modern-web/guides/modern-web/modern-web.md@@ -0,0 +1,52 @@+# Modern Web++A skill to search for specific web development use cases and retrieve their corresponding best practice guides.++## When to use++Must use this skill:+- At the **start** of implementing any web feature.+- Before creating a new component, to check if a standardized pattern already exists.+- To avoid implementing ad-hoc solutions or loading large dependencies unnecessarily.++## Usage Instructions++### Step 1. Search Use Cases++Search with an action-oriented query summarizing what you want to achieve using the `search` command. Run `modern-web.mjs` directly with `node`.++```sh+node <modern-web-directory>/modern-web.mjs search "<query>"+```++**Example Output**:+```json+[+ {+ "id": "content-vis",+ "description": "Defer rendering of offscreen content using content-visibility.",+ "category": "performance",+ "distance": "0.85"+ }+]+```++---++### Step 2. Retrieve Best Practices++Once you have a relevant `id` from the search results, call this script using the `retrieve` command to get the full guide. You can pass multiple IDs separated by commas.++```sh+node <modern-web-directory>/modern-web.mjs retrieve "<id>"+```+++**Example Output**:+`The markdown content of the guide describing implementation steps...`++## Guidelines++- Always search **first** to find the most specific design/performance patterns.+- These guides are usually framework-agnostic; adapt them correctly to your setup.+- Do not hallucinate guides or ignore them; they represent the preferred local standard for the user's project.diff --git a/skills/modern-web/guides/performance/performance.md b/skills/modern-web/guides/performance/performance.mdnew file mode 100644index 0000000..ded9ec2--- /dev/null+++ b/skills/modern-web/guides/performance/performance.md@@ -0,0 +1,366 @@+## Critical Rendering Path (CRP) Optimization++The Critical Rendering Path dictates how quickly the browser converts HTML, CSS, and JavaScript into painted pixels.++### DOs+* **DO inline critical CSS**: Extract styles necessary for above-the-fold content and inject them directly into the HTML `<head>`. Defer the rest of the stylesheet.+* **DO use `async` or `defer` for all non-critical scripts**: Prevent JavaScript from blocking the DOM parser. Use `defer` for scripts that depend on the DOM or each other, and `async` for independent scripts. `type="module"` is preferred for modern JavaScript and is deferred by default so no need to have an explicit `defer` attribute but you can use `async` on independent module scripts.+* **DO split CSS by media queries**: Use the `media` attribute on `<link>` tags so the browser downloads unused stylesheets (e.g., print styles or desktop styles on mobile) without blocking the render.+* **DO utilize resource hints**: Add `preconnect` or `dns-prefetch` for essential third-party domains (e.g., font foundries or API endpoints) to establish early TLS handshakes.++### DON'Ts+* **DON'T use `@import` in CSS**: This creates sequential request chains that delay the CSS Object Model (CSSOM) construction.+* **DON'T place large, non-critical JavaScript in the `<head>`**: This halts DOM construction until the script is downloaded, parsed, and executed.+* **DON'T load invisible or unreachable CSS/JS**: Ensure build tools apply tree-shaking and CSS minification to drop unreachable code before deployment.++### Code Examples++**HTML: Deferring Non-Critical CSS & Scripts**+```html+<!-- Inline critical styles directly in head -->+<style>+ body { margin: 0; font-family: system-ui; }+ .hero { min-height: 100vh; }+</style>++<!-- Defer non-critical CSS -->+<link rel="preload" href="non-critical.css" as="style" onload="this.onload=null;this.rel='stylesheet'">+<noscript><link rel="stylesheet" href="non-critical.css"></noscript>++<!-- Load CSS conditionally based on viewport -->+<link rel="stylesheet" href="mobile.css" media="(max-width: 768px)">++<!-- Defer JavaScript execution -->+<script defer src="app-bundle.js"></script>+```++### The Resource Hint Navigator++| Hint | Tool Use Case | Example |+| :--- | :--- | :--- |+| `preconnect` | Resolve TLS/DNS for known third-party APIs | API endpoints, font services |+| `dns-prefetch` | Lean fallback for non-critical third-party origins | Ad servers, analytics fallbacks |+| `preload` | Same-origin asset needed *now* for rendering | Hero images, render-blocking fonts |+| `prefetch` | Assets needed for next-page navigation | Next-page bundle, detail views |++**Single-Sentence Mental Model**: "Preconnect for domains, Preload for viewport, Prefetch for futures."++## Largest Contentful Paint (LCP) & Resource Fetching++LCP measures the time required to render the largest visible text or image block within the viewport. Optimize LCP by prioritizing visible elements and prepolishing.++### DOs+* **DO use `fetchpriority="high"` on the LCP image**: Signal to the browser's heuristic engine to elevate the image's priority above scripts and non-critical assets.+* **DO declare the LCP image in standard HTML**: Ensure the `<img>` tag is present in the raw HTML response so the preload scanner discovers it immediately. Avoid relying on JavaScript to mount the LCP element.+* **DO preload background images acting as LCP**: If the LCP element is a CSS `background-image`, force early discovery using `<link rel="preload" as="image">` coupled with `fetchpriority="high"`.+* **DO use `fetchpriority="low"` to demote competing elements**: Lower the priority of large images or carousels that appear above the fold but are *not* the primary LCP element.++### DON'Ts+* **DON'T lazy-load the LCP image**: Never apply `loading="lazy"` to above-the-fold images. This purposefully delays the fetch until layout calculation is complete, severely degrading LCP.+* **DON'T overuse `fetchpriority="high"`**: Prioritization is a zero-sum mechanism. Elevating too many resources creates network contention and negates the benefit.+* **DON'T implement complex JavaScript loaders for the hero section**: Client-side rendering of the LCP element introduces substantial request chains (HTML -> JS -> Execution -> Image Request).++### Code Examples++**HTML: LCP Image Optimization**+```html+<!-- Standard LCP Image -->+<img+ src="/images/hero.webp"+ alt="Hero Product"+ fetchpriority="high"+ decoding="sync"+ width="1200"+ height="600"+>++<!-- Preloading a CSS-based LCP background -->+<link rel="preload" as="image" href="/images/bg-hero.webp" fetchpriority="high" type="image/webp">++<!-- Demoting an above-the-fold non-LCP carousel image -->+<img src="/images/carousel-2.webp" fetchpriority="low" alt="Slide 2">+```++## Interaction to Next Paint (INP) & Main Thread Unblocking++INP measures the latency of all interactive events across the page's lifecycle. Poor INP is caused by long-running JavaScript tasks blocking the main thread.++### DOs+* **DO break up long tasks**: Any JavaScript execution exceeding 50ms should be split. Yield to the main thread frequently so the browser can process pending user inputs.+* **DO use `scheduler.yield()` with a fallback**: Utilize the modern `scheduler.yield()` API to place task continuations at the *front* of the queue, falling back to `setTimeout` wrapped in a Promise for unsupported browsers.+* **DO debounce or throttle rapid event listeners**: Limit the execution frequency of handlers attached to `scroll`, `resize`, or rapid `input` events.+* **DO separate UI updates from heavy computations**: Update the UI synchronously to provide immediate visual feedback, then push background processing to a Web Worker or deferred task.++### DON'Ts+* **DON'T rely solely on `setTimeout(..., 0)` for continuous yielding**: Standard `setTimeout` places continuations at the *back* of the task queue, potentially causing long delays if other tasks are pending.+* **DON'T cause layout thrashing**: Avoid interleaving DOM reads (`offsetHeight`, `getBoundingClientRect`) and writes (`style.height`) within the same loop. Batch DOM reads, then batch DOM writes.+* **DON'T block the thread with recurring timers**: Avoid heavy polling with `setInterval` that starves the main thread.++### Code Examples++**JS: `scheduler.yield` Polyfill and Usage**+```javascript+// Polyfill for yielding to main thread+async function yieldToMain() {+ if ('scheduler' in window && 'yield' in scheduler) {+ return await scheduler.yield();+ }+ return new Promise(resolve => setTimeout(resolve, 0));+}++// Processing a large array without blocking user input+async function processLargeList(items) {+ for (let i = 0; i < items.length; i++) {+ processItem(items[i]);++ // Yield every 50 iterations to allow rendering/interaction+ if (i % 50 === 0) {+ await yieldToMain();+ }+ }+}+```++### Main Thread Task Slicing Heuristic++**The 50ms Rule for INP**:+- **< 50ms**: Execute synchronously.+- **50ms - 250ms**: Slice tasks and yield with `scheduler.yield()`.+- **> 250ms**: Offload to a Web Worker.++## Third-Party Script Management++Third-party scripts (analytics, ads, chat widgets) are the primary source of main thread congestion.++### DOs+* **DO avoid third-party scripts blocking main content**: Use `defer` with all third-party scripts unless critical to the page load and load them in the footer of the page, rather than the `<head>`.+* **DO self-host critical third-party dependencies**: Reduce DNS lookups and enforce custom `Cache-Control` logic by hosting third-party libraries on the origin domain.++### Code Examples++**HTML: Third-Party Script Execution**+```html+<!-- 1. Place third-party scripts near the end of the page with the defer attribute -->+<script defer src="http://www.example.com/third-party.js"></script>+```++## CSS Rendering & Containment Optimization++Rendering involves Layout, Style, Paint, and Compositing calculations. CSS Containment limits the scope of these calculations which is useful on large, complex pages where such calculations can cause performance problems.++### DOs+* **DO use `content-visibility: auto` on off-screen sections on large, complex pages**: Instruct the browser to skip layout and paint calculations for entire subtrees until they approach the viewport.+* **DO pair `content-visibility` with `contain-intrinsic-size`**: Prevent layout shifts and scrollbar jumping by providing a placeholder height/width for unrendered containers.+* **DO apply explicit CSS containment (`contain`)**: For isolated UI components (like modals or widgets), use `contain: layout style paint` to prevent internal changes from triggering page-wide reflows.++### DON'Ts+* **DON'T apply `content-visibility: auto` on smaller, simpler pages**: The gains will be negligible and there are risks of side effects with content jumping.+* **DON'T apply `content-visibility: auto` to above-the-fold content**: The browser will still evaluate it, but forcing it through the containment engine unnecessarily adds slight overhead to visible elements.+* **DON'T overuse `will-change` globally**: Indiscriminately applying `will-change: transform` to multiple elements consumes excessive VRAM, causing GPU crashes or sluggish rendering.+* **DON'T forget accessibility when hiding elements**: `content-visibility: auto` keeps elements in the DOM for screen readers. If content should be truly hidden from assistive technology when off-screen, manage `aria-hidden` attributes manually.++### Code Examples++**CSS: Content Visibility and Containment**+```css+/* Optimize a long list of articles below the fold */+.article-list-item {+ content-visibility: auto;+ contain-intrinsic-size: auto 600px; /* Provides a 600px placeholder */+}++/* Scope a complex widget to prevent layout thrashing */+.isolated-widget {+ contain: layout style paint;+}++/* Hardware accelerate an animation only on hover */+.interactive-button:hover {+ will-change: transform;+ transform: scale(1.05);+}+```++## Modern Image & Media Optimization++Images typically represent the largest payload on a given web page. Optimization requires format negotiation, responsive sizing, and layout stabilization.++### DOs+* **DO serve modern formats (AVIF / WebP)**: Use the `<picture>` element to offer AVIF (best compression), falling back to WebP, and finally JPEG/PNG for legacy browsers.+* **DO apply explicit `width` and `height` attributes**: Setting native attributes allows the browser to compute the aspect ratio immediately, reserving space and eliminating CLS. Image dimensions may be set either as HTML attributes or CSS properties.+* **DO utilize `loading="lazy"` on all below-the-fold images**: Utilize native browser lazy loading to defer network requests for images outside the initial viewport.+* **DO implement responsive images with `srcset` and `sizes`**: Serve tailored resolutions based on screen density and viewport width to prevent mobile devices from downloading desktop-sized images.++### DON'Ts+* **DON'T lazy load above-the-fold images**: This directly harms LCP. Visible images must use `loading="eager"` (the default).+* **DON'T delete necessary dimensions**: Failing to specify width/height on lazy loaded images causes layout shifts.+* **DON'T omit the `sizes` attribute when using `srcset`**: Without `sizes`, the browser assumes `100vw` and downloads the largest available image.++### Code Examples++**HTML: Comprehensive Responsive Image Component**+```html+<picture>+ <!-- Modern Formats with Source Negotiation -->+ <source type="image/avif" srcset="hero-400w.avif 400w, hero-800w.avif 800w" sizes="(max-width: 600px) 100vw, 50vw">+ <source type="image/webp" srcset="hero-400w.webp 400w, hero-800w.webp 800w" sizes="(max-width: 600px) 100vw, 50vw">++ <!-- Fallback + Dimensions + Priority for Above-The-Fold -->+ <img+ src="hero-800w.jpg"+ alt="Descriptive text"+ width="800"+ height="600"+ fetchpriority="high"+ loading="eager"+ >+</picture>++<!-- Below-The-Fold Image -->+<img+ src="footer-icon.png"+ alt="Footer Logo"+ width="100"+ height="100"+ loading="lazy"+>++<!-- DO: Use native lazy loading for below the fold iframes -->+<iframe src="https://example.com/map" width="800" height="600" loading="lazy" title="Example Map"></iframe>+```++## Service Workers & Caching Strategies++Client-side caching via Service Workers allows applications to bypass the network entirely, serving resources from disk/memory.++### DOs+* **DO use a `CacheFirst` strategy for static, versioned assets**: Immutable files (fonts, JS/CSS bundles with hash strings) should be served directly from the cache to guarantee instant loading.+* **DO use `StaleWhileRevalidate` for dynamic, non-critical resources**: For API calls where slight staleness is acceptable, serve immediately from cache while silently updating the cache in the background.+* **DO implement a `NetworkFirst` strategy for HTML documents**: Ensure the user always receives the latest application shell and manifest, falling back to cache only if offline.+* **DO restrict cache sizes and expiry**: Use expiration plugins to prevent the Service Worker from exhausting the device's storage quota.++### DON'Ts+* **DON'T cache opaque responses blindly**: Responses from third-party domains lacking CORS headers are "opaque". Caching them heavily consumes quota and fails silently. Only cache them using `NetworkFirst` or `StaleWhileRevalidate`.+* **DON'T cache POST requests**: Service workers cannot cache non-GET requests natively. Implement background sync queues for offline submissions.+* **DON'T bypass versioning**: Failing to update asset hashes/versions will trap users in infinite cache loops.++### Code Examples++**JS: Service Worker Caching via Workbox**+```javascript+import { registerRoute } from 'workbox-routing';+import { CacheFirst, StaleWhileRevalidate, NetworkFirst } from 'workbox-strategies';+import { ExpirationPlugin } from 'workbox-expiration';+import { CacheableResponsePlugin } from 'workbox-cacheable-response';++// 1. HTML Documents: Network First+registerRoute(+ ({ request }) => request.mode === 'navigate',+ new NetworkFirst({ cacheName: 'pages-cache' })+);++// 2. Static Assets (JS, CSS, Fonts): Cache First+registerRoute(+ ({ request }) => ['style', 'script', 'font'].includes(request.destination),+ new CacheFirst({+ cacheName: 'static-resources',+ plugins: [+ new CacheableResponsePlugin({ statuses: [0, 200] }),+ new ExpirationPlugin({ maxEntries: 50, maxAgeSeconds: 30 * 24 * 60 * 60 })+ ]+ })+);++// 3. API Responses: Stale While Revalidate+registerRoute(+ ({ url }) => url.pathname.startsWith('/api/v1/content'),+ new StaleWhileRevalidate({+ cacheName: 'api-cache',+ plugins: [+ new CacheableResponsePlugin({ statuses: [0, 200] })+ ]+ })+);+```++## Web Fonts Optimization++Web fonts are a common source of render blocking. Optimizing them reduces the Flash of Invisible Text (FOIT) and speeds up initial rendering.++### DOs+* **DO preload critical fonts**: Use `<link rel="preload" as="font" type="font/woff2" crossorigin>` for fonts seen above the fold.+* **DO subset fonts**: Trim font weights and glyph variations to include only the characters your application requires.++### DON'Ts+* **DON'T preload all fonts**: Over-preloading leads to network contention that starves other critical assets.++### Code Examples++**CSS: Font Loading Face**+```css+@font-face {+ font-family: 'Modern Sans';+ src: url('/fonts/modern-sans.woff2') format('woff2');+}+```++**HTML: Critical Font Preload**+```html+<!-- Always use crossorigin for fonts even if on the same origin -->+<link rel="preload" href="/fonts/modern-sans.woff2" as="font" type="font/woff2" crossorigin>+```++## Video Performance & Metrics++Video payloads are among the heaviest assets. Optimization focuses on reducing bandwidth stall and preserving Cumulative Layout Shift (CLS) stability.++### DOs+* **DO specify explicit `width` and `height` attributes**: Setting native dimensions reserves layout space and prevents CLS.+* **DO provide a `poster` image fallback**: Display a lightweight image placeholder while the video buffers to improve perceived performance.+* **DO use `preload="none"` for non-critical videos**: Delay bandwidth consumption for below-the-fold or non-autoplaying videos.+* **DO serve modern formats via source negotiation**: Offer WebM (better compression ratio) alongside standard MP4 formats.+* **DO use `loading="lazy"` for offscreen videos**: Lazy-loading videos allow `poster` and `preload` downloads to be deferred until the video is in or near the viewport.++### DON'Ts+* **DON'T auto-play video files blindly**: Rely on user intent or use progressive enhancement streams.+* **DON'T auto-play large video files at all**: Rely on user intent before downloading large files.++### Code Examples++**HTML: Accessible and Dynamic Video Loader**+```html+<video+ controls+ width="1200"+ height="675"+ poster="/images/video-poster.webp"+ preload="none"+>+ <source src="/videos/intro.webm" type="video/webm">+ <source src="/videos/intro.mp4" type="video/mp4">+ <!-- Include accessibility tracks -->+ <track src="/video-caps.vtt" kind="captions" srclang="en" label="English">+</video>+```++## JavaScript Code-Splitting++Heavy monolithic bundles block main thread parse times on low-end devices. Splitting ensures we only download bytes required for the immediate viewport.++### DOs+* **DO use dynamic imports**: Split routes or heavy UI libraries using standard `import()` specifications.+* **DO configure bundler asset chunking**: Use Vite or Webpack rollup directives to split third-party vendors from runtime application logic.++### DON'Ts+* **DON'T ship a single, enormous `app.js` bundle**: It increases parse time and memory consumption for initial views.++### Code Examples++**JS: Route based Dynamic Splitting**+```javascript+// Dynamic import of heavy module only when button is clicked+document.getElementById('heavy-btn').addEventListener('click', async () => {+ const { heavyFunction } = await import('./heavy-module.js');+ heavyFunction();+});+```diff --git a/skills/modern-web/guides/webmcp/webmcp.md b/skills/modern-web/guides/webmcp/webmcp.mdnew file mode 100644index 0000000..a9f7629--- /dev/null+++ b/skills/modern-web/guides/webmcp/webmcp.md@@ -0,0 +1,44 @@+# WebMCP (Web Model Context Protocol)++WebMCP is a browser-native JavaScript API that allows web pages to expose their client-side functionality as structured "tools" to AI agents, browser assistants, and assistive technologies.++IMPORTANT: WebMCP is currently **Chrome-only** (Early Preview). It requires Chrome `146.0.7672.0` or higher and the `#enable-webmcp-testing` flag.++**Crucial Distinction:** WebMCP runs entirely **client-side** in the browser tab. It is *not* a backend server, and it does *not* use HTTP, Server-Sent Events (SSE), or `stdio` transports. The web page itself acts as the tool registry.++Currently, WebMCP **only supports Tools**. It does not support the "Resources" or "Prompts" primitives found in the backend Model Context Protocol.++## Quick Overview++- **Imperative API**: Use `navigator.modelContext.registerTool()` for complex logic and dynamic interactions.+- **Declarative API**: Annotate standard HTML `<form>` elements with `toolname` and `tooldescription` to turn them into tools.++## Best Practices++* **Naming and Semantics**: Use specific verbs describing exact behavior (e.g. `create-event` vs `start-event-creation-process`). Favor positive descriptions over listing limitations.+* **Schema Design**: Accept raw user input (avoid agent math/calculation). Ensure all parameters have specific types and explain the purpose of options.+* **Reliability**: Validate constraints in code and return descriptive errors for retries. Handle rate limiting gracefully. Ensure the function returns *after* UI state updates for consistency.+* **Tool Strategy**: Tools should be atomic, composable, and distinct. Do not force flow control instructions ("Don't call B after A") — let the agent decide. Register/unregister tools dynamically depending on the current page context. Use `annotations: { readOnlyHint: true }` (placed after `execute`) for tools that do not modify state to inform the agent of safe execution.+* **Clean Up**: Always use `AbortSignal` to unregister tools when pages transition or resources are released to avoid leaks and collisions. Do not use `unregisterTool`.++### When to Discourage WebMCP++* **Backend Operations**: If the operation requires intensive compute, access to secure databases, or requires API keys that shouldn't be exposed to the client, use a standard backend MCP server instead of WebMCP.+* **High-Risk Actions without Guardrails**: Avoid auto-submitting tools for destructive or irreversible actions (e.g., deleting data) unless the UI requires manual user confirmation outside the agent's control.+* **Hyper-Dynamic State**: If data changes faster than the agent can react, it may work with stale context.++### Anti-Patterns & Warnings (DO NOT DO THIS)++* **Do not use backend transports.** WebMCP is for browser tabs, not Node.js background processes.+* **Do not include Resources or Prompts.** These are not supported in the current WebMCP spec.+* **Do not ignore `inputSchema` structure.** Always provide clear descriptions for every parameter to minimize agent hallucinations.+* **Do not use outside of a Secure Context (HTTPS).**++## Implementation Status++WebMCP is currently in early preview in Chrome browser:++* **Current Status**: Early preview.+* **Required Version**: Chrome `146.0.7672.0` or higher.+* **Activation**: Requires enabling the flag `chrome://flags/#enable-webmcp-testing`.+* **Specification**: Evolving [Draft Community Group specification](https://webmachinelearning.github.io/webmcp/); not yet a standards-track recommendation.