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.

33.4 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>Star Rating — Animation Handbook</title>
  <meta name="description" content="Stars fill up to your pointer and pop when you choose. Best for reviews.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/star-rating/">
  <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="Star Rating — Animation Handbook">
  <meta property="og:description" content="Stars fill up to your pointer and pop when you choose. Best for reviews.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/star-rating/">
  <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="Star Rating — Animation Handbook">
  <meta name="twitter:description" content="Stars fill up to your pointer and pop when you choose. Best for reviews.">
  <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": "Star Rating", "name": "Star Rating", "description": "Stars fill up to your pointer and pop when you choose. Best for reviews.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/star-rating/", "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, Star Rating"}</script>
  <style>
    :root{--ui-accent:#ff9d5c;--ui-muted:#8a8a92;--bg:#0b0b0d;--star:clamp(44px,11vw,60px);--pop:1.35;--fill-dur:180ms}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:clamp(18px,4vh,32px);padding:clamp(16px,4vw,40px);background:var(--bg)}
    /* Rating control */
    .rate{--gap:clamp(4px,1.5vw,12px);display:inline-flex;flex-wrap:wrap;justify-content:center;max-width:100%;gap:var(--gap);outline:none;touch-action:none}
    /* the row draws its own focus look, so it also hides the site ring (.stage keeps this above body.hb :focus-visible). The outline stays, transparent, for forced-colors mode, which removes box-shadow. */
    .stage .rate:focus-visible{outline:2px solid transparent;box-shadow:0 0 0 2px var(--bg),0 0 0 4px var(--ui-accent);border-radius:8px}
    .star{position:relative;width:var(--star);height:var(--star);color:var(--ui-muted);cursor:pointer;transition:color var(--fill-dur) ease;-webkit-tap-highlight-color:transparent;transform-origin:center;will-change:transform}
    .star svg{position:absolute;inset:0;width:100%;height:100%;display:block}
    .star .half{position:absolute;left:0;top:0;height:100%;width:50%;overflow:hidden;color:var(--ui-accent);opacity:0}
    .star .half svg{width:var(--star)}
    .star.full{color:var(--ui-accent)}
    .star.half-on .half{opacity:1}
    @keyframes pop{0%{transform:scale(1)}35%{transform:scale(var(--pop))}70%{transform:scale(.94)}100%{transform:scale(1)}}
    .star.pop{animation:pop .42s cubic-bezier(.22,1,.36,1)}
    .value{font-weight:700;font-size:clamp(20px,5vw,32px)}
    .value small{font-weight:400;font-size:clamp(11px,1.6vw,14px);color:var(--ui-muted)}
    /* More than five stars that cannot share one row wrap into two equal rows, not nine and one. Ten stars fit one row from 846px wide, or 864px with classic scrollbars, so the two rows hold up to 870px */
    @media(max-width:870px){.rate.many{max-width:calc(5*var(--star) + 4*var(--gap) + 1px)}}
    @media(prefers-reduced-motion:reduce){.star{transition:none}.star.pop{animation:none}}
    /* See inside and Compare: two panes (no box in Normal) hold the real row and the copy; all that is drawn sits in .views, which lets the pointer through */
    .pane{display:contents}
    .pane.twin,.views,.picks,.popo,.mark{display:none}
    .twin .star{transition:none;will-change:auto}
    .views{position:absolute;inset:0;pointer-events:none}
    .pick,.popo{position:absolute;border:2px dashed rgba(244,244,242,.6);border-radius:8px}
    .pick.mid::after{content:"";position:absolute;left:50%;top:0;bottom:0;margin-left:-1px;border-left:2px dashed rgba(244,244,242,.6)}
    .popo{border-color:var(--ui-accent);border-radius:12px}
    .mark{position:absolute;width:12px;height:8px;background:#f4f4f2;clip-path:polygon(50% 0,0 100%,100% 100%)}.mark.dn{clip-path:polygon(0 0,100% 0,50% 100%)}
    .lbl{position:absolute;display:none;width:max-content;max-width:min(290px,calc(100% - 10px));padding:3px 7px;border-radius:5px;background:rgba(11,11,13,.92);color:#f4f4f2;font:600 13px/1.25 var(--hb-font)}
    .cmp-l{top:10px;left:12px;white-space:nowrap}
    @media(max-width:340px){.lbl{font-size:12px}}
    /* each See inside label starts with a small copy of the mark it names */
    .lbl[data-k]::before{content:"";display:inline-block;width:10px;height:10px;margin-right:6px;vertical-align:-1px;border:1.5px dashed rgba(244,244,242,.75);border-radius:3px}
    .lbl[data-k="pop"]::before{border-color:var(--ui-accent)}
    .lbl[data-k="chosen"]::before,.lbl[data-k="prev"]::before{border:0;background:#f4f4f2;clip-path:polygon(50% 0,0 100%,100% 100%)}
    .lbl[data-k="prev"]::before{clip-path:polygon(0 0,0 86%,33% 66%,57% 100%,77% 94%,53% 60%,100% 60%)}
    .cmp-div{position:absolute;display:none;left:50%;top:0;bottom:0;width:1px;background:rgba(244,244,242,.2)}
    .lay{position:absolute;inset:0}
    .ptr{position:absolute;left:0;top:0;display:none;fill:#f4f4f2;stroke:#0b0b0d;stroke-width:1.5;stroke-linejoin:round;overflow:visible}
    .ptr.on{display:block}
    @media(prefers-reduced-motion:no-preference){.glide .ptr{transition:transform .11s linear}}
    .stage[data-hb-mode="inside"] .views,.stage[data-hb-mode="compare"] .views{display:block}
    .stage[data-hb-mode="inside"] .picks,.stage[data-hb-mode="inside"] .popo,.stage[data-hb-mode="inside"] .mark{display:block}
    .stage[data-hb-mode="inside"]{gap:clamp(44px,10vh,58px)}
    .stage[data-hb-mode="inside"] .in-l,.stage[data-hb-mode="compare"] .cmp-l,.stage[data-hb-mode="compare"] .cmp-div{display:block}
    /* Compare: the copy first (left, or on top where they stack), each pane's row below its name; phone star size below 871px, Ten stars wrap five and five */
    .stage[data-hb-mode="compare"]{display:grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr;align-items:stretch;padding:0;gap:0}
    .stage[data-hb-mode="compare"] .pane{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:clamp(8px,2.4vh,20px);min-width:0;min-height:0;padding:38px 12px 10px}
    .stage[data-hb-mode="compare"] .twin{order:-1}.stage[data-hb-mode="compare"] .second{left:calc(50% + 12px)}
    .stage[data-hb-mode="compare"] .rate.many{max-width:calc(5*var(--star) + 4*var(--gap) + 1px)}
    .stage[data-hb-mode="compare"] .lay-a{clip-path:inset(0 50% 0 0)}.stage[data-hb-mode="compare"] .lay-b{clip-path:inset(0 0 0 50%)}
    /* two rows in a short or stacked half: the number moves up onto the name's line */
    .stage[data-hb-mode="compare"].tight .rate.many + .value{position:absolute;top:8px;right:12px;font-size:20px}
    @media(max-width:870px){.stage[data-hb-mode="compare"]{--star:44px}.stage[data-hb-mode="inside"] .rate.many{--star:44px}}
    @media(max-width:660px){
      .stage[data-hb-mode="compare"]{grid-template-columns:1fr;grid-template-rows:1fr 1fr}
      .stage[data-hb-mode="compare"] .cmp-div{left:0;right:0;top:50%;bottom:auto;width:auto;height:1px}
      .stage[data-hb-mode="compare"] .second{left:12px;top:calc(50% + 10px)}
      .stage[data-hb-mode="compare"] .lay-a{clip-path:inset(0 0 50% 0)}.stage[data-hb-mode="compare"] .lay-b{clip-path:inset(50% 0 0 0)}
    }
  </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="../copy-to-clipboard/" rel="prev" aria-label="Previous: Copy to Clipboard"><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>Copy to Clipboard</span></a><a href="../toast-notification/" rel="next" aria-label="Next: Toast Notification"><span><span class="hb-dir">Next: </span>Toast Notification</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.26 · Micro-Interactions</p>
    <h1>Star Rating</h1>
    <p class="hb-lede">Stars fill up to your pointer and pop when you choose. Best for reviews.</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">Click it</h2><p>Point along the stars and click or tap one to choose, 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">
      <div class="pane">
        <div class="rate" id="rate" role="slider" tabindex="0" aria-label="Rating"
             aria-valuemin="0" aria-valuemax="5" aria-valuenow="3" aria-valuetext="3 out of 5"></div>
        <div class="value"><span id="val">3.0</span><small> / <span id="max">5</span></small></div>
      </div>
      <div class="pane twin" aria-hidden="true" inert>
        <div class="rate"></div>
        <div class="value"><span>3.0</span><small> / <span>5</span></small></div>
      </div>
      <div class="views" aria-hidden="true">
        <div class="cmp-div"></div>
        <div class="picks"></div>
        <div class="popo"></div>
        <div class="mark"></div>
        <span class="lbl in-l" data-k="prev" data-hb-caption>Pointing here previews 4</span>
        <span class="lbl in-l" data-k="chosen" data-hb-caption>Chosen: 3, shown again when you leave</span>
        <span class="lbl in-l" data-k="pop" data-hb-caption>Pops a third bigger when chosen</span>
        <span class="lbl in-l" data-k="pick" data-hb-caption>Each dashed box picks one star</span>
        <span class="lbl cmp-l" data-hb-caption>Click only</span>
        <span class="lbl cmp-l second" data-hb-caption>Previews and pops</span>
        <!-- the pretend pointer and, in Compare, its ghost over the copy: after the labels, so no label hides them -->
        <div class="lay lay-a"><svg class="ptr" id="ghost" width="15" height="22" viewBox="0 0 15 22"><path d="M0 0V19L5 14.5L8.5 22L11.5 20.7L8 13.3H14.5Z"/></svg></div>
        <div class="lay lay-b"><svg class="ptr" id="pretend" width="15" height="22" viewBox="0 0 15 22"><path d="M0 0V19L5 14.5L8.5 22L11.5 20.7L8 13.3H14.5Z"/></svg></div>
      </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, each dashed box is the spot that picks a star: pointing previews the rating, clicking chooses it and the chosen star pops. Point along the stars, or press Show me.</p>
      <p data-hb-for="compare" hidden>Click only: nothing shows until you click; Previews and pops: the stars fill up to the pointer first, and the chosen one pops. Point along the stars, or press 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="pop-lbl">Pop size</p>
        <div class="seg" id="pop-seg" role="group" aria-labelledby="pop-lbl">
          <button type="button" data-pop="1.15" aria-pressed="false">Small</button>
          <button type="button" data-pop="1.35" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-pop="1.6" aria-pressed="false">Large</button>
        </div>
        <p class="hb-hint">How much the chosen star grows as it pops.</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="300" aria-pressed="false">Slow</button>
          <button type="button" data-ms="180" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-ms="110" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How quickly each star fills with color.</p>
      </div>
      <div class="hb-setting">
        <label class="hb-switch-row"><span>Allows half stars</span><input class="hb-switch" type="checkbox" role="switch" id="half-tog" autocomplete="off"></label>
        <p class="hb-hint">The left half of a star gives half a point.</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="count-lbl">Number of stars</p>
          <div class="seg" id="count-seg" role="group" aria-labelledby="count-lbl">
            <button type="button" data-n="3" aria-pressed="false">Three</button>
            <button type="button" data-n="5" class="on" aria-pressed="true">Five</button>
            <button type="button" data-n="10" aria-pressed="false">Ten</button>
          </div>
          <p class="hb-hint">Five is the usual scale; ten gives finer steps.</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 a star rating to [the review or feedback form]. As the pointer moves along the row, fill the stars up to the one under it so the choice shows before it is made, and bring back the chosen rating when the pointer leaves. Clicking or tapping a star chooses that rating and makes the star pop: it grows briefly, dips a little below its size and settles. On touch screens, a finger dragged along the row previews too. Make the row one control that the arrow keys can change, and show the rating as a number as well, so it never depends on color alone. If the visitor has reduced motion turned on, fill the stars without the pop. 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>Reviews</li><li>Surveys</li><li>Feedback forms</li><li>Media ratings</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Precise scores</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 STAR='M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14l-5-4.87 6.91-1.01L12 2z';
  const stage=document.querySelector('.stage');
  const rate=document.getElementById('rate'),valEl=document.getElementById('val'),maxEl=document.getElementById('max');
  const slowTog=document.getElementById('slow-tog');
  const vars=document.documentElement.style;
  const starSvg=`<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="${STAR}"/></svg>`;
  let count=5,rating=3,step=1,runTimers=[];
  // See inside and Compare: the parts drawn over the stage, the copy of the row, and what the pretend pointer is doing
  const views=stage.querySelector('.views'),picks=views.querySelector('.picks'),popo=views.querySelector('.popo'),mark=views.querySelector('.mark');
  const twinRow=stage.querySelector('.twin .rate'),twinVal=stage.querySelector('.twin .value span'),twinMax=stage.querySelector('.twin small span');
  const valueBox=stage.querySelector('.value'),ghost=document.getElementById('ghost'),pretend=document.getElementById('pretend');
  const lbl={};views.querySelectorAll('.in-l').forEach(el=>lbl[el.dataset.k]=el);
  const RM=matchMedia('(prefers-reduced-motion: reduce)'),stackedMQ=matchMedia('(max-width:660px)');
  // aim: the value the pretend pointer points at (null: none); inRow: a real pointer or finger is on the row; keyed: the keys changed the rating
  let mode='normal',aim=null,inRow=false,keyed=false,rp=null,lastKey='';

  function build(){
    rate.innerHTML='';
    for(let i=0;i<count;i++){
      const s=document.createElement('span');
      s.className='star';s.dataset.i=i;
      s.innerHTML=starSvg+'<span class="half">'+starSvg+'</span>';
      rate.appendChild(s);
    }
    rate.classList.toggle('many',count>5);
    twinRow.innerHTML=rate.innerHTML;twinRow.classList.toggle('many',count>5);twinMax.textContent=count;
    picks.innerHTML='<i class="pick"></i>'.repeat(count);
    rate.setAttribute('aria-valuemax',count);
    maxEl.textContent=count;
    if(rating>count)rating=count;
    commit(false);
  }
  // Paint stars up to value v (0..count), supporting halves.
  function render(v){
    rate.querySelectorAll('.star').forEach((s,i)=>{
      s.classList.toggle('full',v>=i+1);
      s.classList.toggle('half-on',v>=i+0.5&&v<i+1);
    });
  }
  // The chosen rating: stars, number and what a screen reader hears. The visitor's click, tap and keys and Show me all end here.
  function commit(doPop){
    render(rating);
    valEl.textContent=rating.toFixed(1);
    rate.setAttribute('aria-valuenow',rating);
    rate.setAttribute('aria-valuetext',rating+' out of '+count);
    if(doPop&&rating>0){
      const star=rate.querySelector('.star[data-i="'+(Math.ceil(rating)-1)+'"]');
      if(star){star.classList.remove('pop');void star.offsetWidth;star.classList.add('pop')}
    }
    if(mode!=='normal'){if(mode==='compare')syncTwin();draw()}
  }
  // Map a pointer position within a star to a rating value.
  function valueAt(star,clientX){
    const i=+star.dataset.i,r=star.getBoundingClientRect();
    if(step===0.5&&clientX-r.left<r.width/2)return i+0.5;
    return i+1;
  }
  // The star under the pointer. A finger keeps hitting the star it first touched (touch pointers stay captured by it),
  // so a drag along the row has to ask what is at its position.
  function starAt(e){
    const el=document.elementFromPoint(e.clientX,e.clientY);
    return el&&el.closest('.star');
  }
  rate.addEventListener('pointermove',e=>{
    const star=starAt(e);if(star)render(valueAt(star,e.clientX));
  });
  rate.addEventListener('pointerleave',()=>render(rating));
  rate.addEventListener('pointerdown',e=>{
    const star=starAt(e);if(!star)return;
    rating=valueAt(star,e.clientX);rate.focus();commit(true);
  });
  rate.addEventListener('keydown',e=>{
    if(e.altKey||e.ctrlKey||e.metaKey)return;
    let handled=true;
    if(e.key==='ArrowRight'||e.key==='ArrowUp')rating=Math.min(count,rating+step);
    else if(e.key==='ArrowLeft'||e.key==='ArrowDown')rating=Math.max(0,rating-step);
    else if(e.key==='Home')rating=0;
    else if(e.key==='End')rating=count;
    else handled=false;
    if(handled){e.preventDefault();commit(true)}
  });

  // 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(keep){runTimers.forEach(clearTimeout);runTimers=[];render(rating);aim=null;if(!keep)settle()}
  // A run starts at the resting rating of 3, put there without animating: the fill transitions are turned off, the stars are
  // filled, a reflow makes it stick, and the transitions come back.
  function toRest(){
    const stars=[...rate.querySelectorAll('.star')];
    stars.forEach(s=>{s.style.setProperty('transition','none','important');s.classList.remove('pop')});
    rating=3;commit(false);
    void rate.offsetWidth;
    stars.forEach(s=>s.style.removeProperty('transition'));
  }
  // An invisible pointer sweeps along the row, one star every 120ms, and comes back one star; that star is chosen and pops
  // (420ms), and 1200ms later the rating goes back to 3. The run never moves the focus. Each step reads the current settings.
  document.getElementById('btn-demo').addEventListener('click',()=>{
    stopRun(true);aim=null;
    toRest();
    const n=count;
    for(let i=0;i<n;i++)later(()=>{render(i+1);look(i+1)},i*120);
    later(()=>{render(count-1);look(count-1)},n*120);
    later(()=>{rating=step===0.5?count-0.5:count-1;commit(true);look(rating)},(n+1)*120);
    later(()=>{rating=3;aim=null;commit(false);settle()},(n+1)*120+420,1200);
  });
  // The visitor pressed, typed, scrolled or touched inside the stage, or moved a pointer over it (the row's own hover preview
  // would fight the sweep): the run stops and the stars show the chosen rating.
  document.addEventListener('hb:input',()=>{if(running())stopRun()});
  stage.addEventListener('pointermove',e=>{if(e.isTrusted&&running())stopRun()},true);

  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);
      refresh();
    }));
  }
  choices('pop-seg',d=>vars.setProperty('--pop',d.pop));
  choices('speed-seg',d=>vars.setProperty('--fill-dur',d.ms+'ms'));
  choices('count-seg',d=>{count=+d.n;build()});
  document.getElementById('half-tog').addEventListener('change',e=>{
    step=e.target.checked?0.5:1;
    if(!e.target.checked)rating=Math.round(rating);
    commit(false);
    refresh();
  });

  // ---- See inside and Compare ----
  // The mode switch: the shared script marks the stage, then sends this. Each view is drawn at once; Normal gets its own picture back.
  document.addEventListener('hb:mode',e=>{
    mode=e.detail.mode;lastKey='';
    if(mode==='compare')syncTwin();
    if(mode==='normal'){aim=null;if(idle())snap(()=>render(rating))}else snap(settle);
  });
  function idle(){return!inRow&&!keyed&&!running()}
  function snap(fn){const stars=[...rate.children];stars.forEach(s=>s.style.setProperty('transition','none','important'));fn();void rate.offsetWidth;stars.forEach(s=>s.style.removeProperty('transition'))}
  // Resting picture: a pretend pointer over the fourth star (the second with three) and the row previewing up to it by render() only, never the rating. It lifts for a pointer, a key or Show me.
  function poseValue(){const c=[count>3?4:2,2,count].map(n=>n-(step===.5?.5:0));return c.find(v=>v!==rating)}
  function settle(){if(mode==='normal')return;if(idle()){aim=poseValue();render(aim)}draw()}
  function refresh(){lastKey='';settle()}
  function look(v){if(mode!=='normal'&&v>0){aim=v;draw()}}
  function syncTwin(){
    twinRow.querySelectorAll('.star').forEach((st,i)=>{st.classList.toggle('full',rating>=i+1);st.classList.toggle('half-on',rating>=i+.5&&rating<i+1)});
    twinVal.textContent=rating.toFixed(1);
  }
  function track(e){inRow=true;aim=null;if(mode==='normal')return;const r=rate.getBoundingClientRect();rp={x:e.clientX-r.left,y:e.clientY-r.top};draw()}
  ['pointerenter','pointerdown','pointermove'].forEach(t=>rate.addEventListener(t,track));
  rate.addEventListener('pointerleave',()=>{inRow=false;rp=null;settle()});
  rate.addEventListener('keydown',e=>{if(e.defaultPrevented){keyed=true;aim=null;draw()}});
  rate.addEventListener('blur',()=>{keyed=false;settle()});
  slowTog.addEventListener('change',refresh);
  addEventListener('resize',refresh);
  document.fonts.ready.then(refresh);

  const fmt=v=>v%1?(Math.floor(v)||'')+'½':String(v);
  const shown=()=>rate.querySelectorAll('.star.full').length+(rate.querySelector('.star.half-on')?.5:0);
  const cssNum=n=>parseFloat(getComputedStyle(stage).getPropertyValue(n));
  // where an element is, from the stage's padding box; the stars from their layout boxes, which the pop's scale never moves
  function boxOf(el){const s=stage.getBoundingClientRect(),r=el.getBoundingClientRect();return{x:r.left-s.left-stage.clientLeft,y:r.top-s.top-stage.clientTop,w:r.width,h:r.height}}
  function starsOf(row){const b=boxOf(row);return[...row.children].map(c=>({x:b.x+c.offsetLeft-row.offsetLeft,y:b.y+c.offsetTop-row.offsetTop,w:c.offsetWidth,h:c.offsetHeight}))}
  function ptr(el,p){const was=el.classList.contains('on');el.classList.toggle('on',!!p);if(!p)return;el.style.transition=was?'':'none';el.style.transform=`translate(${p.x}px,${p.y}px)`;if(!was){void el.getBoundingClientRect();el.style.transition=''}}
  const hit=(a,b)=>a.x<b.x+b.w+3&&b.x<a.x+a.w+3&&a.y<b.y+b.h+3&&b.y<a.y+a.h+3;
  // The nearest spot beside R that the label can have inside the box without touching anything taken
  function spot(el,R,taken){
    const W=stage.clientWidth,H=stage.clientHeight;
    const scan=()=>{
      const w=el.offsetWidth,h=el.offsetHeight;
      let best={low:1e9};
      for(let y=5;y<=Math.max(5,H-h-5);y+=4)for(let x=5;x<=Math.max(5,W-w-5);x+=8){
        const c={x,y,w,h},near=Math.hypot(Math.max(R.x-x-w,x-R.x-R.w,0),Math.max(R.y-y-h,y-R.y-R.h,0));
        const low=taken.reduce((n,t)=>n+hit(c,t),0)*1e4+near+Math.hypot(x+w/2-R.x-R.w/2,y+h/2-R.y-R.h/2)/100;
        if(low<best.low)best={...c,low};
      }
      return best;
    };
    // a label with no free place on one line is tried on two
    el.style.maxWidth='';let best=scan();
    if(best.low>=1e4){el.style.maxWidth='190px';const two=scan();if(two.low<best.low)best=two;else el.style.maxWidth=''}
    el.style.left=best.x+'px';el.style.top=best.y+'px';taken.push(best);return best.low;
  }
  function words(){const ms=cssNum('--fill-dur')*(slowTog.checked?3:1);return ms<145?'a tenth of a second':ms<240?'a fifth of a second':ms<420?'a third of a second':ms<750?'half a second':'a second'}
  function at(fr,v){const f=fr[Math.ceil(v)-1];return{x:f.x+f.w*(v%1?.25:.5),y:f.y+f.h/2}}
  // Draws the mode for what is happening now (nothing in Normal)
  function draw(){
    if(mode==='normal')return;
    stage.classList.toggle('tight',mode==='compare'&&(stackedMQ.matches||stage.clientHeight<300));
    views.classList.toggle('glide',running());
    const fr=starsOf(rate),rb=boxOf(rate),q=aim!==null?at(fr,aim):null;
    const P=inRow&&rp?rp:q&&{x:q.x-rb.x,y:q.y-rb.y};   // the pointer in the row's own frame
    const tip=q&&!inRow&&{x:rb.x+P.x,y:rb.y+P.y};
    ptr(pretend,tip);
    if(mode==='compare'){const tb=boxOf(twinRow);ptr(ghost,P&&{x:tb.x+P.x,y:tb.y+P.y});return}
    ptr(ghost,null);
    inside(fr,rb);
  }
  function inside(fr,rb){
    const W=stage.clientWidth,H=stage.clientHeight,rm=RM.matches,pop=cssNum('--pop'),half=step===.5,sh=shown(),pointing=aim!==null||inRow;
    const key=[sh,rating,aim,inRow,count,step,pop,rm,words(),W,H,rb.x,rb.y,rb.w,fr[0].w].join();
    if(key===lastKey)return;
    lastKey=key;
    [...picks.children].forEach((el,i)=>{Object.assign(el.style,{left:fr[i].x+'px',top:fr[i].y+'px',width:fr[i].w+'px',height:fr[i].h+'px'});el.classList.toggle('mid',half)});
    const taken=[...fr,boxOf(valueBox)],all={x:rb.x,y:rb.y,w:rb.w,h:rb.h},f=fr[Math.ceil(rating)-1],chosen=rating>0&&!!f;
    const show=(k,on,txt)=>{lbl[k].style.display=on?'':'none';if(on&&lbl[k].textContent!==txt)lbl[k].textContent=txt;return on};
    popo.style.display=chosen&&!rm?'':'none';mark.style.display=chosen?'':'none';
    let o,m;
    if(chosen){
      const ov=rm?0:(pop-1)*f.h/2,upper=new Set(fr.map(c=>Math.round(c.y))).size>1&&fr.every(c=>c.y>=f.y-1);
      o={x:f.x-ov,y:f.y-ov,w:f.w+2*ov,h:f.h+2*ov};
      m={x:f.x+f.w/2-6,y:upper?o.y-11:o.y+o.h+3,w:12,h:8};
      Object.assign(popo.style,{left:o.x+'px',top:o.y+'px',width:o.w+'px',height:o.h+'px'});
      Object.assign(mark.style,{left:m.x+'px',top:m.y+'px'});mark.classList.toggle('dn',upper);
      taken.push(m);if(!rm)taken.push(o);
    }
    const on={chosen:show('chosen',chosen,`Chosen: ${fmt(rating)}, shown again when you leave`),
      pop:show('pop',chosen&&!rm,`Pops ${pop<1.25?'a little bigger':pop<1.5?'a third bigger':'over half again as big'} when chosen`),
      pick:show('pick',true,half?"Each box's left half picks half a star":'Each dashed box picks one star'),
      prev:show('prev',pointing&&sh>0,`Pointing here previews ${fmt(sh)}: stars fill to it${rm?' at once':', each in about '+words()}`)};
    const part={chosen:m,pop:o,pick:all,prev:fr[Math.ceil(sh)-1]};
    const put=keys=>{const t=[...taken];return Math.max(0,...keys.filter(k=>on[k]).map(k=>spot(lbl[k],part[k],t)))};
    // the labels that do not follow the pointer go first, so they stay put while it moves; where its label then has no place close to its star, it goes first
    if(put(['chosen','pop','pick','prev'])>=50)put(['prev','chosen','pop','pick']);
  }
  // The notes in the markup are for motion; under reduced motion the pop is left out of both
  const notes=[document.querySelector('[data-hb-for="inside"]'),document.querySelector('[data-hb-for="compare"]')];
  const NOTES=notes.map(n=>n.textContent),NOTES_RM=['Inside, each dashed box is the spot that picks a star: pointing previews the rating and clicking chooses it. Point along the stars, or press Show me.',
    'Click only: nothing shows until you click; Previews and pops: the stars fill up to the pointer first, and the chosen one pops when motion is on. Point along the stars.'];
  function writeNotes(){notes.forEach((n,i)=>{const t=(RM.matches?NOTES_RM:NOTES)[i];if(n.textContent!==t)n.textContent=t})}
  writeNotes();RM.addEventListener('change',()=>{writeNotes();refresh()});
  build();
</script>
</body>
</html>