Files
archie/ui/src/chat/dock-window.ts
T
sam eb7d852567 refactor(ui/chat): remove chat features the server never sends
The dashboard talks only to the modules/chat API, which sends no slash
commands, model list, voice support, attachments or any question other
than an approval, so the UI built on those could never appear:

- the slash command menu, Retry, Undo, Branch and Preview compression in
  the More menu, and the /model, /update and /new handling
- the model picker, the update card and the api.update* calls
- voice recording and the task tags nothing ever added
- the questionnaire, picker and clarify cards, and the "Always this
  session" answer, so components/ui/questionnaire loses its last user
- channel.ts, command-scroll.ts and turn.ts, which nothing imported
- the old dock-storage migration and the second capitalised spelling of
  message and tool fields

Tasks are gone from the binary too, so chat links and prompts speak of
runs: the #N task-link step in the markdown renderer goes, since an agent
already links pages through dashboard_navigate.

state.ts keeps the shared state and actions; types.ts, stream.ts,
transcript.ts, escape.ts and dock-window.ts hold the types, the stream
reader, turn-to-message building, Escape layers and the dock's pointer
and keyboard handling. ChatDock.vue drops from 560 lines to 307.
2026-11-26 01:59:26 +11:00

314 lines
12 KiB
TypeScript

