feat(chat): float the chat dock anywhere on screen (#1904) #1912

Merged
sam merged 3 commits from feat/1904-chat-dock-float into main 2026-11-12 14:23:35 +00:00
3 changed files with 784 additions and 101 deletions

No files matched your search

+341 -101
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ChevronDown, ChevronUp } from "@lucide/vue";
import { ChevronDown, ChevronUp, GripVertical, PanelLeft, PanelRight, Square } from "@lucide/vue";
import { useEventListener, useMediaQuery, useStorage, useWindowSize } from "@vueuse/core";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
@@ -11,26 +11,63 @@ import { cn } from "@/lib/utils";
import ChatBar from "./ChatBar.vue";
import ChatComposer from "./ChatComposer.vue";
import ChatTranscript from "./ChatTranscript.vue";
import { composerText, escapeOwnedByLayer, isSending, reloadTranscript, useChat } from "./state";
import {
DOCK_STORAGE_KEY,
DRAG_START,
MAX_W,
MIN_H,
MIN_W,
RESIZE_DIRS,
barPlacement,
fitRect,
handleOrientation,
handleValue,
isSwipeDown,
keyboardCover,
keyStep,
migrateDockStorage,
normalizeLayout,
phoneBarBottom,
pinnedWidth,
resizeRect,
snapEdge,
type DockLayout,
type DockMode,
type Rect,
type ResizeDir,
} from "./ChatDockLayout";
import { escapeOwnedByLayer, isSending, reloadTranscript, useChat } from "./state";
import { setDockOpen, unseenCount } from "./unseen";
/**
* Chat is a bar docked at the bottom of every page, not a route: the operator
* asks Archie about the page they are already on, so navigating must not reset
* it, and it must not replace the work that prompted the question. The agent
* is told which page that is.
* Chat is a window docked to every page, not a route: the operator asks Archie
* about the page they are already on, so navigating must not reset it, and it
* must not replace the work that prompted the question. The agent is told
* which page that is.
*
* It is the composer alone until the operator focuses it or a turn starts, then
* the conversation opens above it. Hiding the conversation leaves the bar. It is
* deliberately not a modal: no scrim, no scroll lock, no focus trap.
* the conversation opens above it. Hiding the conversation leaves the bar where
* it was. It is deliberately not a modal: no scrim, no scroll lock, no focus
* trap.
*
* On a desktop-width screen the expanded conversation can be pinned to the left
* or right edge, where the page reflows beside it instead of sitting under it.
* Dragging the header to an edge pins it; dragging it away, or double-clicking
* the header, unpins it. The side and width are remembered per browser.
* On a desktop-width screen the expanded conversation is a free-floating
* window: the header drags it anywhere, all eight edges and corners resize it
* (pointer and keyboard), and dragging near a side edge shows the pinned
* split, committing on release. Left / Float / Right in the header switch
* modes explicitly; pinned, the page reflows beside the dock instead of
* sitting under it. Ctrl+/ toggles the window, Escape collapses it, and the
* collapsed bar stays where it was and drags too. The layout (mode, x, y,
* width, height) is remembered per browser under "archie.chat.dock.v2", which
* replaces the old edge-pin preference.
*
* On a phone the bar rides above the on-screen keyboard, which iOS does not
* resize the page for, and swiping down on the conversation header hides it.
* On a phone-width screen the dock stays the full-width bottom bar: it rides
* above the on-screen keyboard, which iOS does not resize the page for, and
* swiping down on the conversation header hides it. No float or resize handles
* exist below the desktop breakpoint.
*
* The collapsed bar's show button carries the count of replies that landed
* while it was closed, and a task this conversation started reports its
* outcome into the transcript while the dock stays mounted.
*
* It stays mounted, so the session and any turn in flight survive a navigation.
* It is mounted outside the app shell: `.shell`'s backdrop-filter makes it a
@@ -45,21 +82,38 @@ useLiveResource("chat", () => void reloadTranscript());
const expanded = ref(false);
watch(expanded, setDockOpen, { immediate: true });
const MIN_WIDTH = 320;
const EDGE = 64;
type Side = "left" | "right";
const saved = useStorage<{ side: Side | null; width: number }>(
"archie.chat.dock",
{ side: null, width: 420 },
// The old edge-pin preference moves into the new key before useStorage reads it.
migrateDockStorage(localStorage, window.innerWidth, window.innerHeight);
const stored = useStorage<DockLayout>(
DOCK_STORAGE_KEY,
normalizeLayout(null, window.innerWidth, window.innerHeight),
localStorage,
{ mergeDefaults: true },
);
const desktop = useMediaQuery("(min-width: 768px)");
const { width: viewport } = useWindowSize();
const width = computed(() =>
Math.round(Math.min(Math.max(saved.value.width, MIN_WIDTH), Math.max(MIN_WIDTH, Math.min(720, viewport.value - 480)))),
);
const side = computed(() => (desktop.value && expanded.value ? saved.value.side : null));
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(() => Math.max(MIN_W, Math.min(MAX_W, vw.value - 480)));
// The rendered rectangle of the window: 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);
});
// The part of the layout viewport the on-screen keyboard covers, and the height
// left above it. Fixed elements stay anchored to the layout viewport, so without
// this the bar sits under the keyboard.
@@ -67,18 +121,29 @@ const keyboard = ref(0);
const visibleHeight = ref(window.innerHeight);
function followViewport(): void {
const vv = window.visualViewport;
keyboard.value = vv ? Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop)) : 0;
keyboard.value = keyboardCover(window.innerHeight, vv);
visibleHeight.value = vv ? vv.height : window.innerHeight;
}
useEventListener(() => window.visualViewport, ["resize", "scroll"], followViewport);
const phoneBottom = computed(() =>
keyboard.value > 0 ? `${keyboard.value + 8}px` : "max(0.5rem, env(safe-area-inset-bottom))",
);
const composer = ref<InstanceType<typeof ChatComposer> | null>(null);
const phoneBottom = computed(() => phoneBarBottom(keyboard.value));
const wrapStyle = computed<Record<string, string> | undefined>((): Record<string, string> | undefined => {
if (!desktop.value) return { bottom: phoneBottom.value };
if (pinned.value) {
return { left: `${winRect.value.x}px`, top: "0px", width: `${pinW.value}px`, height: `${vh.value}px` };
}
const rect = winRect.value;
if (expanded.value) {
return { left: `${rect.x}px`, top: `${rect.y}px`, width: `${rect.w}px`, height: `${rect.h}px` };
}
const bar = barPlacement(rect, mode.value, vw.value, vh.value);
return { left: `${bar.x}px`, bottom: `${bar.bottom}px`, width: `${bar.w}px` };
});
// Nothing outside the dock closes it: every navigation control is outside it,
// so a click-outside dismissal turned navigation into a collapse and read as a
// lost conversation. Hide and Escape are the only ways to collapse.
// lost conversation. Hide, swipe down, Escape and Ctrl+/ are the only ways to
// collapse.
watch(isSending, (sending) => {
if (sending) expanded.value = true;
@@ -97,16 +162,29 @@ watch(expanded, (open) => {
else document.removeEventListener("keydown", onKeydown);
});
onUnmounted(() => document.removeEventListener("keydown", onKeydown));
watch(expanded, () => nextTick(reserve));
function onGlobalKeydown(event: KeyboardEvent): void {
if (event.defaultPrevented) return;
if ((event.ctrlKey || event.metaKey) && event.key === "/") {
event.preventDefault();
expanded.value = !expanded.value;
}
}
onMounted(() => document.addEventListener("keydown", onGlobalKeydown));
onUnmounted(() => document.removeEventListener("keydown", onGlobalKeydown));
// 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.
// the last line of any page can scroll clear of it. A bar floating clear of the
// bottom of the screen reserves nothing.
const dock = ref<HTMLElement | null>(null);
let observer: ResizeObserver | null = null;
function reserve(): void {
if (expanded.value || !dock.value) return;
const clear = window.innerHeight - dock.value.getBoundingClientRect().top;
document.documentElement.style.setProperty("--chat-dock-clear", `${Math.ceil(clear)}px`);
const rect = dock.value.getBoundingClientRect();
// Only a bar sitting in the bottom quarter of the screen needs the page to
// reserve room under it; one floating higher up does not.
const clear = rect.bottom >= window.innerHeight * 0.75 ? Math.ceil(window.innerHeight - rect.top) : 0;
document.documentElement.style.setProperty("--chat-dock-clear", `${clear}px`);
}
onMounted(() => {
observer = new ResizeObserver(reserve);
@@ -118,66 +196,82 @@ onUnmounted(() => {
window.removeEventListener("resize", reserve);
document.documentElement.style.removeProperty("--chat-dock-clear");
});
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([side, width], ([s, w]) => {
watch([pinned, mode, pinW], () => {
const root = document.documentElement.style;
root.setProperty("--chat-pin-l", s === "left" ? `${w}px` : "0px");
root.setProperty("--chat-pin-r", s === "right" ? `${w}px` : "0px");
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(() => {
document.documentElement.style.removeProperty("--chat-pin-l");
document.documentElement.style.removeProperty("--chat-pin-r");
});
function edgeAt(x: number): Side | null {
if (x <= EDGE) return "left";
if (x >= window.innerWidth - EDGE) return "right";
return null;
const MODES: { mode: DockMode; label: string; icon: typeof PanelLeft; aria: string; title: string }[] = [
{ mode: "left", label: "Left", icon: PanelLeft, aria: "Pin chat to left edge", title: "Dock left, reflowing the page beside it" },
{ mode: "float", label: "Float", icon: Square, aria: "Float window", title: "Float the window, dragging and resizing freely" },
{ mode: "right", label: "Right", icon: PanelRight, aria: "Pin chat to right edge", title: "Dock right, reflowing the page beside it" },
];
function setMode(next: DockMode): void {
if (!desktop.value) return;
layout.value = { ...layout.value, mode: next };
expanded.value = true;
}
// Pointer travel before a press on the header becomes a drag, so a click or a
// double-click on it never moves the dock.
const INTERACTIVE = "button, a, input, select, textarea, [role=combobox]";
const DRAG_START = 4;
const offset = ref<{ x: number; y: number } | null>(null);
const target = ref<Side | null>(null);
// Pointer travel before a press on a drag surface becomes a drag, so a click or
// a double-click on it never moves the dock.
const dragging = ref(false);
const snapTarget = ref<"left" | "right" | null>(null);
function startDrag(event: PointerEvent): void {
if (event.button !== 0 || (event.target as HTMLElement).closest(INTERACTIVE)) return;
if (!desktop.value) return startSwipe(event);
if (!desktop.value || event.button !== 0 || !event.isPrimary) return;
// The move handle is a button that drags, so it is exempt from the ignore list.
const target = event.target as HTMLElement;
if (target.closest("button, a, input, select, textarea, [role=combobox], [role=separator]") && !target.closest("[data-move-handle]")) return;
const grip = event.currentTarget as HTMLElement;
const { clientX: x0, clientY: y0 } = event;
const origin = { ...winRect.value };
const x0 = event.clientX;
const y0 = event.clientY;
grip.setPointerCapture(event.pointerId);
let moved = false;
let snap: "left" | "right" | null = null;
const move = (e: PointerEvent): void => {
const dx = e.clientX - x0;
const dy = e.clientY - y0;
if (!offset.value && Math.hypot(dx, dy) < DRAG_START) return;
offset.value = { x: dx, y: dy };
target.value = edgeAt(e.clientX);
if (!moved && Math.hypot(dx, dy) < DRAG_START) return;
moved = true;
dragging.value = true;
const next = fitRect({ x: origin.x + dx, y: origin.y + dy, w: origin.w, h: origin.h }, vw.value, vh.value);
layout.value = { ...layout.value, mode: "float", x: next.x, y: next.y, w: next.w, h: next.h };
snap = expanded.value ? snapEdge(e.clientX, vw.value) : null;
snapTarget.value = snap;
};
const end = (e: PointerEvent): void => {
grip.removeEventListener("pointermove", move);
grip.removeEventListener("pointerup", end);
grip.removeEventListener("pointercancel", end);
if (offset.value && e.type === "pointerup") saved.value.side = edgeAt(e.clientX);
offset.value = null;
target.value = null;
if (moved && e.type === "pointerup" && snap) layout.value = { ...layout.value, mode: snap };
moved = false;
dragging.value = false;
snapTarget.value = null;
};
grip.addEventListener("pointermove", move);
grip.addEventListener("pointerup", end);
grip.addEventListener("pointercancel", end);
}
// A downward flick on the header hides the conversation. It must be mostly
// vertical so a sideways slip does not collapse it.
const SWIPE = 48;
// On a phone the header is a swipe surface, not a drag surface: a downward
// flick hides the conversation.
function startSwipe(event: PointerEvent): void {
const grip = event.currentTarget as HTMLElement;
const { clientX: x0, clientY: y0 } = event;
const end = (e: PointerEvent): void => {
grip.removeEventListener("pointerup", end);
grip.removeEventListener("pointercancel", end);
const dy = e.clientY - y0;
if (e.type === "pointerup" && dy >= SWIPE && dy > Math.abs(e.clientX - x0) * 1.5) {
if (e.type === "pointerup" && isSwipeDown(e.clientX - x0, e.clientY - y0)) {
// The keyboard is for the composer, which is no longer in front of it.
(document.activeElement as HTMLElement | null)?.blur();
expanded.value = false;
@@ -186,16 +280,100 @@ function startSwipe(event: PointerEvent): void {
grip.addEventListener("pointerup", end);
grip.addEventListener("pointercancel", end);
}
function onHeaderPointerDown(event: PointerEvent): void {
if (!desktop.value) return startSwipe(event);
startDrag(event);
}
function togglePin(event: MouseEvent): void {
if (!desktop.value || (event.target as HTMLElement).closest(INTERACTIVE)) return;
saved.value.side = saved.value.side ? null : "right";
const target = event.target as HTMLElement;
if (!desktop.value || (target.closest("button, a, input, select, textarea, [role=combobox], [role=separator]") && !target.closest("[data-move-handle]"))) return;
layout.value = { ...layout.value, mode: mode.value === "float" ? "right" : "float" };
}
function resize(event: PointerEvent): void {
// The collapsed bar drags from its own padding and its move handle; the
// composer inside it keeps its text selection.
function onBarPointerDown(event: PointerEvent): void {
if (expanded.value) return;
startDrag(event);
}
function moveByKey(event: KeyboardEvent): void {
if (!desktop.value || !event.key.startsWith("Arrow")) return;
event.preventDefault();
const step = keyStep(event.shiftKey);
const rect = winRect.value;
const next = fitRect(
{
...rect,
x: rect.x + (event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0),
y: rect.y + (event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0),
},
vw.value,
vh.value,
);
layout.value = { ...layout.value, mode: "float", x: next.x, y: next.y, w: next.w, h: next.h };
}
const HANDLE_CLASS: Record<ResizeDir, string> = {
n: "top-[-3px] left-3.5 right-3.5 h-2 cursor-ns-resize",
s: "bottom-[-3px] left-3.5 right-3.5 h-2 cursor-ns-resize",
e: "right-[-3px] top-3.5 bottom-3.5 w-2 cursor-ew-resize",
w: "left-[-3px] top-3.5 bottom-3.5 w-2 cursor-ew-resize",
ne: "top-0 right-0 size-3.5 cursor-nesw-resize",
nw: "top-0 left-0 size-3.5 cursor-nwse-resize",
se: "bottom-0 right-0 size-4 cursor-nwse-resize",
sw: "bottom-0 left-0 size-4 cursor-nesw-resize",
};
const DIR_LABEL: Record<ResizeDir, string> = {
n: "top",
s: "bottom",
e: "right",
w: "left",
ne: "top right",
nw: "top left",
se: "bottom right",
sw: "bottom left",
};
// The minimised bar keeps its height, so only its width edges resize it.
const visibleDirs = computed<ResizeDir[]>(() => (expanded.value ? [...RESIZE_DIRS] : ["e", "w"]));
function applyResize(dir: ResizeDir, dx: number, dy: number): void {
const rect = resizeRect(winRect.value, dir, dx, dy, vw.value, vh.value);
layout.value = { ...layout.value, mode: "float", x: rect.x, y: rect.y, w: rect.w, h: rect.h };
}
function startResize(dir: ResizeDir, event: PointerEvent): void {
if (!desktop.value || event.button !== 0 || !event.isPrimary) return;
const handle = event.currentTarget as HTMLElement;
handle.setPointerCapture(event.pointerId);
const move = (e: PointerEvent): void => applyResize(dir, e.clientX - event.clientX, e.clientY - event.clientY);
const end = (): void => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
handle.removeEventListener("pointercancel", end);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
}
function onHandleKey(dir: ResizeDir, event: KeyboardEvent): void {
if (!desktop.value || !event.key.startsWith("Arrow")) return;
event.preventDefault();
const step = keyStep(event.shiftKey);
const dx = event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0;
const dy = event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0;
applyResize(dir, dx, dy);
}
// The pinned split keeps its single divider, which resizes the pin width.
function startPinResize(event: PointerEvent): void {
if (!desktop.value || event.button !== 0 || !event.isPrimary) return;
const handle = event.currentTarget as HTMLElement;
handle.setPointerCapture(event.pointerId);
const move = (e: PointerEvent): void => {
saved.value.width = side.value === "right" ? window.innerWidth - e.clientX : e.clientX;
const delta = e.clientX - event.clientX;
layout.value = { ...layout.value, w: clampWidth(layout.value.w + (mode.value === "left" ? delta : -delta)) };
};
const end = (): void => {
handle.removeEventListener("pointermove", move);
@@ -206,69 +384,116 @@ function resize(event: PointerEvent): void {
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
}
function resizeByKey(event: KeyboardEvent): void {
const grow = event.key === (side.value === "right" ? "ArrowLeft" : "ArrowRight");
const shrink = event.key === (side.value === "right" ? "ArrowRight" : "ArrowLeft");
function clampWidth(w: number): number {
return Math.min(Math.max(w, MIN_W), pinMax.value);
}
function onPinKey(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();
saved.value.width = width.value + (grow ? 16 : -16);
}
function usePrompt(text: string): void {
composerText.value = text;
composer.value?.focus();
layout.value = { ...layout.value, w: clampWidth(layout.value.w + (grow ? 16 : -16)) };
}
</script>
<template>
<div
v-if="target"
v-if="snapTarget"
aria-hidden="true"
:class="cn('pointer-events-none fixed inset-y-0 z-40 border-primary/40 bg-primary/10', target === 'left' ? 'left-0 border-r-2' : 'right-0 border-l-2')"
:style="{ width: `${width}px` }"
:class="cn('pointer-events-none fixed inset-y-0 z-40 border-primary/40 bg-primary/10', snapTarget === 'left' ? 'left-0 border-r-2' : 'right-0 border-l-2')"
:style="{ width: `${pinW}px` }"
/>
<div
:class="cn(
'pointer-events-none fixed z-40',
side ? cn('inset-y-0', side === 'left' ? 'left-0' : 'right-0') : 'inset-x-0 bottom-4 flex justify-center px-3',
'pointer-events-none fixed z-40 transition-[left,top,bottom,width,height] duration-200 ease-out motion-reduce:transition-none',
dragging && 'transition-none',
!desktop && 'inset-x-0 bottom-4 flex justify-center px-3 max-md:bottom-2',
)"
:style="side ? { width: `${width}px` } : desktop ? undefined : { bottom: phoneBottom }"
:style="wrapStyle"
>
<aside
ref="dock"
aria-label="Chat with Archie"
:class="cn(
'touch-hit pointer-events-auto relative flex flex-col border-border-strong bg-popover shadow-[var(--shadow-md)]',
side
? cn('h-full w-full', side === 'left' ? 'border-r' : 'border-l')
: 'w-full max-w-xl rounded-lg border',
offset && 'z-50 opacity-90',
desktop ? cn('w-full', pinned || expanded ? 'h-full' : '', pinned ? (mode === 'left' ? 'border-r' : 'border-l') : 'rounded-lg border') : 'w-full max-w-xl rounded-lg border',
dragging && 'z-50 opacity-90',
)"
:style="offset ? { transform: `translate(${offset.x}px, ${offset.y}px)` } : undefined"
>
<template v-if="desktop && !pinned">
<div
v-for="dir in visibleDirs"
:key="dir"
role="separator"
tabindex="0"
aria-label="Resize chat"
:title="`Resize from the ${DIR_LABEL[dir]} edge. Arrow keys resize; Shift changes faster.`"
:aria-orientation="handleOrientation(dir)"
:aria-valuenow="handleValue(dir, winRect)"
:aria-valuemin="dir === 'n' || dir === 's' ? MIN_H : MIN_W"
:aria-valuemax="dir === 'n' || dir === 's' ? vh : vw"
:data-resize="dir"
:class="cn('absolute z-10 touch-none hover:bg-primary/30 focus-visible:bg-primary/50 focus-visible:outline-none', HANDLE_CLASS[dir])"
@pointerdown.prevent="startResize(dir, $event)"
@keydown="onHandleKey(dir, $event)"
/>
</template>
<div
v-if="side"
v-if="desktop && pinned"
role="separator"
aria-orientation="vertical"
aria-label="Resize chat"
tabindex="0"
:aria-valuenow="width"
:aria-valuemin="MIN_WIDTH"
class="absolute inset-y-0 z-10 w-1.5 cursor-col-resize hover:bg-primary/30 focus-visible:bg-primary/30 focus-visible:outline-none"
:class="side === 'left' ? '-right-0.5' : '-left-0.5'"
@pointerdown.prevent="resize"
@keydown="resizeByKey"
:aria-valuenow="pinW"
:aria-valuemin="MIN_W"
:aria-valuemax="pinMax"
class="absolute inset-y-0 z-10 w-1.5 cursor-col-resize hover:bg-primary/30 focus-visible:bg-primary/50 focus-visible:outline-none"
:class="mode === 'left' ? '-right-0.5' : '-left-0.5'"
@pointerdown.prevent="startPinResize"
@keydown="onPinKey"
/>
<div
v-if="expanded"
:class="desktop ? 'cursor-grab select-none active:cursor-grabbing' : 'touch-none'"
@pointerdown="startDrag"
@pointerdown="onHeaderPointerDown"
@dblclick="togglePin"
>
<div class="flex justify-center pt-1.5" aria-hidden="true">
<div v-if="desktop" class="flex justify-center pt-1.5" aria-hidden="true">
<span class="h-1 w-8 rounded-full bg-border-strong" />
</div>
<ChatBar>
<div v-if="desktop" class="flex flex-none items-center gap-0.5" role="group" aria-label="Chat window position">
<Button
v-for="m in MODES"
:key="m.mode"
variant="ghost"
size="xs"
:aria-pressed="mode === m.mode"
:aria-label="m.aria"
:title="m.title"
:class="mode === m.mode && 'bg-muted text-foreground'"
@click="setMode(m.mode)"
>
<component :is="m.icon" aria-hidden="true" />{{ m.label }}
</Button>
</div>
<Tooltip v-if="desktop">
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none"
data-move-handle
aria-label="Move chat"
title="Drag to move. Arrow keys move; Shift moves further."
@keydown="moveByKey"
>
<GripVertical />
</Button>
</TooltipTrigger>
<TooltipContent>Move chat</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button
@@ -287,14 +512,29 @@ function usePrompt(text: string): void {
</div>
<div
v-if="expanded"
:class="cn('flex min-h-0 flex-col', side ? 'flex-1' : 'h-[min(28rem,55dvh)]')"
:style="side || desktop ? undefined : { height: `min(28rem, ${Math.round(visibleHeight * 0.55)}px)` }"
:class="cn('flex min-h-0 flex-col', desktop ? 'flex-1' : 'h-[min(28rem,55dvh)]')"
:style="desktop ? undefined : { height: `min(28rem, ${Math.round(visibleHeight * 0.55)}px)` }"
>
<ChatTranscript @prompt="usePrompt" />
<ChatTranscript />
</div>
<div @focusin="expanded = true">
<ChatComposer ref="composer" :open="false" :flat="!expanded">
<div @focusin="expanded = true" @pointerdown="onBarPointerDown">
<ChatComposer :open="false" :flat="!expanded">
<template v-if="!expanded" #actions>
<Tooltip v-if="desktop">
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
data-move-handle
aria-label="Move chat"
title="Drag to move. Arrow keys move; Shift moves further."
@keydown="moveByKey"
>
<GripVertical />
</Button>
</TooltipTrigger>
<TooltipContent>Move chat</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button
+200
View File
@@ -0,0 +1,200 @@
/**
* Geometry and persistence for the chat dock window. The dock floats freely on
* desktop-width screens: the header drags it anywhere, eight edges and corners
* resize it, and dragging near a side edge offers the pinned split, which
* reflows the page. On phone-width screens it stays a full-width bottom bar,
* riding above the on-screen keyboard. Pure functions live here so the
* placement rules are testable without a DOM; ChatDock.vue owns the pointer
* and keyboard events.
*/
export type DockMode = "left" | "float" | "right";
export interface Rect {
x: number;
y: number;
w: number;
h: number;
}
export interface DockLayout extends Rect {
mode: DockMode;
}
export const DOCK_STORAGE_KEY = "archie.chat.dock.v2";
export const LEGACY_DOCK_STORAGE_KEY = "archie.chat.dock";
export const MIN_W = 320;
export const MIN_H = 280;
export const MAX_W = 720;
/** Margin kept between a floating window and the viewport edge. */
export const INSET = 8;
/** Pointer distance from a side edge that offers the snap preview. */
export const EDGE = 64;
/** Pointer travel before a press on a drag surface becomes a drag. */
export const DRAG_START = 4;
export const KEY_STEP = 10;
export const KEY_STEP_FAST = 40;
export const RESIZE_DIRS = ["n", "s", "e", "w", "ne", "nw", "se", "sw"] as const;
export type ResizeDir = (typeof RESIZE_DIRS)[number];
export function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), Math.max(min, max));
}
export function defaultLayout(vw: number, vh: number): DockLayout {
const w = Math.min(440, Math.max(MIN_W, vw - INSET * 2));
const h = Math.min(560, Math.max(MIN_H, vh - INSET * 2));
return { mode: "float", x: Math.max(INSET, vw - w - 24), y: Math.max(INSET, vh - h - 24), w, h };
}
/** Largest width a floating window may take in this viewport. */
export function windowWidth(w: number, vw: number): number {
return clamp(w, MIN_W, Math.max(MIN_W, Math.min(MAX_W, vw - INSET * 2)));
}
/** Largest width the pinned split may take, leaving the page room to reflow. */
export function pinnedWidth(w: number, vw: number): number {
return clamp(w, MIN_W, Math.max(MIN_W, Math.min(MAX_W, vw - 480)));
}
/** Clamp a rectangle into the viewport, keeping its size within the minimums. */
export function fitRect<T extends Rect>(rect: T, vw: number, vh: number, inset = INSET): T {
const availW = Math.max(1, vw - inset * 2);
const availH = Math.max(1, vh - inset * 2);
const w = clamp(rect.w, Math.min(MIN_W, availW), Math.min(MAX_W, availW));
const h = clamp(rect.h, Math.min(MIN_H, availH), availH);
return {
...rect,
x: clamp(rect.x, inset, vw - w - inset),
y: clamp(rect.y, inset, vh - h - inset),
w,
h,
};
}
/** Validate a stored value, filling any missing field from the defaults. */
export function normalizeLayout(raw: unknown, vw: number, vh: number): DockLayout {
const d = defaultLayout(vw, vh);
if (!raw || typeof raw !== "object") return d;
const o = raw as Partial<Record<keyof DockLayout, unknown>>;
const mode: DockMode = o.mode === "left" || o.mode === "right" || o.mode === "float" ? o.mode : "float";
const num = (value: unknown, fallback: number): number =>
typeof value === "number" && Number.isFinite(value) ? value : fallback;
return fitRect(
{ mode, x: num(o.x, d.x), y: num(o.y, d.y), w: num(o.w, d.w), h: num(o.h, d.h) },
vw,
vh,
);
}
/** Resize a rectangle from one of the eight edges/corners by a pointer delta. */
export function resizeRect(origin: Rect, dir: ResizeDir, dx: number, dy: number, vw: number, vh: number): Rect {
const rect = { ...origin };
const minW = Math.min(MIN_W, Math.max(1, vw - INSET * 2));
const minH = Math.min(MIN_H, Math.max(1, vh - INSET * 2));
if (dir.includes("e")) rect.w = clamp(origin.w + dx, minW, Math.max(minW, vw - origin.x - INSET));
if (dir.includes("s")) rect.h = clamp(origin.h + dy, minH, Math.max(minH, vh - origin.y - INSET));
if (dir.includes("w")) {
rect.x = clamp(origin.x + dx, INSET, origin.x + origin.w - minW);
rect.w = origin.x + origin.w - rect.x;
}
if (dir.includes("n")) {
rect.y = clamp(origin.y + dy, INSET, origin.y + origin.h - minH);
rect.h = origin.y + origin.h - rect.y;
}
return rect;
}
/** The pinned side a pointer near an edge would commit to on release. */
export function snapEdge(pointerX: number, vw: number, edge = EDGE): "left" | "right" | null {
if (pointerX <= edge) return "left";
if (pointerX >= vw - edge) return "right";
return null;
}
/**
* Where the minimised bar sits: at the bottom edge of the window's rectangle,
* on the side the mode pins to. Returned as a bottom offset so the bar's own
* height never has to be known here.
*/
export function barPlacement(rect: Rect, mode: DockMode, vw: number, vh: number): { x: number; bottom: number; w: number } {
const w = rect.w;
const x = mode === "left" ? 0 : mode === "right" ? Math.max(0, vw - w) : rect.x;
return { x, bottom: clamp(vh - (rect.y + rect.h), INSET, Math.max(INSET, vh - INSET)), w };
}
/** Pointer travel down on the header that hides the conversation on a phone. */
export const SWIPE = 48;
/**
* How much of the layout viewport the on-screen keyboard covers, 0 when there
* is none. Fixed elements stay anchored to the layout viewport, so the phone
* bar offsets by this to ride above the keyboard.
*/
export function keyboardCover(innerHeight: number, vv: { height: number; offsetTop: number } | null): number {
return vv ? Math.max(0, Math.round(innerHeight - vv.height - vv.offsetTop)) : 0;
}
/** The phone bar's bottom offset: above the keyboard while one is up, else the safe area. */
export function phoneBarBottom(keyboard: number): string {
return keyboard > 0 ? `${keyboard + 8}px` : "max(0.5rem, env(safe-area-inset-bottom))";
}
/** A header flick hides the conversation only when it is mostly downward, so a sideways slip does not collapse it. */
export function isSwipeDown(dx: number, dy: number): boolean {
return dy >= SWIPE && dy > Math.abs(dx) * 1.5;
}
/** The old { side, width } dock preference, as a partial new layout. */
export function legacyLayout(raw: unknown): Partial<DockLayout> | null {
if (!raw || typeof raw !== "object") return null;
const o = raw as Record<string, unknown>;
const partial: Partial<DockLayout> = { mode: o.side === "left" || o.side === "right" ? o.side : "float" };
if (typeof o.width === "number" && Number.isFinite(o.width)) partial.w = o.width;
return partial;
}
export interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
/**
* Move the old "archie.chat.dock" preference into the new key (the side becomes
* the mode, the width the window width) and drop the old key either way: the
* new key deliberately replaces it.
*/
export function migrateDockStorage(storage: StorageLike, vw: number, vh: number): void {
try {
const legacy = storage.getItem(LEGACY_DOCK_STORAGE_KEY);
if (storage.getItem(DOCK_STORAGE_KEY) === null && legacy !== null) {
let parsed: unknown = null;
try {
parsed = JSON.parse(legacy);
} catch {
parsed = null;
}
storage.setItem(DOCK_STORAGE_KEY, JSON.stringify(normalizeLayout(legacyLayout(parsed) ?? {}, vw, vh)));
}
if (legacy !== null) storage.removeItem(LEGACY_DOCK_STORAGE_KEY);
} catch {
// Unwritable storage leaves the dock at its defaults for this visit.
}
}
export function keyStep(fast: boolean): number {
return fast ? KEY_STEP_FAST : KEY_STEP;
}
/** The separator orientation announced for a resize handle. */
export function handleOrientation(dir: ResizeDir): "horizontal" | "vertical" {
return dir === "e" || dir === "w" ? "vertical" : "horizontal";
}
/** The size a resize handle announces: its height on the north/south edges, else its width. */
export function handleValue(dir: ResizeDir, rect: Rect): number {
return dir === "n" || dir === "s" ? Math.round(rect.h) : Math.round(rect.w);
}
+243
View File
@@ -0,0 +1,243 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
DOCK_STORAGE_KEY,
LEGACY_DOCK_STORAGE_KEY,
MIN_H,
MIN_W,
barPlacement,
defaultLayout,
fitRect,
handleOrientation,
handleValue,
isSwipeDown,
keyboardCover,
keyStep,
legacyLayout,
migrateDockStorage,
normalizeLayout,
phoneBarBottom,
pinnedWidth,
resizeRect,
snapEdge,
windowWidth,
type DockLayout,
type ResizeDir,
type StorageLike,
} from "../src/chat/ChatDockLayout.ts";
class MemoryStorage implements StorageLike {
readonly values = new Map<string, string>();
getItem(key: string): string | null {
return this.values.get(key) ?? null;
}
setItem(key: string, value: string): void {
this.values.set(key, value);
}
removeItem(key: string): void {
this.values.delete(key);
}
}
const VW = 1280;
const VH = 800;
test("a stored layout is validated and clamped into the viewport", () => {
const cases: Array<[unknown, DockLayout]> = [
[null, defaultLayout(VW, VH)],
[{}, defaultLayout(VW, VH)],
[
{ mode: "right", x: 4000, y: -50, w: 10, h: 99999 },
{ mode: "right", x: 1280 - MIN_W - 8, y: 8, w: MIN_W, h: 800 - 16 },
],
[
{ mode: "float", x: 100, y: 120, w: 440, h: 560 },
{ mode: "float", x: 100, y: 120, w: 440, h: 560 },
],
[
{ mode: "sideways", x: "10", y: Number.NaN, w: 440, h: 560 },
{ ...defaultLayout(VW, VH), w: 440, h: 560 },
],
];
for (const [raw, want] of cases) {
assert.deepEqual(normalizeLayout(raw, VW, VH), want, JSON.stringify(raw));
}
});
test("fitRect keeps the whole rectangle inside the viewport at any size", () => {
const cases: Array<[[number, number, number, number], [number, number, number, number]]> = [
[[-100, -100, 440, 560], [8, 8, 440, 560]],
[[1200, 700, 440, 560], [1280 - 440 - 8, 800 - 560 - 8, 440, 560]],
[[0, 0, 99999, 99999], [8, 8, 720, 784]],
[[0, 0, 100, 100], [8, 8, MIN_W, MIN_H]],
];
for (const [[x, y, w, h], want] of cases) {
assert.deepEqual(fitRect({ x, y, w, h }, VW, VH), { x: want[0], y: want[1], w: want[2], h: want[3] });
}
// A viewport smaller than the minimum still yields a usable rectangle.
assert.deepEqual(fitRect({ x: 0, y: 0, w: 500, h: 500 }, 300, 200), { x: 8, y: 8, w: 284, h: 184 });
});
test("all eight edges and corners resize the rectangle in their own direction", () => {
const origin = { x: 100, y: 100, w: 400, h: 300 };
const cases: Array<[ResizeDir, number, number, [number, number, number, number]]> = [
["e", 20, 0, [100, 100, 420, 300]],
["e", -20, 0, [100, 100, 380, 300]],
["s", 0, 30, [100, 100, 400, 330]],
["w", 20, 0, [120, 100, 380, 300]],
["w", -20, 0, [80, 100, 420, 300]],
["n", 0, 20, [100, 120, 400, 280]],
["n", 0, -20, [100, 80, 400, 320]],
["se", 10, 10, [100, 100, 410, 310]],
["nw", -10, -10, [90, 90, 410, 310]],
["ne", 10, -10, [100, 90, 410, 310]],
["sw", -10, 10, [90, 100, 410, 310]],
];
for (const [dir, dx, dy, want] of cases) {
assert.deepEqual(
resizeRect(origin, dir, dx, dy, VW, VH),
{ x: want[0], y: want[1], w: want[2], h: want[3] },
dir,
);
}
});
test("resize never collapses the window below the minimum or pushes it off screen", () => {
const origin = { x: 100, y: 100, w: 400, h: 300 };
assert.deepEqual(resizeRect(origin, "e", -9999, 0, VW, VH), { x: 100, y: 100, w: MIN_W, h: 300 });
assert.deepEqual(resizeRect(origin, "s", 0, -9999, VW, VH), { x: 100, y: 100, w: 400, h: MIN_H });
assert.deepEqual(resizeRect(origin, "w", 9999, 0, VW, VH), { x: 100 + 400 - MIN_W, y: 100, w: MIN_W, h: 300 });
assert.deepEqual(resizeRect(origin, "n", 0, 9999, VW, VH), { x: 100, y: 100 + 300 - MIN_H, w: 400, h: MIN_H });
assert.deepEqual(resizeRect({ x: 0, y: 0, w: 400, h: 300 }, "e", 99999, 0, VW, VH), { x: 0, y: 0, w: VW - 8, h: 300 });
assert.deepEqual(resizeRect({ x: 0, y: 0, w: 400, h: 300 }, "s", 0, 99999, VW, VH), { x: 0, y: 0, w: 400, h: VH - 8 });
});
test("a pointer near a side edge offers that pinned split, otherwise none", () => {
const cases: Array<[number, "left" | "right" | null]> = [
[0, "left"],
[64, "left"],
[65, null],
[640, null],
[1215, null],
[1216, "right"],
[1280, "right"],
];
for (const [x, want] of cases) {
assert.equal(snapEdge(x, VW), want, String(x));
}
});
test("the minimised bar sits at the bottom of the window's rectangle on the pinned side", () => {
const rect = { x: 300, y: 100, w: 440, h: 560 };
assert.deepEqual(barPlacement(rect, "float", VW, VH), { x: 300, bottom: 800 - 660, w: 440 });
assert.deepEqual(barPlacement(rect, "left", VW, VH), { x: 0, bottom: 800 - 660, w: 440 });
assert.deepEqual(barPlacement(rect, "right", VW, VH), { x: 1280 - 440, bottom: 800 - 660, w: 440 });
// A window dragged to the bottom keeps the bar fully on screen.
assert.deepEqual(barPlacement({ x: 10, y: 700, w: 440, h: 560 }, "float", VW, VH), { x: 10, bottom: 8, w: 440 });
});
test("the old edge-pin preference migrates into the new key and is removed", () => {
const cases: Array<[string | null, DockLayout | null]> = [
['{"side":"right","width":500}', { mode: "right", x: 772, y: 216, w: 500, h: 560 }],
['{"side":"left","width":300}', { mode: "left", x: 816, y: 216, w: 320, h: 560 }],
['{"side":null,"width":380}', { mode: "float", x: 816, y: 216, w: 380, h: 560 }],
["not json", defaultLayout(VW, VH)],
[null, null],
];
for (const [legacy, want] of cases) {
const storage = new MemoryStorage();
if (legacy !== null) storage.setItem(LEGACY_DOCK_STORAGE_KEY, legacy);
migrateDockStorage(storage, VW, VH);
assert.equal(storage.getItem(LEGACY_DOCK_STORAGE_KEY), null, "legacy key removed");
if (want === null) {
assert.equal(storage.getItem(DOCK_STORAGE_KEY), null);
} else {
assert.deepEqual(JSON.parse(storage.getItem(DOCK_STORAGE_KEY) ?? "null"), want, legacy ?? "");
}
}
});
test("an existing new-key layout wins and still retires the legacy key", () => {
const storage = new MemoryStorage();
const kept: DockLayout = { mode: "float", x: 40, y: 40, w: 360, h: 420 };
storage.setItem(DOCK_STORAGE_KEY, JSON.stringify(kept));
storage.setItem(LEGACY_DOCK_STORAGE_KEY, '{"side":"left","width":900}');
migrateDockStorage(storage, VW, VH);
assert.deepEqual(JSON.parse(storage.getItem(DOCK_STORAGE_KEY) ?? "null"), kept);
assert.equal(storage.getItem(LEGACY_DOCK_STORAGE_KEY), null);
});
test("legacy pin and float widths are clamped to what the viewport allows", () => {
assert.equal(pinnedWidth(500, VW), 500);
assert.equal(pinnedWidth(9999, VW), 720);
assert.equal(pinnedWidth(100, VW), MIN_W);
assert.equal(pinnedWidth(700, 900), 420); // vw - 480 caps below MAX_W
assert.equal(windowWidth(440, VW), 440);
assert.equal(windowWidth(9999, VW), 720);
assert.equal(windowWidth(440, 400), 384);
});
test("keyboard steps and handle metadata follow the contract", () => {
assert.equal(keyStep(false), 10);
assert.equal(keyStep(true), 40);
const dirs = ["n", "s", "e", "w", "ne", "nw", "se", "sw"] as const;
for (const dir of dirs) {
assert.match(handleOrientation(dir), /^(horizontal|vertical)$/);
assert.ok(Number.isFinite(handleValue(dir, { x: 0, y: 0, w: 412.4, h: 287.6 })));
}
assert.equal(handleValue("n", { x: 0, y: 0, w: 100, h: 287.6 }), 288);
assert.equal(handleValue("se", { x: 0, y: 0, w: 412.4, h: 100 }), 412);
assert.equal(handleOrientation("e"), "vertical");
assert.equal(handleOrientation("w"), "vertical");
assert.equal(handleOrientation("s"), "horizontal");
});
test("legacyLayout maps only the known fields of the old preference", () => {
assert.deepEqual(legacyLayout({ side: "left", width: 420 }), { mode: "left", w: 420 });
assert.deepEqual(legacyLayout({ side: "right" }), { mode: "right" });
assert.deepEqual(legacyLayout({ side: null, width: 420 }), { mode: "float", w: 420 });
assert.deepEqual(legacyLayout({ side: "up", width: "wide" }), { mode: "float" });
assert.equal(legacyLayout(null), null);
assert.equal(legacyLayout("right"), null);
});
test("the on-screen keyboard's cover of the layout viewport is measured, never negative", () => {
const cases: Array<[{ height: number; offsetTop: number } | null, number]> = [
[null, 0],
[{ height: 800, offsetTop: 0 }, 0],
[{ height: 500, offsetTop: 0 }, 300],
[{ height: 500, offsetTop: 20 }, 280],
[{ height: 460.4, offsetTop: 10 }, 330],
[{ height: 900, offsetTop: 0 }, 0],
];
for (const [vv, want] of cases) {
assert.equal(keyboardCover(800, vv), want, JSON.stringify(vv));
}
});
test("the phone bar sits above the keyboard while one is up, else at the safe area", () => {
assert.equal(phoneBarBottom(0), "max(0.5rem, env(safe-area-inset-bottom))");
assert.equal(phoneBarBottom(300), "308px");
assert.equal(phoneBarBottom(1), "9px");
});
test("a header flick hides the conversation only when it is mostly downward", () => {
const cases: Array<[number, number, boolean]> = [
[0, 48, true],
[0, 47, false],
[0, 200, true],
[-30, 60, true], // 60 > 45
[40, 60, false], // 60 is not > 60
[31, 48, true], // 48 > 46.5
[33, 49, false], // 49 is not > 49.5
[100, 50, false],
[0, -48, false], // upward flick never hides
];
for (const [dx, dy, want] of cases) {
assert.equal(isSwipeDown(dx, dy), want, `dx=${dx} dy=${dy}`);
}
});