Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

extract drag-to-pan gesture into useDragToPan and fix ModelComparison chart guards (#7577)

[._.]/ Adam Eivyd2bd61649abe
diff --git a/client/src/components/fableloom/LoomCanvas.jsx b/client/src/components/fableloom/LoomCanvas.jsx
index be7024892d..afee8f1fdf 100644
--- a/client/src/components/fableloom/LoomCanvas.jsx
+++ b/client/src/components/fableloom/LoomCanvas.jsx
@@ -22,6 +22,7 @@
import { useEffect, useId, useMemo, useRef } from 'react';
import { Flag, Play } from 'lucide-react';
import useContainerWidth from '../../hooks/useContainerWidth';
+import useDragToPan from '../../hooks/useDragToPan';
import { isTapGesture } from '../../lib/graphPicking';
import {
layoutLoomGraph, LOOM_EDGE_LABEL_MAX, LOOM_ORIENTATION,
@@ -64,12 +65,19 @@ export default function LoomCanvas({
// once on release. Routing it through setState re-rendered every node card
// (each with a foreignObject media surface) ~60×/s. Edges catch up on release.
const dragRef = useRef(null);
- // A pan is the same story one level up: scrollLeft/scrollTop are mutated
- // directly per pointermove so no node re-renders while the view moves.
- const panRef = useRef(null);
// Set by whichever gesture actually moved, read once by the surface's
// click-capture handler — one mechanism for "this click was a drag".
const draggedRef = useRef(false);
+ // A pan is the same story one level up: scrollLeft/scrollTop are mutated
+ // directly per pointermove so no node re-renders while the view moves. A
+ // card's own drag wins when both could claim the gesture (`canStart`), and
+ // a completed pan folds into `draggedRef` so the shared click-capture below
+ // swallows it exactly like a card drag does.
+ const pan = useDragToPan({
+ slop: DRAG_THRESHOLD_PX,
+ canStart: () => !dragRef.current,
+ onPanEnd: () => { draggedRef.current = true; },
+ });
const cardRefs = useRef(new Map());
const mediaRefs = useRef(new Map());
const [measureRef, measuredWidth] = useContainerWidth();
@@ -137,37 +145,11 @@ export default function LoomCanvas({
const handleSurfacePointerDown = (event) => {
// Cleared at the START of every gesture: a drag released outside the canvas
// (or cancelled) never gets its click, and a stale flag would then swallow
- // the next genuine select.
+ // the next genuine select. `canStart` (above) already answers "did a scene
+ // card claim this drag?" by asking `dragRef` — on the stacked layout cards
+ // never claim a drag, so a card is pannable surface there.
draggedRef.current = false;
- if (event.pointerType !== 'mouse' || event.button !== 0) return;
- // This runs after the card's own pointerdown, so `dragRef` already answers
- // "did a scene card claim this drag?" — ask it rather than re-deriving the
- // card handler's eligibility rules from the event target. On the stacked
- // layout cards never claim a drag, so a card is pannable surface there.
- if (dragRef.current) return;
- const surface = event.currentTarget;
- surface.setPointerCapture?.(event.pointerId);
- panRef.current = {
- start: { x: event.clientX, y: event.clientY },
- scrollLeft: surface.scrollLeft,
- scrollTop: surface.scrollTop,
- moved: false,
- };
- };
-
- const handleSurfacePointerMove = (event) => {
- const pan = panRef.current;
- const delta = pan && gestureDelta(pan, event);
- if (!delta) return;
- const surface = event.currentTarget;
- surface.scrollLeft = pan.scrollLeft - delta.dx;
- surface.scrollTop = pan.scrollTop - delta.dy;
- };
-
- const handleSurfacePointerUp = () => {
- const pan = panRef.current;
- panRef.current = null;
- if (pan?.moved) draggedRef.current = true;
+ pan.panProps.onPointerDown(event);
};
// Either drag still fires a click when it ends — on the card, on an edge, or
@@ -192,14 +174,14 @@ export default function LoomCanvas({
return (
<div className="relative h-full w-full">
<div
- ref={measureRef}
+ ref={(el) => { measureRef.current = el; pan.surfaceRef.current = el; }}
className={`overflow-auto h-full w-full overscroll-contain cursor-grab active:cursor-grabbing ${showStrip ? 'pb-28' : ''}`}
data-testid="loom-canvas"
data-orientation={orientation}
onPointerDown={handleSurfacePointerDown}
- onPointerMove={handleSurfacePointerMove}
- onPointerUp={handleSurfacePointerUp}
- onPointerCancel={handleSurfacePointerUp}
+ onPointerMove={pan.panProps.onPointerMove}
+ onPointerUp={pan.panProps.onPointerUp}
+ onPointerCancel={pan.panProps.onPointerCancel}
onClickCapture={handleSurfaceClickCapture}
>
<svg
diff --git a/client/src/components/models/ModelComparison.jsx b/client/src/components/models/ModelComparison.jsx
index 6af2ad7863..93f0041a66 100644
--- a/client/src/components/models/ModelComparison.jsx
+++ b/client/src/components/models/ModelComparison.jsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, useSearchParams } from 'react-router';
import {
ArrowUpRight,
@@ -30,10 +30,12 @@ import {
discoverComparisonModels,
syncBenchmarkSource,
} from '../../services/apiModelComparison';
+import useDragToPan from '../../hooks/useDragToPan';
import Modal from '../ui/Modal';
import toast from '../ui/Toast';
import ComparisonResearch from './ComparisonResearch';
import { EFFORT_LADDER, withEstimatedCosts } from '../../lib/effortCostEstimate';
+import { TAP_SLOP_PX } from '../../lib/graphPicking';
import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';
const SETTINGS_STORAGE_KEY = 'portos-model-comparison-settings';
@@ -150,10 +152,16 @@ export default function ModelComparison() {
const [inputYMax, setInputYMax] = useState(yMaxParam ?? '');
const [showAxisInputs, setShowAxisInputs] = useState(false);
- const scrollContainerRef = useRef(null);
- const [isDragging, setIsDragging] = useState(false);
- const [startX, setStartX] = useState(0);
- const [scrollLeft, setScrollLeft] = useState(0);
+ // x-only: the stretched chart only ever overflows horizontally. Opts out on
+ // an interactive child so a click on a real control still reaches it. Must
+ // sit above the `!catalog` early return below with every other hook.
+ const stretch = Math.min(4, Math.max(1, parseFloat(params.get('stretch')) || 1));
+ const pan = useDragToPan({
+ enabled: stretch > 1,
+ axis: 'x',
+ slop: TAP_SLOP_PX,
+ canStart: e => !e.target.closest('button, input, select, a, [role="button"]'),
+ });
useEffect(() => {
setInputXMin(xMinParam ?? '');
@@ -381,30 +389,8 @@ export default function ModelComparison() {
// stacks every affordable model on the y-axis. Log is the readable default.
const scale = params.get('scale') === 'log' || (!params.has('scale') && xAxis === 'cost') ? 'log' : 'linear';
const showAllModels = params.get('allModels') === '1' || availableSet.size === 0;
- const stretch = Math.min(4, Math.max(1, parseFloat(params.get('stretch')) || 1));
const chartHeight = Math.min(1000, Math.max(380, parseInt(params.get('height'), 10) || 480));
-
- const handleMouseDown = e => {
- if (stretch <= 1 || !scrollContainerRef.current) return;
- if (e.target.closest('button, input, select, a, [role="button"]')) return;
- setIsDragging(true);
- setStartX(e.pageX - scrollContainerRef.current.offsetLeft);
- setScrollLeft(scrollContainerRef.current.scrollLeft);
- };
-
- const handleMouseMove = e => {
- if (!isDragging || !scrollContainerRef.current) return;
- e.preventDefault();
- const x = e.pageX - scrollContainerRef.current.offsetLeft;
- const walk = x - startX;
- scrollContainerRef.current.scrollLeft = scrollLeft - walk;
- };
-
- const handleMouseUp = () => {
- setIsDragging(false);
- };
-
// Scope once, then derive every list from the scoped rows — so the provider
// and effort pills can't offer values that have nothing left to plot.
const scoped = showAllModels ? estimatedRows : estimatedRows.filter(row => availableSet.has(row.model));
@@ -1271,14 +1257,15 @@ export default function ModelComparison() {
</div>
)}
<div
- ref={scrollContainerRef}
- onMouseDown={handleMouseDown}
- onMouseMove={handleMouseMove}
- onMouseUp={handleMouseUp}
- onMouseLeave={handleMouseUp}
+ ref={pan.surfaceRef}
+ onPointerDown={pan.panProps.onPointerDown}
+ onPointerMove={pan.panProps.onPointerMove}
+ onPointerUp={pan.panProps.onPointerUp}
+ onPointerCancel={pan.panProps.onPointerCancel}
+ onClickCapture={pan.panProps.onClickCapture}
style={{ height: `${chartHeight}px` }}
className={`overflow-x-auto px-1 sm:px-4 pt-4 scrollbar-thin ${
- stretch > 1 ? (isDragging ? 'cursor-grabbing select-none' : 'cursor-grab') : ''
+ stretch > 1 ? (pan.isPanning ? 'cursor-grabbing select-none' : 'cursor-grab') : ''
}`}
role="img"
aria-label={`${AXES[yAxis].label} versus ${AXES[xAxis].label}. Exact values and source links are in the table below.`}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index e4b390bd32..3d590368d2 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -113,6 +113,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useCmdKSearch` | `⌘K` open/close state. | Anywhere that needs to toggle the palette. |
| `useContainerWidth` | `[ref, width]` via ResizeObserver. | Layout responds to a specific container's width. |
| `useCooldownTick` | 1-second ticker over a `{ id: epochMs }` cooldown map; fires `onAllExpired` once when every deadline passes. | Rate-limit countdown labels that need to refetch when the last cooldown clears (agents tabs pattern). |
+| `useDragToPan` | Shared drag-to-pan gesture: mouse-only pointer drag scrolls a surface by writing `scrollLeft`/`scrollTop` directly, past a per-caller `slop` threshold, with built-in click suppression so ending a drag over a control doesn't activate it. `canStart(event)` opts a gesture out (an interactive child, or another gesture that already claimed the pointerdown); `onPanEnd(moved)` lets a caller with more than one drag source (a card's own drag) fold this into its own combined click-suppression ref. Returns `{ surfaceRef, panProps, panned, isPanning }`. | Any pannable overflow surface bigger than its pane (FableLoom's scene graph, a stretched chart) — don't re-roll the scrollLeft/scrollTop drag math. |
| `useDrawerTab` | Deep-linkable `[activeTab, setActiveTab]` for a tabbed `<Drawer>`, backed by a caller-named URL search param (falls back to a default on stale/missing). | A tabbed config drawer whose open section should be shareable/bookmarkable — use with `<Drawer tabs>`; don't re-roll the search-param plumbing. |
| `useLocalLlmStatus` | `{ status, loading, selected, setSelected, loadStatus, runAction, installBackend, actionInProgress, busy, progressMsg, setProgressMsg, confirmAction, setConfirmAction }` — the installed-model status both local-LLM views read, the single `localLlm:progress` subscription, and the one busy/toast/refresh path every action routes through. Takes stable `onRefresh` (extra loads on a status refresh) and `onReload` (extra reload after an action or `complete` frame) callbacks. | `LocalLlmRuntimesView` / `LocalLlmLibraryView` — they never mount together, so the mounted one is the only subscriber. |
| `useDownloadPreflightConfirm` | `{ confirm, request({ title, preview, run }), cancel, confirmRun }` — shows a loading modal, resolves a disk-preflight assessment, and holds `run` until confirmed. | Any weight/LoRA download confirm step — pair with `<DownloadPreflightConfirm>`. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 074cfa998d..5da42249dd 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -22,6 +22,7 @@ export { default as useClickOutside } from './useClickOutside.js';
export { default as useConfirmDelete } from './useConfirmDelete.js';
export { default as useColorMatch } from './useColorMatch.js';
export { default as useContainerWidth } from './useContainerWidth.js';
+export { default as useDragToPan } from './useDragToPan.js';
export { default as useEscapeKey } from './useEscapeKey.js';
export { default as useFieldDraft } from './useFieldDraft.js';
export { default as useFableLoomAiRun } from './useFableLoomAiRun.js';
diff --git a/client/src/hooks/useDragToPan.js b/client/src/hooks/useDragToPan.js
new file mode 100644
index 0000000000..3dc6b3ff8a
--- /dev/null
+++ b/client/src/hooks/useDragToPan.js
@@ -0,0 +1,87 @@
+import { useCallback, useRef, useState } from 'react';
+import { isTapGesture } from '../lib/graphPicking';
+
+/**
+ * Shared drag-to-pan gesture: a mouse-only pointer drag scrolls a surface by
+ * writing `scrollLeft`/`scrollTop` directly (the pane's own scroll position
+ * IS the viewport, so no transform or `scrollIntoView` cost). A drag under
+ * `slop` px reads as a tap/click and never touches scroll; a drag past it
+ * pans, and the pan swallows the click that would otherwise fire on release
+ * (`panProps.onClickCapture`) so ending over a button doesn't activate it.
+ *
+ * `canStart(event)` lets a caller opt a gesture out before it's claimed — an
+ * interactive child (ModelComparison's `closest('button, input, …')`) or
+ * another gesture that already owns this pointerdown (LoomCanvas asks its own
+ * node-drag `dragRef`). `onPanEnd(moved)` lets a caller fold this gesture's
+ * "did it drag" signal into its own combined click-suppression ref when it
+ * has more than one drag source landing on the same surface.
+ */
+export default function useDragToPan({
+ enabled = true,
+ axis = 'both',
+ slop,
+ canStart,
+ onPanEnd,
+} = {}) {
+ const surfaceRef = useRef(null);
+ const gestureRef = useRef(null);
+ const pannedRef = useRef(false);
+ const [isPanning, setIsPanning] = useState(false);
+
+ const onPointerDown = useCallback((event) => {
+ if (!enabled || event.pointerType !== 'mouse' || event.button !== 0) return;
+ if (canStart && !canStart(event)) return;
+ const surface = surfaceRef.current;
+ if (!surface) return;
+ surface.setPointerCapture?.(event.pointerId);
+ gestureRef.current = {
+ start: { x: event.clientX, y: event.clientY },
+ scrollLeft: surface.scrollLeft,
+ scrollTop: surface.scrollTop,
+ moved: false,
+ };
+ }, [enabled, canStart]);
+
+ const onPointerMove = useCallback((event) => {
+ const gesture = gestureRef.current;
+ if (!gesture) return;
+ const point = { x: event.clientX, y: event.clientY };
+ if (!gesture.moved) {
+ if (isTapGesture(gesture.start, point, slop)) return;
+ gesture.moved = true;
+ setIsPanning(true);
+ }
+ const surface = surfaceRef.current;
+ if (!surface) return;
+ if (axis !== 'y') surface.scrollLeft = gesture.scrollLeft - (point.x - gesture.start.x);
+ if (axis !== 'x') surface.scrollTop = gesture.scrollTop - (point.y - gesture.start.y);
+ }, [axis, slop]);
+
+ const endPan = useCallback(() => {
+ const gesture = gestureRef.current;
+ gestureRef.current = null;
+ if (!gesture?.moved) return;
+ pannedRef.current = true;
+ setIsPanning(false);
+ onPanEnd?.(true);
+ }, [onPanEnd]);
+
+ const onClickCapture = useCallback((event) => {
+ if (!pannedRef.current) return;
+ pannedRef.current = false;
+ event.stopPropagation();
+ }, []);
+
+ return {
+ surfaceRef,
+ panProps: {
+ onPointerDown,
+ onPointerMove,
+ onPointerUp: endPan,
+ onPointerCancel: endPan,
+ onClickCapture,
+ },
+ panned: pannedRef,
+ isPanning,
+ };
+}
diff --git a/client/src/hooks/useDragToPan.test.jsx b/client/src/hooks/useDragToPan.test.jsx
new file mode 100644
index 0000000000..e941f64877
--- /dev/null
+++ b/client/src/hooks/useDragToPan.test.jsx
@@ -0,0 +1,90 @@
+import { expect, it, vi } from 'vitest';
+import { fireEvent, render, screen } from '@testing-library/react';
+import useDragToPan from './useDragToPan';
+
+function Harness(props) {
+ const pan = useDragToPan(props);
+ return (
+ <div
+ ref={pan.surfaceRef}
+ data-testid="surface"
+ data-panning={pan.isPanning ? 'true' : 'false'}
+ {...pan.panProps}
+ >
+ <button type="button" onClick={props.onButtonClick}>Control</button>
+ </div>
+ );
+}
+
+it('pans past the slop threshold and leaves a tap alone', () => {
+ const onClick = vi.fn();
+ render(<Harness slop={4} onButtonClick={onClick} />);
+ const surface = screen.getByTestId('surface');
+ surface.scrollLeft = 100;
+ surface.scrollTop = 50;
+
+ // Under the slop threshold: no scroll change, and the click still fires.
+ fireEvent.pointerDown(surface, { pointerId: 1, pointerType: 'mouse', button: 0, clientX: 200, clientY: 200 });
+ fireEvent.pointerMove(surface, { pointerId: 1, pointerType: 'mouse', clientX: 202, clientY: 201 });
+ fireEvent.pointerUp(surface, { pointerId: 1, pointerType: 'mouse' });
+ fireEvent.click(surface);
+ expect(surface.scrollLeft).toBe(100);
+ expect(surface.scrollTop).toBe(50);
+
+ // Past the slop threshold: pans, and the ending click is swallowed.
+ fireEvent.pointerDown(surface, { pointerId: 2, pointerType: 'mouse', button: 0, clientX: 200, clientY: 200 });
+ fireEvent.pointerMove(surface, { pointerId: 2, pointerType: 'mouse', clientX: 150, clientY: 170 });
+ fireEvent.pointerUp(surface, { pointerId: 2, pointerType: 'mouse' });
+ fireEvent.click(screen.getByRole('button', { name: 'Control' }));
+ expect(surface.scrollLeft).toBe(150);
+ expect(surface.scrollTop).toBe(80);
+ expect(onClick).not.toHaveBeenCalled();
+});
+
+it('locks panning to one axis when asked', () => {
+ render(<Harness slop={4} axis="x" onButtonClick={vi.fn()} />);
+ const surface = screen.getByTestId('surface');
+ surface.scrollLeft = 0;
+ surface.scrollTop = 0;
+
+ fireEvent.pointerDown(surface, { pointerId: 1, pointerType: 'mouse', button: 0, clientX: 200, clientY: 200 });
+ fireEvent.pointerMove(surface, { pointerId: 1, pointerType: 'mouse', clientX: 140, clientY: 260 });
+ fireEvent.pointerUp(surface, { pointerId: 1, pointerType: 'mouse' });
+
+ expect(surface.scrollLeft).toBe(60);
+ expect(surface.scrollTop).toBe(0);
+});
+
+it('never claims a gesture canStart rejects, so its click still reaches the control', () => {
+ const onClick = vi.fn();
+ render(
+ <Harness
+ slop={4}
+ onButtonClick={onClick}
+ canStart={e => !e.target.closest('button')}
+ />,
+ );
+ const surface = screen.getByTestId('surface');
+ const button = screen.getByRole('button', { name: 'Control' });
+ surface.scrollLeft = 0;
+
+ fireEvent.pointerDown(button, { pointerId: 1, pointerType: 'mouse', button: 0, clientX: 200, clientY: 200 });
+ fireEvent.pointerMove(surface, { pointerId: 1, pointerType: 'mouse', clientX: 140, clientY: 200 });
+ fireEvent.pointerUp(surface, { pointerId: 1, pointerType: 'mouse' });
+ fireEvent.click(button);
+
+ expect(surface.scrollLeft).toBe(0);
+ expect(onClick).toHaveBeenCalledTimes(1);
+});
+
+it('ignores non-mouse pointers so touch scrolling is left to the browser', () => {
+ render(<Harness slop={4} onButtonClick={vi.fn()} />);
+ const surface = screen.getByTestId('surface');
+ surface.scrollLeft = 0;
+
+ fireEvent.pointerDown(surface, { pointerId: 1, pointerType: 'touch', clientX: 200, clientY: 200 });
+ fireEvent.pointerMove(surface, { pointerId: 1, pointerType: 'touch', clientX: 100, clientY: 200 });
+ fireEvent.pointerUp(surface, { pointerId: 1, pointerType: 'touch' });
+
+ expect(surface.scrollLeft).toBe(0);
+});