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.

37.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>Drag to Reorder — Animation Handbook</title>
  <meta name="description" content="Drag an item and the others slide aside to make room. Best for to-do lists.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/drag-to-reorder/">
  <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="Drag to Reorder — Animation Handbook">
  <meta property="og:description" content="Drag an item and the others slide aside to make room. Best for to-do lists.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/drag-to-reorder/">
  <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="Drag to Reorder — Animation Handbook">
  <meta name="twitter:description" content="Drag an item and the others slide aside to make room. Best for to-do lists.">
  <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": "Drag to Reorder", "name": "Drag to Reorder", "description": "Drag an item and the others slide aside to make room. Best for to-do lists.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/drag-to-reorder/", "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, Drag to Reorder"}</script>
  <style>
    :root{--ui-accent:#ff9d5c;--ui-text:#f4f4f2;--ui-muted:#8a8a92;--card:#16161a;--slide:220ms;--row:52px;--gap:8px;--col:244px}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;display:flex;align-items:center;justify-content:center;padding:12px clamp(16px,4vw,32px);background:#0b0b0d;overflow:hidden}
    /* Every row sits at the top of the list and is moved to its place, slot --i, with a transform, so a new order never changes the layout */
    .list{position:relative;width:100%;max-width:360px;height:calc(4*var(--row) + 3*var(--gap));list-style:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
    .row{position:absolute;left:0;right:0;top:0;height:var(--row);transform:translateY(calc(var(--i)*(var(--row) + var(--gap))));transition:transform var(--slide) cubic-bezier(.2,.8,.2,1);cursor:grab;touch-action:pan-y}
    .row.lifted{z-index:2;cursor:grabbing}.row.settling{z-index:1}
    .card{position:relative;height:100%;display:flex;align-items:center;gap:10px;padding-right:14px;border:1px solid rgba(255,255,255,.1);border-radius:10px;background:var(--card);transition:transform .16s ease-out}
    /* The lift: the card grows a little and a shadow fades in under it (only its opacity changes) */
    .card::after{content:"";position:absolute;inset:0;border-radius:inherit;box-shadow:0 8px 18px rgba(0,0,0,.5);opacity:0;transition:opacity .16s;pointer-events:none}
    .lifted .card{transform:scale(1.02);border-color:var(--ui-accent)}.lifted .card::after{opacity:1}
    .strong .lifted .card{transform:scale(1.06) rotate(-1.5deg)}.strong .card::after{box-shadow:0 18px 34px rgba(0,0,0,.65)}
    .grip{flex:none;display:flex;align-items:center;justify-content:center;width:44px;height:44px;margin-left:3px;border:1px solid transparent;border-radius:8px;background:none;color:var(--ui-muted);cursor:inherit;touch-action:none}
    .grip svg{width:20px;height:20px;fill:currentColor}
    /* Drags by the handle only: the grip looks like the thing to hold, and only it starts a drag */
    .by-grip .row{cursor:default}
    .by-grip .grip{border-color:rgba(255,255,255,.18);background:rgba(255,255,255,.06);color:var(--ui-text);cursor:grab}
    .tag{flex:none;width:10px;height:10px;border-radius:50%}.label{min-width:0;font-size:14px;color:var(--ui-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    /* Show me's fingertip: it rides in the row it holds */
    .tip{position:absolute;left:62%;top:50%;width:28px;height:28px;margin:-14px 0 0 -14px;border-radius:50%;background:rgba(255,255,255,.28);border:2px solid rgba(255,255,255,.75);opacity:0;transition:opacity .2s;pointer-events:none}
    .by-grip .tip{left:25px}.tip.on{opacity:1}
    .sr-only{position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
    @media(prefers-reduced-motion:reduce){.row,.card,.card::after,.tip{transition:none!important}}
    /* See inside and Compare, drawn from the page's own numbers (the script measures the list and the slot height). See inside: four dashed places behind
       the rows, numbered at the left, an arrow in the gutter for each task that slid, and callouts in a column at the right (the list is narrower to make
       room). Compare: two halves, a copy of the list made in the script and the real one. */
    .slots,.views,.num,.views svg,.twin{display:none}
    .slots,.views{position:absolute;inset:0;pointer-events:none}.views{z-index:3}
    .slot{position:absolute;border:2px dashed rgba(244,244,242,.4);border-radius:14px}.slot.lit{border-color:var(--ui-accent);background:rgba(255,157,92,.12)}
    .num{position:absolute;left:0;top:0;width:18px;height:18px;border-radius:50%;background:#0b0b0d;border:1px solid rgba(244,244,242,.45);color:var(--ui-text);font:700 12px/16px var(--hb-font);text-align:center}.num.lit{background:var(--ui-accent);border-color:var(--ui-accent);color:#0b0b0d}
    .views svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible}.arrow{fill:none;stroke:var(--ui-text);stroke-width:2.5;stroke-linecap:round;stroke-linejoin:round}
    .cap{position:absolute;left:0;top:0;width:max-content;max-width:calc(var(--col) - 30px);padding:3px 7px;border-radius:5px;background:#0b0b0d;color:var(--ui-text);font:600 13px/1.25 var(--hb-font);white-space:pre-line}
    .cap[hidden]{display:none}.cap.nm{max-width:none;white-space:nowrap}.cap.lands{color:var(--ui-accent)}
    .cap::before{content:"";position:absolute;top:var(--pt,50%);left:-26px;width:22px;margin-top:-1px;border-top:2px dotted rgba(244,244,242,.5)}.cap.nm::before,.cap.nc::before,.cap.right::before{display:none}
    /* The fingertip of the held task: one rides in each row and in each faint copy (the same look as Show me's), and shows in the two modes while a finger holds it */
    .f{left:calc(100% - 30px)}.fing .lifted .f,.fing .ghost.held .f{opacity:1}
    .twin .row{transition:none;cursor:default}.twin .ghost{display:none;opacity:.5;transition:transform var(--slide) cubic-bezier(.2,.8,.2,1)}.twin .ghost.held{display:block}.twin .ghost .card{border-color:var(--ui-accent)}.twin .ghost .label{visibility:hidden}
    .stage[data-hb-mode="inside"] .slots,.stage[data-hb-mode="inside"] .num,.stage[data-hb-mode="inside"] .views svg,.stage[data-hb-mode="inside"] .views,.stage[data-hb-mode="compare"] .views{display:block}
    .stage[data-hb-mode="inside"] #tip,.stage[data-hb-mode="compare"] #tip{display:none}
    .stage[data-hb-mode="inside"]{padding-inline:8px}.stage[data-hb-mode="inside"] .list{margin:0 var(--col) 0 24px}
    /* Compare: the copy that jumps in the first half, the real list in the second; on a stage too short for the half names above the lists the rows are a little shorter */
    .stage[data-hb-mode="compare"]{--m:clamp(8px,2.5vw,20px);display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-items:center;justify-items:center;padding-inline:0}
    .stage[data-hb-mode="compare"].tight{--row:46px;--gap:4px}.stage[data-hb-mode="compare"]::after{content:"";position:absolute;left:50%;top:0;bottom:0;width:1px;background:rgba(255,255,255,.2);pointer-events:none}
    .stage[data-hb-mode="compare"] .twin{display:block}.stage[data-hb-mode="compare"] .list{width:calc(100% - 2*var(--m));max-width:360px;clip-path:inset(-80px calc(-1*var(--m)))}
    @media(max-width:600px){:root{--col:136px}.cap{font-size:12px}
      .stage[data-hb-mode="inside"] .card,.stage[data-hb-mode="compare"] .card{gap:6px;padding-right:8px}.stage[data-hb-mode="inside"] .grip,.stage[data-hb-mode="compare"] .grip{margin-left:0}}
    @media(max-width:359px){:root{--col:116px}}   /* a narrower caption column keeps a few more letters of each task */
  </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="../add-to-cart-fly/" rel="prev" aria-label="Previous: Add-to-Cart Fly"><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>Add-to-Cart Fly</span></a><a href="../rolling-numbers/" rel="next" aria-label="Next: Rolling Numbers"><span><span class="hb-dir">Next: </span>Rolling Numbers</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.33 · Micro-Interactions</p>
    <h1>Drag to Reorder</h1>
    <p class="hb-lede">Drag an item and the others slide aside to make room. Best for to-do lists.</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">Drag it</h2><p>Drag a task up or down and let go (or Tab to its grip, then use Space and the arrow keys), 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="slots" aria-hidden="true"><i class="slot"></i><i class="slot"></i><i class="slot"></i><i class="slot"></i></div>
      <ul class="list" id="list" aria-label="Today's tasks">
        <li class="row" style="--i:0"><div class="card"><button class="grip" type="button" aria-label="Move Reply to Sam" aria-describedby="moves-help"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="6" r="1.7"/><circle cx="15" cy="6" r="1.7"/><circle cx="9" cy="12" r="1.7"/><circle cx="15" cy="12" r="1.7"/><circle cx="9" cy="18" r="1.7"/><circle cx="15" cy="18" r="1.7"/></svg></button><span class="tag" style="background:#ff9d5c"></span><span class="label">Reply to Sam</span></div><span class="tip" id="tip" aria-hidden="true"></span></li>
        <li class="row" style="--i:1"><div class="card"><button class="grip" type="button" aria-label="Move Book the flights" aria-describedby="moves-help"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="6" r="1.7"/><circle cx="15" cy="6" r="1.7"/><circle cx="9" cy="12" r="1.7"/><circle cx="15" cy="12" r="1.7"/><circle cx="9" cy="18" r="1.7"/><circle cx="15" cy="18" r="1.7"/></svg></button><span class="tag" style="background:#58a6ff"></span><span class="label">Book the flights</span></div></li>
        <li class="row" style="--i:2"><div class="card"><button class="grip" type="button" aria-label="Move Review the draft" aria-describedby="moves-help"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="6" r="1.7"/><circle cx="15" cy="6" r="1.7"/><circle cx="9" cy="12" r="1.7"/><circle cx="15" cy="12" r="1.7"/><circle cx="9" cy="18" r="1.7"/><circle cx="15" cy="18" r="1.7"/></svg></button><span class="tag" style="background:#56d364"></span><span class="label">Review the draft</span></div></li>
        <li class="row" style="--i:3"><div class="card"><button class="grip" type="button" aria-label="Move Water the plants" aria-describedby="moves-help"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="6" r="1.7"/><circle cx="15" cy="6" r="1.7"/><circle cx="9" cy="12" r="1.7"/><circle cx="15" cy="12" r="1.7"/><circle cx="9" cy="18" r="1.7"/><circle cx="15" cy="18" r="1.7"/></svg></button><span class="tag" style="background:#d2a8ff"></span><span class="label">Water the plants</span></div></li>
      </ul>
      <p class="sr-only" id="moves-help">Press Space to pick up the task, the up and down arrow keys to move it, and Space again to drop it. Escape puts it back.</p>
      <p class="sr-only" id="status" role="status" aria-live="polite"></p>
      <div class="views" aria-hidden="true">
        <b class="num">1</b><b class="num">2</b><b class="num">3</b><b class="num">4</b>
        <svg><path class="arrow"/><path class="arrow"/><path class="arrow"/><path class="arrow"/></svg>
        <span class="cap nm" data-hb-caption hidden>Four fixed places</span>
        <span class="cap nc" data-hb-caption hidden>Slide one place to make room</span>
        <span class="cap" data-hb-caption hidden>Follows your finger exactly</span>
        <span class="cap lands" data-hb-caption hidden>Lands here</span>
        <span class="cap" data-hb-caption hidden>It started here</span>
        <span class="cap nm" data-hb-caption hidden>Jumps when dropped</span>
        <span class="cap nm" data-hb-caption hidden>Makes room</span>
      </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>
      <button class="hb-play" type="button" id="btn-reset" data-hb-reset><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>Reset</button>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, the outlines are four fixed places: the held task follows your finger, and the others move one place to make room before it lands. Drag a task, or press Show me.</p>
      <p data-hb-for="compare" hidden>Jumps when dropped: nothing moves aside while you drag, then the list jumps; Makes room: the held task lifts and the others move aside. Drag a task, 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="speed-lbl">Slide speed</p>
        <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
          <button type="button" data-ms="420" aria-pressed="false">Slow</button>
          <button type="button" data-ms="220" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-ms="120" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How fast the other tasks slide out of the way.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="lift-lbl">How much it lifts</p>
        <div class="seg" id="lift-seg" role="group" aria-labelledby="lift-lbl">
          <button type="button" data-lift="subtle" class="on" aria-pressed="true">Subtle</button>
          <button type="button" data-lift="strong" aria-pressed="false">Strong</button>
        </div>
        <p class="hb-hint">Strong makes the task you hold grow, tilt and cast a deeper shadow.</p>
      </div>
      <div class="hb-setting">
        <label class="hb-switch-row"><span>Drags by the handle only</span><input class="hb-switch" type="checkbox" role="switch" id="grip-tog" autocomplete="off"></label>
        <p class="hb-hint">Only the grip starts a drag, so a finger on the rest of a row still scrolls the page.</p>
      </div>
    </div>
  </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 drag to reorder to [the list whose order people can change]. Lift the picked-up item and let it follow the pointer exactly; as it passes a neighbor's middle, slide that neighbor into the gap, and on release settle it into place and save the order. Shift the items rather than changing the layout, so it stays smooth. Support the keyboard: Space picks up, the arrow keys move, Space drops and Escape cancels, each step read out to screen readers. On touch screens, start a drag at once from the grip; if the rest of an item can start one too, only after a short press, so swipes still scroll. If the visitor has reduced motion turned on, move items straight to their places. 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>To-do lists</li><li>Playlists</li><li>Priority rankings</li><li>Menu editors</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Lists sorted by date</li><li>Very long lists</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 $=id=>document.getElementById(id);
  const list=$('list'),tip=$('tip'),statusEl=$('status'),reduceMq=matchMedia('(prefers-reduced-motion:reduce)');
  const START=[...list.children];
  let order=[...START],byGrip=false,drag=null,press=null;   // drag: the row held now; press: a finger waiting on a row
  const nameOf=row=>row.querySelector('.label').textContent,say=text=>{statusEl.textContent=text};
  const slotPx=()=>START[0].offsetHeight+parseFloat(getComputedStyle(list).getPropertyValue('--gap'));
  const place=(row,i)=>row.style.setProperty('--i',i);
  const drawnY=row=>new DOMMatrix(getComputedStyle(row).transform).m42;   // where the row is drawn now, mid-slide too

  // See inside and Compare. The views are drawn from `drag` (the held task: its row, the slot it came from and is over, how it is held), from
  // `order` and from G, what is measured from the page: the list's place and size, the height of a slot and the box's height.
  const stage=document.querySelector('.stage'),SLOTS=[...stage.querySelectorAll('.slot')],NUMS=[...stage.querySelectorAll('.num')],ARROWS=[...stage.querySelectorAll('.arrow')];
  const CAPS=[...stage.querySelectorAll('.cap')],[cFixed,cSlide,cFinger,cLands,cStart,cOne,cTwo]=CAPS;
  const SPEED={420:'in under half a second',220:'in a fifth of a second',120:'in a tenth of a second'};
  let mode='normal',G={},slideMs=220,poseTimer=0;
  // Compare's first list is a copy made once: the same rows (the grips are plain spans; nothing has an id, takes focus or is read out) and, after
  // them, a faint copy of each row for the one being held. Its rows only move when the real list is dropped or reset.
  const twin=document.createElement('ul'),TW=[],GH=[];
  twin.className='list twin';twin.setAttribute('aria-hidden','true');twin.inert=true;
  START.forEach(r=>{const f=document.createElement('span');f.className='tip f';f.setAttribute('aria-hidden','true');r.append(f)});
  START.forEach(r=>[TW,GH].forEach((to,k)=>{
    const c=r.cloneNode(true),g=c.querySelector('.grip'),sp=document.createElement('span');
    sp.className=g.className;sp.innerHTML=g.innerHTML;g.replaceWith(sp);
    c.querySelector('#tip')?.remove();if(k)c.classList.add('ghost');
    to.push(c);
  }));
  twin.append(...TW,...GH);list.before(twin);
  const stepwise=()=>!!drag&&(drag.by==='key'||drag.by==='run'&&reduceMq.matches);   // the held task moves a place at a time, with no finger
  // A callout's size is measured when its words change, and again when the page is measured
  function fit(c,text){
    if(text!==undefined&&c.textContent!==text){c.textContent=text;c._s=0}
    c.hidden=false;
    return c._s||(c._s=[c.offsetWidth,c.offsetHeight]);
  }
  // Compare puts a shorter row in a box too short for the half names above the lists
  function measure(){
    const was=G.s;   // a new slot height (Compare's shorter rows) means the pose is made again at the new height
    stage.classList.remove('tight');
    stage.classList.toggle('tight',mode==='compare'&&(stage.clientHeight-list.offsetHeight)/2<30);
    const s=slotPx(),h=START[0].offsetHeight,x=list.offsetLeft,y=list.offsetTop,w=list.offsetWidth;
    G={s,h,x,y,w,H:stage.clientHeight};
    SLOTS.forEach((e,j)=>Object.assign(e.style,{left:x-4+'px',top:y+j*s-2+'px',width:w+8+'px',height:h+4+'px'}));
    NUMS.forEach((e,j)=>{e.style.transform=`translate(${x-24}px,${y+j*s+(h-18)/2}px)`});
    CAPS.forEach(c=>{c._s=0;c.hidden=true});
    if(mode==='compare')[[cOne,twin],[cTwo,list]].forEach(([c,l])=>{const [cw,ch]=fit(c);c.style.transform=`translate(${Math.round(l.offsetLeft+(l.offsetWidth-cw)/2)}px,${Math.round((l.offsetTop-ch)/2)}px)`});
    if(drag&&drag.by==='pose'&&G.s!==was){unpose();poseNow()}
  }
  // A callout at x, as near the height `at` (the middle of what it names) as the ones put before it leave room; its pointer shows `at`
  function put(c,text,at,x,taken,right){
    const [w,h]=fit(c,text),lo=4,hi=G.H-4-h,want=Math.min(hi,Math.max(lo,at-h/2));
    const clear=t=>t>=lo&&t<=hi&&taken.every(([a,b])=>t+h+5<=a||t>=b+5);
    const t=[want,...taken.flatMap(([a,b])=>[a-5-h,b+5])].filter(clear).sort((p,q)=>Math.abs(p-want)-Math.abs(q-want))[0];
    if(t===undefined){c.hidden=true;return}
    taken.push([t,t+h]);c.classList.toggle('right',!!right);
    c.style.setProperty('--pt',Math.max(8,Math.min(h-8,at-t))+'px');
    c.style.transform=`translate(${Math.round(right?x-w:x)}px,${Math.round(t)}px)`;
  }
  // See inside: the place the held task will land in is lit; each task that slid has an arrow the way it went; the callouts take the first free
  // height near what they name, the finger's first
  function inside(){
    const {s,h,x,y,w}=G,to=drag?drag.to:-1,mid=j=>y+j*s+h/2,col=x+w+30,right=[],left=[],moved=[];
    SLOTS.forEach((e,j)=>{e.classList.toggle('lit',j===to);NUMS[j].classList.toggle('lit',j===to)});
    if(drag)order.forEach((r,j)=>{const k=+r.style.getPropertyValue('--i');if(r!==drag.row&&k!==j)moved.push([k,k<j?-1:1])});
    ARROWS.forEach((p,j)=>{
      const m=moved.find(a=>a[0]===j),u=m?m[1]:0,ax=x+w+14,tip=mid(j)+9*u;
      const d=m?`M${ax} ${mid(j)-9*u}V${tip}M${ax-5} ${tip-5*u}L${ax} ${tip}L${ax+5} ${tip-5*u}`:'';
      if(p.getAttribute('d')!==d)p.setAttribute('d',d);
    });
    [cSlide,cFinger,cLands,cStart].forEach(c=>{c.hidden=true});
    if(drag){
      put(cFinger,stepwise()?'Moves a place at a time':'Follows your finger exactly',mid(0)+drag.y,col,right);
      put(cLands,'Lands here',mid(to),col,right);
      if(moved.length)put(cSlide,reduceMq.matches?'Move one place to make room':`Slide one place to make room\n${SPEED[slideMs]}`,mid(moved.reduce((a,m)=>a+m[0],0)/moved.length),col,right);
    }
    const fh=fit(cFixed)[1],sw=fit(cStart)[0];cStart.hidden=true;
    if(y>=fh+12)cFixed.style.transform=`translate(${x}px,${Math.round((y-fh)/2)}px)`;   // above the list when there is room, else in the column
    else put(cFixed,undefined,mid(3),col,right);
    if(drag&&drag.from!==to&&x>=sw+50)put(cStart,undefined,mid(drag.from),x-36,left,true);   // only where the left side has room
  }
  // Draws the mode on show from the state: Compare's copy keeps the real list's order from its last drop, with the held task's faint copy at the
  // real row's height (the same transform and transition)
  function view(){
    if(mode==='normal')return;
    TW.forEach((r,i)=>place(r,order.indexOf(START[i])));
    GH.forEach((g,i)=>{const on=!!drag&&drag.row===START[i];g.classList.toggle('held',on);if(on){g.style.transition=drag.row.style.transition;g.style.transform=drag.row.style.transform;place(g,drag.to)}});
    stage.classList.toggle('fing',!stepwise());
    if(mode==='inside')inside();
  }
  // The pose both views rest on: the first task held half way between places 2 and 3 by the page's own lift() and follow(), so the two tasks it
  // passed have slid up and place 3 is lit. Anything that acts on the list puts it back first, without a slide; it comes back once nothing is
  // held, pressed or running.
  function poseNow(){
    poseTimer=0;
    if(mode==='normal'||drag||press||running())return;
    order.forEach(r=>{r.style.transition='none'});
    lift(order[0],'pose');follow(1.5*slotPx());
    void list.offsetWidth;order.forEach(r=>{if(r!==drag.row)r.style.transition=''});
  }
  function poseSoon(ms){clearTimeout(poseTimer);poseTimer=mode==='normal'?0:setTimeout(poseNow,ms)}
  function unpose(){
    if(!drag||drag.by!=='pose')return;
    drop(false);
    order.forEach(r=>{r.style.transition='none';r.classList.remove('settling')});void list.offsetWidth;order.forEach(r=>{r.style.transition=''});
  }
  // The mode switch draws the mode at once (its pose, or in Normal the list as it was); the shared script then presses Show me, which plays it.
  document.addEventListener('hb:mode',e=>{
    mode=e.detail.mode;
    if(mode==='normal'){clearTimeout(poseTimer);stage.classList.remove('tight','fing');unpose();return}
    measure();poseNow();view();
  });
  addEventListener('resize',()=>{if(mode!=='normal'){measure();view()}});
  document.fonts.ready.then(()=>{if(mode!=='normal'){measure();view()}});

  // The visitor's drag, the keyboard and Show me all pick a row up with lift(), move it and put it down with drop().
  function lift(row,by){
    const from=order.indexOf(row);
    drag={row,by,from,to:from,y:drawnY(row)};
    row.classList.remove('settling');row.classList.add('lifted');view();
  }
  // The rows between where the held one started and slot `to` slide one slot toward the gap it left.
  function makeRoom(to){
    const {row,from}=drag;drag.to=to;
    order.forEach((r,j)=>{if(r!==row)place(r,from<to&&j>from&&j<=to?j-1:to<from&&j>=to&&j<from?j+1:j)});
  }
  // Pointer and Show me: the held row is drawn at y, exactly under the pointer, and the others make room around the slot it is over.
  function follow(y){
    const s=slotPx(),n=order.length,r=drag.row;
    drag.y=Math.max(-.4*s,Math.min((n-.6)*s,y));
    r.style.transition='none';r.style.transform=`translateY(${drag.y}px)`;
    const to=Math.max(0,Math.min(n-1,Math.round(drag.y/s)));
    if(to!==drag.to)makeRoom(to);
    view();
  }
  // Keyboard and reduced motion: the held row itself slides (or jumps) one slot.
  function step(to){drag.row.style.transition=drag.row.style.transform='';place(drag.row,to);makeRoom(to);drag.y=to*slotPx();view()}
  // Moving a row in the document ends the slide it is in the middle of: it would be drawn in its slot at once. So each moved row is
  // first read where it is drawn, given that place back as a still transform after the move, and let go, so its slide carries on.
  function keepSlides(rows,move){
    const at=rows.map(drawnY);move();
    rows.forEach((r,i)=>{r.style.transition='none';r.style.transform=`translateY(${at[i]}px)`});
    void list.offsetWidth;rows.forEach(r=>{r.style.transition=r.style.transform=''});
  }
  // Letting go: the row settles into its slot (or back where it was picked up), and the list's real order follows. The rows it
  // passed move to its other side in the document, so the held row never leaves it and keeps its keyboard focus.
  function drop(keep){
    const {row,from}=drag,to=keep?drag.to:from,passed=to>from?order.slice(from+1,to+1):order.slice(to,from).reverse();
    if(!keep)makeRoom(from);
    row.style.transition=row.style.transform='';row.classList.remove('lifted');row.classList.add('settling');place(row,to);
    keepSlides(passed,()=>passed.forEach(r=>list.insertBefore(r,to>from?row:row.nextSibling)));
    order.splice(from,1);order.splice(to,0,row);drag=null;view();poseSoon(900);
    return to;
  }
  list.addEventListener('transitionend',e=>{if(e.target.classList.contains('settling')&&e.propertyName==='transform')e.target.classList.remove('settling')});
  // The pointer: a mouse or pen lifts the row at once; a finger lifts it from the grip at once, elsewhere after a 300ms press, so a
  // quick swipe over the list still scrolls the page. Once a row is held, the browser is kept from scrolling under it.
  function grab(row,pid,clientY){lift(row,'pointer');drag.pid=pid;drag.start=clientY-drag.y;try{row.setPointerCapture(pid)}catch(_){}}
  list.addEventListener('pointerdown',e=>{
    const row=e.target.closest('.row'),onGrip=!!e.target.closest('.grip');
    if(!row||press||(drag&&drag.by==='pointer')||(e.pointerType==='mouse'&&e.button!==0)||(byGrip&&!onGrip))return;
    const wait=e.pointerType==='touch'&&!onGrip;   // a finger on a row's body may be a swipe: the pose is lifted only once the press is long enough
    if(!wait)unpose();
    if(drag&&drag.by!=='pose')drop(true);   // a row picked up with the keyboard is put down where it is
    if(wait)press={pid:e.pointerId,row,x:e.clientX,y:e.clientY,timer:setTimeout(()=>{const p=press;press=null;unpose();grab(p.row,p.pid,p.y)},300)};
    else grab(row,e.pointerId,e.clientY);
  });
  list.addEventListener('pointermove',e=>{
    if(press&&e.pointerId===press.pid){
      if(Math.hypot(e.clientX-press.x,e.clientY-press.y)>8){clearTimeout(press.timer);press=null}else press.y=e.clientY;
    }else if(drag&&drag.by==='pointer'&&e.pointerId===drag.pid)follow(e.clientY-drag.start);
  });
  function letGo(e){
    poseSoon(900);
    if(press&&e.pointerId===press.pid){clearTimeout(press.timer);press=null}
    if(!drag||drag.by!=='pointer'||e.pointerId!==drag.pid)return;
    const {row,from}=drag,to=drop(e.type==='pointerup');
    if(to!==from)say(`${nameOf(row)} moved to position ${to+1} of ${order.length}.`);
  }
  list.addEventListener('pointerup',letGo);list.addEventListener('pointercancel',letGo);
  list.addEventListener('touchmove',e=>{if(drag&&drag.by==='pointer'&&e.cancelable)e.preventDefault()},{passive:false});
  list.addEventListener('contextmenu',e=>{if(press||drag&&drag.by!=='pose')e.preventDefault()});
  // The keyboard, on a grip: Space or Enter picks the task up and puts it down, the arrows move it, Escape puts it back.
  list.addEventListener('keydown',e=>{
    const grip=e.target.closest('.grip'),row=grip&&grip.closest('.row');
    if(!row)return;
    if([' ','Enter','ArrowUp','ArrowDown','Escape'].includes(e.key))unpose();
    const held=drag&&drag.row===row&&drag.by==='key',n=order.length;
    if(e.key===' '||e.key==='Enter'){
      e.preventDefault();
      if(held){say(`${nameOf(row)} dropped in position ${drop(true)+1} of ${n}.`);return}
      if(drag)drop(true);
      lift(row,'key');say(`${nameOf(row)} picked up, position ${drag.from+1} of ${n}.`);
    }else if(held&&(e.key==='ArrowUp'||e.key==='ArrowDown')){
      e.preventDefault();
      step(Math.max(0,Math.min(n-1,drag.to+(e.key==='ArrowUp'?-1:1))));
      say(`${nameOf(row)}, position ${drag.to+1} of ${n}.`);
    }else if(held&&e.key==='Escape'){
      e.preventDefault();
      say(`${nameOf(row)} is back in position ${drop(false)+1} of ${n}.`);
    }
  });
  list.addEventListener('focusout',e=>{if(drag&&drag.by==='key'&&drag.row.contains(e.target))drop(true)});
  // Puts the rows in this order: sliding from where they are drawn, around the settling row so its lift and fingertip fade out (Reset),
  // or at once, with the slides off for a moment (before a run).
  function setOrder(next,slide){
    const keep=slide&&list.querySelector('.settling'),k=next.indexOf(keep),move=()=>{order=[...next];if(keep){order.slice(0,k).forEach(r=>list.insertBefore(r,keep));list.append(...order.slice(k+1))}else list.append(...order);order.forEach((r,i)=>place(r,i));view()};
    if(slide)return keepSlides([...order],move);
    order.forEach(r=>{r.style.transition='none';r.classList.remove('settling')});move();void list.offsetWidth;order.forEach(r=>{r.style.transition=''});
  }
  // Show me: one run at a time. Every timer of the run goes through later(); stopRun() cancels the whole run.
  let runTimers=[],runFrame=0;
  function later(fn,ms){const id=setTimeout(()=>{runTimers=runTimers.filter(t=>t!==id);fn()},ms);runTimers.push(id)}
  function running(){return runTimers.length>0||runFrame!==0}
  // A task still held by the run is put down where it is when the visitor takes over (keep), else back where the run picked it up.
  function stopRun(keep){
    runTimers.forEach(clearTimeout);runTimers=[];cancelAnimationFrame(runFrame);runFrame=0;tip.classList.remove('on');
    if(drag&&drag.by==='run')drop(!!keep);
    poseSoon(900);
  }
  // The fingertip rides in the row the run holds; glide() moves the row as a hand would, frame by frame by the time passed.
  function hold(row){lift(row,'run');row.append(tip);void tip.offsetWidth;tip.classList.add('on')}
  function release(){cancelAnimationFrame(runFrame);runFrame=0;tip.classList.remove('on');if(drag&&drag.by==='run')drop(true)}
  function glide(to,ms){
    const y0=drag.y,y1=to*slotPx(),t0=performance.now();
    (function frame(now){
      if(!drag){runFrame=0;return}
      const k=Math.min(1,Math.max(0,(now-t0)/ms));
      follow(y0+(y1-y0)*k*k*(3-2*k));
      runFrame=k<1?requestAnimationFrame(frame):0;
    })(t0);
  }
  // The first task is picked up, dragged two places down and let go; after a pause it is dragged back up to the top. Under reduced
  // motion it jumps one place at a time, as with the arrow keys. A run starts from the first order, put back at once.
  $('btn-demo').addEventListener('click',()=>{
    stopRun();if(drag)drop(false);
    setOrder(START,false);
    const row=order[0];hold(row);
    if(reduceMq.matches){
      [[1,350],[2,700]].forEach(([to,ms])=>later(()=>step(to),ms));later(release,1050);
      later(()=>hold(row),1850);[[1,2200],[0,2550]].forEach(([to,ms])=>later(()=>step(to),ms));later(release,2900);
      return;
    }
    later(()=>glide(2,900),150);later(release,1200);
    later(()=>hold(row),2000);later(()=>glide(0,800),2150);later(release,3050);
  });
  $('btn-reset').addEventListener('click',()=>{stopRun();unpose();if(drag)drop(false);setOrder(START,true);say('');poseSoon(900)});
  // The visitor pressed, typed, scrolled or touched inside the stage: the run stops and the list stays as it is.
  document.addEventListener('hb:input',()=>{if(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);view();
    }));
  }
  choices('speed-seg',d=>{slideMs=+d.ms;document.documentElement.style.setProperty('--slide',d.ms+'ms')});
  choices('lift-seg',d=>{list.classList.toggle('strong',d.lift==='strong')});
  $('grip-tog').addEventListener('change',e=>{byGrip=e.target.checked;list.classList.toggle('by-grip',byGrip);twin.classList.toggle('by-grip',byGrip);view()});
</script>
</body>
</html>