Try 'magnetic button'
View code

Number 89: Delete that asks where you clicked

Specification

Catalogue
No. 89 of 110
Interaction
Press, Feedback
Element
Button
Preview
Live component
Imports
react 19.3.1, @number-flow/react 0.6.2, framer-motion 12.40.0
Added

Notes

A Delete button that widens into "Delete project? Cancel, Delete", then into a spinner, then into the result with Undo. On the entry page it can ask for a press, a one-second hold, or a three-second countdown that Cancel can still stop.

A small destructive action needs no modal, and the answer stays where the hand already is. Unlike hold to confirm it offers three ways to answer and a way back.

Only the pill's width moves: it grows on a 0.28s spring and shrinks on a 0.24s one, both with no bounce. Each face sits at its natural width against the leading edge, so the question starts where the label was and the moving edge reveals the rest; the parts of a new face arrive out of a 2px blur while the old face fades where it stood. A press within 280ms of the question appearing is ignored, so the opening press cannot double as the answer. The done tick pops and draws itself. Escape, Cancel, a press outside, or six seconds without an answer put it back at rest; the result stands for five seconds. Focus stays on the control from face to face. Every button is 44px tall, and white on the delete red is 5.4:1. Faces crossfade without the width spring under reduced motion.

The project name is sample content, and deleting is simulated.

Code

React and plain CSS
"use client";

import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { AnimatePresence, animate, motion, useIsPresent, useMotionValue, type Variants } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { EASE_ENTER, physicalSpring } from "@/components/pieces/kit/physical-spring";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { radioArrows } from "@/components/pieces/shared";
import { useStageMode } from "@/components/pieces/stage/mode";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./confirm-in-place.css";

type State = "idle" | "asking" | "counting" | "pending" | "done" | "undoing";
type Mode = "press" | "hold" | "countdown";

/** A press this soon after the question appears is the tail of the press that opened it, not an answer. */
const ARM_MS = 280;
const HOLD_MS = 1000;
const COUNT_FROM = 3;
const ASK_TIMEOUT = 6000;
const RESULT_TIMEOUT = 5000;
const GROW = physicalSpring(0.28);
const SHRINK = physicalSpring(0.24);

// Faces never move or scale: each sits at its natural width against the pill's leading edge and the moving edge reveals it.
const face: Variants = {
  hidden: { opacity: 1 },
  shown: { opacity: 1 },
  gone: { opacity: 0, filter: "blur(2px)", transition: { duration: 0.1 } },
};
const part: Variants = {
  hidden: { opacity: 0, filter: "blur(2px)" },
  shown: { opacity: 1, filter: "blur(0px)", transition: { duration: 0.18, ease: EASE_ENTER, delay: 0.03 } },
};
const plainFace: Variants = { hidden: { opacity: 0 }, shown: { opacity: 1, transition: { duration: 0 } }, gone: { opacity: 0, transition: { duration: 0.08 } } };
const plainPart: Variants = { hidden: { opacity: 1 }, shown: { opacity: 1 } };

function Face({ k, reduce, onSize, children }: { k: string; reduce: boolean; onSize: (w: number) => void; children: ReactNode }) {
  const ref = useRef<HTMLDivElement>(null);
  // A face that is fading out takes no more input, so a late release or press never reaches it.
  const present = useIsPresent();
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    const report = () => onSize(el.offsetWidth);
    report();
    const ro = new ResizeObserver(report);
    ro.observe(el);
    return () => ro.disconnect();
  }, [onSize]);
  return (
    <motion.div ref={ref} className="cf-face" data-face={k} inert={!present || undefined} variants={reduce ? plainFace : face} initial="hidden" animate="shown" exit="gone">
      {children}
    </motion.div>
  );
}

function Part({ reduce, children }: { reduce: boolean; children: ReactNode }) {
  return (
    <motion.span className="cf-part" variants={reduce ? plainPart : part}>
      {children}
    </motion.span>
  );
}

