Files
AgentHub/client/src/components/Sagi/useSagiPosition.ts
T
nntrivi2001 6715fbd971 feat(settings): data-safe editors, deep-linked search, Data/About/Cost pages
- EditorModal loads once per path (a parent re-render no longer reloads the
  file over the user's typing), refuses Save after a failed load, opens a
  truncated (>256 KB) file read-only, and asks before overwriting a file
  that changed on disk or could not be re-read.
- Settings/Hooks editors unset only keys from the snapshot taken at Edit,
  warn when the file changed underneath, keep a renamed key's value, and
  refuse a new key named like a redacted one (env) or a read-only hook
  event, which used to replace the secret/hooks.
- Project scope shows its resolved folder and is disabled inside the
  plugin cache. Account-profile, pricing-row and pet deletes confirm;
  two-click actions disarm after 3 s; unsaved drafts ask before closing.
- Search indexes every Claude Code / Codex sub-tab, opens it via ?tab= and
  scrolls to + highlights the row; the active config tab is in the URL.
- General splits into General / Data / About; Pricing moves to a Cost
  group with one shared load; config tabs group as Content / Extensions /
  Config with arrow-key roving; Promise.allSettled per tab.
- Data: browser-preferences export/import (allowlisted keys), per-section
  reset, housekeeping dry-run first, clear-all behind a typed phrase.
  Server: purge days must be a whole number >= 1 (INVALID_PURGE_DAYS) and
  dry_run returns exactly what the real run would delete.
- Alerts can be edited; webhooks/alerts/remote-source failures toast;
  copies go through copyText; modals get dialog roles and useDialog.
- Sagi: Ctrl/Cmd+B only when shown and not typing, default spot clear of
  row controls, arrow keys move it, reduced motion honoured; the dead
  /run launch link goes to the workspace.
2026-10-05 13:22:08 +07:00

243 lines
10 KiB
TypeScript

/**
* @file useSagiPosition.ts
* @description AssistiveTouch-style draggable docking for the Sagi avatar. The
* avatar follows the pointer 1:1 while dragging (via Pointer Capture, so it
* keeps tracking even if the cursor outruns it), and on release snaps to the
* nearest left/right edge, remembering its vertical offset (persisted as a
* viewport fraction so it survives resizes). A small movement threshold tells
* a drag apart from a tap so dragging never opens the panel. The arrow keys
* move a focused avatar too (WCAG 2.5.7): ←/→ dock it to an edge, ↑/↓ step it.
* It never rests over the fixed bottom status bar; by default it docks
* bottom-right just above it.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Sagi is the optional on-screen mascot assistant — quips, intents, and lightweight event reactions layered above the dashboard chrome. React hook: isolates side effects and subscription wiring so presentational components stay declarative.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Internal dependencies
* - `./prefs`
*
* ## Public surface
* - `SAGI_SIZE` — exported API; see TSDoc on the symbol for behavior.
* - `SAGI_MARGIN` — exported API; see TSDoc on the symbol for behavior.
* - `SagiPlacement` — exported API; see TSDoc on the symbol for behavior.
* - `useSagiPosition` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **SAGI_SIZE**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* **SAGI_MARGIN**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* **SagiPlacement**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* **useSagiPosition**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { useCallback, useEffect, useRef, useState } from "react";
import { sagiPrefs, type SagiPos } from "./prefs";
import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from "react";
// Avatar footprint + edge gap, in px. SIZE matches SagiAvatar's default size.
export const SAGI_SIZE = 68;
export const SAGI_MARGIN = 16;
const DRAG_THRESHOLD = 5;
// The fixed bottom StatusBar (`h-6`); the avatar never rests over it.
const STATUS_BAR = 24;
// One arrow-key step, in px.
const KEY_STEP = 40;
const vw = () => (typeof window !== "undefined" ? window.innerWidth : 1024);
const vh = () => (typeof window !== "undefined" ? window.innerHeight : 768);
function defaultPos(): SagiPos {
// Bottom-right, above the status bar: a centred dock covered row controls.
return { side: "right", y: 1 };
}
/** Resting top-left screen coords for a docked position. */
function restingScreen(pos: SagiPos, size: number) {
const avail = Math.max(0, vh() - size - 2 * SAGI_MARGIN - STATUS_BAR);
const left = pos.side === "left" ? SAGI_MARGIN : vw() - size - SAGI_MARGIN;
const top = SAGI_MARGIN + pos.y * avail;
return { left, top };
}
export interface SagiPlacement {
/** Avatar top-left, in screen px. */
left: number;
top: number;
size: number;
side: "left" | "right";
/** True when the avatar sits in the lower half - flyouts open upward. */
openUp: boolean;
dragging: boolean;
onPointerDown: (e: ReactPointerEvent) => void;
onPointerMove: (e: ReactPointerEvent) => void;
onPointerUp: (e: ReactPointerEvent) => void;
/** Returns true (once) if a drag just ended, so the click handler can skip. */
consumeDrag: () => boolean;
/** Arrow keys on the focused avatar: ←/→ dock to an edge, ↑/↓ step. */
onKeyDown: (e: ReactKeyboardEvent) => void;
}
/** `size`: the avatar's current footprint (the pet size pref), in px. */
export function useSagiPosition(size: number = SAGI_SIZE): SagiPlacement {
const [pos, setPos] = useState<SagiPos>(() => sagiPrefs.getPos() ?? defaultPos());
const [drag, setDrag] = useState<{ left: number; top: number } | null>(null);
const [, force] = useState(0); // re-derive resting coords on resize
const draggedRef = useRef(false);
const startRef = useRef<{ px: number; py: number; left: number; top: number } | null>(null);
const movedRef = useRef(false);
// Latest dragged coords, mirrored in a ref so pointerup can read them
// synchronously - the setDrag state may not have committed yet under React's
// event batching, so we never rely on its functional-updater `cur`.
const liveRef = useRef<{ left: number; top: number } | null>(null);
useEffect(() => {
const onResize = () => force((n) => n + 1);
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
const resting = restingScreen(pos, size);
const screen = drag ?? resting;
const onPointerDown = useCallback(
(e: ReactPointerEvent) => {
if (e.button !== undefined && e.button !== 0) return;
// Capture so the avatar keeps receiving move/up events even when the
// pointer leaves it - essential for a fast, 1:1 drag.
try {
(e.currentTarget as Element).setPointerCapture?.(e.pointerId);
} catch {
/* capture unsupported - window-free fallback still works via props */
}
startRef.current = { px: e.clientX, py: e.clientY, left: screen.left, top: screen.top };
movedRef.current = false;
},
[screen.left, screen.top]
);
const onPointerMove = useCallback(
(e: ReactPointerEvent) => {
const start = startRef.current;
if (!start) return;
const dx = e.clientX - start.px;
const dy = e.clientY - start.py;
if (!movedRef.current && Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
movedRef.current = true;
const left = Math.min(vw() - size - SAGI_MARGIN, Math.max(SAGI_MARGIN, start.left + dx));
const top = Math.min(
vh() - size - SAGI_MARGIN - STATUS_BAR,
Math.max(SAGI_MARGIN, start.top + dy)
);
liveRef.current = { left, top };
setDrag({ left, top });
},
[size]
);
const onPointerUp = useCallback(
(e: ReactPointerEvent) => {
try {
(e.currentTarget as Element).releasePointerCapture?.(e.pointerId);
} catch {
/* ignore */
}
const live = liveRef.current;
if (live) {
draggedRef.current = true;
const side: "left" | "right" = live.left + size / 2 < vw() / 2 ? "left" : "right";
const avail = Math.max(1, vh() - size - 2 * SAGI_MARGIN - STATUS_BAR);
const y = Math.min(1, Math.max(0, (live.top - SAGI_MARGIN) / avail));
const next: SagiPos = { side, y };
sagiPrefs.setPos(next);
setPos(next);
setDrag(null); // leave drag mode; resting coords (with transition) take over
}
liveRef.current = null;
startRef.current = null;
movedRef.current = false;
},
[size]
);
const onKeyDown = useCallback(
(e: ReactKeyboardEvent) => {
if (e.altKey || e.ctrlKey || e.metaKey) return;
const avail = Math.max(1, vh() - size - 2 * SAGI_MARGIN - STATUS_BAR);
let next: SagiPos | null = null;
if (e.key === "ArrowLeft") next = { ...pos, side: "left" };
else if (e.key === "ArrowRight") next = { ...pos, side: "right" };
else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
const dy = (e.key === "ArrowUp" ? -KEY_STEP : KEY_STEP) / avail;
next = { ...pos, y: Math.min(1, Math.max(0, pos.y + dy)) };
}
if (!next) return;
e.preventDefault();
sagiPrefs.setPos(next);
setPos(next);
},
[pos, size]
);
const consumeDrag = useCallback(() => {
const was = draggedRef.current;
draggedRef.current = false;
return was;
}, []);
return {
left: screen.left,
top: screen.top,
size,
side: pos.side,
openUp: screen.top + size / 2 > vh() / 2,
dragging: drag !== null,
onPointerDown,
onPointerMove,
onPointerUp,
consumeDrag,
onKeyDown,
};
}