Files
archie/ui/src/chat/ChatDock.vue
T

579 lines
24 KiB
Vue

<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ChevronDown, ChevronUp, GripVertical, PanelLeft, PanelRight, PictureInPicture2 } from "@lucide/vue";
import { useDraggable, useEventListener, useMediaQuery, usePointerSwipe, useStorage, useWindowSize } from "@vueuse/core";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useLiveResource } from "@/stores/session";
import { cn } from "@/lib/utils";
import ChatBar from "./ChatBar.vue";
import ChatComposer from "./ChatComposer.vue";
import ChatTranscript from "./ChatTranscript.vue";
import {
DOCK_STORAGE_KEY,
DRAG_START,
MAX_W,
MIN_H,
MIN_W,
RESIZE_DIRS,
SWIPE,
barPlacement,
fitRect,
BAR_W,
INSET,
handleOrientation,
handleValue,
keyboardCover,
keyStep,
migrateDockStorage,
normalizeLayout,
phoneBarBottom,
pinnedWidth,
resizeRect,
snapEdge,
type DockLayout,
type DockMode,
type Rect,
type ResizeDir,
} from "./ChatDockLayout";
import { dockExpanded, escapeOwnedByLayer, isSending, reloadTranscript, useChat, useEscapeLayer } from "./state";
import { setDockOpen, unseenCount } from "./unseen";
/**
* 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 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 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. The header's position menu picks Left, Float
* or Right outright; 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-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
* containing block for `position: fixed`, so a bar nested inside would anchor to
* the shell and ride off the bottom of a long page.
*/
useChat();
// A task this conversation started reports its outcome into it. The dock stays
// mounted while collapsed, so a reply that lands then is still read and counted.
useLiveResource("chat", () => void reloadTranscript());
const expanded = dockExpanded;
watch(expanded, setDockOpen, { immediate: true });
// 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,
);
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(() => 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 };
}
// Opening the window never narrows it below the minimised bar.
const minW = Math.min(BAR_W, vw.value - INSET * 2);
return fitRect({ ...layout.value, w: Math.max(layout.value.w, minW) }, 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.
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);
function followViewport(): void {
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;
}
useEventListener(() => window.visualViewport, ["resize", "scroll"], followViewport);
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) {
// A tablet's on-screen keyboard covers the layout viewport's bottom; keep
// the window, and so its composer, in the part left 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 bar = barPlacement(rect, mode.value, vw.value);
return { left: `${bar.x}px`, bottom: `${bar.bottom + keyboard.value}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, swipe down, Escape and Ctrl+/ are the only ways to
// collapse.
watch(isSending, (sending) => {
if (sending) expanded.value = true;
});
function onKeydown(event: KeyboardEvent): void {
// A focused control (the composer dismissing its palette, or the topbar
// search) already handled Escape via preventDefault; collapsing too would
// make that menu impossible to dismiss on its own. A popover portalled out
// of the bar owns Escape by being open, which the flag reports.
if (event.defaultPrevented || event.key !== "Escape" || escapeOwnedByLayer()) return;
expanded.value = false;
}
watch(expanded, (open) => {
if (open) document.addEventListener("keydown", onKeydown);
else document.removeEventListener("keydown", onKeydown);
});
onUnmounted(() => document.removeEventListener("keydown", onKeydown));
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. 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 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);
if (dock.value) observer.observe(dock.value);
window.addEventListener("resize", reserve);
});
onUnmounted(() => {
observer?.disconnect();
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([pinned, mode, pinW], () => {
const root = document.documentElement.style;
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");
});
const MODES: { mode: DockMode; label: string; icon: typeof PanelLeft }[] = [
{ mode: "left", label: "Left", icon: PanelLeft },
{ mode: "float", label: "Float", icon: PictureInPicture2 },
{ mode: "right", label: "Right", icon: PanelRight },
];
const positionOpen = ref(false);
useEscapeLayer(positionOpen);
function setMode(next: DockMode): void {
if (!desktop.value) return;
layout.value = { ...layout.value, mode: next };
expanded.value = true;
}
const dragging = ref(false);
const snapTarget = ref<"left" | "right" | null>(null);
// A resize follows the pointer directly; the position transition would lag it.
const resizing = ref(false);
const header = ref<HTMLElement | null>(null);
const bar = ref<HTMLElement | null>(null);
// The header drags the open window and the bar drags the minimised 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("button, a, input, select, textarea, [role=combobox], [role=separator]") || !!target.closest("[data-move-handle]");
}
// Pointer travel before a press becomes a drag, so a click or a double-click
// on a drag surface never moves the dock.
let drag: { origin: Rect; x0: number; y0: number; moved: boolean; snap: "left" | "right" | null } | null = null;
useDraggable(dock, {
disabled: () => !desktop.value,
onStart: (_, e) => {
if (!e.isPrimary || !onDragSurface(e.target as HTMLElement)) return false;
drag = { origin: { ...winRect.value }, x0: e.clientX, y0: e.clientY, moved: false, snap: null };
},
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;
const next = fitRect({ ...drag.origin, x: drag.origin.x + dx, y: drag.origin.y + dy }, vw.value, vh.value);
layout.value = { ...layout.value, mode: "float", x: next.x, y: next.y, w: next.w, h: next.h };
drag.snap = expanded.value ? snapEdge(e.clientX, vw.value) : null;
snapTarget.value = drag.snap;
},
onEnd: (_, e) => {
if (drag?.moved && e.type === "pointerup" && drag.snap) layout.value = { ...layout.value, mode: drag.snap };
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 compounded 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 dir = (e.target as HTMLElement).closest<HTMLElement>("[data-resize]")?.dataset.resize as ResizeDir | "pin" | undefined;
if (!e.isPrimary || !dir) return false;
resize = { dir, origin: resizeOrigin(), 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: clampWidth(resize.w0 + (mode.value === "left" ? dx : -dx)) };
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
// flick hides the conversation.
usePointerSwipe(header, {
threshold: SWIPE,
onSwipeEnd: (e, direction) => {
if (desktop.value || e.type !== "pointerup" || direction !== "down") return;
// The keyboard is for the composer, which is no longer in front of it.
(document.activeElement as HTMLElement | null)?.blur();
expanded.value = false;
},
});
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 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"]));
// The rectangle a resize starts from. Minimised, the bar can sit at an edge
// rather than at the stored x, so its rendered x and width are the origin, or
// the first move would jump it.
function resizeOrigin(): Rect {
const rect = winRect.value;
if (expanded.value || !dock.value) return rect;
const bar = dock.value.getBoundingClientRect();
return { ...rect, x: bar.left, w: bar.width };
}
function applyResize(origin: Rect, dir: ResizeDir, dx: number, dy: number): void {
const rect = resizeRect(origin, 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 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(resizeOrigin(), dir, dx, dy);
}
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();
layout.value = { ...layout.value, w: clampWidth(layout.value.w + (grow ? 16 : -16)) };
}
</script>
<template>
<div
v-if="snapTarget"
aria-hidden="true"
: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 transition-[left,top,bottom,width,height] duration-200 ease-out motion-reduce:transition-none',
(dragging || resizing) && 'transition-none',
!desktop && 'inset-x-0 bottom-4 flex justify-center px-3 max-md:bottom-2',
// Docked, minimising hides the dock; the topbar button and Ctrl+/ bring
// it back. It stays mounted so the session and a turn in flight survive.
desktop && mode !== 'float' && !expanded && 'hidden',
)"
: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)]',
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',
)"
>
<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', HANDLE_CLASS[dir])"
@keydown="onHandleKey(dir, $event)"
/>
</template>
<div
v-if="desktop && pinned"
role="separator"
aria-orientation="vertical"
aria-label="Resize chat"
tabindex="0"
:aria-valuenow="pinW"
:aria-valuemin="MIN_W"
:aria-valuemax="pinMax"
data-resize="pin"
class="absolute inset-y-0 z-10 w-1.5 cursor-col-resize touch-none hover:bg-primary/30 focus-visible:bg-primary/50"
:class="mode === 'left' ? '-right-0.5' : '-left-0.5'"
@keydown="onPinKey"
/>
<div
v-if="expanded"
ref="header"
:class="cn('touch-none', desktop && 'cursor-grab select-none active:cursor-grabbing')"
@dblclick="togglePin"
>
<ChatBar>
<template v-if="desktop" #start>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none cursor-grab touch-none active:cursor-grabbing"
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>
</template>
<template v-if="desktop" #actions>
<DropdownMenu v-model:open="positionOpen">
<!-- No Tooltip around the trigger: nested in TooltipTrigger the menu
loses its anchor and opens off-screen, as MoreMenu found. -->
<DropdownMenuTrigger as-child>
<Button variant="ghost" size="icon-sm" class="flex-none" aria-label="Chat position" title="Position">
<component :is="MODES.find((m) => m.mode === mode)?.icon ?? PictureInPicture2" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="min-w-36">
<DropdownMenuRadioGroup :model-value="mode" @update:model-value="setMode($event as DockMode)">
<DropdownMenuRadioItem v-for="m in MODES" :key="m.mode" :value="m.mode">
<component :is="m.icon" />{{ m.label }}
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
</template>
<template #end>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none"
aria-label="Hide conversation"
@click="expanded = false"
>
<ChevronDown />
</Button>
</TooltipTrigger>
<TooltipContent>Hide conversation</TooltipContent>
</Tooltip>
</template>
</ChatBar>
</div>
<div
v-if="expanded"
: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 />
</div>
<div ref="bar" class="touch-none" @focusin="expanded = true">
<ChatComposer :open="false" :flat="!expanded">
<template v-if="!expanded && desktop" #start>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="cursor-grab touch-none active:cursor-grabbing"
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>
</template>
<template v-if="!expanded" #actions>
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
:class="cn(unseenCount && 'w-auto gap-1 px-2')"
:aria-label="unseenCount ? `Show conversation, ${unseenCount} new` : 'Show conversation'"
@click="expanded = true"
>
<ChevronUp />
<Badge v-if="unseenCount" variant="default" aria-hidden="true">{{ unseenCount }}</Badge>
</Button>
</TooltipTrigger>
<TooltipContent>Show conversation</TooltipContent>
</Tooltip>
</template>
</ChatComposer>
</div>
</aside>
</div>
</template>