agentleFS
Leo-AtienzaLeo-Atienza/atlas-claude/skills/_archived/web-platform-apis/SKILL.md

web-platform-apis

Skill4 starsChanged 4 months agoMITView on GitHub

Apply when implementing UI features that can use native browser APIs instead of JavaScript libraries. Always prefer native APIs over JS libraries when browser support is sufficient. Auto-activate on keywords: popover, tooltip, dropdown, smooth-scroll, page-transition, prerender, prefetch, anchor, dialog. Baseline since April 2024 — Chrome 114+, Firefox 125+, Safari 17+

The file

We split this skill into the rules it gives an agent

7 rules. About 0 are common, 4 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use autofocus on the primary action button

    line 612
  2. Very specific:

    Use returnValue to determine which button closed the dialog

    line 613
  3. Very specific:

    Use ::view-transition-group(*) to globally control timing

    line 800
  4. Distinctive:

    Always provide a visible close mechanism — relying on Esc alone fails in some AT

    line 813
  5. Distinctive:

    Test with VoiceOver/NVDA — focus management matters

    line 815
  6. Distinctive:

    Never prerender authenticated pages served without proper cache headers — risk serving stale auth state

    line 822
  7. Distinctive:

    Avoid prerending checkout or cart mutation pages

    line 824

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md
<!-- id: SK-054 name: web-platform-apis description: Modern Web Platform APIs — View Transitions, Popover, Anchor Positioning, Scroll Animations, Speculation Rules, WebGPU keywords: view-transitions, popover, anchor-positioning, scroll-driven-animations, speculation-rules, navigation-api, trusted-types, webgpu, dialog, css-api version: 1.0.0 -->

Web Platform APIs — SK-046

When to Use This Skill

Apply when implementing UI features that can use native browser APIs instead of JavaScript libraries. Always prefer native APIs over JS libraries when browser support is sufficient. Auto-activate on keywords: popover, tooltip, dropdown, smooth-scroll, page-transition, prerender, prefetch, anchor, dialog.


1. View Transitions API

SPA (same-document) — Chrome 111+, Firefox 144+, Safari 18+

document.startViewTransition(async () => {
  await updateDOM();
});

MPA (cross-document) — Chrome 126+, Safari 18.2+

@view-transition { navigation: auto; }

.hero-image { view-transition-name: hero; }

::view-transition-old(hero) { animation: fade-out 0.3s; }
::view-transition-new(hero) { animation: fade-in 0.3s; }

Dynamic naming with pageswap/pagereveal (Chrome 126+)

window.addEventListener('pagereveal', (e) => {
  if (e.viewTransition) {
    const targetUrl = new URL(navigation.activation.entry.url);
    // Set view-transition-name dynamically based on navigation target
    // e.g., document.querySelector(`[data-id="${targetUrl.searchParams.get('id')}"]`)
    //   ?.style.setProperty('view-transition-name', 'hero');
  }
});

Integration with React/Next.js

// Next.js App Router with View Transitions
'use client';
import { useRouter } from 'next/navigation';

function navigate(href: string) {
  const router = useRouter();
  if (!document.startViewTransition) {
    router.push(href);
    return;
  }
  document.startViewTransition(() => router.push(href));
}

Progressive enhancement wrapper

export function withViewTransition(fn: () => void | Promise<void>) {
  if (!document.startViewTransition) return fn();
  return document.startViewTransition(fn).ready;
}

CSS animation patterns

/* Default cross-fade override */
::view-transition-old(root) {
  animation: slide-out 0.3s ease-in both;
}
::view-transition-new(root) {
  animation: slide-in 0.3s ease-out both;
}

@keyframes slide-out {
  to { transform: translateX(-100%); opacity: 0; }
}
@keyframes slide-in {
  from { transform: translateX(100%); opacity: 0; }
}

/* Reduce motion */
@media (prefers-reduced-motion) {
  ::view-transition-old(root),
  ::view-transition-new(root) {
    animation: none;
  }
}

2. Popover API

Baseline since April 2024 — Chrome 114+, Firefox 125+, Safari 17+

