Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

34.6 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Focus Ring Animation — Animation Handbook</title>
  <meta name="description" content="A ring closes in around the item the Tab key reaches. Best for forms and menus.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/focus-ring/">
  <link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
  <link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
  <link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
  <meta property="og:type" content="article">
  <meta property="og:site_name" content="Animation Handbook">
  <meta property="og:title" content="Focus Ring Animation — Animation Handbook">
  <meta property="og:description" content="A ring closes in around the item the Tab key reaches. Best for forms and menus.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/focus-ring/">
  <meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="Focus Ring Animation — Animation Handbook">
  <meta name="twitter:description" content="A ring closes in around the item the Tab key reaches. Best for forms and menus.">
  <meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Focus Ring Animation", "name": "Focus Ring Animation", "description": "A ring closes in around the item the Tab key reaches. Best for forms and menus.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/focus-ring/", "inLanguage": "en", "articleSection": "Micro-Interactions", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Micro-Interactions, Focus Ring Animation"}</script>
  <style>
    :root{--ui-accent:#ff9d5c;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-text:#f4f4f2;--ui-muted:#8a8a92;--ring-color:#ff9d5c;--ring-w:2px;--ring-offset:3px;--ring-dur:140ms}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:16px;background:#0b0b0d}
    .form{display:flex;flex-direction:column;gap:12px;width:100%;max-width:340px}
    /* A window this short gives the stage 260 to 290px, less than the form needs: the stage and the form give up some spacing, the items keep their size.
       The bottom keeps 11px, the reach of the widest ring (Thick, Large gap, Wide), so the last item's ring is not cut. */
    @media(min-width:601px) and (max-height:620px){.stage{padding:5px 8px 11px}.form{gap:8px}}
    .field{display:flex;flex-direction:column;gap:6px}
    .field label{font-size:11px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-muted)}
    /* Reset browser outline */
    .focusable{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:inherit;font-size:12px;padding:10px 12px;border-radius:4px;width:100%;outline:none;min-height:44px;transition:border-color var(--ring-dur) ease}
    /* iOS zooms the whole page when a text field or menu under 16px gets focus */
    @media(pointer:coarse){input.focusable,select.focusable{font-size:16px}}
    .focusable::placeholder{color:var(--ui-muted);opacity:1}
    .form-btn{background:var(--ui-accent);color:#000;border:none;font-family:inherit;font-weight:bold;padding:0 20px;cursor:pointer}
    .form-link{color:var(--ui-accent);text-decoration:none;font-family:inherit;padding:10px 2px;display:inline-block;line-height:24px}
    /* The ring is drawn while an item has keyboard focus (:focus-visible) and while Show me points at it (.is-demo). The .stage in front
       makes each rule outrank the site ring and its inward offset inside the stage (.hb-page .stage :focus-visible, 0,3,0), which the
       ring styles would otherwise tie with and lose to. */
    .stage .ring-solid .focusable:is(:focus-visible,.is-demo,.is-pose){border-color:var(--ring-color);outline:var(--ring-w) solid var(--ring-color);outline-offset:var(--ring-offset);animation:ring-in var(--ring-dur) ease-out both}
    .stage .ring-dashed .focusable:is(:focus-visible,.is-demo,.is-pose){border-color:var(--ring-color);outline:var(--ring-w) dashed var(--ring-color);outline-offset:var(--ring-offset);animation:ring-in var(--ring-dur) ease-out both}
    .stage .ring-glow .focusable:is(:focus-visible,.is-demo,.is-pose){border-color:var(--ring-color);outline:var(--ring-w) solid var(--ring-color);outline-offset:var(--ring-offset);box-shadow:0 0 0 5px rgba(255,157,92,.18);animation:ring-in var(--ring-dur) ease-out both}
    .stage .ring-dual .focusable:is(:focus-visible,.is-demo,.is-pose){outline:var(--ring-w) solid var(--ring-color);outline-offset:var(--ring-offset);box-shadow:0 0 0 1px #0b0b0d,0 0 0 calc(var(--ring-w) + 1px + var(--ring-offset)) var(--ring-color);animation:ring-in var(--ring-dur) ease-out both}
    @keyframes ring-in{from{outline-offset:calc(var(--ring-offset) + 8px);opacity:.3}to{outline-offset:var(--ring-offset);opacity:1}}
    /* Reduced motion: keep the focus outline (a11y) but drop the ring-in expansion */
    @media(prefers-reduced-motion:reduce){.focusable,.focusable:focus-visible,.focusable.is-demo{animation:none!important;transition:none!important}}

    /* See inside and Compare. The marks sit behind the form (the form's items cover them where they meet), the captions and their lines above it.
       The copy of the form and everything a view adds are shown only in their mode. */
    .stage{position:relative}
    .plain,.views,.caps,.lbl,.lbl i,.cmp-line{display:none}
    .views{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
    .views *{fill:none;stroke-linecap:round;stroke-linejoin:round}
    .v-start{stroke:var(--ring-color);stroke-opacity:.7;stroke-width:1.5;stroke-dasharray:5 4}
    .v-tick{stroke:#f4f4f2;stroke-width:1.5}
    .v-path{stroke:rgba(244,244,242,.6);stroke-width:1.5}
    .v-lead{stroke:rgba(244,244,242,.5);stroke-width:1}
    .v-node{stroke:#f4f4f2;stroke-width:7}
    .v-dot{stroke:#f4f4f2;stroke-width:5}
    .caps{position:absolute;inset:0;z-index:2;pointer-events:none}
    .lbl{position:absolute;align-items:center;width:max-content;padding:3px 8px;border:1px solid rgba(255,255,255,.14);border-radius:5px;background:rgba(11,11,13,.92);color:#f4f4f2;font:600 12px/1.25 var(--hb-font);text-wrap:balance}
    .lbl i{flex:none;margin-right:7px}
    .k1{border:5px solid transparent;border-top:7px solid #f4f4f2;border-bottom:0}
    .k2,.k3{width:16px;height:10px;border:2px solid var(--ring-color)}
    .k2{border-style:dashed;opacity:.7}
    .k4{width:8px;height:6px;margin:0 11px 0 5px!important;border:1px solid #8a8a92;outline:2px solid var(--ring-color);outline-offset:2px}
    .cmp-l{top:10px;left:10px}
    .cmp-l.second{left:calc(50% + 10px)}
    .cmp-line{position:absolute;left:50%;top:0;bottom:0;width:1px;background:rgba(255,255,255,.14)}
    .stage[data-hb-mode="inside"] .views,.stage[data-hb-mode="inside"] .caps,.stage[data-hb-mode="compare"] .caps,.stage[data-hb-mode="compare"] .cmp-line{display:block}
    .stage[data-hb-mode="inside"] .in-l,.stage[data-hb-mode="compare"] .cmp-l{display:flex}
    /* The pose: Full name carries the ring at rest, without closing in again each time the view is drawn */
    .stage[data-hb-mode="inside"] .focusable.is-pose:not(.is-demo):not(:focus-visible),
    .stage[data-hb-mode="compare"] .focusable.is-pose:not(.is-demo):not(:focus-visible){animation:none}
    /* See inside: the form moves left to make room for the captions (the script sets --fx and --fw); a label gets a backing so the dashed line behind it never cuts its words */
    .stage[data-hb-mode="inside"]{align-items:flex-start}
    .stage[data-hb-mode="inside"] .form{position:relative;z-index:1;margin-left:var(--fx,0px);width:var(--fw,100%)}
    .stage[data-hb-mode="inside"] .field label{align-self:flex-start;margin-left:-3px;padding:0 3px;background:#0b0b0d}
    /* Compare: the copy draws no ring, not even the site's own, on the left; the real form on the right */
    .stage[data-hb-mode="compare"]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:24px;align-items:center;justify-items:center;padding:38px 12px 12px}
    .stage[data-hb-mode="compare"] .plain{display:flex}
    .stage[data-hb-mode="compare"] .plain .focusable:focus-visible{outline:none}
    @media(min-width:601px) and (max-height:639px){.stage[data-hb-mode="compare"] .form>.field:nth-child(even){display:none}}
    @media(max-width:600px){
      .stage[data-hb-mode="inside"]{justify-content:flex-start;padding:10px 16px}
      .stage[data-hb-mode="inside"] .form{gap:18px;margin-left:28px;width:calc(100% - 28px - max(0px, var(--ring-offset) + var(--ring-w) / 2 - 6px))}
      .stage[data-hb-mode="inside"] .form>.field:nth-child(even),.stage[data-hb-mode="compare"] .form>.field:nth-child(even){display:none}
      .stage[data-hb-mode="inside"] .caps{display:flex;flex-direction:column;align-items:flex-start;justify-content:flex-end;gap:4px;padding:10px}
      .stage[data-hb-mode="inside"] .in-l{position:static;max-width:100%}
      .stage[data-hb-mode="inside"] .lbl i{display:block}
      .stage[data-hb-mode="compare"]{grid-template-columns:minmax(0,1fr);grid-template-rows:repeat(2,minmax(0,1fr));padding:2px 12px}
      .stage[data-hb-mode="compare"] .form{flex-direction:row;align-items:flex-end;margin-top:26px}
      .stage[data-hb-mode="compare"] .form>.field:first-child{flex:1 1 0;min-width:0}
      .stage[data-hb-mode="compare"] .form>.field:nth-child(3){flex:none}
      .stage[data-hb-mode="compare"] .field{gap:12px}
      .stage[data-hb-mode="compare"] .cmp-l{top:8px}
      .stage[data-hb-mode="compare"] .cmp-l.second{top:calc(50% + 8px);left:10px}
      .stage[data-hb-mode="compare"] .cmp-line{left:0;right:0;top:50%;bottom:auto;width:auto;height:1px}
    }
  </style>
  <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
  <script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="do" data-hb-autoplay>
<nav class="hb-bar" aria-label="Animation Handbook">
  <a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
  <span class="hb-pager"><a href="../click-ripple/" rel="prev" aria-label="Previous: Click / Tap Ripple"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Click / Tap Ripple</span></a><a href="../button-press-scale/" rel="next" aria-label="Next: Button Press Scale"><span><span class="hb-dir">Next: </span>Button Press Scale</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
  <a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
  <header class="hb-head">
    <p class="hb-cat">04.03 · Micro-Interactions</p>
    <h1>Focus Ring Animation</h1>
    <p class="hb-lede">A ring closes in around the item the Tab key reaches. Best for forms and menus.</p>
  </header>

  <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">1</span>
      <div><h2 id="hb-watch-title">Press Tab</h2><p>Click the first field and press Tab to move through the form, or press Show me.</p></div>
    </div>
    <div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
      <button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
      <button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
      <button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
    </div>
    <div class="stage hb-dots">
      <svg class="views" aria-hidden="true"><rect class="v-start" id="v-start"/><path class="v-tick" id="v-tick"/><path class="v-path" id="v-path"/><path class="v-node" id="v-node"/></svg>
      <div class="form ring-solid" id="the-form">
        <div class="field">
          <label for="f-name">Full name</label>
          <input class="focusable" id="f-name" type="text" placeholder="Your name" autocomplete="off">
        </div>
        <div class="field">
          <label for="f-country">Country</label>
          <select class="focusable" id="f-country">
            <option>Select a country…</option>
            <option>United States</option>
            <option>United Kingdom</option>
            <option>Canada</option>
          </select>
        </div>
        <div class="field">
          <button class="form-btn focusable" type="button">Submit Form</button>
        </div>
        <div class="field">
          <a href="#" class="form-link focusable">Forgot password?</a>
        </div>
      </div>
      <div class="caps" aria-hidden="true">
        <svg class="views"><path class="v-lead" id="v-lead"/><path class="v-dot" id="v-dot"/></svg>
        <span class="lbl in-l" id="cap-path" data-hb-caption><i class="k1"></i>Tab goes down the form in this order</span>
        <span class="lbl in-l" id="cap-from" data-hb-caption><i class="k2"></i>The ring starts out here, faint</span>
        <span class="lbl in-l" id="cap-close" data-hb-caption><i class="k3"></i>and closes in, in a little over a tenth of a second</span>
        <span class="lbl in-l" id="cap-look" data-hb-caption><i class="k4"></i>A small gap and a medium line</span>
        <span class="lbl cmp-l" data-hb-caption>No ring</span>
        <span class="lbl cmp-l second" data-hb-caption>With a ring</span>
        <i class="cmp-line"></i>
      </div>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-demo" data-hb-demo><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/></svg>Show me</button>
      <label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo="css" autocomplete="off"><span>Slow motion</span></label>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, the dashed line is where the ring starts, faint, before it closes in around the item Tab reaches; the arrows show Tab's order. Press Tab, or press Show me.</p>
      <p data-hb-for="compare" hidden>No ring: Tab reaches Full name here too, but nothing shows it; With a ring: you can always see where Tab is. Press Tab through both forms, or Show me.</p>
    </div>
  </section>

  <section class="hb-step hb-try" aria-labelledby="hb-try-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">2</span>
      <div><h2 id="hb-try-title">Try it</h2><p>Change a setting, then try it again or press Show me.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="style-lbl">Ring style</p>
        <div class="seg" id="style-seg" role="group" aria-labelledby="style-lbl">
          <button type="button" data-ring="ring-solid" class="on" aria-pressed="true">Solid</button>
          <button type="button" data-ring="ring-dashed" aria-pressed="false">Dashed</button>
          <button type="button" data-ring="ring-glow" aria-pressed="false">Glow</button>
          <button type="button" data-ring="ring-dual" aria-pressed="false">Wide</button>
        </div>
        <p class="hb-hint">Glow adds a soft halo; Wide fills the gap with color.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="speed-lbl">Speed</p>
        <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
          <button type="button" data-ms="220" aria-pressed="false">Slow</button>
          <button type="button" data-ms="140" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-ms="80" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How quickly the ring closes in around the item.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="width-lbl">Ring thickness</p>
        <div class="seg" id="width-seg" role="group" aria-labelledby="width-lbl">
          <button type="button" data-w="1" aria-pressed="false">Thin</button>
          <button type="button" data-w="2" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-w="4" aria-pressed="false">Thick</button>
        </div>
        <p class="hb-hint">Thicker rings are easier to spot.</p>
      </div>
    </div>
    <details class="hb-options">
      <summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
      <div class="hb-settings">
        <div class="hb-setting">
          <p class="hb-setting-name" id="gap-lbl">Ring gap</p>
          <div class="seg" id="gap-seg" role="group" aria-labelledby="gap-lbl">
            <button type="button" data-gap="0" aria-pressed="false">None</button>
            <button type="button" data-gap="3" class="on" aria-pressed="true">Small</button>
            <button type="button" data-gap="6" aria-pressed="false">Large</button>
          </div>
          <p class="hb-hint">The space between the ring and the item.</p>
        </div>
      </div>
    </details>
  </section>

  <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">3</span>
      <div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
    </div>
    <div class="hb-card">
      <p class="hb-prompt">Add an animated focus ring to [the links, buttons and form fields on your page]. When keyboard focus moves to an item, draw an outline around it that starts a little further out and faint, then closes in to its place, so each Tab press is easy to follow. Show the ring only for keyboard focus, not after mouse clicks, and never remove the browser's focus outline without drawing this one instead. Make sure the ring stands out against every background it sits on. If the visitor has reduced motion turned on, show the ring at once without closing in. Match the settings listed below.</p>
      <div class="hb-chips-box" hidden>
        <p class="hb-chips-title">Your settings</p>
        <ul class="hb-chips"></ul>
      </div>
      <div class="hb-copy-row">
        <button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
        <p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
      </div>
    </div>
    <div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
  </section>

  <section class="hb-about" aria-labelledby="hb-what-title">
    <div class="hb-what">
      <h2 id="hb-what-title">What it is</h2>
      <div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
    </div>
    <div class="hb-fit">
      <h2>Good for</h2>
      <ul class="hb-tags hb-good"><li>Forms</li><li>Buttons</li><li>Links</li><li>Menus</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Non-interactive items</li></ul>
    </div>
  </section>

  <section class="hb-related" aria-labelledby="hb-related-title" hidden>
    <h2 id="hb-related-title">Similar animations</h2>
    <div class="hb-rel-list"></div>
  </section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
  const form=document.getElementById('the-form');
  const stage=document.querySelector('.stage');
  const items=[...form.querySelectorAll('.focusable')];
  const slowTog=document.getElementById('slow-tog');
  const vars=document.documentElement.style;
  const ringStyles=['ring-solid','ring-dashed','ring-glow','ring-dual'];
  let ringDur=140,runTimers=[];
  // What See inside and Compare read: the mode on show, whether a mode press is making the Show me click, the ring's thickness and gap
  const $=id=>document.getElementById(id);
  let mode='normal',modePress=false,ringW=2,ringOff=3,ringStyle='ring-solid';

  // A menu keeps the text spacing it was first drawn with until the page is next laid out (any change at all, a mode press
  // included), when it takes a slightly different spacing. So the menu is laid out again at the visitor's first move, and Normal
  // looks the same before a mode press as after it.
  const menu=document.getElementById('f-country');
  let menuFresh=false;
  function freshMenu(){
    if(menuFresh)return;
    menuFresh=true;menu.style.letterSpacing='.01px';void menu.offsetWidth;menu.style.letterSpacing='';
  }

  // The link only takes the focus; it goes nowhere.
  form.querySelector('.form-link').addEventListener('click',e=>e.preventDefault());

  // Compare's first half: a working copy of the form that draws no ring. Focus is the lesson, so unlike other copies it takes Tab
  // (neither inert nor hidden): ids and for renamed, no ring style class, named for screen readers, shown only in Compare.
  const copy=form.cloneNode(true);
  copy.removeAttribute('id');copy.className='form plain';copy.setAttribute('role','group');copy.setAttribute('aria-label','No ring');
  copy.querySelectorAll('[id]').forEach(el=>{el.id=el.id.replace('f-','c-')});
  copy.querySelectorAll('label').forEach(l=>{l.htmlFor=l.htmlFor.replace('f-','c-')});
  copy.querySelector('.form-link').addEventListener('click',e=>e.preventDefault());
  form.before(copy);
  const copyItems=[...copy.querySelectorAll('.focusable')],everyItem=[...items,...copyItems];

  // Show me: one run at a time. Every timer of the run goes through later(); stopRun() cancels the whole run.
  // later(fn, move, hold) waits move*(slow?3:1) + hold ms: Slow motion triples the movement, never the hold.
  function later(fn,move,hold){
    const id=setTimeout(()=>{runTimers=runTimers.filter(t=>t!==id);fn()},move*(slowTog.checked?3:1)+(hold||0));
    runTimers.push(id);
  }
  function running(){return runTimers.length>0}
  function stopRun(){runTimers.forEach(clearTimeout);runTimers=[];everyItem.forEach(el=>el.classList.remove('is-demo'));settle()}
  // A run's steps, one ring each: the item, and in Compare the copy's item with it (which shows nothing). An item the view hides
  // (the menu and the link on a phone) has no step.
  const steps=()=>items.map((el,i)=>mode==='compare'?[el,copyItems[i]]:[el]).filter(s=>s[0].getClientRects().length);
  // The ring closes in on item i for ringDur and stays 460ms, then moves on; the last one is let go the same way.
  // The run only adds a class and never moves the real focus (that would take a keyboard user's place and open the phone keyboard);
  // a stage item that has the real focus is blurred first, so two rings never show at once. The arrival press is not the visitor's:
  // it does nothing while the visitor is already in the form. A press of See inside or Compare is not the visitor's either, but it
  // does play the run (modePress), as a real press does.
  document.getElementById('btn-demo').addEventListener('click',e=>{
    if(!e.isTrusted&&!modePress&&stage.contains(document.activeElement))return;
    stopRun();
    if(stage.contains(document.activeElement))document.activeElement.blur();
    const list=steps(),ring=(els,on)=>els.forEach(x=>x.classList.toggle('is-demo',on));
    list.forEach((els,i)=>later(()=>{if(i)ring(list[i-1],false);ring(els,true);draw()},i*ringDur,i*460));
    later(()=>{ring(list[list.length-1],false);settle()},list.length*ringDur,list.length*460);
    settle();
  });
  // The visitor pressed, typed, scrolled or touched inside the stage: the run stops. A Tab press from outside the form sends no
  // hb:input (the key goes to the element that had the focus), but the run never moves the focus, so any focus arriving in the
  // stage while it runs is the visitor's.
  document.addEventListener('hb:input',()=>{freshMenu();if(running())stopRun()});
  stage.addEventListener('focusin',e=>{if(e.isTrusted&&running())stopRun()});

  // The mode switch: draws the mode at once. The shared script then presses Show me (not under reduced motion), which plays it.
  document.addEventListener('hb:mode',e=>{
    freshMenu();
    mode=e.detail.mode;
    modePress=true;queueMicrotask(()=>{modePress=false});
    if(mode==='compare'){form.setAttribute('role','group');form.setAttribute('aria-label','With a ring')}
    else{form.removeAttribute('role');form.removeAttribute('aria-label')}
    refresh();
  });

  // ── See inside and Compare ──
  const phone=matchMedia('(max-width:600px)'),reduced=matchMedia('(prefers-reduced-motion:reduce)');
  const cap={path:$('cap-path'),from:$('cap-from'),close:$('cap-close'),look:$('cap-look')},caps=Object.values(cap);
  const mark={start:$('v-start'),tick:$('v-tick'),path:$('v-path'),node:$('v-node'),lead:$('v-lead'),dot:$('v-dot')};
  const FROM=8,SIDE=34; // ring-in starts the ring 8px further out; the captions stand 34px right of the form
  const noteIn=document.querySelector('[data-hb-for="inside"]'),NOTE=noteIn.textContent;
  const secs=ms=>ms<100?'under a tenth of a second':ms<180?'a little over a tenth of a second':ms<230?'about a fifth of a second':
    ms<300?'about a quarter of a second':ms<500?'less than half a second':'about two thirds of a second';
  const GAP={0:'no gap',3:'a small gap',6:'a wide gap'},LINE={1:'a thin',2:'a medium',4:'a thick'};
  const say=(el,t)=>{if(el.lastChild.nodeValue!==t)el.lastChild.nodeValue=t};
  const arrow=(x0,y0,x1,y1)=>{
    const a=Math.atan2(y1-y0,x1-x0),p=k=>`${x1-3.5*Math.cos(a+k)} ${y1-3.5*Math.sin(a+k)}`;
    return`M${x0} ${y0}L${x1} ${y1}M${p(-.6)}L${x1} ${y1}L${p(.6)}`;
  };

  // Words for the settings and for reduced motion, in the captions and in See inside's note
  function words(){
    const r=reduced.matches,gap=ringOff&&ringStyle==='ring-dual'?GAP[ringOff].replace('gap','filled gap'):GAP[ringOff];
    const line=LINE[ringW]+(ringStyle==='ring-dashed'?' dashed':'')+' line'+(ringStyle==='ring-glow'?', with a soft glow':''),text=gap+' and '+line;
    say(cap.from,r?'The ring would start out here, faint':'The ring starts out here, faint');
    say(cap.close,r?'With reduced motion on it appears at once, in its place':'and closes in, in '+secs(ringDur*(slowTog.checked?3:1)));
    say(cap.look,text[0].toUpperCase()+text.slice(1));
    const n=r?"Inside, the dashed line is where the ring would start; with reduced motion on it appears at once around the item Tab reaches, and the arrows show Tab's order. Press Tab, or press Show me.":NOTE;
    if(noteIn.textContent!==n)noteIn.textContent=n;
  }
  // A caption whose words wrap keeps the full width it was given; trim its box to its widest line, its key (phones only) and its edges
  function snug(el){
    const t=document.createRange(),k=el.firstElementChild,c=getComputedStyle(el),ks=getComputedStyle(k);
    const sum=(st,...p)=>p.reduce((n,x)=>n+parseFloat(st[x]),0);
    el.style.width='';t.selectNodeContents(el.lastChild);
    const lines=[...t.getClientRects()].map(q=>q.width);
    if(lines.length>1)el.style.width=Math.ceil(Math.max(...lines))+1+sum(c,'paddingLeft','paddingRight','borderLeftWidth','borderRightWidth')+(k.offsetWidth?k.offsetWidth+sum(ks,'marginLeft','marginRight'):0)+'px';
  }
  // See inside moves the form left to make room for its captions: the left caption, the path, the form and the right captions
  // stand in a row, trimmed to the stage's width. Phones put the captions under the form instead (their own rules).
  function layout(){
    const W=stage.clientWidth,pad=parseFloat(getComputedStyle(stage).paddingLeft);
    if(mode!=='inside'||phone.matches){
      ['--fx','--fw'].forEach(v=>stage.style.removeProperty(v));
      caps.forEach(el=>{el.style.maxWidth=el.style.left=el.style.top='';if(mode==='inside')snug(el);else el.style.width=''});
      return;
    }
    // the right captions stand in a column 280px wide (the left one as wide as its words, at most 130px), then the row is trimmed to
    // the stage: the right captions first (to 150px), then the form (to 195px), then the left caption (to 105px)
    const nat=el=>{el.style.maxWidth=el.style.width='';return el.offsetWidth},right=[cap.from,cap.close,cap.look];
    const C0=280,L0=Math.min(130,nat(cap.path));
    let cut=Math.max(0,L0+42+340+SIDE+C0+24-W);
    const trim=(base,most)=>{const n=Math.min(cut,Math.max(0,most));cut-=n;return base-n};
    const C=trim(C0,C0-150),F=trim(340,145),L=trim(L0,L0-105),fl=(W-(L+42+F+SIDE+C))/2+L+42;
    stage.style.setProperty('--fx',fl-pad+'px');stage.style.setProperty('--fw',F+'px');
    cap.path.style.maxWidth=L+'px';right.forEach(el=>{el.style.maxWidth=C+'px'});caps.forEach(snug);
  }
  // With nothing running and the focus outside the form, See inside and Compare pose the ring on Full name (a class, not the real
  // focus). A run, or a visitor in the form, lifts it; it comes back when the run ends, the focus leaves, or a mode, a setting
  // or the size changes.
  function settle(){
    items[0].classList.toggle('is-pose',mode!=='normal'&&!running()&&!stage.contains(document.activeElement));
    draw();
  }
  function refresh(){words();layout();settle()}
  // See inside's marks and captions, in the stage's pixels, from the numbers the page uses: the ring's gap and thickness, the 8px
  // it starts further out, and the boxes of the items. They follow the ring from item to item.
  function draw(){
    if(mode!=='inside')return;
    const sb=stage.getBoundingClientRect(),H=stage.clientHeight,small=phone.matches;
    const R=el=>{const b=el.getBoundingClientRect();return{l:b.left-sb.left-stage.clientLeft,t:b.top-sb.top-stage.clientTop,w:b.width,h:b.height}};
    const shown=items.filter(el=>el.getClientRects().length),rows=shown.map(R),on=shown.find(el=>el.matches(':focus-visible,.is-demo,.is-pose'));
    const r=on&&R(on),fr=R(form),ys=rows.map(q=>q.t+q.h/2),xp=fr.l-(small?26:30),last=rows[rows.length-1];
    // Tab's order: a line down the form's left side, a dot at each item, an arrowhead half way between
    mark.path.setAttribute('d',`M${xp} ${ys[0]}V${ys[ys.length-1]}`+ys.slice(1).map((y,i)=>{const m=(ys[i]+y)/2;return`M${xp-4} ${m-3}L${xp} ${m+2}L${xp+4} ${m-3}`}).join(''));
    mark.node.setAttribute('d',ys.map(y=>`M${xp} ${y}h.01`).join(''));
    // The captions: on desktop the three about the ring in a stack right of the form, level with the ringed item, the one about the path left of the path
    const mids=[],mid=(rows[0].t+last.t+last.h)/2,fit=(y,h)=>Math.max(8,Math.min(H-8-h,y));
    if(!small){
      const right=[cap.from,cap.close,cap.look],hs=right.map(el=>el.offsetHeight),stack=hs.reduce((a,h)=>a+h+8,-8);
      let y=fit((r?r.t+r.h/2:mid)-stack/2,stack);
      right.forEach((el,i)=>{el.style.left=fr.l+fr.w+SIDE+'px';el.style.top=y+'px';mids[i]=y+hs[i]/2;y+=hs[i]+8});
      cap.path.style.left=Math.max(8,xp-12-cap.path.offsetWidth)+'px';cap.path.style.top=fit(mid-cap.path.offsetHeight/2,cap.path.offsetHeight)+'px';
    }
    // The ring's start: a faint dashed outline 8px beyond the ring, short arrows at its corners, and a line from each caption
    let tick='',lead='',dots='';
    mark.start.style.display=r?'':'none';
    [cap.from,cap.close,cap.look].forEach(el=>{el.style.visibility=r?'':'hidden'});
    if(r){
      const d=ringOff+FROM+ringW/2;
      Object.entries({x:r.l-d,y:r.t-d,width:r.w+2*d,height:r.h+2*d,rx:4+d}).forEach(([k,v])=>mark.start.setAttribute(k,v));
      [[-1,-1],[1,-1],[-1,1],[1,1]].forEach(([sx,sy])=>{
        const cx=r.l+(sx<0?4:r.w-4),cy=r.t+(sy<0?4:r.h-4),at=o=>[cx+sx*(4+o)*.7071,cy+sy*(4+o)*.7071];
        tick+=arrow(...at(d+7),...at(ringOff+ringW+1.5));
      });
      if(!small){
        const yc=r.t+r.h/2,xr=r.l+r.w;
        [[xr+d,yc-13],[xr+ringOff+ringW/2,yc],[xr+ringOff/2,yc+13]].forEach(([x,y],i)=>{lead+=`M${fr.l+fr.w+SIDE} ${mids[i]}L${x} ${y}`;dots+=`M${x} ${y}h.01`});
      }
    }
    mark.tick.setAttribute('d',tick);mark.lead.setAttribute('d',lead);mark.dot.setAttribute('d',dots);
  }
  // Focus coming or going changes what is ringed; a new size of the window changes every place; the font changes the captions' size
  ['focusin','focusout'].forEach(t=>stage.addEventListener(t,()=>{if(mode!=='normal')setTimeout(settle)}));
  addEventListener('resize',()=>{if(mode!=='normal')refresh()});
  slowTog.addEventListener('change',()=>{if(mode==='inside')refresh()});
  reduced.addEventListener('change',refresh);
  document.fonts&&document.fonts.ready.then(()=>{if(mode!=='normal')refresh()});
  words();

  function choices(id,pick){
    const buttons=document.querySelectorAll('#'+id+' button');
    buttons.forEach(b=>b.addEventListener('click',()=>{
      buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
      pick(b.dataset);
      freshMenu();
      if(mode!=='normal')refresh();
    }));
  }
  choices('style-seg',d=>{ringStyle=d.ring;form.classList.remove(...ringStyles);form.classList.add(d.ring)});
  choices('speed-seg',d=>{ringDur=+d.ms;vars.setProperty('--ring-dur',ringDur+'ms')});
  choices('width-seg',d=>{ringW=+d.w;vars.setProperty('--ring-w',d.w+'px')});
  choices('gap-seg',d=>{ringOff=+d.gap;vars.setProperty('--ring-offset',d.gap+'px')});
</script>
</body>
</html>