Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: drag sidebar rows in the desktop app, and drop the drag hint (#11561)

Michael Han92e14851be53
diff --git a/studio/backend/core/inference/diffusion_cache.py b/studio/backend/core/inference/diffusion_cache.py
index 2313f78e05b..42372482b36 100644
--- a/studio/backend/core/inference/diffusion_cache.py
+++ b/studio/backend/core/inference/diffusion_cache.py
@@ -83,9 +83,10 @@ def register_unregistered_transformer_blocks(logger: Any = None) -> tuple:
from diffusers.hooks._helpers import TransformerBlockMetadata, TransformerBlockRegistry
except Exception: # noqa: BLE001 - an older diffusers has no registry to fill
return ()
- for (module_name, class_name), (hidden_index, encoder_index) in (
- _UNREGISTERED_BLOCK_METADATA.items()
- ):
+ for (module_name, class_name), (
+ hidden_index,
+ encoder_index,
+ ) in _UNREGISTERED_BLOCK_METADATA.items():
try:
import importlib
block_cls = getattr(importlib.import_module(module_name), class_name, None)
diff --git a/studio/backend/core/inference/prequant_safetensors.py b/studio/backend/core/inference/prequant_safetensors.py
index 3eaeb79fc43..23790cdfa24 100644
--- a/studio/backend/core/inference/prequant_safetensors.py
+++ b/studio/backend/core/inference/prequant_safetensors.py
@@ -195,7 +195,9 @@ def save_prequant_safetensors(path: str, *, fmt: str, state_dict: Any, metadata:
# Root-level plain tensors go beside the flat set, not through it. Split BEFORE flatten so
# torchao only ever sees dotted keys, and the pair stays exactly the one it supports.
roots = _root_level_keys(state_dict)
- quantizable = {k: v for k, v in state_dict.items() if k not in set(roots)} if roots else state_dict
+ quantizable = (
+ {k: v for k, v in state_dict.items() if k not in set(roots)} if roots else state_dict
+ )
flatten, _ = helpers
try:
@@ -284,7 +286,12 @@ def _drop_field(value: Any, name: str, removed: list) -> Any:
def _header_without_unconstructible_fields(
- unflatten: Any, tensors: Any, raw: dict, *, path: str, attempts: int = 8
+ unflatten: Any,
+ tensors: Any,
+ raw: dict,
+ *,
+ path: str,
+ attempts: int = 8,
) -> dict:
"""``raw``, minus fields THIS torchao cannot construct, when dropping them changes nothing.
@@ -383,7 +390,7 @@ def load_prequant_safetensors(path: str, *, device: str = "cpu") -> dict:
# tensors that never needed it. Keyed off the prefix rather than the header list, so a file
# written by a build that recorded one and not the other still reads; the list is the order.
roots = {
- key[len(UNSLOTH_ROOT_PREFIX):]: tensors.pop(key)
+ key[len(UNSLOTH_ROOT_PREFIX) :]: tensors.pop(key)
for key in [k for k in tensors if k.startswith(UNSLOTH_ROOT_PREFIX)]
}
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 68e93214f53..c6ebb146742 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -2250,9 +2250,11 @@ class SdCppDiffusionBackend:
server_binary = ensure_sd_server_binary(
allow_install = _install_allowed() and not upgrade_pending, accelerator = accelerator
)
- if server_binary is not None and not sd_cpp_binary_runs_family(
- server_binary, self._loading_family
- ) and self._loading_family is not None:
+ if (
+ server_binary is not None
+ and not sd_cpp_binary_runs_family(server_binary, self._loading_family)
+ and self._loading_family is not None
+ ):
# Not fatal on its own: the one-shot path resolves its own binary, which may well be a
# newer build, and _resolve_engine refuses it if it is not.
logger.warning(
diff --git a/studio/backend/tests/test_diffusion_cache.py b/studio/backend/tests/test_diffusion_cache.py
index f6ab99c1e3b..7227bcccae1 100644
--- a/studio/backend/tests/test_diffusion_cache.py
+++ b/studio/backend/tests/test_diffusion_cache.py
@@ -100,7 +100,13 @@ class _PrefixKVTransformer(_MixinTransformer):
FLUX.2 klein KV, Wan-Animate-2): its blocks see the whole joint sequence on the first step and
the target tokens alone afterwards."""
- def forward(self, hidden_states, *, kv_cache = None, kv_cache_mode = None):
+ def forward(
+ self,
+ hidden_states,
+ *,
+ kv_cache = None,
+ kv_cache_mode = None,
+ ):
return hidden_states
diff --git a/studio/backend/tests/test_diffusion_precision.py b/studio/backend/tests/test_diffusion_precision.py
index f2a4f16ee95..d40f3545fda 100644
--- a/studio/backend/tests/test_diffusion_precision.py
+++ b/studio/backend/tests/test_diffusion_precision.py
@@ -611,7 +611,7 @@ def test_an_unset_request_takes_the_family_scheme_and_is_marked_as_not_asked_for
def test_an_opt_out_still_pins_the_released_bf16_encoder():
- """"none"/"off" has to survive the new default, or the bf16 reference configuration
+ """ "none"/"off" has to survive the new default, or the bf16 reference configuration
becomes unreachable and no comparison against it can be run."""
for opt_out in ("none", "off", " OFF "):
assert resolve_te_quant_request(opt_out, "fp8") == (None, False)
diff --git a/studio/backend/tests/test_diffusion_te_prequant.py b/studio/backend/tests/test_diffusion_te_prequant.py
index 24df566cc57..fc0497372a0 100644
--- a/studio/backend/tests/test_diffusion_te_prequant.py
+++ b/studio/backend/tests/test_diffusion_te_prequant.py
@@ -1049,10 +1049,15 @@ def test_every_family_default_scheme_is_one_we_actually_host_for_that_family():
if scheme is None:
continue
if not any(
- family_te_prequant_repo(fam, scheme, component) for component in tpq.TE_PREQUANT_COMPONENTS
+ family_te_prequant_repo(fam, scheme, component)
+ for component in tpq.TE_PREQUANT_COMPONENTS
):
- offenders.append(f"{fam.name}: te_quant_auto={scheme!r} with no hosted {scheme} encoder")
- assert not offenders, "\n ".join(["families default to an unhosted encoder scheme:", *offenders])
+ offenders.append(
+ f"{fam.name}: te_quant_auto={scheme!r} with no hosted {scheme} encoder"
+ )
+ assert not offenders, "\n ".join(
+ ["families default to an unhosted encoder scheme:", *offenders]
+ )
def test_qwen_image_2_1_defaults_to_the_hosted_fp8_encoder():
diff --git a/studio/backend/tests/test_prequant_safetensors.py b/studio/backend/tests/test_prequant_safetensors.py
index a0582baa823..a5c01c44e22 100644
--- a/studio/backend/tests/test_prequant_safetensors.py
+++ b/studio/backend/tests/test_prequant_safetensors.py
@@ -489,8 +489,9 @@ def test_a_field_a_newer_torchao_added_is_dropped_when_it_is_inert(monkeypatch):
return {"w.weight": object()}, {}
header = {
- "w.weight": json.dumps({"_type": "Int8Tensor", "_data": {"reduce_range": False,
- "block_size": [1, 4]}}),
+ "w.weight": json.dumps(
+ {"_type": "Int8Tensor", "_data": {"reduce_range": False, "block_size": [1, 4]}}
+ ),
ps.UNSLOTH_FORMAT_KEY: "fp8_v1",
}
pruned = ps._header_without_unconstructible_fields(
@@ -506,6 +507,7 @@ def test_a_field_a_newer_torchao_added_is_dropped_when_it_is_inert(monkeypatch):
def test_a_field_carrying_a_real_setting_is_refused_rather_than_dropped():
"""Dropping a field that is doing something would load the weights under settings the file did
not ask for. A refusal keeps the dense fallback, which is merely slower."""
+
def _unflatten(tensors, header):
raise ValueError("unexpected keyword argument 'reduce_range'")
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 5ecc9e0dfed..e41a9f506f9 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -84,7 +84,6 @@ import {
AudioWave01Icon,
Delete02Icon,
Download01Icon,
- DragDropVerticalIcon,
Edit03Icon,
FolderAddIcon,
FolderAttachmentIcon,
@@ -227,7 +226,6 @@ import {
useState,
type ReactNode,
} from "react";
-import { createPortal } from "react-dom";
import { isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import { useIsCoarsePointer } from "@/hooks/use-mobile";
@@ -1810,7 +1808,6 @@ export function AppSidebar() {
projectChatRowIds,
],
);
- const dropHintRef = useRef<HTMLDivElement | null>(null);
// A chat's row stays on screen while its move is written, so it can be dropped again before
// the first move lands. Moves of one chat run one after another, and only the latest drop
// commits its slot and pin, so an earlier drop cannot land after, or on top of, a later one.
@@ -1821,7 +1818,6 @@ export function AppSidebar() {
const coarsePointer = useIsCoarsePointer();
const dnd = useSidebarDrag({
context: dropContext,
- hintRef: dropHintRef,
// A closed folder or section the pointer rests on opens.
onSpringOpen: (zone) => {
if (zone.folderId) {
@@ -1970,59 +1966,6 @@ export function AppSidebar() {
);
}
- /** The hint beside the cursor: what the drop would do. */
- function dropHint(plan: SidebarDropPlan): {
- icon: typeof PinIcon;
- text: string;
- } {
- switch (plan.action.kind) {
- case "pin":
- return { icon: PinIcon, text: t("shell.drag.pin") };
- case "unpin":
- return { icon: PinOffIcon, text: t("shell.drag.unpin") };
- case "reorder":
- return { icon: DragDropVerticalIcon, text: t("shell.drag.reorder") };
- case "move": {
- const projectId = plan.action.projectId;
- if (projectId === null) {
- return { icon: MessageCircleIcon, text: t("shell.drag.moveToRecents") };
- }
- const name = projects.find((project) => project.id === projectId)?.name ?? "";
- return { icon: Folder01Icon, text: t("shell.drag.moveTo", { name }) };
- }
- }
- }
-
- /** The hint, in a portal so the sidebar cannot clip it. Positioned through the ref, hidden
- * between answers rather than unmounted. No inline style: a re-render would write it back
- * over the transform the pointer set. */
- const dropHintPortal =
- draggingRow && typeof document !== "undefined"
- ? createPortal(
- <div
- ref={dropHintRef}
- data-testid="sidebar-drop-hint"
- aria-hidden
- className={cn(
- "pointer-events-none fixed left-0 top-0 z-[100] flex items-center gap-1.5 rounded-full border border-border bg-popover px-2.5 py-1 text-ui-12 leading-ui-16 font-medium text-popover-foreground shadow-md transition-opacity duration-100",
- dnd.plan ? "opacity-100" : "opacity-0",
- )}
- >
- {dnd.plan && (
- <>
- <HugeiconsIcon
- icon={dropHint(dnd.plan).icon}
- strokeWidth={1.75}
- className="size-3.5 shrink-0"
- />
- <span className="max-w-48 truncate">{dropHint(dnd.plan).text}</span>
- </>
- )}
- </div>,
- document.body,
- )
- : null;
-
useEffect(() => {
const activeVisibleThreadIdSet = new Set(
activeVisibleThreadIdKey ? activeVisibleThreadIdKey.split("\n") : [],
@@ -3875,7 +3818,6 @@ export function AppSidebar() {
return (
<>
{slotShortcuts}
- {dropHintPortal}
<Sidebar
collapsible="icon"
collapseToZero={isTauri}
diff --git a/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts b/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
index cc7372d5cee..52af3f2d130 100644
--- a/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
+++ b/studio/frontend/src/features/chat/hooks/use-sidebar-drag.ts
@@ -2,7 +2,11 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
// The React side of sidebar drag-and-drop: the lifted row, the plan under the pointer, and the
-// native drag events that feed both. What a drop does is decided in lib/sidebar-drag.ts.
+// pointer events that feed both. What a drop does is decided in lib/sidebar-drag.ts.
+//
+// Pointer events, not the HTML5 drag API. The desktop webview answers every OS drag itself and
+// never forwards it to the page, so dragover and drop never fire there and a row wired to them
+// is dead. Same reason shared-composer.tsx skips its drop handlers under isTauri.
import { useCallback, useEffect, useRef, useState } from "react";
@@ -26,11 +30,70 @@ import {
/** How long the pointer rests on a closed folder or section before it opens. */
export const SPRING_OPEN_DELAY_MS = 450;
-// Zones nest (row in folder block in section). The first zone to answer a dragover marks the
-// event here; outer zones stand down, and the document listener reads the same mark to know
-// whether anything answered. Marking instead of stopping propagation keeps the document
-// listener, which moves the hint, in the loop.
-let lastHandledEvent: Event | null = null;
+/** Pointer travel before a press on a row becomes a drag, so a click stays a click and a
+ * double-click still renames. */
+export const DRAG_THRESHOLD_PX = 5;
+
+/** Marks a drop zone in the DOM, carrying the zone itself. A zone needs no ref and no
+ * registration: the hit test reads it back off whatever sits under the pointer. */
+export const DROP_ZONE_ATTR = "data-sidebar-drop";
+
+/** Set on the body for the length of a drag: no text selection, and the grabbing cursor
+ * follows the row off its own list. */
+export const DRAGGING_BODY_CLASS = "sidebar-row-dragging";
+
+/** Controls that own their own press. A drag never starts from the pin or the kebab. */
+const NO_DRAG_SELECTOR = ".sidebar-row-action";
+
+/** How near an edge of the scroller the pointer scrolls the list, and by how much per move. */
+const EDGE_PX = 48;
+const EDGE_STEP_PX = 12;
+
+interface ZoneHit {
+ zone: SidebarDropZone;
+ closed: boolean;
+ rect: DOMRect;
+}
+
+/** The drop zones under the pointer, innermost first: a row paints over its folder block,
+ * which paints over its section. */
+function zonesUnder(x: number, y: number): ZoneHit[] {
+ if (typeof document === "undefined") return [];
+ const hits: ZoneHit[] = [];
+ for (const element of document.elementsFromPoint(x, y)) {
+ const raw = element.getAttribute(DROP_ZONE_ATTR);
+ if (!raw) continue;
+ try {
+ const parsed = JSON.parse(raw) as {
+ zone: SidebarDropZone;
+ closed?: boolean;
+ };
+ hits.push({
+ zone: parsed.zone,
+ closed: Boolean(parsed.closed),
+ rect: element.getBoundingClientRect(),
+ });
+ } catch {
+ // A zone that cannot be read is one the pointer passes through.
+ }
+ }
+ return hits;
+}
+
+/** The list the row scrolls while it is carried: the nearest ancestor that actually scrolls. */
+function scrollerOf(element: Element | null): HTMLElement | null {
+ for (let node = element; node; node = node.parentElement) {
+ if (!(node instanceof HTMLElement)) continue;
+ const overflow = getComputedStyle(node).overflowY;
+ if (
+ (overflow === "auto" || overflow === "scroll") &&
+ node.scrollHeight > node.clientHeight
+ ) {
+ return node;
+ }
+ }
+ return null;
+}
export interface UseSidebarDragOptions {
/** Read at event time, so a plan sees the lists as they stand. */
@@ -39,8 +102,6 @@ export interface UseSidebarDragOptions {
onDrop: (plan: SidebarDropPlan, drag: SidebarDragItem) => void;
/** Opens the closed folder or section the pointer rested on. */
onSpringOpen?: (zone: SidebarDropZone) => void;
- /** The hint element. Positioned directly, so pointer moves do not re-render the sidebar. */
- hintRef?: React.RefObject<HTMLDivElement | null>;
}
export interface SidebarDragApi {
@@ -50,18 +111,13 @@ export interface SidebarDragApi {
plan: SidebarDropPlan | null;
/** Props that let a row be picked up. */
dragHandleProps: (item: SidebarDragItem) => {
- draggable: true;
- onDragStart: (event: React.DragEvent) => void;
- onDragEnd: () => void;
+ onPointerDown: (event: React.PointerEvent) => void;
};
/** Props that let a spot take a drop. `closed` marks a collapsed folder or section. */
dropZoneProps: (
zone: SidebarDropZone,
options?: { closed?: boolean },
- ) => {
- onDragOver: (event: React.DragEvent) => void;
- onDrop: (event: React.DragEvent) => void;
- };
+ ) => Record<string, string>;
/** The edge the insertion line is drawn on for this row in this list, if any. */
lineEdge: (scope: string, id: string) => DropEdge | undefined;
/** Whether the whole target under this key is lit. */
@@ -81,6 +137,9 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
optionsRef.current = options;
});
const spring = useRef<{ key: string; timer: number } | null>(null);
+ const scroller = useRef<HTMLElement | null>(null);
+ /** The gesture in flight, so a second pointer cannot start another over the top of it. */
+ const press = useRef<{ end: () => void } | null>(null);
const cancelSpring = useCallback(() => {
if (spring.current) {
@@ -99,114 +158,225 @@ export function useSidebarDrag(options: UseSidebarDragOptions): SidebarDragApi {
const clear = useCallback(() => {
setSidebarDragSource(null);
cancelSpring();
+ scroller.current = null;
+ document.body.classList.remove(DRAGGING_BODY_CLASS);
setDrag(null);
showPlan(null);
}, [cancelSpring, showPlan]);
- // One listener per drag: moves the hint, and clears the cue when nothing answered the
- // dragover. `dragleave` fires for every child crossed, so it cannot be trusted for that.
- useEffect(() => {
- if (!drag) return;
- const onDragOver = (event: DragEvent) => {
- const hint = optionsRef.current.hintRef?.current;
- if (hint) {
- hint.style.transform = `translate(${event.clientX + 14}px, ${event.clientY + 18}px)`;
+ useEffect(() => () => clear(), [clear]);
+
+ /** The first zone under the pointer with an answer. No answer lets the zone around it
+ * answer instead. */
+ const aim = useCallback(
+ (
+ x: number,
+ y: number,
+ ): { hit: ZoneHit; outcome: SidebarDropPlan | typeof STAY } | null => {
+ const dragged = sidebarDragSource();
+ if (!dragged) return null;
+ const context = optionsRef.current.context();
+ for (const hit of zonesUnder(x, y)) {
+ const outcome = planSidebarDrop(
+ dragged,
+ hit.zone,
+ dropEdgeAt(hit.rect, y),
+ context,
+ );
+ if (outcome) return { hit, outcome };
}
- if (lastHandledEvent !== event) {
+ return null;
+ },
+ [],
+ );
+
+ /** One step of the edge scroll, true when the list actually moved. Driven by the frame loop,
+ * not by pointermove: a pointer resting on the edge sends no moves and would stall. */
+ const edgeScroll = useCallback((y: number): boolean => {
+ const list = scroller.current;
+ if (!list) return false;
+ const rect = list.getBoundingClientRect();
+ const before = list.scrollTop;
+ if (y < rect.top + EDGE_PX) list.scrollTop -= EDGE_STEP_PX;
+ else if (y > rect.bottom - EDGE_PX) list.scrollTop += EDGE_STEP_PX;
+ return list.scrollTop !== before;
+ }, []);
+
+ const track = useCallback(
+ (x: number, y: number) => {
+ const aimed = aim(x, y);
+ if (!aimed || aimed.outcome === STAY) {
+ // Nothing here, or the row is already in this slot: nothing to paint either way.
cancelSpring();
showPlan(null);
+ return;
}
- };
- // A drop that unmounts the lifted row loses its dragend, so drop ends the gesture too.
- const onEnd = () => clear();
- document.addEventListener("dragover", onDragOver);
- document.addEventListener("dragend", onEnd);
- document.addEventListener("drop", onEnd);
- return () => {
- document.removeEventListener("dragover", onDragOver);
- document.removeEventListener("dragend", onEnd);
- document.removeEventListener("drop", onEnd);
- };
- }, [drag, cancelSpring, clear, showPlan]);
-
- useEffect(() => cancelSpring, [cancelSpring]);
+ showPlan(aimed.outcome);
- const dragHandleProps = useCallback(
- (item: SidebarDragItem) => ({
- draggable: true as const,
- onDragStart: (event: React.DragEvent) => {
- // Firefox needs a payload to drag at all.
- event.dataTransfer.effectAllowed = "move";
- event.dataTransfer.setData("text/plain", item.id);
- event.stopPropagation();
- setSidebarDragSource(item);
- setDrag(item);
- },
- onDragEnd: clear,
- }),
- [clear],
- );
-
- const dropZoneProps = useCallback(
- (zone: SidebarDropZone, zoneOptions?: { closed?: boolean }) => {
+ const { zone, closed } = aimed.hit;
const springKey = zone.folderId
? `folder:${zone.folderId}`
: `section:${zone.section}`;
- return {
- onDragOver: (event: React.DragEvent) => {
- const dragged = sidebarDragSource();
- if (!dragged || lastHandledEvent === event.nativeEvent) return;
- const next = planSidebarDrop(
- dragged,
- zone,
- dropEdgeAt(event.currentTarget.getBoundingClientRect(), event.clientY),
- optionsRef.current.context(),
- );
- // No answer here lets the zone around it answer instead.
- if (!next) return;
- event.preventDefault();
- lastHandledEvent = event.nativeEvent;
- event.dataTransfer.dropEffect = "move";
- if (next === STAY) {
- // Already here: nothing to paint, and nothing for the outer zones to add.
- cancelSpring();
- showPlan(null);
+ if (!closed) {
+ if (spring.current?.key !== springKey) cancelSpring();
+ return;
+ }
+ if (spring.current?.key === springKey) return;
+ cancelSpring();
+ spring.current = {
+ key: springKey,
+ timer: window.setTimeout(() => {
+ spring.current = null;
+ optionsRef.current.onSpringOpen?.(zone);
+ }, SPRING_OPEN_DELAY_MS),
+ };
+ },
+ [aim, cancelSpring, showPlan],
+ );
+
+ const dragHandleProps = useCallback(
+ (item: SidebarDragItem) => ({
+ onPointerDown: (event: React.PointerEvent) => {
+ // Touch scrolls the list and keeps Move up and Move down. The right button opens the
+ // row menu, and a control with its own press keeps it.
+ if (event.button !== 0 || event.pointerType === "touch") return;
+ if (!event.isPrimary) return;
+ if ((event.target as Element | null)?.closest?.(NO_DRAG_SELECTOR)) {
+ return;
+ }
+ // Abandoned rather than refused: a release the window never saw would otherwise leave a
+ // gesture in flight for good and block every drag after it.
+ press.current?.end();
+
+ const startX = event.clientX;
+ const startY = event.clientY;
+ const row = event.currentTarget as HTMLElement;
+ const pointerId = event.pointerId;
+ const at = { x: startX, y: startY };
+ let started = false;
+ let frame = 0;
+
+ const detach = () => {
+ if (press.current === self) press.current = null;
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", onUp);
+ window.removeEventListener("pointercancel", onCancel);
+ window.removeEventListener("keydown", onKey, true);
+ // Captured on the body, which no re-render can unmount mid-gesture. A row can.
+ if (document.body.hasPointerCapture?.(pointerId)) {
+ document.body.releasePointerCapture(pointerId);
+ }
+ };
+ // Scrolling moves the rows, not the pointer, so the frame that scrolls re-aims too or
+ // the cue would sit on whichever row has slid out from under the pointer.
+ const onFrame = () => {
+ // Self-terminating, so an unmount mid-drag cannot leave the loop running.
+ if (!sidebarDragSource()) {
+ frame = 0;
return;
}
- showPlan(next);
- if (zoneOptions?.closed) {
- if (spring.current?.key !== springKey) {
- cancelSpring();
- spring.current = {
- key: springKey,
- timer: window.setTimeout(() => {
- spring.current = null;
- optionsRef.current.onSpringOpen?.(zone);
- }, SPRING_OPEN_DELAY_MS),
- };
+ frame = requestAnimationFrame(onFrame);
+ if (edgeScroll(at.y)) track(at.x, at.y);
+ };
+ // Abandons this gesture whole, for a drop that never came: the same as a cancel.
+ const self = {
+ end: () => {
+ detach();
+ if (started) clear();
+ },
+ };
+ press.current = self;
+
+ // Swallow the click the release would otherwise fire on the row it landed on.
+ const swallowClick = () => {
+ const stop = (clicked: MouseEvent) => {
+ clicked.preventDefault();
+ clicked.stopPropagation();
+ };
+ window.addEventListener("click", stop, { capture: true, once: true });
+ window.setTimeout(() => {
+ window.removeEventListener("click", stop, { capture: true });
+ }, 0);
+ };
+
+ // Every window handler answers only the pointer that started the gesture. A second
+ // pointer, a finger on a touch screen above all, is not this drag.
+ function onMove(moved: PointerEvent) {
+ if (moved.pointerId !== pointerId) return;
+ at.x = moved.clientX;
+ at.y = moved.clientY;
+ if (!started) {
+ if (
+ Math.abs(moved.clientX - startX) < DRAG_THRESHOLD_PX &&
+ Math.abs(moved.clientY - startY) < DRAG_THRESHOLD_PX
+ ) {
+ return;
+ }
+ started = true;
+ scroller.current = scrollerOf(row);
+ document.body.classList.add(DRAGGING_BODY_CLASS);
+ // Without capture a release outside the window never arrives and the row stays
+ // stuck. Capture retargets events only, so the hit test still finds the zone.
+ try {
+ document.body.setPointerCapture(pointerId);
+ } catch {
+ // No capture: window listeners still carry the drag inside the window.
}
- } else if (spring.current?.key !== springKey) {
- cancelSpring();
+ setSidebarDragSource(item);
+ setDrag(item);
+ frame = requestAnimationFrame(onFrame);
}
- },
- onDrop: (event: React.DragEvent) => {
+ // Held by the window, so the row keeps following the pointer outside the sidebar.
+ moved.preventDefault();
+ track(moved.clientX, moved.clientY);
+ }
+
+ function onUp(released: PointerEvent) {
+ if (released.pointerId !== pointerId) return;
+ detach();
+ if (!started) return;
+ swallowClick();
const dragged = sidebarDragSource();
- if (!dragged || lastHandledEvent === event.nativeEvent) return;
- const next = planSidebarDrop(
- dragged,
- zone,
- dropEdgeAt(event.currentTarget.getBoundingClientRect(), event.clientY),
- optionsRef.current.context(),
- );
- if (!next) return;
- event.preventDefault();
- lastHandledEvent = event.nativeEvent;
+ const aimed = aim(released.clientX, released.clientY);
clear();
- if (next !== STAY) optionsRef.current.onDrop(next, dragged);
- },
- };
- },
- [cancelSpring, clear, showPlan],
+ if (dragged && aimed && aimed.outcome !== STAY) {
+ optionsRef.current.onDrop(aimed.outcome, dragged);
+ }
+ }
+
+ function onCancel(cancelled: PointerEvent) {
+ if (cancelled.pointerId !== pointerId) return;
+ detach();
+ if (started) clear();
+ }
+
+ function onKey(pressed: KeyboardEvent) {
+ if (pressed.key !== "Escape") return;
+ detach();
+ if (!started) return;
+ pressed.preventDefault();
+ swallowClick();
+ clear();
+ }
+
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", onUp);
+ window.addEventListener("pointercancel", onCancel);
+ window.addEventListener("keydown", onKey, true);
+ },
+ }),
+ [aim, clear, edgeScroll, track],
+ );
+
+ const dropZoneProps = useCallback(
+ (zone: SidebarDropZone, zoneOptions?: { closed?: boolean }) => ({
+ [DROP_ZONE_ATTR]: JSON.stringify(
+ zoneOptions?.closed ? { zone, closed: true } : { zone },
+ ),
+ }),
+ [],
);
const lineEdge = useCallback(
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index bd59f6772ad..9d447b4539f 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -220,13 +220,6 @@ export const ar = {
moveUp: "تحريك لأعلى",
moveDown: "تحريك لأسفل",
},
- drag: {
- reorder: "إعادة ترتيب",
- pin: "تثبيت",
- unpin: "إلغاء التثبيت",
- moveTo: "نقل إلى {name}",
- moveToRecents: "نقل إلى الأخيرة",
- },
dialog: {
deleteChat: {
title: "حذف المحادثة",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index cb4eddd954a..13c35e9382e 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -223,13 +223,6 @@ export const de = {
moveUp: "Nach oben",
moveDown: "Nach unten",
},
- drag: {
- reorder: "Umordnen",
- pin: "Anheften",
- unpin: "Lösen",
- moveTo: "Verschieben nach {name}",
- moveToRecents: "Zu Zuletzt verschieben",
- },
dialog: {
deleteChat: {
title: "Chat löschen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index c07ff594ed0..80c8639701c 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -225,13 +225,6 @@ export const en = {
moveUp: "Move up",
moveDown: "Move down",
},
- drag: {
- reorder: "Reorder",
- pin: "Pin",
- unpin: "Unpin",
- moveTo: "Move to {name}",
- moveToRecents: "Move to Recents",
- },
dialog: {
deleteChat: {
title: "Delete chat",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 7636ec188b4..b7d50ce5590 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -222,13 +222,6 @@ export const es = {
moveUp: "Subir",
moveDown: "Bajar",
},
- drag: {
- reorder: "Reordenar",
- pin: "Fijar",
- unpin: "Desfijar",
- moveTo: "Mover a {name}",
- moveToRecents: "Mover a Recientes",
- },
dialog: {
deleteChat: {
title: "Eliminar chat",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index dfee6a2c7b8..afcce783380 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -223,13 +223,6 @@ export const fr = {
moveUp: "Monter",
moveDown: "Descendre",
},
- drag: {
- reorder: "Réordonner",
- pin: "Épingler",
- unpin: "Désépingler",
- moveTo: "Déplacer vers {name}",
- moveToRecents: "Déplacer vers Récents",
- },
dialog: {
deleteChat: {
title: "Supprimer la discussion",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 072a2c87cb0..6c040d96786 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -223,13 +223,6 @@ export const hi = {
moveUp: "ऊपर ले जाएँ",
moveDown: "नीचे ले जाएँ",
},
- drag: {
- reorder: "क्रम बदलें",
- pin: "पिन करें",
- unpin: "अनपिन करें",
- moveTo: "{name} में ले जाएँ",
- moveToRecents: "हाल के में ले जाएँ",
- },
dialog: {
deleteChat: {
title: "चैट हटाएँ",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 7fa806ff414..c2dc3532ba8 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -187,13 +187,6 @@ export const it = {
moveUp: "Sposta su",
moveDown: "Sposta giù",
},
- drag: {
- reorder: "Riordina",
- pin: "Fissa",
- unpin: "Sblocca",
- moveTo: "Sposta in {name}",
- moveToRecents: "Sposta in Recenti",
- },
dialog: {
deleteChat: {
title: "Elimina la chat",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 1eb6f396c44..c334ef4206b 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -222,13 +222,6 @@ export const ja = {
moveUp: "上へ移動",
moveDown: "下へ移動",
},
- drag: {
- reorder: "並べ替え",
- pin: "ピン留め",
- unpin: "ピン留めを解除",
- moveTo: "{name} に移動",
- moveToRecents: "最近に移動",
- },
dialog: {
deleteChat: {
title: "チャットの削除",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index b621a5bf453..57527b0fc5d 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -220,13 +220,6 @@ export const ko = {
moveUp: "위로 이동",
moveDown: "아래로 이동",
},
- drag: {
- reorder: "순서 변경",
- pin: "고정",
- unpin: "고정 해제",
- moveTo: "{name}(으)로 이동",
- moveToRecents: "최근으로 이동",
- },
dialog: {
deleteChat: {
title: "채팅 삭제",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 694bd263a9e..c9aa9a8a2ee 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -222,13 +222,6 @@ export const ptBR = {
moveUp: "Mover para cima",
moveDown: "Mover para baixo",
},
- drag: {
- reorder: "Reordenar",
- pin: "Fixar",
- unpin: "Desafixar",
- moveTo: "Mover para {name}",
- moveToRecents: "Mover para Recentes",
- },
dialog: {
deleteChat: {
title: "Excluir chat",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 96d9c4b3aa5..ac4ea4b4cc8 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -222,13 +222,6 @@ export const ru = {
moveUp: "Переместить вверх",
moveDown: "Переместить вниз",
},
- drag: {
- reorder: "Переставить",
- pin: "Закрепить",
- unpin: "Открепить",
- moveTo: "Переместить в {name}",
- moveToRecents: "Переместить в Недавние",
- },
dialog: {
deleteChat: {
title: "Удалить чат",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index c0608e866e4..48d55aa4709 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -218,13 +218,6 @@ export const zhCN = {
moveUp: "上移",
moveDown: "下移",
},
- drag: {
- reorder: "重新排序",
- pin: "固定",
- unpin: "取消固定",
- moveTo: "移动到 {name}",
- moveToRecents: "移动到最近",
- },
dialog: {
deleteChat: {
title: "删除聊天",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 4986436a074..c8e84401e7d 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -3341,6 +3341,15 @@ html[data-chat-font] .aui-root {
cursor: pointer;
}
+/* A sidebar row is being carried. The gesture is a pointer drag, not a native one, so the
+ selection it would otherwise sweep up and the cursor off the row are ours to hold. */
+body.sidebar-row-dragging,
+body.sidebar-row-dragging * {
+ -webkit-user-select: none;
+ user-select: none;
+ cursor: grabbing !important;
+}
+
/* Flat scrollbar chrome */
* {
scrollbar-width: thin;
diff --git a/studio/frontend/tests/sidebar-row-drag.test.ts b/studio/frontend/tests/sidebar-row-drag.test.ts
index 5009caec8c6..5787ad837e4 100644
--- a/studio/frontend/tests/sidebar-row-drag.test.ts
+++ b/studio/frontend/tests/sidebar-row-drag.test.ts
@@ -752,39 +752,47 @@ test("the dragged row is known before React re-renders", async () => {
assert.ok(!/const dragged = drag;/.test(HOOK));
});
-// dragleave fires for every child crossed, so one document listener clears the cue instead.
+// The desktop app's webview answers every OS drag itself and never forwards it to the page, so
+// `dragstart`, `dragover` and `drop` never fire there and a row wired to them is dead. The whole
+// gesture is pointer events, which both the browser and the desktop app deliver.
+test("the gesture is pointer events, not the HTML5 drag API", () => {
+ for (const source of [HOOK, APP_SIDEBAR]) {
+ assert.ok(!/\bdraggable\b\s*[:=]/.test(source));
+ assert.ok(!source.includes("onDragStart"));
+ assert.ok(!source.includes("onDragOver"));
+ assert.ok(!source.includes("onDragEnd"));
+ assert.ok(!source.includes("onDragLeave"));
+ assert.ok(!source.includes("dataTransfer"));
+ }
+ assert.match(HOOK, /onPointerDown: \(event: React\.PointerEvent\) => \{/);
+ assert.match(HOOK, /window\.addEventListener\("pointermove", onMove\);/);
+ assert.match(HOOK, /window\.addEventListener\("pointerup", onUp\);/);
+ // A press is only a drag once it travels, or a click on a row would never open the chat.
+ assert.match(HOOK, /export const DRAG_THRESHOLD_PX = \d+;/);
+ // Touch scrolls the list; its rows keep Move up and Move down.
+ assert.match(HOOK, /event\.pointerType === "touch"\) return;/);
+});
+
+// A zone is found by hit-testing the pointer, innermost first, so a row still answers before the
+// folder block and the section around it. Nothing under the pointer clears the cue outright,
+// which no `dragleave` has to be trusted for.
test("a cue over nothing is cleared without trusting dragleave", () => {
- assert.ok(!HOOK.includes("onDragLeave"));
- assert.ok(!APP_SIDEBAR.includes("onDragLeave"));
- assert.match(HOOK, /lastHandledEvent = event\.nativeEvent;/);
- assert.match(
- HOOK,
- /if \(lastHandledEvent !== event\) \{\n\s*cancelSpring\(\);\n\s*showPlan\(null\);/,
- );
- // No answer lets the outer zone answer; an answer marks the event rather than stopping it.
+ assert.match(HOOK, /for \(const element of document\.elementsFromPoint\(x, y\)\)/);
+ // No answer here lets the zone around it answer instead.
+ assert.match(HOOK, /if \(outcome\) return \{ hit, outcome \};\n\s*\}\n\s*return null;/);
assert.match(
HOOK,
- /if \(!next\) return;\n\s*event\.preventDefault\(\);\n\s*lastHandledEvent = event\.nativeEvent;/,
- );
- assert.ok(
- !HOOK.includes("event.stopPropagation();\n lastHandledEvent"),
- );
- assert.match(
- HOOK,
- /if \(!dragged \|\| lastHandledEvent === event\.nativeEvent\) return;/,
+ /if \(!aimed \|\| aimed\.outcome === STAY\) \{\n\s*\/\/[^\n]*\n\s*cancelSpring\(\);\n\s*showPlan\(null\);\n\s*return;\n\s*\}/,
);
});
-// Over its own row a lifted row is already home. The row claims the drag and paints nothing,
+// Over its own row a lifted row is already home: nothing is painted and the drop does nothing,
// so the section body never gets to offer its last slot for it.
test("a row over itself claims the drag and paints nothing", () => {
+ assert.match(HOOK, /showPlan\(aimed\.outcome\);/);
assert.match(
HOOK,
- /if \(next === STAY\) \{\n\s*\/\/[^\n]*\n\s*cancelSpring\(\);\n\s*showPlan\(null\);\n\s*return;\n\s*\}/,
- );
- assert.match(
- HOOK,
- /if \(next !== STAY\) optionsRef\.current\.onDrop\(next, dragged\);/,
+ /if \(dragged && aimed && aimed\.outcome !== STAY\) \{\n\s*optionsRef\.current\.onDrop\(aimed\.outcome, dragged\);/,
);
});
@@ -878,26 +886,15 @@ test("alt and an arrow reorder a row without a pointer", async () => {
);
});
-// The hint names every kind of drop.
-test("the hint beside the cursor names every kind of drop", () => {
- for (const key of ["reorder", "pin", "unpin", "moveTo", "moveToRecents"]) {
- assert.ok(EN.includes(`${key}:`), `${key} is missing from the en locale`);
- }
- for (const use of [
- 't("shell.drag.pin")',
- 't("shell.drag.unpin")',
- 't("shell.drag.reorder")',
- 't("shell.drag.moveToRecents")',
- 't("shell.drag.moveTo", { name })',
- ]) {
- assert.ok(APP_SIDEBAR.includes(use), `${use} is never rendered`);
- }
- // In a portal, so the sidebar cannot clip it.
- assert.match(
- APP_SIDEBAR,
- /draggingRow && typeof document !== "undefined"\n\s*\? createPortal\(/,
- );
- assert.ok(APP_SIDEBAR.includes('data-testid="sidebar-drop-hint"'));
+// The line on the landing edge and the ring around a folder already say where the row goes, so
+// no label rides along with the cursor saying it again.
+test("nothing follows the cursor while a row is carried", () => {
+ assert.ok(!APP_SIDEBAR.includes('data-testid="sidebar-drop-hint"'));
+ assert.ok(!APP_SIDEBAR.includes("createPortal"));
+ assert.ok(!APP_SIDEBAR.includes("shell.drag."));
+ assert.ok(!EN.includes("drag: {"));
+ // And the hook has no element to place: it paints the cue and nothing else.
+ assert.ok(!HOOK.includes("hintRef"));
});
// The gesture has one behaviour, not three switches: the hint shows, a reorder in a sorted list
@@ -927,7 +924,13 @@ test("a closed folder or section opens under a resting pointer", () => {
APP_SIDEBAR,
/if \(zone\.section === "pinned"\) setPinnedOpen\(true\);/,
);
- assert.match(HOOK, /if \(zoneOptions\?\.closed\) \{/);
+ // A zone carries `closed` in the DOM, and only a closed one arms the timer.
+ assert.match(HOOK, /const \{ zone, closed \} = aimed\.hit;/);
+ assert.match(
+ HOOK,
+ /if \(!closed\) \{\n\s*if \(spring\.current\?\.key !== springKey\) cancelSpring\(\);\n\s*return;\n\s*\}/,
+ );
+ assert.match(HOOK, /zoneOptions\?\.closed \? \{ zone, closed: true \} : \{ zone \}/);
});
// A chat dropped into a folder or Recents is moved, and the move can fail. Its slot in the new
@@ -971,3 +974,35 @@ test("a drop that moves writes its slot and takes the pin off after the move", (
/\): Promise<boolean> \{\n\s*if \(item\.projectId === projectId\) return true;/,
);
});
+
+// A pointer resting on the edge of a long list sends no more moves, so scrolling driven off
+// pointermove alone took one step and stalled. The frame loop keeps it going, and re-aims: the
+// rows slide under a pointer that has not moved, so the cue would otherwise stay on the row that
+// left.
+test("the edge keeps scrolling while the pointer rests on it", () => {
+ assert.match(HOOK, /const onFrame = \(\) => \{[^]*?frame = requestAnimationFrame\(onFrame\);\n\s*if \(edgeScroll\(at\.y\)\) track\(at\.x, at\.y\);/);
+ // Started with the drag and cancelled with it, and it stops itself if the drag is gone.
+ assert.match(HOOK, /setDrag\(item\);\n\s*frame = requestAnimationFrame\(onFrame\);/);
+ assert.match(HOOK, /if \(frame\) cancelAnimationFrame\(frame\);/);
+ assert.match(HOOK, /if \(!sidebarDragSource\(\)\) \{\n\s*frame = 0;\n\s*return;\n\s*\}/);
+ // track no longer scrolls: one driver, or a move and a frame would both step the list.
+ assert.ok(!/const track = useCallback\(\n\s*\(x: number, y: number\) => \{\n\s*(auto|edge)Scroll/.test(HOOK));
+});
+
+// The window hears every pointer, not just the one that pressed the row. Without this a finger
+// could drive, and drop, a drag the mouse started, which is exactly what touch is kept out of.
+test("only the pointer that started the drag drives it", () => {
+ for (const handler of [
+ /function onMove\(moved: PointerEvent\) \{\n\s*if \(moved\.pointerId !== pointerId\) return;/,
+ /function onUp\(released: PointerEvent\) \{\n\s*if \(released\.pointerId !== pointerId\) return;/,
+ /function onCancel\(cancelled: PointerEvent\) \{\n\s*if \(cancelled\.pointerId !== pointerId\) return;/,
+ ]) {
+ assert.match(HOOK, handler);
+ }
+ assert.match(HOOK, /if \(!event\.isPrimary\) return;/);
+ // One gesture at a time, and a stale one is abandoned rather than left to block every later
+ // drag: a release the window never saw would strand it otherwise.
+ assert.match(HOOK, /press\.current\?\.end\(\);/);
+ assert.match(HOOK, /end: \(\) => \{\n\s*detach\(\);\n\s*if \(started\) clear\(\);/);
+ assert.match(HOOK, /if \(press\.current === self\) press\.current = null;/);
+});