Declarative, zero JS

<!-- Auto type: light-dismiss, stacks with other popovers -->
<button popovertarget="menu">Open Menu</button>
<div id="menu" popover>
  <nav>Menu content with light-dismiss</nav>
</div>

<!-- Manual control: no light-dismiss, programmatic only -->
<div id="modal" popover="manual">
  <button popovertarget="modal" popovertargetaction="hide">Close</button>
</div>

<!-- Hint type for hover tooltips (Chrome 131+) -->
<button popovertarget="tip">Hover me</button>
<div id="tip" popover="hint">Tooltip text</div>

Types

TypeLight-dismissStackingUse case
autoYesCloses othersMenus, dropdowns
hintYesLayered above autoHover tooltips
manualNoDoes not close othersNotifications, drawers

CSS

/* Open state */
[popover]:popover-open {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

/* Entry animation with @starting-style */
[popover] {
  transition: opacity 0.2s, transform 0.2s, display 0.2s allow-discrete;
  opacity: 0;
  transform: scale(0.95);
}
[popover]:popover-open {
  opacity: 1;
  transform: scale(1);
}
@starting-style {
  [popover]:popover-open {
    opacity: 0;
    transform: scale(0.95);
  }
}

/* Backdrop overlay */
[popover]::backdrop {
  background: hsl(0 0% 0% / 0.4);
  backdrop-filter: blur(2px);
}

JavaScript API

const popover = document.getElementById('menu');
popover.showPopover();
popover.hidePopover();
popover.togglePopover();

// Events
popover.addEventListener('beforetoggle', (e) => {
  console.log(e.oldState, e.newState); // 'closed'/'open'
});
popover.addEventListener('toggle', (e) => {
  if (e.newState === 'open') initPopoverContent();
});

3. CSS Anchor Positioning

Chrome 125+, Safari 26+, Interop 2025 target

Replaces: Floating UI, Popper.js, Tippy.js — zero JS required.

Basic tooltip

.trigger {
  anchor-name: --my-anchor;
}

.tooltip {
  position: absolute;
  position-anchor: --my-anchor;
  position-area: top center;
  /* Fallback order if no space */
  position-try-fallbacks: bottom center, right center, left center;
  margin-block-end: 8px;
  /* Optional: size relative to anchor */
  max-width: anchor-size(width);
}

With Popover API (complete solution — zero JS)

<button
  popovertarget="dropdown"
  style="anchor-name: --btn"
>
  Options
</button>

<ul
  id="dropdown"
  popover
  style="
    position: absolute;
    position-anchor: --btn;
    position-area: bottom span-left;
    margin-block-start: 4px;
  "
>
  <li>Edit</li>
  <li>Duplicate</li>
  <li>Delete</li>
</ul>

Dynamic anchor (JS-set)

// Register named anchor on element imperatively
trigger.style.anchorName = '--dynamic-anchor';
tooltip.style.positionAnchor = '--dynamic-anchor';

Position area values

/* Cardinal positions */
position-area: top;          /* centered above */
position-area: bottom start; /* left-aligned below */
position-area: inline-end;   /* after in inline direction */

/* Spanning */
position-area: top span-all; /* full width above */
position-area: center;       /* overlaps anchor center */

Feature detection

@supports (anchor-name: --test) {
  /* Use anchor positioning */
}
@supports not (anchor-name: --test) {
  /* Fallback: use Floating UI */
}

4. CSS Scroll-Driven Animations

Chrome 115+, Firefox 110+, Safari 18+ (Baseline 2024)

GPU-composited, zero JS, no jank.

Fade-in on scroll into view

@keyframes fade-in {
  from { opacity: 0; translate: 0 40px; }
  to   { opacity: 1; translate: 0; }
}

.card {
  animation: fade-in linear both;
  animation-timeline: view();
  animation-range: entry 0% entry 100%;
}

Scroll progress bar

.progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  height: 3px;
  background: hsl(220 90% 56%);
  transform-origin: left;
  animation: grow linear both;
  animation-timeline: scroll(root);
}

