{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"delete-undo","type":"registry:component","title":"Delete with undo","description":"One call on any element: it folds in half and in half again, turns edge-on and is gone. unfold() brings it back.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/delete-undo.tsx","type":"registry:component","content":"// Hairline UI · delete-undo · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\n/* ─────────────────────────────────────────────────────────\n * DELETE WITH UNDO: fold it away\n *\n * One call on any element: `await foldAway(element)`. The\n * element is folded like a print in your hands, picture side\n * out, in half and in half again, each fold a little quicker,\n * until it's a small square; then the square turns edge-on and\n * is gone, because paper has no thickness. The promise resolves\n * and your code removes the item the way it already does.\n * `unfold(element)` plays it back, for your own Undo.\n *\n * Nothing about your app is taken over: no list, no toast, no\n * timer, no API. The fold is a copy of the element drawn over\n * the page (clipped clones hinged in 3D); the element itself is\n * only hidden, so it keeps its place in the layout and the copy\n * follows it every frame, through scrolling and resizing.\n * ───────────────────────────────────────────────────────── */\n\nimport { playSound } from \"./ui-sounds\";\n\nexport interface FoldAwayOptions {\n  /** Play a soft crease for each fold and a tick as it goes (synthesised, no files). */\n  sound?: boolean;\n  /** The colour of the paper's back, any CSS background. */\n  back?: string;\n}\n\nconst PAPER = \"linear-gradient(140deg, var(--card, #fff), color-mix(in oklab, var(--muted, #f4f4f5) 80%, var(--foreground, #000) 6%))\";\nconst MAX_FOLDS = 4;\nconst SMALLEST = 56;\nconst FIRST = 480;\nconst QUICKER = 0.84;\nconst EDGE = 460;\n\ntype Rect = { x: number; y: number; w: number; h: number };\ntype Corners = [number, number, number, number]; // top-left, top-right, bottom-right, bottom-left\n\ninterface Step {\n  root: HTMLDivElement;\n  duration: number;\n  /** f is the fold, 0 flat to 1 folded; e is the final turn edge-on, used on the last step only. */\n  set(f: number, e: number): void;\n  /** Where the middle of the paper sits, inside the step, at fold f. */\n  centre(f: number): [number, number];\n  shown: boolean;\n}\n\ninterface Run {\n  steps: Step[];\n  t: number;\n  total: number;\n  dir: 1 | -1;\n  last: number;\n  frame: number;\n  step: number;\n  sound: boolean;\n  visibility: string;\n  waiting: { dir: 1 | -1; resolve: (done: boolean) => void }[];\n}\n\nconst runs = new WeakMap<HTMLElement, Run>();\nconst gone = new WeakMap<HTMLElement, { visibility: string; options: FoldAwayOptions }>();\n\nconst clamp01 = (n: number) => (n < 0 ? 0 : n > 1 ? 1 : n);\nconst smooth = (n: number) => (1 - Math.cos(Math.PI * clamp01(n))) / 2;\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\n\nlet layer: HTMLDivElement | null = null;\nfunction topLayer() {\n  if (layer && layer.isConnected) return layer;\n  layer = document.createElement(\"div\");\n  layer.setAttribute(\"aria-hidden\", \"true\");\n  layer.style.cssText = \"position:fixed;inset:0;pointer-events:none;z-index:2147483000;contain:layout style;\";\n  document.body.appendChild(layer);\n  return layer;\n}\n\nfunction reducedMotion() {\n  return typeof window !== \"undefined\" && !!window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/** One piece of the paper: a clipped clone of the element in front, the paper's back behind, a shade for turning away. */\nfunction piece(source: HTMLElement, W: number, H: number, part: Rect, local: Rect, back: string) {\n  const face = document.createElement(\"div\");\n  face.style.cssText = `position:absolute;left:${local.x}px;top:${local.y}px;width:${local.w}px;height:${local.h}px;transform-style:preserve-3d;`;\n  const front = document.createElement(\"div\");\n  front.style.cssText = \"position:absolute;inset:0;overflow:hidden;backface-visibility:hidden;-webkit-backface-visibility:hidden;\";\n  const clone = source.cloneNode(true) as HTMLElement;\n  clone.removeAttribute(\"id\");\n  clone.querySelectorAll(\"[id]\").forEach((n) => n.removeAttribute(\"id\"));\n  clone.setAttribute(\"inert\", \"\");\n  clone.style.cssText += `;position:absolute;left:${-part.x}px;top:${-part.y}px;width:${W}px;height:${H}px;margin:0;transform:none;translate:none;scale:none;rotate:none;opacity:1;visibility:visible;animation:none;transition:none;`;\n  const shade = document.createElement(\"div\");\n  shade.style.cssText = \"position:absolute;inset:0;background:#000;opacity:0;pointer-events:none;\";\n  front.append(clone, shade);\n  const rear = document.createElement(\"div\");\n  rear.style.cssText = `position:absolute;inset:0;background:${back};transform:rotateX(180deg);backface-visibility:hidden;-webkit-backface-visibility:hidden;`;\n  face.append(front, rear);\n  const round = (c: Corners) => {\n    const r = c.map((v) => `${v.toFixed(2)}px`).join(\" \");\n    front.style.borderRadius = r;\n    rear.style.borderRadius = r;\n  };\n  return { face, shade, round };\n}\n\nfunction build(source: HTMLElement, options: FoldAwayOptions): Run {\n  const W = source.offsetWidth || 1;\n  const H = source.offsetHeight || 1;\n  const computed = getComputedStyle(source);\n  const corner = parseFloat(computed.borderTopLeftRadius) || 0;\n  // Rounding follows the size: a small folded square can't keep a big photo's corners.\n  const radius = (r: Rect) => Math.min(Math.max(corner, 6), 0.16 * Math.min(r.w, r.h));\n  const back = options.back ?? PAPER;\n\n  const steps: Step[] = [];\n  let region: Rect = { x: 0, y: 0, w: W, h: H };\n  let duration = FIRST;\n  for (let i = 0; i < MAX_FOLDS; i++) {\n    const R = region;\n    // Fold the longer side, keeping whichever half is nearer the middle of the picture, so the folds close in on it and\n    // the last small square shows the middle (a face, a product), not a corner.\n    const down = R.h >= R.w;\n    const near = down\n      ? Math.abs(R.y + R.h / 4 - H / 2) <= Math.abs(R.y + (3 * R.h) / 4 - H / 2) + 0.01\n      : Math.abs(R.x + R.w / 4 - W / 2) <= Math.abs(R.x + (3 * R.w) / 4 - W / 2) + 0.01;\n    const hw = R.w / 2, hh = R.h / 2;\n    const kept: Rect = down ? { x: R.x, y: near ? R.y : R.y + hh, w: R.w, h: hh } : { x: near ? R.x : R.x + hw, y: R.y, w: hw, h: R.h };\n    // The folding half reaches a pixel under the kept one, so no hairline shows where they meet.\n    const folded: Rect = down\n      ? { x: R.x, y: near ? R.y + hh - 1 : R.y, w: R.w, h: hh + 1 }\n      : { x: near ? R.x + hw - 1 : R.x, y: R.y, w: hw + 1, h: R.h };\n    // Which corners of each piece lie on the crease (top-left, top-right, bottom-right, bottom-left).\n    const keptCrease = down ? (near ? [2, 3] : [0, 1]) : near ? [1, 2] : [0, 3];\n    const foldCrease = down ? (near ? [0, 1] : [2, 3]) : near ? [0, 3] : [1, 2];\n    const origin = down ? (near ? \"50% 0\" : \"50% 100%\") : near ? \"0 50%\" : \"100% 50%\";\n    const swing = (f: number) => (down ? `rotateX(${(near ? -1 : 1) * f * 180}deg)` : `rotateY(${(near ? 1 : -1) * f * 180}deg)`);\n    const local = (r: Rect): Rect => ({ x: r.x - R.x, y: r.y - R.y, w: r.w, h: r.h });\n    const last = i === MAX_FOLDS - 1 || Math.max(kept.w, kept.h) <= SMALLEST;\n\n    const root = document.createElement(\"div\");\n    root.style.cssText = `position:absolute;left:0;top:0;width:${R.w}px;height:${R.h}px;display:none;will-change:transform;color:${computed.color};font:${computed.font};`;\n    const k = local(kept);\n    const stage = document.createElement(\"div\");\n    stage.style.cssText = `position:absolute;inset:0;perspective:${Math.max(500, Math.max(W, H) * 2.4)}px;perspective-origin:${k.x + k.w / 2}px ${k.y + k.h / 2}px;`;\n    const turn = document.createElement(\"div\");\n    turn.style.cssText = `position:absolute;inset:0;transform-style:preserve-3d;transform-origin:${k.x + k.w / 2}px ${k.y + k.h / 2}px;`;\n    const f0 = local(folded);\n    const hinge = document.createElement(\"div\");\n    hinge.style.cssText = `position:absolute;left:${f0.x}px;top:${f0.y}px;width:${f0.w}px;height:${f0.h}px;transform-origin:${origin};transform-style:preserve-3d;`;\n    const away = piece(source, W, H, folded, { x: 0, y: 0, w: f0.w, h: f0.h }, back);\n    hinge.appendChild(away.face);\n    const stay = piece(source, W, H, kept, k, back);\n    turn.append(hinge, stay.face);\n    stage.appendChild(turn);\n    root.appendChild(stage);\n    topLayer().appendChild(root);\n\n    const from = radius(R), to = radius(kept);\n    // Corners on the crease start square, so the two halves read as one sheet, and round as the fold closes.\n    const corners = (crease: number[], onCrease: number, elsewhere: number) =>\n      [0, 1, 2, 3].map((c) => (crease.includes(c) ? onCrease : elsewhere)) as Corners;\n    away.round(corners(foldCrease, 0, from));\n    let tuckedAway = false;\n    steps.push({\n      root,\n      duration,\n      shown: false,\n      set(f, e) {\n        hinge.style.transform = `translateZ(${-f * 0.8}px) ${swing(f)}`;\n        away.shade.style.opacity = String(Math.min(1, f * 1.8) * 0.42);\n        const tucked = f >= 0.999;\n        if (tucked !== tuckedAway) {\n          tuckedAway = tucked;\n          // display, not visibility: the clone sets its own visibility, which would show through a hidden parent.\n          hinge.style.display = tucked ? \"none\" : \"\";\n        }\n        stay.round(corners(keptCrease, to * f, lerp(from, to, f)));\n        if (last) {\n          // The flick: the little square tips back a touch, as a finger would set it, then spins edge-on, faster and\n          // faster, and is gone, because paper has no thickness.\n          const wind = smooth(e / 0.3);\n          const spin = clamp01((e - 0.3) / 0.7) ** 2;\n          const angle = -12 * wind + 102 * spin;\n          turn.style.transform = e > 0 ? `rotateY(${angle}deg) scale(${1 + 0.05 * wind - 0.17 * spin})` : \"\";\n          stay.shade.style.opacity = String(Math.max(0, angle / 90) * 0.4);\n        }\n      },\n      centre(f) {\n        return [lerp(R.w / 2, k.x + k.w / 2, f), lerp(R.h / 2, k.y + k.h / 2, f)];\n      },\n    });\n    if (last) break;\n    region = kept;\n    duration = Math.round(duration * QUICKER);\n  }\n\n  const total = steps.reduce((sum, s) => sum + s.duration, 0) + EDGE;\n  return { steps, t: 0, total, dir: 1, last: 0, frame: 0, step: -1, sound: !!options.sound, visibility: source.style.visibility, waiting: [] };\n}\n\nfunction draw(source: HTMLElement, run: Run) {\n  const box = source.getBoundingClientRect();\n  // The element may be scaled by a pressed state; the copy keeps its real size and follows its middle.\n  const cx = box.left + box.width / 2, cy = box.top + box.height / 2;\n  let t = run.t;\n  let active = run.steps.length - 1;\n  let f = 1, e = 0;\n  for (let i = 0; i < run.steps.length; i++) {\n    const d = run.steps[i].duration;\n    if (t < d || i === run.steps.length - 1) {\n      active = i;\n      f = smooth(t / d);\n      e = i === run.steps.length - 1 ? clamp01((t - d) / EDGE) : 0;\n      break;\n    }\n    t -= d;\n  }\n  if (active !== run.step) {\n    if (run.sound && run.dir > 0 && active > run.step) playSound(\"fold\", Math.max(0.15, 0.5 - active * 0.07));\n    run.step = active;\n  }\n  run.steps.forEach((step, i) => {\n    const show = i === active;\n    if (show !== step.shown) {\n      step.shown = show;\n      step.root.style.display = show ? \"\" : \"none\";\n    }\n  });\n  const step = run.steps[active];\n  step.set(f, e);\n  const [mx, my] = step.centre(f);\n  step.root.style.transform = `translate3d(${cx - mx}px, ${cy - my}px, 0)`;\n}\n\nfunction settle(run: Run, dir: 1 | -1, done: boolean) {\n  run.waiting = run.waiting.filter((w) => {\n    if (w.dir !== dir) return true;\n    w.resolve(done);\n    return false;\n  });\n}\n\nfunction destroy(run: Run) {\n  cancelAnimationFrame(run.frame);\n  run.steps.forEach((s) => s.root.remove());\n  if (layer && !layer.childElementCount) {\n    layer.remove();\n    layer = null;\n  }\n}\n\nfunction play(source: HTMLElement, run: Run, dir: 1 | -1) {\n  if (run.dir !== dir) settle(run, run.dir, false);\n  run.dir = dir;\n  cancelAnimationFrame(run.frame);\n  run.last = performance.now();\n  const finish = (done: boolean) => {\n    destroy(run);\n    runs.delete(source);\n    settle(run, run.dir, done);\n  };\n  const tick = (now: number) => {\n    // Unfolding runs a little quicker than folding: getting it back should feel prompt.\n    const dt = Math.min(64, now - run.last) * (run.dir > 0 ? 1 : 1.25);\n    run.last = now;\n    run.t = Math.min(run.total, Math.max(0, run.t + dt * run.dir));\n    if (!source.isConnected) return finish(run.dir > 0);\n    draw(source, run);\n    if (run.dir > 0 && run.t >= run.total) {\n      if (run.sound) playSound(\"tick\", 0.35);\n      finish(true);\n    } else if (run.dir < 0 && run.t <= 0) {\n      source.style.visibility = run.visibility;\n      finish(true);\n    } else {\n      run.frame = requestAnimationFrame(tick);\n    }\n  };\n  draw(source, run);\n  run.frame = requestAnimationFrame(tick);\n}\n\n/**\n * Folds `element` away: in half and in half again, then edge-on and gone. Resolves `true` once it's gone (the element\n * stays in the page, hidden, until you remove it), or `false` if `unfold` turned it back first.\n */\nexport function foldAway(element: HTMLElement | null | undefined, options: FoldAwayOptions = {}): Promise<boolean> {\n  if (!element || typeof window === \"undefined\") return Promise.resolve(false);\n  if (gone.has(element)) return Promise.resolve(true);\n  if (reducedMotion() && !runs.has(element)) {\n    // Without motion the item just fades, quickly.\n    const visibility = element.style.visibility;\n    return element.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 160, easing: \"ease-out\" }).finished.then(() => {\n      element.style.visibility = \"hidden\";\n      gone.set(element, { visibility, options });\n      return true;\n    });\n  }\n  let run = runs.get(element);\n  if (!run) {\n    run = build(element, options);\n    runs.set(element, run);\n    element.style.visibility = \"hidden\";\n  }\n  const current = run;\n  return new Promise<boolean>((resolve) => {\n    current.waiting.push({\n      dir: 1,\n      resolve: (done) => {\n        if (done) gone.set(element, { visibility: current.visibility, options });\n        resolve(done);\n      },\n    });\n    play(element, current, 1);\n  });\n}\n\n/** Brings a folded-away element back: the fold plays in reverse, from wherever it is. Resolves once it's back. */\nexport function unfold(element: HTMLElement | null | undefined): Promise<boolean> {\n  if (!element || typeof window === \"undefined\") return Promise.resolve(false);\n  const folded = gone.get(element);\n  let run = runs.get(element);\n  if (!run && !folded) return Promise.resolve(false);\n  gone.delete(element);\n  if (!run && folded) {\n    if (reducedMotion()) {\n      element.style.visibility = folded.visibility;\n      return element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 160, easing: \"ease-out\" }).finished.then(() => true);\n    }\n    run = build(element, folded.options);\n    run.visibility = folded.visibility;\n    run.t = run.total;\n    runs.set(element, run);\n  }\n  const current = run!;\n  if (current.sound) playSound(\"unfold\", 0.4);\n  return new Promise<boolean>((resolve) => {\n    current.waiting.push({ dir: -1, resolve });\n    play(element, current, -1);\n  });\n}\n\n/** True while `element` is folded away (and not yet unfolded). */\nexport function isFoldedAway(element: HTMLElement | null | undefined) {\n  return !!element && gone.has(element);\n}\n"},{"path":"registry/ui-sounds.ts","type":"registry:component","content":"// Hairline UI · delete-undo · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * UI SOUNDS: small interface sounds, made in code\n *\n * No files and nothing to license: every sound is built from a\n * tone or a burst of noise with the Web Audio API the moment it\n * plays. They're short and quiet, made to sit under an interface,\n * and components only play them when you pass `sound`.\n *\n *   fold     paper creasing: two short crisp bursts\n *   unfold   paper opening: a soft rising sweep\n *   drop     something small landing: a low, soft knock\n *   tick     a light click\n *   pop      a quick bright blip\n *   success  two soft rising notes\n *   error    two low falling notes\n *\n * Browsers only start audio after the visitor has pressed\n * something on the page, so a sound before that stays silent.\n * ───────────────────────────────────────────────────────── */\n\nexport type UiSound = \"fold\" | \"unfold\" | \"drop\" | \"tick\" | \"pop\" | \"success\" | \"error\";\n\nlet context: AudioContext | null = null;\nlet noise: AudioBuffer | null = null;\n\nfunction audio() {\n  if (typeof window === \"undefined\") return null;\n  if (!context) {\n    const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n    if (!Ctx) return null;\n    context = new Ctx();\n  }\n  if (context.state === \"suspended\") void context.resume().catch(() => {});\n  return context;\n}\n\nfunction noiseBuffer(ctx: AudioContext) {\n  if (noise && noise.sampleRate === ctx.sampleRate) return noise;\n  noise = ctx.createBuffer(1, Math.floor(ctx.sampleRate * 0.5), ctx.sampleRate);\n  const data = noise.getChannelData(0);\n  for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n  return noise;\n}\n\n/** A burst of filtered noise. */\nfunction burst(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"bandpass\", from = 2000, to = from, q = 0.9, level = 0.5 }: { type?: BiquadFilterType; from?: number; to?: number; q?: number; level?: number }) {\n  const src = ctx.createBufferSource();\n  src.buffer = noiseBuffer(ctx);\n  const filter = ctx.createBiquadFilter();\n  filter.type = type;\n  filter.Q.value = q;\n  filter.frequency.setValueAtTime(from, at);\n  filter.frequency.exponentialRampToValueAtTime(Math.max(40, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + Math.min(0.012, length / 3));\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  src.connect(filter).connect(gain).connect(out);\n  src.start(at, Math.random() * 0.3, length + 0.02);\n}\n\n/** A tone that glides from one pitch to another. */\nfunction tone(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"sine\", from, to = from, level = 0.4 }: { type?: OscillatorType; from: number; to?: number; level?: number }) {\n  const osc = ctx.createOscillator();\n  osc.type = type;\n  osc.frequency.setValueAtTime(from, at);\n  osc.frequency.exponentialRampToValueAtTime(Math.max(20, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + 0.006);\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  osc.connect(gain).connect(out);\n  osc.start(at);\n  osc.stop(at + length + 0.02);\n}\n\n/** Plays one sound. `volume` is 0 to 1; the default sits quietly under an interface. */\nexport function playSound(name: UiSound, volume = 0.5) {\n  const ctx = audio();\n  if (!ctx) return;\n  const out = ctx.createGain();\n  out.gain.value = Math.max(0, Math.min(1, volume)) * 0.5;\n  out.connect(ctx.destination);\n  const t = ctx.currentTime + 0.005;\n  switch (name) {\n    case \"fold\":\n      burst(ctx, out, t, 0.05, { type: \"highpass\", from: 2600, q: 0.7, level: 0.45 });\n      burst(ctx, out, t + 0.07, 0.07, { type: \"bandpass\", from: 3200, to: 1800, q: 1.2, level: 0.35 });\n      break;\n    case \"unfold\":\n      burst(ctx, out, t, 0.16, { type: \"bandpass\", from: 900, to: 2800, q: 0.8, level: 0.3 });\n      break;\n    case \"drop\":\n      tone(ctx, out, t, 0.12, { from: 180, to: 70, level: 0.55 });\n      burst(ctx, out, t, 0.03, { type: \"lowpass\", from: 1200, q: 0.5, level: 0.2 });\n      break;\n    case \"tick\":\n      tone(ctx, out, t, 0.025, { type: \"triangle\", from: 1900, to: 1500, level: 0.25 });\n      break;\n    case \"pop\":\n      tone(ctx, out, t, 0.06, { from: 620, to: 980, level: 0.3 });\n      break;\n    case \"success\":\n      tone(ctx, out, t, 0.11, { from: 660, level: 0.22 });\n      tone(ctx, out, t + 0.09, 0.16, { from: 990, level: 0.22 });\n      break;\n    case \"error\":\n      tone(ctx, out, t, 0.12, { type: \"triangle\", from: 330, level: 0.25 });\n      tone(ctx, out, t + 0.1, 0.18, { type: \"triangle\", from: 247, level: 0.25 });\n      break;\n  }\n  window.setTimeout(() => out.disconnect(), 600);\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/delete-undo. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}