Keep your coding agent up to date with the latest web best practices
Release v0.0.95
github-actions[bot]06b89cd7d2b9
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 104f2cf..c8f9fef 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.94"+ "version": "0.0.95"}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 06a754c..3de74f8 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.94",+ "version": "0.0.95","author": {"name": "Google Chrome"}diff --git a/README.md b/README.mdindex 3c9f97c..c33d57f 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.94`+#### Skill Coverage in `v0.0.95`<details><summary><strong>83 web features with implementation guidance from Chrome's experts</strong>: `::backdrop`, `:autofill`, `:has()`, `:not()`, `:user-valid and :user-invalid`, `@starting-style`, `<details>`, `<dialog closedby>`, `<dialog>`, `<link rel="expect">`, `<link rel="preload">`, `AbortController and AbortSignal`, `accent-color`, `Active view transition`, `Anchor position container queries`, `Anchor positioning`, `blocking="render"`, `calc-size()`, `color-scheme`, `Container queries`, `Container scroll-state queries`, `content-visibility`, `Cross-document view transitions`, `Customizable <select>`, `Email, telephone, and URL <input> types`, `enterkeyhint`, `Event timing`, `Fetch`, `Fetch priority`, `fetchLater`, `field-sizing`, `font-size-adjust`, `Form-associated WebMCP attributes`, `hidden="until-found"`, `image-set()`, `Individual transform properties`, `inert`, `inputmode`, `Interest invokers`, `interpolate-size`, `Intersection observer`, `Intl.DurationFormat`, `Invoker commands`, `Language detector`, `light-dark()`, `linear() easing`, `Long animation frames`, `Masks`, `moveBefore()`, `Mutually exclusive <details> elements`, `Navigation API`, `navigator.modelContext`, `overlay`, `Page visibility`, `Page visibility state`, `Popover`, `popover="hint"`, `prefers-color-scheme media query`, `prefers-contrast media query`, `prefers-reduced-motion media query`, `Registered custom properties`, `Scheduler API`, `Scroll snap`, `Scroll-driven animations`, `scroll-initial-target`, `scrollbar-color`, `scrollbar-width`, `scrollend`, `scrollIntoView()`, `sibling-count() and sibling-index()`, `sin(), cos(), tan(), asin(), acos(), atan(), and atan2() (CSS)`, `Speculation rules`, `Summarizer`, `Temporal`, `text-box`, `text-wrap`, `text-wrap: balance`, `text-wrap: pretty`, `Top-level await`, `transition-behavior`, `Translator`, `View transitions`, `view-transition-class`</summary>diff --git a/THIRD_PARTY_NOTICES b/THIRD_PARTY_NOTICESdeleted file mode 100644index aaa9b31..0000000--- a/THIRD_PARTY_NOTICES+++ /dev/null@@ -1,322 +0,0 @@-Name: @huggingface/jinja-URL: https://github.com/huggingface/huggingface.js.git-Version: 0.5.5-License: MIT--MIT License--Copyright (c) 2023 Hugging Face--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in all-copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.----------------------- DEPENDENCY DIVIDER ----------------------Name: @huggingface/transformers-URL: https://github.com/huggingface/transformers.js#readme-Version: 3.8.1-License: Apache-2.0--- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/-- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION-- 1. Definitions.-- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.-- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.-- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright [yyyy] [name of copyright owner]-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.----------------------- DEPENDENCY DIVIDER ----------------------Name: @tensorflow/tfjs-backend-cpu-URL: https://github.com/tensorflow/tfjs.git-Version: 4.22.0-License: Apache-2.0---------------------- DEPENDENCY DIVIDER ----------------------Name: @tensorflow/tfjs-converter-URL: https://github.com/tensorflow/tfjs.git-Version: 4.22.0-License: Apache-2.0---------------------- DEPENDENCY DIVIDER ----------------------Name: @tensorflow/tfjs-core-URL: https://github.com/tensorflow/tfjs.git-Version: 4.22.0-License: Apache-2.0---------------------- DEPENDENCY DIVIDER ----------------------Name: encoding-URL: https://github.com/andris9/encoding.git-Version: 0.1.13-License: MIT--Copyright (c) 2012-2014 Andris Reinman--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.----------------------- DEPENDENCY DIVIDER ----------------------Name: node-fetch-URL: https://github.com/bitinn/node-fetch-Version: 2.6.13-License: MIT--The MIT License (MIT)--Copyright (c) 2016 David Frank--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in all-copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.------------------------ DEPENDENCY DIVIDER ----------------------Name: onnxruntime-web-URL: https://github.com/Microsoft/onnxruntime.git-Version: 1.22.0-dev.20250409-89f8206ba4-License: MIT\ No newline at end of filediff --git a/gemini-extension.json b/gemini-extension.jsonindex 6bd1d91..3c9543f 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.94",+ "version": "0.0.95","author": {"name": "Google Chrome"}diff --git a/package.json b/package.jsonindex d49355a..d0d72c1 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.94",+ "version": "0.0.95","publisher": "GoogleChrome","engines": {"vscode": "^1.90.0",diff --git a/skills/modern-web/guides/accessibility/accessible-error-announcement.md b/skills/modern-web/guides/accessibility/accessible-error-announcement.mddeleted file mode 100644index 6d011dc..0000000--- a/skills/modern-web/guides/accessibility/accessible-error-announcement.md+++ /dev/null@@ -1,207 +0,0 @@-# Accessible Error Announcement--## The Problem-Standard HTML5 validation provides visual feedback (via `:invalid` or `:user-invalid`), but it doesn't automatically synchronize with accessibility attributes like `aria-invalid`.--If you use standard `:invalid` styling, screen readers might announce "Invalid entry" the moment a user tabs into a required field that is currently empty. This creates a disruptive experience for users using assistive technologies, as the error is announced before interaction has occurred.--## The Solution-We want the *programmatic* state (`aria-invalid="true"`) to be applied **at the exact same moment** the *visual* state (`:user-invalid`) applies. Since `:user-invalid` relies on the browser's internal "user-interacted" flag, we can use JavaScript to check that this selector matches during standard interaction events.--See [MDN aria-invalid](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-invalid) for more details.--### Implementation Strategy--1. **Visual Layer**: Use CSS `:user-invalid` to show borders/icons.-2. **Accessibility Layer**: Use `aria-invalid` and `aria-errormessage` to communicate state to Assistive Technology (AT).-3. **Bridge Visual & Accessibility Layer**: Create a lightweight JavaScript utility that listens for `blur` and `input` events, checks if the element matches `:user-invalid`, and updates the ARIA attributes accordingly.--## Implementation Guide--### 1. HTML Structure-Link your input to its error message using `aria-errormessage` (or `aria-describedby` for broader support).--```html-<form>- <div class="field">- <label for="email">Email</label>- <input- type="email"- id="email"- required- aria-errormessage="email-error"- >- <span id="email-error" class="error-msg">- Please enter a valid email address.- </span>- </div>-</form>-```--### 2. CSS-Control the visibility of the error message using the native pseudo-class `:user-invalid`.--```css-.error-msg {- display: none;- color: #d93025;-}--/* Show error message when input is user-invalid */-input:user-invalid ~ .error-msg {- display: block;-}--/* Optional: Visual cues on the input itself */-input:user-invalid {- border-color: #d93025;-}-```--### 3. JavaScript-Since there is no "UserInvalidChanged" event, hook into standard form events to check the state.--```javascript-const updateAriaState = (event) => {- const input = event.target;- if (!input.matches?.('input, textarea, select')) return;-- // Check if the browser currently considers this input "user-invalid"- const isUserInvalid = input.matches(':user-invalid');-- if (isUserInvalid) {- input.setAttribute('aria-invalid', 'true');- } else {- input.removeAttribute('aria-invalid');- }-};--// Listen on the document to handle dynamically added fields.-// 'blur' and 'focus' do not bubble, so we must use the capture phase (true).-document.addEventListener('blur', updateAriaState, true);-document.addEventListener('focus', updateAriaState, true);--// Also update on input if we've already shown the error,-// so the error clears immediately when fixed.-document.addEventListener('input', (event) => {- const input = event.target;- if (!input.matches?.('input, textarea, select')) return;-- const hasAriaInvalid = input.hasAttribute('aria-invalid');- const ariaInvalid = input.getAttribute('aria-invalid');- if (hasAriaInvalid && ariaInvalid === 'true') {- updateAriaState(event);- }-});-```--## Fallbacking & Browser Support--The `:user-invalid` pseudo-class is widely supported (Baseline 2023), but older browsers need a fallback.--### Feature Detection-You can check for support in CSS and JavaScript.--**JavaScript Check:**-```javascript-if (!CSS.supports('selector(:user-invalid)')) {- // Fallback logic here-}-```--### CSS for Fallback-To ensure your fallback logic is visually indistinguishable from the native behavior, you must apply your error styles to both the pseudo-class and your fallback class.--```css-/* Apply error styles to both native selector and fallback class */-input:user-invalid,-input.user-invalid-fallback {- border-color: #d93025;- background-color: #fce8e6;-}--/* Show error message for both cases */-input:user-invalid ~ .error-msg,-input.user-invalid-fallback ~ .error-msg {- display: block;-}-```--### Fallback Logic-If `:user-invalid` is missing manually track the interaction state using a `WeakMap`.--```javascript-const UserInvalidFallback = (() => {- const dirtyState = new WeakMap();-- const updateState = (input) => {- const isValid = input.checkValidity();-- // Update both visual and ARIA state- input.classList.toggle('user-invalid-fallback', !isValid);- input.classList.toggle('user-valid-fallback', isValid);-- if (!isValid) {- input.setAttribute('aria-invalid', 'true');- } else {- input.removeAttribute('aria-invalid');- }- };-- const handleEvent = (event) => {- const input = event.target;-- if (event.type === 'reset' && input.matches?.('form')) {- const controls = input.elements || [];- for (const control of controls) {- dirtyState.delete(control);- control.classList.remove('user-invalid-fallback');- control.classList.remove('user-valid-fallback');- control.removeAttribute('aria-invalid');- }- return;- }-- if (!input.matches?.('input, textarea, select')) return;-- if (event.type === 'input' || event.type === 'change') {- const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };- state.hasInteracted = true;- dirtyState.set(input, state);- if (state.hasBlurred) {- updateState(input);- }- } else if (event.type === 'blur') {- const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };- state.hasBlurred = true;- dirtyState.set(input, state);- if (state.hasInteracted) {- updateState(input);- }- }- };-- const init = () => {- if (CSS.supports('selector(:user-invalid)')) return;-- document.addEventListener('blur', handleEvent, true); // Capture phase required- document.addEventListener('input', handleEvent, true);- document.addEventListener('change', handleEvent, true);- document.addEventListener('reset', handleEvent, true); // Capture resets- };-- return { init };-})();--// Initialize globally-UserInvalidFallback.init();-```--## Other Considerations--1. **`aria-live` vs. `aria-errormessage`**:- * `aria-errormessage` connects the input to the text, but screen readers might not announce it immediately upon appearance (only when focusing the input).- * If you need *immediate* announcement when the error appears (e.g., on blur), consider adding `role="alert"` or `aria-live="polite"` to the error message container, but test thoroughly to avoid "double announcement" when the user focuses the field to fix it.--2. **Internationalization**:- * Ensure the text content of your error message (`#email-error`) is translated. The logic remains the same.diff --git a/skills/modern-web/guides/built-in-ai/language-detection.md b/skills/modern-web/guides/built-in-ai/language-detection.mddeleted file mode 100644index e9456f6..0000000--- a/skills/modern-web/guides/built-in-ai/language-detection.md+++ /dev/null@@ -1,87 +0,0 @@-The **Language Detector API** is a client-side web API designed to identify the language of a given text string. By performing detection locally in the browser, it enhances user privacy and reduces the need for heavy external libraries or costly server-side calls.--## Key Use Cases--- **Translation Prep:** Identifying the source language before sending text to a translator.-- **Safety & Filtering:** Loading specific models for tasks like toxicity detection.-- **Accessibility:** Labeling content with the correct `lang` attribute for screen readers.-- **UI Localization:** Adjusting application interfaces based on the user's input language.--## Hardware & System Requirements--- **OS:** Windows 10/11, macOS 13+, Linux, or Chromebook Plus.-- **Storage:** 22 GB free space (model is removed if space drops below 10 GB).-- **RAM/CPU:** 16 GB RAM and 4+ CPU cores.-- **VRAM:** 4 GB+ if using a GPU.--## Implementation Guide--### 1. Model Management & User Activation--Check model availability before attempting to instantiate the detector or trigger download.--**MANDATORY:** Instantiating the language detector or triggering a model download with `LanguageDetector.create()` **MUST** be initiated by a user gesture (such as a button click) to prevent a `NotAllowedError` when the model is in a `downloadable` or `downloading` state.--```javascript-// Check if the model is available or downloadable-const availability = await LanguageDetector.availability();--if (availability !== 'unavailable') {- button.addEventListener('click', async () => {- const detector = await LanguageDetector.create({- monitor(m) {- m.addEventListener('downloadprogress', (e) => {- console.log(`Downloaded ${e.loaded * 100}%`);- });- },- });- });-}-```--### 2. Running Detection--The API returns a ranked list of potential languages with a confidence score between `0.0` and `1.0`.--```javascript-const someUserText = 'Hallo und herzlich willkommen!';-const results = await detector.detect(someUserText);--for (const result of results) {- // result.detectedLanguage (e.g., 'de')- // result.confidence (e.g., 0.999)- console.log(result.detectedLanguage, result.confidence);-}-```--Avoid using the detector on very short phrases or single words, as accuracy drops significantly.--## Security and Environment--- **Iframes:** Cross-origin iframes require an explicit Permissions Policy to access the API.- ```html- <iframe- src="https://cross-origin.example.com/"- allow="language-detector"- ></iframe>- ```-- **Web Workers:** The API is **not** currently available in Web Workers due to Permission Policy complexities.-- **Privacy:** No data is sent to Google or third parties during the detection process.--## Fallback Strategy--Language detector has limited availability.--Before use, check if the `LanguageDetector` object is available in the global scope:--```javascript-if ('LanguageDetector' in self) {- // The Language Detector API is supported.-} else {- // Execute fallback strategy-}-```--If the `LanguageDetector` API is unsupported or availability checks return `'unavailable'`, you must gracefully fall back:-1. **Remote API Fallback**: Redirect the detection request to a server endpoint or a cloud API (such as the Vertex AI Gemini API) to identify the language.-2. **Graceful Degradation**: Disable language detection elements/buttons and inform the user that client-side detection is currently unsupported in this browser, preventing any unhandled exceptions or crashes.diff --git a/skills/modern-web/guides/built-in-ai/summarizer.md b/skills/modern-web/guides/built-in-ai/summarizer.mddeleted file mode 100644index f04313a..0000000--- a/skills/modern-web/guides/built-in-ai/summarizer.md+++ /dev/null@@ -1,152 +0,0 @@-The **Summarizer API** allows web developers to offer local, AI-powered text distillation directly within the browser using **Gemini Nano**. This API supports various formats, including key points, headlines, and TL;DRs, while operating entirely on-device to ensure user privacy.-------## Getting Started--The Summarizer API is available starting in **Chrome 138**. It requires a one-time model download of Gemini Nano.---### Hardware & Software Requirements--- **OS**: Windows 10/11, macOS 13+, Linux, or ChromeOS (Chromebook Plus).-- **Storage**: 22GB free space for the profile volume.-- **RAM/CPU**: 16GB+ RAM and 4+ CPU cores.-- **VRAM**: 4GB+ (if using GPU).--### Model Download and Availability--Check if the model is ready, needs downloading, or is unavailable.--**Mandatory Options Passing:** You must pass the identical configuration options object to both `Summarizer.availability(options)` and `Summarizer.create(options)`. Do NOT use the deprecated `window.ai.summarizer` API surface.--**Mandatory Progress Monitoring:** You MUST implement a monitor for model download progress by providing a `monitor(m)` callback to `Summarizer.create()` and adding a listener for the `downloadprogress` event.--**User Gesture Requirement:** When `availability` is `'downloadable'` or `'downloading'`, triggering the actual download via `Summarizer.create()` requires a user gesture (such as a user click). You must place the creation call inside an event listener rather than calling it unconditionally on page load to prevent `NotAllowedError`.--```javascript-const options = {- type: 'key-points',- format: 'plain-text',- length: 'medium'-};--const availability = await Summarizer.availability(options);--if (availability === 'available') {- const summarizer = await Summarizer.create(options);- // Ready to use immediately-} else if (availability === 'downloadable') {- // A user gesture is strictly required to start the download- document.getElementById('start-download-btn').addEventListener('click', async () => {- const summarizer = await Summarizer.create({- ...options,- monitor(m) {- m.addEventListener('downloadprogress', (e) => {- console.log(`Downloaded ${Math.round((e.loaded / e.total) * 100)}%`);- });- },- });- });-}-```--## API Functions & Configuration--When creating a summarizer via `Summarizer.create(options)`, you can customize-the output:--| Parameter | Options | Description |-| :----------- | :----------------------------------------- | :-------------------------------------- |-| `type` | `key-points`, `tldr`, `teaser`, `headline` | Defines the summary strategy. |-| `format` | `markdown`, `plain-text` | Output syntax style. |-| `length` | `short`, `medium`, `long` | Target length (e.g., 1 vs 5 sentences). |-| `preference` | `auto`, `speed`, `capability` | Balances latency vs. quality. |--### Example Configuration--```javascript-const options = {- sharedContext: 'This is a scientific article',- type: 'key-points',- format: 'markdown',- length: 'medium',-};--if (navigator.userActivation.isActive) {- const summarizer = await Summarizer.create(options);-}-```--### Language Support--You can specify expected languages to ensure the browser can handle the specific-summary request.--```javascript-const summarizer = await Summarizer.create({- type: 'key-points',- expectedInputLanguages: ['en', 'ja'],- outputLanguage: 'es',-});-```--## Summarization Methods--### 1. Batch Summarization--Processes the entire text at once and returns the result.--```javascript-const longText = document.querySelector('article').innerText;-const summary = await summarizer.summarize(longText, {- context: 'This article is intended for a tech-savvy audience.',-});-console.log(summary);-```--### 2. Stream Summarization--Returns results in real-time as the model generates them, providing a more-responsive UI.--```javascript-const stream = summarizer.summarizeStreaming(longText);-for await (const chunk of stream) {- console.log(chunk);-}-```--## Security and Permissions--- **Data Privacy**: No data is sent to Google; processing happens on the local- device.-- **Cross-Origin**: Access can be granted to iframes using the Permission- Policy.- ```html- <iframe src="https://example.com/" allow="summarizer"></iframe>- ```-- **Web Workers**: Currently not supported.--## Fallback Strategy--Summarizer has limited availability.--Before initializing or querying availability, check if the browser supports the `Summarizer` API:--```javascript-if ('Summarizer' in self) {- // The Summarizer API is supported.-} else {- // Execute fallback strategy-}-```--If the `Summarizer` API is unsupported or availability checks return `'unavailable'`, you must gracefully fall back.--Recommended options:-1. **Remote API Fallback**: Direct the distillation request to a server endpoint or remote API (such as the Vertex AI Gemini API) so that users still get summaries.-2. **Graceful Degradation**: Visually disable the summarization controls in the UI, or hide the button while displaying a friendly message (e.g., `"Local summarization is currently unsupported in this browser"`). Do not allow interaction to trigger generic unhandled runtime exceptions.-3. **Polyfill Fallback**: You can use community-maintained polyfills like `built-in-ai-task-apis-polyfills` or `prompt-api-polyfill` to emulate the API surface using remote services with models in the cloud or on-device inference with local models.--> **Privacy and Cost Implications:** These polyfills possibly proxy requests to remote servers (such as Gemini API over the cloud). This completely nullifies the on-device privacy guarantees of the native Built-in AI APIs and will incur server-side API usage costs.diff --git a/skills/modern-web/guides/built-in-ai/translator.md b/skills/modern-web/guides/built-in-ai/translator.mddeleted file mode 100644index 85db741..0000000--- a/skills/modern-web/guides/built-in-ai/translator.md+++ /dev/null@@ -1,159 +0,0 @@-The **Translator API** allows developers to perform client-side text translation using built-in AI models in Chrome. This approach eliminates the need for cloud-based translation services for ephemeral content, reducing costs and improving privacy by keeping data on the user's device.---## Prerequisites & Requirements--### Browser Support--- **Chrome:** Version 138+ (Desktop only).-- **Not Supported:** Mobile (Android/iOS), Edge, Firefox, Safari.--### Hardware Requirements--To run Gemini Nano and associated models, the system needs:--- **Operating System:** Windows 10/11, macOS 13+, Linux, or ChromeOS (Chromebook- Plus).-- **Storage:** At least **22 GB** free on the Chrome profile volume.-- **Memory/CPU:** 16 GB+ RAM and 4+ CPU cores.-- **GPU:** 4 GB+ VRAM (Mandatory for Prompt API with audio).-- **Network:** Required only for the initial download of language packs/models.--## Implementation & Code Samples--### 1. Checking Availability & Downloading Models--**Mandatory Options Passing:** You must pass the identical configuration options object to both `Translator.availability(options)` and `Translator.create(options)`.--**Mandatory Progress Monitoring:** You MUST implement a monitor for model download progress by providing a `monitor(m)` callback to `Translator.create()` and adding a listener for the `downloadprogress` event.--**User Gesture Requirement:** When `availability` is `'downloadable'`, triggering the model download via `Translator.create()` requires a user gesture (such as a button click listener context). Unconditional page-load calls will trigger a `NotAllowedError`.--```javascript-const options = {- sourceLanguage: 'es',- targetLanguage: 'fr',-};--const availability = await Translator.availability(options);--if (availability === 'available' || availability === 'downloadable') {- // A user gesture is strictly required to trigger create when downloadable- document.getElementById('start-translation-btn').addEventListener('click', async () => {- const translator = await Translator.create({- ...options,- monitor(m) {- m.addEventListener('downloadprogress', (e) => {- console.log(`Downloaded ${Math.round(e.loaded * 100)}%`);- });- },- });- });-}-```--### 3. Executing Translations--The API supports both static and streaming responses.--**Standard Translation:**--```javascript-const translator = await Translator.create({- sourceLanguage: 'en',- targetLanguage: 'fr',-});--const result = await translator.translate(- 'Where is the next bus stop, please?',-);-console.log(result);-// Output: "Où est le prochain arrêt de bus, s'il vous plaît ?"-```--**Streaming Translation (for long text):**--```javascript-const stream = translator.translateStreaming(longText);-for await (const chunk of stream) {- console.log(chunk);-}-```--## Supported Languages--The API supports a wide range of BCP 47 language codes: Here are the languages supported by Chrome's implementation of the Translator API:--- **ar**: Arabic-- **bg**: Bulgarian-- **bn**: Bengali-- **cs**: Czech-- **da**: Danish-- **de**: German-- **el**: Greek-- **en**: English-- **es**: Spanish-- **fi**: Finnish-- **fr**: French-- **hi**: Hindi-- **hr**: Croatian-- **hu**: Hungarian-- **id**: Indonesian-- **it**: Italian-- **iw**: Hebrew-- **ja**: Japanese-- **kn**: Kannada-- **ko**: Korean-- **lt**: Lithuanian-- **mr**: Marathi-- **nl**: Dutch-- **no**: Norwegian-- **pl**: Polish-- **pt**: Portuguese-- **ro**: Romanian-- **ru**: Russian-- **sk**: Slovak-- **sl**: Slovenian-- **sv**: Swedish-- **ta**: Tamil-- **te**: Telugu-- **th**: Thai-- **tr**: Turkish-- **uk**: Ukrainian-- **vi**: Vietnamese-- **zh**: Chinese-- **zh-Hant**: Chinese (Traditional)--## Security & Performance--- **Permissions Policy:** Cross-origin iframes require explicit permission.- ```html- <iframe src="https://example.com/" allow="translator"></iframe>- ```-- **Web Workers:** Currently **not supported** due to Permission Policy- complexities.-- **Privacy:** No data is sent to Google servers during the translation process- once the model is downloaded.--## Fallback Strategy--Translator has limited availability.--Before use, check if the `Translator` object is available in the global scope:--```javascript-if ('Translator' in self) {- // The Translator API is supported.-} else {- // Execute fallback strategy-}-```--If the `Translator` API is unsupported or availability checks return `'unavailable'`, you must gracefully fall back.--Recommended options:-1. **Remote API Fallback**: Redirect the translation request to a server endpoint or cloud remote API (such as the Vertex AI Gemini API) to deliver translation functionality.-2. **Graceful Degradation**: Visually disable translation control elements or buttons while showing an end-user friendly note (e.g., `"Client-side translation is currently unsupported in this browser"`). Do not allow unhandled exceptions.-3. **Polyfill Fallback**: You can use community-maintained polyfills like `built-in-ai-task-apis-polyfills` or `prompt-api-polyfill` to emulate the API surface using remote services.--> **Privacy and Cost Implications:** These polyfills proxy requests to remote servers (such as Gemini API over the cloud). This completely nullifies the on-device privacy guarantees of the native Built-in AI APIs and will incur server-side API usage costs.diff --git a/skills/modern-web/guides/forms/animated-select-picker.md b/skills/modern-web/guides/forms/animated-select-picker.mddeleted file mode 100644index 88de7b3..0000000--- a/skills/modern-web/guides/forms/animated-select-picker.md+++ /dev/null@@ -1,162 +0,0 @@-# Animated Select Picker--The customizable select API offers a declarative, CSS-driven way to animate `<select>` elements and their dropdown pickers. By combining `appearance: base-select` with modern CSS animation techniques—such as `@starting-style` and the `allow-discrete` transition behavior—you can create fluid, premium UI transitions for top-layer elements without relying on heavy JavaScript libraries.--Previously, animating native select dropdowns was impossible because their UI was rendered outside the accessible viewport constraints. With `appearance: base-select`, the picker becomes styleable and animatable like any other page element.--## How to Implement--To implement an animated select picker:--1. **Opt-in to customization:** Apply `appearance: base-select` to both the `<select>` element and the `::picker(select)` pseudo-element.-2. **Enable auto-sizing transitions (Optional):** Define `interpolate-size: allow-keywords` (usually on `:root`) to allow the browser to transition between discrete metric values like `height: auto` and `height: 0`.-3. **Animate the top-layer container:** Apply standard entry/exit styles to `::picker(select)`. To make sure the opacity transition works when moving between `display: none` and `display: block`, you must use `transition-behavior: allow-discrete` (often written inline as `transition: display 0.3s allow-discrete`).-4. **Hook into the opening state with `@starting-style`:** Use `@starting-style` to define the baseline styles the browser should compute *before* the transition begins. For example, if you want it to fade in, set the opacity to `0` inside the `@starting-style` block.-5. **Rotate the icon:** Use pseudo-element focus or active selectors like `:open::picker-icon` to apply transitions (such as rotation or translation) to the arrow indicator.--## Example Code: Smooth Select Scale and Fade--The following example demonstrates a custom select styled with standard page animations for the picker container.--```html-<!-- Always use a <label> linked via 'for' to the select for accessibility -->-<label for="theme-select">Visual Theme</label>-<select id="theme-select" class="animated-select" name="theme">- <!-- The <button> inside <select> becomes the visible trigger when appearance: base-select is used -->- <button>- <!-- <selectedcontent> automatically displays the content of the chosen <option> -->- <selectedcontent></selectedcontent>- </button>- <option value="system">- <!-- SVGs are allowed inside options when appearance: base-select is active -->- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">- <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>- <line x1="8" y1="21" x2="16" y2="21"></line>- <line x1="12" y1="17" x2="12" y2="21"></line>- </svg>- System Default- </option>- <option value="light">- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">- <circle cx="12" cy="12" r="5"></circle>- <line x1="12" y1="1" x2="12" y2="3"></line>- <line x1="12" y1="21" x2="12" y2="23"></line>- <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>- <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>- <line x1="1" y1="12" x2="3" y2="12"></line>- <line x1="21" y1="12" x2="23" y2="12"></line>- <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>- <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>- </svg>- Light UI- </option>-</select>-```--```css-/* Opt-in to customizable select */-.animated-select,-.animated-select::picker(select) {- appearance: base-select;-}--/* Enable auto-keyword transitions (usually set globally at :root) */-:root {- interpolate-size: allow-keywords;-}--/* Style the visible trigger and icon rotation */-.animated-select {- display: flex;- align-items: center;- justify-content: space-between;- width: 100%;- padding: 0.875rem 1rem;- font-size: 1rem;- border-radius: 8px;- cursor: pointer;- transition: border-color 0.2s ease;-}--.animated-select::picker-icon {- transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);-}--.animated-select:open::picker-icon {- transform: rotate(180deg);-}--/*- * The Picker Container- * Uses top-layer animations with `allow-discrete` visibility hooks- */-.animated-select::picker(select) {- background: white;- border-radius: 12px;- box-shadow: 0 10px 25px -3px rgba(0,0,0,0.1);- padding: 0.5rem;- margin-top: 0.25rem;- width: anchor-size(width);- overflow: hidden;-- /* The crucial transition setting for popover animations */- transition:- display 0.4s allow-discrete,- overlay 0.4s allow-discrete,- opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1),- height 0.4s cubic-bezier(0.16, 1, 0.3, 1);- opacity: 0;- height: 0;-}--/* Open State */-.animated-select:open::picker(select) {- opacity: 1;- height: auto;-}--/* @starting-style to hook the transition on initial popover open */-@starting-style {- .animated-select:open::picker(select) {- opacity: 0;- height: 0;- }-}--/* Support for SVG inside Options and Selected Content */-.animated-select option svg,-.animated-select selectedcontent svg {- flex-shrink: 0; /* Prevent icons from shrinking */- width: 1.25rem;- height: 1.25rem;-}-```--## Strategic Implementation & Best Practices--- **DO** use `@starting-style` when you need animations to trigger exactly when an element transitions from `display: none` to visible.-- **DO NOT** use ad-hoc scroll locking. Top-layer elements managed by ‘base-select’ should allow natural backdrop dismiss behaviors.-- **DO** verify reduced motion preferences. Always wrap animation constraints in a `prefers-reduced-motion` media query to ensure accessible environments for those affected by motion sickness.-- **DO** test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.-- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.--## Fallback strategies--### Fallbacks & browser support for Customizable <select>--Customizable <select> has limited availability.--For browsers that do not yet support `appearance: base-select`, the `<select>` element degrades gracefully to a standard operating system dropdown.--- **Non-Text Content Ignored**: Older browsers strip HTML tags (like `<svg>` or `<div>`) inside `<option>` tags and render only the text nodes. Ensure the text content of the `<option>` is readable and meaningful on its own.-- **HTML Structure Handling**: Standard parsers may ignore the `<button>` and `<selectedcontent>` tags inside `<select>` or treat them as invalid. No heavy JavaScript polyfills are strictly required for progressive enhancement if you view standard text as a readable fallback.---```javascript-document.addEventListener("DOMContentLoaded", () => {- // Check if browser supports base-select value- if (!CSS.supports("appearance", "base-select")) {- // Custom select overrides are not supported natively.- }-});-```diff --git a/skills/modern-web/guides/forms/autofill-address-form.md b/skills/modern-web/guides/forms/autofill-address-form.mddeleted file mode 100644index a3d87ea..0000000--- a/skills/modern-web/guides/forms/autofill-address-form.md+++ /dev/null@@ -1,73 +0,0 @@-# Build an address form that follows best practice--Create a form that makes it as easy as possible for users to enter address data on desktop and mobile. Ensure the form makes the most of built-in browser features for autofill, validation and data entry constraints.--## How to implement--Outlined below are the most important guidelines for building successful address forms.--### Use meaningful, valid HTML--Make the most of the elements and attributes built for creating forms:--- `<form>`, `<input>`, `<label>`, and `<button>`-- `type`, `autocomplete`, and `inputmode`--These enable built-in browser functionality, improve accessibility, and add meaning to markup.--### Use the <label> element to label form fields for data entry--To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a label with an input by giving the label's `for` attribute the same value as the input's `id`.--### Make the most of HTML attributes--Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.--Always use `type="email"` for email addresses and `type="tel"` for phone numbers.--```html-<!-- type="email"/"tel" gives mobile users the right keyboard and enables built-in validation -->-<input type="email" id="email" name="email" autocomplete="email" required>-<input type="tel" id="phone" name="phone" autocomplete="tel">-```--Every `<input>`, `<select>`, and `<textarea>` element SHOULD have an appropriate `autocomplete` attribute, to improve accessibility and help users avoid re-entering data.--### Make buttons helpful--Use `<button>` for buttons. You can also use `<input type="submit">`, but don't use a `div` or some other random element acting as a button. Button elements provide accessible behaviour, built-in form submission functionality, and can easily be styled.--Give each form submit button a value that says what it does. For each step towards checkout, use a descriptive call-to-action that shows progress and makes the next step obvious. For example, label the submit button on your delivery address form **Proceed to Payment** rather than **Continue** or **Save**.--### Use a single name input where possible--Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.--Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.--### Allow for a variety of address formats--When building an address form, be aware of the variety of address formats, even within a single country. Do not make assumptions about "normal" addresses.--Use a single `<textarea>` element for the street address if possible.--```html-<!-- textarea handles multi-line international address formats that split inputs can't accommodate -->-<textarea id="address" name="address" autocomplete="street-address" required></textarea>-```--This is the most flexible option for a variety of local and international address formats.--### Help save users from accidentally missing data fields--Add the `required` attribute to mandatory fields.--```html-<input type="text" id="city" name="city" autocomplete="address-level2" required>-```--### Fallback strategies--:autofill has limited availability.--Autofill is a progressive enhancement. In browsers that do not support autofill, users will simply need to manually enter their address details. The semantic HTML constraints (such as `type`, `inputmode`, and `required`) will still function appropriately as standard form validation.diff --git a/skills/modern-web/guides/forms/autofill-highlight-inputs.md b/skills/modern-web/guides/forms/autofill-highlight-inputs.mddeleted file mode 100644index 6653f0e..0000000--- a/skills/modern-web/guides/forms/autofill-highlight-inputs.md+++ /dev/null@@ -1,35 +0,0 @@-# Use the CSS :autofill pseudo-class to highlight form fields that have been autofilled by the browser and not edited by the user--Use the CSS `:autofill` to highlight fields that have (or have not been) autofilled, to help guide the user to successful form completion.--## How to implement--To highlight a form field that has been autofilled by the browser (and not edited by the user) add a selector to your CSS using the `:autofill` class. This can be used for an `<input>`, `<select>`, or `<textarea>` element.--The following example uses `:autofill` to set border color:--```css-input:autofill,-input:-webkit-autofill,-input:-webkit-autofill:hover,-input:-webkit-autofill:focus {- /* box-shadow overrides the autofill background color, which cannot be changed via background-color */- /* box-shadow: 0 0 0 100vmax #efe inset; */- border-color: green;- outline: none;-}-```--As shown in this example, the `box-shadow` property can be used to customize the background if required, since `background-color` cannot be overridden directly.--## Use the correct CSS pseudo-class name--**Do not** use `:auto-fill`: this is incorrect.--MANDATORY: Use `:autofill` as this is the correct pseudo-class name.--### Fallback strategies--:autofill has limited availability.--The `:autofill` pseudo-class is a progressive enhancement. In browsers that do not support it, the form will still function normally, but the inputs will simply not receive the custom autofill highlighting. Users will still be able to successfully complete the form. No additional JavaScript fallback should be used.diff --git a/skills/modern-web/guides/forms/autofill-payment-form.md b/skills/modern-web/guides/forms/autofill-payment-form.mddeleted file mode 100644index 5e0a8af..0000000--- a/skills/modern-web/guides/forms/autofill-payment-form.md+++ /dev/null@@ -1,120 +0,0 @@-# Build a payment form that follows best practice--Payment forms are the single most critical part of the checkout process. Poor payment form design is a common cause of shopping cart abandonment.--Create a form that makes it as easy as possible for users to enter payment details on desktop and mobile. Ensure the form makes the most of built-in browser features for autofill, validation and data entry constraints.--## How to implement--Outlined below are the most important guidelines for building successful payment forms.--### Use meaningful, valid HTML--Make the most of the elements and attributes built for creating forms:--- `<form>`, `<input>`, `<label>`, and `<button>`-- `type`, `autocomplete`, and `inputmode`--These enable built-in browser functionality, improve accessibility, and add meaning to markup.--### Use the <label> element to label form fields for data entry--To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a label with an input by giving the label's `for` attribute the same value as the input's `id`.--### Make the most of HTML attributes--Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.--Always use `type="email"` for email addresses and `type="tel"` for phone numbers.--```html-<!-- type="email"/"tel" gives mobile users the right keyboard and enables built-in validation -->-<input type="email" id="email" name="email" autocomplete="email" required>-<input type="tel" id="phone" name="phone" autocomplete="tel">-```--Every `<input>`, `<select>`, and `<textarea>` element SHOULD have an appropriate `autocomplete` attribute, to improve accessibility and help users avoid re-entering data.--### Make buttons helpful--Use `<button>` for buttons. You can also use `<input type="submit">`, but don't use a `div` or some other random element acting as a button. Button elements provide accessible behaviour, built-in form submission functionality, and can easily be styled.--Give each form submit button a value that says what it does. For each step towards checkout, use a descriptive call-to-action that shows progress and makes the next step obvious. For example, label the submit button on your delivery address form **Proceed to Payment** rather than **Continue** or **Save**.--### Use a single name input where possible--Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.--Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.--### Allow for a variety of address formats--When adding form fields for an address in a payment form, be aware of the variety of address formats, even within a single country. Do not make assumptions about "normal" addresses.--If possible within your data requirements, consider using a single `<textarea>` element for address. This is the most flexible option for a variety of local and international address formats.--### Use autocomplete for billing address--By default, set the billing address to be the same as the delivery address. Reduce visual clutter by providing a link to edit the billing address (or use summary and details elements) rather than displaying the billing address in a form.--Use appropriate autocomplete values for the billing address, just as you do for shipping address, so the user doesn't have to enter data more than once. Add a prefix word to autocomplete attributes if you have different values for inputs with the same name in different sections. For example:--```-<input autocomplete="shipping address-line-1" ...>-...-<input autocomplete="billing address-line-1" ...>-```--### Show checkout progress--For each step towards payment, use page headings and descriptive button values that make it clear what needs to be done now, and what checkout step is next.--Use the `enterkeyhint` attribute on form inputs to set the mobile keyboard enter key label. For example, use `enterkeyhint="previous"` and `enterkeyhint="next"` within a multi-page form, `enterkeyhint="done"` for the final input in the form, and `enterkeyhint="search"` for a search input.--### Help users avoid re-entering payment data--Make sure to add appropriate `autocomplete` values in payment card forms. Without autocomplete, users may keep a physical record of payment card details or store them insecurely.--```html-<!-- cc-number tells autofill this is a card number, not a generic number field -->-<!-- inputmode="numeric" gives a numeric keyboard without the increment/decrement spinner -->-<!-- DO NOT use type="number" — it adds increment/decrement controls and strips leading zeros -->-<input id="cc-number" name="cc-number" type="text" autocomplete="cc-number"- inputmode="numeric" maxlength="19" pattern="[\d ]{13,19}" required>--<!-- cc-name autofills with the name exactly as it appears on the card; Unicode pattern allows international names -->-<input id="cc-name" name="cc-name" type="text" autocomplete="cc-name"- maxlength="50" pattern="[\p{L} \-\.]+" required>--<!-- cc-exp autofills the full expiry date as MM/YY -->-<input id="cc-exp" name="cc-exp" type="text" autocomplete="cc-exp"- placeholder="MM/YY" maxlength="5" required>--<!-- cc-csc autofills the security code; DO NOT use type="password" here -->-<input id="cc-csc" name="cc-csc" type="text" autocomplete="cc-csc"- inputmode="numeric" maxlength="4" pattern="[0-9]{3,4}" required>-```--### Use a single input for payment card and phone numbers--For payment card and phone numbers use a single input: don't split the number into parts. That makes it easier for users to enter data, makes validation simpler, and enables browsers to autofill. Consider doing the same for other numeric data such as PIN and bank codes.--### Validate carefully--You should validate data entry both in realtime and before form submission. One way to do this is by adding a pattern attribute to a payment card input. If the user attempts to submit the payment form with an invalid value, the browser displays a warning message and sets focus on the input.--However, your pattern regular expression must be flexible enough to handle the range of payment card number lengths: from 14 digits (or possibly less) to 20 (or more). Card security codes (also known as CSC, CVC, CVV, or other names) consist of 3 or 4 digits.--Allow users to include spaces when they're entering a new payment card number, since this is how numbers are displayed on physical cards. That's friendlier to the user (you won't have to tell them "they did something wrong"), less likely to interrupt conversion flow, and it's straightforward to remove spaces in numbers before processing.--### Help save users from accidentally missing data fields--Add the `required` attribute to mandatory fields. Modern browsers automatically prompt and set focus for missing data.--### Fallback strategies--Baseline status for enterkeyhint: Widely available. It's been Baseline since 2021-11-02.-Baseline status for Email, telephone, and URL <input> types: Widely available. It's been Baseline since 2015-07-29.-Baseline status for inputmode: Widely available. It's been Baseline since 2021-12-07.--Autofill is a progressive enhancement. In browsers that do not support autofill, users will simply need to manually enter their payment details. The semantic HTML constraints (such as `type`, `inputmode`, `pattern`, and `required`) will still function appropriately to validate user input and provide the correct virtual keyboards.diff --git a/skills/modern-web/guides/forms/autofill-sign-in-form.md b/skills/modern-web/guides/forms/autofill-sign-in-form.mddeleted file mode 100644index 1b796fd..0000000--- a/skills/modern-web/guides/forms/autofill-sign-in-form.md+++ /dev/null@@ -1,133 +0,0 @@-# Build a sign-in form that follows best practice--Use cross-platform browser features to build sign-in forms that are secure, accessible and easy to use.--If users ever need to sign in to your site, then good sign-in form design is critical. This is especially true for people on poor connections, on mobile, in a hurry, or under stress. Poorly designed sign-in forms get high bounce rates. Each bounce could mean a lost customer and a disgruntled user—not just a missed sign-in opportunity.--## How to implement--Outlined below are the most important guidelines for building successful sign-in forms.--### Use meaningful, valid HTML--Make the most of the elements and attributes built for creating forms:--- `<form>`, `<input>`, `<label>`, and `<button>`-- `type`, `autocomplete`, and `inputmode`--These enable built-in browser functionality, improve accessibility, and add meaning to markup.--### Use the <label> element to label form fields for data entry--To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a label with an input by giving the label's `for` attribute the same value as the input's `id`.--### Make the most of HTML attributes--Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.--Always use `type="email"` for email addresses and `type="tel"` for phone numbers.--Every `<input>`, `<select>`, and `<textarea>` element SHOULD have an appropriate `autocomplete` attribute, to improve accessibility and help users avoid re-entering data.--### Make buttons helpful--Use `<button>` for buttons. You can also use `<input type="submit">`, but don't use a `div` or some other random element acting as a button. Button elements provide accessible behaviour, built-in form submission functionality, and can easily be styled.--Give each form submit button a value that says what it does. Use a clear, recognizable label. For example, use **Sign In** rather than **Continue** or **Submit**.--### Use a single name input where possible--Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.--Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.--### Show sign-in progress--For each step towards sign-in, use page headings and descriptive button values that make it clear what needs to be done now, and what the next step is.--Use the `enterkeyhint` attribute on form inputs to set the mobile keyboard enter key label. For example, use `enterkeyhint="previous"` and `enterkeyhint="next"` within a multi-page form, `enterkeyhint="done"` for the final input in the form, and `enterkeyhint="search"` for a search input.--### Help users avoid re-entering sign-in data--Make sure to add appropriate `autocomplete` values in sign-in forms.--This enables browsers to help users by securely storing sign-in details and correctly entering form data. Without autocomplete, users may be more likely to keep a physical record of sign-in details, or store sign-in data insecurely on their device.--### Validate carefully--Validate data entry both in realtime and before form submission. Use `type="email"` for email inputs — the browser will validate the format automatically. Add the `required` attribute to mandatory fields to prevent empty submissions.--### Put sign-in in its own <form> element--Always use the `<form>` element when you're getting users to enter data--Don't wrap inputs in a `<div>` and handle input data submission purely with JavaScript. It's generally better to use a `<form>` element. This makes your site accessible to screenreaders and other assistive devices, enables a range of built-in browser features, makes it simpler to build basic functional sign-in for older browsers, and can still work even if JavaScript fails.--### Don't double up inputs--Some sites force users to enter emails or passwords twice. That might reduce errors for a few users, but causes extra work for all users, and increases abandonment rates. Asking twice also makes no sense where browsers autofill email addresses or suggest strong passwords. It's better to enable users to confirm their email address (you'll need to do that anyway) and make it easy for them to reset their password if necessary.--### Keep passwords private—but enable users to see them if they want--Passwords inputs should have `type="password"` to hide password text and help the browser understand that the input is for passwords. (Note that browsers use a variety of techniques to understand input roles and decide whether or not to offer to save passwords.)--You should add a **Show password** toggle to enable users to check the text they've entered—and don't forget to add a **Forgot password** link.--### Give mobile users the right keyboard--Use `<input type="email">` to give mobile users an appropriate keyboard and enable basic built-in email address validation by the browser… no JavaScript required!--If you need to use a telephone number instead of an email address, `<input type="tel">` enables a telephone keypad on mobile. You can also use the `inputmode` attribute where necessary: `inputmode="numeric"` is ideal for PIN numbers.--### Prevent mobile keyboard from obstructing the Sign in button--If you're not careful, mobile keyboards may cover your form or, worse, partially obstruct the Sign in button. Users may give up before realizing what has happened.--Where possible, avoid this by displaying only the email (or phone) and password inputs and Sign in button at the top of your sign-in page. Put other content underneath.--### Help users to avoid re-entering data--You can help browsers store data correctly and autofill inputs, so users don't have to remember to enter email and password values. This is particularly important on mobile, and crucial for email inputs, which get high abandonment rates. There are two parts to this:--1. The `autocomplete`, `name`, `id`, and `type` attributes help browsers understand the role of inputs in order to store data that can later be used for autofill. To allow data to be stored for autofill, modern browsers also require inputs to have a stable `name` or `id` value (not randomly generated on each page load or site deployment), and to be in a `<form>` element with a `submit` button.-1. The `autocomplete` attribute helps browsers correctly autofill inputs using stored data.--For email inputs use `autocomplete="username"`, since `username` is recognized by password managers in modern browsers—even though you should use `type="email"` and you may want to use `id="email"` and `name="email"`. For password inputs, use the appropriate `autocomplete` and `id` values to help browsers differentiate between new and current passwords.--### Use autocomplete="current-password" and id="current-password" for an existing password--MANDATORY: Use `autocomplete="current-password"` and `id="current-password"` for the password input in a sign-in form. This tells the browser that you want it to use the current password that it has stored for the site.--For a sign-in form:--```-<input type="password" autocomplete="current-password" id="current-password" …>-```--### Enable the browser to suggest a strong password--Modern browsers use heuristics to decide when to show the password manager UI and suggest a strong password.--Built-in browser password generators mean users and developers don't need to work out what a "strong password" is. Since browsers can securely store passwords and autofill them as necessary, there's no need for users to remember or enter passwords. Encouraging users to take advantage of built-in browser password generators also means they're more likely to use a unique, strong password on your site, and less likely to reuse a password that could be compromised elsewhere.--### Help save users from accidentally missing inputs--MANDATORY: Add the `required` attribute to both email and password fields. Modern browsers automatically prompt and set focus for missing data.--```html-<input type="email" id="email" name="email" autocomplete="username" required>-<input type="password" id="password" name="password" autocomplete="current-password" required>-```--### Allow password pasting--Some sites don't allow text to be pasted into password inputs.--Disallowing password pasting annoys users, encourages passwords that are memorable (and therefore may be easier to compromise) and, according to organizations such as the UK National Cyber Security Centre, may actually reduce security. Users only become aware that pasting is disallowed after they try to paste their password, so disallowing password pasting doesn't avoid clipboard vulnerabilities.--### Fallback strategies--Baseline status for Email, telephone, and URL <input> types: Widely available. It's been Baseline since 2015-07-29.-Baseline status for inputmode: Widely available. It's been Baseline since 2021-12-07.--Autofill is a progressive enhancement. In browsers that do not support autofill, users will simply need to manually enter their sign-in credentials. The semantic HTML constraints (such as `type`, `inputmode`, and `required`) will still function appropriately to validate user input and provide the correct virtual keyboards.diff --git a/skills/modern-web/guides/forms/autofill-sign-up-form.md b/skills/modern-web/guides/forms/autofill-sign-up-form.mddeleted file mode 100644index ebae9dc..0000000--- a/skills/modern-web/guides/forms/autofill-sign-up-form.md+++ /dev/null@@ -1,143 +0,0 @@-# Build a sign-up form that follows best practice--Use cross-platform browser features to build sign-up forms that are secure, accessible and easy to use.--If users ever need to sign up to your site, then good sign-up form design is critical. This is especially true for people on poor connections, on mobile, in a hurry, or under stress. Poorly designed sign-up forms get high bounce rates. Each bounce could mean a lost customer and a disgruntled user—not just a missed sign-up opportunity.--## How to implement--Outlined below are the most important guidelines for building successful sign-up forms.--### Use meaningful, valid HTML--Make the most of the elements and attributes built for creating forms:--- `<form>`, `<input>`, `<label>`, and `<button>`-- `type`, `autocomplete`, and `inputmode`--These enable built-in browser functionality, improve accessibility, and add meaning to markup.--### Use the <label> element to label form fields for data entry--To label an `<input>`, `<select>`, or `<textarea>`, use a `<label>`. Associate a label with an input by giving the label's `for` attribute the same value as the input's `id`.--### Make the most of HTML attributes--Make it easy for users to enter data, by using the appropriate `<input>` element `<type>` attribute to provide the right keyboard on mobile and enable basic built-in validation by the browser.--Always use `type="email"` for email addresses and `type="tel"` for phone numbers.--Every `<input>`, `<select>`, and `<textarea>` element SHOULD have an appropriate `autocomplete` attribute, to improve accessibility and help users avoid re-entering data.--### Make buttons helpful--Use `<button>` for buttons. You can also use `<input type="submit">`, but don't use a `div` or some other random element acting as a button. Button elements provide accessible behaviour, built-in form submission functionality, and can easily be styled.--Give each form submit button a value that says what it does. Use a clear, recognizable label. For example, use **Create account** or **Sign up** rather than **Continue** or **Submit**.--### Use a single name input where possible--Allow your users to enter their name using a single input, unless you have a good reason for separately storing given names, family names, honorifics, or other name parts. Using a single name input makes forms less complex, enables cut-and-paste, and makes autofill simpler.--Allow international names. For validation, avoid using regular expressions that only match Latin characters. Latin-only excludes users with names or addresses that include characters that aren't in the Latin alphabet. Allow Unicode letter matching instead—and ensure your backend supports Unicode securely as both input and output. Unicode in regular expressions is well supported by modern browsers.--### Show sign-up progress--For each step towards sign-up, use page headings and descriptive button values that make it clear what needs to be done now, and what the next step is.--Use the `enterkeyhint` attribute on form inputs to set the mobile keyboard enter key label. For example, use `enterkeyhint="previous"` and `enterkeyhint="next"` within a multi-page form, `enterkeyhint="done"` for the final input in the form, and `enterkeyhint="search"` for a search input.--### Help users avoid re-entering sign-up data--Make sure to add appropriate `autocomplete` values in sign-up forms.--This enables browsers to help users by securely storing sign-up details and correctly entering form data. Without autocomplete, users may be more likely to keep a physical record of sign-up details, or store sign-up data insecurely on their device.--### Validate carefully--Validate data entry both in realtime and before form submission. Use `type="email"` for email inputs — the browser will validate the format automatically. For passwords, use a `pattern` attribute to enforce strength requirements and provide clear error messages when validation fails. Add the `required` attribute to mandatory fields to prevent empty submissions.--### Put sign-up in its own <form> element--Always use the `<form>` element when you're getting users to enter data--Don't wrap inputs in a `<div>` and handle input data submission purely with JavaScript. It's generally better to use a `<form>` element. This makes your site accessible to screenreaders and other assistive devices, enables a range of built-in browser features, makes it simpler to build basic functional sign-up for older browsers, and can still work even if JavaScript fails.--### Don't double up inputs--Some sites force users to enter emails or passwords twice. That might reduce errors for a few users, but causes extra work for all users, and increases abandonment rates. Asking twice also makes no sense where browsers autofill email addresses or suggest strong passwords. It's better to enable users to confirm their email address (you'll need to do that anyway) and make it easy for them to reset their password if necessary.--### Keep passwords private—but enable users to see them if they want--Passwords inputs should have `type="password"` to hide password text and help the browser understand that the input is for passwords. (Note that browsers use a variety of techniques to understand input roles and decide whether or not to offer to save passwords.)--You should add a **Show password** toggle to enable users to check the text they've entered—and don't forget to add a **Forgot password** link.--### Give mobile users the right keyboard--Use `<input type="email">` to give mobile users an appropriate keyboard and enable basic built-in email address validation by the browser… no JavaScript required!--If you need to use a telephone number instead of an email address, `<input type="tel">` enables a telephone keypad on mobile. You can also use the `inputmode` attribute where necessary: `inputmode="numeric"` is ideal for PIN numbers.--### Prevent mobile keyboard from obstructing the Sign up button--If you're not careful, mobile keyboards may cover your form or, worse, partially obstruct the Sign up button. Users may give up before realizing what has happened.--Where possible, avoid this by displaying only the email (or phone) and password inputs and Sign up button at the top of your sign-up page. Put other content underneath.--### Help users to avoid re-entering data--You can help browsers store data correctly and autofill inputs, so users don't have to remember to enter email and password values. This is particularly important on mobile, and crucial for email inputs, which get high abandonment rates. There are two parts to this:--1. The `autocomplete`, `name`, `id`, and `type` attributes help browsers understand the role of inputs in order to store data that can later be used for autofill. To allow data to be stored for autofill, modern browsers also require inputs to have a stable `name` or `id` value (not randomly generated on each page load or site deployment), and to be in a `<form>` element with a `submit` button.-1. The `autocomplete` attribute helps browsers correctly autofill inputs using stored data.--For email inputs use `autocomplete="username"`, since `username` is recognized by password managers in modern browsers—even though you should use `type="email"` and you may want to use `id="email"` and `name="email"`. For password inputs, use the appropriate `autocomplete` and `id` values to help browsers differentiate between new and current passwords.--### Use autocomplete="new-password" and id="new-password" for a new password--MANDATORY: For a sign-up form, use `autocomplete="new-password"`.--```html-<!-- new-password prevents password managers from auto-filling an existing password into this field -->-<input type="password" id="new-password" name="new-password" autocomplete="new-password" required>-```--### Enable the browser to suggest a strong password--Modern browsers use heuristics to decide when to show the password manager UI and suggest a strong password.--Built-in browser password generators mean users and developers don't need to work out what a "strong password" is. Since browsers can securely store passwords and autofill them as necessary, there's no need for users to remember or enter passwords. Encouraging users to take advantage of built-in browser password generators also means they're more likely to use a unique, strong password on your site, and less likely to reuse a password that could be compromised elsewhere.--### Help save users from accidentally missing inputs--Add the `required` attribute to both email and password fields. Modern browsers automatically prompt and set focus for missing data.--### Allow password pasting--Some sites don't allow text to be pasted into password inputs.--Disallowing password pasting annoys users, encourages passwords that are memorable (and therefore may be easier to compromise) and, according to organizations such as the UK National Cyber Security Centre, may actually reduce security. Users only become aware that pasting is disallowed after they try to paste their password, so disallowing password pasting doesn't avoid clipboard vulnerabilities.--### Offer third-party login--Many users prefer to sign in to websites using an email address and password sign-up form. However, you should also enable users to sign in using a third-party identity provider, also known as federated login.--This approach has several advantages. For users who create an account using federated login, you don't need to ask for, communicate, or store passwords.--You may also be able to access additional verified profile information from federated login, such as an email address—which means the user doesn't have to enter that data and you don't need to do the verification yourself. Federated login can also make it much easier for users when they get a new device.--### Take care with usernames--Don't insist on a username unless (or until) you need one. Enable users to sign up and sign in with only an email address (or telephone number) and password—or federated login if they prefer. Don't force them to choose and remember a username.--If your site does require usernames, don't impose unreasonable rules on them, and don't stop users from updating their username. On your backend you should generate a unique ID for every user account, not an identifier based on personal data such as username.--Also make sure to use `autocomplete="username"` for usernames.--### Fallback strategies--Baseline status for Email, telephone, and URL <input> types: Widely available. It's been Baseline since 2015-07-29.-Baseline status for inputmode: Widely available. It's been Baseline since 2021-12-07.--Autofill is a progressive enhancement. In browsers that do not support autofill, users will simply need to manually enter their sign-up credentials. The semantic HTML constraints (such as `type`, `inputmode`, and `required`) will still function appropriately to validate user input and provide the correct virtual keyboards.diff --git a/skills/modern-web/guides/forms/brand-consistent-forms.md b/skills/modern-web/guides/forms/brand-consistent-forms.mddeleted file mode 100644index 23bca1b..0000000--- a/skills/modern-web/guides/forms/brand-consistent-forms.md+++ /dev/null@@ -1,243 +0,0 @@-# Brand-Consistent Forms--Customizing standard HTML form elements like checkboxes and radio buttons has historically been difficult. Developers often faced a choice between using the browser defaults or building custom components from scratch. Building custom controls is time-consuming and can easily lead to accessibility issues or missing states (like the indeterminate state for checkboxes).--The CSS property `accent-color` provides a simple way to bring your brand color to built-in HTML form inputs with a single line of CSS, without sacrificing accessibility or built-in browser features.--## How to Implement--To apply your brand color to form controls:--1. **Identify your brand color:** Choose a color that represents your brand.-2. **Apply the `accent-color` property:** Add `accent-color` to the element or a container element (like `body` or a specific form) in your CSS.-3. **Support Dark Mode (Optional but Recommended):** Use `color-scheme` to let the browser know your site supports dark mode, and adjust the `accent-color` if necessary for better contrast.--## Example Code: Brand-Consistent Form Controls--```css-:root {- --brand-color: #6200ee;-}--/* Apply accent-color to the body or a specific container */-body {- accent-color: var(--brand-color);-}--/* Optional: Adjust for dark mode if needed */-@media (prefers-color-scheme: dark) {- :root {- --brand-color: #bb86fc; /* A lighter shade for dark mode */- }-}-```--```html-<form>- <!-- Checkbox -->- <label>- <input type="checkbox" checked>- Subscribe to newsletter- </label>-- <!-- Radio Buttons -->- <label>- <input type="radio" name="plan" value="monthly">- Monthly- </label>- <label>- <input type="radio" name="plan" value="yearly" checked>- Yearly- </label>-- <!-- Range Slider -->- <label for="volume">Volume:</label>- <input type="range" id="volume" min="0" max="100" value="70">-- <!-- Progress Bar -->- <label for="file">Upload Progress:</label>- <progress id="file" max="100" value="70">70%</progress>-</form>-```--## Strategic Implementation & Best Practices--- **DO** use `accent-color` to easily theme form controls to match your brand.-- **DO NOT** blindly trust the browser to handle contrast. While browsers are supposed to automatically determine an eligible contrast color, known bugs in implementations like **Safari** (WebKit bug 244233) and **Android Chrome** (Chromium bug 343503163) can fail to invert checkmark colors, leading to invisible or hard-to-see controls when using colors that lack sufficient contrast against the background (e.g., light colors in light mode, or dark colors in dark mode).-- **DO** combine `accent-color` with `color-scheme: light dark` to ensure form controls look good in both light and dark themes.-- **DO NOT** use a color that is too close to the background color, even though browsers try to guarantee contrast, it's best to provide a color with good base contrast.-- **DO NOT** assume `accent-color` works on all form elements. Currently, it only tints `checkbox`, `radio`, `range`, and `progress` elements.--## Fallback Strategy--accent-color has limited availability.--For browsers that do not support `accent-color`, the form controls fall back to the browser's default appearance. To ensure full brand consistency and high reliability across all environments, you MUST implement a custom fallback strategy using the established "visually hidden input" technique.--### Progressive Enhancement with `@supports not`--You MUST use the `@supports not` rule to apply custom fallback styles only when `accent-color` is not supported. This ensures you leverage the simplicity of `accent-color` for modern browsers while guaranteeing a consistent branded experience for older ones.--#### 1. HTML Structure-Ensure your labels wrap the text in a `<span>` to allow for sibling selectors in CSS:-```html-<label>- <input type="checkbox" checked>- <span>Subscribe to newsletter</span>-</label>-```--#### 2. CSS Fallback-Apply custom styles within a `@supports not` block:-```css-/* Fallback for older browsers without accent-color */-@supports not (accent-color: var(--brand-color)) {- /* Visually hide the native input */- form input[type="checkbox"] {- position: absolute;- opacity: 0;- width: 0;- height: 0;- }-- /* Style the wrapper label */- label {- position: relative;- padding-left: 2rem;- cursor: pointer;- display: inline-flex;- align-items: center;- }-- /* Custom box for checkbox */- input[type="checkbox"] + span::before {- content: "";- position: absolute;- left: 0;- top: 50%;- transform: translateY(-50%);- width: 1.2rem;- height: 1.2rem;- border: 2px solid #ccc;- background: white;- border-radius: 4px;- box-sizing: border-box;- transition: all 0.2s ease;- }-- /* Checked State */- input[type="checkbox"]:checked + span::before {- background-color: var(--brand-color, #6200ee);- border-color: var(--brand-color, #6200ee);- }-- /* Checkmark (Unicode) */- input[type="checkbox"]:checked + span::after {- content: "✓";- position: absolute;- left: 0.25rem;- top: 50%;- transform: translateY(-50%);- color: white;- font-weight: bold;- font-size: 0.9rem;- }-- /* Fallback for Range Slider */- input[type="range"] {- -webkit-appearance: none;- appearance: none;- background: transparent;- }-- /* Webkit (Chrome, Safari, Edge) */- input[type="range"]::-webkit-slider-runnable-track {- width: 100%;- height: 8px;- /* Use gradient to show progress for a static value (e.g., 70%) or update with JS */- background: linear-gradient(to right, var(--brand-color, #6200ee) 70%, #ccc 70%);- border-radius: 4px;- }-- input[type="range"]::-webkit-slider-thumb {- -webkit-appearance: none;- appearance: none;- height: 16px;- width: 16px;- border-radius: 50%;- background: var(--brand-color, #6200ee);- cursor: pointer;- margin-top: -4px; /* Center vertically */- }-- /* Firefox */- input[type="range"]::-moz-range-track {- width: 100%;- height: 8px;- background: #ccc;- border-radius: 4px;- }-- input[type="range"]::-moz-range-thumb {- height: 16px;- width: 16px;- border-radius: 50%;- background: var(--brand-color, #6200ee);- cursor: pointer;- }-- /* Firefox specific progress bar */- input[type="range"]::-moz-range-progress {- background-color: var(--brand-color, #6200ee);- height: 8px;- border-radius: 4px;- }-- /* Fallback for Progress Bar */- progress {- -webkit-appearance: none;- -moz-appearance: none;- appearance: none;- border: none;- background: #ccc;- height: 8px;- border-radius: 4px;- }-- progress::-webkit-progress-bar {- background-color: #ccc;- border-radius: 4px;- }-- progress::-webkit-progress-value {- background-color: var(--brand-color, #6200ee);- border-radius: 4px;- }-- progress::-moz-progress-bar {- background-color: var(--brand-color, #6200ee);- border-radius: 4px;- }-}-```--### Dynamic Range Progress in Webkit Fallback--To make the progress fill move with the thumb on a range slider in Webkit browsers (without `accent-color`), you can use a CSS variable and a small amount of JavaScript.--1. **Update CSS**: Use a CSS variable for the gradient stop:-```css-input[type="range"]::-webkit-slider-runnable-track {- background: linear-gradient(to right, var(--brand-color) var(--progress, 0%), #ccc var(--progress, 0%));-}-```--2. **Add JavaScript**: Update the variable on the `input` event:-```javascript-if (!CSS.supports('accent-color')) {- const slider = document.getElementById('volume');- slider.addEventListener('input', (e) => {- e.target.style.setProperty('--progress', `${e.target.value}%`);- });-}-```diff --git a/skills/modern-web/guides/forms/branded-select-styling.md b/skills/modern-web/guides/forms/branded-select-styling.mddeleted file mode 100644index f4aaa2d..0000000--- a/skills/modern-web/guides/forms/branded-select-styling.md+++ /dev/null@@ -1,112 +0,0 @@-# Branded Select Styling--The customizable select API offers a declarative, CSS-driven way to style `<select>` elements to perfectly match your brand's design system. By opting into `appearance: base-select`, you gain access to the internal shadow DOM of the select element, allowing you to style the button, the options picker list, the arrow icon, and the checkmark indicator using standard CSS properties.--Previously, achieving a fully branded select required rebuilding the control from scratch with JavaScript, which often broke accessibility, keyboard navigation, and native form integration. With `appearance: base-select`, you get a custom look while the browser handles focus management, top-layer rendering, and accessibility bindings.--## How to Implement--To implement branded select styling:--1. **Opt-in to customization:** Apply `appearance: base-select` to both the `<select>` element and the `::picker(select)` pseudo-element (which targets the drop-down list of options).-2. **Structure the custom button (Optional):** Define a `<button>` element directly inside the `<select>` to replace the default trigger. Use the `<selectedcontent>` element inside this button to represent the text or content of the currently selected option.-3. **Style the Picker List:** Use the `::picker(select)` pseudo-element to apply typography, background colors, borders, and shadows to the dropdown list. The browser renders this in the top-layer, making `z-index` conflicts a thing of the past.-4. **Style Internal Icons:**- - Use `select::picker-icon` to style or replace the arrow icon.- - Use `option::checkmark` to style the checkmark indicator next to the active option.-5. **Style Options:** Apply styles to `<option>` elements for hover states, padding, and layout.--## Example Code: Branded Courier Select--The following example demonstrates a custom select styled with a monospace font and dashed borders to match a specific "parcel" brand aesthetic.--```css-/* Enable customization for the select and its picker */-.brand-select,-.brand-select::picker(select) {- appearance: base-select;-}--/* Style the visible trigger button */-.brand-select {- font-family: 'Courier New', monospace;- background-color: #fffaf0;- color: #8b4513;- border: 2px dashed #8b4513;- border-radius: 4px;- padding: 0.75rem;- font-size: 1rem;- cursor: pointer;-}--/* Style the dropdown options list */-.brand-select::picker(select) {- font-family: 'Courier New', monospace;- background-color: #fffaf0;- border: 2px dashed #8b4513;- border-radius: 4px;- padding: 0.5rem;-}--/* Customize internal part colors to match text */-.brand-select::picker-icon {- color: #8b4513;-}--.brand-select option::checkmark {- color: #8b4513;-}--/* Style individual options and hover effects */-.brand-select option {- padding: 0.5rem;- border-radius: 4px;- color: #8b4513;- cursor: pointer;-}--.brand-select option:hover {- background-color: #fdf5e6;-}-```--```html-<label for="preferences">Select shipping preference</label>-<select class="brand-select" id="preferences" name="preferences">- <button>- <selectedcontent></selectedcontent>- </button>- <option value="standard">Standard Shipping</option>- <option value="express" selected>Express Shipping</option>- <option value="overnight">Overnight Delivery</option>-</select>-```--## Strategic Implementation & Best Practices--- **DO** use `appearance: base-select` when your design system requires high-fidelity, visual consistency across all form controls that cannot be achieved with standard cross-browser select overrides.-- **DO NOT** use this if you rely on the operating system's native picker experience (e.g., the standard scroll wheel picker on iOS devices). Opting into `base-select` opts out of native mobile UI controls in favor of web-rendered top-layer menus.-- **DO** verify that color contrast meets WCAG standards. The customizable picker allows you to set ad-hoc colors, but you are responsible for ensuring text remains legible against custom backgrounds.-- **DO** test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.-- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.--## Fallback strategies--### Fallbacks & browser support for Customizable <select>--Customizable <select> has limited availability.--For browsers that do not yet support `appearance: base-select`, the `<select>` element degrades gracefully to a standard operating system dropdown.--- **Non-Text Content Ignored**: Older browsers strip HTML tags (like `<svg>` or `<div>`) inside `<option>` tags and render only the text nodes. Ensure the text content of the `<option>` is readable and meaningful on its own.-- **HTML Structure Handling**: Standard parsers may ignore the `<button>` and `<selectedcontent>` tags inside `<select>` or treat them as invalid. No heavy JavaScript polyfills are strictly required for progressive enhancement if you view standard text as a readable fallback.---```javascript-document.addEventListener("DOMContentLoaded", () => {- // Check if browser supports base-select value- if (!CSS.supports("appearance", "base-select")) {- // Custom select overrides are not supported natively.- }-});-```diff --git a/skills/modern-web/guides/forms/custom-select-picker-layouts.md b/skills/modern-web/guides/forms/custom-select-picker-layouts.mddeleted file mode 100644index 6f4e641..0000000--- a/skills/modern-web/guides/forms/custom-select-picker-layouts.md+++ /dev/null@@ -1,99 +0,0 @@-# Custom Select Picker Layouts--"Custom Select Picker Layouts" allow developers to break away from the traditional vertical list of options in a `<select>` dropdown. Using `appearance: base-select` and the `::picker(select)` pseudo-element, you can style the options list using modern CSS layout techniques like Grid or Flexbox. This is ideal for color pickers, emoji selectors, or product variants where a visual menu is more effective than a list.--The CSS property `appearance: base-select` unlocks the ability to style the internal parts of a `<select>` element. By targeting `select::picker(select)`, you can apply `display: grid` and position options in columns, creating a rich visual experience without custom JavaScript.--## How to Implement--To implement a custom select picker layout:--1. **Activate Base Styling:** Apply `appearance: base-select` to both the `<select>` element and its internal picker pseudo-element `select::picker(select)`.-2. **Style the Picker Container:** Target `select::picker(select)` and apply `display: grid` (or `display: flex`). Define columns and gaps as you would for any container.-3. **Style Options:** Target the `<option>` elements to style them as grid items or cards. You can add images, SVGs, or complex layouts inside them.-4. **Customize the Trigger (Optional):** Use `<selectedcontent>` inside a `<button>` to render rich content for the selected value.--## Example Code: Custom Grid Picker--```html-<label for="weather-picker">Select weather</label>-<select class="grid-picker" name="weather" id="weather-picker">- <button>- <selectedcontent></selectedcontent>- </button>- <option value="sunny">- <span class="icon">☀️</span>- <span class="label">Sunny</span>- </option>- <option value="cloudy">- <span class="icon">☁️</span>- <span class="label">Cloudy</span>- </option>- <!-- More options... -->-</select>-```--```css-/* Activate the customizable select state */-.grid-picker,-.grid-picker::picker(select) {- appearance: base-select;-}--/* Style the dropdown list as a grid */-.grid-picker::picker(select) {- display: grid;- grid-template-columns: repeat(2, 1fr); /* 2 columns */- gap: 10px;- padding: 15px;- background: white;- border: 1px solid #ccc;- border-radius: 8px;-}--/* Style options as grid cards */-.grid-picker option {- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;- padding: 15px;- border: 1px solid #eee;- border-radius: 6px;-}--.grid-picker option:checked {- border-color: #007bff;- background-color: #f0f7ff;-}-```--## Strategic Implementation & Best Practices--- **DO** use `appearance: base-select` when you need to change the visual layout of options from a standard list to a 2D grid or custom flex flow.-- **DO NOT** assume the styles apply to all browsers equally yet; verify support and provide a fallback.-- **DO NOT** confuse visual layout with keyboard navigation. Standard select uses linear navigation. If you arrange options in a grid, ensure visual order matches DOM order so tab/arrow navigation makes sense.-- **DO** use `<selectedcontent>` if you want the trigger button to show images or icons from the selected option automatically.-- **DO** use standard `value` attributes on options to ensure form submission works exactly as before.-- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.--## Fallback Strategy--### Fallbacks & browser support for Customizable <select>--Customizable <select> has limited availability.--For browsers that do not yet support `appearance: base-select`, the `<select>` element degrades gracefully to a standard operating system dropdown.--- **Non-Text Content Ignored**: Older browsers strip HTML tags (like `<svg>` or `<div>`) inside `<option>` tags and render only the text nodes. Ensure the text content of the `<option>` is readable and meaningful on its own.-- **HTML Structure Handling**: Standard parsers may ignore the `<button>` and `<selectedcontent>` tags inside `<select>` or treat them as invalid. No heavy JavaScript polyfills are strictly required for progressive enhancement if you view standard text as a readable fallback.---```javascript-document.addEventListener("DOMContentLoaded", () => {- // Check if browser supports base-select value- if (!CSS.supports("appearance", "base-select")) {- // Custom select overrides are not supported natively.- }-});-```\ No newline at end of filediff --git a/skills/modern-web/guides/forms/form-fields-automatically-fit-contents.md b/skills/modern-web/guides/forms/form-fields-automatically-fit-contents.mddeleted file mode 100644index 8ad76e8..0000000--- a/skills/modern-web/guides/forms/form-fields-automatically-fit-contents.md+++ /dev/null@@ -1,119 +0,0 @@-By default, form controls like `<input>`, `<textarea>`, and `<select>` have fixed dimensions. Their sizes remain constant, regardless of the amount of content the user enters or selects.--To allow these controls to automatically shrink or grow to fit their content (including placeholders), use the `field-sizing: content` CSS property.--### Auto-sizing form controls--Setting `field-sizing: content` on inputs, selects, or textareas allows them to resize dynamically as the user types or selects options. However, you must account for inherited styling, layout defaults, and minimum/maximum constraints to ensure a robust user experience.--To prevent layout issues, it is recommended to set both `min-inline-size` (or `min-width`) and `max-inline-size` (or `max-width`) alongside `field-sizing: content` on text inputs. A minimum size prevents the input from collapsing to a width of zero when empty (making it unclickable), and a maximum size ensures it doesn't expand indefinitely and break the page layout.--For textareas, allowing horizontal auto-sizing can cause a jarring UX (e.g., a textarea with a long placeholder will abruptly shrink horizontally when the user types a single character). To prevent this, apply an explicit width (like `width: 100%`) to the textarea. This forces the textarea to maintain a stable horizontal width while still auto-sizing vertically as content wraps.--It is recommended to set a `max-inline-size` (or `max-width`) on `<select>` elements using `field-sizing: content` to ensure that extremely long selected options do not break the page layout.--```css-/* Applies horizontal auto-sizing to inputs */-input {- /* Instructs the element to size itself to fit its content */- field-sizing: content;-- /* Reset explicit width if inherited from global styles */- width: auto;-- /* Prevents the input from collapsing and disappearing when empty */- min-inline-size: 15ch;-- /* Prevents infinite horizontal growth */- max-inline-size: 50ch;-}--textarea {- /* Instructs the element to size itself to fit its content */- field-sizing: content;-- /* Reset explicit height if inherited from global styles */- height: auto;-- /* Use a fixed width to prevent jarring horizontal shifts when replacing a long placeholder */- width: 50ch; /* or 100% depending on your layout */-- /* Sets a reasonable minimum height (e.g., 3 lines) for empty textareas */- min-block-size: 3lh;-- /* Prevents infinite vertical growth. Once a textarea hits this */- /* height, it will stop growing and show a vertical scrollbar. */- max-block-size: 10lh;-}--select {- /* Sizes the select element to fit the active option only */- field-sizing: content;-- /* Prevents the dropdown from expanding infinitely and breaking the layout */- max-inline-size: 50ch;-}-```--IMPORTANT: Explicit `width` and `height` properties override `field-sizing: content` on all form controls. If your project's global CSS sets inputs, selects, or textareas to `width: 100%`, you must explicitly reset them to `width: auto` (or `width: fit-content`) on the elements using `field-sizing: content` for auto-sizing to work. Conversely, you should explicitly set `height: auto` on textareas if a fixed height was previously set globally.--IMPORTANT: Grid and Flexbox layouts often implicitly stretch their children to fill available space. If any form control using `field-sizing: content` refuses to shrink, check its container's alignment properties and apply `align-self: start` or `justify-self: start` to the form control to override the stretching.--### Fallback strategies--field-sizing has limited availability.--`field-sizing` should be treated as a progressive enhancement. In browsers that do not support the property, form controls gracefully degrade back to their default, fixed sizing behavior. Users will simply experience standard scrolling for overflowing content inside fixed-size inputs and textareas.--If dynamically growing fields are absolutely required for older browsers, you must use feature detection and a complex workaround. The most robust fallback for textareas uses a CSS Grid trick where a hidden pseudo-element mirrors the user's input in real-time, forcing the grid container (and the textarea inside it) to expand.--```html-<!-- The textarea is wrapped in a container that will mirror its value -->-<div class="growable-textarea" data-replicated-value="">- <textarea></textarea>-</div>-```--```javascript-// Only attach the fallback event listeners if field-sizing is unsupported-if (!CSS.supports('field-sizing', 'content')) {- document.querySelectorAll('.growable-textarea > textarea').forEach(textarea => {- textarea.addEventListener('input', () => {- textarea.parentNode.dataset.replicatedValue = textarea.value;- });- });-}-```--```css-/* Only apply the fallback if field-sizing is NOT supported */-@supports not (field-sizing: content) {- .growable-textarea {- display: grid;- }-- /* The pseudo-element and textarea must share the exact same cell, font, and padding */- .growable-textarea::after,- .growable-textarea > textarea {- grid-area: 1 / 1 / 2 / 2;- font: inherit;- padding: 0.5rem;- border: 1px solid #999;- }-- /* The pseudo-element renders the copied text invisibly to stretch the grid */- .growable-textarea::after {- /* The space is necessary for trailing empty lines to be rendered */- content: attr(data-replicated-value) " ";- white-space: pre-wrap;- visibility: hidden;- }-- .growable-textarea > textarea {- resize: none;- overflow: hidden;- }-}-```--Given the complexity of duplicating styles and synchronizing state across DOM nodes for every form control, relying on the default fallback behavior of fixed inputs is the recommended approach for most applications unless dynamic sizing is critical to the user experience.\ No newline at end of filediff --git a/skills/modern-web/guides/forms/required-field-feedback.md b/skills/modern-web/guides/forms/required-field-feedback.mddeleted file mode 100644index 707a1e4..0000000--- a/skills/modern-web/guides/forms/required-field-feedback.md+++ /dev/null@@ -1,176 +0,0 @@-# 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--### Fallbacks & browser support for :user-valid and :user-invalid--Baseline status for :user-valid and :user-invalid: Newly available. It's been Baseline since 2023-11-02.--### 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--Use a reusable utility that tracks interaction state using a `WeakMap`. This avoids polluting the DOM with "dirty" classes or data attributes.--```javascript-const UserInvalidFallback = (() => {- const dirtyState = new WeakMap();-- const updateState = (input) => {- const isValid = input.checkValidity();-- // Update both visual and ARIA state- input.classList.toggle('user-invalid-fallback', !isValid);- input.classList.toggle('user-valid-fallback', isValid);-- if (!isValid) {- input.setAttribute('aria-invalid', 'true');- } else {- input.removeAttribute('aria-invalid');- }- };-- const handleEvent = (event) => {- const input = event.target;-- if (event.type === 'reset') {- const controls = input.elements || [];- for (const control of controls) {- dirtyState.delete(control);- control.classList.remove('user-invalid-fallback');- control.classList.remove('user-valid-fallback');- control.removeAttribute('aria-invalid');- }- return;- }-- if (!input.checkValidity) return;-- if (event.type === 'input' || event.type === 'change') {- const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };- state.hasInteracted = true;- dirtyState.set(input, state);- if (state.hasBlurred) {- updateState(input);- }- } else if (event.type === 'blur') {- const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };- state.hasBlurred = true;- dirtyState.set(input, state);- if (state.hasInteracted) {- updateState(input);- }- }- };-- const init = (root = document) => {- if (CSS.supports('selector(:user-invalid)')) return;-- root.addEventListener('blur', handleEvent, true); // Capture phase- root.addEventListener('input', handleEvent);- root.addEventListener('change', handleEvent);- root.addEventListener('reset', handleEvent, true); // Capture resets- };-- return { init };-})();--// Initialize for a specific form-const form = document.querySelector('#demo-form');-UserInvalidFallback.init(form);-```--## Other Considerations--1. **Asterisks**: It is still best practice to indicate required fields visually (e.g., with an asterisk `*`) in the label, so users know what to expect *before* they interact.-2. **Submit Buttons**: Unlike `disabled` buttons, keep your submit button enabled. If the user clicks it, the browser will automatically trigger `:user-invalid` on all empty required fields and focus the first one. This is excellent for accessibility and UX.-3. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:--```javascript-// Sync aria-invalid with the CSS :user-invalid state-const syncAria = (el) => {- el.toggleAttribute?.('aria-invalid', el.matches(':user-invalid'));-};--// Update on blur (to show error) and input (to clear it)-document.addEventListener('blur', (e) => syncAria(e.target), true);-document.addEventListener('input', (e) => {- if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);-});-```diff --git a/skills/modern-web/guides/forms/rich-media-picker.md b/skills/modern-web/guides/forms/rich-media-picker.mddeleted file mode 100644index abb2b82..0000000--- a/skills/modern-web/guides/forms/rich-media-picker.md+++ /dev/null@@ -1,120 +0,0 @@-# Rich Media Picker (Customizable Select)--The native `<select>` element was historically difficult to style and could only contain plain text options. The `appearance: base-select` property offers a declarative, CSS-only way to opt into a customizable state for the `<select>` element. This allows developers to include rich HTML content—such as images, SVGs, and complex layouts—inside `<option>` elements, while retaining native keyboard accessibility and form integration. Use this pattern to replace heavy, custom-built select components with standard, native elements.--## How to Implement--To implement a rich media picker using the Customizable Select API:--1. **Opt-in to base styles**: Apply `appearance: base-select` to both the `<select>` element and its internal picker using the `::picker(select)` pseudo-element. This changes the browser's HTML parser for the contents inside the `<select>`.-2. **Define the Button Content**: Use standard `<button>` and `<selectedcontent>` elements inside the `<select>` to define what is shown when the picker is closed. The `<selectedcontent>` element automatically mirrors the content of the selected option. This is required if you want to display the currently selected rich content in the button.-3. **Use Rich Content inside Options**: You can now place images, SVGs, and other HTML tags inside `<option>` tags. Prior to this API, the browser would strip tags from `<option>` tags and render only plain text.-4. **Style the Popover**: Style the dropped-down options list by targeting the `::picker(select)` pseudo-element. It renders in the top layer, meaning you don't need to fight with `z-index`. Options are positioned using the Anchor Positioning API natively.--## Example Code: Rich Role Picker--```html-<label for="role-picker">Select your role</label>-<select class="custom-select" name="role" id="role-picker">- <button>- <selectedcontent></selectedcontent> <!-- Mirrors the selected option's content automatically so you do not need JS to update the button -->- </button>-- <option value="frontend">- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">- <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>- </svg>- <div class="option-text">- <span class="option-title">Frontend Developer</span>- <span class="option-desc">React, Vue, CSS</span>- </div>- </option>-- <option value="backend">- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">- <rect x="2" y="12" width="20" height="14" rx="2" ry="2"></rect>- </svg>- <div class="option-text">- <span class="option-title">Backend Developer</span>- <span class="option-desc">Node.js, Python</span>- </div>- </option>-</select>-```--```css-select.custom-select,-select.custom-select::picker(select) {- appearance: base-select; /* MUST opt-in both the select and its picker to enable the customizable state, otherwise browser standard rendering applies */-}--select.custom-select {- display: flex;- align-items: center;- justify-content: space-between;- width: 100%;- padding: 12px;- background-color: #1e293b;- border: 1px solid #334155;- border-radius: 8px;- color: #f1f5f9;- cursor: pointer;-}--select.custom-select::picker(select) {- background-color: #0f172a;- border: 1px solid #334155;- border-radius: 8px;- padding: 8px;- box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5);- width: anchor-size(width); /* Uses Anchor Positioning API to keep the dropdown precisely aligned to the button trigger width */-}--select.custom-select option {- display: flex;- align-items: center;- gap: 12px;- padding: 10px;- border-radius: 4px;- cursor: pointer;-}--select.custom-select option:hover {- background-color: #1e293b;-}--/* Remove standard OS checkmark for base-select */-select.custom-select option::before {- display: none;-}-```--## Strategic Implementation & Best Practices--- **DO** use `appearance: base-select` when you need complex options layouts (icons, descriptions, images) that was previously only possible with heavy JavaScript UI frameworks.-- **DO NOT** use ad-hoc elements if you notice performance lags; the browser handles native keyboard focus natively.-- **DO** account for top-layer rendering. The picker renders in the top-layer, meaning it overrides relative `z-index` of page content.-- **DO** hide secondary details (like descriptions) in the button state if they take too much space, by styling `.custom-select selectedcontent .option-desc { display: none; }`.-- **DO** test layout behavior. Setting `appearance: base-select` removes the default browser behavior of sizing the select based on its longest option width. You may need to set a fixed width or use flex/grid constraints to prevent layout shifts.-- **DO** ensure your `<select>` has a `name` attribute and an associated `<label>`. This ensures that even with a custom UI, the component remains accessible to screen readers and works correctly with standard form submissions.--## Fallback Strategies--### Fallbacks & browser support for Customizable <select>--Customizable <select> has limited availability.--For browsers that do not yet support `appearance: base-select`, the `<select>` element degrades gracefully to a standard operating system dropdown.--- **Non-Text Content Ignored**: Older browsers strip HTML tags (like `<svg>` or `<div>`) inside `<option>` tags and render only the text nodes. Ensure the text content of the `<option>` is readable and meaningful on its own.-- **HTML Structure Handling**: Standard parsers may ignore the `<button>` and `<selectedcontent>` tags inside `<select>` or treat them as invalid. No heavy JavaScript polyfills are strictly required for progressive enhancement if you view standard text as a readable fallback.---```javascript-document.addEventListener("DOMContentLoaded", () => {- // Check if browser supports base-select value- if (!CSS.supports("appearance", "base-select")) {- // Custom select overrides are not supported natively.- }-});-```diff --git a/skills/modern-web/guides/forms/select-menu-interaction.md b/skills/modern-web/guides/forms/select-menu-interaction.mddeleted file mode 100644index 26cc038..0000000--- a/skills/modern-web/guides/forms/select-menu-interaction.md+++ /dev/null@@ -1,179 +0,0 @@-# 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.--### Fallbacks & browser support for :user-valid and :user-invalid--Baseline status for :user-valid and :user-invalid: Newly available. It's been Baseline since 2023-11-02.--### 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--Use a reusable utility that tracks interaction state using a `WeakMap`. This avoids polluting the DOM with "dirty" classes or data attributes.--```javascript-const UserInvalidFallback = (() => {- const dirtyState = new WeakMap();-- const updateState = (input) => {- const isValid = input.checkValidity();-- // Update both visual and ARIA state- input.classList.toggle('user-invalid-fallback', !isValid);- input.classList.toggle('user-valid-fallback', isValid);-- if (!isValid) {- input.setAttribute('aria-invalid', 'true');- } else {- input.removeAttribute('aria-invalid');- }- };-- const handleEvent = (event) => {- const input = event.target;-- if (event.type === 'reset') {- const controls = input.elements || [];- for (const control of controls) {- dirtyState.delete(control);- control.classList.remove('user-invalid-fallback');- control.classList.remove('user-valid-fallback');- control.removeAttribute('aria-invalid');- }- return;- }-- if (!input.checkValidity) return;-- if (event.type === 'input' || event.type === 'change') {- const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };- state.hasInteracted = true;- dirtyState.set(input, state);- if (state.hasBlurred) {- updateState(input);- }- } else if (event.type === 'blur') {- const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };- state.hasBlurred = true;- dirtyState.set(input, state);- if (state.hasInteracted) {- updateState(input);- }- }- };-- const init = (root = document) => {- if (CSS.supports('selector(:user-invalid)')) return;-- root.addEventListener('blur', handleEvent, true); // Capture phase- root.addEventListener('input', handleEvent);- root.addEventListener('change', handleEvent);- root.addEventListener('reset', handleEvent, true); // Capture resets- };-- return { init };-})();--// Initialize for a specific form-const form = document.querySelector('#demo-form');-UserInvalidFallback.init(form);-```--## Other Considerations--1. **Mobile behavior**: On mobile devices, "blur" might happen differently depending on the OS picker. Testing on actual devices is recommended.-2. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:--```javascript-// Sync aria-invalid with the CSS :user-invalid state-const syncAria = (el) => {- el.toggleAttribute?.('aria-invalid', el.matches(':user-invalid'));-};--// Update on blur (to show error) and input (to clear it)-document.addEventListener('blur', (e) => syncAria(e.target), true);-document.addEventListener('input', (e) => {- if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);-});-```diff --git a/skills/modern-web/guides/forms/validate-input-after-interaction.md b/skills/modern-web/guides/forms/validate-input-after-interaction.mddeleted file mode 100644index dfa3964..0000000--- a/skills/modern-web/guides/forms/validate-input-after-interaction.md+++ /dev/null@@ -1,248 +0,0 @@-# 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--### Fallbacks & browser support for :user-valid and :user-invalid--Baseline status for :user-valid and :user-invalid: Newly available. It's been Baseline since 2023-11-02.--### 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--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. **Accessibility**:- * MANDATORY: Use `aria-describedby` to link the rules list to the input.- * DO NOT: Hide rules lists entirely until the input is valid; users need to know what to type!-2. **Pattern Attribute Limits**: MANDATORY: The `pattern` attribute performs a full match (implied `^...$`). Ensure your password regex accounts for the entire string.-3. **Validation Strictness**: DO note that the browser's default `type="email"` validation is quite permissive (e.g., `user@localserver` might pass). If you need stricter validation, you may need to use a more robust validation library or a custom validation function alongside `type="email"`.-4. **Focus Management**: MANDATORY: If a user submits the form with an invalid field, the browser will automatically focus the first invalid field. Your `:user-invalid` styles will apply immediately because a submission attempt counts as an interaction.-5. **Consistent ARIA Experience**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:--```javascript-// Sync aria-invalid with the CSS :user-invalid state-const syncAria = (el) => {- el.toggleAttribute?.('aria-invalid', el.matches(':user-invalid'));-};--// Update on blur (to show error) and input (to clear it)-document.addEventListener('blur', (e) => syncAria(e.target), true);-document.addEventListener('input', (e) => {- if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);-});-```diff --git a/skills/modern-web/guides/guides/css.md b/skills/modern-web/guides/guides/css.mddeleted file mode 100644index a0195bd..0000000--- a/skills/modern-web/guides/guides/css.md+++ /dev/null@@ -1,285 +0,0 @@-# CSS: Modern Architecture and Performance--These guidelines provide a high-density reference for writing maintainable, performant, and standard-compliant CSS.--## 1. Architectural Foundations and The Cascade-Effective CSS architecture focuses on managing the global namespace and controlling specificity natively.--### DOs and DON'Ts-- **DO** use a global `box-sizing: border-box` reset to ensure padding doesn't break layouts.-- **DO** use keywords like `inherit`, `initial`, `unset`, or `revert` to explicitly control inheritance.-- **DO** use **Cascade Layers** (`@layer`) to define explicit priority zones (e.g., `reset`, `base`, `theme`, `components`, `utilities`).-- **DO** declare the layer order upfront in your main CSS file: `@layer reset, base, theme, components, utilities;`.-- **DO** understand that `!important` declarations in a lower-priority layer override those in a higher-priority layer (precedence is reversed).-- **DO** use specialized naming conventions like **BEM** (`.block__element--modifier`) to avoid namespace collisions.-- **DO** use `isolation: isolate` to create a fresh stacking context without side-effects.--### Code Example: Foundations & Reset-```css-/* Global Reset */-*, *::before, *::after {- box-sizing: border-box;-}--/* 1. Define order */-@layer reset, theme, components;--/* 2. Low priority foundational styles */-@layer reset {- a { color: inherit; text-decoration: none; }-}--/* 3. Higher priority component styles */-@layer components {- .btn {- background: var(--brand);- color: white;- }-}--/* Unlayered styles (Highest priority outside of !important) */-.emergency-override {- display: block;-}-```--## 2. Advanced Visuals, Borders, and Blend Modes-Modern CSS provides advanced effects for depth, textures, and non-rectangular geometries.--### DOs and DON'Ts-- **DO** layer multiple shadows (comma-separated) for realistic soft depth effects.-- **DO** use `filter: drop-shadow()` instead of `box-shadow` for non-rectangular shapes or transparent PNGs.-- **DO** use elliptical `border-radius` (e.g., `10px / 20px`) for proportional curves without extra elements.-- **DO** use `mix-blend-mode` and `background-blend-mode` for lighting overlays (limit scope with `isolation: isolate`).-- **DO** use keywords before length values in `background-position` (e.g., `bottom 10px right 20px`).-- **DO** use `clip-path` and `mask-image` for custom geometric reveals and smooth fade-outs.-- **DO** use `::selection` to customize highlighted text colors.-- **DO** use CSS Counters (`counter-reset`, `counter-increment`) for automated numbering visible in `::before`/`::after`.--### Code Example: Advanced Visuals-```css-.card {- box-shadow:- 0 1px 1px rgba(0,0,0,0.1),- 0 2px 2px rgba(0,0,0,0.1),- 0 4px 4px rgba(0,0,0,0.1); /* Layered shadow */-- border-radius: 50px / 25px; /* Elliptical corners */-}--.icon {- filter: drop-shadow(0 5px 15px rgba(0,0,0,0.5)); /* Edge-following shadow */-}--.hero {- background-image: url('texture.png'), linear-gradient(to bottom, #fff, #eee);- background-blend-mode: soft-light;-}--.portrait {- clip-path: circle(50% at center);- mask-image: linear-gradient(to bottom, black, transparent);-}-```---## 3. Native Selectors and Scoping-Modern browser-native selectors reduce the need for preprocessors and complex state-tracking in JS.--### DOs and DON'Ts-- **DO** use native CSS nesting to group related styles (3 levels max).-- **DO** use `:has()` to style parents based on child state (e.g., `.form-group:has(:invalid)`). For more information, see the guides at `child-state-based-styling` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "child-state-based-styling"`) and `content-based-styling` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "content-based-styling"`).-- **DON'T** nest `:has()` or use pseudo-elements inside `:has()` (browser API limitation).-- **DO** use Attribute selectors (e.g., `[disabled]`) to style elements based on their state or metadata.-- **DO** use `:where()` for baseline styles you want to be easily overridable (0 specificity).-- **DO** use `:focus-visible` instead of `:focus` to hide focus rings for pointer interactions (mouse/touch) while preserving them for keyboard navigation and elements requiring text input.-- **DO** pair focus outlines with `outline-offset` to separate the ring from the element.-- **DON'T** use `outline: none` without providing a visible focus style.-- **DON'T** rely on `box-shadow` for focus rings if you need to support Windows High Contrast Mode (use `outline` instead).-- **DON'T** use `::before` or `::after` on replaced elements (`<img>`, `<input>`, `<video>`).--### Code Example: Advanced Selectors-```css-.card {- position: relative;-- /* Accessible focus visible state */- &:focus-visible {- outline: 2px solid var(--accent);- outline-offset: 4px; /* Separate ring from border */- }-- /* Conditional styling based on content */- &:has(img) { padding: 0; }-- /* State management without extra classes */- &:has(input:checked) { border-color: var(--active); }-- /* Shared styles without high specificity */- :is(.title, .subtitle) {- margin: 0;- font-weight: bold;- }-}--/* Zero-specificity reset */-:where(a) { color: blue; }-```--### Functional Selectors Specificity Matrix--| Selector | Specificity Weight | Primary Use Case |-| :--- | :--- | :--- |-| **`:where()`** | Exactly **0** | Baseline resets and design system defaults. |-| **`:is()`** | Max specificity of its arguments | Reducing code duplication for shared styles. |-| **`:has()`** | Max specificity of its arguments | Parent/relational styling based on child states or siblings. |--**Single-Sentence Mental Model**: "`:where()` = Spec-neutral resets, `:is()` = Spec-heavy grouping, `:has()` = Relational state."--## 4. Design Systems and Theming-CSS Custom Properties (Variables) and modern color functions are the foundation of dynamic theming.--### DOs and DON'Ts-- **DO** define design tokens as Custom Properties (`--brand-color`) on `:root`.-- **DO** use `light-dark()` for simplified color scheme support (requires `color-scheme: light dark;`).-- **DO** leverage `light-dark()` responding to *localized* `color-scheme` overrides (forcing dark theme on a subtree).-- **DO** use `color-mix(in oklab, var(--primary) 70%, white 30%)` for dynamic tints outside of relative color syntax.-- **DO** use **Relative Color Syntax** (`oklch(from var(--primary) l c h / 0.5)`) to derive tints dynamically.--### Code Example: Modern Theming-```css-:root {- color-scheme: light dark;- --primary: oklch(60% 0.15 250);-}--.dark-sidebar {- color-scheme: dark; /* Forces child light-dark() values to use dark options */-}-```--### Theme Management Matrix--| Feature | `light-dark()` | `@media (prefers-color-scheme)` |-| :--- | :--- | :--- |-| **Scope** | Local or Global | Strictly Global |-| **Trigger Mechanism** | `color-scheme` property | OS/Browser preference |-| **Component Overrides** | ✅ Easy | ❌ Difficult |--**Single-Sentence Mental Model**: "`light-dark()` = Contextual theme (supports local overrides), `@media` = Global preference (OS-level)."--## 5. Transitions, Animations, and Performance-Rendering performance is critical for smooth user experiences, especially in heavy DOM trees.--### DOs and DON'Ts-- **DO** only animate `transform` and `opacity` to ensure animations stay on the compositor thread.-- **DO** use `translate` (or `transform: translate()`) instead of animating `top`/`left`/`right`/`bottom` to avoid triggering layout reflows and ensure smoother animations.-- **DO** use `transition-behavior: allow-discrete` to animate layout properties like `display` or `<dialog>` state natively.-- **DO** always pair `content-visibility` with `contain-intrinsic-size` to prevent scrollbar jumps (CLS).-- **DO** use `contain: layout style paint` to isolate component rendering updates.--### Code Example: Render Optimization-```css-.large-section {- content-visibility: auto;- contain-intrinsic-size: auto 800px;-}--.popover-reveal {- /* Allow discrete animations for display transitions */- transition: display 0.2s allow-discrete;-}-```----## 6. Modern Gradients and Color Spaces-Create vibrant UI patterns without gray dead-zones using modern color spaces.--### DOs and DON'Ts-- **DO** use `in <color-space>` (e.g., `in oklch` or `in oklab`) to avoid vibrant colors washing out into grayscale in between.-- **DO** use hard-edge color stops for sharp patterns (e.g., `red 50%, blue 50%`).-- **DO** use `conic-gradient()` for progress rings or charts.-- **DON'T** use `linear-gradient()` without a color space override if you are transitioning between highly saturated colors.--### Code Example: Modern Gradients-```css-/* Smooth, vibrant transition without standard gray dead-zones */-.hero-gradient {- background: linear-gradient(in oklch, var(--primary), var(--secondary));-}--/* Hard-edge stripes */-.stripe-bg {- background: linear-gradient(to right, var(--main) 50%, var(--accent) 50%);-}-```--## 7. Responsive Typography and Visual Sizing-Use fluid and accessible typography that respects viewport widths and browser zoom.--### DOs and DON'Ts-- **DO** use unitless numbers for `line-height` (e.g., `1.5`) to ensure relative scaling during font-size inheritance.-- **DO** use `clamp(min, preferred, max)` for fluid typography without media queries.-- **DO** use standalone `min()` and `max()` to constrain values responsively.-- **DO** use `text-wrap: balance` for short headlines (up to 4-6 lines) to prevent uneven orphans.-- **DO** use `overflow-wrap: break-word` (or `anywhere`) to contain long URLs.-- **DO** use `@container` queries to create component-driven responsive layouts that adapt to their parent container's size rather than the viewport.-- **DO** use dynamic viewport units (`dvh`, `dvw`) instead of `vh`/`vw` to prevent layout breakage when mobile browser UI elements (like address bars) appear or disappear.-- **DO** use `aspect-ratio` for media elements (like `<img>` and `<video>`) to reserve space during loading and prevent Cumulative Layout Shift (CLS).-- **DON'T** use `px` for font-size. Prefer `rem` to honor the user's browser font-size preferences (root font size), as `px` values are absolute and may ignore user-defined defaults.-- **DON'T** use `vw` alone for font-size without a min/max clamp, as it can scale text too small or too large on extreme screens.--### Code Example: Fluid Typography-```css-h1 {- font-size: clamp(2rem, 5vw + 1rem, 4rem); /* Fluid typography */- text-wrap: balance;- line-height: 1.2;-}--.url-container {- overflow-wrap: anywhere;- hyphens: auto;-}-```--## 8. Transitions, View Transitions, and Scroll Motion-Leverage browser-native APIs for page navigations and viewport-bound animations.--### DOs and DON'Ts-- **DO** use `prefers-reduced-motion` media queries to turn off heavy motion for users who prefer it.-- **DO** use **Scroll-Driven Animations** (`animation-timeline: scroll()`) for scroll-bound parallax effects instead of JS listeners.-- **DO** use the **View Transitions API** (`view-transition-name`) to animate layouts seamlessly between page states.--### Code Example: Native Motion Primitives-```css-@media (prefers-reduced-motion: reduce) {- * { animation-duration: 0.01ms !important; }-}--.scroll-tracker {- animation: progress-tint linear;- animation-timeline: scroll(); /* Native, zero-JS */-}-```--## 9. Scoping and Shadow DOM-Keep CSS architecture clean by explicitly scoping styles to components.--### DOs and DON'Ts-- **DO** use native `@scope` to isolate styles to a component boundary (e.g., `@scope (.card) to (.content) { ... }`).-- **DO** use `:host` to style the custom element wrapper in Shadow DOM.-- **DON'T** use global resets if you are relying on Shadow DOM isolation, as they will override local component styles unless scoped.--### Code Example: Scoped CSS-```css-/* Isolation without BEM side-effects */-@scope (.media-object) {- .title {- font-weight: bold;- }-}---```diff --git a/skills/modern-web/guides/guides/forms.md b/skills/modern-web/guides/guides/forms.mddeleted file mode 100644index 67b0fe3..0000000--- a/skills/modern-web/guides/guides/forms.md+++ /dev/null@@ -1,364 +0,0 @@-## 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/guides/html.md b/skills/modern-web/guides/guides/html.mddeleted file mode 100644index 90350a4..0000000--- a/skills/modern-web/guides/guides/html.md+++ /dev/null@@ -1,406 +0,0 @@-## Table of Contents--1. Fundamental Semantics and Validation-2. Content Grouping and Attribution-3. Resource Prioritization and Performance-4. Native Overlays: Dialogs and Popovers-5. Disclosures: Details and Summary-6. Focus Boundaries and Visibility-7. HTML APIs and Forms Grouping-8. Native Media Elements-9. Dynamic Styles and Interactivity--## 1. Fundamental Semantics and Validation--### Guidelines--- **DO** use the standard HTML5 doctype `<!DOCTYPE html>` to prevent quirky rendering modes.-- **DO** set the `lang` attribute on the `<html>` element for screen reader pronunciation and translation tools.-- **DO** use the `<meta name="viewport">` element with the `content` attribute set to `"width=device-width, initial-scale=1.0"` to ensure page responsiveness.-- **DO** use a single `<h1>` per page/view representing the main topic. Exceptions can be made for modal dialogs, which can also use a single `<h1>`.-- **DO** maintain a sequential, non-skipping heading hierarchy (`<h2>` to `<h3>`, but not `<h2>` to `<h4>`).-- **DO** use semantic landmarks (`<header>`, `<nav>`, `<main>`, `<aside>`, `<footer>`) to create regional navigation for assistive technologies.-- **DO** use `<search>` to enclose search and filtering mechanisms (eliminates the need for `role="search"`).-- **DO** use `<button>` for triggered actions (JS, Modals, Forms) and `<a>` strictly for URL navigation. Set `type="button"` for non-submit buttons in forms to prevent unintended submission.-- **DO** use `<ul>`, `<ol>`, and `<dl>` elements for list content.-- **DO** ensure that all interactive elements like links and buttons have accessible names.-- **DO** hide purely decorative SVG images from assistive technology using `aria-hidden="true"`. If using a decorative `<img>`, always include an empty `alt` attribute (e.g. `alt=""`).-- **DO** ensure that informative SVGs like logos, data visualizations, or icon buttons have a proper accessible name.--- **DON'T** use generic `<div>` or `<span>` when semantic elements exist, for instance for interactive elements, headings, or independently reusable self-contained content.-- **DON'T** use boolean attributes with redundant values (e.g., use `disabled`, not `disabled="disabled"`).-- **DON'T** use generic elements with added ARIA roles or states when native elements with built-in semantics and behavior exist.-- **DON'T** change the native semantics of elements with ARIA unless it is a critical requirement.-- **DON'T** use `role="presentation"` or `aria-hidden="true"` on focusable elements or their parents and ancestors.-- **DON'T** disable page zooming capabilities.--### Code Example--```html-<!DOCTYPE html>-<html lang="en">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>Dashboard | Platform</title>-</head>-<body>- <header>- <nav>- <ul>- <li><a href="#">About</a></li>- <li><a href="#">Contact</a></li>- </ul>- </nav>- </header>- <main>- <h1>Analytics</h1>- <search>- <form action="/filter" method="GET">- <label for="search-input">Scan items:</label>- <input type="search" id="search-input" name="q">- <button type="submit">Search</button>- </form>- </search>- <article>- <h2>First post</h2>- </article>- </main>-</body>-</html>-```--## 2. Content Grouping and Attribution--### Guidelines--- **DO** use `<blockquote>` for extended quotations from another source, and use the `cite` attribute to provide a machine-readable URL for that source.-- **DO** use `<figure>` to group self-contained content (images, code snippets, or quotes) that is referenced from the main flow but could be moved to an appendix or sidebar without affecting the document's meaning.-- **DO** use `<figcaption>` as the first or last child of a `<figure>` to provide a human-readable caption or attribution.-- **DO** use the `<cite>` element inside a caption or attribution to identify the **title** of a work (e.g., a book or website name), not the author's name.-- **DO** use the `<code>` element for short fragments of computer code (e.g., variable names, file paths, or inline snippets).-- **DO** wrap `<code>` inside a `<pre>` element when displaying blocks of code to preserve whitespace and line breaks.-- **DO** ensure that code blocks are accessible by adding `tabindex="0"` to the `<pre>` element if it becomes scrollable, allowing keyboard users to reach the content.--- **DON'T** use `<blockquote>` for purely visual indentation of non-quoted text.-- **DON'T** use `<figure>` for every single image; use it only when a caption is required or when the content is a distinct, referenced unit.-- **DON'T** use `<pre>` without `<code>` for code blocks; `<pre>` alone only preserves formatting but doesn't convey that the content is a computer language.--### Code Example--```html-<!-- Quote with attribution using Figure -->-<figure>- <blockquote cite="https://html.spec.whatwg.org/">- <p>The figure element represents some flow content, optionally with a caption, that is self-contained and is typically referenced as a single unit from the main flow of the document.</p>- </blockquote>- <figcaption>- Definition of the <figure> element from the <cite>HTML Living Standard</cite>- </figcaption>-</figure>--<!-- Image with caption -->-<figure>- <img- src="architecture-diagram.webp"- alt="Diagram showing the flow between Client, API Gateway, and Microservices"- width="800"- height="450"- loading="lazy"- >- <figcaption>Figure 1: High-level system architecture overview.</figcaption>-</figure>--<!-- Code block with accessibility and language hint -->-<figure>- <figcaption>Example configuration:</figcaption>- <pre tabindex="0"><code class="language-json">-{- "name": "gemini-cli",- "version": "1.0.0",- "private": true-}- </code></pre>-</figure>--<!-- Inline code -->-<p>To initialize the project, run the <code>npm install</code> command.</p>-```--## 3. Resource Prioritization and Performance--### Guidelines--- **DO** use `fetchpriority="high"` for the Largest Contentful Paint (LCP) element (e.g., hero image) to elevate network priority.-- **DO** use `<link rel="preload" as="image">` with `fetchpriority="high"` for LCP background images defined in CSS.-- **DO** apply `loading="lazy"` to off-screen images and iframes to defer bandwidth.-- **DO** specify `width` and `height` on all `<img>` tags to preserve aspect ratio and prevent Layout Shifts (CLS).-- **DO** use the `srcset` attribute on `<img>`s for adding multiple versions of the same image at different sizes.-- **DO** use the `<picture>` element with a fallback `<img>` for more fine-grained image control like switching between image formats, image sizes, and cropping images at different device sizes.--- **DON'T** apply `loading="lazy"` to above-the-fold or hero images. This delays LCP.-- **DON'T** overuse `fetchpriority="high"`; prioritization is a zero-sum mechanism. Use `fetchpriority="low"` to demote non-critical trackers or carousel items.--### Code Example--```html-<!-- High-priority hero image with responsive sizes -->-<img- src="hero-large.webp"- srcset="hero-small.webp 480w, hero-medium.webp 800w, hero-large.webp 1200w"- sizes="(max-width: 600px) 100vw, (max-width: 1200px) 80vw, 70vw"- alt="Main product view"- fetchpriority="high"- width="1200"- height="600"->--<!-- Art direction and format switching with <picture> -->-<picture>- <!-- Mobile Art Direction: Different aspect ratio (square) and format (AVIF) -->- <source- media="(max-width: 600px)"- srcset="hero-mobile.avif 1x, hero-mobile-2x.avif 2x"- type="image/avif"- width="600"- height="600"- >- <source- media="(max-width: 600px)"- srcset="hero-mobile.webp 1x, hero-mobile-2x.webp 2x"- width="600"- height="600"- >-- <!-- Desktop: Modern format for primary layout -->- <source srcset="hero-desktop.avif" type="image/avif">-- <!-- Fallback img defines the default aspect ratio (2:1) -->- <img- src="hero-desktop.webp"- alt="Platform dashboard overview"- width="1200"- height="600"- loading="lazy"- >-</picture>--<!-- Low-priority decorative footer image -->-<img- src="footer-art.png"- alt=""- loading="lazy"- width="200"- height="100"->-```--## 4. Native Overlays: Dialogs and Popovers--### Guidelines--See `declarative-dialog-popover-control` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "declarative-dialog-popover-control"`) for more info on fallback strategies for using the Popover API in a cross-browser way.-- **DO** use `<dialog>` for modal overlays (requires JS `.showModal()`) to automatically trap focus, dim backgrounds, and support dismissing via `Esc`. Use the `closedby="any"` attribute to enable native "light-dismiss" (closing on backdrop click) without custom JavaScript.-- **DO** utilize the Popover API (`popover` attribute) for non-modal UI (menus, tooltips) that do not require focus traps.-- **DO** use `::backdrop` to style modal backgrounds.-- **DO** use `<form method="dialog">` to dismiss dialogs without manual JS handlers. Combined button `formmethod="dialog"` yields the button's value to the dialog `.returnValue`.--- **DON'T** use `show()` for modals where keyboard traps are expected (use `showModal()`).-- **DON'T** call `showModal()` on elements possessing a `popover` attribute (they are mutually exclusive programmatic states). However, `<dialog popover="auto">` is a valid declarative architecture to combine dialog semantics with light-dismiss mechanics.--### Code Example--```html-<!-- Popover (No JS required for toggle) -->-<button popovertarget="help-menu">Info</button>-<div id="help-menu" popover="auto">- <p>Standard help text.</p>-</div>--<!-- Modal Dialog with Form-based closing -->-<button id="show-dialog">Open dialog</button>-<dialog id="fav-modal">- <!-- method="dialog" closes the dialog natively and sets the returnValue -->- <form method="dialog">- <p>Confirm action?</p>- <button value="cancel">Cancel</button>- <button value="confirm">Confirm</button>- </form>-</dialog>--<script>- const dialog = document.getElementById("fav-modal");- const openModal = document.getElementById("show-dialog");-- // Show modal dialog- openModal.addEventListener('click', () => dialog.showModal());-- // Listen for the 'close' event to retrieve the user's choice (returnValue)- dialog.addEventListener('close', () => {- console.log(dialog.returnValue); // "confirm" or "cancel"- });-</script>-```--### Native UI Overlay & Disclosure Matrix--| Feature | Modality | Focus | Dismiss Mechanism | Use Case |-| :--- | :--- | :--- | :--- | :--- |-| **`<dialog>`** | Modal / Non-modal | Automatic trap (Modal) | Esc / Form / `closedby` | Critical Actions, Settings |-| **`[popover]`** | Non-modal | Standard Tab flow | Light-dismiss (Click outside) | Menus, Tooltips, Toasts |-| **`<details>`** | Inline Disclosure | Standard Tab flow | Toggle summary | Accordions, FAQs |--**Heuristic Rule**: Use `<dialog>` for interruptions requiring user action, `popover` for transient info, and `<details>` for inline content expansion.--## 5. Disclosures: Details and Summary--### Guidelines--- **DO** use `<details>` and `<summary>` for native accordions or revealable content without JS.-- **DO** place `<summary>` as the *first* child of `<details>`.-- If headings must be used within a `<summary>`, consider if the heading is essential for understanding or navigating the document structure. If it is, use a more robust disclosure approach that allows wrapping the disclosure trigger with the heading (e.g. `<h2><button type="button" aria-expanded="false" aria-controls="significant-section-content">Significant section</button></h2>`). This ensures the heading semantics aren’t lost, and the button and its state are announced.-- **DO** use `details[open]` attribute for styling expanded states.-- **DO** use `details::details-content` for styling the contents of the `<details>` element.-- **DO** use the `name` attribute on multiple `<details>` elements to create exclusive accordions (opening one closes others).--- **DON'T** nest other interactive elements (links, buttons) directly inside `<summary>` text as it acts as a button and breaks focus.-- **DON'T** hide visible triangles via `list-style: none` without providing explicit directional cues (via `::before`/`::after` pseudo-elements).-- **DON'T** use the `title` attribute to create tooltip effects.--### Code Example--```html-<!-- Exclusive Accordion Set -->-<details name="faq">- <summary>Item 1</summary>- <p>Contents...</p>-</details>-<details name="faq">- <summary>Item 2</summary>- <p>Contents...</p>-</details>-```--## 6. Focus Boundaries and Visibility--### Guidelines--- **DO** use the global `inert` attribute for entire hidden sections (off-screen menus, background while custom modal is open) to remove them from tab flows and accessibility trees.-- **DO** pair `[inert]` with CSS (`opacity: 0.5`) to visually signify inactivity.-- **DO** rely on natural DOM order for sequential navigation.--- **DON'T** use positive `tabindex` values (e.g., `1`, `2`). Use `0` to add element to tab flow, or `-1` for JS program focus.-- **DON'T** alter focus flow using CSS properties (`flex-flow: row-reverse`, `order`) without aligning the DOM structure.-- **DON'T** use `node.focus({ preventScroll: true })` without usability validation; it can hide the focused element off-screen.--### Code Example--```html-<!-- De-tabbing a background app shell while custom drawer is open -->-<main id="app-shell" inert>- <a href="/">Dashboard</a>-</main>-<aside id="drawer">- <button>Close</button>-</aside>-```--```css-[inert], [inert] * {- opacity: 0.5;- cursor: default;- user-select: none;-}-```--## 7. HTML APIs and Forms Grouping--### Guidelines--See `forms` (via `npx -p modern-web-guidance@latest -- modern-web retrieve "forms"`) for more details on creating modern web forms.--- **DO** utilize the `form="form-id"` attribute to decouple inputs from the physical `<form>` tree.-- **DO** use `<datalist>` coupled with `<input list="id">` for lightweight auto-suggestions (note: visually unstylable and has screen-reader quirks).-- **DON'T** use `autocomplete="off"` on credential, address, payment, or contact fields. Browsers and password managers ignore it there by design. Use a specific token instead (`autocomplete="email"`, `"street-address"`, `"cc-number"`, etc.).-- **DON'T** use `autocomplete="off"` unless handling highly sensitive tracking tokens (violates standard password manager overrides). Use standard inputs `type="email"`, `type="tel"`.-- **DO** distinguish `autocomplete="current-password"` (sign-in) from `autocomplete="new-password"` (registration / password change) so password managers offer the right action.-- **DO** match `autocomplete` tokens with appropriate `inputmode` and `type` (`type="email"` + `inputmode="email"` + `autocomplete="email"`). They control different things — keyboard, validation, and autofill respectively — and reinforce each other.--### Code Example--```html-<form>- <fieldset>- <legend>Address Information</legend>- <label for="city">City:</label>- <input type="text" id="city" list="cities" autocomplete="address-level2">- <datalist id="cities">- <option value="New York">- <option value="London">- </datalist>- </fieldset>-</form>-```--## 8. Native Media Elements--### Guidelines--- **DO** set `width` and `height` to prevent layout shifts (CLS) on `<video>` elements.-- **DO** provide a `poster` image fallback for videos.-- **DO** include subtitles and captions with `<track>`.-- **DO** ensure background videos are `muted`, provide users with full control over playback, and use `role="none"` or `aria-hidden="true"`. The `controls` attribute must also be omitted to make sure the video is not focusable.--- **DON'T** rely on JS for basic video controls if native `controls` attribute is sufficient.--### Code Example--```html-<video- controls- width="800"- height="450"- poster="poster.webp"->- <source src="intro.webm" type="video/webm">- <source src="intro.mp4" type="video/mp4">- <track src="caps.vtt" kind="captions" srclang="en" label="English">-</video>-```--## 9. Dynamic Styles and Interactivity--### Guidelines-- **DO** use the `style` attribute to pass state to CSS via **Custom Properties**. This keeps visual logic in your stylesheet while JavaScript provides the raw data.--- **DON'T** use inline styles for static design (colors, padding, margins) that belong in a stylesheet.-- **DON'T** use inline event handlers (e.g., `onclick`). Trigger actions using `addEventListener()`.--### Code Example--```html-<body>- <!-- Progress with style-driven color data -->- <label for="upload-progress">Upload status:</label>- <progress id="upload-progress" class="loading-bar" value="0" max="100" style="--brand-hue: 200;"></progress>-- <script>- const updateProgress = (percent, hue) => {- const bar = document.querySelector('.loading-bar');- bar.value = percent;-- // Update dynamic style variable- if (hue) bar.style.setProperty('--brand-hue', hue);- };-- // Example: Move to 85% and shift color to green (120)- setTimeout(() => updateProgress(85, 120), 1000);- </script>-</body>-```-```css-.loading-bar {- accent-color: hsl(var(--brand-hue, 200) 80% 50%);- transition: accent-color 0.3s ease;-}-```diff --git a/skills/modern-web/guides/guides/javascript.md b/skills/modern-web/guides/guides/javascript.mddeleted file mode 100644index 165ff52..0000000--- a/skills/modern-web/guides/guides/javascript.md+++ /dev/null@@ -1,177 +0,0 @@-# JavaScript Development Standards--This skill is a baseline for writing clean, performant, and secure JavaScript. These guidelines apply to web platform development and assume modern ECMAScript standards (ES2023+).--This skill defers to specific use-case guidance found in the `/guides/` directory when applicable.--## Modern Syntax and Variable Declarations--- **Use `const` by Default**: Use `const` for all variable declarations. Use `let` only when reassignment is strictly required.-- **Never Use `var`**: Deprecate the legacy `var` keyword to avoid function-scoping and hoisting bugs.-- **Enforce Strict Mode**: Add `"use strict";` at the top of scripts or functions if not inside an ES module or class (which are strict by default).-- **Prefer Primitives and Literals**: Avoid object wrappers (e.g., `new String()`, `new Number()`). Define variables using literals (e.g., `""`, `0`, `true`), standard conversion functions (e.g., `Number()`, `String()`) for type conversion, and standard parse functions (e.g.,`parseInt()`, `parseFloat()`) for string-to-number parsing.-- **Use Strict Equality `===`**: Always use `===` and `!==` over `==` and `!=` to bypass dangerous implicit type coercion. Use `Number.isNaN()` to check if a value is `NaN`.-- **Nullish Operators for Safety**:- - Use Optional Chaining (`?.`) to safely traverse nested objects without throwing `TypeError`.- - Use Nullish Coalescing (`??`) for defaults instead of logical OR (`||`) to avoid accidentally overriding valid falsy values like `0` or `""`.-- **Use Template Literals**: Use backticks `` ` `` and `${}` for string interpolation instead of concatenation `+`.-- **Naming Conventions**: Use `camelCase` for variables and functions, `PascalCase` for classes.-- **Use `structuredClone()` to Recursively Copy Objects**: Avoid using `JSON.parse(JSON.stringify(object))` to clone an object.-- **Precise Calculations**: Use integers or whole numbers for precision-critical math (e.g., currency) to avoid floating-point issues (`0.1 + 0.2 !== 0.3`).-- **Document with JSDoc**: Provide inline code documentation that integrates with tooling with JSDoc. DO include `@param` and `@returns` to document functions.--```javascript-// ✅ GOOD-const score = 0;-const finalScore = score ?? 10; // 0--// ❌ BAD-const finalScoreLegacy = score || 10; // 10 (incorrectly overrides 0)-```--## Functions and Async Flow--- **Prefer Rest and Default Parameters**: Use Rest parameters (`...args`) instead of the legacy `arguments` object. Define defaults inside the signature (`param = value`).-- **Arrow Functions for Lexical `this`**: Use arrow functions when you want to preserve the surrounding context's `this` (e.g., inside callbacks or timers).-- **Standard Functions for Dynamic `this`**: Use standard function syntax (`functionName() {}`) when you need `this` to bind dynamically (e.g., object methods or event handlers).-- **Asynchronous Flow with `async/await`**: Use `async`/`await` for readable asynchronous code instead of heavy promise chains or callbacks. Always wrap with `try/catch` for error handling.-- **Fail Fast with Early Returns**: Return early from functions to keep code flat and avoid deep `if-else` nesting.-- **Use Ternary Statements for Conditional Variable Assignment**: Prefer standard `if/else` statements over side effects in a conditional ternary statement.(e.g., `condition ? doSomething() : doSomethingElse()`). Avoid nesting ternary operators, prefer `if-else` or switch statements.-- **Throw Error Objects**: Don't throw strings or other literals (e.g., `throw "CustomError"`). Instead throw an `Error` or a subclass of `Error`, (e.g., `throw new Error('CustomError')`).--```javascript-// ✅ GOOD: Readable async flow-async function fetchData(url) {- try {- const response = await fetch(url);- const data = await response.json();- return data;- } catch (error) {- console.error("Fetch failed:", error);- throw error; // Propagate or handle- }-}-```--### Async Patterns Decision Matrix--| Pattern | Best For | Error Behavior | Execution |-| :--- | :--- | :--- | :--- |-| **`async / await`** | Sequential dependencies | `try/catch` per call | Serial (One by one) |-| **`Promise.all()`** | Parallel tasks, all required | Fails fast (rejects on first error) | Parallel |-| **`Promise.allSettled()`** | Parallel tasks, independent | Never fails (returns status for all) | Parallel |--**Heuristic Rule**: Use `Promise.all()` when you need all results to proceed (e.g., initial data load). Use `Promise.allSettled()` when results are independent (e.g., batching multiple analytics pings).--## Objects, Classes, and Prototypes--- **Prefer Class Syntax**: Use modern `class` over legacy constructor functions and `prototype` manipulation.-- **Use `#` for Private Encapsulation**: Utilize the `#` prefix for internal fields and methods to expose only necessary surface area.-- **Super Calls First**: In subclass constructors, always call `super()` before accessing `this`.-- **Static Utilities**: Use `static` methods for utility functions or domain factories that do not need instance state.-- **Safe Property Checks**: Use `Object.hasOwn(obj, "prop")` instead of `obj.hasOwnProperty("prop")`.-- **Avoid Prototype Poisoning**: Use `Object.getPrototypeOf()` and `Object.setPrototypeOf()` instead of the legacy `__proto__`.-- **Use Getters and Setters**: Encapsulate custom logic, value validation and formatting using `get` and `set`.--```javascript-class UserService {- #privateToken; // Encapsulated-- constructor(token) {- this.#privateToken = token;- }-- set privateToken(token){- if(!validateToken(token)){- console.log('Invalid Token');- } else {- this.#privateToken = token;- }- }-- get hasValidToken(){- return validateToken(this.#privateToken)- }-- static fromConfig(config) { // Factory utility- return new UserService(config.token);- }-}-```--## Collections and Iteration--- **Prefer Array Literals**: Use `[]` over `new Array()`.-- **Iterate with `for...of`**: Use `for...of` for standard iterable collections. Use `for...in` sparingly and only for plain object properties (paired with `Object.hasOwn`).-- **Sets for Uniqueness**: Use `Set` when you require collections of unique values.-- **Maps for Complex Keys**: Use `Map` when keys are complex objects or when insertion order is critical.-- **Weak Collections for Memory Management**: Use `WeakMap` or `WeakSet` to associate temporary data with objects without preventing garbage collection.--### JS Collection Decision Matrix--| Requirement | Data Structure | Key Type | Order Preserved |-| :--- | :--- | :--- | :--- |-| **Unique values** | `Set` | Value itself | ✅ Yes |-| **Object-keyed pairs** | `Map` | Any (Objects/Primitives) | ✅ Yes |-| **Standard JSON pairs** | Object `{}` | String / Symbol | ❌ No |-| **Ordered lists** | Array `[]` | Integer Index | ✅ Yes |--**Heuristic Rule**: Use `Map` for dynamic dictionaries and lookup tables, `Set` for lists of unique items, and arrays for ordered lists of non-unique items.--## DOM Manipulation and Performance--- **Reduce Layout Thrashing (Reflows)**: Accessing geometric properties (`offsetHeight`, `clientWidth`) after a DOM write forces synchronous layout. Batch all DOM reads first, then all DOM writes.-- **Offload Heavy Tasks with Web Workers**: Do not block the main thread with heavy computation. Offload non-DOM work like data manipulation or image rendering to Web Workers.-- **Prevent Memory Leaks**: Remove event listeners when removing DOM elements, set detached DOM references to `null`, and clear timers to allow garbage collection. Use a shared AbortController signal to clean up multiple asynchronous events.-- **Share Observer Instances**: If there are many elements to observe with a `ResizeObserver` or `IntersectionObserver`, attach them to a single shared Observer instance rather than spawning one per item.-- **Disconnect Cleanup**: Always call `.unobserve(el)` or `.disconnect()` when elements or components unmount to prevent memory leaks.-- **Use `DocumentFragment` for Batch Appends**: When inserting many elements, append them first to an in-memory `DocumentFragment` before a single insertion into the live DOM tree.--```javascript-// Clean up multiple items with a shared AbortController.-const controller = new AbortController();-const signal = controller.signal;--// Use the same `signal` when setting up event listeners and fetches.-async function setup(){- button.addEventListener('click', ()=>{}, { signal })- const response = await fetch(url, { signal });-}-// Calling `abort()` cleans up all processes with a shared signal.-function tearDown(){- controller.abort();-}-```--```javascript-// ✅ Optimized Batch DOM Insertion-const list = document.getElementById('myList');-const fragment = document.createDocumentFragment();--for (let i = 0; i < 1000; i++) {- const li = document.createElement('li');- li.textContent = `Item ${i + 1}`;- fragment.appendChild(li); // Appended in-memory, no reflow-}-list.appendChild(fragment); // Single layout recalculation pass-```--## Modern Browser APIs--- **Prefer Modern Browser APIs over Third Party Libraries** - Use native APIs like `document.querySelectorAll()` over jQuery selectors, and `Object.groupBy()` over Lodash `groupBy()`.-- **Prefer HTML and CSS for UI over JavaScript** - Don't use JavaScript when a feature is possible without it, (e.g., `<details>` and `<summary>` for simple accordion components, Relative Color Syntax for color manipulation, `position:sticky` for sticky positioning, or native form validation).-- **Prefer HTML and CSS features over Observers**: Use `<img loading="lazy" />` or scroll driven animations over `IntersectionObserver`, and container queries over `ResizeObserver`.-- **Use JavaScript as a Progressive Enhancement**: Anticipate that JavaScript will not always be able to run, and ensure your site is functional without it.-- **Trigger Actions Using `addEventListener()`**: Don't use `on*` HTML attributes like `onclick`.-- **Avoid Extending CustomEvent**: Use native events like `TouchEvent` or `FocusEvent` when possible, or extend `Event`.-- **Avoid Recreating Native Elements**: Use `<button>` to trigger events, `<a>` to navigate, etc. Avoid replicating their behavior by adding event listeners to `<div>` or other generic elements. Do use JavaScript to add required dynamic ARIA, for instance `aria-expanded` or `aria-selected`.--## Security--- **Prevent DOM-XSS with Trusted Types**: Enforce Trusted Types in CSP to reject direct raw string assignments to dangerous sinks (like `innerHTML`). Use standard sanitization libraries like **DOMPurify** with `RETURN_TRUSTED_TYPE: true`.-- **Never Use Eval Utilities**: Avoid `eval()`, `setTimeout(string)`, or `new Function()`. Use `JSON.parse()` for parsing and standard functions for evaluation.--## Delivery--- **Use Import Maps**: Use `<script type="importmap">` to control how `import` statements resolve.-- **Preprocess Scripts to Reduce Filesize**: Use preprocessor tooling to minimize and tree shake the scripts delivered in production.diff --git a/skills/modern-web/guides/guides/modern-web.md b/skills/modern-web/guides/guides/modern-web.mddeleted file mode 100644index de9955c..0000000--- a/skills/modern-web/guides/guides/modern-web.md+++ /dev/null@@ -1,52 +0,0 @@-# 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/guides/performance.md b/skills/modern-web/guides/guides/performance.mddeleted file mode 100644index ded9ec2..0000000--- a/skills/modern-web/guides/guides/performance.md+++ /dev/null@@ -1,366 +0,0 @@-## 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/guides/webmcp.md b/skills/modern-web/guides/guides/webmcp.mddeleted file mode 100644index a9f7629..0000000--- a/skills/modern-web/guides/guides/webmcp.md+++ /dev/null@@ -1,44 +0,0 @@-# 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.diff --git a/skills/modern-web/guides/performance/batch-analytics-events.md b/skills/modern-web/guides/performance/batch-analytics-events.mddeleted file mode 100644index 7520f27..0000000--- a/skills/modern-web/guides/performance/batch-analytics-events.md+++ /dev/null@@ -1,152 +0,0 @@-# Debounce and batch multiple analytics events--Most analytics and telemetry data is low priority and you can safely defer sending it until the user leaves the page. The exception to this is if you need to deliver real-time updates, in which case timeliness matters.--The optimal way to provide real-time analytics updates, while still minimizing beacons, is to use `fetchLater()` with the `activateAfter` configuration option. This allows you to effectively debounce and batch all analytics events that occur within a given time window into a single beacon, that is reliably sent even if the user leaves the page before the timeout expires.--## How to implement--1. **Schedule the request:** As soon as any relevant analytics data is available, call `fetchLater()` with your data payload and pass an `activateAfter` value. This queues the data to be sent after that amount of time passes, or if the user leaves the page beforehand.--2. **Batch multiple events together:** If a new analytics event occurs before the `activateAfter` timeout expires, abort the previously scheduled request and call `fetchLater()` again (with the same `activateAfter` value) with the full event queue in a single payload.--3. **Reset the event queue when the timeout expires:** If a new analytics event occurs after the scheduled beacon has successfully sent (i.e. the `fetchLater()` result's `activated` value is `true`), reset the event queue.--3. **Let the browser handle the rest:** If the user navigates away or closes the tab before the `activateAfter` timeout expires, the browser will still reliably send the payload from your most recent `fetchLater()` call.--## Example code--This code tracks all `load` and `click` events on a page, and batches together all events that occur within a 10-second timeout.--```javascript-// Replace with your analytics endpoint.-const ANALYTICS_ENDPOINT = '/path/to/analytics/endpoint';--// Replace with a time window of your choice. All analytics events that-// occur within this time window will be batched together.-const BATCH_WINDOW = 10 * 1000;--// The maximum number of events to batch. Pick a number that is unlikely-// to overflow the fetchLater() quota for the page.-const MAX_QUEUE_SIZE = 100;--const eventQueue = [];-let fetchLaterResult;-let fetchLaterController;--function trackEvent(eventData) {- // If the previously queued beacon has already been sent, or if the- // max queue size has been met, reset the queue.- if (fetchLaterResult?.activated || eventQueue.length > MAX_QUEUE_SIZE) {- fetchLaterController = null;- fetchLaterResult = null;- eventQueue.length = 0;- }-- eventQueue.push(eventData);-- // Abort any pending beacons before creating a new one.- if (fetchLaterController) {- fetchLaterController.abort();- }- fetchLaterController = new AbortController();-- // Schedule a fetch for the events to be sent when the batch window expires.- // IMPORTANT: wrap the call in a try/catch to handle quota errors.- try {- fetchLaterResult = fetchLater(ANALYTICS_ENDPOINT, {- method: 'POST',- headers: {'content-type': 'application/json'},- body: JSON.stringify(eventQueue),- signal: fetchLaterController.signal,- activateAfter: BATCH_WINDOW,- });- } catch (error) {- // Handle errors as needed.- }-}--// Track page loads.-window.addEventListener('load', () => {- trackEvent({type: 'page_load'});-});--// Track click events.-window.addEventListener('click', (event) => {- trackEvent({type: 'click', target: serializeElement(event.target)});-});-```--## Best Practices--- **DO** use `fetchLater()` with the `activateAfter` option set to batch multiple analytics events that occur within close proximity of each other.-- **DO** use an `AbortController` to cancel the pending fetch in cases where a new analytics event occurs.-- **DO** check to ensure you do not batch too many events together and exceed the `fetchLater()` quota (currently roughly 64KB per origin).-- **DO** wrap calls to `fetchLater()` in a `try/catch` to handle quota errors.-- **DO** feature detect the presence of `fetchLater()` on `globalThis` and implement a fallback strategy for browsers that don't support the API.-- **DO NOT** use a `ReadableStream` object for the request body, as that will error.--## Browser support and fallback strategies--fetchLater has limited availability.. Therefore, a fallback strategy is typically required.--However, given the improved reliability and performance benefits of this API, `fetchLater()` should be used if the browser supports it.--### `fetchLater()` polyfill--Use the following minimal `fetchLater()` polyfill, which implements the API as closely as possible in unsupporting browsers.--The only notable behavior difference with this polyfill is instead of sending the payload when the user leaves the page, it sends it whenever the page's `visibilityState` changes to "hidden", since this is the most reliable end-of-session signal that's widely available today.--```js-globalThis.fetchLater ??= function fetchLater(url, init = {}) {- let timeoutHandle;- let activated = false;-- function sendNow() {- if (!(init.signal && init.signal.aborted)) {- // Use fetch keepalive if the browser supports it or if custom fetch- // parameters are specified (e.g. custom headers or methods).- // Otherwise fall back to `navigator.sendBeacon()`.- if (- 'keepalive' in Request.prototype ||- init.method !== 'POST' ||- init.headers- ) {- fetch(url, Object.assign({}, init, {keepalive: true}));- activated = true;- } else {- activated = navigator.sendBeacon(url, init.body);- }- }- destroy();- }-- function destroy() {- document.removeEventListener('visibilitychange', sendNow);- clearTimeout(timeoutHandle);- }-- if (document.visibilityState === 'hidden') {- // If the beacon was created while the page is already hidden, send data- // ASAP but wait until the next microtask to allow all sync code to run.- queueMicrotask(sendNow);- } else {- document.addEventListener('visibilitychange', sendNow);-- if (typeof init.activateAfter === 'number' && init.activateAfter >= 0) {- timeoutHandle = setTimeout(sendNow, init.activateAfter);- }- }-- if (init.signal) {- init.signal.addEventListener('abort', destroy);- }-- return {- get activated() {- return activated;- },- };-};-```diff --git a/skills/modern-web/guides/performance/break-up-long-tasks.md b/skills/modern-web/guides/performance/break-up-long-tasks.mddeleted file mode 100644index cb0aef0..0000000--- a/skills/modern-web/guides/performance/break-up-long-tasks.md+++ /dev/null@@ -1,58 +0,0 @@-Heavy computations or long loops can block the main thread, causing the page to become unresponsive. To prevent this, you should yield control back to the browser periodically. The `scheduler.yield()` API allows you to pause a long task and let the browser handle user input or rendering before continuing.--### Breaking up long tasks--Use `scheduler.yield()` inside async functions to break up work.--```javascript-async function processLargeArray(items) {- // DO: Set a time-based deadline 50 milliseconds into the future. 50- // milliseconds is the boundary for when a task becomes a long task.- let deadline = performance.now() + 50; // 50ms budget-- for (const item of items) {- // Process the item- processItem(item);-- // MANDATORY: Yield to the main thread periodically to keep the UI- // responsive. This can be done by checking if the deadline set earlier- // has been exceeded. When it has been, yield, then reset the deadline- // another 50 milliseconds into the future.- if (performance.now() >= deadline) {- await scheduler.yield();- deadline = performance.now() + 50;- }- }-}-```--### Fallback strategies--Scheduler API has limited availability.--Some browsers may not support the `scheduler` API. You MUST implement a fallback using `setTimeout` to ensure code executes without breaking.--#### Fallback for `scheduler.yield()`--```javascript-async function processLargeArrayWithFallback(items) {- // DO: Set a time-based deadline 50 milliseconds into the future.- let deadline = performance.now() + 50;-- for (const item of items) {- processItem(item);-- // MANDATORY: Yield to the main thread periodically to keep the UI responsive.- if (performance.now() >= deadline) {- // DO: Feature detect scheduler.yield- if ('scheduler' in window && 'yield' in window.scheduler) {- await scheduler.yield();- } else {- // DO: Fallback to setTimeout for older browsers- await new Promise(resolve => setTimeout(resolve, 0));- }- deadline = performance.now() + 50;- }- }-}-```diff --git a/skills/modern-web/guides/performance/calculate-total-foreground-time.md b/skills/modern-web/guides/performance/calculate-total-foreground-time.mddeleted file mode 100644index f5ad378..0000000--- a/skills/modern-web/guides/performance/calculate-total-foreground-time.md+++ /dev/null@@ -1,64 +0,0 @@-This guide details how to accurately calculate the total time a user spends actively viewing a page. Traditional metrics like time-on-page often incorrectly include time spent with the tab in the background. By using the `VisibilityStateEntry` API, you can measure only the "foreground time," providing a better metric of user engagement.--### Implementing foreground time calculation--The `PerformanceTimeline` API exposes visibility state changes as performance entries. Rather than reacting to `visibilitychange` events and manually accumulating time throughout a session, you can query the entire visibility history at any time.--MANDATORY: You must query the `visibility-state` performance entries to calculate the true foreground time.--```javascript-/**- * Calculates total time the page was in the visible state.- *- * @returns {number} Total foreground time in milliseconds.- */-function getTotalForegroundTime() {- // MANDATORY: Query the visibility-state entries from the performance timeline.- const entries = performance.getEntriesByType('visibility-state');-- // Fallback: If the browser does not support VisibilityStateEntry,- // the API will gracefully return an empty array.- if (entries.length === 0) {- // Return total time since navigation start as a fallback.- return performance.now();- }-- let totalForegroundTime = 0;-- for (let i = 0; i < entries.length; i++) {- // Only calculate duration for periods where the state was 'visible'- if (entries[i].name === 'visible') {- const start = entries[i].startTime;-- // The end time is the start time of the next state change,- // or the current time if this is the final entry.- const end = i + 1 < entries.length- ? entries[i + 1].startTime- : performance.now();-- totalForegroundTime += (end - start);- }- }-- return totalForegroundTime;-}-```--### Fallback strategies--Page visibility state has limited availability.--The `VisibilityStateEntry` API has limited availability and is currently unsupported in several major browsers.--Because `performance.getEntriesByType('visibility-state')` will return an empty array in browsers that do not support it, feature detection is straightforward and built directly into the execution flow. You must always check if the returned array is empty before attempting to calculate foreground time.--If it is empty, the recommended fallback strategy is to gracefully degrade to standard time-on-page analytics by returning `performance.now()`. This represents the total time elapsed since the page was loaded, ensuring a valid duration is still recorded without throwing runtime errors.--```javascript-const entries = performance.getEntriesByType('visibility-state');--// Empty array means unsupported-if (entries.length === 0) {- return performance.now(); // Fallback-}-```diff --git a/skills/modern-web/guides/performance/conditional-async-dependencies.md b/skills/modern-web/guides/performance/conditional-async-dependencies.mddeleted file mode 100644index 645a72c..0000000--- a/skills/modern-web/guides/performance/conditional-async-dependencies.md+++ /dev/null@@ -1,69 +0,0 @@-Top-level `await` allows modules to act as asynchronous functions, meaning they can pause module execution to await promises. This is extremely useful for conditionally loading async dependencies—like polyfills or heavy secondary libraries—only when required by the browser.--By utilizing top-level await, you can encapsulate the conditional loading logic inside a single module, effectively preventing downstream consumer modules from executing until the dependency is fully loaded and ready.--### Conditional polyfill pattern--While top-level `await` can be used to conditionally load any async dependency that's a module, a good use of the conditional depenency loading pattern is to conditionally load polyfills for browsers that don't support a specific feature. This approach encapsulates feature detection and the dynamic import inside a single dependency module.--In the following case, the `popover` attribute polyfill is conditionally loaded if it isn't present on `HTMLElement.prototype`:--```javascript-// conditionally-load-polyfill.js--// Check if the feature is missing before doing work.-// MANDATORY: Prefer checking HTMLElement.prototype over window or document-// when checking for a global DOM attribute or property like popover.-if (!('popover' in HTMLElement.prototype)) {- // Use top-level await to pause the execution of any module that imports this file- // until the polyfill finishes downloading and executing.- await import('/path/to/popover-polyfill.js');-}--// Export a marker if needed by your application-export const polyfillLoaded = true;-```--```javascript-// main.js--// MANDATORY: Because conditionally-load-polyfill.js uses top-level await,-// this import will block execution of main.js until the polyfill is ready.-import './conditionally-load-polyfill.js';--// Now it is safe to use the feature (e.g., showing a popover)-const myPopover = document.getElementById('my-popover');-if (myPopover) {- myPopover.showPopover();-}-```--### Avoiding the Safari top-level `await` bug--**MANDATORY:** You must structure your imports carefully to avoid a bug where top-level await doesn't behave as expected in Webkit, which occurs when multiple modules *simultaneously* import a module that contains a top-level `await`:--```javascript-// DO NOT do this: importing the top-level await module from multiple sibling modules-// simultaneously will crash in Safari.-//-// a.js: import './conditionally-load-polyfill.js';-// b.js: import './conditionally-load-polyfill.js';-// main.js: import './a.js'; import './b.js'; // CRASH!--// INSTEAD, guarantee a single entry point:-// Import the top-level await module ONCE at the very top of your application tree.-import './conditionally-load-polyfill.js';--// Then import the rest of your application code, ensuring the await resolves first.-import './app.js';-```--### Fallback strategies--Top-level await has limited availability.--Top-level `await` has been supported in all major browsers since 2021 (Chrome 89, Firefox 89, Safari 15). Because of this broad support, **you do not need to implement a fallback strategy for modern web applications.**--As long as you follow the guidance in the previous section to **avoid the Safari execution order bug**, you can safely rely on top-level `await` directly to manage your async dependencies.--You only need to avoid top-level `await` and fall back to standard asynchronous functions or dynamic `import()` orchestration if your application is explicitly required to support legacy browsers released before 2021.diff --git a/skills/modern-web/guides/performance/defer-rendering-heavy-content.md b/skills/modern-web/guides/performance/defer-rendering-heavy-content.mddeleted file mode 100644index 7680b1f..0000000--- a/skills/modern-web/guides/performance/defer-rendering-heavy-content.md+++ /dev/null@@ -1,146 +0,0 @@-# Defer rendering heavy content--Web pages with extensive content—such as infinite scrolls, complex dashboards, or dense articles can suffer from slow initial rendering and sluggish interactions. Modern web technologies allow you to defer the rendering workload for content that is not immediately visible, significantly boosting performance without breaking accessibility or user expectations.--To optimize rendering, you can utilize the CSS `content-visibility` property and the HTML `hidden="until-found"` attribute. While both aid performance, they serve distinct use cases.--## When to use which--| Scenario / Example | Feature Applied | Performance Benefit |-| :--- | :--- | :--- |-| **1. Below the fold** (Delay initial load) | **`content-visibility: auto`** | Browser automatically offloads layout/paint workload until the container scrolls close to view, keeping standard page load speed frictionless. |-| **2. Toggle State** (Fast view switching) | **`content-visibility: hidden`** | Skips layout calculations for hidden divs but preserves style containment state, allowing for instantaneous toggling without structural shifts (superior to `display: none`). |-| **3. Searchable & Deferred** (Collapsible specs/FAQ) | **`hidden="until-found"`** | Same benefits as previous, defers load-time rendering fully, but remains searchable via native Find-in-page. The browser automatically unhides and scrolls to the target on match. |--## How to implement `content-visibility: auto`--### Choosing off-screen content--**MANDATORY**: You MUST carefully identify which elements receive `content-visibility: auto`.-- **DO** target large, self-contained layout blocks that are strictly **below the initial fold** (e.g., card items in an infinite feed, trailing comments, or bottom-heavy layout sections).-- **DO NOT** apply this property to elements within the initial, above-the-fold viewport. Doing so forces the browser to evaluate visibility boundaries before rendering, which paradoxically delays critical page load performance.-- **DO** target elements with deep or complex internal DOM structures to maximize rendering cost savings.--### Implementation steps--1. **MANDATORY**: Identify heavy sections that are confirmed to be off-screen on initial load.-2. **MANDATORY**: Apply `content-visibility: auto` to each of these off-screen elements.-3. **MANDATORY**: Provide an estimated layout structure size using `contain-intrinsic-size` on each element.--### How to use `contain-intrinsic-size`--**MANDATORY**: You MUST pair `content-visibility: auto` with `contain-intrinsic-size`. Failure to do so forces the browser to collapse the element to a 0px height when off-screen, causing severe layout shifting and scrollbar jumping as the user scrolls.--The `contain-intrinsic-size` CSS shorthand property acts as a placeholder dimension. Using the `auto` keyword enables the browser to "remember" the exact size once the element is finally rendered, using that calculated size over the placeholder if the element goes off-screen again.--### Example code--```css-/* DO ONLY apply this class to items OUTSIDE the initial layout viewport */-.heavy-section-deferred {- /* MANDATORY: Skips rendering calculations when off-screen */- content-visibility: auto;-- /* Mandatory: Provide an estimated size to prevent layouts shifts.- - 'auto' is optional and enables the browser to remember the actual size- once rendered. It must be paired with a <length> value to be used for- the first render.- - 'none' tells the browser not to apply any intrinsic width to this element.- It can be used for either the height or the width value.- - '150px' is the estimated height of this element. This can be any valid- CSS <length> value.- */- contain-intrinsic-size: auto none auto 150px;-}-```--## How to implement `content-visibility: hidden`--1. **Identify heavy sections:** Locate layout blocks that are initially hidden (e.g., extra rows in a large data table).-2. **Apply CSS:** Add `content-visibility: hidden` to the element.-3. **Reveal the element:** When the element should be revealed, change the `content-visibility` property to `visible` or `auto`.--### Example code--```css-.cached-view {- /* Hides content but caches rendering state */- content-visibility: hidden;-}--.cached-view.is-active {- content-visibility: visible;-}-```--Because `content-visibility: hidden` excludes the element and its children from the accessibility tree and find-in-page search, **DO NOT** use it if the content must remain discoverable while hidden. For searchable hidden content, use `hidden="until-found"`.--## How to implement `hidden="until-found"`--The `hidden="until-found"` attribute forces the browser to apply an internal `content-visibility: hidden` rule. This hides content until a user utilizes "Find in page" or navigates via document fragments directly into the container.--1. **Identify heavy sections:** Locate layout blocks that are initially hidden (e.g., extra rows in a large data table).-2. **Apply the attribute:** Add `hidden="until-found"` directly onto the collapsible container element.-3. **Handle state synchronization:** If reveal states require DOM updates (such as toggling an aria-expanded attribute or rotating a chevron icon), use the `beforematch` event listener.--### Example code--```html-<div class="heavy-section" hidden="until-found">- <p>Heavy content.</p>-</div>-```--```javascript-// Optional: Handle state synchronization-const heavySection = document.querySelector('.heavy-section');--heavySection.addEventListener('beforematch', (event) => {- // Logic to execute immediately before the browser reveals the match-});-```--## Best Practices--- **DO** use `contain-intrinsic-size` with `content-visibility: auto`. Failure to do so forces height recalculations on scroll, causing viewport layout jumping or visual glitches.-- **DO NOT** apply `content-visibility: auto` to elements inside the initial fold viewport, as this delays critical page rendering.-- **DO NOT** apply standard `display: none` or `visibility: hidden` to elements designed to use `hidden="until-found"`, as this permanently excludes them from search discovery.-- **DO** verify that `hidden="until-found"` handles interactive states gracefully on trigger.--## Fallback strategies--### `content-visibility` fallback--Baseline status for content-visibility: Newly available. It's been Baseline since 2025-09-15.--When `content-visibility` is not supported it will be ignored by the browser. In most cases `content-visibility: auto` will not need a fallback, though without it performance gains will be lost. An unsupported browser will leave `content-visibility: hidden` elements completely visible. Use feature detection to implement a fallback.--```css-/* Default for everyone */-.inactive {- display: none;-}--/* Modern Browsers only */-@supports (content-visibility: hidden) {- .inactive {- display: block; /* Turn the layout box back on */- content-visibility: hidden;- }-}-```--### `hidden="until-found"` fallback--hidden="until-found" has limited availability.--When `hidden="until-found"` is not supported elements will remain hidden. Use feature detection targeting `onbeforematch` and extract or reveal content accordingly. Feature detection MUST check for the existence of `onbeforematch` in `HTMLElement.prototype`.--```javascript-if (!('onbeforematch' in HTMLElement.prototype)) {- document.querySelectorAll('[hidden="until-found"]').forEach(el => {- // Unsupported browsers show content to maintain searchability- el.removeAttribute('hidden');- });-}-```diff --git a/skills/modern-web/guides/performance/defer-work-until-scroll-ends.md b/skills/modern-web/guides/performance/defer-work-until-scroll-ends.mddeleted file mode 100644index 7a36789..0000000--- a/skills/modern-web/guides/performance/defer-work-until-scroll-ends.md+++ /dev/null@@ -1,77 +0,0 @@-# Defer Work Until Scroll Ends--Scrolling on the web should be smooth and responsive. Executing heavy tasks—such as layout recalculations, analytics data beacons tracking, or dynamic DOM updates—during scrolling can saturate the main thread, resulting in dropped frames and layout thrashing.--Historically, developers have relied on debouncing the `scroll` event using `setTimeout()` to guess when a scroll is finished. However, these debounced functions are notoriously unreliable. They may trigger while the user’s is still scrolling.--The `scrollend` event offers a highly reliable, performance-driven solution. The browser fires a `scrollend` event exactly when a scroll has rested, all transitions are finished, and a touch gesture has been released.--## How to Implement--To implement a defer-work pattern:--1. **Set Up a Scrollable Container**: Create a container with `overflow: auto` or `overflow: scroll`.-2. **Listen for `scroll` events**: Only use this listener for basic dynamic metrics or informative layout styling. Do not execute heavy work here.-3. **Listen for `scrollend` events**: Register a `scrollend` callback on the scroll container or the document itself.-4. **Execute Expensive work in the callback**: This is where it's safe to fetch dynamic content or trigger comprehensive DOM layouts.--## Example Code--```css-.scroll-container {- height: 300px;- overflow-y: auto;-}-```--```javascript-const scroller = document.querySelector('.scroll-container');--// 1. Informative feedback during scroll-scroller.addEventListener('scroll', () => {- // Avoid dynamic heavier data updates here- console.log('Scrolling dynamically... updates deferred');-});--// 2. Safe callback when scrolling rests-scroller.addEventListener('scrollend', () => {- // Run layout recalculations or analytical beacons updates here- const currentVisibleSection = findMostVisibleSection(scroller);- fetchAdditionalData(currentVisibleSection);-});-```--## Strategic Implementation & Best Practices--- **DO** use `scrollend` instead of debounced `scroll` events when firing layout data beacons or fetching new content content layout dynamically.-- **DO** consider pairing this with `scrollSnapChange` or `scrollSnapChanging` snap interactions if you're building carousels or testimonial galleries slides.-- **DO NOT** bundle layout-dependent dynamic updates inside dynamic visual scroll callbacks.-- **DO** consider that visual viewport zooming and scrolling triggers the `scrollend` event correctly.--## Fallback Strategy--Baseline status for scrollend: Newly available. It's been Baseline since 2025-12-12.--For unsupported browsers, fall back to a debounced `scroll` event with `setTimeout` to dispatch a custom `scrollend` event.--```javascript-function initializeDemo() {- const scroller = document.querySelector('#scroller');- scroller.addEventListener('scrollend', () => {- // Safe execution- });-}--if ('onscrollend' in window) {- initializeDemo();-} else {- initializeDemo();- const scroller = document.querySelector('#scroller');- scroller.addEventListener('scroll', () => {- clearTimeout(window.scrollendtimer);- window.scrollendtimer = setTimeout(() => {- scroller.dispatchEvent(new CustomEvent('scrollend'));- }, 100);- });-}-```diff --git a/skills/modern-web/guides/performance/deprioritize-background-fetches.md b/skills/modern-web/guides/performance/deprioritize-background-fetches.mddeleted file mode 100644index 91fdbd1..0000000--- a/skills/modern-web/guides/performance/deprioritize-background-fetches.md+++ /dev/null@@ -1,36 +0,0 @@-# Deprioritize background fetches--When a page performs multiple simultaneous network requests, they often compete for the same bandwidth. Non-critical data such as analytics, logging, or background synchronization should be deprioritized so that user-initiated or critical data fetches can complete more quickly.--## How to implement--1. **Identify background requests**: Determine which `fetch()` calls are for non-essential data that doesn't impact the immediate user experience.-2. **Apply fetch priority**: Add the `priority: 'low'` option to the `fetch()` initialization object.--## Example code--```javascript-// Use high priority (default) for critical UI updates-const criticalData = await fetch('/api/data');--// Explicitly deprioritize background analytics-fetch('/api/analytics', {- method: 'POST',- body: JSON.stringify(eventData),- // Lower the priority to prevent network contention- priority: 'low'-});-```--## Best practices--- **DO** use `priority: 'low'` for analytics, beacons, or telemetry data that isn't required for the current view.-- **DO** use `priority: 'low'` for "prefetching" data that the user *might* need later, ensuring it doesn't slow down what they need *now*.-- **DO NOT** use `priority: 'low'` for fetches that are critical to the user experience.-- **DO NOT** use the deprecated `importance` key in the fetch options object. The correct key is `priority`.--## Fallback strategy--Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.--The `priority` option in the Fetch API is a progressive enhancement. Browsers that do not support it will ignore the option and treat the request with default priority. No explicit feature detection or fallback logic is required for basic usage.diff --git a/skills/modern-web/guides/performance/detect-initial-visibility-state.md b/skills/modern-web/guides/performance/detect-initial-visibility-state.mddeleted file mode 100644index 2ff9e88..0000000--- a/skills/modern-web/guides/performance/detect-initial-visibility-state.md+++ /dev/null@@ -1,97 +0,0 @@-Determining if a page was initially loaded in the background (e.g., opened in a new background tab) is critical for accurate performance monitoring. Pages loaded in the background often have delayed rendering and longer metric times (like First Contentful Paint). Identifying these pages allows you to filter them out of performance analytics to avoid skewed data.--The most accurate way to measure this is by using the `VisibilityStateEntry` API, which reliably records visibility changes on the browser's performance timeline, regardless of when your script actually executes.--### Detecting initial visibility and background time--MANDATORY: Use `performance.getEntriesByType('visibility-state')` to access the exact visibility history. Do not rely solely on checking `document.visibilityState` at execution time, as it is susceptible to race conditions.--```javascript-/**- * Accurately determines visibility state history using the Performance API.- */-function getVisibilityInfo() {- // Retrieve VisibilityStateEntry members:- const entries = performance.getEntriesByType('visibility-state');-- if (entries.length > 0) {- const firstEntry = entries[0];-- // If the first performance entry for visibility is 'hidden',- // the page was loaded in the background.- const initiallyBackgrounded = firstEntry.name === 'hidden';-- // Find the precise, high-resolution timestamp of when the page- // was first backgrounded.- let timeBackgrounded = null;- for (const entry of entries) {- if (entry.name === 'hidden') {- // entry.startTime is used because it provides the exact browser- // timestamp of the visibility change, which is required for precision- timeBackgrounded = entry.startTime;- break;- }- }-- return {- initiallyBackgrounded,- timeBackgrounded- };- }-}-```--### Fallback strategies--Page visibility state has limited availability.--For unsupported environments, you may fall back to checking the `document.visibilityState` property or listening for the `visibilitychange` event.--**MANDATORY:** You must understand that this fallback approach is often **highly inaccurate for determining initial background state**. Because scripts can load and execute asynchronously, a page could be opened in a background tab and then foregrounded by the user *before* your script has finished downloading and executing. When your script finally runs, `document.visibilityState` will synchronously read as `'visible'`, and you will incorrectly assume the page was loaded in the foreground, completely missing its initial hidden state. Furthermore, the fallback timestamp lacks the internal precision of the Performance API. If precision is a high priority, do not use the fallback.--```javascript-/**- * Fallback implementation using document.visibilityState.- * This approach is prone to race conditions if the script loads asynchronously.- */-function getFallbackVisibilityInfo() {- // Check the state exactly when this script executes.- // This will fail to detect an initial background state if the user- // foregrounded the page before this script executed.- let initiallyBackgrounded = document.visibilityState === 'hidden';-- // If it's hidden now, we approximate that it was hidden from load (time 0).- let timeBackgrounded = initiallyBackgrounded ? 0 : null;-- // Listen for future visibility changes to capture if it is backgrounded later.- document.addEventListener('visibilitychange', () => {- if (document.visibilityState === 'hidden' && timeBackgrounded === null) {- // performance.now() is used here as a fallback, but it only gives- // us the time the event listener fired, not the precise internal- // browser time the visibility actually changed.- timeBackgrounded = performance.now();- }- });-- return {- get initiallyBackgrounded() { return initiallyBackgrounded; },- get timeBackgrounded() { return timeBackgrounded; }- };-}--// Modern implementation using VisibilityStateEntry API.-function getVisibilityInfo() {- // Code omitted here would be the same modern- // implementation shown earlier in this guide- // ...-}--// DO: Detect if the VisibilityStateEntry API is available-if ('VisibilityStateEntry' in window) {- // DO: If VisibilityStateEntry is available, use it first:- getVisibilityInfo();-} else {- // DO: If VisibilityStateEntry is unavailable, fall back to `document.visibilityState`:- getFallbackVisibilityInfo();-}-```diff --git a/skills/modern-web/guides/performance/efficient-background-processing.md b/skills/modern-web/guides/performance/efficient-background-processing.mddeleted file mode 100644index e23951b..0000000--- a/skills/modern-web/guides/performance/efficient-background-processing.md+++ /dev/null@@ -1,116 +0,0 @@-# Efficient Background Processing--Pause heavy background tasks when a component is not being rendered by the browser to conserve system resources and battery life.--## Overview--The `content-visibility: auto` property allows the browser to skip rendering calculations for elements that are far outside the viewport. When the browser decides to skip or resume rendering for an element, it fires the `contentvisibilityautostatechange` event on that element.--By listening to this event, you can pause expensive operations like `<canvas>` animations, WebGL rendering, or high-frequency WebSocket data polling when they are not needed, and resume them just-in-time when the browser prepares to display the content.--### `contentvisibilityautostatechange` vs. `IntersectionObserver`--It is important to understand when to use which API:--* **Use `IntersectionObserver` for application logic** tied to the exact visual visibility of an element in the viewport (e.g., lazy-loading data, infinite scroll triggers).-* **Use `contentvisibilityautostatechange` for rendering-heavy work** (like complex canvas updates or heavy DOM mutations). This event ties directly to the browser's internal rendering lifecycle. The browser often starts rendering an element before it actually appears on screen (the pre-render margin). This event tells you when that happens, ensuring your content is ready to be seen.--## Implementation--### 1. Apply CSS Content Visibility--Set `content-visibility: auto` on the heavy container and provide a placeholder size to prevent scrollbar jumping.--```css-.heavy-component {- /* Defer rendering work when off-screen */- content-visibility: auto;-- /* Mandatory: Provide a placeholder 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.- - '500px' is the estimated height of this element. This can be any valid- CSS <length> value. Replace it with the expected height of your- component.- */- contain-intrinsic-size: auto none auto 500px;-}-```--### 2. Listen for State Changes--Add an event listener for `contentvisibilityautostatechange` to pause or resume background tasks.--> **Important:** The `contentvisibilityautostatechange` event does not bubble in some browser implementations. To handle this event reliably, you must either:-> - Attach the event listener directly to the element that has `content-visibility: auto` applied.-> - Use a capturing event listener (`{ capture: true }`) if you are delegating events to a parent container.--```javascript-const component = document.querySelector('.heavy-component');--// Option 1: Direct listener (recommended)-component.addEventListener('contentvisibilityautostatechange', (event) => {- if (event.skipped) {- // The browser skipped rendering this content.- // DO NOT perform heavy mutations or animation loops here.- stopSimulation();- pauseWebSocketPolling();- } else {- // The browser is about to render the content.- // Resume your work so it is ready when visible.- startSimulation();- resumeWebSocketPolling();- }-});--// Option 2: Capturing listener for event delegation-document.addEventListener('contentvisibilityautostatechange', (event) => {- if (event.target.matches('.heavy-component')) {- if (event.skipped) {- stopSimulation();- } else {- startSimulation();- }- }-}, { capture: true });-```--### Fallback strategies--Baseline status for content-visibility: Newly available. It's been Baseline since 2025-09-15.--The `content-visibility` property and the associated `contentvisibilityautostatechange` event are progressive enhancements. In browsers that do not support them:-* The CSS property is ignored, and the content is rendered normally.-* The event never fires, so background tasks will continue to run as they normally would without optimization.--If you must support pausing tasks on older browsers, you can fallback to using `IntersectionObserver` as a rough approximation. This helps save battery and CPU on older devices too.--```javascript-// Fallback using IntersectionObserver for older browsers-const target = document.getElementById('target-container');--// Check if content-visibility is supported-const isSupported = 'contentVisibility' in document.documentElement.style;--if (!isSupported) {- const observer = new IntersectionObserver((entries) => {- entries.forEach(entry => {- if (entry.isIntersecting) {- // The element is close to the screen. Start work!- startSimulation();- } else {- // The element is far away. Pause work!- stopSimulation();- }- });- }, {- // Use rootMargin to start rendering before it hits the screen- rootMargin: '200px'- });-- observer.observe(target);-}-```diff --git a/skills/modern-web/guides/performance/faster-spa-view-transitions.md b/skills/modern-web/guides/performance/faster-spa-view-transitions.mddeleted file mode 100644index 51d650d..0000000--- a/skills/modern-web/guides/performance/faster-spa-view-transitions.md+++ /dev/null@@ -1,78 +0,0 @@-# Faster SPA View Transitions via State Caching--Enable instant navigation between views in a Single-Page Application (SPA) by caching the rendered state of inactive views instead of destroying them.--## Overview--Traditionally, when a user navigates between tabs or views in an SPA, developers either destroy the old view or hide it using `display: none`. Both approaches require the browser to recreate or recalculate the full layout and paint when the user returns to that view.--By using `content-visibility: hidden` on inactive views, the browser removes the element’s contents from the layout flow and stops painting it, but *retains* its cached rendering state in memory. When the user switches back, the view restores nearly instantly.--### The CPU vs. RAM Trade-off--While this approach offers massive performance benefits, it introduces a specific trade-off that you must manage carefully:--* **CPU Savings:** Massive. The browser completely skips layout and paint passes for hidden views.-* **RAM Cost:** High. The browser keeps all DOM nodes, event listeners, and state for the hidden view in memory.--#### When This Trade-off Becomes Dangerous--* **DO** use this strategy for simple applications with a small, predictable number of views (e.g., a 3-to-5 tabbed interface).-* **DO NOT** unconditionally cache every view in highly dynamic applications that generate dozens of unique reports or use infinite dynamic routes. Doing so will eventually cause severe memory bloat and may crash the browser on low-end devices.-* **MANDATORY:** If your application is highly dynamic, you MUST implement an **eviction strategy** (like a Least Recently Used cache) to destroy old views when a memory threshold is reached.--## Implementation--### 1. Configure View Containers--Set `content-visibility: hidden` on views that are not currently active.--> **Note:** The `content-visibility: hidden` property hides an element's *contents*, but the element itself remains styled and visible. Its background, borders, padding, and margins will still be painted by the browser.--```css-.spa-view.inactive {- /* MANDATORY: Use hidden to cache the rendering state of inactive views */- content-visibility: hidden;-- /* Optional: Prevent hidden views from taking up physical space in layout flow */- position: absolute;-}-```--### 2. Manage Focus--When swapping views, ensure you manage keyboard focus correctly to preserve accessibility.--```javascript-function switchToView(viewId) {- // Hide all views- document.querySelectorAll('.spa-view').forEach(view => {- view.classList.add('inactive');- view.setAttribute('aria-hidden', 'true');- });-- // Show the target view- const activeView = document.getElementById(viewId);- activeView.classList.remove('inactive');- activeView.setAttribute('aria-hidden', 'false');-- // MANDATORY: Move focus to the new view to ensure a logical tab-order- activeView.focus();-}-```--### Fallback strategies--Baseline status for content-visibility: Newly available. It's been Baseline since 2025-09-15.--The `content-visibility` property degrades gracefully. In browsers that do not support it:-* The property is ignored.-* To prevent fallback browsers from rendering all views simultaneously, you should provide a fallback to `display: none` in your CSS:--```css-@supports not (content-visibility: hidden) {- .spa-view.inactive {- display: none;- }-}-```diff --git a/skills/modern-web/guides/performance/full-session-analytics.md b/skills/modern-web/guides/performance/full-session-analytics.mddeleted file mode 100644index 02e270e..0000000--- a/skills/modern-web/guides/performance/full-session-analytics.md+++ /dev/null@@ -1,133 +0,0 @@-# Reliably measure full-session analytics and telemetry--To reliably analytics and telemetry data that covers the entirety of a user's visit to a web page (not just until page load) use the `fetchLater()` API.--The `fetchLater()` API is the most reliably way to send data to a server in cases where a response is not required and delivery timing is not urgent, which applies to data such as user analytics, telemetry, error tracking, and performance metrics like Core Web Vitals.--Older technique like creating an `<img>` pixel in an `unload` event listener are notoriously unreliably (especially on mobile) and can negatively impact performance (by making pages ineligible for bfcache).--## How to implement--1. **Schedule the request:** As soon as relevant data is available, call `fetchLater()` with your data payload. This queues the data to be sent later.--2. **Update the payload as needed:** If the user generates more data or the state changes, abort the previously scheduled request and call `fetchLater()` again with the fully updated snapshot.--3. **Let the browser handle the rest:** When the user navigates away or closes the tab, the browser will reliably send the payload from your most recent `fetchLater()` call.--## Example code--This code measures the session duration of a user's visit to a page using `fetchLater()` to queue a new beacon every 10 seconds with the updated session duration.--```javascript-const ANALYTICS_ENDPOINT = '/path/to/analytics/endpoint';--const sessionData = {- duration: 0,- id: crypto.randomUUID(),-};--let fetchLaterController = null;--function queueBeacon() {- // Abort any pending beacons before creating a new one.- if (fetchLaterController) {- fetchLaterController.abort();- }- fetchLaterController = new AbortController();-- // Update session duration to the current page time.- sessionData.duration = performance.now();-- // Schedule a fetch for the data payload to be sent later.- // IMPORTANT: wrap the call in a try/catch to handle quota errors.- try {- fetchLater(ANALYTICS_ENDPOINT, {- method: 'POST',- headers: {'content-type': 'application/json'},- body: JSON.stringify(sessionData),- signal: fetchLaterController.signal,- });- } catch (error) {- // Handle errors as needed.- }-}--// Update the session data and queue a new beacon every 10 seconds.-setInterval(queueBeacon, 10000);-```--## Best Practices--- **DO** use `fetchLater()` to send data to a server in any situation where a response is not necessary, and it's not critical that the data is sent immediately.-- **DO** use an `AbortController` to cancel the pending fetch in cases where the data may need to be updated before the user leaves the page-- **DO** minimum the payload size to avoid exceeding the quota (currently roughly 64KB per origin).-- **DO** wrap calls to `fetchLater()` in a `try/catch` to handle quota errors.-- **DO** feature detect the presence of `fetchLater()` on `globalThis` and implement a fallback strategy for browsers that don't support the API.-- **DO NOT** use a `ReadableStream` object for the request body, as that will error.--## Browser support and fallback strategies--fetchLater has limited availability.--A fallback strategy is required if `fetchLater()` doesn't meet your Baseline target. However, given the improved reliability and performance benefits of this API, `fetchLater()` should be used if the browser supports it.--The recommended fallback strategy is to use the polyfill below, which internally handles unsupporting browsers using `fetch()` with `keepalive` or `navigator.sendBeacon()`. Your own code MUST call `fetchLater()` directly — never call `fetch()`, `sendBeacon()`, or other beacon APIs yourself.--### `fetchLater()` polyfill--Use the following minimal `fetchLater()` polyfill, which implements the API as closely as possible in unsupporting browsers.--The only notable behavior difference with this polyfill is that it uses `visibilitychange` to detect when the user leaves, rather than relying on the browser's native unload handling. This is an internal implementation detail — your code does not need to listen for `visibilitychange` or any other page lifecycle events. Just call `fetchLater()` and the polyfill handles delivery.--```js-globalThis.fetchLater ??= function fetchLater(url, init = {}) {- let timeoutHandle;- let activated = false;-- function sendNow() {- if (!(init.signal && init.signal.aborted)) {- // Use fetch keepalive if the browser supports it or if custom fetch- // parameters are specified (e.g. custom headers or methods).- // Otherwise fall back to `navigator.sendBeacon()`.- if (- 'keepalive' in Request.prototype ||- init.method !== 'POST' ||- init.headers- ) {- fetch(url, Object.assign({}, init, {keepalive: true}));- activated = true;- } else {- activated = navigator.sendBeacon(url, init.body);- }- }- destroy();- }-- function destroy() {- document.removeEventListener('visibilitychange', sendNow);- clearTimeout(timeoutHandle);- }-- if (document.visibilityState === 'hidden') {- // If the beacon was created while the page is already hidden, send data- // ASAP but wait until the next microtask to allow all sync code to run.- queueMicrotask(sendNow);- } else {- document.addEventListener('visibilitychange', sendNow);-- if (typeof init.activateAfter === 'number' && init.activateAfter >= 0) {- timeoutHandle = setTimeout(sendNow, init.activateAfter);- }- }-- if (init.signal) {- init.signal.addEventListener('abort', destroy);- }-- return {- get activated() {- return activated;- },- };-};-```diff --git a/skills/modern-web/guides/performance/identify-heavy-scripts.md b/skills/modern-web/guides/performance/identify-heavy-scripts.mddeleted file mode 100644index 0377614..0000000--- a/skills/modern-web/guides/performance/identify-heavy-scripts.md+++ /dev/null@@ -1,67 +0,0 @@-# Identify heavy-running JavaScript--Heavy-running JavaScript can have a detrimental effect on both page load performance and interactivity. Modern web applications are more heavily reliant on JavaScript than ever before, from multiple sources. These include the application code itself (and the framework code it relies on), as well as third-party scripts that add functionality like chat widgets and video players. Behind-the-scenes analytics and marketing scripts are also common contributors that are all too easy to forget.--Identifying root causes of an unresponsive web page can be tricky with certain expertise required to run web performance tracing or profiling and how to interpret the results. Additionally field data is often very different to lab data, which only replicates a small subset of real user scenarios. This can make it difficult to identify the root causes of poor performance, especially for interactions.--The Long Animation Frames API is a lightweight API that can be used to identify heavy-running JavaScript in the field. A heavy-running script can be either a single long-running script, or a script that runs multiple times during the page lifecycle.--## How to implement--Long animation frames are monitored using the `PerformanceObserver` interface. It emits a `long-animation-frame` entry when an animation frame takes longer than 50ms to render. The entry contains information about the long animation frame, including the duration of the frame and the scripts that were executed during the frame.--The `long-animation-frame` entry contains a `scripts` property which is an array of `PerformanceScript` objects. Each `PerformanceScript` object contains information about the script that was executed during the long animation frame, including the `sourceURL` and `duration` of the script.--### Example of identifying the longest running scripts that contribute to long animation frames--```javascript-// Accumulate all script entries across the page lifecycle so no-// data is lost between observer callbacks.-const allScripts = [];--const observer = new PerformanceObserver(list => {- // Collect all script entries across frames to find the biggest offenders.- allScripts.push(...list.getEntries().flatMap(entry => entry.scripts));-- // Group by sourceURL so you can identify which scripts contribute- // the most total time, even if each individual invocation is short.- const scriptSource = [...new Set(allScripts.map(script => script.sourceURL))];- const scriptsBySource = scriptSource.map(sourceURL => ([sourceURL,- allScripts.filter(script => script.sourceURL === sourceURL)- ]));- const processedScripts = scriptsBySource.map(([sourceURL, scripts]) => ({- sourceURL,- count: scripts.length,- totalDuration: scripts.reduce((subtotal, script) => subtotal + script.duration, 0)- }));-- // Only include scripts above a certain threshold to reduce noise.- const heavyScripts = processedScripts.filter(script => {- return script.totalDuration > 100;- });-- // Sort by total duration so the worst offenders appear first,- // making it easier to prioritize optimization efforts.- heavyScripts.sort((a, b) => b.totalDuration - a.totalDuration);-- // Log to the console for local debugging. In production, replace- // this with a call to send the data to your analytics service.- console.table(heavyScripts);-});--// Use buffered: true to capture any long frames that occurred before-// this observer was registered.-observer.observe({type: 'long-animation-frame', buffered: true});-```--## Best Practices--- **DO** prefer the Long Animation Frames API over alternatives like the JS Self-Profiling API, which carries higher runtime overhead.-- **DO** summarize the key information as the Long Animation Frames API contains a lot of detail.-- **DO** send the required information to an analytics service in production.--## Browser support and fallback strategies--Long animation frames has limited availability..--The Long Animation Frames API is ignored by browsers that do not support it, so it can be safely used without fallbacks. In most cases the performance opportunities it identifies will apply to other browsers as well.diff --git a/skills/modern-web/guides/performance/identify-inp-causes.md b/skills/modern-web/guides/performance/identify-inp-causes.mddeleted file mode 100644index 0856d08..0000000--- a/skills/modern-web/guides/performance/identify-inp-causes.md+++ /dev/null@@ -1,70 +0,0 @@-# 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.--The Event Timing API allows for splitting the INP duration into three subparts: Input Delay (processing that is already happing when the interaction happens), Processing Duration (delays due as a direct result of the interaction), and Presentation Delay (delays that are due to rendering the next frame after the interaction). This helps identify if the issue is in other code, the interaction JavaScript code, or browser processing rendering updates respectively rather than jumping straight to the interaction code.--It is possible to gather further insights for JavaScript code delaying an interaction. 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 subparts and long animation frame data for the INP interaction.--## Get attributions for INP interactions using web-vitals library--The `web-vitals` library 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 INP subparts and 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 give the INP subparts:- inputDelay: metric.attribution.inputDelay,- presentationDelay: metric.attribution.presentationDelay,- processingDuration: metric.attribution.processingDuration,- interactionTarget: metric.attribution.interactionTarget,- // 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** use INP subparts initially to identify whether the delay is already running JavaScript (input delay), the event handlers JavaScript for the interaction (processing duration), or the subsequent rendering (presentation delay).-- **DO** attempt to identify the biggest blocking JavaScript as additional detail, particularly for input delay, and processing duration.-- **DO** prefer the Long Animation Frames API for providing this further detail 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 subparts and 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--Baseline status for Event timing: Newly available. It's been Baseline since 2025-12-12.--The Event Timing API is available in most modern browsers and is necessary to calculate INP and the INP subparts. For browsers that do not support this API INP cannot be measured.--Long animation frames has limited availability.--The Long Animation Frames API provides optional, additional details. It can be safely used without fallbacks. In most cases the performance opportunities it identifies will apply to other browsers as well.diff --git a/skills/modern-web/guides/performance/improve-next-page-load-performance.md b/skills/modern-web/guides/performance/improve-next-page-load-performance.mddeleted file mode 100644index 08ec9b3..0000000--- a/skills/modern-web/guides/performance/improve-next-page-load-performance.md+++ /dev/null@@ -1,119 +0,0 @@-# Improve next page load performance--One of the most effective ways to improve page load performance for users navigating a site is to initiate loading the next page they're about to visit *before* they visit it. This can be done through a technique called speculative loading using the Speculation Rules API.--## How it works--Speculative loading works by using JSON-based speculation rules to tell the browser about links that can be prefetched or prerendered improving page load performance when user clicks on them.--The rules can either be a hardcoded list of URLs a `urls` key (known as a list rule), or with a `where` key containing a set of href and CSS selectors used to find links on the page (known as a `document` rule).--Rules can also include an optional `eagerness` property that specifies when the page should be prefetched or prerendered. The `eagerness` property can be set to `immediate`, `eager`, `moderate`, or `conservative`. `immediate` speculates as soon as possible, while the others wait for user signals such as hovering for a short period, for a longer period, or starting to click on the page respectively.--Rules can be combined with different eagerness settings to prefetch eagerly and then prerender when the user interacts more.--## When to use it--Speculative loading is especially useful for static pages, where the content is not likely to change often, and where pages are cheaper to produce—especially if cached at the edge. It can also be used for dynamic pages, but it is important to be careful about the potential for stale content.--Speculative loading is typically used for same-origin links, though more advanced options allow for some cross-origin speculation. This guide concentrates on the more-common same-origin use case.--More eager speculative loading is a good choice for pages that are likely to be visited next, such as a headline article or the next page in a stepped process like a learning a course.--Less eager speculative loading is a good choice when it is less obvious what the user will do next, when there are many links on the page, each equally likely to be visited. By waiting for more signals, such as hovering, or starting to click on the page, you can get a head-start on the next page and improve the user experience, even if it is not fully prefetched or prerendered.--Similarly, prefetch is a more conservative choice than prerender, using less resources (on both the client and the server side) but providing less benefit to the user. It is a good choice for initial implementation, expanding to prerender later when the developer explicitly requests it.--## How to use it--Speculation rules have a JSON-based format and can be included in a `<script type="speculationrules">` tag. The rules can be included in the `<head>` or `<body>` of the document, or can be dynamically added using JavaScript.--A `tag` can also be used, either at a global level or on a per-rule basis. When set, this tag will be included in the `Sec-Speculation-Tags` header, and allows you to identify server-side which speculations were made.--### Example of a simple URL list rule for prefetching predefined URLs--```html-<script type="speculationrules">- {- "tag": "product-page-speculations",- "prefetch": [- {- "urls": ["/product/1", "/product/2", "/product/3"]- }- ]- }-</script>-```--### Example of a simple document rule for prerendering all same-origin links on a page--```html-<script type="speculationrules">- {- "tag": "all-links-speculations",- "prerender": [{- "where": { "href_matches": "/*" }- }]- }-</script>-```--### Example of a complex document rule for prerendering links with exclusions for interactive sites--```html-<script type="speculationrules">- {- "tag": "speculations-with-exclusions",- "prerender": [{- "where": {- "and": [- { "href_matches": "/*" },- { "not": {"href_matches": "/wp-admin"}},- { "not": {"href_matches": "/*\\?*(^|&)add-to-cart=*"}},- { "not": {"selector_matches": ".do-not-prerender"}},- { "not": {"selector_matches": "[rel~=nofollow]"}}- ]- }- }]- }-</script>-```--### Example of a mixed rule set--This example shows a rule set that prefetches all links eagerly, and then goes further than this to prerender those same links when it gets more signals with `moderate` eagerness.--```html-<script type="speculationrules">- {- "prefetch": [{- "tag": "prefetch-speculations",- "where": { "href_matches": "/*" },- "eagerness": "eager"- }],- "prerender": [{- "tag": "prerender-speculations",- "where": { "href_matches": "/*" },- "eagerness": "moderate"- }]- }-</script>-```--## Best Practices--- **DO** use speculation rules to prefetch and prerender pages that the user is likely to visit next.-- **DO** use speculation rules for static sites, where the content is not likely to change often, and where pages are cheaper to produce—especially if cached at the edge.-- **DO** take more care when using speculation rules for dynamic pages, where the content is more likely to change often, may become out of date, and where pages are more expensive to produce.-- **DO** prefer document rules over list rules, as they are more flexible, allow the same rule to be shared across multiple pages, and can be used to prefetch and prerender pages that are not known in advance.-- **DO** consider the trade-offs between prefetch and prerender, and choose the appropriate one for your use case. Prerender is more expensive than prefetch and can cause more unintended side effects in complex applications that display dynamic state, but provides a better user experience. Ask the developer for their preference if unsure.-- **DO** consider the trade-offs between the different `eagerness` levels, and choose the appropriate one for your use case. More eager speculation provides a better user experience but uses more resources and can cause more unintended side effects in complex applications that display dynamic state. Ask the developer for their preference if unsure.-- **DO NOT** overuse speculation rules, for example, to speculate every link on the page. Browsers have limits (2 speculations for non-eager speculations). `immediate` should only be used for a very small number of links.-- **DO NOT** speculate URLs that likely trigger state changes, like `/logout` or `/add-to-cart`, and explicitly exclude them from your speculation rules if they are likely to be included in document rules.-- **DO NOT** use speculation rules on Single Page Applications (SPAs). Speculation rules are designed for multi-page applications (MPAs) where the browser navigates to a new document on each navigation. In SPAs, the browser does not navigate to a new document on each navigation, so speculation rules will not work as expected.--## Browser support and fallback strategies--Speculative loading is a new feature, and as such, is not supported in all modern browsers (Baseline limited availability).--However, speculative loading is a progressive enhancement. It is perfectly safe to use as an enhancement, and is highly recommended given the potential performance benefits. If a browser does not support speculation rules, it will simply ignore them.diff --git a/skills/modern-web/guides/performance/interactions-in-complex-layouts.md b/skills/modern-web/guides/performance/interactions-in-complex-layouts.mddeleted file mode 100644index 804fdc4..0000000--- a/skills/modern-web/guides/performance/interactions-in-complex-layouts.md+++ /dev/null@@ -1,77 +0,0 @@-# Optimizing Interactions in Complex Layouts--Maintain high frame rates (60FPS) and eliminate interaction latency during drag-and-drop or heavy mutations in complex, multi-column layouts like Kanban boards or massive data grids.--## Overview--In complex layouts, performing a minor change to a single item—such as dragging a card or editing a cell—can trigger a chain reaction of style and layout calculations that forces the browser to reflow the entire page. This results in dropped frames and high Interaction to Next Paint (INP) latency.--By applying `content-visibility: auto` to self-contained layout regions (like columns in a Kanban board), you can isolate rendering work.--### Mechanism for On-Screen Elements--It is important to understand how `content-visibility: auto` benefits elements that are **already visible on the screen**:--* For visible elements, the browser **does not** skip rendering.-* Instead, the performance benefit comes entirely from the **CSS containments** that the property automatically enforces (i.e., layout, style, and paint).-* This containment acts as a boundary. If a mutation occurs inside a container with containment applied, the browser knows that the changes cannot affect the geometry or styles of elements outside that container. The page reflow is isolated, preventing a global layout recalculation.--## Implementation--### 1. Identify Containment Regions--Apply `content-visibility: auto` to large, self-contained containers that represent isolated layout units (e.g., grid columns, board lists).--```css-.board-column {- /* Apply containment boundaries */- content-visibility: auto;-- /* Mandatory: Provide a placeholder size to prevent layouts shifts.- For a vertical column, define a reasonable width and height.- - '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.- - '300px' is the estimated width of this element. This can be any valid- CSS <length> value. Replace it with the expected width of your- component.- - '800px' is the estimated height of this element. This can be any valid- CSS <length> value. Replace it with the expected height of your- component.- */- contain-intrinsic-size: auto 300px auto 800px;-}-```--### 2. Manage Interactions--Ensure that interactions occurring inside the column benefit from the containment.--```javascript-// Example: Drag and drop item movement-function moveItemToColumn(itemId, columnId) {- const item = document.getElementById(itemId);- const column = document.getElementById(columnId);-- // The browser will only reflow this specific column,- // not the entire board layout!- column.appendChild(item);-}-```--### Fallback strategies--Baseline status for content-visibility: Newly available. It's been Baseline since 2025-09-15.--The property degrades gracefully. In unsupported browsers:-* The property is ignored, and mutations will cause the standard global reflow.-* To achieve a similar isolation effect in older browsers, you can fall back to applying containment manually:--```css-@supports not (content-visibility: auto) {- .board-column {- /* Manual fallback for containment */- contain: layout style paint;- }-}-```diff --git a/skills/modern-web/guides/performance/optimize-image-priority.md b/skills/modern-web/guides/performance/optimize-image-priority.mddeleted file mode 100644index c390d28..0000000--- a/skills/modern-web/guides/performance/optimize-image-priority.md+++ /dev/null@@ -1,60 +0,0 @@-# Optimize image priority--Browsers use heuristics to assign loading priorities to images, but these defaults may not always align with your page's Largest Contentful Paint (LCP). Using `fetchpriority` on an `<img>` element allows you to explicitly signal an image's importance to the browser, ensuring critical images load faster while non-essential ones don't compete for bandwidth.--## How to implement--1. **Identify the LCP image**: Determine which image is the most likely candidate for the Largest Contentful Paint (usually the hero image at the top of the page).-2. **Elevate LCP priority**: Add `fetchpriority="high"` to the `<img>` element for the LCP candidate.-3. **Deprioritize non-critical images**: For images that are part of a secondary UI or are only revealed after user interaction (like mega menus, modals, or off-screen carousel slides), add `fetchpriority="low"`.-4. **Optimize lazy loading**: Never use `loading="lazy"` on the LCP image. For standard below-the-fold images, `loading="lazy"` is sufficient to defer the request until the user scrolls near them. Avoid adding `fetchpriority="low"` to these images, as you want them to load at normal priority once the user scrolls to them. Reserve `fetchpriority="low"` for images that are technically "above the fold" but not initially visible (e.g., hidden carousel slides or mega menus). For these hidden images, it is acceptable to use `loading="lazy"` as well; the browser will handle the request timing while respecting the low priority.-5. **Prefer default priorities**: If an image should have normal loading priority, omit the `fetchpriority` attribute entirely rather than setting it to `auto`. This is a stylistic convention to keep your HTML cleaner while relying on the browser's native heuristics.--## Example code--```html-<!-- Elevate priority for the LCP image -->-<img src="/images/hero-lcp.jpg"- alt="Main Banner"- fetchpriority="high"- width="800" height="400">--<!-- Deprioritize initially hidden images above the fold -->-<img src="/images/gallery-alt.jpg"- alt="Gallery Image"- fetchpriority="low"- width="400" height="300">--<!-- Deprioritize images revealed only after user interaction -->-<img src="/images/mega-menu-promo.jpg"- alt="Special Offer"- fetchpriority="low"- width="300" height="150">--<!-- Use lazy loading ALONE for standard below-the-fold images -->-<img src="/images/footer-logo.png"- alt="Footer Logo"- loading="lazy"- width="120" height="60">--<!-- Omit fetchpriority for images with standard priority -->-<img src="/images/standard-image.jpg"- alt="Standard Image"- width="400" height="300">-```--## Best practices--- **MANDATORY**: Always apply `fetchpriority="high"` to the LCP image.-- **MANDATORY**: Only use `fetchpriority="high"` on at most 1-2 critical images to avoid network contention and diluting the priority boost.-- **MANDATORY**: Use `fetchpriority="low"` for images that are technically "above the fold" but initially hidden (e.g., hidden carousel slides, mega menu images).-- **MANDATORY**: **Do not** use `fetchpriority="low"` on standard below-the-fold images that are already using `loading="lazy"`. These images should load at normal priority once they enter the viewport.-- **RECOMMENDED**: Avoid using `fetchpriority="auto"`. If you want the default priority, omit the attribute entirely to keep your HTML clean.-- **DO NOT** combine `fetchpriority="high"` with `loading="lazy"` for the LCP image.-- **DO NOT** use the deprecated `importance` attribute. It has been replaced by `fetchpriority` and is not supported by any browser.--## Fallback strategy--Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.--The `fetchpriority` attribute is a progressive enhancement for the `<img>` element. If a browser does not support it, the attribute is ignored, and the browser uses its default priority heuristics.diff --git a/skills/modern-web/guides/performance/optimize-preload-priority.md b/skills/modern-web/guides/performance/optimize-preload-priority.mddeleted file mode 100644index b7a86da..0000000--- a/skills/modern-web/guides/performance/optimize-preload-priority.md+++ /dev/null@@ -1,40 +0,0 @@-# Optimize preload priority--Preloading resources with `<link rel="preload">` signals to the browser that a resource will be needed soon. However, preloads inherit the default priority for the resource type and for images in particular this is low. Using `fetchpriority` allows you to refine this relative priority, in particular ensuring image preloads are preloaded with a high priority allowing them to start earlier and use get more bandwidth resources.--## How to implement--1. **Identify preload candidates**: Find resources that are not discovered early by the browser (e.g., video poster images or background images in CSS) but are essential for the page's appearance.-2. **Elevate critical image preloads**: For the LCP image or other critical images that are not prioritized by default, use `<link rel="preload" fetchpriority="high">` to ensure they are prioritized above other preloads. Note that fonts are already high priority by default.-3. **Deprioritize non-critical preloads**: For resources that aren't critical for the initial render (e.g., a background video or secondary fonts), use `<link rel="preload" fetchpriority="low">`.-4. **Coordinate with resource types**: Note that different `as` types have different default priorities; use `fetchpriority` to override these defaults when necessary.--## Example code--```html-<!-- Elevate priority for a video poster image that acts as the LCP candidate -->-<link rel="preload" href="/images/video-poster.jpg" as="image" fetchpriority="high">--<!-- Elevate priority for a critical LCP image that is hidden in CSS -->-<link rel="preload" href="/images/hero-background.jpg" as="image" fetchpriority="high">--<!-- Deprioritize a secondary font to avoid network contention -->-<link rel="preload" href="/fonts/secondary-font.woff2" as="font" type="font/woff2" fetchpriority="low" crossorigin>-```--## Best Practices--- **MANDATORY**: Only use `fetchpriority="high"` on at most 1-2 critical image preloads to avoid network contention and diluting the priority boost.-- **MANDATORY**: Use `fetchpriority="high"` on Largest Contentful Paint (LCP) images.-- **DO**: Limit the total number of preloads on a page to at most 2 images and 2-3 essential fonts to prevent bandwidth contention.-- **DO** use `fetchpriority="low"` for preloads that you want the browser to start early but not at the expense of critical resources (especially non-critical fonts).-- **DO** specify the `as` attribute correctly to ensure the preload will be used.-- **DO** prefer making critical resources (like LCP images) statically discoverable in HTML via `<img>` tags rather than relying on preloads for background images.-- **DO** ensure that font preloads always have the `crossorigin` attribute (even if same-origin).-- **DO NOT** use the deprecated `importance` attribute. It has been replaced by `fetchpriority`.--## Fallback strategy--Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.--The `fetchpriority` attribute on `<link rel="preload">` is a progressive enhancement. Browsers that do not support it will still preload the resource using their default priority for that resource type. To ensure compatibility, always provide correct `as` and `type` attributes.diff --git a/skills/modern-web/guides/performance/optimize-script-priority.md b/skills/modern-web/guides/performance/optimize-script-priority.mddeleted file mode 100644index 0db018d..0000000--- a/skills/modern-web/guides/performance/optimize-script-priority.md+++ /dev/null@@ -1,37 +0,0 @@-# Optimize script priority--Browsers assign default priorities to scripts based on where they appear in the document and whether they have attributes like `async` or `defer`. Using `fetchpriority` gives developers explicit control to ensure critical scripts load first, while non-essential scripts stay out of the way.--## How to implement--1. **Identify critical scripts**: Determine which scripts are essential for the page's core functionality or initial user interaction.-2. **Elevate critical async scripts**: For critical scripts loaded with `async` or `defer`, add the `fetchpriority="high"` attribute to ensure they are prioritized during the discovery phase.-3. **Deprioritize non-essential scripts**: For scripts that are not needed immediately (e.g., analytics, ads, or below-the-fold widgets), add `fetchpriority="low"` and ensure they have a `async`, `defer`, or `module` attribute to avoid blocking.-4. **Sequence parser-blocking scripts**: Use `fetchpriority="low"` on parser-blocking scripts at the end of the body to prevent them from contending for bandwidth with more critical resources.--## Example code--```html-<!-- Elevate the priority of the critical app logic -->-<script src="/js/app.js" async fetchpriority="high"></script>--<!-- Deprioritize non-essential tracking scripts -->-<script src="/js/tracker.js" async fetchpriority="low"></script>--<!-- Deprioritize late-body scripts to favor critical images or CSS -->-<script src="/js/legacy-widgets.js" fetchpriority="low"></script>-```--## Best Practices--- **MANDATORY**: Only use `fetchpriority="high"` on at most 1-2 critical scripts to avoid network contention and diluting the priority boost.-- **DO** use `fetchpriority="high"` specifically for `async` scripts that are known to be critical for Interaction to Next Paint (INP).-- **DO** deprioritize scripts that are not required for the initial user experience using `fetchpriority="low"`.-- **DO NOT** use `fetchpriority` on every script tag; it should only be used to change the browser's default heuristic when it is known to be sub-optimal.-- **DO NOT** use the deprecated `importance` attribute. It has been replaced by `fetchpriority`.--## Fallback strategy--Baseline status for Fetch priority: Newly available. It's been Baseline since 2024-10-29.--The `fetchpriority` attribute is a progressive enhancement. Browsers that do not support it will ignore the attribute and use their internal scheduling logic without error. No explicit feature detection or fallback logic is required for basic usage.diff --git a/skills/modern-web/guides/performance/resolution-optimized-pseudo-elements.md b/skills/modern-web/guides/performance/resolution-optimized-pseudo-elements.mddeleted file mode 100644index 636b751..0000000--- a/skills/modern-web/guides/performance/resolution-optimized-pseudo-elements.md+++ /dev/null@@ -1,46 +0,0 @@-Using resolution-optimized images in CSS pseudo-elements (like `::before` or `::after`) allows you to add decorative icons or structural graphics without cluttering your HTML with extra DOM nodes. By combining pseudo-elements with the `image-set()` CSS function, you can provide the browser with multiple formats (such as AVIF or WebP) and resolutions (like `1x` and `2x`). The browser will automatically choose the most optimal image for the user's device capabilities.--### Implementation--You can use the `image-set()` function directly within the `content` property of a pseudo-element, or within its `background-image` property (while setting `content: ""`). Note that while providing both the image format via `type()` and the resolution (like `1x` or `2x`) yields the best results, both of these arguments are optional.--```css-.icon-button::before {- /* Using image-set directly in the content property */- /* MANDATORY: Always order your formats from most optimized (AVIF) to least optimized (JPEG/PNG).- The browser will stop at the first supported format. */- content: image-set(- url("icon.avif") type("image/avif") 1x,- url("icon-2x.avif") type("image/avif") 2x,- url("icon.webp") type("image/webp") 1x,- url("icon-2x.webp") type("image/webp") 2x,- url("icon.png") type("image/png") 1x,- url("icon-2x.png") type("image/png") 2x- );-- display: inline-block;- margin-right: 8px;- vertical-align: middle;-}-```--### Fallback strategies--Baseline status for image-set(): Widely available. It's been Baseline since 2023-09-18.--For older browsers that do not support the `image-set()` function, you **MUST** provide a standard image declaration *before* the `image-set()` rule. This progressive enhancement strategy relies on CSS's cascading nature: unsupported rules are ignored.--```css-.icon-button::before {- /* MANDATORY: Fallback for browsers that do not support image-set() */- content: url("icon.png");-- /* Modern browsers will apply this and override the fallback */- content: image-set(- url("icon.avif") type("image/avif") 1x,- url("icon-2x.avif") type("image/avif") 2x,- url("icon.png") type("image/png") 1x,- url("icon-2x.png") type("image/png") 2x- );-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/performance/schedule-tasks-by-priority.md b/skills/modern-web/guides/performance/schedule-tasks-by-priority.mddeleted file mode 100644index e0be384..0000000--- a/skills/modern-web/guides/performance/schedule-tasks-by-priority.md+++ /dev/null@@ -1,57 +0,0 @@-When building complex web applications, tasks have different levels of urgency. Completing tasks for the current view is more important than sending analytics or prefetching assets. The Prioritized Task Scheduling API allows you to schedule work with specific priorities, ensuring the browser remains responsive to user input.--### Scheduling tasks by priority--Use `scheduler.postTask()` to schedule tasks with one of three priorities:-- `user-blocking`: Tasks that block user interaction (e.g., input handling, critical rendering).-- `user-visible`: Tasks visible to the user but not blocking (default).-- `background`: Tasks that are not time-critical (e.g., analytics, prefetching).--```javascript-// Schedule a high-priority task that blocks user interaction-scheduler.postTask(() => {- // DO: Handle critical updates that impact user interaction- handleCriticalUpdate();-}, { priority: 'user-blocking' });--// Schedule a default priority task-scheduler.postTask(() => {- // DO: Render non-critical content that is visible to the user- renderSecondaryContent();-}); // Defaults to 'user-visible'--// Schedule a low-priority background task-scheduler.postTask(() => {- // DO: Perform heavy background work that is not time-critical- sendAnalytics();-}, { priority: 'background' });-```--### Fallback strategies--Scheduler API has limited availability.--To support browsers that do not have the Prioritized Task Scheduling API, you must use a polyfill to maintain task prioritization.--```javascript-// Feature detect the scheduler API-if (!('scheduler' in window && 'postTask' in window.scheduler)) {- // DO: Conditionally load the polyfill for browsers that need it- const script = document.createElement('script');- script.src = 'https://unpkg.com/scheduler-polyfill';- script.onload = () => {- // Polyfill is loaded and ready to use- runScheduledTasks();- };- document.head.appendChild(script);-} else {- runScheduledTasks();-}--function runScheduledTasks() {- // Now safe to use scheduler.postTask in all browsers- scheduler.postTask(() => {- console.log('Task with priority support');- }, { priority: 'background' });-}-```diff --git a/skills/modern-web/guides/performance/sequence-distributed-events.md b/skills/modern-web/guides/performance/sequence-distributed-events.mddeleted file mode 100644index 1f4aa5f..0000000--- a/skills/modern-web/guides/performance/sequence-distributed-events.md+++ /dev/null@@ -1,74 +0,0 @@-# Sequencing Distributed Events--High-frequency tracing and event logging in distributed systems require precise timestamps to ensure correct causal ordering. Standard JavaScript `Date.now()` provides millisecond resolution, which can lead to timestamp collisions when multiple events occur within the same millisecond.--The `Temporal` API, specifically `Temporal.Instant`, provides nanosecond-resolution timestamps, enabling precise sequencing of events without collisions.--## How to Implement--To sequence high-frequency events using `Temporal`:--1. **Capture exact timestamps**: Use `Temporal.Now.instant()` to get the current exact time with nanosecond precision.-2. **Sort events chronologically**: Use `Temporal.Instant.compare(a, b)` to sort event objects. This method resolves ordering differences up to the nanosecond level.-3. **Calculate delays**: Use `Temporal.Instant.prototype.since(other)` to find the precise duration between events.-4. **Serialize for transmission**: Use `Temporal.Instant.prototype.toString()` to convert the timestamp to a standard ISO-8601 string for logging or network transmission.--## Example Code: High-Frequency Event Sequencing--```javascript-// 1. Capture timestamps for incoming events-function recordEvent(eventType, nodeId) {- return {- nodeId,- eventType,- timestamp: Temporal.Now.instant() // Nanosecond resolution- };-}--// 2. Sort events chronologically-function sequenceEvents(events) {- // Always use Temporal.Instant.compare for sorting instants- return [...events].sort((a, b) => Temporal.Instant.compare(a.timestamp, b.timestamp));-}--// 3. Calculate delays between events-function analyzeTelemetry(sortedEvents) {- for (let i = 1; i < sortedEvents.length; i++) {- const prev = sortedEvents[i - 1];- const curr = sortedEvents[i];-- // Calculate difference in nanoseconds- const duration = curr.timestamp.since(prev.timestamp);- const nsDiff = duration.total('nanoseconds');-- console.log(`Delay between Event ${prev.eventType} and Event ${curr.eventType}: ${nsDiff}ns`);- }-}-```--## Strategic Implementation & Best Practices--- **DO** use `Temporal.Now.instant()` for server-side tracing or client-side telemetry where millisecond precision is insufficient (e.g., microsecond profiling).-- **DO NOT** use `Date.now()` if you require stable sorting of events that happen back-to-back.-- **DO NOT** use `Temporal.Instant` for wall-clock time display unless you pair it with a time zone (use `Temporal.ZonedDateTime` for localized display).-- **DO** verify that the environment supports `Temporal` before using it natively or providing a fallback.--## Fallback strategies--Temporal has limited availability.--For environments without native support, use a standards-compliant polyfill such as `@js-temporal/polyfill`. Load it conditionally to avoid bloating the payload for modern clients. Note that `@js-temporal/polyfill` does not automatically install a global `Temporal` object, so you must explicitly assign it if you need it globally.--```javascript-(async () => {- // Check for native support- if (typeof Temporal === 'undefined') {- // Dynamically load polyfill using an ESM-compatible CDN- const module = await import('https://esm.sh/@js-temporal/polyfill');- // The polyfill does not auto-install globally, so we must assign it- globalThis.Temporal = module.Temporal;- }-- // Proceed with application logic-})();-```diff --git a/skills/modern-web/guides/user-experience/adapt-scrollbar-to-contrast-preferences.md b/skills/modern-web/guides/user-experience/adapt-scrollbar-to-contrast-preferences.mddeleted file mode 100644index 4954ade..0000000--- a/skills/modern-web/guides/user-experience/adapt-scrollbar-to-contrast-preferences.md+++ /dev/null@@ -1,73 +0,0 @@-# 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;- }-}-```--### Issues to be aware of when using scrollbar-color--- Do NOT animate or transition `scrollbar-color`. A [WebKit bug](https://bugs.webkit.org/show_bug.cgi?id=311752) causes the scrollbar to flicker every time `scrollbar-color` changes.-- 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.-- Even with `scrollbar-width` applied, macOS overlay scrollbars render the track (gutter) as transparent by default. If the 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.-- Even with `scrollbar-gutter: stable` the track may be transparent on MacOS. The thumb should not depend on the track color to be visible.--## Fallbacks & Browser Support--### Fallbacks & browser support for scrollbar-color--Baseline status for scrollbar-color: Newly available. It's been Baseline since 2025-12-12.--This feature is progressive enhancement and does not always require fallbacks.--If the styling is important and the user's Baseline target is "Baseline Widely Available" or earlier, you SHOULD include the non-standard `::-webkit-scrollbar` pseudo-elements as fallbacks.--Wrap legacy fallbacks in an `@supports not (scrollbar-color: auto)` block to prevent conflicts between standard properties and legacy WebKit selectors in browsers that support both natively.--If you are using custom properties to define colors, these will cascade to the legacy WebKit selectors automatically. You do NOT need to duplicate them.--```css-/* 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 {- background: var(--scrollbar-thumb);- }-- .scroller::-webkit-scrollbar-track {- background: var(--scrollbar-track);- }-}-```-diff --git a/skills/modern-web/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.md b/skills/modern-web/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.mddeleted file mode 100644index 4232a43..0000000--- a/skills/modern-web/guides/user-experience/adapt-scrollbar-to-light-dark-preferences.md+++ /dev/null@@ -1,111 +0,0 @@-# Adapt scrollbar colors 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.--When using `scrollbar-color`, use CSS variables to keep thumb and track colors separate, for readability and maintainability (especially when using fallbacks).--```css-.scroller {- --scrollbar-thumb: var(--color-neutral-70);- --scrollbar-track: var(--color-neutral-90);-- scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);-}-```--You can use either the `prefers-color-scheme` media query or the `light-dark()` function to define how these colors behave in light and dark mode. The latter will adapt to color-scheme overrides as well (local or global), but has narrower browser support.--Using `light-dark()`:--```css-/* DO: Define light mode colors as variables */-.scroller {- --scrollbar-thumb: light-dark(#bbb, #555555);- --scrollbar-track: light-dark(#f1f1f1, #222222);-- scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);- scrollbar-width: thin;- scrollbar-gutter: stable;-}-```--Using `prefers-color-scheme`:--```css-/* DO: Define light mode colors as variables */-.scroller {- --scrollbar-thumb: #bbb;- --scrollbar-track: #f1f1f1;-- scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);- scrollbar-width: thin;- scrollbar-gutter: stable;-}--/* DO: Override variables for dark mode */-@media (prefers-color-scheme: dark) {- .scroller {- --scrollbar-thumb: #555555;- --scrollbar-track: #222222;- }-}-```--### Issues to be aware of when using scrollbar-color--- Do NOT animate or transition `scrollbar-color`. A [WebKit bug](https://bugs.webkit.org/show_bug.cgi?id=311752) causes the scrollbar to flicker every time `scrollbar-color` changes.-- 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.-- Even with `scrollbar-width` applied, macOS overlay scrollbars render the track (gutter) as transparent by default. If the 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.-- Even with `scrollbar-gutter: stable` the track may be transparent on MacOS. The thumb should not depend on the track color to be visible.--## Fallbacks & Browser Support--### Fallbacks & browser support for scrollbar-color--Baseline status for scrollbar-color: Newly available. It's been Baseline since 2025-12-12.--This feature is progressive enhancement and does not always require fallbacks.--If the styling is important and the user's Baseline target is "Baseline Widely Available" or earlier, you SHOULD include the non-standard `::-webkit-scrollbar` pseudo-elements as fallbacks.--Wrap legacy fallbacks in an `@supports not (scrollbar-color: auto)` block to prevent conflicts between standard properties and legacy WebKit selectors in browsers that support both natively.--If you are using custom properties to define colors, these will cascade to the legacy WebKit selectors automatically. You do NOT need to duplicate them.--```css-/* 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 {- background: var(--scrollbar-thumb);- }-- .scroller::-webkit-scrollbar-track {- background: var(--scrollbar-track);- }-}-```--diff --git a/skills/modern-web/guides/user-experience/anchor-positioning-tab-underline.md b/skills/modern-web/guides/user-experience/anchor-positioning-tab-underline.mddeleted file mode 100644index 71f9a6e..0000000--- a/skills/modern-web/guides/user-experience/anchor-positioning-tab-underline.md+++ /dev/null@@ -1,81 +0,0 @@-In a tab menu, you should provide visual hints to users about what page they are on. One option is by underlining the tab. With anchor positioning, you can create a smooth animation between the positions of the underline. This does not work when changing the active tab loads a new web page.--You can also use this effect to add an animated dot to indicate the active tab in a vertical tab bar.--Create the underline using a `::before` pseudo-element on the `<ul>` that contains the `<li>` elements. **Using a pseudo-element is the preferred approach as it keeps the DOM clean and avoids adding extra elements for purely decorative effects.**--```css-ul::before {- /* Use a pseudo-element on the container to represent the animated indicator */- content: '';-}-```--Make the active list item an anchor by adding the `anchor-name` property, which has a value that starts with `--`.--```css-li.active {- /* Make a unique anchor-name for the active element. */- anchor-name: --active;-}-```--Tether the underline to the active item anchor with a `position-anchor` that matches the `anchor-name` on the anchor, and making it `position: absolute`.--```css-ul::before {- /* Tether the underline to the active element. */- position: absolute;- position-anchor: --active;-}-```--Position the underline relative to the anchor using the inset properties and `anchor()` functions.--```css-ul::before {- /* DO NOT use position-area, which can not be transitioned. */- /* Use calc() to offset the top slightly */- inset-block-start: calc(anchor(bottom) + .1lh);- inset-inline-start: anchor(left);- inset-inline-end: anchor(right);-}-```--Add a height and other visual styles.--```css-ul::before {- /* Apply your project's styles for the indicator */- block-size: .25lh;- background: red;-}-```--Finally, add a transition on the `inset` properties.--```css-ul::before {- @media (prefers-reduced-motion: no-preference) {- /* MANDATORY: The transition must be wrapped in a prefers-reduced-motion media query to respect user preferences. */- transition: inset .2s;- }-}-```--This is only a visual indicator, and must not be a replacement for setting the appropriate `aria-current="page"` or `aria-selected` aria values.--### Fallback strategies--Anchor positioning has limited availability.--If anchor positioning is not supported in the browser, use a `border-bottom` to add an underline. It will not be animated.--```css-ul li.active {- @supports not (position-anchor: auto) {- /* Choose a color appropriate to the app theme. */- border-bottom: .25lh var(--primary) solid;- }-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/animate-element-entry-exit.md b/skills/modern-web/guides/user-experience/animate-element-entry-exit.mddeleted file mode 100644index 719972f..0000000--- a/skills/modern-web/guides/user-experience/animate-element-entry-exit.md+++ /dev/null@@ -1,130 +0,0 @@-In the past, CSS transitions could not animate elements when they were first added to the DOM or when their `display` property changed from `none`. The `@starting-style` at-rule and `transition-behavior: allow-discrete` provide a declarative way to create smooth entry and exit animations.--## Implementation--### 1. Animating `display: none` Toggles--To animate an element when toggling its visibility via an attribute (e.g., `hidden` with `display: none`):--1. **Define the visible state**: Set the final property values (e.g., `opacity: 1`) on the base class.-2. **Define the entry starting state**: Use `@starting-style` to specify the values to transition *from* when the element becomes visible.-3. **Enable discrete transitions**: Include `display` in the `transition` property and use `transition-behavior: allow-discrete`.-4. **Define the exit state**: Set the target values in the `hidden` attribute.--```css-.card {- display: block;- opacity: 1;- translate: 0;- /* MANDATORY: Use transition-behavior: allow-discrete for display transition */- transition:- display 0.4s,- opacity 0.4s ease-out,- translate 0.4s ease-out;- transition-behavior: allow-discrete;-}--/* Entry animation: transition FROM these values when first rendered */-@starting-style {- .card {- opacity: 0;- translate: 0 -20px;- }-}--/* Exit animation: transition TO these values when hidden */-.card:where(.hidden, [hidden]) {- display: none;- opacity: 0;- translate: 0 -20px;-}--/* Respect user preference for reduced motion */-@media (prefers-reduced-motion: reduce) {- .card {- /* Disable movement and shorten duration for a simple fade */- translate: none;- transition-duration: 0.1s;- }-- @starting-style {- .card {- translate: none;- }- }-- .card:where(.hidden, [hidden]) {- translate: none;- }-}-```--### 2. Animating DOM Insertion and Removal--For elements added via `appendChild()` or removed via `remove()`:--- **Entry**: Use `@starting-style` as shown above. The browser will automatically detect the style change from "nothing" to the element's initial styles and trigger the transition from the `@starting-style` values.-- **Removal**: Since `element.remove()` is instantaneous and doesn't trigger a CSS transition on its own, you must trigger the exit transition first (e.g., by adding a class) and wait for it to finish before removing the node from the DOM.--```javascript-// Trigger exit transition-element.setAttribute('hidden', true);--// 2. Wait for all active transitions/animations to finish,-// with a failsafe timeout in case an animation never ends (e.g. for looping animations)-const animations = element.getAnimations();-if (animations.length > 0) {- await Promise.race([- // Promise.allSettled ensures we wait even if some animations fail- Promise.allSettled(animations.map(a => a.finished)),- new Promise(r => setTimeout(r, 2000))- ]);-}--// 3. Finally remove the node from the DOM-element.remove();-```--## Constraints & Accessibility--- **MANDATORY**: Use `transition-behavior: allow-discrete` when transitioning `display`. Without it, the element will instantly disappear during exit.-- **DO NOT** use `allow-discrete` in the `transition` shorthand — it will make older browsers ignore the entire `transition` declaration. Except in use cases where that is desirable, use a separate `transition-behavior: allow-discrete` declaration.-- **MANDATORY**: Use `@starting-style` for entry animations. Browsers skip transitions on an element's first style update (initial render or `display: none` change) unless this is provided.-- **DO**: Include `overlay` in the `transition` list if animating top-layer elements like `<dialog>` or `popover` to ensure they stay in the top layer during the exit animation.-- **DO**: Respect user preferences for reduced motion using the `prefers-reduced-motion` media query.-- **DO NOT**: Rely on `@starting-style` for exit animations; it only defines the *starting* point for an entry transition. Exit animations are defined by the transition to the hidden state.--## Fallback strategies--Baseline status for @starting-style: Newly available. It's been Baseline since 2024-08-06.--For browsers that do not support these features, elements will toggle `display: none` instantly. You can detect support in JavaScript using `CSS.supports()` to conditionally apply manual animation logic.--```javascript-// Detect support for discrete transitions and starting-style-const supportsModernTransitions =- window.CSS &&- CSS.supports('transition-behavior', 'allow-discrete');--if (!supportsModernTransitions) {- // Implement manual JS-based fallback for entry/exit-}-```--### Manual Entry Animation (JS Fallback)--```javascript-// To show:-el.style.display = '';-requestAnimationFrame(() => {- requestAnimationFrame(() => {- el.classList.remove('hidden');- });-});--// To hide:-el.setAttribute('hidden', true);-el.addEventListener('transitionend', () => {- if (el.classList.contains('hidden')) el.style.display = 'none';-}, { once: true });-```diff --git a/skills/modern-web/guides/user-experience/animate-to-from-top-layer.md b/skills/modern-web/guides/user-experience/animate-to-from-top-layer.mddeleted file mode 100644index 33c75c2..0000000--- a/skills/modern-web/guides/user-experience/animate-to-from-top-layer.md+++ /dev/null@@ -1,135 +0,0 @@-Elements that render in the "top layer" (like `<dialog>`, elements with the `popover` attribute, or tooltips) have historically been difficult to animate because they toggle between `display: none` and a visible state. Modern CSS provides `@starting-style`, `transition-behavior: allow-discrete`, and the `overlay` property to enable smooth entry and exit transitions for these elements. Note that native CSS nesting is used in the examples below.--## Implementation--### 1. Enable Discrete Transitions--To animate the `display` property, you must set `transition-behavior: allow-discrete`. This allows the element to remain visible during its exit transition. If using transition shorthands, be sure to place the `transition-behavior: allow-discrete` afterwards to prevent the shorthand from negating it.--### 2. The `overlay` Property--When an element moves in or out of the top layer, it must transition the `overlay` property. This ensures the element stays in the top layer for the duration of the animation, preventing it from being clipped by other elements or the viewport prematurely.--### 3. Entry Animations with `@starting-style`--Use the `@starting-style` at-rule to define the styles an element should transition *from* when it is first rendered or its `display` changes from `none`.--### 4. Animating the Backdrop--The `::backdrop` pseudo-element can be animated similarly by applying transitions to its own properties.--## Example--```css-/* 1. Define the visible (open) state */-dialog[open],-[popover]:popover-open {- opacity: 1;- transform: scale(1);-- /* 2. Define the starting state for entry (must come after open state) */- @starting-style {- opacity: 0;- transform: scale(0.9);- }-}--/* 3. Define the base (closed/exit) state and transitions */-dialog,-[popover] {- opacity: 0;- transform: scale(0.9);-- /* MANDATORY: transition display and overlay for top-layer elements */- transition-property: opacity, transform, display, overlay;- transition-duration: 0.3s;- transition-timing-function: ease-out;- /* Applies to discrete properties like display and overlay */- transition-behavior: allow-discrete; /* Note: be sure to write this after the shorthand */-}--/* 4. Animate the backdrop */-dialog::backdrop,-[popover]::backdrop {- background-color: rgba(0, 0, 0, 0);- /* The transition shorthand can also be used with allow-discrete */- transition:- display 0.3s allow-discrete,- overlay 0.3s allow-discrete,- background-color 0.3s ease-out;-}--dialog[open]::backdrop,-[popover]:popover-open::backdrop {- background-color: rgba(0, 0, 0, 0.5);-- @starting-style {- background-color: rgba(0, 0, 0, 0);- }-}--/* 5. Respect user preference for reduced motion */-@media (prefers-reduced-motion: reduce) {- dialog,- [popover] {- /* Disable movement and shorten duration for a simple fade */- transform: none;- transition-duration: 0.1s;- }-- @starting-style {- dialog[open],- [popover]:popover-open {- transform: none;- }- }-}-```--## Constraints & Accessibility--- **MANDATORY**: Include `overlay` in your `transition` list for any element moving into or out of the top layer.-- **MANDATORY**: Use `allow-discrete` for the `display` property transition.-- **MANDATORY**: Respect user preferences for reduced motion using `prefers-reduced-motion` by simplifying transitions (e.g., removing transforms and shortening duration).-- **DO**: Place the `@starting-style` block inside or after the "open" state selector to ensure proper cascading.-- **DO NOT**: Use `@starting-style` for exit animations; exit animations are defined by the transition to the base (closed) state.--## Fallback strategies--#### Top-layer animation features--Baseline status for @starting-style: Newly available. It's been Baseline since 2024-08-06.-Baseline status for transition-behavior: Newly available. It's been Baseline since 2024-08-06.-overlay has limited availability.--For browsers that do not support these features, top-layer elements will appear and disappear instantly. To provide animations in older browsers, you must use JavaScript to coordinate classes and wait for `transitionend` events or use the Web Animations API.--```javascript-// Feature detection for top-layer animations-const supportsTopLayerAnimation =- window.CSS &&- CSS.supports('transition-behavior', 'allow-discrete') &&- CSS.supports('overlay', 'auto');--if (!supportsTopLayerAnimation) {- // Manual JS fallback for entry/exit animations:- // 1. Add an `.is-opening` class for entry.- // 2. On close, add an `.is-closing` class, wait for the `transitionend` event, then call .close() or hide the popover.-}-```--#### popover--Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.--If the browser does not support Popover, use the `@oddbird/popover-polyfill`:--```html-<script type="module">- if (!HTMLElement.prototype.hasOwnProperty('popover')) {- await import('https://unpkg.com/@oddbird/popover-polyfill');- }-</script>-```--Alternatively, for legacy support without a polyfill, use `position: fixed` and manually calculate coordinates via JavaScript `getBoundingClientRect()`.diff --git a/skills/modern-web/guides/user-experience/animate-to-intrinsic-sizes.md b/skills/modern-web/guides/user-experience/animate-to-intrinsic-sizes.mddeleted file mode 100644index 243fc05..0000000--- a/skills/modern-web/guides/user-experience/animate-to-intrinsic-sizes.md+++ /dev/null@@ -1,97 +0,0 @@-# Animate to Intrinsic Sizes--Animating elements to dynamic sizes like `block-size: auto` or `inline-size: max-content` has historically required JavaScript or fragile "max-height" hacks. The `interpolate-size` property and `calc-size()` function allow the browser to natively interpolate between fixed lengths and intrinsic sizing keywords.--## Implementation steps--1. **Opt-in to keyword interpolation**: Apply `interpolate-size: allow-keywords` to a parent element (typically `:root`) to enable transitions for properties using intrinsic keywords.-2. **Define the transition**: Set a `transition` for the sizing property (e.g., `block-size`, `inline-size`) on the target element.-3. **Use intrinsic keywords**: Change the sizing property to a supported intrinsic keyword—`auto`, `min-content`, `max-content`, `fit-content`, or (for flex-basis) `content`—during an interaction (e.g., `:hover` or a state class).-4. **Perform calculations (Optional)**: Use `calc-size()` if you need to perform math on an intrinsic size (e.g., `auto + 2rem`). `calc-size()` also supports the `any` keyword for basis-agnostic calculations.--## Example: Generic Expansion Pattern--You can apply this pattern to any container (like a "Show More" section or a navigation menu) to transition between a restricted height and the element's natural size.--```css-/* Opt-in globally for all children */-:root {- /* MANDATORY: Transitions to intrinsic keywords are disabled by default for compatibility */- interpolate-size: allow-keywords;-}--.expandable-container {- /* 1. Define a fixed initial size (or 0) and hide overflow */- block-size: 100px;- overflow: hidden;-- /* 2. Transition the sizing property */- transition: block-size 0.4s ease-out;-}--.expandable-container.is-expanded {- /* 3. Smoothly animate to the intrinsic natural height */- block-size: auto;-}-```--## Example: Calculated Intrinsic Inline-Size--```css-.badge {- inline-size: 40px;- overflow: hidden;- white-space: nowrap;- transition: inline-size 0.3s ease;-}--.badge:hover {- /* calc-size(basis, calculation) */- /* 'size' refers to the evaluated basis (max-content in this case) */- inline-size: calc-size(max-content, size + 20px);-}-```--## Example: Transition from Intrinsic to Fixed--You can also animate in the opposite direction—starting from a natural size and collapsing to a specific length. This is useful for "dismissible" components.--```css-.collapsible-alert {- /* 1. Start with the natural content height */- block-size: auto;- overflow: hidden;- transition: block-size 0.5s ease-in-out, opacity 0.5s ease;-}--.collapsible-alert.is-dismissed {- /* 2. Smoothly collapse to zero */- block-size: 0;- opacity: 0;- pointer-events: none;-}-```--## Key constraints--* **Keyword-to-Keyword Restriction**: You cannot animate between two different keywords directly (e.g., from `min-content` to `max-content`). One end of the transition must be a fixed length or percentage (e.g., `0` to `auto`).-* **Calc-size Syntax**: Inside `calc-size()`, you cannot mix different intrinsic keywords in the same expression. The first argument (the basis) defines what `size` represents.-* **Opt-in Requirement**: Transitions to intrinsic keywords are disabled by default (`numeric-only`) to maintain backward compatibility. You must apply `interpolate-size: allow-keywords` to the element or an ancestor. `calc-size()` acts as a per-property override, automatically enabling interpolation whenever it is used.--## Fallback strategies--interpolate-size has limited availability.-calc-size() has limited availability.--`interpolate-size` and `calc-size()` are progressive enhancements. Browsers that do not support them will perform an instant jump to the target size.--* **Graceful Degradation**: For simple `block-size: auto` transitions, standard browsers will simply toggle the size instantly, which is functional but less polished.-* **Manual keyword fallbacks**: When using `calc-size()`, always provide a standard keyword fallback for older browsers, as they will discard the entire `calc-size()` declaration.--```css-.card {- block-size: auto; /* Fallback for older browsers */- block-size: calc-size(auto, size); /* Modern browsers use this */- transition: block-size 0.3s ease;-}-```diff --git a/skills/modern-web/guides/user-experience/browser-ui-color-theme.md b/skills/modern-web/guides/user-experience/browser-ui-color-theme.mddeleted file mode 100644index 1992041..0000000--- a/skills/modern-web/guides/user-experience/browser-ui-color-theme.md+++ /dev/null@@ -1,50 +0,0 @@-# Browser UI color theme--The `color-scheme` property indicates which color schemes (such as light or dark) your page supports. This informs the browser that it can automatically theme native UI elements—like scrollbars, form controls, and the default canvas background—to match your site's design and help minimize white flashes during initial loading.--## Implementation--### 1. Declare supported schemes in HTML-MANDATORY: To help prevent a "flash of un-themed content" (FOUC), place a `<meta>` tag in your `<head>` to ensure the browser knows which themes you support before it even starts rendering. While this `<meta>` tag helps to avoid FOUC by setting the initial canvas color early, it may not completely eliminate flashes in all browsers or loading conditions.--```html-<!-- MANDATORY: Declare support for both light and dark themes -->-<meta name="color-scheme" content="light dark">-```--### 2. Apply theme to CSS :root or html-MANDATORY: Apply the `color-scheme` property to the `html` element or the `:root` pseudo-class. Browsers specifically look to the root element to determine the theme for the entire viewport—including the root scrollbars and the initial "canvas" background. If applied only to the `body`, these global UI surfaces may remain in light mode because the `body` does not control the window's rendering context.--```css-/* MANDATORY: Apply to :root or html for viewport-wide theming */-:root {- /* MANDATORY: Automatically adapt native UI to user system preferences */- color-scheme: light dark;-}-```--### 3. Component-Specific Overrides-You can override the global theme for specific elements. This is useful for "dark mode" sections within a light-themed site (e.g., a dark sidebar or a code editor).--```css-.dark-sidebar {- /* Force this element and its children to use dark themed UI */- color-scheme: dark;- background-color: #111;- color: #eee;-}-```--## Best Practices-- **System Colors**: Use system color keywords like `Canvas` (background) and `CanvasText` (text) for your custom components when you want them to match the browser's native themed surfaces exactly. This is ideal for ensuring consistency between your content and the browser's UI (like scrollbars) while automatically respecting OS-level accessibility features like High Contrast mode.-- **Respect User Preference**: **MANDATORY**: Avoid forcing a single theme on the overall page. While specific components (like a code editor) may benefit from a fixed theme, the main application should respect the user's system preference and ideally provide a manual toggle to allow users to choose between light, dark, or system-default modes.-- **Forcing a Theme**: Use a single value like `color-scheme: dark` or `color-scheme: light` ONLY for specific sections of your site (like a code editor or a video player) that must remain in one theme. Avoid applying this to the root element unless it's the result of an explicit user selection via a theme toggle.-- **Opting out of Auto-Dark Mode**: Use `color-scheme: only light` to prevent browsers (particularly on mobile) from automatically inverting your colors if you haven't yet implemented a dedicated dark theme.--## Fallback strategies--Baseline status for color-scheme: Widely available. It's been Baseline since 2022-02-03.--- **Progressive Enhancement**: Browsers that do not support `color-scheme` will simply ignore the property and use their default light-mode UI.-- **Manual Dark Mode Styling**: For older browsers, continue to use `prefers-color-scheme` media queries to provide custom styles for your own components.-- **Custom Scrollbars**: If you need consistent scrollbar styling across all modern browsers, use the `scrollbar-color` property. For older WebKit-based browsers that do not support the standard property, continue to use the non-standard `::-webkit-scrollbar` pseudo-elements.diff --git a/skills/modern-web/guides/user-experience/calculate-event-differentials.md b/skills/modern-web/guides/user-experience/calculate-event-differentials.mddeleted file mode 100644index 7530e94..0000000--- a/skills/modern-web/guides/user-experience/calculate-event-differentials.md+++ /dev/null@@ -1,83 +0,0 @@-# Calculating Event Differentials with Temporal--Calculating the time elapsed between events (such as trial expirations, subscription durations, or prorated costs) has historically been difficult with the legacy `Date` object due to complexities with time zones, daylight saving time (DST), and inconsistent parsing.--The `Temporal` API provides a modern, robust solution for date and time arithmetic. Specifically, `Temporal.ZonedDateTime` and `Temporal.Duration` enable exact, DST-safe calculations of time differences.--## How to Implement--To calculate differentials between two events:--1. **Obtain ZonedDateTime objects**: Convert your inputs (dates and times) into `Temporal.ZonedDateTime` objects. This ensures calculations are time-zone aware.-2. **Calculate active time with `.since()`**: Use `currentZonedDateTime.since(startZonedDateTime)` to find the time elapsed since a start event.-3. **Calculate remaining time with `.until()`**: Use `currentZonedDateTime.until(endZonedDateTime)` to find the time remaining until a future event.-4. **Control precision with options**: Use `largestUnit`, `smallestUnit`, and `roundingMode` to control how the resulting duration is balanced and rounded.--### Example: Trial Expiration Calculation--```javascript-// 1. Get current time point in the system time zone-const now = Temporal.Now.zonedDateTimeISO();-const tz = now.timeZoneId;--// 2. Parse inputs (assuming ISO strings from form inputs)-const startDateStr = "2025-01-01";-const startTimeStr = "12:00:00";-const endDateStr = "2025-01-31";-const endTimeStr = "12:00:00";--const startDate = Temporal.PlainDate.from(startDateStr);-const startTime = Temporal.PlainTime.from(startTimeStr);-const start = startDate.toPlainDateTime(startTime).toZonedDateTime(tz);--const endDate = Temporal.PlainDate.from(endDateStr);-const endTime = Temporal.PlainTime.from(endTimeStr);-const end = endDate.toPlainDateTime(endTime).toZonedDateTime(tz);--// 3. Calculate difference using .since() and .until()-// By default, units larger than hours might not wrap automatically.-// Use largestUnit to ensure differences are expressed in larger units if applicable.-const timeActive = now.since(start, { largestUnit: 'year' });-const timeRemaining = now.until(end, { largestUnit: 'year' });--console.log(`Active: ${timeActive.days} days, ${timeActive.hours} hours`);-console.log(`Remaining: ${timeRemaining.days} days, ${timeRemaining.hours} hours`);--// 4. Compare dates-const isExpired = Temporal.ZonedDateTime.compare(now, end) > 0;-if (isExpired) {- console.log("Subscription is expired.");-}-```--## Strategic Implementation & Best Practices--- **DO** use `Temporal.ZonedDateTime` for calculations involving real-world events that occur in specific time zones (like subscription renewals or event scheduling).-- **DO** use `largestUnit` to specify the largest unit you want in the result (e.g., `'year'` or `'month'`). If you omit it, it defaults to `'auto'` which might not always sum up to years/months as expected for human-readable durations.-- **DO** use `.since()` when calculating time elapsed *since* a past event (e.g., `now.since(start)`), and `.until()` for time remaining *until* a future event (e.g., `now.until(end)`).-- **DO NOT** modify instances directly; `Temporal` objects are **immutable**. Operations like `add()`, `subtract()`, or `with()` return a *new* instance.-- **DO** use `Temporal.ZonedDateTime.compare` to check if one time point is after another. It returns `1` if the first is after the second, `-1` if before, and `0` if equal.--## Fallback Strategy--### Fallbacks & browser support for Temporal--Temporal has limited availability.--For browsers that do not yet support the native `Temporal` API, use feature detection and a polyfill. The standard reference polyfill is `@js-temporal/polyfill`.--Note that the polyfill does not automatically assign the `Temporal` object to the global scope to avoid conflicts. You must manually assign it if your code relies on the global `Temporal` object.--```javascript-// Check if Temporal is supported natively-(async () => {- if (typeof Temporal === 'undefined') {- // Load the polyfill conditionally- const module = await import("https://esm.sh/@js-temporal/polyfill");- globalThis.Temporal = module.Temporal;- // Extend Date.prototype if needed- Date.prototype.toTemporalInstant = module.toTemporalInstant;- initializeApp();- }-})();-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/calculate-with-intrinsic-sizes.md b/skills/modern-web/guides/user-experience/calculate-with-intrinsic-sizes.mddeleted file mode 100644index 72a47f9..0000000--- a/skills/modern-web/guides/user-experience/calculate-with-intrinsic-sizes.md+++ /dev/null@@ -1,192 +0,0 @@-`calc-size()` is a CSS function for performing mathematical operations on intrinsic sizing keywords like `auto`, `min-content`, and `fit-content`. **MANDATORY**: Use `calc-size()` only when you need to modify an intrinsic size with a calculation or constraint; for simple keyword-based animations (e.g., `0` to `auto`), you must use `interpolate-size: allow-keywords`.--## Implementation Steps--1. **Identify the Intrinsic Basis**: Determine which intrinsic keyword (`auto`, `min-content`, etc.) should form the base of your calculation.-2. **Define Constraints**: Use CSS math functions like `clamp()`, `min()`, or `max()` within the second argument to enforce design constraints on the intrinsic size.-3. **MANDATORY: Provide a Fallback**: Always declare a standard sizing keyword or length immediately before the property using `calc-size()` to ensure the layout remains functional in unsupported browsers.-4. **Apply Logical Properties**: Default to using logical properties like `inline-size` or `block-size` to ensure the calculations respect the document's writing mode.-5. **Optional: Progressive Enhancement**: Wrap complex layout logic or animations in a `@supports (inline-size: calc-size(auto, size + 0px))` block to deliver advanced features only to capable browsers.--## Basic Syntax--```css-/* calc-size(<calc-size-basis>, <calc-sum>) — mathematical operations on intrinsic sizing keywords */-.element {- /* MANDATORY: Always provide a fallback for browsers that do not support calc-size() */- inline-size: min-content;-- /* DO: Use calc-size to modify an intrinsic basis with a calculation or function */- inline-size: calc-size(min-content, size + 2rem);-}-```--### Valid Basis Arguments (`<calc-size-basis>`)-The first argument defines the "base" size for the calculation.--**Standard Keywords:**-- `auto`: The default sizing for the element.-- `min-content`: The smallest size the element can take without overflowing.-- `max-content`: The size the element takes to fit all content on one line.-- `fit-content`: Equivalent to `clamp(min-content, auto, max-content)`.-- `content`: Only valid when `calc-size()` is used within the `flex-basis` property.--**Special Arguments:**-- `any`: A generic basis used when the specific intrinsic type is unknown or when nesting calculations.-- Nested `calc-size()`: Allows for multi-step or conditional calculations.-- `<calc-sum>`: A specific length, percentage, or mathematical expression (e.g., `100px` or `20%`). When a fixed value is used as the basis, the **`size` keyword is still available** (but only within the second argument) and represents the resolved value of that basis.--**MANDATORY**: The `size` keyword is **not valid** within the first argument (`<calc-size-basis>`) itself. It is a local variable that only exists to refer back to the basis from within the second argument (`<calc-sum>`).--### Valid Calculation Arguments (`<calc-sum>`)-The second argument is the mathematical expression.-- It typically uses the `size` keyword to refer to the value of the basis.-- While the `size` keyword is technically optional, omitting it means the calculation will resolve to a fixed value, ignoring the basis entirely.-- It can include standard math operators (`+`, `-`, `*`, `/`).-- It can include CSS math functions like `clamp()`, `min()`, `max()`, and `round()`.-- **MANDATORY**: `calc-size()` only allows a **single** intrinsic size value (the basis) in each calculation. You cannot mix intrinsic sizing keywords in the same `calc-size()` call.--## Use Cases--### Animating to and from Intrinsic Sizes-By default, browsers cannot interpolate between a length (e.g., `0px`) and an intrinsic keyword (e.g., `auto`). Wrapping the keyword in `calc-size()` makes it an interpolatable value.--#### Choosing the Right Tool for Animations-- **MANDATORY: Use `interpolate-size: allow-keywords`**: For simple animations to or from intrinsic sizes (e.g., `height: 0` to `height: auto`) without any mathematical modifications. This is the required approach for simple keyword interpolation and should ideally be applied globally via `:root`.-- ```css- :root {- /* Best practice: Enable keyword interpolation globally */- interpolate-size: allow-keywords;- }-- .item {- height: 0;- transition: height 0.3s ease;- }-- .item.open {- /* Simple interpolation from 0 to auto now works without calc-size() */- height: auto;- }- ```--- **Use `calc-size()`**: ONLY when you need to perform mathematical calculations on an intrinsic size during a transition (e.g., adding padding or clamping the size).--```css-.accordion-content {- display: block;- overflow: hidden;- /* MANDATORY: Fallback value for closed state */- block-size: 0;- transition: block-size 0.3s ease-out;-}--.accordion-content.open {- /* MANDATORY: Fallback value for open state */- block-size: auto;-- /*- DO: Use calc-size(auto, ...) to enable animation from 0 to the element's- intrinsic size while doing a calculation (in this case, adding a space of 2rem).- */- block-size: calc-size(auto, size + 2rem);-}-```--**MANDATORY**: Interpolation between two intrinsic sizing keywords is not possible directly. One end of the transition must be a length or a percentage.--#### Respecting User Motion Preferences-Animations that change the size of large layout areas can be particularly disruptive for users with vestibular disorders. **MANDATORY**: Always respect user motion preferences by using the `prefers-reduced-motion` media query to simplify or minimize non-essential animations. Common strategies include disabling motion entirely, reducing duration, or replacing layout shifts with subtle opacity transitions.--```css-.accordion-content {- opacity: 0;- transition: block-size 0.3s ease, opacity 0.3s ease;-}--.accordion-content.open {- opacity: 1;-}--@media (prefers-reduced-motion: reduce) {- .accordion-content {- /*- EXAMPLE: Replacing disruptive layout animations with a subtle fade-in.- Setting the block-size instantly and transitioning opacity- provides a clear state change without large-scale motion.- */- transition: opacity 1.5s ease;- }-- .accordion-content.open {- /* Jump the size instantly */- block-size: auto;- }-}-```---### Applying Constraints to Intrinsic Sizes-You can use `calc-size()` with any CSS math function—such as `min()`, `max()`, `clamp()`, or `round()`—to ensure an element's intrinsic size remains within design boundaries.--```css-.dynamic-container {- /* MANDATORY: Always provide a fallback for browsers that do not support calc-size() */- inline-size: fit-content;-- /*- DO: Establish a dynamic size based on content, while:- 1. Enforcing boundaries using CSS math functions (min, clamp, etc.)- 2. Modifying the intrinsic size with fixed or relative offsets- */- inline-size: calc-size(fit-content, min(size + var(--extra-space), var(--max-allowed)));-}-```--## Critical Considerations--- **Percentage Pitfalls**: Percentages inside the `<calc-sum>` are resolved against the **container's size**, not the `size` keyword. For example, `calc-size(auto, size + 10%)` adds 10% of the *parent's* width to the element's `auto` width, which may lead to unexpected results or overflows.-- **Calculations requirement**: **MANDATORY**: Use `interpolate-size: allow-keywords` instead of `calc-size()` for simple animations (e.g., `0` to `auto`). `calc-size()` should only be used when the layout requires dynamic mathematical adjustments to the intrinsic base.-- **Performance Note**: Animating box model properties like `inline-size` or `block-size` triggers layout recalculations, which can be expensive. Use `calc-size()` animations primarily for layout-critical elements where non-layout alternatives are insufficient.--## Fallback strategies--calc-size() has limited availability.-interpolate-size has limited availability.--`calc-size()` and `interpolate-size` are **progressive enhancements**. In browsers that do not support them, the properties will be ignored and the layout will remain functional, though animations to intrinsic keywords will jump instead of transitioning. Always provide a standard keyword or length as a fallback.--```css-.element {- /* Fallback for browsers that don't support calc-size() */- inline-size: fit-content;- /* Modern browsers will override the fallback */- inline-size: calc-size(fit-content, size + 2rem);-}-```--### Animation and Transition Fallbacks-In browsers without support for `calc-size()` or `interpolate-size`, transitions involving intrinsic sizing keywords will fail to interpolate.--- **Graceful Degradation**: The default fallback is an "instant jump" between states (e.g., from `0` to `auto`). This is often acceptable as the layout remains functional.-- **Enhanced Experience**: Use `@supports` to apply complex layout logic or additional styling that only makes sense when smooth intrinsic animations are possible.-- **Avoid JS-based measurements**: While you could use JavaScript to measure elements and manually animate their dimensions, this is often unnecessary and can lead to layout thrashing. Relying on the native "instant jump" is the recommended fallback for modern web applications.--For animations, the fallback experience will be an instant jump to the final size. To detect support in CSS or JavaScript:--```css-/* CSS Feature Detection */-@supports (inline-size: calc-size(auto, size + 0px)) {- .element {- /* Apply advanced logic only when supported */- }-}-```--```javascript-/* JavaScript Feature Detection */-if (CSS.supports('inline-size', 'calc-size(auto, size + 0px)')) {- // Apply advanced sizing or animations-}-```diff --git a/skills/modern-web/guides/user-experience/capture-location-agnostic-data.md b/skills/modern-web/guides/user-experience/capture-location-agnostic-data.mddeleted file mode 100644index b4bd78b..0000000--- a/skills/modern-web/guides/user-experience/capture-location-agnostic-data.md+++ /dev/null@@ -1,61 +0,0 @@-# Capturing Location-Agnostic Data with Temporal--Recording chronological data that should remain identical regardless of the viewer's location (such as birthdates, recurring alarms, or national holidays) has historically been error-prone with the legacy `Date` object. Because `Date` objects always represent a specific instant in time and are tied to a time zone, saving a date like "1990-01-01" can result in users in different time zones seeing "1989-12-31" due to offset shifts.--The `Temporal` API introduces "Plain" types—such as `Temporal.PlainDate` and `Temporal.PlainTime`—which have no concept of a time zone. These types represent calendar dates and wall-clock times exactly as you would read them off a calendar or a clock, making them ideal for location-agnostic data.--## How to Implement--To capture and display location-agnostic data:--1. **Use `Temporal.PlainDate` for dates**: For data like birthdates or holidays, use `Temporal.PlainDate.from()` to create an instance from an ISO 8601 string or an object.-2. **Use `Temporal.PlainTime` for times**: For data like a daily alarm or a preferred lunch time, use `Temporal.PlainTime.from()`.-3. **Display without conversion**: Since these objects are time-zone unaware, they will display the same values regardless of the user's local time zone.--### Example: Capturing a Birthdate--```javascript-// 1. Parse a date string from an input (e.g., "1990-01-01")-const birthdateStr = "1990-01-01";-const plainDate = Temporal.PlainDate.from(birthdateStr);--// 2. Display the date-// This will output "01/01/1990" (or equivalent) in any time zone-console.log(plainDate.toLocaleString('en-GB'));--// 3. Compare with standard Date (which might drift)-const dateObj = new Date("1990-01-01T00:00:00Z");-// In a UTC-5 time zone, this might print "31/12/1989"-console.log(new Intl.DateTimeFormat('en-GB', { timeZone: 'America/New_York' }).format(dateObj));-```--## Strategic Implementation & Best Practices--- **DO** use `Temporal.PlainDate` for "calendar dates" like birthdates, anniversaries, and holidays where the specific time of day or time zone is irrelevant.-- **DO** use `Temporal.PlainTime` for "wall-clock times" like a daily reminder at 9:00 AM, where the time should be 9:00 AM in whatever time zone the user happens to be in.-- **DO NOT** use Plain types if you need to represent a specific moment in physical time (an "instant"). Use `Temporal.Instant` or `Temporal.ZonedDateTime` for logs, event timestamps, or anything requiring time zone awareness.-- **DO** remember that `Temporal` objects are **immutable**. Methods like `add()` or `with()` return a new instance rather than modifying the original.--## Fallback Strategy--### Fallbacks & browser support for Temporal--Temporal has limited availability.--For browsers that do not yet support the native `Temporal` API, use feature detection and a polyfill. The standard reference polyfill is `@js-temporal/polyfill`.--Note that the polyfill does not automatically assign the `Temporal` object to the global scope to avoid conflicts. You must manually assign it if your code relies on the global `Temporal` object.--```javascript-// Check if Temporal is supported natively-(async () => {- if (typeof Temporal === 'undefined') {- // Load the polyfill conditionally- const module = await import("https://esm.sh/@js-temporal/polyfill");- globalThis.Temporal = module.Temporal;- // Extend Date.prototype if needed- Date.prototype.toTemporalInstant = module.toTemporalInstant;- initializeApp();- }-})();-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/carousel-slide-effects.md b/skills/modern-web/guides/user-experience/carousel-slide-effects.mddeleted file mode 100644index 8181e1c..0000000--- a/skills/modern-web/guides/user-experience/carousel-slide-effects.md+++ /dev/null@@ -1,185 +0,0 @@-# Build Carousel Slide Effects--Carousel slide effects are a great way to add visual interest to a carousel. As the user scrolls through the slides, each slide can animate as it enters, centers, and exits the scrollport. For example, the slides can fade in and out, rotate, or scale in size. This creates a dynamic and engaging user experience. Unlike simple entry/exit animations, this effect uses a single, continuous animation to control the slide's appearance across the entire scrollport.--## How to implement--Here’s how to create carousel slide effects:--1. **Create a scroller:** This element will act as the container for your carousel slides. In this example it uses `overflow-x: scroll` to allow horizontal scrolling.-- ```html- <ul class="scroller">- <li class="entry">1</li>- <li class="entry">2</li>- <li class="entry">3</li>- …- </ul>- ```-- ```css- .scroller {- overflow-x: scroll;- }- ```--2. **Define the animation:** Create a CSS animation that defines the different states of your slides as they traverse the scrollport. You can define keyframes for any part of the animation. For example, you can define a state for when the slides are in the center of the scrollport by including a `50%` keyframe. In this example, the `scale` property makes the slides grow as they approach the center and shrink as they move away.-- ```css- @keyframes animate {- 0% {- scale: 0.5;- }- 50% {- scale: 1;- }- 100% {- scale: 0.5;- }- }- ```--3. **Apply the animation and `view-timeline`:** Attach the animation to the carousel slides and link it to a `view-timeline` that tracks the element as it scrolls through the container.-- ```css- .scroller > * {- animation: animate auto linear both;- animation-timeline: view(inline);- }- ```-- By default, `view()` tracks the element on the `block` axis. If you need to track it on the `inline` axis, you can use `view(inline)`.--## Example code--This code animates the carousel items of a horizontal scroller on scroll using an **anonymous view-timeline**:--```css-@keyframes animate {- 0% {- scale: 0.5;- }-- 50% {- scale: 1;- }-- 100% {- scale: 0.5;- }-}--.scroller > * {- /* Applies the animation using an `auto` duration */- animation: animate auto linear both;- /* Sets the animation timeline to use an anonymous view progress timeline, tracking the element's progress through the scroller on the inline axis */- animation-timeline: view(inline);-}-```--This code animates the carousel items of a horizontal scroller on scroll using a **named view-timeline**:--```css-@keyframes animate {- 0% {- scale: 0.5;- }-- 50% {- scale: 1;- }-- 100% {- scale: 0.5;- }-}--/* This creates a named view-timeline on each carousel item. The timeline is used to drive the animation that is applied on the same element. */-.scroller > * {- /* Applies the animation using an `auto` duration */- animation: animate auto linear both;- /* Defines a named view progress timeline, tracking the element's progress through the scroller on the inline axis */- view-timeline: --item inline;- /* Sets the animation timeline to use the named view progress timeline defined above */- animation-timeline: --item;-}-```--## Best Practices--When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:--- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: view()) and (animation-range: entry))` to check for support and provide a fallback for browsers that don't support it.- - The `(animation-range: entry)` check **MUST** be included here, to filter out browsers with only partial support.- - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.- - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.-- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.-- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.-- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.--Prefer a named `view-timeline` when multiple DOM elements need to animate based on the same timeline, or when you need to animate children of the element that has the `view-timeline` defined on it. If the element that you animate is also the element that defines the `view-timeline`, you can use an anonymous view-timeline using `view()`.--When using the `view()` function to create a scroll-driven animation:--- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view(block)` or `view(inline)`.--When using the `view-timeline` property to create a scroll-driven animation:--- **DO** use a CSS `<dashed-ident>` for the name (e.g. `view-timeline: --my-custom-name`)-- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view-timeline-axis`.-- **DO** make sure the scope of the lookup works: When the element that is declaring the `view-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `view-timeline`’s name by using `timeline-scope` on a shared ancestor.--## Browser support and fallback strategies--Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.--For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).--In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.--Note that not every effect can be recreated using the fallbacks approach.--For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses the Web Animations API (`Element.animate()`) to create a paused animation for each item in the carousel. It then listens to the `scroll` event on the scroller and updates the `currentTime` of each animation based on the item's scroll progress within the scroller.--```js-// Fallback for browsers that don't support scroll-driven animations-if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {- const scroller = document.querySelector('.scroller');- const entries = document.querySelectorAll('.entry');-- // Create a map to store animations- const animations = new Map();-- entries.forEach(entry => {- const animation = entry.animate(- {- scale: ['0.5', '1', '0.5']- },- {- duration: 1, // We'll control the time ourselves- fill: 'both'- }- );- animation.pause();- animations.set(entry, animation);- });-- // Update animations on scroll- const tick = () => {- const scrollerRect = scroller.getBoundingClientRect();-- entries.forEach(entry => {- const animation = animations.get(entry);- if (!animation) return;-- const entryRect = entry.getBoundingClientRect();- const progress = (entryRect.left + entryRect.width / 2 - scrollerRect.left) / scrollerRect.width;-- animation.currentTime = progress;- });- };-- scroller.addEventListener('scroll', tick);- tick();-}-```diff --git a/skills/modern-web/guides/user-experience/carousel-snap-highlights.md b/skills/modern-web/guides/user-experience/carousel-snap-highlights.mddeleted file mode 100644index e3a6a63..0000000--- a/skills/modern-web/guides/user-experience/carousel-snap-highlights.md+++ /dev/null@@ -1,110 +0,0 @@-Scroll-state container queries allow you to style elements based on their current scroll state, such as whether an element is "stuck" (via sticky positioning) or "snapped" (via scroll snapping). This enables carousel or gallery experiences where the active item can be visually distinguished without relying on JavaScript intersection observers or scroll event listeners.--### Core implementation--To highlight snapped items, you must establish a scroll-snap container, define the snap targets as scroll-state containers, and then query that state to style descendants.--#### 1. Establish the scroll snap container-The parent container must have `scroll-snap-type` enabled.--```css-.carousel {- display: flex;- overflow-x: auto;- /* MANDATORY: Enable scroll snapping on the container */- scroll-snap-type: x mandatory;-}-```--#### 2. Define snap targets as scroll-state containers-Each item in the carousel that should be tracked for snapping must be declared as a `scroll-state` container.--```css-.carousel-item {- /* Define where the item snaps within the container */- scroll-snap-align: center;-- /* MANDATORY: Establish this element as a scroll-state query container */- container-type: scroll-state;-}-```--#### 3. Query the `snapped` state--Because container queries style **descendants**, you must apply the highlight styles to an element *inside* the snap target. Because the scroll container is set to overflow on the x axis, use the `scroll-state(snapped: x)` query.--**MANDATORY**: Wrap the styles in ` @media (prefers-reduced-motion: no-preference)` to only show the effect to users who have not requested reduced motion. Depending on your use case, you may retain portions of the effect, but in this case, the cards flash from white to blue in a way that may cause problems for some users, so we disable it completely.--```css-/* Specify transition outside of queries so that it is applied regardless of state. */-.card {- transition:- scale 0.4s cubic-bezier(0.25, 0.8, 0.25, 1),- background-color 0.4s,- color 0.4s,- box-shadow 0.4s;-}-/*-Only show the effect for users not requesting reduced motion. Disable completely, including the color change, as it causes a flash that may be problematic.-*/-@media (prefers-reduced-motion: no-preference) {- /* Style the content when its parent .carousel-item is snapped on the x axis */- @container scroll-state(snapped: x) {- .card {- background: #007bff;- color: white;- scale: 1.15;- box-shadow: 0 10px 25px rgba(0, 123, 255, 0.3);- }- }-}-```--The `snapped` descriptor can query specific axes: `x`, `y`, `inline`, `block`, or `both`.---### Accessibility--**AVOID**: using `scroll-state` with interactive elements.--Visual highlights for snapped items can improve the UX, but the snapped item is not exposed to the accessibility tree. The visual theme applied to a snapped item should not convey that the element is active or focused, and a keyboard focus ring should be highly visible and distinct from the `snapped` highlight. If the snapped item is interactive, you must use other standard accessibility practices to make it accessible.--Snapping occurs due to scrolling, which does not move keyboard focus. However, keyboard focus may cause the scroll container to move, causing a change in the snapped item, which may or may not be the focused item. This will likely be a source of confusion for users and is discouraged.--### Fallback strategies-Container scroll-state queries has limited availability.--For browsers that do not support scroll-state queries, you should provide a functional base experience where all items are legible, even without the "active" highlight.--#### Feature detection-You can use `@supports` to provide enhancements only to supported browsers:--```css-@supports (container-type: scroll-state) {- /* Enhancement styles here */-}-```--#### JavaScript fallback--If the highlight is critical for the user experience, use `IntersectionObserver` to determine the snapped item. Adjust the observed area to a thin slice in the center of the carousel by providing a `rootMargin` with a negative inline value. For example, to consider an element to be intersecting if it is in the center 2% of the carousel, set the `rootMargin` to `"0px -49%"`.--```javascript-// Optional: detect support and apply a JS-based fallback-if (!CSS.supports('container-type', 'scroll-state')) {- const observer = new IntersectionObserver((entries) => {- entries.forEach(entry => {- // Toggle a class based on intersection- entry.target.classList.toggle('is-snapped', entry.isIntersecting);- });- }, {- root: document.querySelector(".carousel"),- // Carousel item intersects if any part of the carousel item is in the middle 2% of the carousel.- rootMargin: "0px -49%"- });-- document.querySelectorAll('.carousel-item').forEach(item => {- observer.observe(item);- });-}-```diff --git a/skills/modern-web/guides/user-experience/child-state-based-styling.md b/skills/modern-web/guides/user-experience/child-state-based-styling.mddeleted file mode 100644index abd9a4a..0000000--- a/skills/modern-web/guides/user-experience/child-state-based-styling.md+++ /dev/null@@ -1,100 +0,0 @@-Historically, CSS selectors could only traverse downwards—you could style a child based on its parent, but not a parent based on its child. The `:has()` pseudo-class changes this, allowing you to conditionally style a container element depending on the presence or state of its descendants.--By combining `:has()` with state pseudo-classes (like `:checked`, `:focus`, `:valid`, `:invalid`, or `:not()`), you can build complex, interactive UI components entirely in CSS, without needing JavaScript to toggle "modifier" classes (like `.is-active` or `.has-error`) on parent elements.--This is particularly useful for components that need to respond to internal interactions, such as a localized theme toggle reacting to a checkbox (`:checked`), a form group highlighting an error (`:invalid`), or a card elevating when a child link is focused (`:focus-within`).--### Implementing state-based container styling--**MANDATORY**: You must use the `:has()` selector on the container element to detect the specific state (e.g., `:checked`, `:focus`, `:invalid`) of its interactive child element.--To build a component that changes its styling based on a child's state:--1. **Define the default styling**: Set CSS variables on the container to define its base state.-2. **Apply state-based overrides**: Target the container with `:has([child-selector]:[state])` and redefine the CSS variables for the active or alternate state.--*Example: A component that changes theme based on a child toggle.*--```css-/* 1. Define the default state on the component container */-.theme-card {- /* Using custom properties makes state-switching cleaner */- --card-bg: #ffffff;- --card-text: #333333;- --card-border: #cccccc;-- background-color: var(--card-bg);- color: var(--card-text);- border: 1px solid var(--card-border);-- /* Use a transition for smooth state changes */- transition: background-color 0.3s, color 0.3s;-}--/* 2. Apply styles when the child enters the specific state */-/* MANDATORY: Target the container and use :has() to check the descendant's state */-.theme-card:has(.theme-toggle:checked) {- /* Override the properties for the active or alternate state */- --card-bg: #222222;- --card-text: #f0f0f0;- --card-border: #555555;-}-/* You can also combine :has() and :not() to target specific negative states */-/* This selects a card that DOES NOT have a toggle in the checked state */-.theme-card:not(:has(.theme-toggle:checked)) {- /* Optional: Explicit styles for the unchecked state if needed */-}-```--```html-<!-- The container element that receives the styling -->-<div class="theme-card">- <!-- The child element whose state controls the parent -->- <label>- <input type="checkbox" class="theme-toggle">- Enable Dark Mode- </label>-- <h2>Card Title</h2>- <p>The style of this entire card is controlled by the checkbox above.</p>-</div>-```--**Performance tip**: When using `:has()`, scope the selector to the most specific container possible (like `.theme-card`). Avoid anchoring it to very high-level elements like `body:has(...)` if the styling changes are localized, as broad `:has()` queries can trigger more layout recalculations.--### Fallback strategies--Baseline status for :has(): Newly available. It's been Baseline since 2023-12-19.--If the state-based styling is critical to the user experience or page layout, you must provide a fallback for browsers that do not support the `:has()` selector. For purely decorative effects, `:has()` can be used as a progressive enhancement without a fallback.--**MANDATORY**: When implementing a fallback for critical features, you must use `@supports not selector(:has(*))` in your CSS to define a traditional class-based fallback. If the critical state change relies on user interaction, you must also use a small inline script with `CSS.supports()` to toggle that class based on the equivalent JavaScript event (e.g., `change`, `focus`, `blur`) representing the state change.--```css-/* Fallback CSS for older browsers */-/* We check if the browser DOES NOT support the :has() selector */-@supports not selector(:has(*)) {- /* Define a traditional modifier class that applies the exact same overrides */- .theme-card.is-active {- --card-bg: #222222;- --card-text: #f0f0f0;- --card-border: #555555;- }-}-```--```javascript-/* Fallback JavaScript for older browsers */-/* Check for support before running the script to avoid unnecessary work in modern browsers */-if (!CSS.supports('selector(:has(*))')) {- const toggle = document.querySelector('.theme-toggle');- const card = document.querySelector('.theme-card');-- if (toggle && card) {- // Manually toggle the fallback class when the input state changes- toggle.addEventListener('change', (e) => {- card.classList.toggle('is-active', e.target.checked);- });- }-}-```diff --git a/skills/modern-web/guides/user-experience/component-specific-light-dark-theme.md b/skills/modern-web/guides/user-experience/component-specific-light-dark-theme.mddeleted file mode 100644index 7d83f50..0000000--- a/skills/modern-web/guides/user-experience/component-specific-light-dark-theme.md+++ /dev/null@@ -1,110 +0,0 @@-# Component-Specific Light/Dark Themes--The `light-dark()` function allows you to define two colors for a single property, which the browser automatically switches based on the current `color-scheme`. By scoping both the `light-dark()` variables and the `color-scheme` property to a specific component, you can create UI elements that can be independently forced into light or dark mode, regardless of the user's global system preference.--## Implementation steps--1. **MANDATORY: Enable `color-scheme` support.** The `light-dark()` function only resolves if the element (or an ancestor) has an explicit `color-scheme` value of `light`, `dark`, or `light dark`.-- ```css- :root {- /*- MANDATORY: Enable system-wide support for both themes.- Without this, the browser will not know how to resolve light-dark().- */- color-scheme: light dark;- }- ```--2. **Define semantic variables or properties using `light-dark()`.** Use the `light-dark(light-color, dark-color)` syntax.-- ```css- .themed-card {- /*- DO: Use semantic variables to define theme-aware colors.- The first argument is used when color-scheme is 'light'.- The second argument is used when color-scheme is 'dark'.- */- --card-bg: light-dark(#ffffff, #2d2e31);- --card-text: light-dark(#202124, #f8f9fa);-- background-color: var(--card-bg);- color: var(--card-text);- padding: 1.5rem;- border-radius: 8px;- }- ```--3. **Create theme overrides.** You can force a component instance into a specific theme by setting its `color-scheme` property using any valid CSS selector (classes, data attributes, etc.). This overrides the inherited system preference for that specific subtree.-- ```css- /*- DO: Use color-scheme to force a specific theme on a component.- You can use classes, data attributes, or any other selector.- */-- /* Using classes */- .themed-card.force-light {- color-scheme: light;- }-- /* Using data attributes (often preferred for state) */- .themed-card[data-theme="dark"] {- color-scheme: dark;- }- ```--## Critical Considerations--- **Supported Types**: Currently, `light-dark()` is only used for color values. It cannot be used for lengths, numbers, or other non-color types (e.g., `padding`, `font-size`, `opacity`).-- **MANDATORY: Two Arguments**: The function must always have exactly two arguments.--```css-/*- DO NOT: Attempt to use light-dark() for non-color properties like padding.- This will result in an invalid property value.-*/-.themed-card {- padding: light-dark(10px, 20px);-}-```--## Fallback strategies--Baseline status for light-dark(): Newly available. It's been Baseline since 2024-05-13.-Baseline status for color-scheme: Widely available. It's been Baseline since 2022-02-03.--### Color Fallbacks-For browsers that do not support `light-dark()` or the `color-scheme` property, provide a fallback using `@media (prefers-color-scheme: dark)` or manual variable overrides.--```css-.themed-card {- /*- MANDATORY: Define base fallback colors for browsers without light-dark().- Default to light mode values.- */- --card-bg: #ffffff;- --card-text: #202124;-}--/*- DO: Update variables based on system preference for older browsers.-*/-@media (prefers-color-scheme: dark) {- .themed-card {- --card-bg: #2d2e31;- --card-text: #f8f9fa;- }-}--/*- DO: Use @supports to provide progressive enhancement for light-dark().- This ensures that per-component overrides (via color-scheme) work where supported.-*/-@supports (color: light-dark(white, black)) {- .themed-card {- --card-bg: light-dark(#ffffff, #2d2e31);- --card-text: light-dark(#202124, #f8f9fa);- }-}-```diff --git a/skills/modern-web/guides/user-experience/consistent-cross-document-transitions.md b/skills/modern-web/guides/user-experience/consistent-cross-document-transitions.mddeleted file mode 100644index e4f78fb..0000000--- a/skills/modern-web/guides/user-experience/consistent-cross-document-transitions.md+++ /dev/null@@ -1,216 +0,0 @@-# Consistent Cross-Document Transitions--## The Problem--Cross-document view transitions animate elements between two pages during a same-origin navigation. The browser captures a snapshot of the old page, navigates, then animates from the snapshot to the new page. If the new page has not finished loading critical resources — stylesheets, layout scripts, or key DOM elements — the transition animates to an incomplete or unstyled state. This causes visual glitches such as elements morphing to wrong positions, content reflowing mid-animation, or fallback fonts flashing to web fonts after the transition completes.--## The Solution--Use `blocking="render"` on critical `<link>` and `<script>` elements in the new page's `<head>`, and use `<link rel="expect">` to block rendering until specific DOM elements have been parsed. This ensures the browser does not begin the view transition animation until the new page's visual state is stable. The browser continues parsing the HTML in the background — only painting is deferred.--### Implementation Strategy--1. **MANDATORY:** Opt in to cross-document view transitions with the `@view-transition` CSS at-rule on both pages.-2. **MANDATORY:** Ensure critical stylesheets are in the `<head>`. Stylesheets in the `<head>` are render-blocking by default. Dynamically injected stylesheets require explicit `blocking="render"`.-3. **DO** use `blocking="render"` on `<script>` elements that must execute before the transition animates (e.g., scripts that apply a theme or affect the layout).-4. **DO** use `<link rel="expect" href="#element-id" blocking="render">` to block rendering until above-the-fold content has been parsed. This applies to all transition types: full-page cross-fades (to avoid animating to a blank page), morph animations (to ensure named elements exist in the DOM), and script-dependent layouts (to ensure styled content is parsed).-5. **DO NOT** block rendering on non-critical content. Only block on resources and elements that affect the initial viewport. Blocking on too much content delays the transition and degrades perceived performance.--## Implementation Guide--### Step 1: Opt in to Cross-Document View Transitions--MANDATORY: Both the source and destination pages must include the `@view-transition` at-rule. Without this, no cross-document transition occurs.--```css-/*- MANDATORY: Include this rule in every page that participates- in cross-document view transitions.- `navigation: auto` enables transitions for standard navigations- (link clicks, form submissions, back/forward).-*/-@view-transition {- navigation: auto;-}-```--### Step 2: Block Rendering Until Critical Scripts Execute--If a non-blocking script in the `<head>` must run before the transition animates (e.g., to apply a theme class or affect the layout), mark it with `blocking="render"`. Without this, `async`, `defer`, or `type="module"` scripts may execute after the transition has already started.--```html-<head>- <!--- DO: Mark layout-critical scripts with blocking="render".- -->- <script type=module blocking="render">- // Example: apply a stored theme before the page renders,- // so the transition snapshot reflects the correct theme.- document.documentElement.dataset.theme =- localStorage.getItem('theme') || 'light';- </script>-</head>-```--### Step 3: Block Rendering Until Key DOM Elements Are Parsed--Stylesheets and `blocking="render"` scripts in the `<head>` only guarantee that the `<head>` has been fully processed. They do **not** wait for any `<body>` content to be parsed. Without additional blocking, the browser may take the new-page snapshot before above-the-fold elements exist in the DOM — resulting in a transition that animates to a blank or partially rendered page.--`<link rel="expect">` solves this by blocking rendering until a specific element (identified by its `id`) has been parsed. The `href` value must be a fragment identifier (e.g., `#hero`) matching the target element's `id` attribute. Once that element's closing tag is parsed, the render block is released.--**DO** use `<link rel="expect">` in all of the following scenarios:--#### Use Case 1: Full-Page Cross-Fade--Even when no individual elements have a `view-transition-name`, the default `root` transition cross-fades the entire page. If the new page's snapshot is taken before above-the-fold content is parsed, the cross-fade animates from the old page to a blank or incomplete page. Block rendering on an element that marks the end of the visible above-the-fold content.--```html-<head>- <link rel="stylesheet" href="/css/styles.css">-- <!--- DO: Block rendering until the main content area is parsed,- even for a simple cross-fade. Without this, the browser may- snapshot the page before visible content exists in the DOM,- causing the cross-fade to reveal a blank or partial page.- -->- <link rel="expect" href="#main-content" blocking="render">-</head>-<body>- <header>...</header>- <main id="main-content">- <h1>Page Title</h1>- <p>Above-the-fold content the user should see immediately.</p>- </main>- <!-- Content below the fold does NOT need to be blocked on -->- <section>...</section>-</body>-```--#### Use Case 2: Morph Animations Between Specific Elements--When elements on both pages share a `view-transition-name`, the browser morphs them smoothly across the navigation. If the target element has not been parsed when the transition starts, the browser cannot find it — the morph degrades to separate exit and entry animations. Block rendering until the element with the `view-transition-name` has been parsed.--```html-<head>- <link rel="stylesheet" href="/css/styles.css">-- <!--- DO: Block rendering until the element participating in the- morph animation has been parsed. Without this, the browser- may start the transition before #hero exists, causing the- morph to degrade to a fade-out/fade-in.- -->- <link rel="expect" href="#hero" blocking="render">-- <!--- When multiple blocking="render" resources are present,- rendering is blocked until ALL of them are satisfied.- Here, the browser waits for both the script to execute- AND the #hero element to be parsed — whichever comes last.- -->- <script async blocking="render" src="/js/transition-setup.js"></script>-</head>-<body>- <header>...</header>- <section id="hero">- <h1 style="view-transition-name: page-title">Product Name</h1>- <img style="view-transition-name: hero-image" src="/img/product.webp" alt="Product">- </section>-</body>-```--### Step 4: Use Media Queries for Responsive Render Blocking--Different viewport sizes may show different amounts of content above the fold. Use the `media` attribute on `<link rel="expect">` to block rendering only for the content visible at a given viewport width.--```html-<head>- <!--- DO: Use media queries to conditionally block rendering.- On wide screens, both the hero and the sidebar are visible,- so block until both are parsed. On narrow screens, only the- hero is visible initially.- -->- <link- rel="expect"- href="#hero"- blocking="render"- media="screen and (width <= 768px)"- >- <link- rel="expect"- href="#sidebar"- blocking="render"- media="screen and (width > 768px)"- >-</head>-```--### Step 5: Use pagereveal for Context-Dependent Transitions (Optional)--The `pagereveal` event is **not required** for the core render-blocking strategy. It is only needed when `view-transition-name` values must be assigned dynamically based on where the user navigated from — for example, morphing a specific list item to a detail page heading.--If `view-transition-name` values are assigned statically in CSS, or if you are only using the default full-page cross-fade, skip this step entirely.--```html-<head>- <!--- MANDATORY: The pagereveal listener must be registered before- the page renders. Use an async script with blocking="render"- so the listener is registered early without blocking parsing.- If the listener is registered too late (e.g., in a deferred- script), the event may have already fired.- -->- <script async blocking="render" src="/js/transition-setup.js"></script>-</head>-```--```javascript-// transition-setup.js-window.addEventListener('pagereveal', async (event) => {- if (!event.viewTransition) return;-- const from = navigation.activation?.from;- if (!from) return;-- const fromUrl = new URL(from.url);-- // DO: Assign view-transition-name based on navigation context.- // This enables a morph animation from the product card on the- // list page to the heading on the detail page.- if (fromUrl.pathname === '/products/') {- const heading = document.querySelector('main h1');- if (heading) {- heading.style.viewTransitionName = 'product-title';- }-- // MANDATORY: Remove the temporary name after the transition- // finishes. Stale names interfere with subsequent navigations- // and prevent the page from entering the bfcache.- await event.viewTransition.finished;- heading.style.viewTransitionName = '';- }-});-```--## Best Practices--- **DO** assign `view-transition-name` via CSS whenever possible. Reserve JavaScript assignment (via `pagereveal`) for cases where the name depends on navigation context.-- **DO** keep render-blocking scripts small and fast. The browser has a built-in timeout (around 4 seconds), after which the transition is skipped entirely with a `TimeoutError`.-- **DO NOT** use `<link rel="expect">` to block on elements deep in the page that are not visible in the initial viewport. This delays the transition without visual benefit.-- **DO NOT** assign the same `view-transition-name` to multiple elements on the same page. Duplicate names cause the entire transition to be skipped.--## Fallback Strategies--Cross-document view transitions has limited availability.--Cross-document view transitions are an excellent candidate for progressive enhancement. In browsers that do not support them, the `@view-transition` rule is ignored and standard same-origin navigations occurs exactly as they would without the feature. Supporting browsers get smooth transitions; all others get standard navigation. Limited browser support is not a reason to avoid adoption.--All browsers that support cross-document view transitions also support `blocking="render"` and `<link rel="expect">`, so no separate fallback is needed for the render-blocking features described in this guide.--## Other Considerations--1. **Performance Impact**: Every render-blocking resource delays the view transition animation start. Minimize the number of render-blocking scripts and use `<link rel="expect">` only for elements that are above the fold. Prerender destination pages using the Speculation Rules API to eliminate loading delays entirely.-2. **Timeout Behavior**: If the combined render-blocking time exceeds approximately 4 seconds, the browser skips the transition with a `TimeoutError`. Ensure critical resources load well within this window.-3. **bfcache Compatibility**: Temporary `view-transition-name` assignments that are not cleaned up after the transition can prevent the page from entering the bfcache. Always remove dynamically assigned names in the `finished` callback.diff --git a/skills/modern-web/guides/user-experience/content-based-styling.md b/skills/modern-web/guides/user-experience/content-based-styling.mddeleted file mode 100644index 42e116b..0000000--- a/skills/modern-web/guides/user-experience/content-based-styling.md+++ /dev/null@@ -1,116 +0,0 @@-Historically, applying different layouts to a component based on its content required either JavaScript or conditional logic in your HTML templating language to inject modifier classes (like `.card--has-image` or `.card--text-only`).--The `:has()` pseudo-class eliminates this need by acting as a parent selector. It allows you to conditionally style a container element based on the presence or absence of specific descendant elements.--Using `:has()`, you can easily define distinct layout variations entirely in CSS based on a component's actual DOM content. You can also optionally combine it with `:not()` to explicitly target the *absence* of content to define default layouts.--### Implementing content-based container styling--**MANDATORY**: You must use the `:has()` selector on the container element to detect the presence of specific child content.--To build a component that changes its layout based on its content:--1. **Define the default styling**: Apply the base layout styles to the container element (e.g., a simple single-column stack).-2. **Apply content-based overrides**: Target the container with `:has([child-selector])` and apply the new layout styles for when that content is present (e.g., a multi-column grid).--*Example: A card component that switches to a side-by-side layout if an image is present.*--```css-/* 1. Define the default state on the component container */-/* This applies when there is NO image */-.article-card {- display: flex;- flex-direction: column;- gap: 1rem;- padding: 1.5rem;- border: 1px solid #ccc;- border-radius: 8px;-}--/* 2. Apply styles when a specific child element is present */-/* MANDATORY: Target the container and use :has() to check for the descendant */-.article-card:has(img) {- /* Change the layout to a row if an image exists */- flex-direction: row;- align-items: center;-}--/* Optional: Style the image itself (no :has() needed here) */-.article-card img {- width: 150px;- height: auto;- border-radius: 4px;-}--/* You can also combine :has() and :not() to explicitly target the ABSENCE of content */-/* This selects a card that DOES NOT have an image */-.article-card:not(:has(img)) {- /* E.g., apply a different background color for text-only cards */- background-color: #f9f9f9;-}-```--```html-<!-- A card WITH an image (will use row layout) -->-<article class="article-card">- <img src="thumbnail.jpg" alt="Article thumbnail" />- <div class="content">- <h2>Card With Image</h2>- <p>This card lays out its content horizontally.</p>- </div>-</article>--<!-- A card WITHOUT an image (will use default column layout) -->-<article class="article-card">- <div class="content">- <h2>Text-Only Card</h2>- <p>This card lays out its content vertically, and gets its background color from the :not(:has()) rule.</p>- </div>-</article>-```--**Performance tip**: When using `:has()`, scope the selector to the most specific component container possible (like `.article-card`). Avoid anchoring it to very high-level elements like `body:has(img)` if the styling changes are highly localized, as broad `:has()` queries can trigger more layout recalculations.--### Fallback strategies--Baseline status for :has(): Newly available. It's been Baseline since 2023-12-19.--If the content-based layout styling is critical to the user experience or page design, you must provide a fallback for browsers that do not support the `:has()` selector. For purely decorative effects, `:has()` can be used as a progressive enhancement without a fallback.--**MANDATORY**: When implementing a fallback for critical layouts, you must use `@supports not selector(:has(*))` in your CSS to define a traditional class-based fallback (e.g., `.has-image`).--Unlike interactive state-based styling, content presence is typically known at render time. The most robust fallback is to have your server-side templating engine (or static site generator) inject a class like `.has-image` onto the container if the child element (like an image) exists in the data.--If server-side rendering is not an option, you must use a small script with `CSS.supports()` to detect the content and append the class on load or after dynamic content injection.--```css-/* Fallback CSS for older browsers */-/* We check if the browser DOES NOT support the :has() selector */-@supports not selector(:has(*)) {- /* Define a traditional modifier class that applies the exact same layout overrides */- .article-card.has-image {- flex-direction: row;- align-items: center;- }-- .article-card:not(.has-image) {- background-color: #f9f9f9;- }-}-```--```javascript-/* Fallback JavaScript for older browsers (if not using SSR to add the class) */-/* Check for support before running the script to avoid unnecessary work in modern browsers */-if (!CSS.supports('selector(:has(*))')) {- // Find all components that need checking- const cards = document.querySelectorAll('.article-card');-- cards.forEach(card => {- // If the critical content exists, manually add the fallback class- if (card.querySelector('img')) {- card.classList.add('has-image');- }- });-}-```diff --git a/skills/modern-web/guides/user-experience/coordinate-global-events.md b/skills/modern-web/guides/user-experience/coordinate-global-events.mddeleted file mode 100644index 21e1b4e..0000000--- a/skills/modern-web/guides/user-experience/coordinate-global-events.md+++ /dev/null@@ -1,77 +0,0 @@-# Coordinating Global Events with Temporal--Scheduling events across different time zones is notoriously difficult with the legacy `Date` object, especially around Daylight Saving Time (DST) transitions when hours can be skipped or repeated.--The `Temporal` API provides `Temporal.ZonedDateTime` to represent a date and time in a specific time zone, handling DST transitions automatically and predictably.--## How to Implement--To coordinate global events and handle potential DST conflicts:--1. **MANDATORY:** **Create a ZonedDateTime**: Use `Temporal.ZonedDateTime.from()` to create a time-zone-aware date-time object.-2. **MANDATORY:** **Handle Ambiguity**: Use the `disambiguation` option to control behavior when a time is ambiguous or does not exist (e.g., during clock changes).-3. **MANDATORY:** **Convert Time Zones**: Use `.withTimeZone()` to see the equivalent time in another location.--### Example: Scheduling and Conflict Detection--```javascript-// 1. Define the event time and target time zone-const date = "2025-03-09";-const time = "02:30"; // This time is skipped in New York during Spring Forward-const timeZone = "America/New_York";-const inputStr = `${date}T${time}[${timeZone}]`;--// 2. Detect conflicts using 'reject'-let hasConflict = false;-try {- // 'reject' throws RangeError if the time is ambiguous or does not exist- Temporal.ZonedDateTime.from(inputStr, { disambiguation: 'reject' });-} catch (e) {- if (e instanceof RangeError) {- hasConflict = true;- console.log("This time falls in a DST transition gap or overlap.");- }-}--// 3. Resolve the time safely using 'compatible' (default)-// 'compatible' will resolve to a valid time even if skipped or repeated-const hostTime = Temporal.ZonedDateTime.from(inputStr, { disambiguation: 'compatible' });-console.log(`Resolved time: ${hostTime.toString()}`);--// 4. Convert to another time zone (e.g., Tokyo)-const tokyoTime = hostTime.withTimeZone("Asia/Tokyo");-console.log(`Tokyo time: ${tokyoTime.toString()}`);-```--## Strategic Implementation & Best Practices--- **DO** use `Temporal.ZonedDateTime` for events that are bound to a specific geographical location (like a meeting in a specific city).-- **DO** use `disambiguation: 'reject'` if you need to detect and warn users about scheduling conflicts during DST transitions.-- **DO** use `disambiguation: 'compatible'` (the default) when you want the system to automatically pick a sensible time when conflicts occur.-- **DO NOT** use `Temporal.PlainDateTime` for global events, as it does not carry time zone information and cannot account for DST changes.-- **DO** use `.withTimeZone()` to calculate the equivalent time in other locations without mutating the original object (Temporal objects are immutable).--### Fallback strategies--Temporal has limited availability.--For environments without native `Temporal` support, you must conditionally load the `@js-temporal/polyfill`.--```javascript-// Check if Temporal is supported natively-(async () => {- if (typeof Temporal === 'undefined') {- // Load the polyfill conditionally- const module = await import("https://esm.sh/@js-temporal/polyfill");- globalThis.Temporal = module.Temporal;- // Extend Date.prototype if needed- Date.prototype.toTemporalInstant = module.toTemporalInstant;- initializeApp();- }-})();--function initializeApp() {- // Your app logic here- console.log("Temporal is ready:", typeof Temporal);-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/cross-document-transitions.md b/skills/modern-web/guides/user-experience/cross-document-transitions.mddeleted file mode 100644index 3f1d0bf..0000000--- a/skills/modern-web/guides/user-experience/cross-document-transitions.md+++ /dev/null@@ -1,123 +0,0 @@-Cross-document view transitions allow you to create smooth, app-like transitions between different pages of a Multi-Page Application (MPA). By default, the browser performs a cross-fade, but you can customize this to match your site's aesthetic.--### Implementation Steps--#### 1. Opt-in to Cross-Document View Transitions--Both the source and destination pages must opt-in to view transitions for the browser to trigger them on navigation.--```css-/* Respect user's preference for reduced motion */-@media (prefers-reduced-motion: no-preference) {- /* Add to a global stylesheet shared by both pages */- @view-transition {- /* Enables transitions for same-origin navigations */- navigation: auto;- }-}-```--#### 2. Customize Transition Animations (Optional)--You can target the old and new states of the transition using pseudo-elements to create effects like slides or reveals.--```css-/* Customizing the outgoing page animation */-::view-transition-old(root) {- /* Move the old page out to the left */- animation: 0.4s ease-in both slide-out;-}--/* Customizing the incoming page animation */-::view-transition-new(root) {- /* Move the new page in from the right */- animation: 0.4s ease-out both slide-in;-}--@keyframes slide-out {- to { transform: translateX(-20%); opacity: 0; }-}--@keyframes slide-in {- from { transform: translateX(100%); }-}-```--#### 3. Create Directional Transitions (Optional)--You may want different transition effects depending on the pages you are navigating between. For instance, when navigating from a home page to a contact page, you may want the effect of new content coming from the right. When navigating back to the home page, it wouldn't make sense to have the same effect.--If the page you are navigating to will always have the same transition type, regardless of how you get to the page, you can specify it with `types` in the `@view-transition` rule.--```css-@media (prefers-reduced-motion: no-preference) {- @view-transition {- navigation: auto;- /* Specify the types of view transitions that will always be used on this page. */- types: previous;- }-}-```--You can also conditionally specify transition types inside of an event listener for `pagereveal`.--```js-window.addEventListener("pagereveal", async (e) => {- if (e.viewTransition && window.navigation?.activation) {- // Use application-specific logic to compute a transition type- const transitionType = yourTransitionTypeLogic(navigation.activation.from, navigation.activation.entry);- e.viewTransition.types.add(transitionType);- }-});-```--Then, use the `:active-view-transition-type()` pseudo selector to apply the different animations for each type.--```css-:active-view-transition-type(next) {- &::view-transition-old(root) {- animation-name: slide-out-next;- }-- &::view-transition-new(root) {- animation-name: slide-in-next;- }-}-:active-view-transition-type(previous) {- &::view-transition-old(root) {- animation-name: slide-out-previous;- }-- &::view-transition-new(root) {- animation-name: slide-in-previous;- }-}-```--### Fallback strategies--Baseline status for View transitions: Newly available. It's been Baseline since 2025-10-14.--Cross-document view transitions has limited availability.--If a browser does not support view transitions, or cross-document view transitions, it will perform a standard instant page navigation. Cross-document view transitions are a progressive enhancement; the core functionality of the site remains unaffected.--To check for support in JavaScript:--```javascript-if ('onpagereveal' in window) {- // Browser supports cross-document view transitions-}-```--Baseline status for Navigation API: Newly available. It's been Baseline since 2026-01-13.--If a browser does not support the Navigation API, you will not be able to use it to determine a transition type. Use an alternate method for determining the transition type, or provide a fallback transition type. Otherwise, the browser will perform a standard instant page navigation.--To check for support in JavaScript:--```javascript-if (window.navigation?.activation) {- // Browser supports the Navigation API-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/customize-scrollbar-color-and-thickness.md b/skills/modern-web/guides/user-experience/customize-scrollbar-color-and-thickness.mddeleted file mode 100644index e5f23c7..0000000--- a/skills/modern-web/guides/user-experience/customize-scrollbar-color-and-thickness.md+++ /dev/null@@ -1,57 +0,0 @@-# 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.--When using `scrollbar-color`, use CSS variables to keep thumb and track colors separate, for readability and maintainability (especially when using fallbacks).--```css-.scroller {- --scrollbar-thumb: var(--color-neutral-70);- --scrollbar-track: var(--color-neutral-90);-- scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);-}-```--## Fallback strategies--Baseline status for scrollbar-width: Newly available. It's been Baseline since 2024-12-11.--### Fallbacks & browser support for scrollbar-color--Baseline status for scrollbar-color: Newly available. It's been Baseline since 2025-12-12.--This feature is progressive enhancement and does not always require fallbacks.--If the styling is important and the user's Baseline target is "Baseline Widely Available" or earlier, you SHOULD include the non-standard `::-webkit-scrollbar` pseudo-elements as fallbacks.--Wrap legacy fallbacks in an `@supports not (scrollbar-color: auto)` block to prevent conflicts between standard properties and legacy WebKit selectors in browsers that support both natively.--If you are using custom properties to define colors, these will cascade to the legacy WebKit selectors automatically. You do NOT need to duplicate them.--```css-/* 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 {- background: var(--scrollbar-thumb);- }-- .scroller::-webkit-scrollbar-track {- background: var(--scrollbar-track);- }-}-```-diff --git a/skills/modern-web/guides/user-experience/declarative-button-actions.md b/skills/modern-web/guides/user-experience/declarative-button-actions.mddeleted file mode 100644index df09f36..0000000--- a/skills/modern-web/guides/user-experience/declarative-button-actions.md+++ /dev/null@@ -1,129 +0,0 @@-# Declarative Button Actions-The Invoker Commands API allows buttons to trigger actions on target elements declaratively using HTML attributes. This approach reduces the need for manual event listeners and ensures interactivity as soon as the HTML is parsed.--For custom, application-specific actions, you can define your own command names. Custom commands must be prefixed with a double dash (`--`) to avoid collisions with future built-in browser commands.--## Implementation steps--1. **Define the target element**: Identify the element that will respond to the action. It must have a unique `id`.-2. **Configure the invoker button**: Use the `commandfor` attribute to point to the target's `id`, and the `command` attribute to specify the custom command name (prefixed with `--`).-3. **Handle the command event**: Attach a `command` event listener to the `document` (or a common parent). This ensures that the event is captured even if it is dispatched by a polyfill or from a child element. The event object contains a `command` property and a `target` property (referring to the element identified by `commandfor`).--## Example: Custom Animation Controls--```html-<!-- The target element that will respond to custom commands -->-<div id="action-target" class="target">- Action Target-</div>--<!-- Buttons declaratively linked to the target element -->-<!-- Each button sends a unique custom command starting with '--' -->-<button commandfor="action-target" command="--spin">- Spin-</button>--<button commandfor="action-target" command="--grow">- Grow-</button>--<button commandfor="action-target" command="--reset">- Reset All-</button>--<script>- // Listen for the 'command' event directly on the target element- // (This is necessary because the native 'command' event does not bubble)- document.getElementById('action-target').addEventListener('command', (event) => {- // Robustly handle both native API and manual/polyfill fallbacks- const command = event.command || event.detail?.command;- const target = event.currentTarget;-- // Custom commands are checked to identify the requested action- if (command === '--spin') {- target.classList.toggle('is-spun');- } else if (command === '--grow') {- target.classList.toggle('is-grown');- } else if (command === '--reset') {- // Clear all custom classes to return to initial state- target.classList.remove('is-spun', 'is-grown');- }- });-</script>-```--## Key constraints--* **Prefix custom commands**: MANDATORY: All custom command names must start with `--` (e.g., `command="--my-action"`).-* **Targeting**: The `commandfor` attribute must match the `id` of an element in the same document tree.--## Fallback strategies--Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.--If the Invoker Commands API is not supported, the `command` event will not fire. For full support across all modern browsers, it is recommended to use the invokers-polyfill from https://github.com/keithamus/invokers-polyfill via `npm install` or CDN.--This polyfill fully supports custom actions (starting with `--`) and dispatches the `command` event exactly like the native API.--### Dynamic Import (Performance Optimization)--For the best performance, you should only load the polyfill if the browser doesn't support the API natively. This saves bandwidth and reduces script execution time for users on modern browsers.--```javascript-// Check for native support first-const hasNativeSupport = 'commandForElement' in HTMLButtonElement.prototype;--if (!hasNativeSupport) {- // Dynamically import the polyfill only when needed- try {- await import('https://cdn.jsdelivr.net/npm/invokers-polyfill@latest/dist/index.min.js');- console.log('Invoker Commands polyfill loaded');- } catch (err) {- console.error('Error loading fallback:', err);- }-}-```--### Manual fallback (Traditional pattern)--If you prefer not to use a polyfill, you can use a combination of **event delegation** to dispatch events and a **command registry** to handle the actions. This is a common architectural pattern in traditional JavaScript development that remains highly efficient and scalable.--```javascript-// 1. Define a registry of requested actions for cleaner logic-const commandRegistry = {- '--spin': (target) => target.classList.toggle('is-spun'),- '--grow': (target) => target.classList.toggle('is-grown'),- '--reset': (target) => target.classList.remove('is-spun', 'is-grown'),-};--const supportsInvokers = 'commandForElement' in HTMLButtonElement.prototype;--// 2. The fallback: Dispatch events manually if native support is missing-if (!supportsInvokers) {- document.addEventListener('click', (event) => {- const button = event.target.closest('button[commandfor]');- if (!button) return;-- const target = document.getElementById(button.getAttribute('commandfor'));- const command = button.getAttribute('command');-- if (target && command) {- target.dispatchEvent(new CustomEvent('command', {- bubbles: true,- detail: { command }- }));- }- });-}--// 3. The unified listener: Registered directly on the target element-document.getElementById('action-target').addEventListener('command', (event) => {- const command = event.command || event.detail?.command;- const target = event.currentTarget;- const action = commandRegistry[command];-- if (action) {- action(target);- }-});-```diff --git a/skills/modern-web/guides/user-experience/declarative-dialog-popover-control.md b/skills/modern-web/guides/user-experience/declarative-dialog-popover-control.mddeleted file mode 100644index 66c37b8..0000000--- a/skills/modern-web/guides/user-experience/declarative-dialog-popover-control.md+++ /dev/null@@ -1,143 +0,0 @@-# Overview--Use the Invoker Commands API to toggle the visibility of `<dialog>` and `[popover]` elements directly from HTML buttons, eliminating the need for custom JavaScript event listeners.--By applying the `commandfor` (target ID) and `command` (action) attributes to a `<button>`, the browser automatically handles open/close state changes, focus management, and accessibility bindings (such as `aria-expanded`). This declarative approach is recommended because it removes brittle boilerplate code, ensures interactions are functional immediately upon HTML parsing, and guarantees a robust, natively accessible user experience.--## Implementing Declarative Popovers--Popovers can be toggled open and closed using a single button.--```html-<!-- MANDATORY: The commandfor attribute links the invoker to the ID of the target element so the browser knows what to control. -->-<!-- MANDATORY: The command attribute specifies the action to perform. Use 'toggle-popover' to handle both open and close states automatically. -->-<button commandfor="my-popover" command="toggle-popover">- Toggle Popover-</button>--<!-- MANDATORY: The target element must have the popover attribute to be controlled as a popover. -->-<div id="my-popover" popover>- <p>Popover content goes here.</p>-</div>-```--If you need to control opening and closing with separate buttons, you can use the `show-popover` and `hide-popover` commands.--```html-<!-- MANDATORY: Use 'show-popover' to explicitly open the popover. It will not close the popover if clicked again. -->-<button commandfor="my-explicit-popover" command="show-popover">- Show Popover-</button>--<div id="my-explicit-popover" popover>- <p>This popover is explicitly opened and closed by separate buttons.</p>-- <!-- MANDATORY: Use 'hide-popover' to explicitly close the targeted popover. -->- <button commandfor="my-explicit-popover" command="hide-popover">- Hide Popover- </button>-</div>-```--## Implementing Declarative Modal Dialogs--Unlike popovers, modal dialogs typically use separate buttons for opening and closing. Use the `show-modal` command specifically when you need to open a dialog as a modal.--```html-<!-- MANDATORY: Use command="show-modal" to trigger the dialog as a modal, trapping focus and preventing interaction with the rest of the page. -->-<!-- MANDATORY: The commandfor attribute connects this button to the dialog ID. -->-<button commandfor="confirm-dialog" command="show-modal">- Open Confirmation-</button>--<dialog id="confirm-dialog">- <p>Are you sure you want to proceed?</p>-- <!-- MANDATORY: Use command="close" to dismiss the dialog safely. -->- <button commandfor="confirm-dialog" command="close">- Cancel- </button>-</dialog>-```--## Fallback strategies--Baseline status for Invoker commands: Newly available. It's been Baseline since 2025-12-12.-Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.--Because Invoker Commands and Popovers are not yet universally supported, you MUST use polyfills as fallbacks for older browsers.--### Polyfilling Invoker Commands--MANDATORY: Feature detect support by checking for the `commandForElement` property on the `HTMLButtonElement` prototype. Do NOT check the window or document object. You MUST dynamically import the polyfill only when the native feature is missing. DO NOT unconditionally load the polyfill.--**Option 1: Using a package manager (e.g., npm)**-Install the polyfill in your project (`npm install invokers-polyfill`).--```javascript-// MANDATORY: Feature detect 'commandForElement' on HTMLButtonElement.prototype.-// Conditionally load the invokers-polyfill only in browsers lacking native support.-if (!('commandForElement' in HTMLButtonElement.prototype)) {- import('invokers-polyfill');-}-```--**Option 2: Manual installation without npm**-If you are not using a package manager, dynamically import the polyfill directly from a CDN (such as unpkg) inside a `<script type="module">`.--```html-<script type="module">- // MANDATORY: Feature detect 'commandForElement' on HTMLButtonElement.prototype.- // Conditionally load the invokers-polyfill from a CDN only in browsers lacking native support.- if (!('commandForElement' in HTMLButtonElement.prototype)) {- import('https://unpkg.com/invokers-polyfill@latest/invoker.min.js');- }-</script>-```--**Invokers Polyfill Limitations**-Unlike the native Invoker Commands API, `invokers-polyfill` does not automatically handle ARIA attributes (such as `aria-expanded`) on the command button.--MANDATORY: You MUST manually manage these ARIA states to ensure your site remains fully accessible to screen readers in browsers relying on the polyfill.--### Polyfilling the Popover Attribute--To support the `popover` attribute in older browsers, use the `@oddbird/popover-polyfill`.--MANDATORY: Feature detect popover support by checking for the `popover` property on the `HTMLElement` prototype. Conditionally initialize the polyfill only if native support is missing.--**Option 1: Using a package manager**-Install the package (`npm install @oddbird/popover-polyfill`).--```javascript-// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.-if (!('popover' in HTMLElement.prototype)) {- import('@oddbird/popover-polyfill/fn').then(({ apply }) => {- apply();- });-}-```--**Option 2: Manual installation without npm**-If you are not using a package manager, dynamically import the polyfill directly from a CDN (such as unpkg) inside a `<script type="module">`.--```html-<script type="module">- // MANDATORY: Feature detect 'popover' on HTMLElement.prototype.- // Conditionally load the popover-polyfill from a CDN only in browsers lacking native support.- if (!('popover' in HTMLElement.prototype)) {- import('https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover-fn.js').then(({ apply }) => {- apply();- });- }-</script>-```--**Popover Polyfill Limitations & Styling Caveats**-MANDATORY: Use `:is()` or `:where()` to combine `:popover-open` with the corresponding polyfill class, otherwise browsers that do not support `:popover-open` will throw away the entire rule.--```css-[popover]:is(:popover-open, .\:popover-open) {- display: block;-}-```diff --git a/skills/modern-web/guides/user-experience/deliver-optimized-decorative-images.md b/skills/modern-web/guides/user-experience/deliver-optimized-decorative-images.mddeleted file mode 100644index 5e2ea8a..0000000--- a/skills/modern-web/guides/user-experience/deliver-optimized-decorative-images.md+++ /dev/null@@ -1,48 +0,0 @@-Delivering optimized decorative images via CSS improves perceived performance without sacrificing visual quality. By using the `image-set()` CSS function, you can provide the browser with multiple options for a single background or mask image. You can specify modern formats (like AVIF or WebP) alongside different resolutions (like `1x` and `2x`). The browser will dynamically select the smallest compatible image that provides the appropriate pixel density for the user's device.--**CAUTION**: If the image is likely to be the Largest Contentful Paint (LCP) element (e.g., a large hero banner), be aware that images referenced in CSS via image-set() are not discoverable by the browser's preload scanner. This can significantly delay image loading and harm LCP. For LCP candidates, consider using a standard HTML <img> or <picture> tag instead or alternatively, preloading the image as well using `<link rel=preload>` option with a `media` attribute.--### Implementation--The `image-set()` function is used anywhere CSS expects an `<image>` value, most commonly in `background-image`, `content`, or `mask-image`. Note that while providing both the image format via `type()` and the resolution (like `1x` or `2x`) yields the best results, both of these arguments are optional.--```css-.gallery-item {- /* Provide multiple resolutions and formats using image-set() */- /* MANDATORY: Always order your formats from most optimized (AVIF) to least optimized (JPEG/PNG).- The browser will stop at the first supported format. */- background-image: image-set(- url("gallery.avif") type("image/avif") 1x,- url("gallery-2x.avif") type("image/avif") 2x,- url("gallery.webp") type("image/webp") 1x,- url("gallery-2x.webp") type("image/webp") 2x,- url("gallery.jpg") type("image/jpeg") 1x,- url("gallery-2x.jpg") type("image/jpeg") 2x- );-- /* Standard decorative properties */- background-size: cover;- background-position: center;-}-```--### Fallback strategies--Baseline status for image-set(): Widely available. It's been Baseline since 2023-09-18.--For older browsers that do not support the `image-set()` function, you **MUST** provide a standard image declaration *before* the `image-set()` rule. This progressive enhancement strategy relies on CSS's cascading nature: unsupported rules are ignored.--```css-.gallery-item {- /* MANDATORY: Fallback for browsers that do not support image-set() */- background-image: url("gallery.jpg");-- /* Modern browsers will apply this and override the fallback */- background-image: image-set(- url("gallery.avif") type("image/avif") 1x,- url("gallery-2x.avif") type("image/avif") 2x,- url("gallery.jpg") type("image/jpeg") 1x,- url("gallery-2x.jpg") type("image/jpeg") 2x- );-}-```diff --git a/skills/modern-web/guides/user-experience/directional-navigation-transitions.md b/skills/modern-web/guides/user-experience/directional-navigation-transitions.mddeleted file mode 100644index 034a453..0000000--- a/skills/modern-web/guides/user-experience/directional-navigation-transitions.md+++ /dev/null@@ -1,123 +0,0 @@-Single Page Applications (SPAs) provide the appearance of navigation by replacing the content of the page without navigating to a new page. By default, the content is simply replaced, without any transitions. Directional transitions can visually reinforce a spatial relationship between views.--By sliding new content in from the direction the user is moving you create a mental map of the application structure. For instance, a product site may show a transition to the right for "forward," and to the left for "back", or a slideshow may transition up and down to show next and previous slides.--### Implementation Steps--1. **Detect Navigation Direction**: Determine if the user is moving "forward" or "backward" in the application flow. How you detect the direction depends on your use case.-2. **Trigger Transition with Types**: Pass the direction in a `types` array to `document.startViewTransition()` to categorize the transition.-3. **Define Directional Animations with CSS**: Use the `:active-view-transition-type()` pseudo-class to apply specific animations based on the navigation type.--### Defining Keyframes--Define sliding animations to and from each direction. For best performance, animate position changes using the `transform` property or the individual transform properties, `scale`, `rotate`, and `translate`. `opacity` is generally performant as well, but avoid animating other CSS properties without first verifying that they don't trigger layout or painting.--```css-/* Slide an element out to the left */-@keyframes slide-to-left {- /* Mandatory: animate `transform` instead of inset properties for better performance. */- to { transform: translateX(-100%); }-}--/* Slide an element in from the right */-@keyframes slide-from-right {- from { transform: translateX(100%); }-}--/* Slide an element out to the right */-@keyframes slide-to-right {- to { transform: translateX(100%); }-}--/* Slide an element in from the left */-@keyframes slide-from-left {- from { transform: translateX(-100%); }-}-```--### Set up shared animation settings--Use the `::view-transition-group(root)` selector to apply animation settings that are shared across all transitions.--```css-::view-transition-group(root){- animation: 0.4s ease-in-out both;-}-```--### Applying Directional Animations--Use the `active-view-transition-type` pseudo-class to target the transition views specifically when the "forward" or "backward" type is active.--```css-/* MANDATORY: Apply forward animations when the 'forward' type is active */-html:active-view-transition-type(forward)::view-transition-old(root) {- animation-name: slide-to-left;-}-html:active-view-transition-type(forward)::view-transition-new(root) {- animation-name: slide-from-right;-}--/* MANDATORY: Apply backward animations when the 'backward' type is active */-html:active-view-transition-type(backward)::view-transition-old(root) {- animation-name: slide-to-right;-}-html:active-view-transition-type(backward)::view-transition-new(root) {- animation-name: slide-from-left;-}-```--### Triggering the Transition--When navigating, pass the appropriate type to the `startViewTransition` method.--```javascript-const transitionType = yourTransitionTypeLogic();-const updateDOM = yourUpdateDOMLogic();--document.startViewTransition({- update: updateDOM,- types: [transitionType] // Matches the CSS :active-view-transition-type() selectors-});-```---### Accessibility--Always respect user preferences for reduced motion by disabling or simplifying animations.--```css-@media (prefers-reduced-motion: reduce) {- ::view-transition-group(root) {- animation: none !important;- }-}-```--### Fallback strategies--Baseline status for View transitions: Newly available. It's been Baseline since 2025-10-14.-Baseline status for Active view transition: Newly available. It's been Baseline since 2026-01-13.--The View Transitions API is a progressive enhancement. In unsupported browsers, `document.startViewTransition` will be `undefined`. You must wrap your navigation logic in a feature detection check to ensure the DOM update still occurs immediately without animation, as shown in this helper function.--```javascript-/**- * Navigates to a new view with a directional transition.- * @param {Function} updateDOM - Callback to update the DOM state.- * @param {string} direction - Either 'forward' or 'backward'.- */-function navigate(updateDOM, direction) {- // Feature detect for browsers that do not support View Transitions- if (!document.startViewTransition) {- updateDOM();- return;- }-- // Start transition with the specific navigation type- document.startViewTransition({- update: updateDOM,- types: [direction] // Matches the CSS :active-view-transition-type() selectors- });-}-```diff --git a/skills/modern-web/guides/user-experience/dynamic-sibling-animations.md b/skills/modern-web/guides/user-experience/dynamic-sibling-animations.mddeleted file mode 100644index 653d1a8..0000000--- a/skills/modern-web/guides/user-experience/dynamic-sibling-animations.md+++ /dev/null@@ -1,52 +0,0 @@-# Creating a stagger animation--Stagger animations provide an interesting effect where multiple ordered elements animate sequentially with a slight delay between each, rather than all animating at once. This technique is often used in lists, galleries, or navigation menus to guide the user's eye and add a polished, rhythmic feel to interactions.--## Stagger animations with `sibling-index()`--Use the `sibling-index()` property on the `animation-delay` property so that the animation on each element is offset by a number proportionate to their position in their parent. The `sibling-index()` function returns an integer, so it must be multiplied by a time unit to convert it to a time.--```css-#stagger-list > .item {- --stagger-time: 0.1s;- /* Define the animation first */- animation: fade-in 0.4s;- /* Set the `animation-delay` to a time multipled by the `sibling-index()` */- animation-delay: calc(sibling-index() * var(--stagger-time))-}-```--**MANDATORY:** Respect user preferences by disabling the animation for users who prefer reduced motion.--```css-@media (prefers-reduced-motion: reduce){- /* Disable animation for users who prefer reduced motion. */- #stagger-list > .item {- animation: none;- }-}-```--## Fallback strategies--sibling-count() and sibling-index() has limited availability.--Test for support for `sibling-index()` using CSS with `@supports (animation-delay: calc(sibling-index() * 0.1s)){}` or JavaScript with `!CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')`.--To support stagger animations in older browsers, use JavaScript to add a `--sibling-index` custom property to each sibling element. MANDATORY: wrap this in a `CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')` test to avoid running unneeded JavaScript.--```js-if(!CSS.supports('animation-delay: calc(sibling-index() * 0.1s)')){- const staggerList = document.getElementById('stagger-list');- [...staggerList.children].forEach((el, index)=>el.style.setProperty('--sibling-index', index + 1));-}-```--Add an `animation-delay` declaration that uses the `--sibling-index` custom property. It must be before the `animation-delay` declaration that uses the `sibling-index()` function. This does not need to be wrapped in `@supports` - older browsers will not parse the second declaration and will use the first declaration.--```css-#stagger-list > .item {- animation-delay: calc(var(--sibling-index) * var(--stagger-time));- animation-delay: calc(sibling-index() * var(--stagger-time));-}-```diff --git a/skills/modern-web/guides/user-experience/dynamic-sibling-styling.md b/skills/modern-web/guides/user-experience/dynamic-sibling-styling.mddeleted file mode 100644index 07ef8b1..0000000--- a/skills/modern-web/guides/user-experience/dynamic-sibling-styling.md+++ /dev/null@@ -1,96 +0,0 @@-# Styling siblings based on count and index--Historically, applying unique styles to each sibling in a list required complex `:nth-child` loops or JavaScript to inject inline styles. Modern CSS provides `sibling-index()` and `sibling-count()` to perform these calculations directly in your stylesheet, enabling dynamic layouts and color systems that automatically adapt as elements are added or removed.--## Dynamic color systems--You can create a color spectrum across a group of siblings by calculating a unique hue or lightness value for each child. This ensures a consistent gradient effect regardless of the number of items.--```css-.swatch {- /* Calculate hue by dividing the full 360deg circle by total siblings */- /* and multiplying by the current element's 1-based index */- background-color: hsl(- calc(360deg / sibling-count() * sibling-index()),- 70%,- 50%- );-}-```--## Symmetrical layout and fan effects--To create symmetrical effects (like a "fan" or centering items), use the total count to find the midpoint of the list.--```css-.card {- /* Find the center index (e.g., 3 if there are 5 siblings) */- --center: calc((sibling-count() + 1) / 2);-- /* Rotate items away from the center: negative for left, positive for right */- /* center element gets 0deg rotation */- transform: rotate(calc(10deg * (sibling-index() - var(--center))));-}-```--## Circular and complex positioning--By combining these functions with CSS trigonometry (`sin()`, `cos()`), you can place elements in a perfect circle without any manual coordinates.--```css-.orb {- /* Calculate the angle for this item's position on a 360deg circle */- --angle: calc(360deg / sibling-count() * sibling-index());- --radius: 150px;-- /* Set the pre-transformed position for all items to be centered */- position: absolute;- place-self: center;--- /* Position each element around the parent center */- transform: translate(- calc(cos(var(--angle)) * var(--radius)),- calc(sin(var(--angle)) * var(--radius))- );-}-```--### Fallback strategies--sibling-count() and sibling-index() has limited availability.--If `sibling-index()` and `sibling-count()` are not supported, provide a fallback by injecting CSS custom properties via JavaScript. **MANDATORY:** Use feature detection with `CSS.supports()` to ensure the script only runs when necessary.--```js-/* MANDATORY: Check for native support before applying fallback */-if (!CSS.supports('top: calc(sibling-index() * 1px)')) {- const items = document.querySelectorAll('.item');- items.forEach((item, index) => {- /* MANDATORY: Injected index must be 1-based to match native function */- item.style.setProperty('--sibling-index', index + 1);- item.style.setProperty('--sibling-count', items.length);- });-}-```--In your CSS, use these variables as a base and override them with native functions inside an `@supports` block. **MANDATORY:** You MUST wrap the native function overrides in `@supports` to ensure the variables remain valid in older browsers.--```css-.item {- /* 1. Set base values using variables (from JS fallback) */- --index: var(--sibling-index);- --count: var(--sibling-count);-- /* 2. Use the computed variables - replace this with your implementation-specific styles */- background-color: hsl(calc(360deg / var(--count) * var(--index)), 70%, 50%);-}--@supports (top: calc(sibling-index() * 1px)) {- .item {- /* 3. Override with native functions ONLY if supported */- --index: sibling-index();- --count: sibling-count();- }-}-```diff --git a/skills/modern-web/guides/user-experience/flicker-free-client-side-ab-testing.md b/skills/modern-web/guides/user-experience/flicker-free-client-side-ab-testing.mddeleted file mode 100644index 8fbb447..0000000--- a/skills/modern-web/guides/user-experience/flicker-free-client-side-ab-testing.md+++ /dev/null@@ -1,166 +0,0 @@-# Flicker-Free Client-Side A/B Testing--## The Problem--Client-side A/B testing tools work by loading a script that modifies the DOM after the browser has already begun constructing the page. Without intervention, the user briefly sees the original content before it flickers or flashes to the experiment variant. Testing platforms have historically worked around this with "anti-flicker snippets" that hide the entire page with `opacity: 0` until the experiment script finishes or an arbitrary timeout (typically 4 seconds) elapses. This approach sacrifices progressive rendering, allows accidental clicks on invisible content, and introduces unnecessary paint cycles.--## The Solution--The `blocking=render` attribute allows a `<script>` or `<link>` element placed in the `<head>` to block rendering—but not parsing—until the resource has been fetched and executed. This gives experimentation scripts the same render-blocking behavior that stylesheets have by default, ensuring the browser never paints the page until the experiment variant has been applied. No opacity hacks, no arbitrary timeouts, and no flicker.--### Implementation Strategy--1. **MANDATORY:** Place the experimentation script in the document `<head>` and add `blocking="render"`.-2. **MANDATORY:** Ensure the script either has `type="module"` (preferred for inline scripts) or `async` (preferred for external scripts with a `src` value).-3. **DO** keep the experimentation script small and fast. Because rendering is blocked until the script executes, a large or slow script directly delays first paint.-4. **DO NOT** use `blocking="render"` on scripts that do not need to run before first paint. It is intended only for scripts whose output must be visible in the initial render.-5. **DO NOT** apply `blocking="render"` to scripts outside the `<head>`. Only scripts in the `<head>` can block rendering.--## Implementation Guide--### Basic Setup--MANDATORY: Load the experimentation script with both `async` and `blocking="render"`. The `async` attribute ensures the script does not block HTML parsing (the browser continues building the DOM while fetching the script). The `blocking="render"` attribute ensures the browser does not paint anything until the script has executed.--```html-<head>- <!--- MANDATORY: Both `async` and `blocking="render"` are required.- - `async`: Prevents parser-blocking, so the DOM is built in parallel.- - `blocking="render"`: Holds rendering until the script executes,- ensuring experiment changes are applied before the user sees anything.- -->- <script- src="https://cdn.example.com/experiment-sdk.js"- async- blocking="render"- ></script>-</head>-```--### Loading Experiment-Specific Styles--If the experiment requires a variant stylesheet, use `blocking="render"` on the `<link>` element. Stylesheets in the `<head>` already block rendering by default, but dynamically injected stylesheets or those added via script do not. Use `blocking="render"` explicitly when the stylesheet is added dynamically or when you want to be explicit about the intent.--```html-<head>- <!--- DO: Use blocking="render" on experiment stylesheets that are- dynamically inserted or conditionally loaded by the experiment SDK.- This ensures variant styles are applied before first paint.- -->- <link- rel="stylesheet"- href="https://cdn.example.com/experiment-variant-b.css"- blocking="render"- >-</head>-```--### Inline Experiment Script--If the experiment logic is lightweight enough to inline, use an inline module script with `blocking="render"`. This is useful when the experiment logic fetches a configuration and applies DOM changes directly.--```html-<head>- <!--- DO: Use an inline module script when the experiment logic is small.- Module scripts are deferred by default (non-parser-blocking),- and blocking="render" ensures rendering waits for execution.- -->- <script type="module" blocking="render">- // Fetch the experiment configuration from your testing platform.- const config = await fetch('/api/experiment?id=homepage-cta')- .then(res => res.json());-- // Apply the variant by setting a data attribute on <html>.- // CSS rules keyed to this attribute will style the variant.- document.documentElement.dataset.variant = config.variant;- </script>-- <style>- /* Default styles (control group) */- .cta-button {- background-color: blue;- }-- /* Variant B styles, activated by the data attribute */- [data-variant="b"] .cta-button {- background-color: green;- }- </style>-</head>-```--## Best Practices--- **MANDATORY:** The experimentation script MUST execute quickly. A slow script delays all rendering. Set a performance budget (e.g., under 100ms execution time) for the render-blocking script.-- **DO** split heavy experiment logic from the render-blocking script. Load a small, render-blocking stub that applies the variant, then load heavier tracking or analytics scripts separately with `async` or `defer` (without `blocking="render"`).-- **DO** use a data attribute on `<html>` or `<body>` to signal the active variant, and use CSS selectors keyed to that attribute for variant styling. This avoids direct DOM manipulation in the render-blocking script.-- **DO NOT** use `blocking="render"` on analytics, tracking, or other non-visual scripts. Only scripts that must change what the user sees on first paint should block rendering.-- **DO NOT** combine `blocking="render"` with legacy anti-flicker snippets. They solve the same problem; using both creates unnecessary delays.--## Fallback Strategies--blocking="render" has limited availability.--The `blocking` attribute is not supported in all browsers. In browsers that do not support it, the attribute is ignored and the script loads with its default behavior (`async` in the examples above), which may result in flicker. A fallback is required to prevent flicker in unsupported browsers.--### Fallback: Anti-Flicker Snippet--DO: Use a lightweight anti-flicker snippet as a fallback only when `blocking="render"` is not supported. Feature-detect support and skip the fallback in browsers that handle it natively.--```html-<head>- <!--- DO: Load the experiment script with blocking="render" for- browsers that support it. This is the preferred approach.- -->- <script- src="https://cdn.example.com/experiment-sdk.js"- async- blocking="render"- ></script>-- <script>- // DO: Only apply the anti-flicker fallback in browsers- // that do not support blocking="render".- if (!Object.hasOwn(HTMLScriptElement.prototype, 'blocking')) {- // Hide the page until the experiment script runs.- document.documentElement.classList.add('ab-loading');-- // DO: Set a timeout to reveal the page if the experiment- // script takes too long. This prevents an indefinitely- // blank page on slow connections. Adjust the timeout- // to match your experiment SDK's expected load time.- setTimeout(() => {- document.documentElement.classList.remove('ab-loading');- }, 4000);- }- </script>-- <style>- /*- DO: Use opacity to hide content during experiment loading.- This is only applied when blocking="render" is unsupported.- */- .ab-loading {- opacity: 0 !important;- }- </style>-</head>-```--```javascript-// DO: In your experiment SDK's initialization callback,-// remove the fallback class to reveal the page.-function onExperimentReady() {- document.documentElement.classList.remove('ab-loading');-}-```--## Other Considerations--1. **Performance Impact**: `blocking="render"` trades first-paint speed for visual correctness. Monitor Largest Contentful Paint (LCP) and First Contentful Paint (FCP) to ensure the experimentation script is not adding excessive delay.-2. **Third-Party Script Reliability**: If the experiment SDK is hosted on a third-party CDN, a CDN outage could block rendering entirely. The browser applies its own timeout heuristics (which may be longer than 4 seconds), but there is no developer-controlled timeout for `blocking="render"`. Ensure the third-party provider has strong uptime guarantees.-3. **Server-Side Alternatives**: For performance-critical pages, consider server-side A/B testing (where the server renders the correct variant directly) instead of client-side testing. Server-side approaches eliminate flicker entirely without any render-blocking cost. Use client-side `blocking="render"` only when server-side testing is not feasible.diff --git a/skills/modern-web/guides/user-experience/fluid-scaling.md b/skills/modern-web/guides/user-experience/fluid-scaling.mddeleted file mode 100644index 2518947..0000000--- a/skills/modern-web/guides/user-experience/fluid-scaling.md+++ /dev/null@@ -1,77 +0,0 @@-## Overview--Fluid scaling allows components to adjust their internal proportions (like font sizes and spacing) based on their current dimensions. This creates a more cohesive design than jumping between fixed breakpoints.--While fluid scaling was historically achieved using viewport units (scaling based on the screen size), modern container query units allow components to scale relative to their parent container instead. This ensures components look good regardless of where they are placed in a layout, promoting better component isolation and reusability.--## Implementation--### 1. Define a container--To use container query units, you must first define a containment context on a parent element.--```css-.component-wrapper {- /* Define the container type. Use 'inline-size' for width-based scaling. */- /* You can also use 'size' for both width and height, but it requires explicit sizing. */- container-type: inline-size;-- /* Optional: Name the container for specific targeting */- container-name: fluid-card;-}-```--### 2. Use container query units--Use container query units (`cqi`, `cqb`, etc.) to set sizes relative to the container's dimensions.--* `cqi`: 1% of the container's inline size (width in horizontal writing modes).-* `cqb`: 1% of the container's block size (height in horizontal writing modes).--**Note**: Container units can be used directly on any property without needing an `@container` query rule. They automatically resolve based on the nearest ancestor with a defined `container-type`.--```css-.component-title {- /* Scale font size based on container width */- /* 10cqi means 10% of the container's width */- font-size: 10cqi;-}--.component-body {- /* Scale padding based on container width */- padding: 5cqi;-}-```--### 3. Constrain values with `clamp()`--To prevent sizes from becoming too small or too large, use the CSS `clamp()` function. This impacts the user's ability to zoom or adjust their base font size. To ensure text meets accessibility guidelines, the maximum size must not be more than 2.5 times the minimum size.--```css-.component-title {- /* Clamp font size between 1rem and 2.5rem, scaling with 5% of container width */- font-size: clamp(1rem, 5cqi, 2.5rem);-}-```--### Fallback strategies--Baseline status for Container queries: Widely available. It's been Baseline since 2023-02-14.--If container queries are not supported by the browser, you should provide a fallback using viewport units or standard media queries.--```css-.component-title {- /* Fallback for browsers that do not support container units */- font-size: clamp(1rem, 5vw, 2.5rem);-}--@supports (font-size: 1cqi) {- .component-title {- /* Use container units where supported */- font-size: clamp(1rem, 5cqi, 2.5rem);- }-}-```--This fallback ensures that the text still scales, but it will be based on the screen width rather than the component's width. This should be tested to verify it works in your use case.diff --git a/skills/modern-web/guides/user-experience/format-human-readable-durations.md b/skills/modern-web/guides/user-experience/format-human-readable-durations.mddeleted file mode 100644index 9dc691d..0000000--- a/skills/modern-web/guides/user-experience/format-human-readable-durations.md+++ /dev/null@@ -1,84 +0,0 @@-# Formatting Human-Readable Durations with Temporal--Presenting elapsed time or durations to users in a readable format (e.g., "1 hour and 30 minutes") has historically required manual math or external libraries. The `Temporal` API's `Temporal.Duration` class simplifies this by providing structured duration objects and powerful "balancing" capabilities via the `round()` method.--## How to Implement--To format a duration:--1. (**MANDATORY**) **Create a Duration**: Use `Temporal.Duration.from()` to create a duration object from a set of units.-2. (**OPTIONAL**) **Apply Balancing**: Use the `round()` method with the `largestUnit` option to control how units are balanced. For example, to convert 90 minutes into hours and minutes, or to keep it as total minutes.-3. (**MANDATORY**) **Build the Display String**: Access the specific unit properties (like `.hours`, `.minutes`) to construct the human-readable string manually, or **(Recommended)** use `Intl.DurationFormat` for a localized, automatic approach.--### Example: Balancing and Localized Formatting--```javascript-// 1. Create a duration (e.g., from user input)-const duration = Temporal.Duration.from({ minutes: 90 });--// 2. Balance to hours (converts 90 minutes to 1 hour and 30 minutes)-const balanced = duration.round({ largestUnit: 'hours' });--// 3. Format using Intl.DurationFormat (Handles pluralization automatically)-const formatter = new Intl.DurationFormat('en', { style: 'long' });-console.log(formatter.format(balanced));-// Note: Output may vary by browser (e.g., "1 hour and 30 minutes" or "1 hour, 30 minutes")-```--### Best Practices--* **DO** use `Temporal.Duration.round()` with `largestUnit` to control the display strategy (detailed breakdown vs total count).-* **DO** use `Intl.DurationFormat` for localized string formatting and automatic pluralization, or fall back to manual construction if not supported.-* **DO NOT** rely on `Temporal.Duration.prototype.toString()` for user-facing text; it returns ISO 8601 strings (e.g., `PT1H30M`).-* **DO** use feature detection and a polyfill for environments lacking native support.--## Fallback strategies--### Fallbacks & browser support for Temporal--Temporal has limited availability.--For browsers that do not yet support the native `Temporal` API, use feature detection and a polyfill. The standard reference polyfill is `@js-temporal/polyfill`.--Note that the polyfill does not automatically assign the `Temporal` object to the global scope to avoid conflicts. You must manually assign it if your code relies on the global `Temporal` object.--```javascript-// Check if Temporal is supported natively-(async () => {- if (typeof Temporal === 'undefined') {- // Load the polyfill conditionally- const module = await import("https://esm.sh/@js-temporal/polyfill");- globalThis.Temporal = module.Temporal;- // Extend Date.prototype if needed- Date.prototype.toTemporalInstant = module.toTemporalInstant;- initializeApp();- }-})();-```--### Intl.DurationFormat--Baseline status for Intl.DurationFormat: Newly available. It's been Baseline since 2025-03-04.--If `Intl.DurationFormat` is not supported, you should feature-detect it and fall back to manual string construction by extracting the balanced duration properties.--* **Guidance:** Use `typeof Intl.DurationFormat !== 'undefined'` to check for support. If unsupported, extract properties like `.hours` and `.minutes` from the balanced `Temporal.Duration` object and combine them, handling pluralization properly.--```javascript-// 3. Format the display string--if (typeof Intl.DurationFormat !== 'undefined') {- // Use recommended Intl API if available- const formatter = new Intl.DurationFormat('en', { style: 'long' });- console.log(formatter.format(balanced));-} else {- // Fallback manual formatting (assuming duration is already balanced)- const h = balanced.hours;- const m = balanced.minutes;-- const hoursStr = `${h} hour${h === 1 ? '' : 's'}`;- const minutesStr = `${m} minute${m === 1 ? '' : 's'}`;-- console.log(`${hoursStr} and ${minutesStr}`);-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/group-element-transitions.md b/skills/modern-web/guides/user-experience/group-element-transitions.mddeleted file mode 100644index 9e1daa4..0000000--- a/skills/modern-web/guides/user-experience/group-element-transitions.md+++ /dev/null@@ -1,123 +0,0 @@-As items are added or removed from a list, or rearranged, transitions can help users maintain context. View transitions provide a way to transition between two states of an element by giving the element a unique `view-transition-name`. When multiple elements on a page share the same transition behavior, `view-transition-class` allows you to define that logic once in CSS rather than repeating it for every unique `view-transition-name`. This keeps your stylesheets maintainable while ensuring consistent animations across a group of elements.--### Implementation steps--1. **Assign unique names and a shared class**--Each element that needs to be tracked individually during a transition must have a unique `view-transition-name`.--```html-<!-- Mandatory: Each element must have a unique view-transition-name -->-<li style="view-transition-name: item-1" class="item">Item 1</li>-<li style="view-transition-name: item-2" class="item">Item 2</li>-```--To apply shared styles, also assign a `view-transition-class`.--```css-.item {- view-transition-class: list-item;-}-```--2. **Define the shared transition logic**--Use the `::view-transition-group()` pseudo-element with the class selector to apply styles to all members of that group.--```css-/* Targets any view transition group that has the 'list-item' class */-::view-transition-group(.list-item) {- animation-duration: 0.5s;- animation-timing-function: ease-in-out;-}--/* Handle accessibility by respecting motion preferences */-@media (prefers-reduced-motion: reduce) {- /* Disable all group transitions, including the default `root` group. */- ::view-transition-group(*),- ::view-transition-old(*),- ::view-transition-new(*) {- animation: none !important;- }-}-```--3. **Optional: Define entry and exit animations**--Use the `:only-child` selector to add specific transitions to the elements that are added or removed. `::view-transition-new()` and `::view-transition-old()` pseudo-elements are children of a `::view-transition-image-pair()` pseudo-element, so we can determine it is an added or removed element if it is the only child.--```css-/* A `::view-transition-new()` element is the only child if it wasn't present before the view transition, so it is an added element. */-::view-transition-new(.list-item):only-child {- animation-name: slide-in;- /* Specify an animation duration if you want something different than the UA default of 0.5s */- animation-duration: 1s;-}-/* A `::view-transition-old()` element is the only child if it isn't present after the view transition, so it is a removed element. */-::view-transition-old(.list-item):only-child {- animation-name: slide-out;- /* Specify an animation duration if you want something different than the UA default of 0.5s */- animation-duration: 1s;-}--@keyframes slide-in {- from {- translate: -100vw 0;- }-}-@keyframes slide-out {- to {- translate: -100vw 0;- }-}-```--4. **Trigger the transition**--Wrap the DOM update in `document.startViewTransition()`. The browser will capture the old state, perform the update, and then animate to the new state.--```javascript-function updateList(newData) {- document.startViewTransition(() => {- // All DOM changes inside this callback will be transitioned- render(newData);- });-}-```--5. **Maintain interactivity of non-transitioned elements**--View transitions work by overlaying snapshots of the DOM elements, and then transitioning the snapshots. This means that during the transition, elements are not interactive. If there are interactive elements that are not transitioned, you can make them interactive by disabling touch events on the view transitions.--```css-::view-transition {- /* Non-transitioned elements below the view transitions remain interactive */- pointer-events: none;-}-```--In addition, by default, the `:root` element has a view transition named `root`, which enables default full-page transitions. If there are no changes to the root element, this will be a transition between two identical snapshots, which are not interactive. Because we are only transitioning specific elements, and not the entire screen, we can disable the `root` transition.--```css-:root {- /* Disable the root transition because we are only transitioning specific elements. */- view-transition-name: none;-}-```--### Fallback strategies--Baseline status for view-transition-class: Newly available. It's been Baseline since 2025-10-14.--View Transitions are a progressive enhancement. If the browser does not support `document.startViewTransition`, the DOM update should still occur immediately, providing a functional but non-animated experience.--```javascript-if (document.startViewTransition) {- document.startViewTransition(() => updateDOM());-} else {- // Fallback: Perform the update without animation- updateDOM();-}-```--For CSS, browsers that do not recognize `view-transition-class` or the `::view-transition-group()` class selector will simply ignore those rules, and no animation will be applied.diff --git a/skills/modern-web/guides/user-experience/improve-body-text-layout-and-legibility.md b/skills/modern-web/guides/user-experience/improve-body-text-layout-and-legibility.mddeleted file mode 100644index a8477a5..0000000--- a/skills/modern-web/guides/user-experience/improve-body-text-layout-and-legibility.md+++ /dev/null@@ -1,47 +0,0 @@-# Improve Body Text Layout and Legibility--The `text-wrap: pretty` CSS property allows you to improve the typographic quality of body text by enabling a more sophisticated wrapping algorithm. It is specifically designed to prevent "orphans" (single words on the last line of a paragraph) and create a more pleasing visual "rag" for long blocks of text.--## Implementation steps--1. **Identify long-form text elements**: Select elements potentially containing long runs of text where orphaned words (runts) or poor line breaks are most noticeable. This includes the following elements:- - `<p>`- - `<blockquote>`- - `<li>`- - Any other element potentially containing long runs of text.-2. **Apply pretty wrapping**: Use `text-wrap: pretty` to enable an optimized algorithm that evaluates the last few lines of a paragraph to find the best break points.--## Example: Optimizing Body Copy--```css-/* Apply to paragraphs to prevent orphaned words */-p {- /* MANDATORY: Enable pretty line-breaking logic */- text-wrap: pretty; /* Prioritizes typographic beauty for body copy */-}--/* Also effective for other multi-line text elements */-blockquote, li, .pretty-text {- /* MANDATORY: Enable pretty line-breaking logic */- text-wrap: pretty;-}-```--## Key constraints--* **Performance vs. Quality**: MANDATORY: `text-wrap: pretty` is more computationally expensive than the default `wrap` (greedy) algorithm because it evaluates multiple lines (typically the last four) to optimize the break points. Avoid applying it globally to every element if your page has an extreme amount of text content.-* **Best for multi-line text**: The benefits of `pretty` are most apparent in paragraphs of three or more lines. It has little to no effect on short, single-line text.-* **Browser-specific behavior**: Be aware that implementation details vary. Chromium-based browsers typically focus on the last four lines, while other engines may evaluate the entire paragraph.--## Fallback strategies--text-wrap: pretty has limited availability.--`text-wrap: pretty` is a progressive enhancement. Browsers that do not support the property will simply ignore it and fall back to the default wrapping behavior. This ensures that your content remains perfectly readable across all browsers while providing a superior experience to those that support it.--```css-/* No @supports block is needed for progressive enhancement */-p {- text-wrap: pretty; /* Supported browsers will prevent orphans; others will ignore this line */-}-```diff --git a/skills/modern-web/guides/user-experience/improve-heading-text-layout-and-legibility.md b/skills/modern-web/guides/user-experience/improve-heading-text-layout-and-legibility.mddeleted file mode 100644index e1f6052..0000000--- a/skills/modern-web/guides/user-experience/improve-heading-text-layout-and-legibility.md+++ /dev/null@@ -1,27 +0,0 @@-To improve the legibility and aesthetic appeal of short text blocks like headings, use `text-wrap: balance`. This property instructs the browser to distribute text as evenly as possible across lines, creating a more symmetrical appearance and preventing "widows" (a single word on the last line).--### Implementation--Apply `text-wrap: balance` specifically to short, multi-line elements such as headings (`h1`-`h6`), subheadings, or blockquotes.--```css-/* Target specific heading elements for balanced wrapping */-h1, h2, h3, .balanced-heading {- /* MANDATORY: Enables balanced line-breaking logic */- text-wrap: balance;-}-```--### Critical Constraints and Performance--* **Line Limit:** Browsers impose a limit on the number of lines they will attempt to balance to maintain performance (typically **6 lines** in Chromium and **10 lines** in Firefox). If the text exceeds this limit, the browser reverts to standard `wrap` behavior.-* **Targeted Application:** DO NOT apply `text-wrap: balance` globally (e.g., `* { text-wrap: balance; }`). The iterative "binary search" algorithm used by browsers is computationally expensive. Limit its use to specific, short text elements.-* **Interaction with Width:** `text-wrap: balance` does not change the container's width (`inline-size`). It only affects how text wraps *within* that width. This can leave empty space at the end of the container, which may affect layouts relying on full-width text blocks.--### Fallback strategies--Baseline status for text-wrap: balance: Newly available. It's been Baseline since 2024-05-13.--In browsers that do not support `text-wrap: balance`, the property is ignored, and the text will wrap using the default `wrap` behavior. This is a progressive enhancement that gracefully degrades to standard typography.--For critical layouts where manual control is required as a fallback, you can use traditional techniques like `<wbr>` (word break opportunity) or ` ` (non-breaking space) to influence line breaks, though these are less flexible than the native CSS property.diff --git a/skills/modern-web/guides/user-experience/individual-transform-properties.md b/skills/modern-web/guides/user-experience/individual-transform-properties.mddeleted file mode 100644index 8d5300d..0000000--- a/skills/modern-web/guides/user-experience/individual-transform-properties.md+++ /dev/null@@ -1,91 +0,0 @@-The `transform` property allows you to apply multiple transformations in a specified order, but any changes to a single transformation require re-specifying the entire transformation chain. This makes it tricky to animate or transition a single transformation.--The individual CSS transform properties (`translate`, `rotate`, and `scale`) allow you to apply transformations independently of the `transform` property. This approach makes it simpler to override a single transformation, for instance on `:hover`.--### Key Implementation Details--Individual transform properties are always applied in a **fixed order**, regardless of their order in your CSS:-1. `translate`-2. `rotate`-3. `scale`-4. `transform` (applied last)--If you require a different order (e.g., scaling *before* rotating), you must continue using the `transform` property functions.--Transform functions do not override the individual transform properties. In other words, `scale: 2; transform: scale(3);` will first scale by 2x, then again by 3x, for a total of 6x.--### Preventing Unexpected Changes in Stacking Contexts and Containing Blocks--The `transform` property and individual transform properties impact the layout and rendering of the page and may cause unexpected behavior with the z-index or anchor positioning. MANDATORY: If an element may have a transform applied as part of a state change like `:hover`, or a transition or animation, apply an identity transformation to the base element. This ensures that the element's stacking context and containment do not change when a transform is applied.--```css-.element{- /* MANDATORY: Apply identity transformations for properties that will- change on state changes (like :hover). This prevents unexpected layout- or z-index shifts caused by creating a new stacking context only on hover. */- translate: 0px;- rotate: 0deg;- scale: 1;-}-.element:hover{- translate: 10px 10px;- rotate: 20deg;- scale: 0.8;-}-```--### Independent Animation and Transitions--The primary benefit is the ability to define overlapping animations or transitions that target different properties without conflict.--```css-.card {- /* Define independent animations that don't overwrite each other */- animation: float 3s infinite ease-in-out;-- /* Transition only the scale property for hover states */- transition: scale 0.3s ease;-- /* Establish the base scale to prevent a sudden stacking context shift when transitioning on hover. */- scale: 1;-}--.card:hover {- /* Only the scale changes; the 'float' animation (translate) continues uninterrupted */- scale: 1.05;-}--@keyframes float {- 0%, 100% { translate: 0 0; }- 50% { translate: 0 -10px; }-}-```--### Fallback strategies--Baseline status for Individual transform properties: Widely available. It's been Baseline since 2022-08-05.--For browsers that do not support individual transform properties, use the traditional `transform` property. Note that this requires re-declaring the entire transform stack if you want to modify one part in a different state.--```css-.element {- /* Base transform */- transform: translate(100px, 0) rotate(45deg);- /* Specify the identity for the scale property. */- scale: 1;-}--@supports not (translate: 0px) {- .element:hover {- /* Fallback: Must repeat translate and rotate even if only scale changes */- transform: translate(100px, 0) rotate(45deg) scale(1.1);- }-}--@supports (translate: 0px) {- .element:hover {- /* Modern: Only declare the change */- scale: 1.1;- }-}-```diff --git a/skills/modern-web/guides/user-experience/interactive-content-reveal.md b/skills/modern-web/guides/user-experience/interactive-content-reveal.mddeleted file mode 100644index 02bbff4..0000000--- a/skills/modern-web/guides/user-experience/interactive-content-reveal.md+++ /dev/null@@ -1,116 +0,0 @@-Add performant, interactive reveal effects to your site with CSS masks and registered custom properties. By using a radial gradient as a mask and registering its stop values, we can smoothly transition the entry and exit, while following a user's pointer with minimal JavaScript.--## Implementation--### 1. Register Custom Properties-To enable smooth interpolation of gradient stop values, you must register the variables using `@property`. This informs the browser's engine about the data type, allowing it to transition between values during updates.--```css-/* Register the spotlight inner and outer sizes to enable interpolation */- @property --inner-size{- syntax: "<length-percentage>";- inherits: true;- initial-value: 0px;-}-@property --outer-size{- syntax: "<length-percentage>";- inherits: true;- initial-value: 0px;-}-```--The custom properties tracking the pointer position do not need to be transitioned, so it is not required to register them.--### 2. Define the Masking Layer-Apply the `mask-image` to the element you want to reveal. Use a `radial-gradient` that references the registered properties.--```css-.reveal-layer {- /* Only transition the size properties, NOT the position variables */- transition: --inner-size 0.2s ease-in-out, --outer-size 0.2s ease-in-out;-- /* The spotlight is defined by the transparent center of the mask */- mask-image: radial-gradient(- circle at var(--mouse-x) var(--mouse-y),- black var(--inner-size, 0%),- transparent var(--outer-size, 0%)- );-- /* Ensure the mask doesn't repeat if the element is large */- mask-repeat: no-repeat;-- /* Make the mask layer non-interactive */- pointer-events: none;-}--/* Update the gradients stops on interaction */-.reveal-layer:hover {- --inner-size: 100px;- --outer-size: 120px;-}-```--### 3. Update Coordinates with JavaScript-Track the pointer position and update the CSS variables. Because the properties are registered and have a `transition` defined, the spotlight will move smoothly even if the pointer events are infrequent.--```javascript-const container = document.querySelector('.container');-// Store the container's bounding rect-let rect = container.getBoundingClientRect();-// Update the rect when the container is resized-const resizeObserver = new ResizeObserver(()=>{- rect = container.getBoundingClientRect();-})-resizeObserver.observe(container);--container.addEventListener('pointermove', (e) => {- // Calculate position as a percentage of the container.- const x = ((e.clientX - rect.left) / rect.width) * 100;- const y = ((e.clientY - rect.top) / rect.height) * 100;-- // Update the registered properties- container.style.setProperty('--mouse-x', `${x}%`);- container.style.setProperty('--mouse-y', `${y}%`);-});-```--### 4. Accessibility and Interaction-MANDATORY: Ensure the reveal effect does not interfere with content accessibility. Avoid using this effect for revealing essential content.--* **Pointer Events:** If the reveal layer is an overlay, set `pointer-events: none` to allow users to interact with buttons or links underneath.-* **Non-Pointer Inputs:** Consider disabling the effect for users without a pointer using the `@media (pointer: none)` media query, especially if the revealed content is critical.-* **Reduced Motion:** Respect user preferences for reduced motion by disabling transitions or the effect entirely.--```css-@media (prefers-reduced-motion: reduce) {- .reveal-layer {- transition: none;- }-}-```--## Fallback strategies--Baseline status for Registered custom properties: Newly available. It's been Baseline since 2024-07-09.--### Non-registered Property Fallback-Browsers that support `mask-image` but not `@property` will still show the spotlight, but the movement will jump between on and off states because they cannot interpolate values inside a `radial-gradient`. Provide fallback values when using `var()`.--```css-.reveal-layer {- mask-image: radial-gradient(- circle at var(--mouse-x) var(--mouse-y),- /* Use fallback values when using the `var()` function for browsers that don't get an initial value from the @property registration. */- black var(--inner-size, 0%),- transparent var(--outer-size, 0%)- );-}-```--Baseline status for Masks: Newly available. It's been Baseline since 2023-12-07.--### Basic Mask Support--For browsers that do not support CSS masking at all:-1. **Prefixed property:** Use the `-webkit-mask-image` prefixed property for broader browser support.-2. **Progressive Enhancement:** Design the base state of the UI to be fully functional and legible without the reveal effect. This is useful when the effect is only adds visual flair, and not a requirement for reading content.diff --git a/skills/modern-web/guides/user-experience/interest-triggered-action-previews.md b/skills/modern-web/guides/user-experience/interest-triggered-action-previews.mddeleted file mode 100644index 66bda5b..0000000--- a/skills/modern-web/guides/user-experience/interest-triggered-action-previews.md+++ /dev/null@@ -1,74 +0,0 @@-It can be beneficial to provide users a preview of their actions before they commit to them. Interest invokers are an experimental web platform feature that provides a declarative-based way of creating interest relationships between an interest source (i.e. a button or a link) and an interest target. Once the declarative relationship has been established there are a number of methods a developer can respond to based on interest and loss of interest using both CSS and JavaScript. For this use case, we can leverage the `interest` and `loseinterest` events to preview various effects for an interest target.--## How to implement--An interest relationship is created by setting the `interestfor` attribute on a button or link (i.e. the interest source). The attribute takes an ID reference to another element (i.e. the interest target). Interest invokers or sources can only have a single interest target, but an interest target can have multiple interest invokers.--```html-<!-- MANDATORY: interest relationships must be established with the `interestfor` attribute on a button or a link -->-<button interestfor="interestingElement" data-effect="A">Some effect</button>-<button interestfor="interestingElement" data-effect="B">Some other effect</button>-<div id="interestingElement">Something interesting</div>-```--For the sake of this use case, we can leverage the `interest` and `loseinterest` events to preview various effects for an interest target. Both of these events are `InterestEvent`s which has a `source` property which is the source of the interest (i.e. the element with the `interestfor` attribute).--```javascript-interestingElement.addEventListener("interest", event => {- // Apply the preview based on `event.source`- event.target.dataset.preview = event.source.dataset.effect;-});--interestingElement.addEventListener("loseinterest", event => {- // Unapply the preview- delete event.target.dataset.preview;-});-```--Active interest sources and targets can be selected with CSS using the `:interest-source` and `:interest-target` pseudo-selectors respectively.--```css-/* Styles to apply when the effect is being previewed */-:interest-source {}-:interest-target {}-```--The start and end delay for an interest invoker (i.e. the element with the `interestfor` attribute) can be set with the `interest-delay-start` and `interest-delay-end` CSS properties or the shorthand `interest-delay` property.--```css-[interestfor] {- interest-delay-start: 0.2s;- interest-delay-end: 0.1s;-}-```--### Fallback strategies--Interest invokers has limited availability.--Interest invokers must be conditionally polyfilled with the `interestfor` polyfill, available at https://github.com/mfreed7/interestfor or on NPM. Do prefer bundling the polyfill over using the CDN.--```html-<script type="module">- if(!HTMLButtonElement.prototype.hasOwnProperty("interestForElement")){- // CDN link only used for example, prefer bundling.- await import("https://unpkg.com/interestfor@latest");- }-</script>-```--When using the polyfill the CSS API changes slightly for the `:interest-source` and `:interest-target` pseudo-classes, as well as, the `interest-delay`, `interest-delay-start`, and `interest-delay-end` properties:--```css-/* Styles to apply when the effect is being previewed */-:is(:interest-source, .interest-source) {}-:is(:interest-target, .interest-target) {}--/* Adjust the start and end delay for interest invokers */-[interestfor] {- --interest-delay-start: 0.2ms;- interest-delay-start: 0.2ms;- --interest-delay-end: 0.1ms;- interest-delay-end: 0.1ms;-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/interest-triggered-tooltips.md b/skills/modern-web/guides/user-experience/interest-triggered-tooltips.mddeleted file mode 100644index 51e616e..0000000--- a/skills/modern-web/guides/user-experience/interest-triggered-tooltips.md+++ /dev/null@@ -1,112 +0,0 @@-# Show a tooltip when hovering--Users expect to see additional related information without completely changing their context. Showing a tooltip when a user is interested in more information can be useful to provide definitions for a term, clarifying the action an icon-only button will take, or provide additional form field guidance.--## Creating the tooltip--You can create a popover with the required behavior by adding the `popover="hint"` attribute to a `<div>` or other semantically appropriate element. When the user opens the tooltip, this hides other `popover="hint"` tooltips, but doesn't hide `auto` or `manual` tooltips. It also handles dismissing nested tooltips.--It also provides light dismiss behavior, so when a user clicks or otherwise focuses outside of the popover, the popover is dismissed.--The tooltip element must have an `id` attribute with a unique value:--```html-<!-- MANDATORY: The tooltip container `<div>` must have a `popover` attribute.- the value of `"hint"` ensures it can be "light dismissed". -->-<div popover="hint" id="tooltip">Tooltip content</div>-```--A user expresses interest in the additional information by hovering or focusing on an `<a>` or `<button>` element. The element must have an `interestfor` attribute that matches the `id` attribute of the tooltip.--```html-<!-- The `interestfor` attribute can be applied to a `<button>` element: -->-<button interestfor="tooltip">Tooltip trigger</button>--<!-- The `interestfor` attribute can also be applied to an `<a>` element: -->-<a interestfor="tooltip" href="">Tooltip trigger</a>-```--The trigger must have a visual indicator to indicate that there is additional information available by interacting with the trigger.--### Positioning the tooltip--The tooltip can be positioned using anchor positioning. When the tooltip is opened using `interestfor`, the trigger becomes an implicit anchor for the tooltip, meaning you don't have to add `anchor-name` or `position-anchor` CSS properties. However, to support browsers without anchor positioning you must use the anchor positioning polyfill, which has several limitations for popovers. **MANDATORY:** Implicit anchors are NOT supported by the polyfill, so YOU MUST explicitly set an `anchor-name` on the trigger and `position-anchor` on the popover.---```css-/* MANDATORY: use explicit anchor names for compatibility with the polyfill */-button[interestfor="tooltip-dom"] {- anchor-name: --tooltip-dom;-}-#tooltip-dom {- position-anchor: --tooltip-dom;-}-```--Also, the polyfill does not support `position-area` on popovers, so **MANDATORY:** DO position using `anchor()` functions, and **YOU MUST** include a `position-try` fallback (e.g. `flip-block` or `flip-inline`).--```css-[popover]{- /* MANDATORY: use anchor functions and a position-try fallback for the polyfill */- top: anchor(bottom);- left: anchor(center);- position-try: flip-block;- margin: unset;-}-```---### Fallback strategies--Interest invokers has limited availability.--Interest invokers must be conditionally polyfilled with the `interestfor` polyfill, available at https://github.com/mfreed7/interestfor or on NPM. Do prefer bundling the polyfill over using the CDN.--```html-<script type="module">- if(!HTMLButtonElement.prototype.hasOwnProperty("interestForElement")){- // CDN link only used for example, prefer bundling.- await import("https://unpkg.com/interestfor@latest");- }-</script>-```--Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.-popover="hint" has limited availability.--Popover and popover hint must conditionally be polyfilled with the `@oddbird/popover-polyfill` polyfill. The hint behavior will not be polyfilled in browsers that support `popover` but not `popover="hint"`. For those browsers, a tooltip opened via focus may stay open when a second tooltip opened via hover.--```html-<script type="module">- if(!HTMLElement.prototype.hasOwnProperty("popover")){- await import("https://unpkg.com/@oddbird/popover-polyfill@latest");- }-</script>-```--Anchor positioning has limited availability.--**MANDATORY:** To support browsers without anchor positioning, you MUST use the `@oddbird/css-anchor-positioning` polyfill. It does not support implicit anchors, so you MUST add anchor names to the trigger. Additionally, `position-area` is not supported on popovers by the polyfill, so you MUST use `anchor()` on the desired insets.--```html-<!-- MANDATORY: Conditionally install the anchor positioning polyfill -->-<script type="module">- if (!("anchorName" in document.documentElement.style)) {- await import("https://unpkg.com/@oddbird/css-anchor-positioning");- }-</script>-```--```css-button[interestfor="tooltip-attrs"] {- /* MANDATORY: Each trigger and popover pair must have a unique anchor name, referenced by `anchor-name` on the trigger and `position-anchor` on the popover. */- anchor-name: --tooltip-attrs;-}-#tooltip-attrs {- position-anchor: --tooltip-attrs;- /* If using the anchor positioning polyfill with a popover, DO use `anchor()` functions, and not `position-area. */- top: anchor(bottom);- left: anchor(right);- margin: unset;-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/light-dismiss-a-dialog.md b/skills/modern-web/guides/user-experience/light-dismiss-a-dialog.mddeleted file mode 100644index ed1d9b9..0000000--- a/skills/modern-web/guides/user-experience/light-dismiss-a-dialog.md+++ /dev/null@@ -1,82 +0,0 @@-Modern modal dialogs often support "light-dismiss," allowing users to close a dialog by clicking or tapping the backdrop (the area outside the dialog). The `closedby` attribute provides a declarative way to enable this behavior without custom JavaScript.--## Implementation--To enable light-dismiss:--1. Add `closedby="any"` to the `<dialog>` element.-2. Open the dialog using `dialog.showModal()`.--### Attribute Values--- `any`: Enables light-dismiss (clicking the backdrop), "close requests" (the `Esc` key), and developer mechanisms (e.g., `dialog.close()`).-- `closerequest`: Enables "close requests" and developer mechanisms only. This is the default for modal dialogs.-- `none`: Only developer mechanisms can close the dialog.--### Styling the Backdrop-When a dialog is opened as a modal using `showModal()`, the browser generates a `::backdrop` pseudo-element. This backdrop covers the entire viewport and sits directly behind the dialog.--```css-/* Style the backdrop to indicate the dialog is modal */-dialog::backdrop {- background-color: rgba(0, 0, 0, 0.5);- backdrop-filter: blur(2px); /* Optional: add blur for modern browsers */-}-```--## Example--```html-<!-- MANDATORY: Use closedby="any" to enable light-dismiss behavior -->-<dialog id="myDialog" closedby="any" aria-labelledby="dialogTitle">- <form method="dialog">- <h2 id="dialogTitle">Feedback</h2>- <p>Click outside this box or press Esc to dismiss.</p>- <button type="submit">Close</button>- </form>-</dialog>--<button onclick="document.getElementById('myDialog').showModal()">Open Dialog</button>-```--## Constraints & Accessibility--- **MANDATORY**: Use `closedby="any"` to enable light-dismiss declaratively.-- **MANDATORY**: Always open modal dialogs with `showModal()`. This ensures the dialog is in the top layer, focus is trapped, and the `Esc` key is handled.-- **DO**: Use `aria-labelledby` or `aria-label` to provide an accessible name for the dialog.-- **DO NOT**: Use `closedby` for non-modal dialogs (opened with `show()`), as they do not have a backdrop and won't trigger light-dismiss.-- **DO NOT**: Use the `click` event for critical logic that should happen *before* closing; instead, listen for the `close` or `cancel` events.--## Fallback strategies--<dialog closedby> has limited availability.--**MANDATORY**: For browsers that do not yet support `closedby`, you **must** implement a fallback for light-dismiss by checking if a click occurred outside the dialog content's boundaries using the following script:--```javascript-const dialog = document.querySelector('dialog');--// Fallback for browsers without closedby support-if (!('closedBy' in HTMLDialogElement.prototype)) {- dialog.addEventListener('click', (event) => {- // 1. When clicking the backdrop, the event target is the dialog element itself.- // Ignore clicks where the target is a child element inside the dialog.- if (event.target !== dialog) return;-- // 2. Check if the click coordinates fall within the dialog's content box.- // This distinguishes between a click on the backdrop vs a click on the dialog's background/padding.- const rect = dialog.getBoundingClientRect();- const isDialogContent = (- rect.top <= event.clientY &&- event.clientY <= rect.top + rect.height &&- rect.left <= event.clientX &&- event.clientX <= rect.left + rect.width- );-- if (isDialogContent) return;-- // 3. Since the click was outside the content area (on the backdrop), manually close the dialog.- dialog.close();- });-}-```diff --git a/skills/modern-web/guides/user-experience/manage-recurring-intervals.md b/skills/modern-web/guides/user-experience/manage-recurring-intervals.mddeleted file mode 100644index 186239d..0000000--- a/skills/modern-web/guides/user-experience/manage-recurring-intervals.md+++ /dev/null@@ -1,71 +0,0 @@-# Managing Recurring Intervals with Temporal--Calculating recurring intervals, such as subscription billing cycles or payroll periods, has historically been error-prone with the legacy `Date` object. Adding a month to a date like January 31st is ambiguous (should it be February 28th/29th or March 3rd?).--The `Temporal` API provides a clean solution with `Temporal.PlainDate` and its `.add()` method, which handles month-end transitions predictably using configurable overflow strategies.--## How to Implement--1. **MANDATORY:** **Parse the starting date**: Use `Temporal.PlainDate.from()` to create a date object.-2. **MANDATORY:** **Add the duration**: Use the `.add()` method with a duration object (e.g., `{ months: 1 }`).-3. **OPTIONAL:** **Specify overflow behavior**: Use the `overflow` option to control how invalid dates (like Feb 31) are handled.- - `'constrain'` (default): Clamps to the last valid day of the month.- - `'reject'`: Throws a `RangeError`.--### Example: Subscription Billing Cycle--```javascript-// 1. Parse the start date (e.g., billing starts on Jan 31st)-const startDate = Temporal.PlainDate.from('2024-01-31');--// 2. Add 1 month with default 'constrain' overflow-// Jan 31 + 1 month -> Feb 29 (2024 is a leap year)-const nextBillingDate = startDate.add({ months: 1 });-console.log(`Next billing: ${nextBillingDate.toString()}`); // 2024-02-29--// 3. Add 1 month to Feb 29-// Feb 29 + 1 month -> Mar 29-// Note: Day is preserved if valid, otherwise constrained.-const thirdBillingDate = nextBillingDate.add({ months: 1 });-console.log(`Third billing: ${thirdBillingDate.toString()}`); // 2024-03-29--// Example with 'reject' strategy-try {- // Jan 31 + 1 month with 'reject' throws because Feb 31 is invalid- const invalidDate = startDate.add({ months: 1 }, { overflow: 'reject' });-} catch (e) {- console.log("Caught expected error:", e.name); // RangeError-}-```--## Strategic Implementation & Best Practices--- **DO** use `Temporal.PlainDate` for calculations that do not depend on specific times or time zones (like calendar dates or billing cycles).-- **DO** understand the default `constrain` behavior. It is usually what users expect for billing (e.g., Jan 31 -> Feb 28/29 -> Mar 28/29).-- **DO NOT** modify instances directly; `Temporal` objects are **immutable**. Operations return a new instance.-- **DO** use `overflow: 'reject'` if you need to enforce that the resulting date must exist in the calendar and handle failures explicitly.--### Fallback strategies--Temporal has limited availability.--For browsers that do not yet support the native `Temporal` API, use feature detection and a polyfill. The standard reference polyfill is `@js-temporal/polyfill`.--```javascript-// Check if Temporal is supported natively-(async () => {- if (typeof Temporal === 'undefined') {- // Load the polyfill conditionally- const module = await import("https://esm.sh/@js-temporal/polyfill");- globalThis.Temporal = module.Temporal;- // Extend Date.prototype if needed- Date.prototype.toTemporalInstant = module.toTemporalInstant;- initializeApp();- }-})();--function initializeApp() {- const date = Temporal.PlainDate.from('2024-01-31');- console.log(date.add({ months: 1 }).toString());-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/model-partial-time-concepts.md b/skills/modern-web/guides/user-experience/model-partial-time-concepts.mddeleted file mode 100644index a429676..0000000--- a/skills/modern-web/guides/user-experience/model-partial-time-concepts.md+++ /dev/null@@ -1,94 +0,0 @@-# Modeling Partial Time Concepts with Temporal--Modeling date concepts that lack a full calendar date—such as credit card expirations, annual renewals, or daily alarms—has historically been error-prone with the legacy `Date` object. Developers often resort to using arbitrary days (like the 1st of the month) or parsing strings, leading to "day leakage" or incorrect calculations due to leap years and varying month lengths.--The `Temporal` API provides dedicated types for these partial concepts: `Temporal.PlainYearMonth`, `Temporal.PlainMonthDay`, and `Temporal.PlainTime`. These types ensure precision and avoid leaking irrelevant date components.--## Implementation Examples--### Monthly Expirations (Credit Cards, Billing Cycles)-Use `Temporal.PlainYearMonth` to represent a year and a month.--```javascript-// Create a PlainYearMonth from values-// Use explicit calendar to avoid mismatch issues in polyfill environments-const expiry = Temporal.PlainYearMonth.from({ year: 2027, month: 12, calendar: 'iso8601' });--// Get the current year/month-const currentMonth = Temporal.Now.plainDateISO().toPlainYearMonth();--// Calculate duration until expiry-// largestUnit ensures the difference is expressed in years if applicable-const duration = currentMonth.until(expiry, { largestUnit: 'years' });--if (duration.sign < 0) {- console.log("Expired");-} else if (duration.sign === 0) {- console.log("Expires this month");-} else {- console.log(`Expires in ${duration.years} years and ${duration.months} months`);-}-```--### Annual Recurring Dates (Birthdays, Renewals)-Use `Temporal.PlainMonthDay` to represent a month and a day without a year.--```javascript-// Create a PlainMonthDay for an annual event-// Include explicit calendar for polyfill safety-const birthday = Temporal.PlainMonthDay.from({ month: 10, day: 31, calendar: 'iso8601' });--// Check if it matches today's date components-const today = Temporal.Now.plainDateISO();-const isBirthdayToday = birthday.equals(today.toPlainMonthDay());--// To perform arithmetic (like days until next occurrence), convert to a full PlainDate-// by providing a specific year.-const birthdayThisYear = birthday.toPlainDate({ year: today.year });-```--### Wall-Clock Time (Alarms, Store Hours)-Use `Temporal.PlainTime` to represent a time of day without a date.--```javascript-// Create a PlainTime from a string-const alarmTime = Temporal.PlainTime.from("08:00:00");--// Add a duration to a PlainTime-const snoozedTime = alarmTime.add({ minutes: 10 });--console.log(`Original alarm: ${alarmTime.toString()}`);-console.log(`Snoozed alarm: ${snoozedTime.toString()}`);-```--## Strategic Implementation & Best Practices--- **DO** use `Temporal.PlainYearMonth` for values that only specify a month and year (like credit card expiry) to avoid leaking arbitrary day values.-- **DO** use `Temporal.PlainMonthDay` for annual events that ignore the year (like birthdays or anniversaries).-- **DO** use `Temporal.PlainTime` for daily schedules or alarms that are independent of the date.-- **DO NOT** try to perform arithmetic directly on `PlainMonthDay`. Convert it to a `PlainDate` first by providing a year, as the length of months varies by year.-- **DO** use explicit calendar properties (like `calendar: 'iso8601'`) when creating instances from objects to ensure safety across polyfill implementations.--## Fallback Strategy--### Fallbacks & browser support for Temporal--Temporal has limited availability.--For browsers that do not yet support the native `Temporal` API, use feature detection and a polyfill. The standard reference polyfill is `@js-temporal/polyfill`.--Note that the polyfill does not automatically assign the `Temporal` object to the global scope to avoid conflicts. You must manually assign it if your code relies on the global `Temporal` object.--```javascript-// Check if Temporal is supported natively-(async () => {- if (typeof Temporal === 'undefined') {- // Load the polyfill conditionally- const module = await import("https://esm.sh/@js-temporal/polyfill");- globalThis.Temporal = module.Temporal;- // Extend Date.prototype if needed- Date.prototype.toTemporalInstant = module.toTemporalInstant;- initializeApp();- }-})();-```diff --git a/skills/modern-web/guides/user-experience/move-dom-element-without-losing-state.md b/skills/modern-web/guides/user-experience/move-dom-element-without-losing-state.mddeleted file mode 100644index c650206..0000000--- a/skills/modern-web/guides/user-experience/move-dom-element-without-losing-state.md+++ /dev/null@@ -1,55 +0,0 @@-When reparenting DOM elements using traditional methods like `appendChild()` or `insertBefore()`, the browser implicitly removes the element from the DOM and then inserts it into its new location. This "remove and insert" operation resets many internal states, causing `<iframe>` elements to reload, CSS animations to restart, and input fields to lose focus.--To move an element while preserving its state, use the `moveBefore()` API. This method performs an atomic move, completely bypassing the removal and insertion steps.--### Moving an element with state--Use `moveBefore()` exactly as you would use `insertBefore()`. It requires two arguments: the node to move, and a reference node to insert before (or `null` to append to the end of the new parent).--```javascript-const newParent = document.getElementById('new-parent');-const elementWithState = document.getElementById('iframe-or-focused-input');--// MANDATORY: Use moveBefore to preserve state.-// Passing null as the second argument appends the element to the end of newParent.-newParent.moveBefore(elementWithState, null);-```--### Moving custom elements (Web Components)--If you are moving custom elements using `moveBefore()`, their `connectedCallback` and `disconnectedCallback` lifecycle methods will **not** be fired.--If your custom element needs to perform specific logic when moved, implement the `connectedMoveCallback()` method inside the custom element definition.--```javascript-class MyCustomElement extends HTMLElement {- connectedCallback() {- // Runs on initial insertion.- }-- connectedMoveCallback() {- // Runs when the element is moved via moveBefore().- // Use this to update state that depends on the new DOM location.- }-}-```--### Fallback strategies--moveBefore() has limited availability.--Since `moveBefore()` is a progressive enhancement, you MUST use feature detection before calling it, falling back to traditional `insertBefore()` or `appendChild()` operations for older browsers.--```javascript-const targetParent = document.getElementById('target-container');-const nodeToMove = document.getElementById('moving-element');--// Check if moveBefore is supported on the Element prototype-if ('moveBefore' in Element.prototype) {- targetParent.moveBefore(nodeToMove, null);-} else {- // Fallback: traditional move.- // Note: This WILL reset <iframe>, animation, and focus state in unsupported browsers.- targetParent.insertBefore(nodeToMove, null);-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/navigation-drawer.md b/skills/modern-web/guides/user-experience/navigation-drawer.mddeleted file mode 100644index 15ff193..0000000--- a/skills/modern-web/guides/user-experience/navigation-drawer.md+++ /dev/null@@ -1,347 +0,0 @@-## Overview--A navigation drawer is a panel that slides in from the edge of the viewport over the page content, dimming everything behind it. It is opened from a trigger button and dismissed by swiping the panel off-screen, tapping the dimmed backdrop, or pressing Escape.--This guide implements the drawer as:--- A `popover="manual"` element promoted to the top layer so the panel and its `::backdrop` overlay every other element on the page, regardless of stacking context.-- A horizontally scrolling container with two CSS scroll-snap stops — one for "open", one for "closed" — so the swipe gesture is handled natively by the browser. This delivers momentum, velocity, and interruption tracking for free, with no JavaScript pointer-event code.-- A scroll-driven animation that ties the backdrop's opacity to the scroll position, so the dim fades in and out smoothly as the user drags the panel.-- An `IntersectionObserver` on the panel that detects when it has fully entered or fully left the viewport, and uses those moments to update focus, `aria-expanded`, and `inert`.--This approach is preferred over JavaScript-driven `transform` animations because the scroll mechanism gives the user direct control of the panel's position (their finger drives it, not a tween) and it much more closely matches the interaction patterns that users are accustomed to in native mobile apps.--## Implementation--### 1. Markup--The drawer is a single popover containing a horizontal scroller, which contains the visible "sheet". The trigger button lives in the page content.--```html-<!-- popover="manual" is REQUIRED. Do not use popover="auto" or "hint". -->-<div class="Drawer" id="drawer" popover="manual">- <div class="Drawer-scroller">- <nav class="Drawer-sheet" tabindex="-1">- <!-- tabindex="-1" makes the sheet programmatically focusable so we- can move focus into it when the drawer opens, without adding it- to the natural tab order. -->- <ul>- <li><a href="/page-1">Page 1</a></li>- <li><a href="/page-2">Page 2</a></li>- <!-- ... -->- </ul>- </nav>- </div>-</div>--<main>- <header>- <!-- aria-controls links the trigger to the drawer; aria-expanded- reflects the current state for assistive tech. -->- <button id="drawer-open"- aria-label="Open menu"- aria-expanded="false"- aria-controls="drawer">- <!-- menu icon SVG -->- </button>- </header>- <!-- Page content. -->-</main>-```--### 2. Styles--#### Reset the popover and fill the viewport--The popover must cover the whole viewport so its `::backdrop` dims the entire page and the swipe surface extends edge-to-edge. The default user-agent popover styles (centered, auto-sized, bordered) get in the way and must be reset.--```css-.Drawer {- /* min() caps the sheet width on large screens but on a phone leaves- a 20% peek of page content visible, which is the affordance that- tells the user they can tap outside to dismiss. */- --drawer-width: min(20em, 80dvw);-- /* Custom property driven by the scroll-driven animation below.- 0 = drawer fully closed (transparent backdrop).- 1 = drawer fully open (visible backdrop). */- --drawer-backdrop: 0;-- /* Reset UA popover style that would constrain the element. */- width: auto;- height: auto;- background: transparent;- border: 0;- overflow: visible;-}--/* Style the popover's ::backdrop to achive the overlay effect and- provide visual affordances indicating that the rest of the page is inert */-.Drawer::backdrop {- background: #000;- /* Use calc() to limit the opacity range so the content beneath is visible */- opacity: calc(var(--drawer-backdrop) / 2);-}-```--#### Build the swipe surface with scroll snap--The scroller is a horizontal grid wider than the viewport: column 1 holds the sheet (width `--drawer-width`), column 2 is an empty pseudo-element spacer the width of the viewport. Snapping between the two columns is what opens and closes the drawer.--```css-.Drawer-scroller {- position: relative;- display: grid;- /* Sheet on the left, full-viewport spacer on the right. The user- scrolls between the two snap stops to open and close. */- grid-template-columns: var(--drawer-width) 100%;-- overflow-x: scroll;- /* Stop the swipe from chaining into the page's vertical scroll- when the user reaches either snap edge. */- overscroll-behavior: none;- scrollbar-width: none;- /* `mandatory` guarantees the drawer always settles fully open or- fully closed — never half-open after a partial swipe. */- scroll-snap-type: x mandatory;-}--/* Enable smooth scrolling natively, but only if the user has not- requested reduced motion. */-@media (prefers-reduced-motion: no-preference) {- .Drawer-scroller {- scroll-behavior: smooth;- }-}--/* The empty spacer that creates the "closed" snap stop. */-.Drawer-scroller::after {- content: '';- scroll-snap-align: end;- /* Open the popover already scrolled to this stop (drawer off-screen),- so the JS only needs to scroll to the open position to- animate it in. */- scroll-initial-target: nearest;-}--.Drawer-sheet {- display: grid;- grid-template-rows: auto 1fr;- /* Use `svh` (small viewport height) — not `vh` or `dvh` — so the- sheet height does not jump when the iOS Safari address bar- resizes mid-swipe. */- height: 100svh;-- background: #333;- color: #fff;- overflow-y: auto;- scroll-snap-align: start;- scrollbar-width: none;-}-```--#### Tie the backdrop opacity to the scroll position--A scroll-driven animation maps `--drawer-backdrop` from 1 (open) to 0 (closed) across the scroller's range, so the backdrop fades in and out perfectly synced with the drag.--```css-/* MANDATORY: Wrap this entire block in @supports. Browsers that don't- support animation-timeline still parse the @keyframes and would- apply the animation's `0%` value (--drawer-backdrop: 1) at all- times, leaving the backdrop permanently opaque. The @supports gate- ensures the animation is only registered where it actually works. */-@supports (animation-timeline: scroll()) {- .Drawer {- /* timeline-scope lets .Drawer reference a scroll-timeline that- is defined on its descendant (the scroller). Without this, the- timeline name is not visible to the .Drawer element. */- timeline-scope: --drawer-fade;- animation: fade-drawer-backdrop linear both;- animation-timeline: --drawer-fade;- }-- .Drawer-scroller {- /* The horizontal scroll position of this element drives the- timeline named `--drawer-fade`. */- scroll-timeline: --drawer-fade x;- }-- /* @property is REQUIRED. Without registering --drawer-backdrop with- a `<number>` syntax, the browser treats it as a string and cannot- interpolate it — the backdrop would jump from 0 to 1 with no- fade. */- @property --drawer-backdrop {- syntax: '<number>';- inherits: true;- initial-value: 0;- }-- @keyframes fade-drawer-backdrop {- /* Scroll position 0 = drawer fully open = backdrop visible. */- 0% { --drawer-backdrop: 1 }- /* Scroll position 100% = drawer fully closed = backdrop hidden. */- 100% { --drawer-backdrop: 0 }- }-}-```--### 3. Open and close the drawer--Opening is two steps: promote the popover to the top layer, then scroll the sheet into view. Closing is one step: scroll back to the spacer; an observer (step 4) hides the popover once the sheet is fully off-screen.--```js-const drawer = document.getElementById('drawer');-const openBtn = document.getElementById('drawer-open');-const scroller = drawer.querySelector('.Drawer-scroller');-const sheet = drawer.querySelector('.Drawer-sheet');--function openDrawer() {- // Show the popover first so the element is in the top layer before- // we trigger any scrolling. `scroll-initial-target` (set on the- // ::after spacer) places the initial scroll position at the closed- // stop, so the drawer enters the top layer already off-screen.- drawer.showPopover();-- // Scroll the sheet into view. The `behavior: 'auto'` option defers- // to the CSS `scroll-behavior` property, which will be smooth unless- // the user prefers reduced motion. Snap takes over at the end and- // locks the drawer fully open.- scroller.scrollTo({left: 0, behavior: 'auto'});-}--function closeDrawer() {- // Scroll back to the spacer. Do NOT call hidePopover() here —- // doing so would remove the element from the top layer mid-animation- // and the close animation would not be visible. The- // IntersectionObserver in step 4 hides the popover once the sheet- // has actually left the viewport.- scroller.scrollTo({left: scroller.offsetWidth, behavior: 'auto'});-}-```--### 4. Detect open and closed state--Use an `IntersectionObserver` on the sheet — not the scroll position — as the source of truth for the drawer's state. The observer fires regardless of how the sheet moved (user swipe, programmatic scroll, snap settle), so all dismissal paths converge in the same callback.--```js-function onDrawerOpened() {- // Mark the rest of the page inert so keyboard and screen-reader- // users cannot tab into content hidden behind the drawer.- document.querySelector('main').inert = true;- openBtn.setAttribute('aria-expanded', 'true');- // Move focus into the drawer for keyboard users.- sheet.focus();-}--function onDrawerClosed() {- // Hide the popover only after the close animation completes,- // so the slide-out is visible to the user.- drawer.hidePopover();- document.querySelector('main').inert = false;- openBtn.setAttribute('aria-expanded', 'false');-}--// Treat "any pixel of the sheet visible inside the popover root" as-// "open enough to count as not closed". This threshold is intentionally-// tiny so the closed callback only fires once the sheet is truly gone.-const visibleThreshold = 1 / window.innerWidth;--const observer = new IntersectionObserver(- (entries) => {- // During programmatic scrolling the observer can deliver multiple- // entries in one batch. Only the most recent describes the- // current state; earlier entries are intermediate positions.- const entry = entries.at(-1);- if (entry.intersectionRatio < visibleThreshold) onDrawerClosed();- if (entry.intersectionRatio === 1) onDrawerOpened();- },- // root: drawer makes the popover element the intersection root,- // so the ratio reflects the sheet's visibility within the popover- // (i.e. how much of it has been swiped on-screen).- {root: drawer, threshold: [visibleThreshold, 1]},-);-observer.observe(sheet);-```--### 5. Wire up the trigger and dismissal handlers--```js-// Open trigger.-openBtn.addEventListener('click', openDrawer);--// Light-dismiss: a tap on the dimmed area (anywhere inside the-// popover but outside the sheet) closes the drawer. We implement-// this manually because popover="manual" disables the browser's-// built-in light-dismiss (which would also fire mid-swipe — see step 1).-drawer.addEventListener('click', (event) => {- if (!sheet.contains(event.target)) closeDrawer();-});--// Escape key. Listen on document because focus may be inside the-// drawer when the user presses Escape.-document.addEventListener('keydown', (event) => {- if (event.key === 'Escape') closeDrawer();-});-```--### Fallback strategies--The drawer's core mechanics — scroll snap, `IntersectionObserver`, and `inert` — are all Baseline Widely available and required for the component to function. The popover API, the scroll-driven animation that fades the backdrop, and `scroll-initial-target` are progressive enhancements with simple fallbacks that can be easily implemented if wide browser support is required.--#### Backdrop fade fallback (no `animation-timeline` support):--Scroll-driven animations has limited availability.--Detect with `CSS.supports('animation-timeline: scroll()')` and write `--drawer-backdrop` from a `scroll` event listener if not supported. The CSS `@supports` block in step 2 ensures the keyframes never apply in unsupported browsers, so the JavaScript value is the only writer.--```js-if (!CSS.supports('animation-timeline: scroll()')) {- scroller.addEventListener('scroll', () => {- // Same mapping as the @keyframes: 0 scroll = 1 (open),- // sheet-width scroll = 0 (closed).- const ratio = 1 - scroller.scrollLeft / sheet.offsetWidth;- drawer.style.setProperty('--drawer-backdrop', ratio);- });-}-```--#### Initial scroll position fallback (no `scroll-initial-target` support):--scroll-initial-target has limited availability.--Detect with `CSS.supports('scroll-initial-target', 'nearest')` and inside `openDrawer()`, jump-scroll the scroller to the closed position immediately after `showPopover()`. Without this, the drawer would appear instantly in the open position with no slide-in animation.--```js-async function openDrawer() {- drawer.showPopover();-- if (!CSS.supports('scroll-initial-target', 'nearest')) {- // Jump-scroll to the closed stop so the scroll below- // animates the drawer in from off-screen.- scroller.scrollTo({left: scroller.offsetWidth, behavior: 'instant'});- // Wait two animation frames for the jump-scroll to commit.- // A single rAF is not enough — the second `scrollTo` would- // cancel the first before the browser has a chance to apply it.- await new Promise((r) =>- requestAnimationFrame(() => requestAnimationFrame(r))- );- }-- scroller.scrollTo({left: 0, behavior: 'auto'});-}-```--#### `@property` fallback (no registered custom properties):--Baseline status for Registered custom properties: Newly available. It's been Baseline since 2024-07-09.--`@property` is only needed because the scroll-driven animation interpolates `--drawer-backdrop` between keyframes — without registration, the property would be treated as a string and would jump between 0 and 1 with no fade. If the scroll-driven animation fallback above is in place, that JavaScript writes a fresh numeric string to `--drawer-backdrop` on every scroll frame and never interpolates, so no seprarate `@property` fallback is needed since all browsers that support scroll-driven animations also support `@property`.---#### Popover API fallback (no `popover` attribute support):--Baseline status for the api.HTMLElement.showPopover capability: Newly available. It's been Baseline since 2024-04-16.--Because this component uses `popover="manual"` and implements dismissal entirely from JavaScript, it does not depend on the popover API's defining behaviors — light-dismiss, the `popovertarget` attribute, top-layer-managed Escape handling, or focus management. The only popover features it actually uses are top-layer promotion (via `showPopover()`) and the `::backdrop` pseudo-element, which have been Baseline since April 2024.--If wider browser support is needed, do not branch on feature detection — simply do not use popover at all. Drop the `popover="manual"` attribute, replace top-layer promotion with `position: fixed` and a high `z-index`, replace `::backdrop` with a sibling element styled identically (using the same `--drawer-backdrop` custom property), and toggle visibility from a class instead of `showPopover()`/`hidePopover()`. The rest of the component (scroll snap, the scroll-driven backdrop animation, the `IntersectionObserver`, and the dismissal handlers) is unchanged.diff --git a/skills/modern-web/guides/user-experience/parallax-scroll-effects.md b/skills/modern-web/guides/user-experience/parallax-scroll-effects.mddeleted file mode 100644index 412fa4f..0000000--- a/skills/modern-web/guides/user-experience/parallax-scroll-effects.md+++ /dev/null@@ -1,228 +0,0 @@-# Build a Parallax Effect on Scroll--A parallax effect on scroll is a visual technique where different layers of content move at varying speeds as the user scrolls down a page. This creates an illusion of depth, with foreground elements appearing to move faster than the background elements, resulting in an engaging and immersive browsing experience. This effect is best achieved using CSS Scroll-Driven Animations, which allow you to link animations to the scroll position of a container.--## How to implement--Here’s how to create a basic parallax effect:--1. **Create a wrapper element:** This element simply groups all the layers of the parallax effect together. It is not the scrollable element, so its overflow should be clipped. Also give it a `height` that matches the height of one of the layers of the parallax effect.-- ```html- <div class="wrapper">- …- </div>- ```-- ```css- .wrapper {- overflow: clip;- height: 100vh; /* Height of one of the layers of the parallax */- }- ```--2. **Declare the layers:** Inside the wrapper, add the individual layers that will move at different speeds.-- ```html- <div class="wrapper">- <div class="layer">LAYER 0</div>- <div class="layer">LAYER 1</div>- <div class="layer">LAYER 2</div>- …- </div>- ```--3. **Add a translate animation:** Define a CSS animation that changes the `transform` property of the layers. For a parallax effect, you'll typically use `translateY` to move the layers vertically.-- ```css- @keyframes parallax {- from {- transform: translateY(700px);- }- }- ```--4. **Set up the `view-timeline`:** To link the animation to the scroll position, create a `view-timeline` on the wrapper element and then apply it to the layers.-- ```css- .wrapper {- view-timeline: --wrapper;- }-- .layer {- animation: parallax linear both;- animation-timeline: --wrapper;- }- ```--5. **Stagger the animations:** To make the layers move at different speeds, you can use one of two main approaches: **staggering in the keyframes**, or **staggering the `animation-range`**.-- Both of these approaches can use hardcoded values, or can use the `sibling-index()`/`sibling-count()` implementation. The hardcoded values are easiest and also useful when having only a limited amount of layers. The `sibling-index()`/`sibling-count()` implementation is handy when you have many layers.-- * **Staggering in the keyframes:**-- Using **hardcoded values**, you can define a custom property for each layer to manually control its parallax offset.-- ```css- .layer:nth-child(1) { --offset: 100px; }- .layer:nth-child(2) { --offset: 200px; }- .layer:nth-child(3) { --offset: 300px; }-- @keyframes parallax {- from {- transform: translateY(var(--offset));- }- }- ```-- Using **`sibling-index()`**, let the `sibling-index()` function return the index of a child element amongst its siblings to automatically calculate the staggered effect.-- ```css- @keyframes parallax {- from {- transform: translateY(calc(100px * sibling-index()));- }- }- ```-- * **Staggering the `animation-range`:**-- Using **hardcoded values**, you can explicitly define the boundaries of the `animation-range` on each layer individually.-- ```css- .layer:nth-child(1) { animation-range: entry 25% exit 50%; }- .layer:nth-child(2) { animation-range: entry 25% exit 75%; }- .layer:nth-child(3) { animation-range: entry 25% exit 100%; }- ```-- Using **`sibling-index()` and `sibling-count()`**, you can calculate the range mathematically based on the total number of layers (`sibling-count()`).-- ```css- .layer {- animation-range: entry 25% exit calc(100% / sibling-count() * sibling-index());- }- ```--## Example code--```css-@keyframes parallax {- from {- transform: translateY(calc(100px * sibling-index()));- }-}--.wrapper {- view-timeline: --wrapper;-}--.layer {- animation: parallax linear both;- animation-timeline: --wrapper;-}--@media (prefers-reduced-motion: reduce) {- .layer {- animation: none;- }-}-```--Alternatively, you can use the `animation-range` property to achieve a similar effect:--```css-@keyframes parallax {- from {- transform: translateY(700px);- }-}--.wrapper {- view-timeline: --wrapper;-}--.layer {- animation: parallax linear both;- animation-timeline: --wrapper;- animation-range: entry 25% exit calc(100% / sibling-count() * sibling-index());-}--@media (prefers-reduced-motion: reduce) {- .layer {- animation: none;- }-}-```--## Best Practices--When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:--- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: view()) and (animation-range: entry))` to check for support and provide a fallback for browsers that don't support it.- - The `(animation-range: entry)` check **MUST** be included here, to filter out browsers with only partial support.- - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.- - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.-- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.-- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.-- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.--As for setting the `animation-range`:--- **DO** give all layers the same start offset, e.g. `entry 25%`-- **DO** give all layers a different end offset that uses `sibling-count()` and `sibling-index()` to distribute the offsets, e.g. `exit calc(100% / sibling-count() * sibling-index())`.---## Browser support and fallback strategies--Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.--For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).--In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.--Note that not every effect can be recreated using the fallbacks approach.--For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of the `.wrapper` element and updates the `transform` property of the layers based on the scroll position.--```js-// Fallback for browsers that don't support scroll-driven animations-if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {- const wrapper = document.querySelector('.wrapper');- const layers = document.querySelectorAll('.layer');-- const observer = new IntersectionObserver((entries) => {- entries.forEach(entry => {- if (entry.isIntersecting) {- window.addEventListener('scroll', onScroll);- } else {- window.removeEventListener('scroll', onScroll);- }- });- }, { threshold: 0 });-- observer.observe(wrapper);-- function onScroll() {- const scrollY = window.scrollY;- const wrapperRect = wrapper.getBoundingClientRect();- const wrapperTop = wrapperRect.top + scrollY;- const wrapperHeight = wrapperRect.height;- const windowHeight = window.innerHeight;-- if (scrollY >= wrapperTop - windowHeight && scrollY <= wrapperTop + wrapperHeight) {- const scrollPercent = (scrollY - (wrapperTop - windowHeight)) / (wrapperHeight + windowHeight);-- layers.forEach((layer, index) => {- // This matches the effect as defined in the CSS example above.- // Customize this further if needed.- const initialTranslateY = 100 * index;- const translateY = initialTranslateY * (1 - scrollPercent);- layer.style.transform = `translateY(${translateY}px)`;- });- }- }-- // Trigger onScroll once to set initial positions- onScroll();-}-```diff --git a/skills/modern-web/guides/user-experience/persistent-app-tours.md b/skills/modern-web/guides/user-experience/persistent-app-tours.mddeleted file mode 100644index e0d606f..0000000--- a/skills/modern-web/guides/user-experience/persistent-app-tours.md+++ /dev/null@@ -1,106 +0,0 @@-# Creating Persistent App Tours--Onboarding tours require overlays that persist while users interact with the highlighted features. Unlike auto popovers, manual popovers do not close when the user clicks elsewhere on the page. Combining `popover="manual"` with CSS Anchor Positioning allows you to create non-modal, tethered tour steps.--### Recommended Implementation--#### HTML-```html-<div id="feature-target">Highlight this feature</div>--<div id="tour-step" popover="manual">- <h3>Step 1</h3>- <p>Learn how to use this feature.</p>- <button popovertarget="tour-step" popovertargetaction="hide">Got it</button>-</div>-```--#### CSS-```css-#feature-target {- anchor-name: --feature-target;-}--#tour-step {- popover: manual;- position-anchor: --feature-target;- position-area: right center;- inset: auto;- margin: 1rem;- padding: 1rem;- border: 1px solid blue;- border-radius: 0.5rem;- background: aliceblue;-}-```--#### JavaScript-```javascript-document.getElementById('tour-step').showPopover();-```--### Implementation Guidelines--* **MANDATORY:** Use `popover="manual"` to prevent the tour step from closing accidentally during user interaction.-* **DO** use CSS Anchor Positioning to tether the tour step to the specific feature being explained.-* **DO** provide an explicit "Close" or "Next" button within the popover that uses `popovertargetaction="hide"`.--### Fallback strategies--#### popover--Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.--If the browser does not support Popover, use the `@oddbird/popover-polyfill`:--```html-<script type="module">- if (!HTMLElement.prototype.hasOwnProperty('popover')) {- await import('https://unpkg.com/@oddbird/popover-polyfill');- }-</script>-```--Alternatively, for legacy support without a polyfill, use `position: fixed` and manually calculate coordinates via JavaScript `getBoundingClientRect()`.--#### anchor-positioning--Anchor positioning has limited availability.--To support browsers without anchor positioning, you can choose between using a polyfill or a pure CSS fallback.--##### Option 1: Polyfill Fallback-The `@oddbird/css-anchor-positioning` polyfill can be used to emulate anchor positioning. It does not support implicit anchors, so you MUST add explicit anchor names to the trigger. Additionally, `position-area` is not supported on popovers by the polyfill, so you MUST use `anchor()` on the desired insets instead of `position-area`.--```html-<script type="module">- if (!CSS.supports('anchor-name: --foo')) {- await import("https://unpkg.com/@oddbird/css-anchor-positioning");- }-</script>-```--```css-#tour-step {- /* If using the anchor positioning polyfill with a popover, DO use `anchor()` functions instead of `position-area`. */- left: anchor(right);- top: anchor(top);-}-```--##### Option 2: Non-Polyfill CSS Fallback-If you prefer not to use a polyfill, you can default the tooltip to a fixed position at the bottom of the viewport using `@supports not`.--```css-@supports not (anchor-name: --foo) {- #tour-step {- position: fixed;- bottom: 0;- left: 0;- right: 0;- width: 100%;- margin: 0;- border-radius: 0;- }-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/persistent-toast-notifications.md b/skills/modern-web/guides/user-experience/persistent-toast-notifications.mddeleted file mode 100644index 51d8492..0000000--- a/skills/modern-web/guides/user-experience/persistent-toast-notifications.md+++ /dev/null@@ -1,30 +0,0 @@-# Creating Toast Notifications--Toast notifications are transient status messages. Unlike menus, they should not close when a user interacts with other parts of the page. The popover="manual" state is ideal because it lacks "light-dismiss" behavior and allows multiple notifications to coexist.--### Implementation Guidelines--* **MANDATORY:** Use popover="manual" so the notification stays visible until explicitly closed or timed out by a script.-* **DO** use a container to manage the stacking of multiple toasts. Since popovers in the Top Layer ignore parent z-index, you must position them individually or within a common layout group.-* **DO** use sibling-index() to add margin between toast notifications so that items lower in the stack are visible.-* **DO** provide an explicit "Close" button within the toast using popovertargetaction="hide".-* **DO** use JavaScript for auto-dismissal timers (e.g., calling hidePopover() after 3000ms).-* **DO** utilize transition-behavior: allow-discrete to animate the entry and exit from the Top Layer.--### Fallback Strategies--#### popover--* **Guidance:** Use the [Popover Polyfill](https://github.com/oddbird/popover-polyfill). For legacy browsers, fall back to a fixed-position div with a high z-index.--#### sibling-index()--* **Guidance:** If sibling-index() is not supported, use the `+` operator to add margin manually. I.e. `popover + popover { margin-top: 1rem }`--#### anchor-positioning--* **Guidance:** Use the [CSS Anchor Positioning Polyfill](https://github.com/oddbird/css-anchor-positioning). For a non-polyfill fallback, default the tooltip to a fixed position at the bottom of the viewport using `@supports not (anchor-name: --foo)`.--#### transition-behavior--* **Guidance:** If transition-behavior is not supported, use JavaScript to add animation via classes as the toast element transitions in and out.\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/persistent-top-layer-ui.md b/skills/modern-web/guides/user-experience/persistent-top-layer-ui.mddeleted file mode 100644index 318a1d7..0000000--- a/skills/modern-web/guides/user-experience/persistent-top-layer-ui.md+++ /dev/null@@ -1,46 +0,0 @@-When moving an open `<dialog>`, `popover`, or fullscreen element in the DOM using traditional methods like `appendChild()` or `insertBefore()`, the browser implicitly removes the element from the DOM and re-inserts it. This removal resets the state, causing open modals, popovers, and fullscreen elements to close abruptly.--To reparent top-layer elements without interrupting the user experience or closing them, use the atomic `moveBefore()` API instead.--### Reparenting open top-layer elements--`moveBefore()` takes two arguments: the node to move, and a reference node to insert before (or `null` to append to the end of the new parent).--```javascript-const newParent = document.getElementById('new-container');-const dialogElement = document.getElementById('my-dialog');--// MANDATORY: Use moveBefore to ensure the <dialog> or popover stays open.-// Passing null appends it to the end of newParent.-newParent.moveBefore(dialogElement, null);-```--### Fallback strategies--moveBefore() has limited availability.--Since `moveBefore()` is a progressive enhancement, you MUST use feature detection before calling it. For older browsers, you will have to fallback to traditional reparenting.--**MANDATORY**: For `<dialog>` elements in unsupported browsers, the traditional move will close the dialog. If you need it to remain open, you must manually re-open it after the move.--```javascript-const targetParent = document.getElementById('target-container');-const popoverOrDialog = document.getElementById('my-top-layer-element');--// Check if moveBefore is supported-if ('moveBefore' in Element.prototype) {- targetParent.moveBefore(popoverOrDialog, null);-} else {- // Fallback: traditional move.- // Note: This WILL close <dialog>, popover, and fullscreen elements.- const wasOpen = popoverOrDialog.hasAttribute('open') || popoverOrDialog.matches(':popover-open');- targetParent.insertBefore(popoverOrDialog, null);-- // Manually restore state if possible- if (wasOpen && typeof popoverOrDialog.showModal === 'function') {- popoverOrDialog.showModal();- } else if (wasOpen && typeof popoverOrDialog.showPopover === 'function') {- popoverOrDialog.showPopover();- }-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/physics-based-easing.md b/skills/modern-web/guides/user-experience/physics-based-easing.mddeleted file mode 100644index 1e307ff..0000000--- a/skills/modern-web/guides/user-experience/physics-based-easing.md+++ /dev/null@@ -1,117 +0,0 @@-Traditional CSS easing functions like `ease-in` or `cubic-bezier()` are limited to simple curves, making it impossible to create complex physics-based effects like bounces or springs. The `linear()` timing function solves this by allowing you to provide a series of stops that can approximate complex curves. Transitions and animations are interpolated based on straight lines between the stops, but within enough stops, it can appear smooth.--### Implementation Steps--1. **Generate the curve stops:**- Manually plotting dozens of points for a spring or bounce is impractical. Use a timing function from an external library, or use a tool to convert an existing JavaScript easing function or an SVG path into the `linear()` syntax. Optional: store these timing functions as CSS custom properties for reuse throughout your site.-2. **Define the timing function:**- Apply the generated stops to the `transition-timing-function` or `animation-timing-function` property, or through the `transition` or `animation` shorthands.-3. **Adjust the duration:**- Unlike JavaScript physics engines where duration is derived from physical properties (mass, stiffness), CSS still requires a fixed `duration`. You may need to adjust the duration to get the intended effect.--### Example: Spring Easing--This example shows how to use a custom `linear()` function to create a spring effect that overshoots the target value before settling.--```css-.spring {- /* Define the physics-based easing as a reusable variable */- --spring-easing: linear(0, 0.016 0.5%, 0.06 1%, 0.226 2%, 1.116 5.4%, 1.375 6.6%, 1.527 7.7%, 1.565 8.2%, 1.585 8.8%, 1.581 9.3%, 1.559 9.8%, 1.458 10.9%, 0.937 14.3%, 0.784 15.5%, 0.693 16.6%, 0.67 17.1%, 0.657 17.7%, 0.671 18.7%, 0.729 19.8%, 1.042 23.3%, 1.13 24.5%, 1.182 25.6%, 1.201 26.7%, 1.192 27.7%, 1.156 28.8%, 0.977 32.2%, 0.925 33.4%, 0.894 34.5%, 0.882 35.6%, 0.887 36.6%, 0.907 37.7%, 1.045 42.4%, 1.069 44.5%, 1.059 46.3%, 0.979 50.9%, 0.96 53.4%, 0.966 55.3%, 1.013 59.9%, 1.024 62.3%, 0.986 71.2%, 1.008 79.9%, 0.995 88.9%, 1);--- /* Apply the easing with a duration that fits the spring's complexity */- /* MANDATORY: Always include a duration; linear() does not calculate it automatically */- transition: scale 0.8s var(--spring-easing);-}--.spring:hover {- scale: 1.2;-}-```-### Example: Bounce Easing--This example shows how to use a custom `linear()` function to create a bounce effect.--```css-.bounce {- /* Define the physics-based easing as a reusable variable */- --bounce-easing: linear(0, 0.214 14.7%, 0.386 23.7%, 0.598 31.9%, 0.999 44.7%, 0.807 52.6%, 0.762 56%, 0.747 59.4%, 0.758 62.4%, 0.793 65.6%, 0.999 77.4%, 0.961 81.2%, 0.949 84.8%, 0.956 88%, 0.993 95.5%, 1);--- /* Apply the easing with a duration that fits the bounce's complexity */- /* MANDATORY: Always include a duration; linear() does not calculate it automatically */- transition: scale 0.4s var(--bounce-easing);-}--.bounce:hover {- scale: 1.2;-}-```--### Key Considerations--* **Performance:** For the smoothest physics-based animations, apply `linear()` to properties that run on a separate thread, such as `transform` and `opacity`.-* **Precision vs. Payload:** While more stops result in a smoother curve, they also increase the size of your CSS. Most generators allow you to "simplify" the curve to find the optimal balance between smoothness and code size.-* **Avoid Opacity for Bounces:** Applying bounce easings to `opacity` can cause visually jarring flickering if the value overshoots below 0 or above 1.-* **Accessibility:** Complex physics-based animations can be distracting or cause motion sensitivity for some users. Always respect user preferences by reducing or disabling these animations.--```css-@media (prefers-reduced-motion: reduce) {- .element {- transition: none;- }-}-```--### Fallback strategies--Baseline status for linear() easing: Newly available. It's been Baseline since 2023-12-11.--#### CSS Fallback-For browsers that do not support `linear()`, provide a standard easing function as a fallback. The browser will ignore the `linear()` value if it doesn't recognize it, falling back to the previous valid declaration.--```css-.element {- /* Fallback for older browsers (standard smooth exit) */- transition: transform 0.8s ease-out;-- /* Modern browsers will override with the physics-based easing */- transition-timing-function: linear(0, 1.1, 0.95, 1.02, 1);-}-```--#### JavaScript Library Fallback (Motion/GSAP)--Optional: If a high-fidelity physics animation is critical even in older browsers, use a JavaScript library like **Motion** (motion.dev) or **GSAP** (greensock.com) to handle the animation when `linear()` is unsupported.--1. **Detect support:** Use `CSS.supports()` to check if the browser handles the `linear()` function.-2. **Conditionally load/apply:** If unsupported, use the library's spring or bounce implementation.--```javascript-/* Detect if the browser supports the linear() function */-const supportsLinearEasing = window.CSS && CSS.supports('animation-timing-function', 'linear(0, 1)');--if (!supportsLinearEasing) {- /*- Example using Motion (motion.dev) for a spring fallback.- This should only be initialized if native CSS support is missing.- */- import("https://cdn.jsdelivr.net/npm/motion@latest/dist/motion.js").then(({ animate, spring }) => {- animate(".element", { transform: "scale(1.2)" }, {- easing: spring({ stiffness: 100, damping: 10 })- });- });-}-```--You can also use `@supports` in CSS for more explicit feature detection:--```css-@supports not (animation-timing-function: linear(0, 1)) {- .element {- /* Alternative experience for unsupported browsers */- transition-duration: 0.4s;- transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1);- }-}-```diff --git a/skills/modern-web/guides/user-experience/platform-controls-dismiss-dialog.md b/skills/modern-web/guides/user-experience/platform-controls-dismiss-dialog.mddeleted file mode 100644index 4fbbffe..0000000--- a/skills/modern-web/guides/user-experience/platform-controls-dismiss-dialog.md+++ /dev/null@@ -1,36 +0,0 @@-When a modal dialog is open, users expect to use familiar controls to dismiss them: pressing the <kbd>Esc</kbd> key on a keyboard, using the back button or gesture on mobile platforms, or a dismiss gesture with assistive technologies.--When the `<dialog>` element was first introduced, it could be dismissed with the <kbd>Esc</kbd> key, but not other platform controls such as a back button/gesture on mobile. With the addition of the `closedby` attribute for `<dialog>` elements, the extended behavior of responding to more platform-specific controls for close requests has been applied for `<dialog>` elements that are opened in a modal state (i.e. when opened imperatively with the `<dialog>` element’s `showModal()` method in JavaScript or declaratively with the `show-modal` invoker command). So, there is no specific change developers need to make if they are already using the `<dialog>` element.--```html-<!-- MANDATORY: must be opened with either `showModal()` with JavaScript or the `show-modal` command using declarative command invokers in order respond to close requests including platform-specific controls. -->-<dialog aria-labelledby="example">- <h1 id="example">Example</h1>- <p>Modal that can be dismissed with close requests.</p>-</dialog>-```--When opened in a modal state, a dialog without the `closedby` attribute responds to close requests the same as explicitly setting the `closedby` attribute to `closerequest`.--```html-<!-- This is unnecessary as it is the default behavior for modal dialogs -->-<dialog closedby="closerequest" aria-labelledby="example">- <h1 id="example">Example</h1>- <p>Modal that can be dismissed with close requests.</p>-</dialog>-```--If you also want “light dismiss” behavior, then you must set `closedby` to `any`:--```html-<dialog closedby="any" aria-labelledby="example">- <h1 id="example">Example</h1>- <p>Modal that can be dismissed with close requests and light dismiss.</p>-</dialog>-```--## Fallback strategies--<dialog closedby> has limited availability.--`<dialog>` elements opened in a modal state can already be dismissed with <kbd>Esc</kbd>, so there is no fallback necessary. There is no good way to implement close requests from mobile back button/gestures, so it is simpler to embrace this feature as a progressive enhancement, especially given that there are other inclusive means to dismiss the modal dialog. Similarly, light dismiss behavior for a `<dialog>` element using `closedby="any"` can be considered a progressive enhancement.\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/position-aware-tooltips.md b/skills/modern-web/guides/user-experience/position-aware-tooltips.mddeleted file mode 100644index 28966ff..0000000--- a/skills/modern-web/guides/user-experience/position-aware-tooltips.md+++ /dev/null@@ -1,151 +0,0 @@-When building tooltips or popovers with CSS Anchor Positioning, the browser can automatically "flip" the element to a fallback position if it would otherwise overflow the viewport. When this happens, you may want to adjust the style of the positioned content, for instance to reposition an arrow that points from the positioned content to the anchor.--**Anchored Container Queries** solve this by allowing you to query the active positioning state of an element and apply styles accordingly.--## The problem--Imagine a tooltip that appears above its anchor by default. It has a "down" arrow at the bottom. If the user scrolls and the tooltip flips to appear *below* the anchor, the arrow is now pointing the wrong way and is on the wrong side of the tooltip.--## The solution: Anchored Container Queries--By setting `container-type: anchored` on your positioned element, you turn it into a query container that knows about its own anchor-positioned state. You can then use the `@container anchored()` query to update its descendants or pseudo-elements.--### 1. Create the tooltip and trigger--Use the Popover API to create a tooltip. This creates an implicit anchor connection that can be used for positioning.--```html-<button popovertarget="tooltip" id="anchor">anchor</button>-<div id="tooltip" popover role="tooltip"></div>-```--Reset the popover inset and margin styles for use with anchor positioning, but only if anchor positioning is supported.--```css-@supports (anchor-name: --my-anchor) {- [popover] {- inset: auto;- margin: unset;- }-}-```--### 2. Set up the container--Apply `container-type: anchored` to the element being positioned. This element must also have `position-try-fallbacks` defined to enable the flipping behavior.--```css-#tooltip {- position: fixed;- position-area: block-start;- position-try-fallbacks: flip-block;-- /* Enable anchored container queries */- container-type: anchored;-}-```--### 3. Style based on the fallback--Use `@container anchored(fallback: <value>)` to apply styles when a specific fallback is active.--Like all container queries, `@container` can only style **descendants** of the container. A common strategy to create the arrows is with the `::before` and `::after` pseudo-elements, which are treated as descendants and can be styled directly. However, to style the tooltip itself (as seen in step 4), we will add a child element to the tooltip, and create the arrow in its `::before` pseudo-element.--```html-<div id="tooltip" popover role="tooltip">- <div class="tooltip-content">Tooltip</div>-</div>-```--```css-.tooltip-content::before {- /* Default "down" arrow for the 'top' position */- content: "▼";- position: absolute;- inset-block-end: 0;- inset-inline-start: 1rem;-}--/* Update to an "up" arrow when the 'flip-block' fallback (bottom) is active */-@container anchored(fallback: flip-block) {- .tooltip-content::before {- content: "▲";- inset-block-start: 0;- inset-block-end: auto;- }-}-```--## 4. Styling the container itself--If you need to change properties on the container itself (like `margin` or `background-color`) when it flips, you should use an **inner wrapper element**.--1. Apply `container-type: anchored` to the outer positioned element.-2. Target the inner element inside the `@container` block.---```css-@container anchored(fallback: flip-block) {- .tooltip-content {- border-radius: 0 0 .5rem .5rem;- margin-block-start: 0.25rem;- }-}-```--## Best practices--- **Prefer logical fallbacks**: Use keywords like `flip-block` and `flip-inline` in `position-try-fallbacks` for simpler queries that handle RTL and different writing modes automatically.-- **Use pseudo-elements for arrows**: Tooltip arrows are purely decorative and are perfect candidates for `::before` or `::after`, which can be styled via anchored container queries without extra DOM.---## Fallback strategies--Anchor position container queries has limited availability.--Positioning the arrow based on the applied fallback is a progressive enhancement, and there is not another way of reacting to the fallback position. To hide the arrow in browsers that don't support anchor position container queries, test for CSS support with `@supports (container-type: anchored)`.--```css-@supports (container-type: anchored) {- .tooltip-content::before {- content: "▼";- }-}-```--### Polyfilling the Popover Attribute--Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.--To support the `popover` attribute in older browsers, use the `@oddbird/popover-polyfill`.--MANDATORY: Feature detect popover support by checking for the `popover` property on the `HTMLElement` prototype. Conditionally initialize the polyfill only if native support is missing.--**Option 1: Using a package manager**-Install the package (`npm install @oddbird/popover-polyfill`).--```javascript-// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.-if (!('popover' in HTMLElement.prototype)) {- import('@oddbird/popover-polyfill/fn').then(({ apply }) => {- apply();- });-}-```--**Option 2: Manual installation without npm**-If you are not using a package manager, dynamically import the polyfill directly from a CDN (such as unpkg) inside a `<script type="module">`.--```html-<script type="module">- // MANDATORY: Feature detect 'popover' on HTMLElement.prototype.- // Conditionally load the popover-polyfill from a CDN only in browsers lacking native support.- if (!('popover' in HTMLElement.prototype)) {- import('https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover-fn.js').then(({ apply }) => {- apply();- });- }-</script>-```--Browsers without support for the Popover API also do not support anchor positioning, so the tooltip will appear in the center of the screen.\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/precise-text-alignment.md b/skills/modern-web/guides/user-experience/precise-text-alignment.mddeleted file mode 100644index 38b3991..0000000--- a/skills/modern-web/guides/user-experience/precise-text-alignment.md+++ /dev/null@@ -1,97 +0,0 @@-# Precise Text Alignment--## The Problem--Browsers automatically add extra whitespace above and below text characters to accommodate line-height and font-specific metrics like ascenders and descenders. This "ghost space" makes it impossible to achieve pixel-perfect vertical alignment using standard CSS.--Common issues include:-- **Misaligned Icons**: Text appears visually lower or higher than an adjacent icon even when using `align-items: center`.-- **Inaccurate Padding**: A button with `padding: 12px` visually appears to have more space on top or bottom because of the font's internal leading.-- **Flush Alignment**: You cannot align the top of a capital letter exactly with the top of a container or an adjacent image without using "magic number" negative margins.--## The Solution--The `text-box-trim` and `text-box-edge` properties (shorthand `text-box`) allow you to trim this internal leading based on specific font metrics. By trimming the text box to the **cap-height** (top of capital letters) and the **alphabetic baseline** (bottom of most letters), you can ensure that the element's bounding box matches its visual content.--### Implementation Strategy--1. **MANDATORY**: Apply `text-box-trim: trim-both` (or the `text-box` shorthand) to the element containing the text.-2. **MANDATORY**: Specify which metrics to use for trimming with `text-box-edge`. For most UI alignment, use `cap alphabetic`.-3. **DO** use this to achieve visual vertical centering in flex or grid containers.-4. **DO** use it to ensure that your CSS `padding` values match the visual gap between the text and the container edge.-5. **DO NOT** use it on long-form body text where traditional line-spacing is necessary for readability. It is best suited for headings, buttons, and UI labels.--## Implementation Guide--### Use case 1: Trim internal leading for badges--Different fonts have different amounts of built-in spacing above and below the text. This can provide challenges in matching a design, or in visually centering text in a badge. When you want a container's padding to exactly hug the text, use `text-box: trim-both cap alphabetic`. This is especially useful for dense UI components like badges or tags. This allows the padding to start right at the text edge on all sides.--```css-.badge {- padding: 10px;- background: hotpink;- border-radius: 10px;- /*- Trims the top to the cap-height and- the bottom to the alphabetic baseline.- */- text-box: trim-both cap alphabetic;-}-```--### Use case 2: Center text with icons--When using Flexbox to align text and icons, the "ghost space" often makes the text look slightly off-center. Trimming the box ensures the layout engine uses the actual visible letter height for alignment.--```css-.button {- display: inline-flex;- align-items: center;- gap: 8px;-}-/*- text-box does NOT inherit, and must be applied directly to the text element.-*/-.button-text{- /*- The flex container now centers against the- visible letters, not the invisible font box.- */- text-box: trim-both cap alphabetic;-}-```--### Use case 3: Align text flush with top edges--To align a heading perfectly with the top of an adjacent image or decorative element, use `trim-start cap alphabetic`. Even though the end will not be trimmed, the end edge must be defined.--```css-.hero {- display: flex;- align-items: flex-start;-}--h1 {- /* MANDATORY: The bottom edge must also be defined, even though only the top is trimmed. */- text-box: trim-start cap alphabetic;-}-```--## Best Practices--- **DO** use the `text-box` shorthand for conciseness: `text-box: <trim-direction> <edges>`.-- **DO** always specify both edges, even if only one edge is being trimmed (unless using the default `text` edge).-- **DO** combine with `line-height` for controlled spacing. Trimming removes the leading before the first and last line of text, but `line-height` still affects the distance between lines in multi-line text.-- **DO NOT** apply to every element. Use it only where precision alignment is a requirement.--### Fallback strategies--text-box has limited availability.--`text-box` is a progressive enhancement. In browsers that do not support it, the text will simply render with its default leading. Your layout will still be functional, though slightly less precise. No special fallback code is required as the properties are safely ignored by older browsers.--## Other Considerations--1. **Font Metrics**: Different fonts have different internal metrics. `cap alphabetic` is a reliable default, but some fonts or use cases may require `ex` (x-height) for better lowercase alignment.-2. **Multi-line Text**: Trimming applies to the first and last line of the block. Internal lines are not affected.diff --git a/skills/modern-web/guides/user-experience/prevent-text-wrapping.md b/skills/modern-web/guides/user-experience/prevent-text-wrapping.mddeleted file mode 100644index 5943958..0000000--- a/skills/modern-web/guides/user-experience/prevent-text-wrapping.md+++ /dev/null@@ -1,61 +0,0 @@-# Prevent text wrapping--Modern CSS provides the `text-wrap` property to control how text breaks within its container. To ensure text stays on a single line and ignores container boundaries, use `text-wrap: nowrap`. This is the modern, more semantic replacement for `white-space: nowrap`.--Preventing text wrapping is useful for UI elements like navigation tabs, horizontal scrolling chips, or any scenario where a line break would break the layout or visual design.--## How to implement `text-wrap: nowrap`--### Basic Usage--To prevent any automatic line breaks, apply `text-wrap: nowrap` to the element containing the text.--1. **MANDATORY**: Apply `text-wrap: nowrap` to the target element.-2. **OPTIONAL**: Use an `overflow` property (such as `hidden`, `scroll`, or `auto`) to manage the resulting overflow.-3. **OPTIONAL**: Use `text-overflow: ellipsis` to provide a visual cue when text is truncated. Note: This requires `overflow: hidden`.--### Example code--```css-.no-wrap-text {- /* MANDATORY: Prevents automatic line breaks */- text-wrap: nowrap;-- /* OPTIONAL: Handles the overflow visually */- overflow: hidden;- text-overflow: ellipsis;-- /* OPTIONAL: Constrain width to force and handle overflow within this element */- max-width: 200px;-}-```--### Specific Control with Longhands--The `text-wrap` property is a shorthand for `text-wrap-mode` (whether text wraps) and `text-wrap-style` (how it wraps). Since `text-wrap-style` is ignored when wrapping is disabled, you should generally stick to the `text-wrap` shorthand.--While the longhand `text-wrap-mode: nowrap` exists, the property name is currently considered a placeholder by the CSS Working Group and may change in the future.--```css-.granular-control {- /* Modern longhand equivalent to white-space: nowrap */- /* Preferred: text-wrap: nowrap; */- text-wrap-mode: nowrap;-}-```--### Fallback strategies--Baseline status for text-wrap: Newly available. It's been Baseline since 2024-10-17.--For browsers that do not yet support `text-wrap`, use the legacy `white-space` property. Modern browsers treat `white-space` as a shorthand for setting both the `text-wrap-mode` and `white-space-collapse` properties.--```css-.no-wrap-with-fallback {- /* Fallback for older browsers */- white-space: nowrap;-- /* Modern standard */- text-wrap: nowrap;-}-```diff --git a/skills/modern-web/guides/user-experience/pull-to-reveal.md b/skills/modern-web/guides/user-experience/pull-to-reveal.mddeleted file mode 100644index 55004c0..0000000--- a/skills/modern-web/guides/user-experience/pull-to-reveal.md+++ /dev/null@@ -1,81 +0,0 @@-# Pull to Reveal--"Pull to reveal" is a UI pattern where content (such as a search bar or refresh control) is hidden above the top of a scrollable area on initial load, and the user can pull down (scroll up) to reveal it. This pattern is commonly used in mobile apps and web apps for search bars, filters, and other secondary controls that should be accessible but not immediately visible.--The CSS property `scroll-initial-target` offers a declarative, CSS-only way to implement this pattern. By setting `scroll-initial-target: nearest` on the main content element, the scroll container will render with the hidden content scrolled out of view. Previously, developers relied on JavaScript (`Element.scrollIntoView()`) or URL fragment identifiers (`#content-id`) to achieve this, both of which have limitations and are tricky to implement.--## How to Implement--To implement a pull-to-reveal pattern:--1. **Ensure a scroll container:** The target element must be inside a scroll container (an element with overflow that allows scrolling, such as `overflow: auto`). This can be any ancestor element, including the root `<html>` element.-2. **Define the hidden element:** Place the content you want to hide (e.g., a search bar) as the first descendant inside the scroll container. This element will be scrolled out of view on initial load.-3. **Define the main content:** Place the main content element immediately after the hidden element. This is the element the user should see first.-4. **Target the main content:** Apply `scroll-initial-target: nearest` to the main content element so the scroll container renders with it scrolled into view, hiding the element above it.-5. **Add scroll snapping:** To ensure the hidden element is always either fully visible or fully hidden (and doesn't rest in a partially-scrolled state), add `scroll-snap-type: y mandatory` to the scroll container and `scroll-snap-align: start` to both the hidden element and the main content element.--## Example Code: Pull to Reveal Search--```css-/**- * ANCESTOR: Define the scroll container.- * Scroll snapping ensures the search bar is always- * either fully visible or fully hidden.- */-.scroll-container {- height: 100vh;- overflow-y: auto;- scroll-snap-type: y mandatory;-}--/**- * HIDDEN ELEMENT: The search bar hidden above the fold on load.- * It has scroll-snap-align so it snaps into place when pulled down.- */-.search-bar {- height: 60px;- scroll-snap-align: start;-}--/**- * MAIN CONTENT + TARGET: The element the user sees first.- * scroll-snap-align makes it a valid snap point.- * scroll-initial-target tells the browser to scroll here on- * initial render, hiding the search bar above it.- */-.main-content {- scroll-snap-align: start;- scroll-initial-target: nearest;-}-```--## Strategic Implementation & Best Practices--- **DO** use `scroll-initial-target: nearest` when you want to draw the user's attention to a specific part of a scrollable area upon load and intentionally hide peripheral UI units like a search bar at the very top.-- **DO NOT** confuse this with accessibility focus. This property only moves the **visual** viewport; it does not move the keyboard focus. You must manually manage `element.focus()` if the target is intended to be the starting point for keyboard users.-- **DO NOT** use this if you need a smooth "scrolling" animation on load; this property is discrete and sets the position instantly during the layout phase.-- **DO NOT** set `scroll-initial-target` on multiple elements within the same scrollable container. If multiple elements specify `scroll-initial-target: nearest`, the browser selects the one that appears first in the DOM tree order.-- **DO** account for the **Precedence Hierarchy**: A URL fragment (e.g., `example.com/#top`) and the container-level `scroll-start` property both take precedence over `scroll-initial-target`.--## Fallback Strategy--scroll-initial-target has limited availability.--For browsers that do not yet support the API, use a JavaScript fallback. Note that for pulling content to reveal, you want the main content to be bound to the `start` (top) of the container.--```javascript-/**- * Progressive Enhancement Fallback- */-document.addEventListener("DOMContentLoaded", () => {- // Check for native CSS support- if (!CSS.supports("scroll-initial-target", "nearest")) {- const targetContent = document.querySelector('.main-content.target');- if (targetContent) {- // Use behavior: "instant" to mimic the native CSS behavior- // 'block: start' should match your CSS 'scroll-snap-align' (or expected top position)- targetContent.scrollIntoView({ behavior: 'instant', block: 'start' });- }- }-});-```diff --git a/skills/modern-web/guides/user-experience/resilient-context-menus-and-nested-dropdowns.md b/skills/modern-web/guides/user-experience/resilient-context-menus-and-nested-dropdowns.mddeleted file mode 100644index fcc3704..0000000--- a/skills/modern-web/guides/user-experience/resilient-context-menus-and-nested-dropdowns.md+++ /dev/null@@ -1,96 +0,0 @@-A dropdown menu is a useful pattern for users to access additional functionality while taking up minimal space. This overlay pattern comes with layout complexity, as the menu must remain tethered to a trigger element while adapting to the viewport constraints. Traditionally, this required complex JavaScript libraries (like Popper.js or Floating UI) to calculate positions and handle collisions.--CSS Anchor Positioning provides a declarative, performance-optimized way to handle these relationships entirely in CSS, allowing browsers to manage the positioning and overflow logic.--### 1. Define the Button and Menu Relationship--The first step is to create a button that opens a dropdown menu, using the Popover API.--```html-<button popovertarget="dropdown-menu">- Open-</button>-<!-- Use the Popover API (`popover="auto"`) for the overlay to ensure it is placed in the top-layer and handled accessibly by the browser. -->-<div id="dropdown-menu" popover="auto">- <button class="menu-item" type="button">Edit</button>-</div>-```--This creates an *implicit* anchor association between the button and the menu, so that the menu can be positioned relative to the button.--### 2. Positioning with `position-area`--Instead of manual `top`/`left` offsets, use `position-area` to place the target on a 3x3 grid relative to the anchor.--```css-.menu {- /*- Position the menu below the anchor (block-end),- aligned to the start of the anchor and spanning to its end (span-inline-end).- */- position-area: block-end span-inline-end;-- /* Reset insets to allow the grid to take control */- inset: auto;-}-```--Prefer logical keywords (`span-inline-end`, `block-start`) over physical ones (`left`, `top`) to support RTL and different writing modes automatically.--**MANDATORY**: Do not mix physical and logical keywords in `position-area`.--### 3. Implement Edge-Resilience (Fallbacks)--To prevent the menu from being cut off at the edge of the screen, define "try tactics" that the browser should attempt if the default position overflows.--```css-.menu {- /*- If the menu overflows the bottom, flip it to the top (flip-block).- If it overflows the inline edges, flip it horizontally (flip-inline).- */- position-try-fallbacks: flip-block, flip-inline;-}-```--### Fallback strategies--Baseline status for Popover: Newly available. It's been Baseline since 2025-01-27.--Popover must conditionally be polyfilled with the `@oddbird/popover-polyfill` polyfill.--```html-<script type="module">- if(!HTMLElement.prototype.hasOwnProperty("popover")){- await import("https://unpkg.com/@oddbird/popover-polyfill@latest");- }-</script>-```--Anchor positioning has limited availability.--To support browsers without anchor positioning, you must set a reasonable position. By default popovers are centered in the middle of the screen, which may work for your use case.--For some use cases, you may be able to use the `@oddbird/css-anchor-positioning` polyfill, which adds support for some anchor positioning use cases. It does not support implicit anchors, so you MUST add anchor names to the trigger. Additionally, `position-area` is not supported on popovers by the polyfill, so you MUST use `anchor()` on the desired insets.--```html-<!-- MANDATORY: Conditionally install the anchor positioning polyfill -->-<script type="module">- if (!("anchorName" in document.documentElement.style)) {- await import("https://unpkg.com/@oddbird/css-anchor-positioning");- }-</script>-```--```css-.menu{- /* Mandatory: use explicit anchor name */- position-anchor: --kebab-anchor;- /* Mandatory: use insets rather that position-area for positioning */- bottom: auto;- right: auto;- top: anchor(bottom);- left: anchor(left);- margin: 0;-}-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/same-document-transitions.md b/skills/modern-web/guides/user-experience/same-document-transitions.mddeleted file mode 100644index e3fba69..0000000--- a/skills/modern-web/guides/user-experience/same-document-transitions.md+++ /dev/null@@ -1,166 +0,0 @@-# Same Document Transitions--## The Problem--Web sites often provide multiple views of an object, for instance a list of products, and then a detail page for each product. Navigating between the two views often feels disconnected. When a user clicks a product thumbnail to view its details, the thumbnail disappears and a new, larger image appears instantly elsewhere on the screen. This lack of continuity makes it harder for users to track relationships between elements.--## The Solution--The **View Transitions API** allows you to specify element pairs that exist in different states before and after a transition. When triggering a transition with `document.startViewTransition()` in a Single Page Navigation (SPA), the browser identifies these shared elements by their shared unique `view-transition-name`. It then automatically calculates the difference in their position, size, and styling, and animates them smoothly from the old state to the new state. This transition occurs in the top layer, above even elements with high `z-index` values.--## Implementation Guide--### Step 1: Wrap State Changes in `startViewTransition`--For Single-Page Applications (SPAs) or simple state changes, wrap the logic that updates the DOM in `document.startViewTransition`. The browser captures a snapshot of the current state, runs the update, and then captures the new state.--```javascript-function navigate(view) {- // MANDATORY: Wrap the update in startViewTransition- document.startViewTransition(() => updateDOM(view));-}-```--### Step 2: Assign Shared Transition Names--Use the `view-transition-name` CSS property to tell the browser which elements should be morphed. The name can be anything (except `none`). **MANDATORY**: there must be no more than 1 element before and after with a given `view-transition-name`. If there are 2 or more elements with a given `view-transition-name`, the DOM will be updated to the new state immediately, without a transition.--You can use multiple `view-transition-name`s to morph multiple pairs of elements. For example, you may want to transition both the product image and title with separate transitions.--Because there are multiple items on the list view, you can not give the all of them the same `view-transition-name`. This can be solved in two ways in a SPA.--1. **Dynamic detail page:** Assign each item on the list page a unique `view-transition-name`, and then dynamically apply that name to the matching element on the detail page when the list item is selected, as shown here.--```css-/* In the list view, give each */-#product-1 { view-transition-name: p1 }-#product-2 { view-transition-name: p2 }-#product-3 { view-transition-name: p3 }-```--```js-function updateDOM(clickedTransitionName){- const hero = document.getElementById("hero");- hero.style.viewTransitionName = clickedTransitionName;-}-```--2. **Dynamic list item:** Assign the element on the detail page a `view-transition-name`, and apply that name to the item on the list page when it is selected. Remove the `view-transition-name` from the item on the list page when returning to the list page.--The `#hero` element on the detail page and the selected `.thumbnail` element on the list page share a `view-transition-name`.--```css-#hero{- view-transition-name: hero;-}-.thumbnail.selected {- view-transition-name: hero;-}-```--When a thumbnail is clicked, we need to prepare the list view by assigning the `view-transition-name` using the `.selected` class selector, and making any changes to the DOM before starting the transition.--Then, you can call `document.startViewTransition()`, and apply the changes to transition the page from the detail to list view.--After navigating back to the list view, you must clean up the view transition classes to prevent the next navigation from erroring. You can perform this cleanup after the transition's `finished` promise resolves.--```javascript-// Function called when a thumbnail is clicked-function goFromListToDetail(e){- e.currentTarget.classList.add("selected");- const hero = document.getElementById("hero");- const bgColor = getComputedStyle(e.currentTarget).backgroundColor;- hero.style.background = bgColor;-- // Trigger the transition, checking for support- if (!document.startViewTransition) {- document.body.classList.add("detail");- return; // MANDATORY: End function execution if view transitions are not supported.- }- const transition = document.startViewTransition(() => {- document.body.classList.add("detail");- });-}--// Function called when navigating from detail back to list view-function goFromDetailToList() {- if (!document.startViewTransition) {- document.body.classList.remove("detail");- return;- }- const transition = document.startViewTransition(() => {- document.body.classList.remove("detail");- });- // Clean up the list view- transition.finished.finally(() => {- // Remove selected classList to remove view-transition-names- document.querySelectorAll(".selected").forEach(- (element) => {- element.classList.remove("selected");- },- );- });-}-```--The method you choose will depend on the use case. The dynamic list item requires less repeated CSS, but more manual JavaScript cleanup.---### Step 3: Fix Aspect Ratio "Stretching"--By default, the browser cross-fades the old and new snapshots within a group that stretches to fit both. If you are transitioning text, set the width of the text element to `fit-content` on both the old and new views, so that the transitioned element's aspect ratio is stable.--```css-#list-page .title {- width: fit-content;-}--#detail-page #title {- width: fit-content;-}-```--If you are transitioning elements that change aspect ratio, you may need to set the height of the old and new pseudo-elements to 100% of the `::view-transition-pair()` pseudo-element.--```css-::view-transition-old(hero),-::view-transition-new(hero){- height: 100%;-}-```--The pseudo-elements are snapshots of the live elements, so you can also use `object-fit` and `object-position` declarations for more control of the transitioning effect.--## Best Practices--- **DO NOT** specify too many transitions. Only use shared elements for primary content that the user is actively tracking (e.g., hero images, headings).-- **DO** remove temporary `view-transition-name` values after the transition finishes to avoid side effects on future transitions.-- **DO NOT** transition elements with active animations. View transitions operate on snapshots, so any animations will appear to be paused during the view transition.-- **DO** respect user preferences for reduced motion using the `prefers-reduced-motion` media query.--```css-@media (prefers-reduced-motion: reduce) {- ::view-transition-group(*),- ::view-transition-old(*),- ::view-transition-new(*) {- animation: none !important;- }-}-```--## Fallback Strategies--Baseline status for View transitions: Newly available. It's been Baseline since 2025-10-14.--The View Transitions API is designed for progressive enhancement. Browsers that do not support it will simply execute the DOM update immediately without animation.--```javascript-function navigate(){- if (!document.startViewTransition) {- // Fallback: Just update the DOM- updateDOM();- } else {- document.startViewTransition(() => updateDOM());- }-}-```diff --git a/skills/modern-web/guides/user-experience/scroll-entry-exit-effects.md b/skills/modern-web/guides/user-experience/scroll-entry-exit-effects.mddeleted file mode 100644index 8f5e462..0000000--- a/skills/modern-web/guides/user-experience/scroll-entry-exit-effects.md+++ /dev/null@@ -1,171 +0,0 @@-# Add entry and exit effects to elements as they enter or exit the scrollport--Entry and exit effects are animations that are triggered when an element enters or leaves the viewport. This can be used to create engaging and dynamic user experiences. For example, you can use an entry effect to fade in an element as it scrolls into view, or an exit effect to scale it down as it scrolls out of view.--## How to implement--To add entry and exit effects to an element, you need to combine a few CSS properties. Here’s a step-by-step guide:--1. **Create separate `@keyframes` for the entry and exit animations.** The entry animation will be applied as the element enters the viewport, and the exit animation will be applied as it leaves.-- ```css- @keyframes slide-in {- from { transform: translateX(-100%); }- }- @keyframes slide-out {- to { transform: translateX(100%); }- }- ```--2. **Attach the entry and exit keyframes to the element.** You can do this by defining multiple animations in the `animation` property.-- - Give the entry animation a `animation-fill-mode` of `forwards` so that it maintains its final state after the animation is complete.- - Give the exit animation a `animation-fill-mode` of `backwards` so that it doesn't affect the element before it starts.-- ```css- .animated-element {- animation:- slide-in 1s linear forwards,- slide-out 1s linear backwards;- }- ```--3. **Create a View Timeline and link it to the animations.** A View Timeline is a type of timeline that is linked to the visibility of an element in the viewport. You can create one using the `view()` function and then apply it to your animations using the `animation-timeline` property.-- ```css- .animated-element {- animation-timeline: view();- }- ```-- By default, `view()` tracks the element on the `block` axis. If you need to track it on the `inline` axis, you can use `view(inline)`.--4. **Limit the animations to the `entry` and `exit` ranges.** The `animation-range` property allows you to specify which part of the timeline an animation should run on.-- - The `entry` range covers the time from when the element first enters the viewport until it is fully visible.- - The `exit` range covers the time from when the element starts to leave the viewport until it is completely hidden.-- ```css- .animated-element {- animation-range: entry, exit;- }- ```--## Example code--This code animates the direct children of the scroller on scroll using an **anonymous view-timeline**:--```css-@media (prefers-reduced-motion: no-preference) {- @supports ((animation-timeline: view()) and (animation-range: entry)) {- @keyframes grow {- from {- scale: 0.5;- }- }- @keyframes shrink {- to {- scale: 0.5;- }- }-- .scroller > * {- animation:- grow auto linear backwards,- shrink auto linear forwards;- animation-timeline: view(inline);- animation-range: entry, exit;- }- }-}-```--As the elements enter the scrollport the `grow` animation is played, and as they leave the scrollport the `shrink` animation is played.--The following code has the same visual outcome, but animates the direct children of the scroller on scroll using an **named view-timeline**:--```css-@media (prefers-reduced-motion: no-preference) {- @supports ((animation-timeline: view()) and (animation-range: entry)) {- @keyframes grow {- from {- scale: 0.5;- }- }- @keyframes shrink {- to {- scale: 0.5;- }- }-- .scroller > * {- view-timeline: --tl inline;- animation:- grow auto linear backwards,- shrink auto linear forwards;- animation-timeline: --tl;- animation-range: entry, exit;- }- }-}-```--## Best Practices--When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:--- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: view()) and (animation-range: entry))` to check for support and provide a fallback for browsers that don't support it.- - The `(animation-range: entry)` check **MUST** be included here, to filter out browsers with only partial support.- - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.- - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.-- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.-- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.-- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` *after* it to prevent the shorthand from resetting the timeline.--When using the `view()` function to create a scroll-driven animation:--- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view(block)` or `view(inline)`.-- When the animation is not applied to the tracked subject itself, use a named view timeline.--When using the `view-timeline` property to create a scroll-driven animation:--- **DO** use a CSS `<dashed-ident>` for the name.-- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view-timeline-axis`.-- **DO** make sure the scope of the lookup works: When the element that is declaring the `view-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `view-timeline`’s name by using `timeline-scope` on a shared ancestor.--Prefer a named `view-timeline` when multiple elements or children of the tracked subject need to animate.--## Browser support and fallback strategies--Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.--For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).--In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.--Note that not every effect can be recreated using the fallbacks approach.--For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of the `.wrapper` element and updates the `transform` property of the layers based on the scroll position.--```html-<script>- if (!CSS.supports('(animation-timeline: view()) and (animation-range: entry)')) {- const observer = new IntersectionObserver(- (entries) => {- for (const entry of entries) {- // This matches the effect as defined in the CSS example above.- // Customize this further if needed.- entry.target.style.scale = 0.5 + entry.intersectionRatio * 0.5;- }- },- {- threshold: Array.from({ length: 101 }, (_, i) => i / 100),- }- );-- document.querySelectorAll('.scroller > *').forEach((el) => {- observer.observe(el);- });- }-</script>-```diff --git a/skills/modern-web/guides/user-experience/scroll-position-aware-elements.md b/skills/modern-web/guides/user-experience/scroll-position-aware-elements.mddeleted file mode 100644index 532f16f..0000000--- a/skills/modern-web/guides/user-experience/scroll-position-aware-elements.md+++ /dev/null@@ -1,126 +0,0 @@-## Overview--Improve the user experience of floating buttons, like a "Back to Top" link, by showing them only when they are useful. This guide shows how to build these elements using CSS `container-scroll-state-queries`, which allows styling elements based on the scroll position of their container without relying on JavaScript scroll listeners or observers.--## Implementation--### 1. Establish the Scroll Container--The scroll container must be declared as a scroll-state query container.--```css-.scroller {- overflow-y: auto;- /* Establish this element as a scroll-state query container */- container-type: scroll-state;-}-```--### 2. Style the Floating Element--Place the element inside the container and style it. By default, it should be hidden.--```css-.back-to-top {- position: sticky;- bottom: 20px;- visibility: hidden;- opacity: 0;- translate: 0 20px;- transition:- visibility 0.3s,- opacity 0.3s ease,- translate 0.3s ease;-}-```--> **Important:** Sticky or floating elements hover above the scrollable content. Ensure that the main content has sufficient bottom padding or margin so that the last few elements are not permanently covered by the button when the user scrolls completely to the bottom.--### 3. Respond to the Scroll State--Use the `@container` rule with the `scroll-state` function. To check if the user has scrolled down, check if the container is scrollable to the top.--```css-/* When the container can be scrolled toward the top, it means the user has scrolled down */-@container scroll-state(scrollable: top) {- .back-to-top {- visibility: visible;- opacity: 1;- translate: 0 0;- }-}-```--## Fallback strategies--Container scroll-state queries has limited availability.--### Basic Fallback-If `container-scroll-state-queries` is not supported, the floating element will remain invisible because of the default `visibility: hidden`. To ensure functionality, you can choose to make the element always visible in unsupported browsers.--```css-/* Fallback for browsers that do not support the feature */-.back-to-top {- visibility: visible; /* Always visible */- opacity: 1;-}--/* Override for supported browsers to handle dynamic visibility */-@supports (container-type: scroll-state) {- .back-to-top {- visibility: hidden;- opacity: 0;- }-- @container scroll-state(scrollable: top) {- .back-to-top {- visibility: visible;- opacity: 1;- translate: 0 0;- }- }-}-```--### Advanced Fallback (Intersection Observer)-If dynamic visibility is required, use an `IntersectionObserver` to toggle a class when a sentinel element at the top of the scroller goes out of view.--```html-<!-- Sentinel element placed at the top of the scroller -->-<div class="scroll-sentinel"></div>-```--```css-/* Marker styling to ensure it does not affect layout */-.scroll-sentinel {- height: 0;- width: 0;- visibility: hidden;-}--.scrolled .back-to-top {- visibility: visible;- opacity: 1;- translate: 0 0;-}-```--```javascript-if (!CSS.supports('container-type', 'scroll-state')) {- const sentinel = document.querySelector('.scroll-sentinel');- const scroller = document.querySelector('.scroller');-- const observer = new IntersectionObserver((entries) => {- entries.forEach(entry => {- // If the sentinel is NOT intersecting, it means the user has scrolled down- if (!entry.isIntersecting) {- scroller.classList.add('scrolled');- } else {- scroller.classList.remove('scrolled');- }- });- }, { root: scroller });-- observer.observe(sentinel);-}-```diff --git a/skills/modern-web/guides/user-experience/scroll-progress-indicator.md b/skills/modern-web/guides/user-experience/scroll-progress-indicator.mddeleted file mode 100644index f7d531e..0000000--- a/skills/modern-web/guides/user-experience/scroll-progress-indicator.md+++ /dev/null@@ -1,129 +0,0 @@-# Build a Scroll Progress Indicator--A scroll progress indicator is a common user interface pattern that visually communicates the user's progress through a scrollable document or container. As the user scrolls, a visual element updates to reflect their position, providing a clear and intuitive sense of how much content has been viewed and how much remains.--## How to implement--To create a scroll progress indicator, you need two things:--1. An element to act as the progress bar. This element is typically `position: fixed` or `position: absolute` so that it stays in view while the user scrolls.-2. An animation that is linked to the scroll position.--Here’s how you can achieve this:--- First, create an HTML element that will serve as your progress bar. This element can be styled to your liking.-- Next, in your CSS, define a `@keyframes` animation that scales the progress bar. A common approach is to scale the element from `scaleX(0)` to `scaleX(1)`.-- Finally, apply this animation to your progress bar element and set its `animation-timeline` to a scroll-timeline. This tells the browser to drive the animation's progress based on the scroll position of the nearest ancestor scroller.--## Example code--This code grows the `#progress` element on scroll using an anonymous scroll-timeline, created by the `scroll()` function.--```css-@media (prefers-reduced-motion: no-preference) {- @supports ((animation-timeline: scroll())) {- @keyframes grow-progress {- from { transform: scaleX(0); }- to { transform: scaleX(1); }- }-- #progress {- position: fixed;- left: 0; top: 0;- width: 100%; height: 1em;- background: red;-- transform-origin: 0 50%;- animation: grow-progress auto linear;- animation-timeline: scroll();- }- }-}-```--Because of its location in the DOM, the `scroll()` function will track its neareast ancestor scroller in the `block` direction, which here is the root scroller.--```html-<body>- <div id="progress"></div>-</body>-```--This code grows the `#progress` element on scroll using a named scroll-timeline, created by the `scroll-timeline` property.--```css-@media (prefers-reduced-motion: no-preference) {- @supports ((animation-timeline: scroll())) {- @keyframes grow-progress {- from { transform: scaleX(0); }- to { transform: scaleX(1); }- }-- :root {- scroll-timeline: --tl block;- }-- #progress {- position: fixed;- left: 0; top: 0;- width: 100%; height: 1em;- background: red;-- transform-origin: 0 50%;- animation: grow-progress auto linear;- animation-timeline: --tl;- }- }-}-```--## Best Practices--When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:--- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports (animation-timeline: scroll())` to check for support and provide a fallback for browsers that don't support it.- - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.- - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.-- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.-- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.-- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` *after* it to prevent the shorthand from resetting the timeline.--When using the `scroll()` function to create a scroll-driven animation:--- **OPTIONAL** be explicit about the scroller: When not targeting the nearest ancestor scroller, be explicit about which scroller you want to use with `scroll(root)` or `scroll(self)`.- - When `root`, `nearest`, or `self` are not sufficient, use a named scroll-timeline.-- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `scroll(block)` or `scroll(inline)`.--When using the `scroll-timeline` property to create a scroll-driven animation:--- **DO** use a CSS `<dashed-ident>` for the name.-- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `scroll-timeline-axis`.-- **DO** make sure the scope of the lookup works: When the element that is declaring the `scroll-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `scroll-timeline`’s name by using `timeline-scope` on a shared ancestor.--## Browser support and fallback strategies--Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.--For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).--In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.--Note that not every effect can be recreated using the fallbacks approach.--For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses a scroll listener to track the scroll position of the root element and updates the `transform` property of the progress bar accordingly.--```html-<script>- if (!CSS.supports('animation-timeline', 'scroll()')) {- const progress = document.querySelector('#progress');-- window.addEventListener('scroll', () => {- const scrollable = document.documentElement.scrollHeight - window.innerHeight;- const scrolled = window.scrollY;- const progressPercentage = (scrolled / scrollable);-- progress.style.transform = `scaleX(${progressPercentage})`;- });- }-</script>-```diff --git a/skills/modern-web/guides/user-experience/scroll-target-on-load.md b/skills/modern-web/guides/user-experience/scroll-target-on-load.mddeleted file mode 100644index b936963..0000000--- a/skills/modern-web/guides/user-experience/scroll-target-on-load.md+++ /dev/null@@ -1,54 +0,0 @@-# Set a scroll target for the initial render--The CSS property `scroll-initial-target` offers a declarative, CSS-only way to bring a specific descendant element into the visible area of its scroll container as soon as that container is rendered. Previously, developers relied on JavaScript (`Element.scrollIntoView()`) or URL fragment identifiers (`#item-id`), both of which have limitations and are tricky to implement.--## How to Implement--To implement this successfully:--1. **Ensure a scroll container:** The target element must be inside a scroll container (an element with overflow that allows scrolling, such as `overflow: auto`). This can be any ancestor element, including the root `<html>` element.-2. **Target the Item:** Apply `scroll-initial-target: nearest` to the specific descendant element you want to bring into view.--## Example Code: Vertical Media Feed--In this example, a feed starts scrolled to a specific "featured" item rather than the very top of the list.--```css-/**- * TARGET: The item that should be visible on initial load.- */-.item.target {- scroll-initial-target: nearest;-}-```--## Strategic Implementation & Best Practices--- **DO** use `scroll-initial-target` for "middle-start" experiences, such as a calendar starting on the current day or a gallery starting on a specific image.-- **DO NOT** confuse this with accessibility focus. This property only moves the **visual** viewport; it does not move the keyboard focus. You must manually manage `element.focus()` if the target is intended to be the starting point for keyboard users.-- **DO NOT** use this if you need a smooth "scrolling" animation on load; this property is discrete and sets the position instantly during the layout phase.-- **DO NOT** set `scroll-initial-target` on multiple elements within the same scrollable container. If multiple elements specify `scroll-initial-target: nearest`, the browser selects the one that appears first in the DOM tree order.-- **DO** provide dimensions for media. Since the scroll position is calculated during initial layout, ensure images or videos have `aspect-ratio` or fixed `height`/`width` to prevent the target from shifting after the media loads.-- **DO** account for the **Precedence Hierarchy**: A URL fragment (e.g., `example.com/#top`) and the container-level `scroll-start` property both take precedence over `scroll-initial-target`.--## Fallback Strategy--scroll-initial-target has limited availability.--For browsers that do not yet support the API, use a JavaScript fallback. Use the `DOMContentLoaded` event to ensure the browser scrolls the element into view as soon as the HTML parsing completes, providing a faster experience than waiting for all images and resources to load. Alternatively, placing the script at the end of the `<body>` element is also acceptable and avoids the need for an event listener.--```javascript-/**- * Progressive Enhancement Fallback- */-document.addEventListener("DOMContentLoaded", () => {- // Check for native CSS support- if (!CSS.supports("scroll-initial-target", "nearest")) {- const feedTarget = document.querySelector(".item.target");- if (feedTarget) {- // 'block: center' ensures the featured media is centered in view- feedTarget.scrollIntoView({ behavior: "instant", block: "center" });- }- }-});-```diff --git a/skills/modern-web/guides/user-experience/scrollability-affordance-hints.md b/skills/modern-web/guides/user-experience/scrollability-affordance-hints.mddeleted file mode 100644index 2175216..0000000--- a/skills/modern-web/guides/user-experience/scrollability-affordance-hints.md+++ /dev/null@@ -1,122 +0,0 @@-## Overview--Visual hints, like shadows or gradients, help users understand that they can scroll to see more content. This guide shows how to build these hints using CSS `container-scroll-state-queries`, which allows styling elements based on the scrollable state of their container without relying on JavaScript scroll listeners or observers.--## Implementation--### 1. Establish the Scroll Container--The scroll container must be declared as a scroll-state query container.--```css-.scroller {- overflow-y: auto;- /* Establish this element as a scroll-state query container */- container-type: scroll-state;- position: relative;-}-```--### 2. Style the Indicators--Place the indicator elements (like shadows, gradients, or arrows) inside the container and style them. By default, they should not be visible. When they are shown, they should not be interactive, by setting `pointer-events: none`.--```css-.indicator-top, .indicator-bottom {- position: sticky;- left: 0;- right: 0;- height: 20px;- opacity: 0;- transition: opacity 0.2s;- pointer-events: none; /* Let clicks pass through */-}--.indicator-top {- top: 0;- background: linear-gradient(to bottom, rgba(0,0,0,0.2), transparent); /* Example: Shadow */-}--.indicator-bottom {- bottom: 0;- background: linear-gradient(to top, rgba(0,0,0,0.2), transparent); /* Example: Shadow */-}-```--### 3. Query the Scroll State--Use the `@container` rule with the `scroll-state` function. Check if the container is scrollable up or down to show the respective indicator.--```css-/* Show top indicator when the user can scroll up */-@container scroll-state(scrollable: top) {- .indicator-top {- opacity: 1;- }-}--/* Show bottom indicator when the user can scroll down */-@container scroll-state(scrollable: bottom) {- .indicator-bottom {- opacity: 1;- }-}-```--## Fallback strategies--Container scroll-state queries has limited availability.--### Basic Fallback-If the feature is not supported, the indicators will remain invisible. Since these are hints and not critical for functionality, it is acceptable to omit them in unsupported browsers.--### Advanced Fallback (Intersection Observer)-If the hints are required, use an `IntersectionObserver` to toggle classes when sentinel elements at the top and bottom of the scroller move in and out of the scrollport.--```html-<!-- Sentinel elements placed at the ends of the scroller -->-<div class="sentinel-top"></div>-<!-- Content goes here -->-<div class="sentinel-bottom"></div>-```--```css-/* Marker styling to ensure it does not affect layout */-.sentinel-top, .sentinel-bottom {- height: 0;- width: 0;- visibility: hidden;-}--.scroller.scrolled-down .indicator-top {- opacity: 1;-}--.scroller.can-scroll-down .indicator-bottom {- opacity: 1;-}-```--```javascript-if (!CSS.supports('container-type', 'scroll-state')) {- const topSentinel = document.querySelector('.sentinel-top');- const bottomSentinel = document.querySelector('.sentinel-bottom');- const scroller = document.querySelector('.scroller');-- const observer = new IntersectionObserver((entries) => {- entries.forEach(entry => {- if (entry.target === topSentinel) {- // If top sentinel is not intersecting, we have scrolled down- scroller.classList.toggle('scrolled-down', !entry.isIntersecting);- }- if (entry.target === bottomSentinel) {- // If bottom sentinel is intersecting, we reached the bottom- scroller.classList.toggle('can-scroll-down', !entry.isIntersecting);- }- });- }, { root: scroller });-- observer.observe(topSentinel);- observer.observe(bottomSentinel);-}-```diff --git a/skills/modern-web/guides/user-experience/scrollytelling.md b/skills/modern-web/guides/user-experience/scrollytelling.mddeleted file mode 100644index 9272fdc..0000000--- a/skills/modern-web/guides/user-experience/scrollytelling.md+++ /dev/null@@ -1,161 +0,0 @@-# Scrollytelling--Scrollytelling is a popular technique used to create engaging and immersive web experiences. It involves animating elements on a page as the user scrolls, effectively telling a story or guiding the user through a narrative. With CSS Scroll-Driven Animations, you can create these effects directly in CSS, without needing to rely on JavaScript. The animations are controlled by the scroll position, not a time-based clock, which ensures they are always in sync with the user's scroll.--## How to implement--To create a scrollytelling experience, you need two sets of elements: one to track the scroll position and another to be animated.--First, define a named `view-timeline` on the elements you want to track. These will act as the drivers for your animations.--```css-#tracked {- section:nth-child(1){ view-timeline: --tl-1 block; }- section:nth-child(2){ view-timeline: --tl-2 block; }- section:nth-child(3){ view-timeline: --tl-3 block; }- section:nth-child(4){ view-timeline: --tl-4 block; }- section:nth-child(5){ view-timeline: --tl-5 block; }-}-```--Next, apply animations to the elements you want to animate and link them to the timelines you just created using the `animation-timeline` property.--```css-#animated {- section {- animation: animate-in auto linear both, animate-out auto linear forwards;- animation-range: entry 25% cover 50%, exit 50% exit 75%;- }-- section:nth-child(1){ animation-timeline: --tl-1; }- section:nth-child(2){ animation-timeline: --tl-2; }- section:nth-child(3){ animation-timeline: --tl-3; }- section:nth-child(4){ animation-timeline: --tl-4; }- section:nth-child(5){ animation-timeline: --tl-5; }-}-```--For the `animation-timeline` to be able to reference the named timelines, they need to be in the same scope. You can use the `timeline-scope` property on a common ancestor to make the timelines available to all the elements that need them. The `:root` element is often a good choice for this.--```css-html {- timeline-scope: --tl-1, --tl-2, --tl-3, --tl-4, --tl-5;-}-```--Finally, you can use the `animation-range` property to specify the exact range of the timeline during which the animation should run. This gives you fine-grained control over when the animations are triggered and how they progress.--```css-#animated section {- animation-range: entry 25% cover 50%, exit 50% exit 75%;-}-```--## Example code--```css-html {- timeline-scope: --tl-1, --tl-2, --tl-3, --tl-4, --tl-5;-}--#tracked {- section:nth-child(1){ view-timeline: --tl-1 block; }- section:nth-child(2){ view-timeline: --tl-2 block; }- section:nth-child(3){ view-timeline: --tl-3 block; }- section:nth-child(4){ view-timeline: --tl-4 block; }- section:nth-child(5){ view-timeline: --tl-5 block; }-}--@keyframes animate-in {- from { scale: 0.5; opacity: 0; transform: rotateY(-180deg); }- to { transform: rotateY(0deg); }-}-@keyframes animate-out {- to { translate: 100% 0; opacity: 0; }-}--#animated {- section {- animation: animate-in auto linear both, animate-out auto linear forwards;- animation-range: entry 25% cover 50%, exit 50% exit 75%;- backface-visibility: hidden;- }-- section:nth-child(1){ animation-timeline: --tl-1; }- section:nth-child(2){ animation-timeline: --tl-2; }- section:nth-child(3){ animation-timeline: --tl-3; }- section:nth-child(4){ animation-timeline: --tl-4; }- section:nth-child(5){ animation-timeline: --tl-5; }-}-```--## Best Practices--When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:--- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: scroll()) and (animation-range: 0% 100%))` to check for support and provide a fallback for browsers that don't support it.- - The `(animation-range: 0% 100%)` check **MUST** be included here, to filter out browsers with only partial support.- - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.- - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.-- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.-- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.-- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.--When using the `view-timeline` property to create a scroll-driven animation:--- **DO** use a CSS `<dashed-ident>` for the name.-- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `view-timeline-axis`.-- **DO** make sure the scope of the lookup works: When the element that is declaring the `view-timeline` is not a flat tree ancestor of the animated element, hoist up the visibility of the `view-timeline`’s name by using `timeline-scope` on a shared ancestor.--## Browser support and fallback strategies--Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.--For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).--In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.--Note that not every effect can be recreated using the fallbacks approach.--For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses an `IntersectionObserver` to track the visibility of each `#tracked section` element and updates the `transform` property of the corresponding `#animated section` accordingly.--```js-const animatedSections = document.querySelectorAll('#animated section');--const observer = new IntersectionObserver((entries) => {- entries.forEach(entry => {- const sectionIndex = Array.from(document.querySelectorAll('#tracked section')).indexOf(entry.target);- if (sectionIndex !== -1) {- const animatedSection = animatedSections[sectionIndex];- const ratio = entry.intersectionRatio;-- // Animate-in- animatedSection.style.opacity = ratio;- animatedSection.style.transform = `scale(${0.5 + ratio * 0.5}) rotateY(${-180 + ratio * 180}deg)`;-- // Animate-out- if (ratio < 0.5) {- animatedSection.style.translate = `${(0.5 - ratio) * 2 * 100}% 0`;- } else {- animatedSection.style.translate = '0 0';- }- }- });-}, { threshold: Array.from({length: 101}, (_, i) => i / 100) });--document.querySelectorAll('#tracked section').forEach(section => {- observer.observe(section);-});-```--And the accompanying CSS:--```css-#animated section {- opacity: 0;- transform: scale(0.5) rotateY(-180deg);- backface-visibility: hidden;-}-```--This fallback provides a more accurate, scroll-driven animation for browsers that do not support the native CSS feature, ensuring a more consistent experience for all users. By using a series of thresholds for the `IntersectionObserver`, we can track the scroll position with more precision and create a smoother animation.\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/search-hidden-content.md b/skills/modern-web/guides/user-experience/search-hidden-content.mddeleted file mode 100644index 9640fc1..0000000--- a/skills/modern-web/guides/user-experience/search-hidden-content.md+++ /dev/null@@ -1,129 +0,0 @@-# Search hidden content--Web interfaces often hide content from view to improve the user experience, save screen space, or increase page performance. Traditional methods like `display: none` or `visibility: hidden` work to hide content visually, but they also make that content completely inaccessible to screen readers and browser features like "Find in page".--To hide content visually but still allow it to be searchable by users and enable it to be deep linked to via URL fragments and "Scroll to Text Fragment" links, you can use either the HTML `<details>` element or the `hidden="until-found"` attribute. The `<details>` element is generally recommended as it's simpler to implement and maintain, but there are some more complex cases where `<details>` is not sufficient and `hidden="until-found"` is required.--For example:--- If you want full control over the styling of the show/hide mechanism.-- If the UI controls to show/hide the content are in another part of the DOM.-- If you don't want to support hiding the content after it's shown.--## How to implement--The `<details>` element has searchable and accessible text by default, and no special implementation is required. Prefer using `<details>` over `hidden="until-found"` if possible.--If you need to use `hidden="until-found"` instead, follow these instructions:--1. **Apply the attribute:** Add the `hidden="until-found"` HTML attribute directly to the elements containing the content that should be hidden from view.-2. **Synchronize UI state:** If the interface has related states that depend on the content's visibility (e.g., updating ARIA attributes, toggling open/close CSS classes, or rotating accordion icons):- - You **MUST** add an event listener for the `beforematch` event.- - Register the `beforematch` event listener directly on the element carrying the `hidden="until-found"` attribute. Since the event bubbles, you may alternatively use event delegation by registering a single listener on a parent element (such as a tab container) to manage multiple hidden sections at once.- - Inside the event listener, execute the logic to synchronize related UI elements (such as closing other open tabs or changing the state of a toggle button).--## Example code--**Goal:** Render a hidden container where the content remains invisible to the user until they search for a word within that section.--### Using `<details>` element--```html-<details>- <summary>Click to expand</summary>- <p>This content is visually hidden.</p>-</details>-```--#### Mutually exclusive content (e.g. tabs)--When handling mutually exclusive regions, like tabs, use the native HTML `<details>` element with a shared `name` attribute.--```html-<div class="tab-container">- <!-- The name attribute creates an exclusive accordion/tab group -->- <details class="tab" name="my-tabs">- <summary>Tab 1 (closed)</summary>- <p>Tab 1 content</p>- </details>-- <details class="tab" name="my-tabs" open>- <summary>Tab 2 (open)</summary>- <p>Tab 2 content</p>- </details>-- <details class="tab" name="my-tabs">- <summary>Tab 3 (closed)</summary>- <p>Tab 3 content</p>- </details>-</div>-```--### Using `hidden="until-found"` attribute--```html-<!-- The browser automatically removes hidden="until-found" upon a search match -->-<div class="hidden-container" hidden="until-found">- <p>This content is visually hidden.</p>-</div>-```--#### Mutually exclusive content (e.g. tabs)--When handling mutually exclusive regions, like tabs, ensure only the matched tab becomes visible. Since the `beforematch` event bubbles, you can listen on a parent container to manage state before the browser reveals the matched content.--```html-<div class="tab-container">- <div class="tab">- <p>Tab 1 content (visible)</p>- </div>-- <div class="tab" hidden="until-found">- <p>Tab 2 content (hidden)</p>- </div>-- <div class="tab" hidden="until-found">- <p>Tab 3 content (hidden)</p>- </div>-</div>-```--```javascript-const tabContainer = document.querySelector('.tab-container');--tabContainer.addEventListener('beforematch', () => {- // Hide all tabs before the browser reveals the matched tab- tabContainer.querySelectorAll('.tab').forEach((tab) => {- tab.hidden = 'until-found';- });-});-```--## Best practices for `hidden="until-found"`--- **DO** apply borders, padding, and backgrounds to nested child wrappers rather than directly to the element with the `hidden="until-found"` attribute. This prevents unintended layout shifts or visual remnants while the element is hidden.-- **DO NOT** apply `display: none`, `visibility: hidden`, or any associated `display` or `visibility` CSS properties directly to elements with the `hidden="until-found"` attribute. This breaks the native functionality and permanently hides the content from the search index.-- **DO NOT** use `hidden="until-found"` for sensitive information, internal data tokens, or irrelevant data that should not be exposed via search.-- **DO NOT** use `hidden="until-found"` as a replacement for "screen reader only" (.sr-only) text.--## Browser support and fallback strategies--The `<details>` element is Baseline Widely available, so a fallback strategy is not required.--The `hidden="until-found"` attribute is not yet Baseline Widely available, but it can be safely used with a fallback in unsupporting browsers. **DO NOT** avoid `hidden="until-found"` because of missing browser support, as its accessiblity benefits far outweigh the cost of implementing a fallback.--#### `hidden="until-found"` fallback--For standard UI elements like accordions or "Read more" sections, use JavaScript to feature-detect and show all content if the feature is unsupported.--```javascript-if (!('onbeforematch' in HTMLElement.prototype)) {- // Expand all hidden content for unsupported browsers- document.querySelectorAll('[hidden="until-found"]').forEach((el) => {- el.removeAttribute('hidden');- // MANDATORY: also update any aria references to this element.- });-}-```--For mutually exclusive UI paradigms (like tabs where content shares the same visual region), the fallback should extract and display all content linearly below the main interactive area, using URL anchor fragments to allow users to navigate directly to the respective sections.diff --git a/skills/modern-web/guides/user-experience/shrinking-header-on-scroll.md b/skills/modern-web/guides/user-experience/shrinking-header-on-scroll.mddeleted file mode 100644index 5ad4254..0000000--- a/skills/modern-web/guides/user-experience/shrinking-header-on-scroll.md+++ /dev/null@@ -1,124 +0,0 @@-# Shrinking headder on scroll--A shrinking header on scroll is a common UI pattern where a fixed header element at the top of the page smoothly transitions to a smaller size as the user scrolls down. This effect is often used to maximize screen real estate for the main content while keeping essential navigation or branding elements accessible. With CSS scroll-driven animations, this effect can be achieved in a declarative and performant way, by linking an animation to the scroll position of the document.--## How to implement--Here’s how to create a shrinking header on scroll:--1. **Create a fixed header:** Start with a header element that is fixed to the top of the page and has a predefined height.-- ```html- <header>HEADER</header>- ```-- ```css- header {- position: fixed;- height: 200px;- top: 0;- left: 0;- right: 0;- }- ```--2. **Define the shrink animation:** Create a CSS animation that changes the height of the header.-- ```css- @keyframes shrink {- to {- height: 50px;- }- }- ```--3. **Apply the animation and scroll timeline:** Attach the animation to the header and use the `scroll()` function to link it to the document’s scroll position.-- ```css- header {- animation: shrink auto linear both;- animation-timeline: scroll(block root);- }- ```--4. **Set the `animation-range`:** Use the `animation-range` property to specify the scroll distance over which the animation should occur. For example, to shrink the header over the first 150 pixels of scrolling, you would use `animation-range: 0px 150px;`.-- ```css- header {- animation-range: 0px 150px;- }- ```--**Tip:** To prevent the content following the header from being obscured by it, add a `padding-top` to the `body` (or the main content container) that is equal to the initial height of the header.--**Tip:** To make sure the contents of the page scroll in sync with the shrinking header, set the `animation-range-end` to the difference between the start and end sizes. This ensures the animation completes precisely when the header reaches its final size. In this demo the header shrinks from `200px` to `50px`, so the `animation-range-end` is set to `150px`.--## Example code--```css-@keyframes shrink {- to {- height: 50px;- }-}--header {- animation: shrink auto linear both;- animation-timeline: scroll(block root);- animation-range: 0px 150px;-}-```--## Best Practices--When using scroll-driven animations, it's important to follow a few best practices to ensure a smooth and accessible experience:--- **DO** include feature detection: Not all browsers support scroll-driven animations. Use `@supports ((animation-timeline: scroll()) and (animation-range: 0% 100%))` to check for support and provide a fallback for browsers that don't support it.- - The `(animation-range: 0% 100%)` check **MUST** be included here, to filter out browsers with only partial support.- - **DO NOT** use the `scroll-timeline-polyfill` package for the fallback strategy as it is not feature complete and has a lot of known issues.- - If the animation is only considered to be decorative, opt for Progressive Enhancement and **DO NOT** provide a fallback.-- **DO** respect user preferences: Some users prefer to have less motion on the web. Use the `prefers-reduced-motion` media query to disable or reduce your animations for these users.-- **DO** try to animate only performant CSS properties: For the smoothest animations, stick to animating properties that can be handled by the browser's compositor thread, such as `transform` and `opacity`. Animating other properties like `width` or `height` can lead to performance issues.-- **DO** use the correct declaration order: When using the `animation` shorthand property, declare `animation-timeline` and `animation-range` *after* it to prevent the shorthand from resetting the timeline.--When using the `scroll()` function to create a scroll-driven animation:--- **OPTIONAL** be explicit about the scroller: When not targeting the nearest ancestor scroller, be explicit about which scroller you want to use with `scroll(root)` or `scroll(self)`.- - When `root`, `nearest`, or `self` are not sufficient, use a named scroll-timeline.-- **OPTIONAL** be explicit about the axis to track: When not targeting the default `block` axis (such as in a horizontal scroller), be explicit about which axis to track with `scroll(block)` or `scroll(inline)`.--As for this use case specifically:--- The element that you animate **MUST** not be `position: static` or `position: relative` when using percentages in the `animation-range`.- - This is because those elements are considered “in-flow”. Shrinking those elements as you scroll, would shrink the total scroll distance, thereby affecting the computed value of — for example — `10%` into the scroll.--## Browser support and fallback strategies--Scroll-driven animations has limited availability.. Therefore, a fallback strategy is typically required.--For browsers that do not support scroll-driven animations, you can use a fallback to recreate the visual effects. The fallbacks are typically built with either a scroll listener (for ScrollTimeline effects) or the IntersectionObserver API (for ViewTimeline effects).--In browsers with built-in support for scroll-driven animations, ALWAYS use the native CSS implementation as those are more performant.--Note that not every effect can be recreated using the fallbacks approach.--For this use-case specifically, the following script applies the fallback for browsers that do not support scroll-driven animations. It uses a scroll listener to track the scroll position of the document over a distance of `150px` and updates the header's height accordingly.--```js-// Fallback for browsers that don't support scroll-driven animations-if (!CSS.supports('(animation-timeline: scroll()) and (animation-range: 0% 100%)')) {- const header = document.querySelector('header');-- const initialHeight = 200;- const finalHeight = 50;- const scrollDistance = 150;-- window.addEventListener('scroll', () => {- const scrollY = window.scrollY;- const scrollPercent = Math.min(1, scrollY / scrollDistance);- const newHeight = initialHeight - (initialHeight - finalHeight) * scrollPercent;-- header.style.height = `${newHeight}px`;- });-}-```diff --git a/skills/modern-web/guides/user-experience/size-aware-styling.md b/skills/modern-web/guides/user-experience/size-aware-styling.mddeleted file mode 100644index 706c02f..0000000--- a/skills/modern-web/guides/user-experience/size-aware-styling.md+++ /dev/null@@ -1,103 +0,0 @@-## Overview--Size-aware styling allows components to change their layout or appearance based on the space available to them, rather than the size of the whole screen. This is useful for components like cards or navigation bars that might be placed in different parts of a layout (like a narrow sidebar or a wide main area).--Using container queries is recommended because it makes components truly modular. You do not need to know where the component will live or write complex media queries to handle every possible layout.--## Implementation--### 1. Define the container--MANDATORY: You must first tell the browser which element is the container to be measured.--```css-.card-container {- /* Define the container type. Use 'inline-size' for width-based queries. */- /* You can also use 'size' for both width and height, but it requires explicit sizing. */- container-type: inline-size;-}-```--### 2. Apply styles based on container size--Use the `@container` rule to apply styles when the container reaches a certain size.--```css-/* Default styles for small containers (stacked layout) */-.card {- display: flex;- flex-direction: column;- gap: 1rem;-}--/* Styles for larger containers (side-by-side layout) */-/* This triggers when the container is wider than 400px */-@container (min-width: 400px) {- .card {- flex-direction: row;- align-items: center;- }-- .card-image {- width: 150px;- height: 150px;- }-}-```--### 3. Conditionally show content--You can also use container queries to hide or show extra details when there is more room.--```css-.card-details {- /* Hide extra details by default in small spaces */- display: none;-}--@container (min-width: 600px) {- .card-details {- /* Show details when there is plenty of room */- display: block;- }-}-```--### Fallback strategies--Baseline status for Container queries: Widely available. It's been Baseline since 2023-02-14.--For browsers that do not support container queries, the best approach is to use a safe default layout (like the stacked vertical layout) and progressively enhance it using media queries if the general screen size allows it.--```css-/* Default safe stacked layout */-.card {- display: flex;- flex-direction: column;-}--/* Fallback using media queries for older browsers */-@media (min-width: 600px) {- .card {- flex-direction: row;- }-}--/* Overwrite with container queries where supported */-@supports (container-type: inline-size) {- @media (min-width: 600px) {- .card {- /* Reset media query fallback if needed, or let container query handle it */- flex-direction: column;- }- }-- @container (min-width: 400px) {- .card {- flex-direction: row;- }- }-}-```--This ensures that users on older browsers still get a usable layout, even if it does not adapt perfectly to every specific container width.diff --git a/skills/modern-web/guides/user-experience/stabilize-reactive-state.md b/skills/modern-web/guides/user-experience/stabilize-reactive-state.mddeleted file mode 100644index f701d97..0000000--- a/skills/modern-web/guides/user-experience/stabilize-reactive-state.md+++ /dev/null@@ -1,70 +0,0 @@-# Stabilize Reactive State with Temporal--While some reactive systems (like [React](https://react.dev/)) rely strictly on reference equality to detect state changes, others (like [Vue](https://vuejs.org/) and [Svelte](https://svelte.dev/)) can track mutations to plain objects. However, for built-in objects like the legacy `Date` object, internal mutations (like `setHours()`) do not change the object's reference and are generally not tracked by any framework's default reactivity system. This leads to missed UI updates and hard-to-debug side effects.--The `Temporal` API solves this by providing immutable objects. Any operation that modifies a value (such as adding time or setting a field) returns a new instance with a new memory reference. This guarantees that state updates are always detected by reactive systems, ensuring UI stability.--## How to Implement--To stabilize reactive state using Temporal:--1. **Use Temporal types for state:** Store `Temporal` objects (like `Temporal.PlainDateTime` or `Temporal.PlainDate`) in your reactive state instead of legacy `Date` objects.-2. **Perform immutable updates:** When updating the state, use Temporal methods like `.add()`, `.subtract()`, or `.with()`. These methods return a new object.-3. **Pass the new reference to the state setter:** Use the newly created Temporal object to update your component state, triggering a reliable re-render.--## Example Code: Temporal vs Legacy Date in State--```javascript-// ❌ BAD: Mutating legacy Date breaks reactivity-let dateState = { deadline: new Date() };--function extendDeadlineBad() {- // Mutates the object in place. Reference remains the same!- dateState.deadline.setHours(dateState.deadline.getHours() + 1);-- // Frameworks will skip re-rendering because- // prevState === nextState (same memory reference)- updateState(dateState);-}--// ✅ GOOD: Temporal ensures immutability and reliable reactivity-let temporalState = { deadline: Temporal.Now.plainDateTimeISO() };--function extendDeadlineGood() {- // Returns a new object with a new reference.- const newDeadline = temporalState.deadline.add({ hours: 1 });-- // Create a new state object with the new Temporal reference- temporalState = { deadline: newDeadline };-- // Frameworks will detect the reference change and re-render the UI- updateState(temporalState);-}-```--## Strategic Implementation & Best Practices--- **DO** use `Temporal` for any date/time values stored in reactive state to benefit from its immutability.-- **DO** use the most specific Temporal type for your use case (e.g., `Temporal.PlainDate` if you only need the calendar date) to avoid unnecessary complexity.-- **DO NOT** mutate `Date` objects in place when they are part of a component's state.-- **DO** ensure you handle environments without native support by conditionally loading a polyfill.--### Fallback strategies--Temporal has limited availability.--Since the `Temporal` API is a newer feature and may not be supported in all browsers, you should feature-detect it and conditionally load a polyfill if needed.--```html-<!-- Conditionally load the Temporal polyfill only if not natively supported -->-<script>- if (typeof Temporal === "undefined") {- try {- const module = await import("https://esm.sh/@js-temporal/polyfill");- globalThis.Temporal = module.Temporal;- } catch (e) {- console.error("Failed to load Temporal polyfill:", e);- }- }-</script>-```\ No newline at end of filediff --git a/skills/modern-web/guides/user-experience/style-parent-with-has.md b/skills/modern-web/guides/user-experience/style-parent-with-has.mddeleted file mode 100644index 93a20a8..0000000--- a/skills/modern-web/guides/user-experience/style-parent-with-has.md+++ /dev/null@@ -1,199 +0,0 @@-# 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--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);-```--```js-// 1. Initialize the generic fallback-const form = document.querySelector('#demo-form');-UserInvalidFallback.init(form);--// 2. Add specialized "parent styling" logic (Separate from fallback)-// Listen for changes to form validity after interaction-form.addEventListener('blur', (e) => {- if (!e.target.matches('input, select, textarea')) return;-- // Find the container we want to style (sync with CSS)- const container = e.target.closest('.card-section');- if (!container) return;-- // Check if ANY fallbacked input in this container is invalid- const hasError = container.querySelector('.user-invalid-fallback');- container.classList.toggle('has-error-fallback', !!hasError);-}, true); // Capture phase to ensure we run after the fallback's blur listener--// Also handle input events for immediate cleanup-form.addEventListener('input', (e) => {- const container = e.target.closest('.card-section');- if (container) {- const hasError = container.querySelector('.user-invalid-fallback');- container.classList.toggle('has-error-fallback', !!hasError);- }-});--// Handle form resets-form.addEventListener('reset', () => {- form.querySelectorAll('.has-error-fallback').forEach(el => {- el.classList.remove('has-error-fallback');- });-});-```--## Other Considerations--1. **Accessibility**: Native `:user-invalid` does not automatically sync with ARIA attributes. Add the following JavaScript to keep `aria-invalid` in sync with the visual state:--```javascript-// Sync aria-invalid with the CSS :user-invalid state-const syncAria = (el) => {- el.toggleAttribute?.('aria-invalid', el.matches(':user-invalid'));-};--// Update on blur (to show error) and input (to clear it)-document.addEventListener('blur', (e) => syncAria(e.target), true);-document.addEventListener('input', (e) => {- if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);-});-```diff --git a/skills/modern-web/guides/user-experience/support-global-calendar-systems.md b/skills/modern-web/guides/user-experience/support-global-calendar-systems.mddeleted file mode 100644index 1260c03..0000000--- a/skills/modern-web/guides/user-experience/support-global-calendar-systems.md+++ /dev/null@@ -1,105 +0,0 @@-# Supporting Global Calendar Systems with Temporal--The traditional JavaScript `Date` object is based on a proleptic Gregorian calendar, making it challenging to build applications for users who rely on other calendar systems, such as the Islamic (lunar), Hebrew (lunisolar), or Chinese (lunisolar) calendars. Developers previously had to rely on complex third-party libraries or manual calculations to support these systems.--The `Temporal` API provides first-class support for multiple calendar systems. By associating a calendar identifier with date objects, Temporal handles the complex arithmetic and formatting required for different cultural contexts natively.--## How to Implement--To support global calendar systems using Temporal:--1. **Associate a Calendar (Mandatory):** When creating or converting a Temporal object (like `Temporal.PlainDate`), you must specify the desired calendar system using `withCalendar()` to perform calendar-sensitive operations.-2. **Use Stable Identifiers (Mandatory for Lunisolar Calendars):** You must use `monthCode` rather than the numeric `month` index to identify specific months across years in lunisolar calendars. Only use this for calendars that use leap months, such as the Hebrew and Chinese calendars.-3. **Respect Calendar Invariants (Mandatory):** When iterating through months or days, you must not assume fixed values (like 12 months in a year or 31 days in a month). Use properties like `monthsInYear` and `daysInMonth` to ensure your code works across all calendars.-4. **Use Calendar-Aware Comparisons (Mandatory):** When comparing dates within a specific calendar system, you must use `Temporal.PlainDate.compare()` instead of comparing year/month/day properties manually. This correctly handles chronological ordering within the calendar rules.--## Example Code: Converting and Iterating Calendars--```javascript-// 1. Helper to check calendar support-function isCalendarSupported(calendarId) {- try {- return Intl.supportedValuesOf('calendar').includes(calendarId);- } catch {- // Fallback for environments where supportedValuesOf is not available- return false;- }-}--// 2. Get current date in default ISO 8601 calendar-const isoDate = Temporal.Now.plainDateISO();--// 3. Convert to Hebrew calendar if supported-const calendarId = 'hebrew';-const targetDate = isCalendarSupported(calendarId)- ? isoDate.withCalendar(calendarId)- : isoDate; // Fallback to ISO if not supported--if (targetDate.calendar.id !== calendarId) {- console.warn(`Calendar ${calendarId} not supported; falling back to ISO 8601`);-}--// 4. Log properties specific to the calendar-console.log(`Calendar: ${targetDate.calendar.id}`);-console.log(`Year: ${targetDate.year}`);-console.log(`Month Code: ${targetDate.monthCode}`); // Stable across leap years--// 5. Safely iterate through months in the current year-for (let m = 1; m <= targetDate.monthsInYear; m++) {- console.log(`Month ${m} has ${targetDate.with({ month: m }).daysInMonth} days.`);-}--// 6. Compare dates within the same calendar-const today = Temporal.Now.plainDateISO().withCalendar(calendarId);-const comparison = Temporal.PlainDate.compare(targetDate, today);-const relative = comparison < 0 ? 'Past' : comparison > 0 ? 'Future' : 'Today';-console.log(`Timeline: ${relative}`);--// 7. Format for display using toLocaleString-const localizedDisplay = targetDate.toLocaleString('en-u-ca-hebrew', {- day: 'numeric',- month: 'long',- year: 'numeric'-});-```--## Strategic Implementation & Best Practices--- **DO** use `monthsInYear` as the upper bound when looping through months, rather than assuming 12.-- **DO** use `monthCode` for identifying specific months in calendars that use leap months (e.g., Hebrew or Chinese), regardless of the year.-- **DO NOT** assume `date.month === 12` is the last month of the year. Use `date.month === date.monthsInYear`.-- **DO NOT** assume `inLeapYear === true` implies the year is only one day longer. In lunisolar calendars, it may add a full leap month.-- **DO** use `Temporal.PlainDate.compare()` when comparing two dates in a specific calendar system instead of comparing Year/Month/Day properties manually.-- **DO** use `toLocaleString()` to format dates for users instead of manual string concatenation.-- **DO** verify that the target calendar system is supported by the environment using `Intl.supportedValuesOf('calendar')` before creating calendar-specific Temporal objects.-- **DO** be aware that some calendars (like variants of the Islamic calendar) may rely on visual observation rather than fixed calculations. The `Temporal` API follows the environment's `Intl` implementation, which usually uses calculated approximations. For critical cultural or religious date calculations, verify with domain experts or use specialized libraries.-- **DO** account for era names when using calendars that use eras (e.g., Japanese, Buddhist), using `toLocaleString()`.--## Fallback Strategy--Temporal has limited availability.--For production use in browsers that do not support it natively, you must use a polyfill.--The recommended approach is to progressively enhance by checking for native support and dynamically loading a polyfill like `@js-temporal/polyfill` if needed.--```javascript-/**- * Progressive Enhancement Fallback- */-async function getTemporal() {- if (typeof Temporal !== 'undefined') {- return Temporal;- }-- try {- // Load polyfill dynamically from CDN- const module = await import('https://esm.sh/@js-temporal/polyfill');- globalThis.Temporal = module.Temporal;- return module.Temporal;- } catch (e) {- console.error('Failed to load Temporal polyfill:', e);- throw e;- }-}-```diff --git a/skills/modern-web/guides/user-experience/visually-stable-font-fallbacks.md b/skills/modern-web/guides/user-experience/visually-stable-font-fallbacks.mddeleted file mode 100644index 0b01512..0000000--- a/skills/modern-web/guides/user-experience/visually-stable-font-fallbacks.md+++ /dev/null@@ -1,48 +0,0 @@-When web fonts load, they often replace a fallback font that has different dimensions, even if both are set to the same `font-size`. This causes "layout shift" (Cumulative Layout Shift) and can make text illegible if the fallback's lowercase letters (x-height) are significantly different than the preferred font.--The `font-size-adjust` property solves this by normalizing the size of the font based on a specific metric (usually the x-height), ensuring that text occupies the same visual space regardless of which font is currently active.--## Implementation steps--### 1. Identify the aspect ratio of your preferred font-To normalize fallbacks, you need the "aspect value" (the ratio of lowercase letters to the font size) of your primary font.--* **Automatic discovery (Recommended):** Use the `from-font` keyword to let the browser extract the ratio from your primary web font.-* **Manual calculation:** If you know the specific value (e.g., 0.545 for Verdana), you can provide it directly for more precise control.--### 2. Apply font-size-adjust to the text container-Apply the property to the element or a parent container. This ensures that if the primary font fails to load or is in the process of loading, the fallback font is scaled to match the visual size of the primary font.--```css-.text-content {- /* Define your font stack as usual */- font-family: "MyWebFont", "Arial", sans-serif;- font-size: 1rem;-- /* MANDATORY: Normalize the font size based on the primary font's x-height.- This ensures that if 'Arial' is used as a fallback, it is scaled- to match the x-height of 'MyWebFont'. */- font-size-adjust: from-font;-}-```--### 3. (Optional) Adjust for specific metrics-While x-height is the default and most common, you can normalize by other metrics like `cap-height` (useful for all-caps headers) or `ch-width` (useful for monospaced fonts).--```css-h1 {- /* Normalize based on the height of capital letters */- font-size-adjust: cap-height from-font;-}-```--### 4. Verify visual stability-Ensure that the `font-size-adjust` value correctly aligns the fallback. You can test this by temporarily blocking the web font or adjusting the `font-family` declaration in your browser's DevTools and verifying that the text layout remains stable.--## Fallback strategies--Baseline status for font-size-adjust: Newly available. It's been Baseline since 2024-07-25.--In browsers that do not support `font-size-adjust`, the font will be rendered at its default scale. This may result in layout shifts or changes in readability during font swaps.--To mitigate this without `font-size-adjust`, you can use the `@font-face` descriptors `size-adjust`, `ascent-override`, and `descent-override` to manually tune fallback fonts, though these are more complex to calculate than a single `font-size-adjust` value.diff --git a/skills/modern-web/guides/user-experience/visually-stable-mixed-fonts.md b/skills/modern-web/guides/user-experience/visually-stable-mixed-fonts.mddeleted file mode 100644index 1fa56ae..0000000--- a/skills/modern-web/guides/user-experience/visually-stable-mixed-fonts.md+++ /dev/null@@ -1,60 +0,0 @@-When mixing different font families, for instance when inserting inline code snippets, or switching out font families for different themes, differences in "x-height" (the height of lowercase letters) can make one font appear much smaller or larger than the other font. This can lead to poor legibility and layout shifts.--The `font-size-adjust` property allows you to normalize the visual size of text by adjusting the font size based on a specific font metric (usually the x-height).--### Implementation Steps--1. **MANDATORY**: Apply `font-size-adjust` to elements where font consistency is critical, such as containers using web fonts or blocks with mixed font families.-2. **MANDATORY**: Use the `from-font` keyword on elements to automatically match font size in nested elements to the proportions of the primary font.-3. **MANDATORY**: Use a specific numeric aspect-ratio override value for `font-size-adjust` (e.g., `font-size-adjust: 0.5`) to normalize proportions independently when the font proportions to base on are from an independent theme.--### Example: Normalizing x-height automatically--Using `from-font` is the most robust approach. It extracts the aspect ratio of the x-height from the first available font and applies it to fonts in child elements.--```css-.content-area {- font-family: "MyCustomWebFont";- /* Automatically extract and apply x-height ratio from MyCustomWebFont */- font-size-adjust: from-font;-}-.content-area span{- font-family: "MyOtherCustomWebFont"-}-```--### Example: Specifying a specific x-height--When the font to adjust is not a child of the font to base the size on, specify a value to adjust the x-height by.--```css-.theme{- font-family: Verdana, sans-serif;-}-.theme.alternate{- font-family: Times;- /* Set to the aspect ratio (x-height / font-size) of the primary font */- font-size-adjust: 0.51;-}-```--### Fallback strategies--Baseline status for font-size-adjust: Newly available. It's been Baseline since 2024-07-25.--**MANDATORY**: In browsers that do not support `font-size-adjust`, fonts will render at their natural `font-size` value. You must provide a valid fallback strategy for non-supporting browsers using a `@supports` block to mitigate this:--- Use `@supports not (font-size-adjust: from-font)` to detect `font-size-adjust` support and provide fallback styles (e.g. adjusted line-height or font-size).-- Choose fonts with similar x-heights to your primary font.-- Apply specific `font-size` and `line-height` overrides for alternate and nested font families.--```css-/* Feature detection for font-size-adjust */-@supports not (font-size-adjust: from-font) {- .content-area {- /* Manual adjustment for browsers without support (if needed) */- line-height: 1.6;- font-size: 1.2rem;- }-}-```diff --git a/skills/modern-web/guides/webmcp/agentic-forms.md b/skills/modern-web/guides/webmcp/agentic-forms.mddeleted file mode 100644index 9f333c8..0000000--- a/skills/modern-web/guides/webmcp/agentic-forms.md+++ /dev/null@@ -1,116 +0,0 @@-The Declarative API transforms standard HTML `<form>` elements into WebMCP tools via attributes. The browser synthesizes a JSON Schema from the form inputs and handles agent interactions.--## Form Attributes--* `toolname`: Unique name for the tool.-* `tooldescription`: Purpose of the tool.-* `toolautosubmit`: (Optional) If present, the agent can submit the form without waiting for user interaction.-* `toolparamdescription`: (Optional) Provides a way to define a property description within the JSON Schema.- * **Resolution Order**: The browser uses `toolparamdescription` if present. In its absence, it uses the `textContent` of the associated `<label>` (skipping labelable descendants). If no label exists, it falls back to the `aria-description`.- * **Grouping (Fieldsets)**: To attach a description to a group of related elements (like `<input type="radio">` buttons), place `toolparamdescription` on the nearest parent `<fieldset>` element so it applies to the parameter group as a whole.--### Example--```html-<form toolname="search-cars"- tooldescription="Perform a car make/model search"- toolautosubmit>- <label for="make">Vehicle Make</label>- <input type="text" id="make" name="make" required>-- <label for="model">Vehicle Model</label>- <input type="text" id="model" name="model" toolparamdescription="e.g., 330i, F-150" required>-- <button type="submit">Search</button>-</form>-```--## Handling Submissions in JavaScript--When an agent submits the form, the `SubmitEvent` includes `agentInvoked` (boolean) and `respondWith(promise)`.--```javascript-document.querySelector('form').addEventListener('submit', (event) => {- event.preventDefault();-- // Validate the form- const formValidationErrors = myFormIsValid();-- if (formValidationErrors.length > 0) {- if (event.agentInvoked) {- const errorString =- 'Validation failed: ' +- formValidationErrors- .map((err) => `${err.field} (${err.message})`)- .join(', ');-- event.respondWith(Promise.resolve(errorString));- }- return;- }-- const resultPromise = performAsyncSearch(new FormData(event.target));-- // Return the result directly to the agent without navigation- if (event.agentInvoked) {- event.respondWith(resultPromise);- }-});-```--## Lifecycle Events--The window emits events when agents start or stop interacting with a tool:--```javascript-window.addEventListener('toolactivated', ({ toolName }) => {- console.log(`Tool "${toolName}" was activated by the agent.`);-});--window.addEventListener('toolcancel', ({ toolName }) => {- console.log(`Tool "${toolName}" interaction was cancelled.`);-});-```--## Visual Feedback (CSS)--Use pseudo-classes to highlight forms when an agent interacts with them:--* `:tool-form-active`: Applied to the `<form>` element actively used by the agent.-* `:tool-submit-active`: Applied to the submit button when the browser pauses for user review (if `toolautosubmit` is omitted).--```css-form:tool-form-active {- outline: 2px dashed blue;- background-color: rgba(0, 0, 255, 0.05);-}--button:tool-submit-active {- outline: 2px dashed red;- animation: pulse 2s infinite;-}-```--## Form Suitability (When to Avoid)--The Declarative API is best for self-contained, standard forms. It is a poor choice in these scenarios:--* **Highly Dependent Fields**: Forms where inputs change options or visibility based on other inputs. The synthesized schema cannot express these dependencies well.-* **Custom UI Components**: Forms relying on non-standard inputs (e.g., canvas, rich text editors) that don't auto-serialize values.-* **Multi-Step Wizards**: Complex workflows requiring multiple form submissions. The Imperative API or standard DOM interaction is better suited here.--## When to use toolautosubmit-* **Read-Only Operations & Queries**: Searches, filters, fetching details, or checking status (e.g., a car model search, searching a directory, checking stock availability).-* **Low-Risk, Reversible Actions**: Form actions that can easily be undone or refined by the user manually (e.g., adding items to a cart, applying a coupon code, saving a draft, or setting temporary layout options).--## When to omit toolautosubmit-* **Destructive or Irreversible Actions**: Deleting records, resetting system configurations, or clearing databases.-* **Financial & Transactional Actions**: Submitting a checkout form, transferring funds, authorizing subscription payments, or final order placements.-* **High-Impact User Communication**: Submitting a final job application, sending emails/messages to other real users, or publishing public-facing content.-* **Sensitive Account Settings**: Changing passwords, modifying user roles/permissions, or updating billing/profile info.--## Fallback strategies--Form-associated WebMCP attributes has limited availability.--The WebMCP Declarative API is safe to use in all browsers. Browsers that do not support WebMCP will ignore the `tool*` attributes, and the `<form>` will continue to function as a normal HTML form. No feature detection is required.diff --git a/skills/modern-web/guides/webmcp/agentic-javascript-tools.md b/skills/modern-web/guides/webmcp/agentic-javascript-tools.mddeleted file mode 100644index 4e2f055..0000000--- a/skills/modern-web/guides/webmcp/agentic-javascript-tools.md+++ /dev/null@@ -1,115 +0,0 @@-The Imperative API uses `navigator.modelContext.registerTool()` to programmatically define JavaScript tools. This is ideal for Single Page Applications (SPAs) where tools need to be added or removed based on the current route or user state.--## Registration and Lifecycle--Tools are registered by passing a tool definition object and an optional options object containing an `AbortSignal`.--### Lifecycle Handling with `AbortController`--WebMCP does not provide an `unregisterTool()` method. To unregister a tool, you must pass an `AbortSignal` during registration and abort that signal when the tool is no longer needed.--```javascript-const controller = new AbortController();--navigator.modelContext.registerTool({- name: "get_user_preferences",- description: "Retrieves the user's saved preferences.",- inputSchema: { type: "object", properties: {} },- execute() {- const prefs = localStorage.getItem("user_prefs");- return prefs ? JSON.parse(prefs) : { theme: "light" };- },- annotations: { readOnlyHint: true }-}, { signal: controller.signal });--// To unregister the tool (e.g., on component unmount):-controller.abort();-```--## Defining Parameters--Parameters (params) are defined using the `inputSchema` property. This must be a **JSON Schema** object that describes the structured data the tool expects.--```javascript-navigator.modelContext.registerTool({- name: "calculate_area",- description: "Calculates the area of a rectangle.",- inputSchema: {- type: "object",- properties: {- width: { type: "number", description: "The width of the rectangle." },- height: { type: "number", description: "The height of the rectangle." }- },- required: ["width", "height"]- },- execute(input) {- // input is { width: 10, height: 20 }- return input.width * input.height;- },- annotations: { readOnlyHint: true }-});-```--## Execution Patterns--### When to use `async execute`-Use `async` when the tool involves operations that return a Promise or take time to complete:-- **Network calls**: Fetching data from an API.-- **Asynchronous Storage**: Accessing IndexedDB.-- **External Events**: Waiting for a specific state change or animation to finish.--```javascript-async execute(input) {- const response = await fetch(`/api/data/${input.id}`);- return await response.json();-}-```--### When to use `execute` (Synchronous)-Use a standard synchronous function for immediate operations:-- **Pure logic**: Math, filtering, or sorting data already in memory.-- **Synchronous state**: Reading from `localStorage` or a synchronous state manager.--```javascript-execute(input) {- return input.items.filter(item => item.active);-}-```--## Tool Factory Pattern--To pass context (like stores or application instances) to your tools, use factory functions.--```javascript-export function createInventoryTool(inventoryManager) {- return {- name: "get_inventory",- description: "Lists items in the inventory.",- inputSchema: { type: "object", properties: {} },- execute() {- return inventoryManager.getItems();- },- annotations: { readOnlyHint: true }- };-}-```--## API Notes--* **annotations**: (Optional) A dictionary for tool metadata.- * **readOnlyHint**: (Optional) Set to `true` if the tool does not modify any state and only reads data. This helps agents decide when it is safe to call the tool.-* **Return Format**: The `execute` function can return any value (object, array, string, number, boolean). Select a structure that best serves your specific use case while ensuring the content is optimized for the LLM to process. The output may encompass raw data, specific error logs, or direct instructions to influence the agent's next action.-* **Secure Context**: WebMCP requires HTTPS.-* **Deprecated/Removed**: `unregisterTool()`, `provideContext()`, and `clearContext()` are no longer supported.--## Fallback strategies--navigator.modelContext has limited availability.--The WebMCP Imperative API should be used with feature detection to ensure compatibility with browsers that do not yet support WebMCP.--```javascript-if ('modelContext' in navigator && 'registerTool' in navigator.modelContext) {- // Register tools-}-```diff --git a/skills/modern-web/package.json b/skills/modern-web/package.jsondeleted file mode 100644index da1d42b..0000000--- a/skills/modern-web/package.json+++ /dev/null@@ -1,8 +0,0 @@-{- "name": "modern-web",- "version": "1.0.0",- "type": "module",- "bin": {- "modern-web": "modern-web.mjs"- }-}