@keyframes grow {
  from { scale: 0 1; }
  to   { scale: 1 1; }
}

Parallax effect

.parallax-bg {
  animation: parallax linear both;
  animation-timeline: scroll();
  animation-range: 0% 100%;
}

@keyframes parallax {
  from { translate: 0 -20%; }
  to   { translate: 0 20%; }
}

Sticky header shrink

.site-header {
  animation: shrink linear both;
  animation-timeline: scroll(root);
  animation-range: 0px 120px;
}

@keyframes shrink {
  from { padding: 1.5rem 2rem; font-size: 1.25rem; }
  to   { padding: 0.5rem 2rem; font-size: 1rem; }
}

Named scroll timeline (scoped to container)

.scroll-container {
  overflow-y: scroll;
  scroll-timeline: --list-scroll block;
}

.list-item {
  animation: reveal linear both;
  animation-timeline: --list-scroll;
  animation-range: entry 20% entry 80%;
}

Key concepts

FunctionDescription
scroll()Progress based on scroll position of container
view()Progress based on element visibility in viewport
entryElement entering the scrollport
exitElement exiting the scrollport
containElement fully contained in scrollport
coverElement covers entire scrollport

Progressive enhancement

@supports (animation-timeline: scroll()) {
  .card {
    animation: fade-in linear both;
    animation-timeline: view();
    animation-range: entry 0% entry 100%;
  }
}

5. Speculation Rules API

Chrome 121+ (prerender), Chrome 110+ (prefetch)

Near-zero LCP on prerendered pages.

Inline rules

<script type="speculationrules">
{
  "prerender": [{
    "where": { "href_matches": "/products/*" },
    "eagerness": "moderate"
  }],
  "prefetch": [{
    "where": { "and": [
      { "href_matches": "/*" },
      { "not": { "href_matches": "/checkout*" } },
      { "not": { "href_matches": "/account*" } }
    ]},
    "eagerness": "conservative"
  }]
}
</script>

Eagerness levels

LevelTriggersBest for
immediateAs soon as rules parsedCritical next pages
eagerAs early as possibleLikely next pages
moderateOn hover (200ms dwell)Navigation links
conservativeOn mousedown/touchstartGeneral links

Chrome limits

  • immediate/eager: 2 concurrent prerenders max
  • moderate/conservative: 10 concurrent prerenders max
  • Prerender won't fire on low-memory devices or data-saver mode

Dynamic injection (A/B testing, auth-aware)

function injectSpeculationRules(rules) {
  if (!HTMLScriptElement.supports?.('speculationrules')) return;
  const script = document.createElement('script');
  script.type = 'speculationrules';
  script.textContent = JSON.stringify(rules);
  document.head.append(script);
}

// Only prerender if logged in
if (userIsLoggedIn) {
  injectSpeculationRules({
    prerender: [{ urls: ['/dashboard'], eagerness: 'moderate' }]
  });
}

Next.js 15+ integration

// next.config.js
module.exports = {
  experimental: {
    speculationRules: {
      prerender: [{ source: 'list', where: { href_matches: '/**' }, eagerness: 'moderate' }]
    }
  }
};

6. Navigation API

Chrome 102+, Edge. Polyfillable.

Replaces popstate + hashchange with a unified, interruptible model.

Intercept all navigations

navigation.addEventListener('navigate', (event) => {
  // Only handle same-origin navigations
  if (!event.canIntercept) return;
  // Skip downloads and cross-origin
  if (event.downloadRequest !== null) return;

  event.intercept({
    async handler() {
      // Show loading state
      document.startViewTransition(async () => {
        const content = await fetchPage(event.destination.url);
        renderPage(content);
      });
    },
    // Abort signal if user navigates away before completion
    commit: 'after-transition',
  });
});

Programmatic navigation

// Navigate with state
await navigation.navigate('/profile', {
  state: { from: 'home', scrollY: window.scrollY }
});

// Back / forward
navigation.back();
navigation.forward();
navigation.traverseTo(navigation.entries()[2].key);