function Check({ reduce }: { reduce: boolean }) {
  return (
    <svg className="cf-check" viewBox="0 0 18 18" fill="none" aria-hidden="true">
      <motion.circle cx="9" cy="9" r="8" style={{ transformOrigin: "9px 9px" }} initial={reduce ? false : { scale: 0.7, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} transition={physicalSpring(0.2)} />
      <motion.path d="M5.6 9.3 7.8 11.4 12.4 6.7" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" initial={reduce ? false : { pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ duration: 0.2, ease: EASE_ENTER, delay: 0.06 }} />
    </svg>
  );
}

function ConfirmDemo() {
  const reduce = useSafeReducedMotion();
  const { context } = useStageMode();
  const [state, setState] = useState<State>("idle");
  const [mode, setMode] = useState<Mode>("press");
  const [left, setLeft] = useState(COUNT_FROM);
  const [holding, setHolding] = useState(false);
  const [said, setSaid] = useState("");
  const root = useRef<HTMLDivElement>(null);
  const askedAt = useRef(0);
  const timers = useRef<number[]>([]);
  const focusInside = useRef(false);
  const holdTimer = useRef<number | undefined>(undefined);
  const width = useMotionValue<number | "auto">("auto");
  const target = useRef(0);
  const uid = useId();

  const clearTimers = () => {
    timers.current.forEach((t) => window.clearTimeout(t));
    timers.current = [];
  };
  const later = (fn: () => void, ms: number) => timers.current.push(window.setTimeout(fn, ms));
  useEffect(
    () => () => {
      clearTimers();
      window.clearTimeout(holdTimer.current);
    },
    [],
  );

  const go = (next: State, announce?: string) => {
    clearTimers();
    window.clearTimeout(holdTimer.current);
    holdTimer.current = undefined;
    focusInside.current = !!root.current?.contains(document.activeElement);
    if (next === "asking") askedAt.current = performance.now();
    setHolding(false);
    setState(next);
    if (announce) setSaid(announce);
  };

  // Simulated work. A real build waits for the server before showing the result.
  const run = () => {
    go("pending", "Deleting");
    later(() => go("done", "Deleted. Undo is available."), 900);
  };

  // After each change of face, keep focus on the control if it was there.
  useEffect(() => {
    if (!focusInside.current) return;
    focusInside.current = false;
    const face = state === "undoing" ? "pending" : state;
    const el = root.current?.querySelector<HTMLElement>(`.cf-face[data-face="${face}"] [data-first]`);
    el?.focus({ preventScroll: true });
  }, [state]);

  // Unanswered questions and finished results return to rest by themselves.
  useEffect(() => {
    if (state === "asking") later(() => go("idle", "Cancelled"), ASK_TIMEOUT);
    if (state === "done") later(() => go("idle"), RESULT_TIMEOUT);
    if (state === "counting") {
      let n = COUNT_FROM;
      const tick = () => {
        n -= 1;
        if (n <= 0) return run();
        setLeft(n);
        later(tick, 1000);
      };
      later(tick, 1000);
    }
    // go and run only set state and timers; re-running on their identity would restart the clocks.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state]);

  // A press outside cancels an open question.
  useEffect(() => {
    if (state !== "asking" && state !== "counting") return;
    const onDown = (e: PointerEvent) => {
      if (e.target instanceof Node && !root.current?.contains(e.target)) go("idle", "Cancelled");
    };
    document.addEventListener("pointerdown", onDown);
    return () => document.removeEventListener("pointerdown", onDown);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state]);

  const undo = () => {
    go("undoing", "Restoring");
    later(() => go("idle", "Restored"), 700);
  };
  const confirm = () => {
    if (performance.now() - askedAt.current < ARM_MS) return;
    if (mode === "countdown") {
      setLeft(COUNT_FROM);
      go("counting", `Deleting in ${COUNT_FROM} seconds`);
    } else run();
  };
  // The hold has its own timer, so letting go only ever cancels a hold that has not finished.
  const startHold = () => {
    if (performance.now() - askedAt.current < ARM_MS || holdTimer.current !== undefined) return;
    clearTimers();
    setHolding(true);
    holdTimer.current = window.setTimeout(() => {
      holdTimer.current = undefined;
      run();
    }, HOLD_MS);
  };
  const endHold = () => {
    if (holdTimer.current === undefined) return;
    window.clearTimeout(holdTimer.current);
    holdTimer.current = undefined;
    setHolding(false);
    later(() => go("idle", "Cancelled"), ASK_TIMEOUT);
  };

  const onSize = useCallback(
    (w: number) => {
      if (Math.abs(w - target.current) < 0.25) return;
      const from = target.current;
      target.current = w;
      if (!from || reduce) {
        width.jump("auto");
        return;
      }
      const now = width.get();
      if (now === "auto") width.jump(from);
      const growing = w > (typeof now === "number" ? now : from);
      void animate(width, w, growing ? GROW : SHRINK).then(() => {
        if (target.current === w) width.jump("auto");
      });
    },
    [reduce, width],
  );

  const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
    if (e.key === "Escape" && (state === "asking" || state === "counting")) {
      e.stopPropagation();
      focusInside.current = true;
      go("idle", "Cancelled");
    }
  };

  const key = state === "undoing" ? "pending" : state;
  return (
    <div className="dm cf">
      {context === "detail" && (
        <div className="cf-modes" role="radiogroup" aria-label="How Delete is confirmed" onKeyDown={radioArrows}>
          {(["press", "hold", "countdown"] as const).map((m) => (
            <button key={m} type="button" role="radio" aria-checked={mode === m} tabIndex={mode === m ? 0 : -1} className="cf-mode" onClick={() => setMode(m)}>
              {m === "press" ? "Press" : m === "hold" ? "Hold" : "Countdown"}
            </button>
          ))}
        </div>
      )}
      <div className="cf-row">
        <span className="cf-file">Harbour Physio website</span>
        <motion.div ref={root} className="cf-pill" data-state={state} style={{ width }} onKeyDown={onKey}>
          <AnimatePresence initial={false} mode="popLayout">
            {key === "idle" && (
              <Face key="idle" k="idle" reduce={reduce} onSize={onSize}>
                <button type="button" className="cf-btn cf-open" data-first onClick={() => go("asking")}>
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M4 7h16M10 11v6M14 11v6M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12M9 7V4h6v3" />
                  </svg>
                  Delete project
                </button>
              </Face>
            )}
            {key === "asking" && (
              <Face key="asking" k="asking" reduce={reduce} onSize={onSize}>
                <Part reduce={reduce}>
                  <span className="cf-q">Delete project?</span>
                </Part>
                <Part reduce={reduce}>
                  <button type="button" className="cf-btn" data-first onClick={() => go("idle", "Cancelled")}>
                    Cancel
                  </button>
                </Part>
                <Part reduce={reduce}>
                  {mode === "hold" ? (
                    <button
                      type="button"
                      className="cf-btn cf-danger cf-delete"
                      data-holding={holding || undefined}
                      aria-describedby={`${uid}-hold`}
                      onPointerDown={startHold}
                      onPointerUp={endHold}
                      onPointerLeave={endHold}
                      onKeyDown={(e) => {
                        if ((e.key === " " || e.key === "Enter") && !e.repeat) {
                          e.preventDefault();
                          startHold();
                        }
                      }}
                      onKeyUp={(e) => {
                        if (e.key === " " || e.key === "Enter") endHold();
                      }}
                    >
                      <span className="cf-fill" aria-hidden="true" />
                      <span className="cf-label">Hold to delete</span>
                      <span id={`${uid}-hold`} className="sr-only">
                        Press and hold for one second
                      </span>
                    </button>
                  ) : (
                    <button type="button" className="cf-btn cf-danger cf-delete" onClick={confirm}>
                      Delete
                    </button>
                  )}
                </Part>
              </Face>
            )}
            {key === "counting" && (
              <Face key="counting" k="counting" reduce={reduce} onSize={onSize}>
                <span className="cf-q">
                  Deleting in <span className="cf-sec">{left}</span>
                </span>
                <button type="button" className="cf-btn" data-first onClick={() => go("idle", "Cancelled")}>
                  Cancel
                </button>
              </Face>
            )}
            {key === "pending" && (
              <Face key="pending" k="pending" reduce={reduce} onSize={onSize}>
                <span className="cf-q cf-busy" data-first tabIndex={-1}>
                  <span className="cf-spin" aria-hidden="true" />
                  {state === "undoing" ? "Restoring" : "Deleting"}
                </span>
              </Face>
            )}
            {key === "done" && (
              <Face key="done" k="done" reduce={reduce} onSize={onSize}>
                <span className="cf-q">
                  <Check reduce={reduce} />
                  Deleted
                </span>
                <button type="button" className="cf-btn cf-undo" data-first onClick={undo}>
                  Undo
                </button>
              </Face>
            )}
          </AnimatePresence>
        </motion.div>
      </div>
      <p className="sr-only" role="status">
        {said}
      </p>
    </div>
  );
}

// What a hovered card shows: ask, confirm, and take it back.
const TOUR: Tour = [
  { click: ".cf-open", wait: 900 },
  { click: ".cf-delete", wait: 1800 },
  { click: ".cf-undo", wait: 1200 },
];

export default function ConfirmInPlaceEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Delete that asks where you clicked" tour={TOUR} sample>
      <ConfirmDemo />
    </PieceStage>
  );
}

More like this

Button that shows its own progress

Press, LoadingButtons and toggles

Cookie choice that folds away

FeedbackOverlays and toasts

Popover that closes faster than it opens

PressOverlays and toasts

Toast that follows a request

Loading, FeedbackOverlays and toasts

Form in named steps

Type, FeedbackForms and inputs

Lit buttons and panels

PressButtons and toggles