Open source CapCut alternative.
TypeScript
refactor(site): one drag-to-sort behind every reorderable list
David Ledcdc28146dd3
diff --git a/site/src/app/cut/app/su/analytics/Reorder.tsx b/site/src/app/cut/app/su/analytics/Reorder.tsxindex 1413e1b6..913375b7 100644--- a/site/src/app/cut/app/su/analytics/Reorder.tsx+++ b/site/src/app/cut/app/su/analytics/Reorder.tsx@@ -1,10 +1,11 @@"use client";-import { useMemo, useState, type ReactNode } from "react";-import { GripVertical } from "lucide-react";+import { useMemo } from "react";+import { useDragSort } from "@/components/Sortable";import { useLocalPref } from "@/cut/lib/uiState";-import { cn } from "@/lib/utils";++export { SortCard as DragBlock } from "@/components/Sortable";/*** Drag-to-reorder for a grid of dashboard blocks. localStorage keeps a list of@@ -18,103 +19,19 @@ export function useReorder<T extends string>(key: string, ids: readonly T[]) {[],(v) => Array.isArray(v) && v.every((x) => typeof x === "string"),);- const [dragId, setDragId] = useState<T | null>(null);- const [overId, setOverId] = useState<T | null>(null);- const order = useMemo(() => {+ const stored = useMemo(() => {const kept = saved.filter((id): id is T => (ids as readonly string[]).includes(id));return [...kept, ...ids.filter((id) => !kept.includes(id))];}, [saved, ids]);- // Dropping onto a block ahead of the dragged one lands after it, behind it- // lands before — the block ends up where the pointer let go.- const move = (from: T, to: T) => {- if (from === to) return;- const forward = order.indexOf(from) < order.indexOf(to);- const next = order.filter((id) => id !== from);- next.splice(next.indexOf(to) + (forward ? 1 : 0), 0, from);- setSaved(next);- };-- const blockProps = (id: T) => ({- dragging: dragId === id,- over: overId === id && dragId !== null && dragId !== id,- onDragEnd: () => {- setDragId(null);- setOverId(null);- },- onDragLeave: () => setOverId((prev) => (prev === id ? null : prev)),- onDragOver: (e: React.DragEvent) => {- if (dragId === null) return;- e.preventDefault();- e.dataTransfer.dropEffect = "move";- setOverId(id);- },- onDragStart: (e: React.DragEvent) => {- setDragId(id);- e.dataTransfer.effectAllowed = "move";- },- onDrop: (e: React.DragEvent) => {- e.preventDefault();- if (dragId !== null) move(dragId, id);- setDragId(null);- setOverId(null);- },- });-- return { blockProps, customized: saved.length > 0, order, reset: () => setSaved([]) };-}+ const sort = useDragSort(stored, setSaved);-/**- * One block in a reordered grid. The card only becomes draggable while its- * grip is held, so charts keep their own pointer handling.- */-export function DragBlock({- dragging,- over,- className,- children,- onDragEnd,- ...handlers-}: {- dragging: boolean;- over: boolean;- className?: string;- children: ReactNode;- onDragEnd: () => void;- onDragLeave: () => void;- onDragOver: (e: React.DragEvent) => void;- onDragStart: (e: React.DragEvent) => void;- onDrop: (e: React.DragEvent) => void;-}) {- const [armed, setArmed] = useState(false);- return (- <div- {...handlers}- draggable={armed}- onDragEnd={() => {- setArmed(false);- onDragEnd();- }}- className={cn(- "group relative h-full rounded-xl [&>div]:h-full",- dragging && "opacity-40",- over && "outline-2 outline-offset-2 outline-[var(--chart-1)]",- className,- )}- >- <button- type="button"- aria-label="Drag to reorder"- title="Drag to reorder"- onPointerDown={() => setArmed(true)}- onPointerUp={() => setArmed(false)}- onPointerCancel={() => setArmed(false)}- className="absolute top-2 right-2 z-20 cursor-grab rounded-md p-1 text-muted-foreground/60 opacity-0 transition-opacity hover:bg-muted focus-visible:opacity-100 active:cursor-grabbing group-hover:opacity-100"- >- <GripVertical className="size-4" />- </button>- {children}- </div>- );+ return {+ blockProps: sort.itemProps,+ containerProps: sort.containerProps,+ customized: saved.length > 0,+ order: sort.order,+ reset: () => setSaved([]),+ };}diff --git a/site/src/components/Sortable.tsx b/site/src/components/Sortable.tsxnew file mode 100644index 00000000..6dc596df--- /dev/null+++ b/site/src/components/Sortable.tsx@@ -0,0 +1,257 @@+"use client";++import { useCallback, useLayoutEffect, useRef, useState, type ReactNode } from "react";+import { GripVertical } from "lucide-react";++import { cn } from "@/lib/utils";++/** How long a displaced item takes to slide into its new slot. */+const SLIDE_MS = 180;++/** A private drag type. Firefox refuses to start a drag with an empty+ * dataTransfer, and a private type keeps a sort drag invisible to the file and+ * asset drop zones the same page may be running. */+const SORT_MIME = "application/x-sort-item";++type ItemHandlers = {+ onDragEnd: () => void;+ onDragOver: (e: React.DragEvent) => void;+ onDragStart: (e: React.DragEvent) => void;+ onDrop: (e: React.DragEvent) => void;+};++/**+ * Drag-to-sort with a live preview: while a drag is in flight the list renders+ * in the order it would land in, so the other items slide out of the way and+ * the hole under the cursor is the drop zone. Letting go commits that order;+ * cancelling the drag slides everything back.+ *+ * The hook owns order and animation only. Each surface decides what makes an+ * item draggable — a grip, the whole row — and spreads the handlers where it+ * wants them.+ */+export function useDragSort<T extends string>(+ order: readonly T[],+ commit: (next: T[]) => void,+) {+ const [drag, setDrag] = useState<{ id: T; preview: T[] } | null>(null);+ // The list keeps living during a drag — a queue drains, a card arrives — so+ // the preview is reconciled against it: ids that left drop out, ids that+ // arrived land at the end.+ const shown = drag+ ? [+ ...drag.preview.filter((id) => order.includes(id)),+ ...order.filter((id) => !drag.preview.includes(id)),+ ]+ : (order as T[]);+ const nodeRef = useSlide(drag !== null);++ // Hovering another item moves the dragged one into that slot: forward past+ // the hovered item, backward in front of it — so it lands where the pointer+ // is. After the shift the pointer sits over the dragged item's own hole,+ // which is ignored, so the preview settles instead of oscillating.+ const hover = (id: T) => {+ if (!drag || drag.id === id) return;+ const from = shown.indexOf(drag.id);+ const to = shown.indexOf(id);+ if (from < 0 || to < 0) return;+ const preview = shown.slice();+ preview.splice(to, 0, ...preview.splice(from, 1));+ setDrag({ id: drag.id, preview });+ };++ const land = () => {+ if (drag) commit(shown);+ setDrag(null);+ };++ const itemProps = (+ id: T,+ ): { dragging: boolean; ref: (el: HTMLElement | null) => void } & ItemHandlers => ({+ dragging: drag?.id === id,+ ref: nodeRef(id),+ onDragEnd: () => setDrag(null),+ onDragOver: (e) => {+ if (!drag) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = "move";+ hover(id);+ },+ onDragStart: (e) => {+ e.dataTransfer.effectAllowed = "move";+ e.dataTransfer.setData(SORT_MIME, id);+ setDrag({ id, preview: [...order] });+ },+ onDrop: (e) => {+ e.preventDefault();+ land();+ },+ });++ // The gaps between items belong to the list too, so a release that lands+ // between two cards keeps the arrangement instead of snapping back.+ const containerProps = {+ onDragOver: (e: React.DragEvent) => {+ if (!drag) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = "move";+ },+ onDrop: (e: React.DragEvent) => {+ if (!drag) return;+ e.preventDefault();+ land();+ },+ };++ return { containerProps, dragging: drag?.id ?? null, itemProps, order: shown };+}++/**+ * Slides items between layout positions. Every commit records where the+ * registered nodes sit; while a drag is live, a commit that moved them puts+ * each one back where it was with a transform and then releases it, so the+ * reordering reads as movement rather than a jump. Layout offsets stand in for+ * viewport rects, so scrolling mid-drag does not register as movement.+ *+ * Measuring on every commit — rather than only when the order changes — is+ * what makes the first drag animate: the list is often laid out after the hook+ * first runs, and a stale record would have nothing to move from.+ */+function useSlide(live: boolean) {+ const nodes = useRef(new Map<string, HTMLElement>());+ const callbacks = useRef(new Map<string, (el: HTMLElement | null) => void>());+ const last = useRef(new Map<string, { x: number; y: number }>());+ // The commit that ends a drag animates too: the list either settles into the+ // dropped order or slides back from a cancel.+ const wasLive = useRef(false);++ useLayoutEffect(() => {+ const now = new Map<string, { x: number; y: number }>();+ nodes.current.forEach((el, id) => now.set(id, { x: el.offsetLeft, y: el.offsetTop }));+ const animate =+ (live || wasLive.current) &&+ !window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ if (animate)+ now.forEach((pos, id) => {+ const was = last.current.get(id);+ const el = nodes.current.get(id);+ if (!was || !el) return;+ const dx = was.x - pos.x;+ const dy = was.y - pos.y;+ if (!dx && !dy) return;+ el.style.transition = "none";+ el.style.transform = `translate(${dx}px, ${dy}px)`;+ requestAnimationFrame(() => {+ el.style.transition = `transform ${SLIDE_MS}ms cubic-bezier(0.2, 0, 0, 1)`;+ el.style.transform = "";+ });+ });+ last.current = now;+ wasLive.current = live;+ });++ return useCallback((id: string) => {+ let cb = callbacks.current.get(id);+ if (!cb) {+ cb = (el: HTMLElement | null) => {+ if (el) nodes.current.set(id, el);+ else nodes.current.delete(id);+ };+ callbacks.current.set(id, cb);+ }+ return cb;+ }, []);+}++/** Longest side of a drag ghost, px. */+const GHOST_MAX = 260;++/**+ * The item itself as the drag ghost, snapshotted before it turns into a hole.+ * A large card shrinks so the thing in hand does not blanket the list it is+ * carried across.+ */+export function setSortDragImage(e: React.DragEvent, el: HTMLElement) {+ const rect = el.getBoundingClientRect();+ const scale = Math.min(1, GHOST_MAX / Math.max(rect.width, rect.height));+ const clone = el.cloneNode(true) as HTMLElement;+ clone.style.width = `${rect.width}px`;+ clone.style.height = `${rect.height}px`;+ clone.style.margin = "0";+ clone.style.opacity = "0.9";+ clone.style.transform = `scale(${scale})`;+ clone.style.transformOrigin = "top left";+ const wrap = document.createElement("div");+ wrap.style.cssText =+ "position:absolute;top:-1000px;left:-1000px;pointer-events:none;" ++ `width:${rect.width * scale}px;height:${rect.height * scale}px;`;+ wrap.appendChild(clone);+ document.body.appendChild(wrap);+ e.dataTransfer.setDragImage(+ wrap,+ Math.min(Math.max(e.clientX - rect.left, 0), rect.width) * scale,+ Math.min(Math.max(e.clientY - rect.top, 0), rect.height) * scale,+ );+ setTimeout(() => wrap.remove(), 0);+}++/**+ * One card in a sorted grid. The card becomes draggable only while its grip is+ * held, so charts keep their own pointer handling, and it empties to a dashed+ * outline for the length of the drag — the hole travels with the pointer and+ * shows where the card lands.+ */+export function SortCard({+ children,+ className,+ dragging,+ onDragEnd,+ onDragStart,+ ref,+ ...handlers+}: {+ children: ReactNode;+ className?: string;+ dragging: boolean;+ ref: (el: HTMLElement | null) => void;+} & ItemHandlers) {+ const host = useRef<HTMLDivElement | null>(null);+ const [armed, setArmed] = useState(false);+ return (+ <div+ {...handlers}+ draggable={armed}+ ref={(el) => {+ host.current = el;+ ref(el);+ }}+ onDragEnd={() => {+ setArmed(false);+ onDragEnd();+ }}+ onDragStart={(e) => {+ if (host.current) setSortDragImage(e, host.current);+ onDragStart(e);+ }}+ className={cn(+ "group relative h-full rounded-xl [&>div]:h-full",+ dragging &&+ "bg-muted/40 outline-2 outline-dashed -outline-offset-2 outline-muted-foreground/30 [&>*]:invisible",+ className,+ )}+ >+ <button+ type="button"+ aria-label="Drag to reorder"+ title="Drag to reorder"+ onPointerDown={() => setArmed(true)}+ onPointerUp={() => setArmed(false)}+ onPointerCancel={() => setArmed(false)}+ className="absolute top-2 right-2 z-20 cursor-grab rounded-md p-1 text-muted-foreground/60 opacity-0 transition-opacity hover:bg-muted focus-visible:opacity-100 active:cursor-grabbing group-hover:opacity-100"+ >+ <GripVertical className="size-4" />+ </button>+ {children}+ </div>+ );+}diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 3a524452..81904ac6 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -1296,12 +1296,18 @@ function ChatSession({)}onRemove={(id) => setQueue((q) => q.filter((m) => m.id !== id))}- onReorder={(from, to) =>+ onReorder={(ids) =>setQueue((q) => {- const next = [...q];- const [grabbed] = next.splice(from, 1);- next.splice(to, 0, grabbed);- return next;+ // The tray only shows part of the queue, so the dropped+ // order refills the slots those rows already occupied and+ // everything else stays where it is.+ const byId = new Map(q.map((m) => [m.id, m]));+ const landed = ids.filter((id) => byId.has(id));+ const moved = new Set(landed);+ let next = 0;+ return q.map((m) =>+ moved.has(m.id) ? (byId.get(landed[next++]) ?? m) : m,+ );})}onTogglePaused={() => {diff --git a/site/src/cut/components/ComposerQueue.tsx b/site/src/cut/components/ComposerQueue.tsxindex a88407c8..d1422abf 100644--- a/site/src/cut/components/ComposerQueue.tsx+++ b/site/src/cut/components/ComposerQueue.tsx@@ -13,6 +13,7 @@ import {} from "lucide-react";import { cn } from "@/lib/utils";import { ScrollArea } from "@/components/ui/scroll-area";+import { useDragSort } from "@/components/Sortable";import { RefThumb } from "./AssetRefs";import type { AssetRef } from "@/cut/lib/assetRef";@@ -59,18 +60,19 @@ export function ComposerQueue({onEditingChange: (id: string | null) => void;onCommitEdit: (id: string, text: string) => void;onRemove: (id: string) => void;- onReorder: (from: number, to: number) => void;+ /** The queued rows in the order they were dropped into. */+ onReorder: (ids: string[]) => void;onTogglePaused: () => void;}) {const [open, setOpen] = useState(true);- const dragFrom = useRef<number | null>(null);- const [dragOver, setDragOver] = useState<number | null>(null);const frozen = editingId !== null;const waiting = items.filter((m) => m.status === "queued");- // Rows carry their index in the full queue so a reorder maps back to it.- const rows = items- .map((item, index) => ({ item, index }))- .filter(({ item }) => frozen || item.status === "queued");+ const rows = items.filter((item) => frozen || item.status === "queued");+ // Dragging renders the queue in the order it would land in, so the rows+ // shift out of the way and the hole is the drop zone.+ const rowIds = rows.map((it) => it.id);+ const byId = new Map(rows.map((it) => [it.id, it] as const));+ const sort = useDragSort(rowIds, onReorder);// The wrapper owns the list height: the rows' measured height capped at// 38vh, animated to zero on collapse, clipped while it moves. The scroll// area fills the wrapper and floats the slim scrollbar over the rows once@@ -146,8 +148,11 @@ export function ComposerQueue({style={{ height: open ? listH : 0, opacity: open ? 1 : 0 }}><ScrollArea className="h-full">- <div ref={listRef}>- {rows.map(({ item: it, index }) => {+ <div ref={listRef} {...sort.containerProps}>+ {sort.order.map((rowId) => {+ const it = byId.get(rowId);+ if (!it) return null;+ const { dragging, onDragStart, ...drag } = sort.itemProps(rowId);const isEditing = editingId === it.id;const shown =it.status === "running" && !busy ? "done" : it.status;@@ -156,10 +161,9 @@ export function ComposerQueue({return (<divkey={it.id}+ {...drag}draggable={!frozen}onDragStart={(e) => {- dragFrom.current = index;- e.dataTransfer.effectAllowed = "move";// The browser snapshots the row on a flat backdrop, which// squares off its corners; hand it a styled clone so the// ghost keeps the rounded row shape.@@ -182,26 +186,12 @@ export function ComposerQueue({e.clientY - rect.top,);setTimeout(() => ghost.remove(), 0);- }}- onDragOver={(e) => {- e.preventDefault();- setDragOver(index);- }}- onDrop={(e) => {- e.preventDefault();- if (dragFrom.current !== null && dragFrom.current !== index)- onReorder(dragFrom.current, index);- dragFrom.current = null;- setDragOver(null);- }}- onDragEnd={() => {- dragFrom.current = null;- setDragOver(null);+ onDragStart(e);}}className={cn("group flex items-start gap-1.5 px-2.5 py-1.5 transition-colors duration-100 motion-reduce:transition-none",- dragOver === index- ? "bg-muted-foreground/20"+ dragging+ ? "bg-muted-foreground/5 outline-1 outline-dashed -outline-offset-2 outline-muted-foreground/40 [&>*]:invisible": !isEditing &&!locked &&!gone &&