// Full history
const entries = navigation.entries(); // NavigationHistoryEntry[]
const current = navigation.currentEntry;
console.log(current.url, current.state, current.index);

Reload with state

navigation.reload({ state: { timestamp: Date.now() } });

7. <dialog> Element (Proper Usage)

Baseline 2022 — all modern browsers

Modal dialog (blocks interaction)

<dialog id="confirm-modal">
  <h2>Confirm action?</h2>
  <p>This cannot be undone.</p>
  <form method="dialog">
    <button value="cancel">Cancel</button>
    <button value="confirm" autofocus>Confirm</button>
  </form>
</dialog>

<button onclick="document.getElementById('confirm-modal').showModal()">
  Delete
</button>

<script>
  const modal = document.getElementById('confirm-modal');
  modal.addEventListener('close', () => {
    if (modal.returnValue === 'confirm') performDelete();
  });
</script>

Non-modal (side panel)

<dialog id="details-panel">
  <button onclick="this.closest('dialog').close()">Close</button>
  <p>Side panel content</p>
</dialog>

<button onclick="document.getElementById('details-panel').show()">
  Open Panel
</button>

CSS with entry/exit animations

dialog {
  /* Reset browser defaults */
  border: none;
  border-radius: 0.75rem;
  padding: 1.5rem;
  max-width: min(90vw, 480px);

  /* Exit animation */
  transition: opacity 0.2s, transform 0.2s, display 0.2s allow-discrete;
  opacity: 0;
  transform: scale(0.95) translateY(8px);
}

dialog[open] {
  opacity: 1;
  transform: scale(1) translateY(0);
}

/* Entry animation */
@starting-style {
  dialog[open] {
    opacity: 0;
    transform: scale(0.95) translateY(8px);
  }
}

dialog::backdrop {
  background: hsl(0 0% 0% / 0.5);
  backdrop-filter: blur(4px);
  transition: opacity 0.2s, display 0.2s allow-discrete;
  opacity: 0;
}

dialog[open]::backdrop {
  opacity: 1;
}

@starting-style {
  dialog[open]::backdrop {
    opacity: 0;
  }
}

Key points

  • showModal() → top-layer, backdrop, focus trap, Esc to close — all free
  • show() → non-modal, no backdrop, no focus trap
  • method="dialog" on <form> auto-closes and sets dialog.returnValue to the button's value
  • Prefer <dialog> over custom modal implementations — accessibility is built in (ARIA role, focus management, Esc key)
  • Use autofocus on the primary action button
  • Use returnValue to determine which button closed the dialog

8. Scroll-State Queries

Chrome 133+ — progressive enhance

Detect scroll-related states without JavaScript. Replaces IntersectionObserver and scroll event listeners for common patterns.

Sticky Header Detection

.sticky-header {
  container-type: scroll-state;
  position: sticky;
  top: 0;
}

/* Add shadow and backdrop when stuck */
@container scroll-state(stuck: top) {
  .sticky-header {
    background: oklch(0.99 0 0 / 0.95);
    backdrop-filter: blur(12px);
    box-shadow: 0 1px 3px oklch(0 0 0 / 0.1);
  }
}

Scroll Direction Indicators

.scroll-container {
  container-type: scroll-state;
  overflow-y: auto;
}

/* Show indicators when more content is scrollable */
@container scroll-state(scrollable: top) {
  .scroll-indicator-up { display: block; }
}

@container scroll-state(scrollable: bottom) {
  .scroll-indicator-down { display: block; }
}

Snap Detection

.carousel {
  container-type: scroll-state;
  scroll-snap-type: x mandatory;
}

@container scroll-state(snapped: x) {
  .carousel-item { opacity: 1; transform: scale(1); }
}

Feature Detection

@supports (container-type: scroll-state) {
  /* Use scroll-state queries */
}

9. Container Queries (Quick Reference)

For full architecture patterns, load css-first-ui (SK-084).

Baseline 2023 (size queries) — use everywhere

.card-wrapper {
  container-type: inline-size;
  container-name: card;
}

@container card (min-width: 400px) {
  .card { grid-template-columns: 200px 1fr; }
}