import {
useDraggable,
useEventListener,
useMediaQuery,
usePointerSwipe,
useResizeObserver,
useStorage,
useWindowSize,
} from "@vueuse/core";
import { computed, nextTick, onUnmounted, ref, watch, type Ref } from "vue";
import {
DOCK_STORAGE_KEY,
DRAG_START,
INSET,
MAX_W,
SWIPE,
barPlacement,
fitRect,
keyboardCover,
keyStep,
normalizeLayout,
phoneBarBottom,
pinnedWidth,
resizeRect,
snapEdge,
type DockLayout,
type DockMode,
type Rect,
type ResizeDir,
} from "./ChatDockLayout";
interface DockElements {
/** The dock itself: the target of every drag and resize. */
dock: Ref<HTMLElement | null>;
/** The conversation header, which drags the expanded window. */
header: Ref<HTMLElement | null>;
/** The composer bar, which drags the collapsed dock. */
bar: Ref<HTMLElement | null>;
}
const NOT_A_DRAG_SURFACE =
'button, a, input, select, textarea, [role="combobox"], [role="separator"], [role="textbox"], [contenteditable="true"], [contenteditable=""]';
/** The horizontal and vertical step an arrow key asks for. */
function arrowDelta(event: KeyboardEvent): { dx: number; dy: number } {
const step = keyStep(event.shiftKey);
return {
dx: event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0,
dy: event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0,
};
}
/**
* The chat dock's window behaviour. On a desktop-width screen the dock floats
* or pins to a side: pointer drags move it, eight handles resize it, arrow keys
* do both, and dragging near a side edge offers the pinned split. On a phone
* it is a full-width bottom bar that rides above the on-screen keyboard and
* hides when its header is swiped down. The layout is stored per browser, and
* the page reads the dock's footprint from CSS variables on the root element.
*/
export function useDockWindow({ dock, header, bar }: DockElements, expanded: Ref<boolean>) {
const stored = useStorage<DockLayout>(
DOCK_STORAGE_KEY,
normalizeLayout(null, window.innerWidth, window.innerHeight),
localStorage,
);
const desktop = useMediaQuery("(min-width: 768px)");
const { width: vw, height: vh } = useWindowSize();
const layout = computed<DockLayout>({
get: () => normalizeLayout(stored.value, vw.value, vh.value),
set: (value) => {
stored.value = value;
},
});
const mode = computed<DockMode>(() => (desktop.value ? layout.value.mode : "float"));
const pinned = computed(() => desktop.value && expanded.value && mode.value !== "float");
const pinW = computed(() => pinnedWidth(layout.value.w, vw.value));
const pinMax = computed(() => pinnedWidth(MAX_W, vw.value));
function floatAt(rect: Rect): void {
layout.value = { ...layout.value, mode: "float", x: rect.x, y: rect.y, w: rect.w, h: rect.h };
}
// The rendered rectangle: full height at an edge when pinned, the clamped
// stored rectangle when floating.
const winRect = computed<Rect>(() => {
if (!desktop.value) return { x: 0, y: 0, w: vw.value, h: vh.value };
if (pinned.value) {
return { x: mode.value === "left" ? 0 : vw.value - pinW.value, y: 0, w: pinW.value, h: vh.value };
}
return fitRect(layout.value, vw.value, vh.value);
});
// Fixed elements stay anchored to the layout viewport, so the dock offsets
// by the part the on-screen keyboard covers to stay above it.
const keyboard = ref(0);
const visibleHeight = ref(window.innerHeight);
// How far the browser has panned the page up to show the focused input.
const visibleTop = ref(0);
useEventListener(() => window.visualViewport, ["resize", "scroll"], () => {
const vv = window.visualViewport;
keyboard.value = keyboardCover(window.innerHeight, vv);
visibleHeight.value = vv ? vv.height : window.innerHeight;
visibleTop.value = vv ? Math.max(0, Math.round(vv.offsetTop)) : 0;
});
const wrapStyle = computed((): Record<string, string> => {
if (!desktop.value) return { bottom: phoneBarBottom(keyboard.value) };
const rect = winRect.value;
if (pinned.value) {
return { left: `${rect.x}px`, top: "0px", width: `${rect.w}px`, height: `${rect.h}px` };
}
if (expanded.value) {
// A tablet's on-screen keyboard covers the bottom of the layout
// viewport; keep the window, and its composer, above it.
const fit = keyboard.value > 0 ? fitRect(rect, vw.value, visibleHeight.value) : rect;
const top = keyboard.value > 0 ? fit.y + visibleTop.value : fit.y;
return { left: `${fit.x}px`, top: `${top}px`, width: `${fit.w}px`, height: `${fit.h}px` };
}
const placed = barPlacement(rect, mode.value, vw.value);
return { left: `${placed.x}px`, bottom: `${placed.bottom + keyboard.value}px`, width: `${placed.w}px` };
});
// The page reserves the collapsed dock's height, read from the rendered bar,
// so the last line of any page can scroll clear of it. Only a bar in the
// bottom quarter of the screen reserves room.
const root = document.documentElement.style;
function reserve(): void {
if (expanded.value || !dock.value) return;
const rect = dock.value.getBoundingClientRect();
const clear = rect.bottom >= window.innerHeight * 0.75 ? Math.ceil(window.innerHeight - rect.top) : 0;
root.setProperty("--chat-dock-clear", `${clear}px`);
}
useResizeObserver(dock, reserve);
useEventListener(window, "resize", reserve);
watch([expanded, desktop, () => layout.value.x, () => layout.value.y, () => layout.value.w, mode], () =>
nextTick(reserve),
);
// The page makes room for a pinned dock through these two variables.
watch(
[pinned, mode, pinW],
() => {
root.setProperty("--chat-pin-l", pinned.value && mode.value === "left" ? `${pinW.value}px` : "0px");
root.setProperty("--chat-pin-r", pinned.value && mode.value === "right" ? `${pinW.value}px` : "0px");
},
{ immediate: true },
);
onUnmounted(() => {
root.removeProperty("--chat-dock-clear");
root.removeProperty("--chat-pin-l");
root.removeProperty("--chat-pin-r");
});
// The header drags the open window and the bar drags the collapsed one. The
// controls inside them keep their own presses, except the move handle.
function onDragSurface(target: HTMLElement): boolean {
const surface = expanded.value ? header.value : bar.value;
if (!surface?.contains(target)) return false;
return !target.closest(NOT_A_DRAG_SURFACE) || !!target.closest("[data-move-handle]");
}
// The rectangle a drag or resize starts from. Collapsed, the bar can sit at
// an edge rather than at the stored x, so its rendered x and width are the
// origin; otherwise the first move would make it jump.
function dragOrigin(): Rect {
const rect = winRect.value;
if (expanded.value || !dock.value) return rect;
const shown = dock.value.getBoundingClientRect();
return { ...rect, x: shown.left, w: shown.width };
}
function applyResize(origin: Rect, dir: ResizeDir, dx: number, dy: number): void {
floatAt(resizeRect(origin, dir, dx, dy, vw.value, vh.value));
}
const dragging = ref(false);
const resizing = ref(false);
const snapTarget = ref<"left" | "right" | null>(null);
// A press becomes a drag only after DRAG_START pixels of travel, so a click
// or double-click on a drag surface never moves the dock.
let drag: { origin: Rect; x0: number; y0: number; moved: boolean } | null = null;
useDraggable(dock, {
disabled: () => !desktop.value,
onStart: (_, e) => {
if (!e.isPrimary || !onDragSurface(e.target as HTMLElement)) return false;
drag = { origin: dragOrigin(), x0: e.clientX, y0: e.clientY, moved: false };
},
onMove: (_, e) => {
if (!drag) return;
const dx = e.clientX - drag.x0;
const dy = e.clientY - drag.y0;
if (!drag.moved && Math.hypot(dx, dy) < DRAG_START) return;
drag.moved = true;
dragging.value = true;
if (!expanded.value) {
const x = Math.min(Math.max(drag.origin.x + dx, INSET), Math.max(INSET, vw.value - drag.origin.w - INSET));
layout.value = { ...layout.value, mode: "float", x };
return;
}
floatAt(fitRect({ ...drag.origin, x: drag.origin.x + dx, y: drag.origin.y + dy }, vw.value, vh.value));
snapTarget.value = snapEdge(e.clientX, vw.value);
},
onEnd: (_, e) => {
if (drag?.moved && e.type === "pointerup" && snapTarget.value) {
layout.value = { ...layout.value, mode: snapTarget.value };
}
drag = null;
dragging.value = false;
snapTarget.value = null;
},
});
// Every resize handle, the pinned divider included, carries data-resize. The
// delta is measured from the press and applied to the rectangle as it was
// then; applying it to the live rectangle would compound every move.
let resize: { dir: ResizeDir | "pin"; origin: Rect; w0: number; x0: number; y0: number } | null = null;
useDraggable(dock, {
disabled: () => !desktop.value,
preventDefault: true,
onStart: (_, e) => {
const handle = (e.target as HTMLElement).closest<HTMLElement>("[data-resize]");
const dir = handle?.dataset.resize as ResizeDir | "pin" | undefined;
if (!e.isPrimary || !dir) return false;
resize = { dir, origin: dragOrigin(), w0: pinW.value, x0: e.clientX, y0: e.clientY };
resizing.value = true;
},
onMove: (_, e) => {
if (!resize) return;
const dx = e.clientX - resize.x0;
if (resize.dir === "pin") {
layout.value = { ...layout.value, w: pinnedWidth(resize.w0 + (mode.value === "left" ? dx : -dx), vw.value) };
return;
}
applyResize(resize.origin, resize.dir, dx, e.clientY - resize.y0);
},
onEnd: () => {
resize = null;
resizing.value = false;
},
});
// On a phone the header is a swipe surface, not a drag surface: a downward
// swipe hides the conversation.
usePointerSwipe(header, {
threshold: SWIPE,
onSwipeEnd: (e, direction) => {
if (desktop.value || e.type !== "pointerup" || direction !== "down") return;
// The keyboard serves the composer, which is no longer in front of it.
(document.activeElement as HTMLElement | null)?.blur();
expanded.value = false;
},
});
function setMode(next: DockMode): void {
if (!desktop.value) return;
layout.value = { ...layout.value, mode: next };
expanded.value = true;
}
function togglePin(event: MouseEvent): void {
if (!desktop.value || !onDragSurface(event.target as HTMLElement)) return;
layout.value = { ...layout.value, mode: mode.value === "float" ? "right" : "float" };
}
function moveByKey(event: KeyboardEvent): void {
if (!desktop.value || !event.key.startsWith("Arrow")) return;
event.preventDefault();
const { dx, dy } = arrowDelta(event);
const rect = winRect.value;
floatAt(fitRect({ ...rect, x: rect.x + dx, y: rect.y + dy }, vw.value, vh.value));
}
function resizeByKey(dir: ResizeDir, event: KeyboardEvent): void {
if (!desktop.value || !event.key.startsWith("Arrow")) return;
event.preventDefault();
const { dx, dy } = arrowDelta(event);
applyResize(dragOrigin(), dir, dx, dy);
}
function resizePinByKey(event: KeyboardEvent): void {
if (!desktop.value) return;
const grow = event.key === (mode.value === "right" ? "ArrowLeft" : "ArrowRight");
const shrink = event.key === (mode.value === "right" ? "ArrowRight" : "ArrowLeft");
if (!grow && !shrink) return;
event.preventDefault();
layout.value = { ...layout.value, w: pinnedWidth(layout.value.w + (grow ? 16 : -16), vw.value) };
}
return {
desktop,
vw,
vh,
mode,
pinned,
pinW,
pinMax,
winRect,
wrapStyle,
visibleHeight,
dragging,
resizing,
snapTarget,
setMode,
togglePin,
moveByKey,
resizeByKey,
resizePinByKey,
};
}