Three types: size queries (Baseline 2023), style queries (Chrome 111+), scroll-state queries (Chrome 133+). See SK-084 for complete patterns.


10. Trusted Types & WebGPU

Moved to reference files for focused access:

  • Trusted Types (XSS Prevention) — Chrome 83+, CSP enforcement, policy creation
  • WebGPU Compute — Chrome 113+, device setup, compute shaders, use cases

11. Browser Support Decision Guide

APIBaselinePolyfill?Use Today?
<dialog>2022Not neededYes — always
Popover2024Yes (popover-polyfill)Yes
View Transitions SPA2024Progressive enhanceYes
View Transitions MPAPartialProgressive enhanceYes (Chrome + Safari)
Scroll-Driven Animations2024Progressive enhanceYes
CSS Anchor PositioningPartialNot yetProgressive enhance
Speculation RulesChrome onlyNoYes (progressive)
Navigation APIChrome/EdgePolyfill availableCautious
Scroll-State QueriesChrome 133+NoProgressive enhance
Container Queries (size)2023Not neededYes — always
Container Queries (style)Chrome 111+NoProgressive enhance
Trusted TypesChromeNoDefense-in-depth
WebGPU~70%NoFeature-detect required

Progressive enhancement pattern

// View Transitions
if (document.startViewTransition) {
  document.startViewTransition(() => update());
} else {
  update();
}

// Speculation Rules
if (HTMLScriptElement.supports?.('speculationrules')) {
  injectSpeculationRules(rules);
}

// Navigation API
if ('navigation' in window) {
  navigation.addEventListener('navigate', handler);
} else {
  window.addEventListener('popstate', legacyHandler);
}

// WebGPU
if (navigator.gpu) {
  await runGPUPipeline();
} else {
  runCPUFallback();
}

CSS feature detection

/* Scroll-driven animations */
@supports (animation-timeline: scroll()) {
  .animated { animation-timeline: view(); }
}

/* Anchor positioning */
@supports (anchor-name: --test) {
  .tooltip { position-anchor: --trigger; }
}

/* @starting-style */
@supports (selector(dialog[open])) {
  @starting-style { dialog[open] { opacity: 0; } }
}

12. API Replacement Matrix

Old patternNative replacementSince
Floating UI / Popper.jsCSS Anchor Positioning + PopoverChrome 125
Custom modal + focus trap<dialog> + showModal()Baseline 2022
IntersectionObserver animationsScroll-Driven AnimationsBaseline 2024
SPA router page transitionsView Transitions APIChrome 111
history.pushState + popstateNavigation APIChrome 102
<link rel="prefetch">Speculation RulesChrome 110
innerHTML + DOMPurify directTrusted Types + DOMPurifyChrome 83

13. Common Pitfalls

View Transitions

  • view-transition-name must be unique per page at the time of transition — remove duplicate names before calling startViewTransition
  • Cross-document transitions require both pages to opt in with @view-transition { navigation: auto; }
  • Use ::view-transition-group(*) to globally control timing

Popover

  • popover="auto" closes all other auto popovers — use manual when building toast stacks
  • The popover element must not be inside another element with overflow: hidden — it renders in the top layer
  • popovertarget only works on <button> and <input type="button"> elements

Scroll-Driven Animations

  • animation-fill-mode: both is almost always required
  • Container must have a defined scroll height — check overflow is set on the scroll container
  • view() respects scroll-margin and scroll-padding

<dialog>

  • Always provide a visible close mechanism — relying on Esc alone fails in some AT
  • returnValue is only set by <form method="dialog"> submit — dialog.close() does not set it unless you pass a value: dialog.close('cancel')
  • Test with VoiceOver/NVDA — focus management matters

Anchor Positioning

  • Anchors in position: fixed containers may not work as expected — anchors must share a formatting context
  • position-try-fallbacks only tries listed fallbacks, not exhaustive positions

Speculation Rules

  • Never prerender authenticated pages served without proper cache headers — risk serving stale auth state
  • prerender does not execute in iframes — full page context only
  • Avoid prerending checkout or cart mutation pages

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.