feat(webui): inspect file context in a live graph sidebar (#6562)
* feat(webui): inspect file context in a live graph sidebar * refactor(webui): place preview controls in the shared sidebar header * fix(webui): synchronize npm lockfile for graph dependencies * fix(webui): preserve compacted context and refine graph inspection * fix(context): harden provenance, request usage, and drawer lifecycle * fix(webui): align source skeleton and browser fixtures * perf(context): reuse source analysis and capture request graphs once * perf(webui): compact graph history and render graph motion on canvas * fix(webui): remove redundant context sidebar header * style(webui): clarify context replay icon * perf(webui): pace context replay on an adaptive timeline * feat(webui): briefly reveal labels for new context nodes * fix(webui): reveal new labels only for loaded context files * fix(webui): restart graph animation clock after idle * fix(webui): reveal labels when replay reverses node exit * refactor(context): project file-use facts without retention tracking * refactor(context): observe file reads outside agent execution * fix(webui): animate context sidebar closing * refactor(context): remove unused graph and usage panel code * refactor(context): isolate prompt observation from execution metadata * fix(webui): clarify cache rate and show context token usage * fix(webui): abbreviate context token counts in thousands * fix(webui): omit token unit from context usage details * fix(webui): restore large source preview highlighting and panel elevation * fix(webui): distinguish modifier scrolling from keyboard focus * fix(webui): align preview tab and panel corner radii * fix(webui): attach file tabs to the header divider * fix(webui): use one action to toggle file preview mode * fix(webui): use hover hint for context replay * fix(webui): share composer layout between graph and file sidebars * fix(webui): align sidebar bottom with composer surface * fix(webui): restore mobile graph drawing and touch file details * test(webui): align legacy cache assertions with current label * perf(context): retain source analysis and bound graph animation work * style(webui): add light elevation to user messages * test(webui): await lazy graph scene before replay assertions * fix(webui): align preview skeleton and browser contracts
This commit is contained in:
1 parent
2b44088413
commit
519ed81132
132 files changed
+4673
-1159
No files matched your search
@@ -59,7 +59,7 @@ const LazyHighlightedCode = lazy(async () => {
|
||||
customStyle={{
|
||||
background: "transparent",
|
||||
margin: 0,
|
||||
padding: chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",
|
||||
padding: viewportHighlight ? "0.75rem 1rem 0.75rem 0.5rem" : chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",
|
||||
fontFamily: "inherit",
|
||||
fontSize: "inherit",
|
||||
lineHeight: "inherit",
|
||||
@@ -134,7 +134,7 @@ function CodeTextBlock({
|
||||
showLineNumbers ? "whitespace-pre" : "whitespace-pre-wrap",
|
||||
chrome === "default"
|
||||
? "py-4 pl-5 pr-14"
|
||||
: compact ? "px-4 py-3" : "p-3",
|
||||
: compact ? "py-3 pl-2 pr-4" : "p-3",
|
||||
className,
|
||||
)}
|
||||
data-testid={testId}
|
||||
@@ -143,7 +143,7 @@ function CodeTextBlock({
|
||||
{showLineNumbers && compact ? (
|
||||
<span className="flex min-w-max">
|
||||
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
|
||||
style={{ minWidth: "4.25em" }}>{lines.map((_, index) => index + 1).join("\n")}</span>
|
||||
style={{ minWidth: `calc(${String(lines.length).length}ch + 1.15rem)` }}>{lines.map((_, index) => index + 1).join("\n")}</span>
|
||||
<span>{renderText(code)}</span>
|
||||
</span>
|
||||
) : showLineNumbers ? (
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useState } from "react";
|
||||
import { surfaceFocusProps } from "@/lib/surface-focus";
|
||||
import { useContext, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { SidebarPanelActionsContext } from "@/components/ui/sidebar-panel";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
|
||||
import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { MarkdownText } from "@/components/MarkdownText";
|
||||
import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
|
||||
import type { FilePreviewPayload } from "@/lib/types";
|
||||
@@ -23,6 +25,7 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const actionsHost = useContext(SidebarPanelActionsContext);
|
||||
const [mode, setMode] = useState<"preview" | "source">("preview");
|
||||
const previewKind = fileKindForPath(path);
|
||||
const markdown = state.status === "ready" && state.payload.kind !== "image"
|
||||
@@ -38,17 +41,18 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
|
||||
: state.message ?? t("filePreview.failed", { defaultValue: "Could not preview this file." }))
|
||||
: null;
|
||||
|
||||
const modeLabel = t(mode === "preview" ? "filePreview.source" : "filePreview.preview");
|
||||
const modeControl = <button type="button" onClick={() => setMode(value => value === "preview" ? "source" : "preview")}
|
||||
className="touch-target inline-flex h-8 items-center justify-center rounded-control px-3 text-xs text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
{modeLabel}
|
||||
</button>;
|
||||
|
||||
return (
|
||||
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
|
||||
{markdown ? (
|
||||
<div className="flex shrink-0 items-center justify-end px-4 py-2">
|
||||
<SegmentedControl value={mode} onChange={setMode} ariaLabel={t("filePreview.displayMode")}
|
||||
options={[{ value: "preview", label: t("filePreview.preview") }, { value: "source", label: t("filePreview.source") }]}
|
||||
itemClassName="px-3 [@media(pointer:coarse)]:min-h-9" />
|
||||
</div>
|
||||
) : null}
|
||||
{markdown && (actionsHost ? createPortal(modeControl, actionsHost) : <div className="flex shrink-0 justify-end px-4 py-2">{modeControl}</div>)}
|
||||
<div key={mode} data-file-preview-scroll tabIndex={0}
|
||||
className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">
|
||||
{...surfaceFocusProps}
|
||||
className="min-h-0 flex-1 overflow-auto outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring/60">
|
||||
{state.status === "loading" ? (
|
||||
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
|
||||
className="h-full" aria-busy="true">
|
||||
@@ -57,9 +61,9 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
|
||||
{previewKind === "image" ? <div className="flex h-full items-center justify-center p-4">
|
||||
<div className="aspect-[8/5] w-full max-w-sm rounded-compact bg-muted/40" />
|
||||
</div> : <>
|
||||
{previewKind === "markdown" ? <div className="flex justify-end px-4 py-2">
|
||||
<div className="inline-flex min-h-8 items-center gap-1 rounded-full bg-muted/40 p-1 text-ui-label">
|
||||
{[t("filePreview.preview"), t("filePreview.source")].map((label) => <span key={label} className="invisible px-3 py-1 [@media(pointer:coarse)]:min-h-9">{label}</span>)}
|
||||
{previewKind === "markdown" && !actionsHost ? <div className="flex justify-end px-4 py-2">
|
||||
<div className="touch-target inline-flex h-8 items-center rounded-control bg-muted/40 px-3 text-xs">
|
||||
<span className="invisible">{modeLabel}</span>
|
||||
</div>
|
||||
</div> : null}
|
||||
{previewKind === "markdown" && mode === "preview" ? <div className="markdown-content px-5 pb-6 pt-1 sm:px-6">
|
||||
@@ -67,10 +71,10 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
|
||||
{["w-full", "w-5/6", "w-3/4"].map((width) => <div key={width} className="mt-4 flex h-[1lh] items-center">
|
||||
<div className={`h-3 rounded bg-muted/40 ${width}`} />
|
||||
</div>)}
|
||||
</div> : <div className="px-4 py-3 font-mono text-code">
|
||||
</div> : <div className="py-3 pl-2 pr-4 font-mono text-code">
|
||||
{["w-2/3", "w-full", "w-5/6", "w-3/4", "w-1/2", "w-3/5"].map((width) => <div key={width} className="flex h-[1lh] items-center">
|
||||
<div className="w-[4.25em] shrink-0 pr-[1.15rem]"><div className="ml-auto h-3 w-2 rounded bg-muted/40" /></div>
|
||||
<div className={`h-3 max-w-[calc(100%-4.25em)] rounded bg-muted/40 ${width}`} />
|
||||
<div className="w-[calc(1ch+1.15rem)] shrink-0 pr-[1.15rem]"><div className="ml-auto h-3 w-2 rounded bg-muted/40" /></div>
|
||||
<div className={`h-3 max-w-[calc(100%-1ch-1.15rem)] rounded bg-muted/40 ${width}`} />
|
||||
</div>)}
|
||||
</div>}
|
||||
</>}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { surfaceFocusProps } from "@/lib/surface-focus";
|
||||
import {
|
||||
Children,
|
||||
isValidElement,
|
||||
@@ -686,7 +687,7 @@ export default function MarkdownTextRenderer({
|
||||
void _node;
|
||||
return (
|
||||
<div
|
||||
data-testid="markdown-data-table"
|
||||
data-testid="markdown-data-table" {...surfaceFocusProps}
|
||||
data-table-kind="data"
|
||||
role="region"
|
||||
tabIndex={0}
|
||||
@@ -694,7 +695,7 @@ export default function MarkdownTextRenderer({
|
||||
className={cn(
|
||||
"not-prose mb-5 mt-3 w-full max-w-full overflow-x-auto rounded-lg",
|
||||
"border border-border/65 bg-muted/20",
|
||||
"overscroll-x-contain focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
"overscroll-x-contain outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-ring",
|
||||
)}
|
||||
>
|
||||
<table
|
||||
@@ -703,9 +704,9 @@ export default function MarkdownTextRenderer({
|
||||
"[&_thead]:bg-muted/45 [&_thead]:text-muted-foreground",
|
||||
"[&_th]:border-b [&_th]:border-border/65 [&_th]:px-3 [&_th]:py-2",
|
||||
"[&_th]:text-left [&_th]:font-medium [&_th]:whitespace-normal",
|
||||
"[&_th]:[overflow-wrap:anywhere]",
|
||||
"[&_th]:[overflow-wrap:normal]",
|
||||
"[&_td]:border-b [&_td]:border-border/55 [&_td]:px-3 [&_td]:py-2",
|
||||
"[&_td]:whitespace-normal [&_td]:[overflow-wrap:anywhere]",
|
||||
"[&_td]:whitespace-normal [&_td]:[overflow-wrap:normal]",
|
||||
"[&_th:not(:last-child)]:border-r [&_th:not(:last-child)]:border-border/45",
|
||||
"[&_td:not(:last-child)]:border-r [&_td:not(:last-child)]:border-border/45",
|
||||
"[&_tbody_tr:last-child_td]:border-b-0",
|
||||
|
||||
@@ -503,7 +503,7 @@ export function MessageBubble({
|
||||
"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",
|
||||
temporary
|
||||
? "border border-dashed border-muted-foreground/40 bg-transparent"
|
||||
: "bg-secondary/70",
|
||||
: "user-message-surface bg-secondary/70",
|
||||
)}
|
||||
>
|
||||
{messageText}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react";
|
||||
import { surfaceFocusProps } from "@/lib/surface-focus";
|
||||
import { useEffect, useId, useRef, type PointerEvent, type ReactNode } from "react";
|
||||
import { SidebarPanel } from "@/components/ui/sidebar-panel";
|
||||
import { PanelRightClose, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FileReferenceIcon, fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
|
||||
@@ -6,6 +8,7 @@ import { FileActions } from "@/components/FileActions";
|
||||
import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/components/SidebarSelectionHighlight";
|
||||
import type { PreviewTab } from "@/hooks/useFilePreviewState";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface";
|
||||
|
||||
/** One stable sidebar shell: switching targets never replays its opening animation. */
|
||||
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: {
|
||||
@@ -21,14 +24,9 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const [entered, setEntered] = useState(false);
|
||||
const buttons = useRef(new Map<string, HTMLButtonElement>());
|
||||
const tabList = useRef<HTMLDivElement>(null);
|
||||
const pendingFocus = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
const frame = requestAnimationFrame(() => setEntered(true));
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const revealActiveTab = () => buttons.current.get(activeId)?.parentElement?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
|
||||
revealActiveTab();
|
||||
@@ -48,29 +46,18 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
|
||||
onCloseTab(tab.id);
|
||||
};
|
||||
const iconButton = "touch-target inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
|
||||
return <aside aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
|
||||
style={{
|
||||
"--file-preview-width": `${width}px`,
|
||||
"--file-preview-slot-width": !entered || isClosing ? "0px" : `${width}px`,
|
||||
"--file-preview-mobile-width": !entered || isClosing ? "0px" : "100%",
|
||||
} as CSSProperties}
|
||||
className={cn("file-preview-pane absolute inset-y-0 right-0 z-30 w-[var(--file-preview-mobile-width)] overflow-hidden transition-[width] duration-300 ease-out motion-reduce:transition-none", isClosing && "pointer-events-none")}
|
||||
>
|
||||
<div className={cn("file-preview-content absolute inset-y-0 right-0 flex w-[100cqw] flex-col border-l border-border/60 bg-background pb-[env(safe-area-inset-bottom)] transition-opacity duration-200 motion-reduce:transition-none", !entered || isClosing ? "opacity-0" : "opacity-100")}>
|
||||
<button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}
|
||||
className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">
|
||||
<span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
|
||||
</button>
|
||||
<div className="flex min-h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2">
|
||||
return <SidebarPanel aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
|
||||
width={width} isClosing={isClosing} contentClassName={sidePanelSurfaceClassName}
|
||||
header={<>
|
||||
<div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<SidebarSelectionHighlight activeId={activeId} scope="preview-tabs" targetSelector="[data-preview-tab-active]"
|
||||
className="relative isolate flex w-max min-w-full items-center gap-1"
|
||||
highlightClassName="rounded-compact">
|
||||
highlightClassName="rounded-none rounded-t-2xl">
|
||||
{tabs.map((tab, index) => {
|
||||
const selected = tab.id === activeId;
|
||||
const name = splitFilePath(tab.value).name;
|
||||
const item = <div key={tab.id} role="presentation" data-preview-tab-active={selected ? "" : undefined}
|
||||
className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-compact", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>
|
||||
className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-t-2xl", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>
|
||||
<button type="button" role="tab" id={`${id}-tab-${index}`} aria-selected={selected} aria-controls={`${id}-panel`}
|
||||
tabIndex={selected ? 0 : -1} title={tab.value}
|
||||
ref={(node) => { if (node) buttons.current.set(tab.id, node); else buttons.current.delete(tab.id); }}
|
||||
@@ -87,7 +74,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
|
||||
onSelect(tabs[next].id);
|
||||
buttons.current.get(tabs[next].id)?.focus();
|
||||
}}
|
||||
className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-compact pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
|
||||
className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-t-2xl pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
|
||||
<span aria-hidden className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
|
||||
<FileReferenceIcon kind={fileKindForPath(tab.value)} className="size-3.5" />
|
||||
</span>
|
||||
@@ -106,11 +93,14 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
|
||||
{tabs.length > 1 ? <button type="button" className={iconButton} onClick={onClose} aria-label={t("previewTabs.closeAll")} title={t("previewTabs.closeAll")}>
|
||||
<PanelRightClose className="size-4" aria-hidden />
|
||||
</button> : null}
|
||||
</div>
|
||||
<div role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}
|
||||
className="flex min-h-0 flex-1 flex-col focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
|
||||
</>}>
|
||||
<button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}
|
||||
className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">
|
||||
<span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
|
||||
</button>
|
||||
<div role="tabpanel" {...surfaceFocusProps} id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}
|
||||
className="flex min-h-0 flex-1 flex-col outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</aside>;
|
||||
</SidebarPanel>;
|
||||
}
|
||||
@@ -10,15 +10,16 @@ function textOf(node: Row): string {
|
||||
return node.type === "text" ? String(node.value ?? "") : (node.children ?? []).map(textOf).join("");
|
||||
}
|
||||
|
||||
const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted }: RowsProps & {
|
||||
const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted, lineNumberWidth }: RowsProps & {
|
||||
text: string;
|
||||
start: number;
|
||||
highlighted: boolean;
|
||||
lineNumberWidth: string;
|
||||
}) {
|
||||
return (
|
||||
<span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max">
|
||||
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
|
||||
style={{ minWidth: "4.25em" }}>
|
||||
style={{ minWidth: lineNumberWidth }}>
|
||||
{rows.map((_, index) => start + index + 1).join("\n")}
|
||||
</span>
|
||||
<span data-highlighted={highlighted}>
|
||||
@@ -78,7 +79,8 @@ export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsProp
|
||||
return (
|
||||
<span ref={rootRef} className="block min-w-max" data-testid="viewport-code-rows">
|
||||
{chunks.map((chunk, index) => <CodeChunk key={chunk.start} {...chunk}
|
||||
stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)} />)}
|
||||
stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)}
|
||||
lineNumberWidth={`calc(${String(rows.length).length}ch + 1.15rem)`} />)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -388,8 +388,8 @@ function SkillDetailSheet({
|
||||
"sm:right-3 sm:top-3",
|
||||
)}
|
||||
className={cn(
|
||||
"w-full max-w-none gap-0 overflow-hidden border-l-0 p-0",
|
||||
"sm:w-[min(34rem,calc(100vw-1rem))] sm:max-w-none sm:border-l",
|
||||
"w-[calc(100vw-1rem)] max-w-none gap-0 p-0",
|
||||
"sm:w-[min(34rem,calc(100vw-1rem))] sm:max-w-none",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
|
||||
@@ -1,82 +1,72 @@
|
||||
import { Fragment, useCallback, useMemo, useRef, useState, type PointerEvent, type ReactNode } from "react";
|
||||
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
|
||||
import { FloatingPortalContext } from "@/components/ui/floating-portal";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { formatCompactTokenCount } from "@/lib/format";
|
||||
import { formatTurnLatency } from "@/lib/format-time";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import { SidebarPanel } from "@/components/ui/sidebar-panel";
|
||||
import { ContextInspector } from "./ContextInspector";
|
||||
import type { ContextSnapshot } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface ComposerContextUsage {
|
||||
estimated?: boolean;
|
||||
contextTokens: number;
|
||||
contextWindowTokens?: number;
|
||||
}
|
||||
|
||||
export interface ComposerRoundUsage {
|
||||
id: string;
|
||||
timestamp: number;
|
||||
inputTokens: number;
|
||||
outputTokens?: number;
|
||||
cachedTokens?: number;
|
||||
estimatedTokens?: number;
|
||||
generationMs?: number;
|
||||
}
|
||||
|
||||
interface NormalizedRoundUsage extends ComposerRoundUsage {
|
||||
cachedTokens?: number;
|
||||
outputTokens: number;
|
||||
}
|
||||
|
||||
function normalizeRounds(
|
||||
rounds: readonly ComposerRoundUsage[],
|
||||
): NormalizedRoundUsage[] {
|
||||
return rounds
|
||||
.filter((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0)
|
||||
.map((round) => ({
|
||||
...round,
|
||||
inputTokens: Math.max(0, round.inputTokens),
|
||||
outputTokens: Number.isFinite(round.outputTokens)
|
||||
? Math.max(0, round.outputTokens ?? 0)
|
||||
: 0,
|
||||
...(Number.isFinite(round.cachedTokens)
|
||||
? { cachedTokens: Math.min(round.inputTokens, Math.max(0, round.cachedTokens ?? 0)) }
|
||||
: {}),
|
||||
}));
|
||||
}
|
||||
|
||||
export function ComposerUsagePopover({
|
||||
context,
|
||||
rounds,
|
||||
snapshots = [],
|
||||
onOpenFile,
|
||||
showLabel = false,
|
||||
compactLabel = false,
|
||||
bottomSheet = false,
|
||||
sidebarHost,
|
||||
triggerHost,
|
||||
open: controlledOpen,
|
||||
onOpenChange,
|
||||
}: {
|
||||
context: ComposerContextUsage | null;
|
||||
rounds: readonly ComposerRoundUsage[];
|
||||
snapshots?: readonly ContextSnapshot[];
|
||||
onOpenFile?: (path: string) => void;
|
||||
showLabel?: boolean;
|
||||
compactLabel?: boolean;
|
||||
bottomSheet?: boolean;
|
||||
sidebarHost?: HTMLElement | null;
|
||||
triggerHost?: HTMLElement | null;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const normalizedRounds = useMemo(() => normalizeRounds(rounds), [rounds]);
|
||||
const { t } = useTranslation();
|
||||
const [localOpen, setLocalOpen] = useState(false);
|
||||
const open = controlledOpen ?? localOpen;
|
||||
const interactedOutside = useRef(false);
|
||||
const setOpen = (next: boolean) => { if (next) interactedOutside.current = false; setLocalOpen(next); onOpenChange?.(next); };
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const panelId = useId();
|
||||
const [narrow, setNarrow] = useState(false);
|
||||
useEffect(() => {
|
||||
const measure = () => setNarrow((sidebarHost?.clientWidth ?? window.innerWidth) < 780);
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
if (sidebarHost) observer.observe(sidebarHost);
|
||||
window.addEventListener("resize", measure);
|
||||
return () => { observer.disconnect(); window.removeEventListener("resize", measure); };
|
||||
}, [sidebarHost]);
|
||||
const close = () => { setOpen(false); requestAnimationFrame(() => triggerRef.current?.focus()); };
|
||||
const hasRounds = rounds.some((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0);
|
||||
const hasContext = !!context
|
||||
&& Number.isFinite(context.contextTokens)
|
||||
&& context.contextTokens >= 0
|
||||
&& Number.isFinite(context.contextWindowTokens)
|
||||
&& (context.contextWindowTokens ?? 0) > 0;
|
||||
if (!hasContext && normalizedRounds.length === 0) {
|
||||
if (!open && !hasContext && !hasRounds && !snapshots.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -99,37 +89,21 @@ export function ComposerUsagePopover({
|
||||
? detailsLabel
|
||||
: t("thread.composer.context.tooltip", {
|
||||
defaultValue: "Context {{percent}}%",
|
||||
percent: contextPercentage,
|
||||
percent: `${context?.estimated ? "≈" : ""}${contextPercentage}`,
|
||||
});
|
||||
const triggerLabel = contextPercentage === null
|
||||
? detailsLabel
|
||||
: `${contextDescription}. ${detailsLabel}`;
|
||||
const ringCircumference = 2 * Math.PI * 6;
|
||||
const ringLength = ringCircumference * meterPercentage / 100;
|
||||
const maxInputTokens = Math.max(0, ...normalizedRounds.map((round) => round.inputTokens));
|
||||
const numberFormatter = new Intl.NumberFormat(i18n.language);
|
||||
const percentageFormatter = new Intl.NumberFormat(i18n.language, {
|
||||
style: "percent",
|
||||
maximumFractionDigits: 0,
|
||||
});
|
||||
const roundDateFormatter = new Intl.DateTimeFormat(i18n.language, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
|
||||
const Root = bottomSheet ? Sheet : Popover;
|
||||
const Trigger = bottomSheet ? SheetTrigger : PopoverTrigger;
|
||||
const RoundRoot = bottomSheet ? Popover : Tooltip;
|
||||
const RoundTrigger = bottomSheet ? PopoverTrigger : TooltipTrigger;
|
||||
const RoundContent = bottomSheet ? PopoverContent : TooltipContent;
|
||||
const RoundBar = bottomSheet ? "button" : "span";
|
||||
const showTextLabel = showLabel && (!compactLabel || contextPercentage !== null);
|
||||
const trigger = (
|
||||
<Trigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
ref={triggerRef}
|
||||
onClick={() => setOpen(!open)}
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? panelId : undefined}
|
||||
data-testid="composer-context-usage"
|
||||
aria-label={triggerLabel}
|
||||
className={cn(
|
||||
@@ -184,372 +158,43 @@ export function ComposerUsagePopover({
|
||||
)}
|
||||
{showTextLabel ? (
|
||||
<span aria-hidden className="whitespace-nowrap tabular-nums">
|
||||
{compactLabel && contextPercentage !== null ? `${contextPercentage}%` : contextDescription}
|
||||
{compactLabel && contextPercentage !== null ? `${context?.estimated ? "≈" : ""}${contextPercentage}%` : contextDescription}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
</Trigger>
|
||||
);
|
||||
|
||||
return (
|
||||
<Root open={open} onOpenChange={setOpen}>
|
||||
<TooltipProvider>
|
||||
{bottomSheet ? trigger : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
align="center"
|
||||
sideOffset={8}
|
||||
className="w-fit max-w-[calc(100vw-2rem)] rounded-full border-border/70 px-2.5 py-1 text-xs font-medium shadow-[0_8px_24px_rgba(15,23,42,0.13)]"
|
||||
>
|
||||
<span className="whitespace-nowrap tabular-nums">{contextDescription}</span>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
const triggerWithTooltip = <TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
|
||||
<TooltipContent side="top" className="text-xs">{contextDescription}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>;
|
||||
|
||||
<UsagePanel bottomSheet={bottomSheet} onDismiss={() => setOpen(false)}>
|
||||
<div className="px-4 pb-4 pt-3.5">
|
||||
{contextPercentage !== null ? (
|
||||
<>
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<div className="flex min-w-0 items-baseline gap-2">
|
||||
<span className={cn("shrink-0 font-medium text-foreground", bottomSheet ? "text-sm" : "text-[12px]")}>
|
||||
{t("thread.composer.context.contextTitle", {
|
||||
defaultValue: "Context",
|
||||
})}
|
||||
</span>
|
||||
<span className={cn("truncate tabular-nums text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
|
||||
{formatCompactTokenCount(context!.contextTokens)} / {formatCompactTokenCount(
|
||||
context!.contextWindowTokens!,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<span className={cn("shrink-0 tabular-nums text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
|
||||
{contextPercentage}%
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label={contextDescription}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={contextPercentage}
|
||||
className="mt-2 h-1 overflow-hidden rounded-full bg-muted"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"h-full rounded-full",
|
||||
status === "critical" && "bg-destructive",
|
||||
status === "caution" && "bg-amber-500",
|
||||
status === "normal" && "bg-foreground/45",
|
||||
)}
|
||||
style={{ width: `${contextPercentage}%` }}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{normalizedRounds.length > 0 ? (
|
||||
<>
|
||||
<div className={cn(
|
||||
"flex items-baseline justify-between gap-3",
|
||||
contextPercentage === null ? "mt-0" : "mt-5",
|
||||
)}>
|
||||
<span className={cn("font-medium text-foreground", bottomSheet ? "text-sm" : "text-[12px]")}>
|
||||
{t("thread.composer.context.recentRounds", {
|
||||
defaultValue: "Recent rounds",
|
||||
})}
|
||||
</span>
|
||||
<span className={cn("text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
|
||||
{t("thread.composer.context.inputTrend", {
|
||||
defaultValue: "Input tokens",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t("thread.composer.context.inputTrend", {
|
||||
defaultValue: "Input tokens",
|
||||
})}
|
||||
className="mt-2 flex h-28 items-end gap-1.5 border-b border-border/60"
|
||||
>
|
||||
{normalizedRounds.map((round, index) => {
|
||||
const cachedKnown = typeof round.cachedTokens === "number";
|
||||
const cachedTokens = round.cachedTokens ?? 0;
|
||||
const notReusedTokens = Math.max(0, round.inputTokens - cachedTokens);
|
||||
const cacheHitRate = cachedKnown
|
||||
? percentageFormatter.format(cachedTokens / round.inputTokens)
|
||||
: null;
|
||||
const cachedHeight = cachedKnown
|
||||
? cachedTokens / round.inputTokens * 100
|
||||
: 0;
|
||||
const barHeight = round.inputTokens / maxInputTokens * 108;
|
||||
const timestampLabel = roundDateFormatter.format(round.timestamp);
|
||||
const detailRows = [
|
||||
{
|
||||
key: "input",
|
||||
label: t("thread.composer.context.input", {
|
||||
defaultValue: "Input tokens",
|
||||
}),
|
||||
value: numberFormatter.format(round.inputTokens),
|
||||
},
|
||||
cachedKnown
|
||||
? {
|
||||
key: "cache-hit-rate",
|
||||
label: t("thread.composer.context.cacheHitRate", {
|
||||
defaultValue: "KV cache hit rate",
|
||||
}),
|
||||
value: cacheHitRate!,
|
||||
}
|
||||
: null,
|
||||
{
|
||||
key: "output",
|
||||
label: t("thread.composer.context.output", {
|
||||
defaultValue: "Output tokens",
|
||||
}),
|
||||
value: numberFormatter.format(round.outputTokens),
|
||||
},
|
||||
typeof round.generationMs === "number"
|
||||
? {
|
||||
key: "duration",
|
||||
label: t("thread.composer.context.duration", {
|
||||
defaultValue: "Generation time",
|
||||
}),
|
||||
value: formatTurnLatency(round.generationMs, i18n.language),
|
||||
}
|
||||
: null,
|
||||
].filter((row): row is NonNullable<typeof row> => !!row);
|
||||
const detailNote = (round.estimatedTokens ?? 0) > 0
|
||||
? t("message.usage.estimated", {
|
||||
defaultValue: "Includes estimated usage",
|
||||
})
|
||||
: null;
|
||||
const detailLabel = [
|
||||
timestampLabel,
|
||||
...detailRows.map((row) => `${row.label} ${row.value}`),
|
||||
detailNote,
|
||||
].filter((part): part is string => !!part).join(". ");
|
||||
|
||||
return (
|
||||
<span
|
||||
key={round.id}
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-1 items-end justify-center rounded-sm",
|
||||
bottomSheet && "relative",
|
||||
"opacity-70 transition-opacity hover:opacity-100",
|
||||
index === 0 && "justify-start",
|
||||
normalizedRounds.length > 1
|
||||
&& index === normalizedRounds.length - 1
|
||||
&& "justify-end",
|
||||
index === normalizedRounds.length - 1 && "opacity-100",
|
||||
)}
|
||||
>
|
||||
<RoundRoot>
|
||||
<RoundTrigger asChild>
|
||||
<RoundBar
|
||||
type={bottomSheet ? "button" : undefined}
|
||||
role={bottomSheet ? undefined : "img"}
|
||||
tabIndex={0}
|
||||
aria-label={detailLabel}
|
||||
data-testid="round-usage-bar"
|
||||
className={cn(
|
||||
"flex w-full max-w-7 flex-col overflow-hidden rounded-t-[3px] bg-muted",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
// Let touch users hit the entire column, even when a
|
||||
// round's proportional bar is less than a pixel high.
|
||||
bottomSheet && "before:absolute before:inset-0 before:content-[''] data-[state=open]:ring-2 data-[state=open]:ring-foreground/20",
|
||||
)}
|
||||
style={{ height: `${barHeight}px` }}
|
||||
>
|
||||
{cachedKnown ? (
|
||||
<>
|
||||
{notReusedTokens > 0 ? (
|
||||
<span
|
||||
className="kv-cache-not-reused block w-full"
|
||||
style={{ height: `${100 - cachedHeight}%` }}
|
||||
/>
|
||||
) : null}
|
||||
{cachedTokens > 0 ? (
|
||||
<span
|
||||
className="kv-cache-reused block w-full"
|
||||
style={{ height: `${cachedHeight}%` }}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<span className="block h-full w-full bg-muted-foreground/25" />
|
||||
)}
|
||||
</RoundBar>
|
||||
</RoundTrigger>
|
||||
<RoundContent
|
||||
side="top"
|
||||
align="center"
|
||||
className="max-w-72 px-3 py-2 text-[11px]"
|
||||
{...(bottomSheet ? {
|
||||
"aria-label": timestampLabel,
|
||||
onOpenAutoFocus: (event: Event) => event.preventDefault(),
|
||||
} : {})}
|
||||
>
|
||||
<span
|
||||
className="block font-medium text-foreground"
|
||||
>
|
||||
{timestampLabel}
|
||||
</span>
|
||||
<span className="mt-1 grid grid-cols-[max-content_max-content] gap-x-3 gap-y-0.5">
|
||||
{detailRows.map((row) => (
|
||||
<Fragment key={row.key}>
|
||||
<span className="text-muted-foreground">
|
||||
{row.label}
|
||||
</span>
|
||||
<span className="text-end tabular-nums text-foreground">
|
||||
{row.value}
|
||||
</span>
|
||||
</Fragment>
|
||||
))}
|
||||
</span>
|
||||
{detailNote ? (
|
||||
<span
|
||||
className="mt-1 block text-muted-foreground"
|
||||
>
|
||||
{detailNote}
|
||||
</span>
|
||||
) : null}
|
||||
</RoundContent>
|
||||
</RoundRoot>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
</div>
|
||||
</UsagePanel>
|
||||
</TooltipProvider>
|
||||
</Root>
|
||||
);
|
||||
}
|
||||
|
||||
function UsagePanel({ bottomSheet, onDismiss, children }: {
|
||||
bottomSheet: boolean;
|
||||
onDismiss: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const panelRef = useRef<HTMLDivElement | null>(null);
|
||||
const [panelNode, setPanelNode] = useState<HTMLDivElement | null>(null);
|
||||
const sheetRef = useCallback((node: HTMLDivElement | null) => {
|
||||
panelRef.current = node;
|
||||
setPanelNode(node);
|
||||
}, []);
|
||||
const gesture = useRef<{ pointerId: number; x: number; y: number; time: number } | null>(null);
|
||||
const suppressClick = useRef(false);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const title = t("thread.composer.context.panelTitle", { defaultValue: "Context usage" });
|
||||
const focusPanel = (event: Event) => {
|
||||
event.preventDefault();
|
||||
gesture.current = null;
|
||||
suppressClick.current = false;
|
||||
setOffset(0);
|
||||
setDragging(false);
|
||||
panelRef.current?.focus({ preventScroll: true });
|
||||
};
|
||||
const cancelDrag = (event: PointerEvent<HTMLButtonElement>) => {
|
||||
if (gesture.current?.pointerId !== event.pointerId) return;
|
||||
gesture.current = null;
|
||||
suppressClick.current = true;
|
||||
setDragging(false);
|
||||
setOffset(0);
|
||||
const inspector = <ContextInspector sidebar expandable={!narrow} context={context} rounds={rounds} snapshots={snapshots}
|
||||
onOpenFile={onOpenFile ? (path) => { setOpen(false); onOpenFile(path); } : undefined} />;
|
||||
const onPanelKeyDown = (event: KeyboardEvent<HTMLElement>) => {
|
||||
if (event.key === "Escape" && !event.defaultPrevented) { event.preventDefault(); close(); }
|
||||
};
|
||||
|
||||
if (bottomSheet) {
|
||||
return (
|
||||
<SheetContent
|
||||
ref={sheetRef}
|
||||
side="bottom"
|
||||
aria-describedby={undefined}
|
||||
showCloseButton={false}
|
||||
onOpenAutoFocus={focusPanel}
|
||||
style={{ translate: `0 ${offset}px`, ...(dragging ? { transition: "none" } : {}) }}
|
||||
className={cn(
|
||||
"mx-auto max-h-[60dvh] w-full max-w-md gap-0 rounded-t-3xl border-t border-border/60 p-0 shadow-xl outline-none",
|
||||
"transition-[translate]",
|
||||
"data-[state=open]:duration-300 data-[state=open]:ease-out data-[state=closed]:duration-200 data-[state=closed]:ease-in",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.close")}
|
||||
className="mx-auto flex h-11 w-24 shrink-0 touch-none select-none items-center justify-center rounded-full cursor-grab active:cursor-grabbing focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => {
|
||||
if (event.button !== 0 || !event.isPrimary || gesture.current) return;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
gesture.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, time: event.timeStamp };
|
||||
suppressClick.current = false;
|
||||
setDragging(true);
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
const start = gesture.current;
|
||||
if (!start || start.pointerId !== event.pointerId) return;
|
||||
const dy = event.clientY - start.y;
|
||||
const dx = event.clientX - start.x;
|
||||
if (Math.abs(dy) > 5 || Math.abs(dx) > 5) suppressClick.current = true;
|
||||
setOffset(Math.max(0, dy));
|
||||
}}
|
||||
onPointerUp={(event) => {
|
||||
const start = gesture.current;
|
||||
if (!start || start.pointerId !== event.pointerId) return;
|
||||
gesture.current = null;
|
||||
const dy = Math.max(0, event.clientY - start.y);
|
||||
const dx = Math.abs(event.clientX - start.x);
|
||||
const threshold = Math.max(48, Math.min(96, (panelRef.current?.offsetHeight ?? 320) * 0.3));
|
||||
const elapsed = Math.max(1, event.timeStamp - start.time);
|
||||
const dismiss = dy > dx && (dy >= threshold || (dy > 20 && dy / elapsed > 0.5));
|
||||
suppressClick.current ||= dy > 5 || dx > 5;
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
setDragging(false);
|
||||
if (dismiss) onDismiss();
|
||||
else setOffset(0);
|
||||
}}
|
||||
onPointerCancel={cancelDrag}
|
||||
onLostPointerCapture={cancelDrag}
|
||||
onClick={(event) => {
|
||||
// A completed drag also emits a click; don't close after a snap-back.
|
||||
if (suppressClick.current && event.detail !== 0) {
|
||||
event.preventDefault();
|
||||
suppressClick.current = false;
|
||||
return;
|
||||
}
|
||||
onDismiss();
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true" className="h-1 w-8 rounded-full bg-foreground/15" />
|
||||
</button>
|
||||
<div className="shrink-0 px-5 pb-2">
|
||||
<SheetTitle className="text-base font-medium">{title}</SheetTitle>
|
||||
</div>
|
||||
<div className="min-h-0 overflow-y-auto overscroll-contain px-1 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
|
||||
<FloatingPortalContext.Provider value={panelNode}>
|
||||
{children}
|
||||
</FloatingPortalContext.Provider>
|
||||
</div>
|
||||
</SheetContent>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PopoverContent
|
||||
ref={panelRef}
|
||||
side="top"
|
||||
align="end"
|
||||
sideOffset={10}
|
||||
onOpenAutoFocus={focusPanel}
|
||||
aria-label={title}
|
||||
className="w-[min(22rem,calc(100vw-1.5rem))] p-0"
|
||||
>
|
||||
{children}
|
||||
</PopoverContent>
|
||||
);
|
||||
return <>
|
||||
{triggerHost === undefined ? triggerWithTooltip : triggerHost && createPortal(triggerWithTooltip, triggerHost)}
|
||||
{narrow ? <Dialog open={open} onOpenChange={setOpen} modal={!sidebarHost}>
|
||||
<DialogContent portalContainer={sidebarHost} placement="bottom" id={panelId} aria-describedby={undefined}
|
||||
data-testid="context-sidebar"
|
||||
overlayClassName={cn("context-drawer-backdrop", sidebarHost && "absolute bg-black/25 backdrop-blur-[8px] sm:bg-transparent sm:backdrop-blur-none")}
|
||||
className="context-drawer-panel flex h-[85%] min-h-0 max-w-none flex-col gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))]"
|
||||
onCloseAutoFocus={(event) => { event.preventDefault(); if (!interactedOutside.current) triggerRef.current?.focus({ preventScroll: true }); }}
|
||||
onInteractOutside={(event) => {
|
||||
if (event.target instanceof Node && triggerRef.current?.contains(event.target)) event.preventDefault();
|
||||
else interactedOutside.current = true;
|
||||
}}>
|
||||
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
|
||||
{inspector}
|
||||
</DialogContent>
|
||||
</Dialog> : createPortal(<SidebarPanel open={open} width={420} floating={!sidebarHost} id={panelId}
|
||||
aria-label={t("thread.composer.context.panelTitle")} data-testid="context-sidebar" onKeyDown={onPanelKeyDown}>
|
||||
{inspector}
|
||||
</SidebarPanel>, sidebarHost ?? document.body)}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useReducedMotion } from "motion/react";
|
||||
import { Maximize2, Minimize2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatCompactTokenCount } from "@/lib/format";
|
||||
import { createGraphSimulation, updateGraphSimulation, advanceGraphSimulation, startGraphSettlement, type GraphParticle, type GraphPosition } from "@/lib/context-graph-layout";
|
||||
import type { ContextGraph } from "@/lib/types";
|
||||
import { createGraphPresentation } from "./graph-presentation";
|
||||
import { paintGraph, readGraphPalette, type GraphPalette } from "./graph-canvas";
|
||||
|
||||
const surface = "context-inspector-surface select-none rounded-[20px] bg-card";
|
||||
|
||||
export const ContextGraphScene = memo(function ContextGraphScene({ graph, epoch, expanded, onExpand, onOpenFile, onReady, sidebar = false }: {
|
||||
graph: ContextGraph; epoch?: string; expanded: boolean; onExpand?: () => void; onOpenFile?: (path: string) => void; onReady?: (graph: ContextGraph) => void; sidebar?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const canvas = useRef<HTMLCanvasElement>(null);
|
||||
const paletteProbe = useRef<HTMLSpanElement>(null);
|
||||
const palette = useRef<GraphPalette>();
|
||||
const nodeElements = useRef(new Map<string, HTMLButtonElement>());
|
||||
const focused = useRef<string | null>(null);
|
||||
const positions = useRef(new Map<string, GraphPosition>());
|
||||
const particles = useRef(new Map<string, GraphParticle>());
|
||||
const simulation = useRef<ReturnType<typeof createGraphSimulation>>();
|
||||
const settlement = useRef<ReturnType<typeof startGraphSettlement> | null>(null);
|
||||
const paintedGraph = useRef<ContextGraph>();
|
||||
const [presentation] = useState(createGraphPresentation);
|
||||
const [frame, setFrame] = useState(presentation.frame);
|
||||
const [size, setSize] = useState({ width: 550, height: 300 });
|
||||
const [active, setActive] = useState<string | null>(null);
|
||||
const [hovered, setHovered] = useState<string | null>(null);
|
||||
const currentNodes = useMemo(() => new Map(graph.nodes.map((node) => [node.path, node])), [graph]);
|
||||
const discovered = useMemo(() => new Set(graph.nodes.filter((node) => node.state === "discovered").map((node) => node.path)), [graph]);
|
||||
const selected = active ? currentNodes.get(active) : undefined;
|
||||
const candidate = active ?? hovered;
|
||||
const highlighted = candidate && currentNodes.has(candidate) ? candidate : null;
|
||||
const reducedMotion = !!useReducedMotion();
|
||||
const clock = useRef({ frame: 0, previous: 0, visible: true, geometry: true });
|
||||
const draw = useRef<(time: number) => void>(() => {});
|
||||
const view = useRef({ x: 0, y: 0, k: 1 });
|
||||
const interacted = useRef(false);
|
||||
const fittedSize = useRef("");
|
||||
const layoutKey = useRef("");
|
||||
const pruneEpoch = useRef(false);
|
||||
const previousEpoch = useRef(epoch);
|
||||
const pan = useRef<{ id: number; x: number; y: number } | null>(null);
|
||||
const dragging = useRef<{ id: number; path: string; x: number; y: number; moved: boolean } | null>(null);
|
||||
const restoreNodeFocus = useRef(false);
|
||||
const schedule = useCallback(() => {
|
||||
if (!clock.current.frame && clock.current.visible && !document.hidden) clock.current.frame = requestAnimationFrame((time) => draw.current(time));
|
||||
}, []);
|
||||
const setView = useCallback((next: typeof view.current) => {
|
||||
view.current = next;
|
||||
schedule();
|
||||
}, [schedule]);
|
||||
draw.current = (time) => {
|
||||
const state = clock.current;
|
||||
state.frame = 0;
|
||||
if (!state.visible || document.hidden) return;
|
||||
const elapsed = state.previous ? time - state.previous : 1000 / 60;
|
||||
state.previous = time;
|
||||
const sim = simulation.current;
|
||||
if (settlement.current) {
|
||||
if (!settlement.current()) { schedule(); return; }
|
||||
settlement.current = null; state.geometry = true;
|
||||
}
|
||||
const running = !!sim && (sim.alpha() > sim.alphaMin() || sim.alphaTarget() > 0);
|
||||
if (sim && running && !reducedMotion) { advanceGraphSimulation(sim, elapsed); state.geometry = true; }
|
||||
const change = presentation.advance(elapsed, reducedMotion);
|
||||
if (change.removed) {
|
||||
setFrame(presentation.frame);
|
||||
if (pruneEpoch.current) {
|
||||
const retained = new Set(presentation.frame.nodes.map((node) => node.path));
|
||||
for (const path of positions.current.keys()) if (!retained.has(path)) positions.current.delete(path);
|
||||
}
|
||||
}
|
||||
if (!change.moving) pruneEpoch.current = false;
|
||||
if (state.geometry && sim) for (const particle of sim.nodes()) {
|
||||
const point = positions.current.get(particle.path);
|
||||
if (point) { point.x = particle.x; point.y = particle.y; }
|
||||
else positions.current.set(particle.path, { x: particle.x, y: particle.y });
|
||||
}
|
||||
const bitmap = canvas.current;
|
||||
const context = bitmap?.getContext("2d");
|
||||
if (bitmap && context && palette.current) {
|
||||
// Keep motion within a pixel budget; the final stationary paint restores
|
||||
// native resolution for crisp labels without paying that cost every frame.
|
||||
const ratio = running || change.moving
|
||||
? Math.min(window.devicePixelRatio || 1, 1.5, Math.sqrt(1_000_000 / (size.width * size.height)))
|
||||
: window.devicePixelRatio || 1;
|
||||
const width = Math.round(size.width * ratio), height = Math.round(size.height * ratio);
|
||||
if (bitmap.width !== width || bitmap.height !== height) { bitmap.width = width; bitmap.height = height; }
|
||||
paintGraph(context, presentation.frame, positions.current, view.current, palette.current, highlighted, focused.current,
|
||||
size.width, size.height, ratio, discovered);
|
||||
if (paintedGraph.current !== graph) { paintedGraph.current = graph; onReady?.(graph); }
|
||||
}
|
||||
state.geometry = false;
|
||||
if (change.moving || (running && !reducedMotion)) schedule();
|
||||
// The next animation starts a new clock; idle time must not consume its labels.
|
||||
else state.previous = 0;
|
||||
};
|
||||
useEffect(() => {
|
||||
if (previousEpoch.current === epoch) return;
|
||||
previousEpoch.current = epoch;
|
||||
pruneEpoch.current = true;
|
||||
palette.current?.labels.clear();
|
||||
const retained = new Set(graph.nodes.map((node) => node.path));
|
||||
for (const node of presentation.frame.nodes) retained.add(node.path);
|
||||
for (const path of positions.current.keys()) if (!retained.has(path)) positions.current.delete(path);
|
||||
}, [epoch, graph, presentation]);
|
||||
useEffect(() => {
|
||||
const element = container.current;
|
||||
if (!element) return;
|
||||
const observer = new ResizeObserver(([entry]) => setSize({ width: entry.contentRect.width, height: entry.contentRect.height }));
|
||||
observer.observe(element);
|
||||
const visibility = () => { clock.current.previous = 0; if (document.hidden) { cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; } else schedule(); };
|
||||
document.addEventListener("visibilitychange", visibility);
|
||||
window.addEventListener("resize", schedule);
|
||||
const intersection = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => {
|
||||
// Drawer entry can batch offscreen and onscreen records together. The
|
||||
// newest record owns visibility; the first can leave painting suspended.
|
||||
const entry = entries[entries.length - 1];
|
||||
clock.current.visible = entry.isIntersecting;
|
||||
if (entry.isIntersecting) { clock.current.previous = 0; schedule(); }
|
||||
else { cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; clock.current.previous = 0; }
|
||||
});
|
||||
intersection?.observe(element);
|
||||
return () => { observer.disconnect(); intersection?.disconnect(); document.removeEventListener("visibilitychange", visibility); window.removeEventListener("resize", schedule); cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; simulation.current?.stop(); };
|
||||
}, [schedule]);
|
||||
useEffect(() => {
|
||||
const sim = simulation.current ?? createGraphSimulation(graph, positions.current, size.width, size.height);
|
||||
if (simulation.current) updateGraphSimulation(sim, graph, positions.current, size.width, size.height);
|
||||
simulation.current = sim.stop();
|
||||
particles.current = new Map(sim.nodes().map((node) => [node.path, node]));
|
||||
const nextLayout = JSON.stringify([graph.nodes.map((node) => node.path), graph.edges, size]);
|
||||
settlement.current = reducedMotion && (layoutKey.current !== nextLayout || sim.alpha() > sim.alphaMin()) ? startGraphSettlement(sim) : null;
|
||||
if (!reducedMotion && layoutKey.current !== nextLayout) sim.alpha(Math.max(sim.alpha(), 0.3));
|
||||
layoutKey.current = nextLayout;
|
||||
clock.current.geometry = true;
|
||||
const key = `${size.width}:${size.height}`;
|
||||
if (!interacted.current && graph.nodes.length && fittedSize.current !== key) {
|
||||
const radius = Math.sqrt(graph.nodes.length * (60 * 0.36) ** 2 / Math.PI);
|
||||
const k = Math.max(0.01, Math.min(1, (size.width - 100) / Math.max(1, radius * 6), (size.height - 80) / Math.max(1, radius * 6)));
|
||||
setView({ k, x: size.width / 2 * (1 - k), y: size.height / 2 * (1 - k) });
|
||||
fittedSize.current = key;
|
||||
}
|
||||
schedule();
|
||||
}, [graph, size, reducedMotion, schedule, setView]);
|
||||
useEffect(() => {
|
||||
setActive((path) => path && currentNodes.has(path) ? path : null);
|
||||
setHovered((path) => path && currentNodes.has(path) ? path : null);
|
||||
}, [currentNodes]);
|
||||
useEffect(() => {
|
||||
setFrame(presentation.update(graph, highlighted));
|
||||
schedule();
|
||||
}, [graph, highlighted, presentation, schedule]);
|
||||
useLayoutEffect(() => { clock.current.geometry = true; schedule(); }, [frame, schedule]);
|
||||
useEffect(() => {
|
||||
const element = container.current;
|
||||
if (!element) return;
|
||||
const wheel = (event: WheelEvent) => {
|
||||
event.preventDefault(); interacted.current = true;
|
||||
const rect = element.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left, y = event.clientY - rect.top, old = view.current;
|
||||
const k = Math.max(0.25, Math.min(4, old.k * Math.exp(-event.deltaY * 0.002)));
|
||||
setView({ k, x: x - (x - old.x) * k / old.k, y: y - (y - old.y) * k / old.k });
|
||||
setActive(null);
|
||||
};
|
||||
element.addEventListener("wheel", wheel, { passive: false });
|
||||
return () => element.removeEventListener("wheel", wheel);
|
||||
}, [setView]);
|
||||
const anchor = useRef({ getBoundingClientRect: () => new DOMRect() });
|
||||
anchor.current.getBoundingClientRect = () => {
|
||||
const rect = container.current?.getBoundingClientRect(), point = active ? positions.current.get(active) : undefined;
|
||||
return new DOMRect((rect?.x ?? 0) + (point?.x ?? 0) * view.current.k + view.current.x - 22,
|
||||
(rect?.y ?? 0) + (point?.y ?? 0) * view.current.k + view.current.y - 22, 44, 44);
|
||||
};
|
||||
const endDrag = (id: number, cancelled: boolean) => {
|
||||
const drag = dragging.current;
|
||||
if (!drag || drag.id !== id) return;
|
||||
const particle = particles.current.get(drag.path);
|
||||
if (particle) {
|
||||
if (particle.fx != null) particle.x = particle.fx;
|
||||
if (particle.fy != null) particle.y = particle.fy;
|
||||
particle.fx = null; particle.fy = null;
|
||||
clock.current.geometry = true;
|
||||
}
|
||||
simulation.current?.alphaTarget(0);
|
||||
if (!cancelled && !drag.moved) setActive((path) => path === drag.path ? null : drag.path);
|
||||
dragging.current = null;
|
||||
schedule();
|
||||
};
|
||||
const nodeAt = (clientX: number, clientY: number, radius: number) => {
|
||||
const rect = container.current?.getBoundingClientRect();
|
||||
if (!rect) return null;
|
||||
const x = clientX - rect.left, y = clientY - rect.top;
|
||||
let closest: string | null = null;
|
||||
let distance = Infinity;
|
||||
for (let index = presentation.frame.nodes.length - 1; index >= 0; index--) {
|
||||
const node = presentation.frame.nodes[index], point = positions.current.get(node.path);
|
||||
if (!point || !currentNodes.has(node.path)) continue;
|
||||
const candidateDistance = Math.hypot(point.x * view.current.k + view.current.x - x, point.y * view.current.k + view.current.y - y);
|
||||
if (candidateDistance <= Math.max(radius, node.radius) && candidateDistance < distance) { closest = node.path; distance = candidateDistance; }
|
||||
}
|
||||
return closest;
|
||||
};
|
||||
useLayoutEffect(() => {
|
||||
const update = () => { if (paletteProbe.current) palette.current = readGraphPalette(paletteProbe.current); schedule(); };
|
||||
update();
|
||||
const observer = new MutationObserver(update);
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style"] });
|
||||
return () => observer.disconnect();
|
||||
}, [schedule]);
|
||||
const controls = useMemo(() => (<div className="sr-only">
|
||||
{graph.nodes.map((node) => <button key={node.path} type="button" data-context-node={node.path} aria-label={node.name} aria-expanded={active === node.path} aria-haspopup="dialog"
|
||||
ref={(element) => { if (element) nodeElements.current.set(node.path, element); else nodeElements.current.delete(node.path); }}
|
||||
onFocus={(e) => { focused.current = e.currentTarget.matches(":focus-visible") ? node.path : null; setHovered(node.path); schedule(); }}
|
||||
onKeyDown={() => { focused.current = node.path; schedule(); }}
|
||||
onBlur={() => { focused.current = null; setHovered(null); schedule(); }}
|
||||
onClick={() => setActive((path) => path === node.path ? null : node.path)}>{node.name}</button>)}
|
||||
</div>), [graph.nodes, active, schedule]);
|
||||
return <div ref={container} className={cn(surface, "relative isolate overflow-clip touch-none cursor-grab active:cursor-grabbing", sidebar ? "min-h-0 flex-1" : expanded ? "h-[min(65dvh,600px)]" : "h-[300px]")}
|
||||
onPointerDown={(e) => {
|
||||
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
|
||||
if (e.button !== 0 || !e.isPrimary || (e.target instanceof Element && e.target.closest("button"))) return;
|
||||
// Keep the node's managed focus. Touch compatibility mouse events would
|
||||
// otherwise focus the drawer and immediately dismiss its node popover.
|
||||
e.preventDefault();
|
||||
interacted.current = true;
|
||||
const path = nodeAt(e.clientX, e.clientY, e.pointerType === "mouse" ? 12 : 22);
|
||||
if (path) {
|
||||
nodeElements.current.get(path)?.focus({ preventScroll: true });
|
||||
dragging.current = { id: e.pointerId, path, x: e.clientX, y: e.clientY, moved: false };
|
||||
pan.current = null;
|
||||
} else { pan.current = { id: e.pointerId, x: e.clientX, y: e.clientY }; setActive(null); }
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
}}
|
||||
onPointerMove={(e) => {
|
||||
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
|
||||
const drag = dragging.current;
|
||||
if (drag && drag.id === e.pointerId) {
|
||||
const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
|
||||
if (!drag.moved && Math.hypot(dx, dy) < 5) return;
|
||||
drag.moved = true; drag.x = e.clientX; drag.y = e.clientY; setActive(null); setHovered(drag.path);
|
||||
const particle = particles.current.get(drag.path);
|
||||
if (particle) {
|
||||
particle.fx = (particle.fx ?? particle.x) + dx / view.current.k; particle.fy = (particle.fy ?? particle.y) + dy / view.current.k;
|
||||
if (reducedMotion) { particle.x = particle.fx; particle.y = particle.fy; clock.current.geometry = true; }
|
||||
else simulation.current?.alphaTarget(0.25);
|
||||
schedule();
|
||||
}
|
||||
} else if (pan.current?.id === e.pointerId) {
|
||||
const old = view.current, previous = pan.current;
|
||||
setView({ ...old, x: old.x + e.clientX - previous.x, y: old.y + e.clientY - previous.y });
|
||||
pan.current = { id: e.pointerId, x: e.clientX, y: e.clientY };
|
||||
} else if (e.pointerType === "mouse") setHovered(nodeAt(e.clientX, e.clientY, 12));
|
||||
}}
|
||||
onPointerLeave={() => { if (!dragging.current) setHovered(null); }}
|
||||
onPointerUp={(e) => { endDrag(e.pointerId, false); if (pan.current?.id === e.pointerId) pan.current = null; }}
|
||||
onPointerCancel={(e) => { endDrag(e.pointerId, true); if (pan.current?.id === e.pointerId) pan.current = null; }}
|
||||
onLostPointerCapture={(e) => { endDrag(e.pointerId, true); if (pan.current?.id === e.pointerId) pan.current = null; }}
|
||||
onDoubleClick={(e) => {
|
||||
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
|
||||
if ((e.target instanceof Element && e.target.closest("button")) || nodeAt(e.clientX, e.clientY, 22)) return;
|
||||
const points = [...particles.current.values()];
|
||||
if (!points.length) return;
|
||||
const xs = points.map((p) => p.x), ys = points.map((p) => p.y);
|
||||
const left = Math.min(...xs), right = Math.max(...xs), top = Math.min(...ys), bottom = Math.max(...ys);
|
||||
const k = Math.max(0.01, Math.min(1, (size.width - 140) / Math.max(1, right - left), (size.height - 110) / Math.max(1, bottom - top)));
|
||||
interacted.current = false; setView({ k, x: size.width / 2 - (left + right) / 2 * k, y: (size.height + 22) / 2 - (top + bottom) / 2 * k });
|
||||
}}>
|
||||
<span ref={paletteProbe} aria-hidden className="invisible absolute bg-background text-muted-foreground" />
|
||||
{onExpand && <button type="button" onClick={onExpand} aria-label={t(expanded ? "thread.composer.context.collapse" : "thread.composer.context.expand")}
|
||||
className="absolute right-2 top-2 z-10 flex size-9 items-center justify-center rounded-full bg-background/90 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
{expanded ? <Minimize2 size={15} /> : <Maximize2 size={15} />}
|
||||
</button>}
|
||||
{!graph.nodes.length && !frame.nodes.length && <p className="absolute inset-0 flex items-center justify-center px-6 text-center text-xs text-muted-foreground">{t("thread.composer.context.noFiles")}</p>}
|
||||
<canvas ref={canvas} aria-hidden="true" className="absolute inset-0 size-full" />
|
||||
{controls}
|
||||
<Popover open={!!selected} onOpenChange={(open) => { if (!open) setActive(null); }}>
|
||||
<PopoverAnchor virtualRef={anchor} />
|
||||
{selected && <PopoverContent updatePositionStrategy="always" side="bottom" sideOffset={12} collisionPadding={12} onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onEscapeKeyDown={() => { restoreNodeFocus.current = true; }}
|
||||
onCloseAutoFocus={(e) => { e.preventDefault(); if (restoreNodeFocus.current) nodeElements.current.get(selected.path)?.focus(); restoreNodeFocus.current = false; }} onInteractOutside={(e) => { if (e.target instanceof Element && container.current?.contains(e.target) && e.target.closest("[data-context-node],canvas")) e.preventDefault(); }} className="flex w-auto select-none items-center gap-4 rounded-xl px-3 py-2.5 font-sans text-ui-label">
|
||||
<span className="text-muted-foreground">{t(selected.state === "loaded" ? "thread.composer.context.loaded" : "thread.composer.context.unloaded")}</span>
|
||||
{selected.state === "loaded" && <span className="tabular-nums text-muted-foreground">{t("thread.composer.context.estimatedNodeTokens", { value: formatCompactTokenCount(selected.tokens) })}</span>}
|
||||
{onOpenFile && <button type="button" className="min-h-8 font-sans text-ui-label text-orange-600 dark:text-orange-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" onClick={() => onOpenFile(selected.path)}>{t("thread.composer.context.openFile")}</button>}
|
||||
</PopoverContent>}
|
||||
</Popover>
|
||||
</div>;
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { lazy, Suspense, useCallback, useEffect, useId, useRef, useState } from "react";
|
||||
import { LayoutGroup, motion, useReducedMotion } from "motion/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatTurnLatency } from "@/lib/format-time";
|
||||
import type { ContextGraph, ContextSnapshot } from "@/lib/types";
|
||||
import type { ComposerContextUsage, ComposerRoundUsage } from "./ComposerUsagePopover";
|
||||
|
||||
import { ContextReplayButton } from "./ContextReplayButton";
|
||||
|
||||
const ContextGraphScene = lazy(() => import("./ContextGraphScene").then(module => ({ default: module.ContextGraphScene })));
|
||||
|
||||
const EMPTY_GRAPH: ContextGraph = { nodes: [], edges: [] };
|
||||
const surface = "context-inspector-surface select-none rounded-[20px] bg-card";
|
||||
|
||||
export function ContextInspector({ context, rounds, snapshots, onOpenFile, sidebar = false, expandable = true }: {
|
||||
context: ComposerContextUsage | null; rounds: readonly ComposerRoundUsage[];
|
||||
snapshots: readonly ContextSnapshot[]; onOpenFile?: (path: string) => void; sidebar?: boolean; expandable?: boolean;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const layoutId = useId();
|
||||
const reducedMotion = useReducedMotion();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [replay, setReplay] = useState<{ frames: readonly ContextSnapshot[]; index: number; startedAt: number; interval: number } | null>(null);
|
||||
const [readyGraph, setReadyGraph] = useState<ContextGraph | null>(null);
|
||||
const [meterHover, setMeterHover] = useState(false);
|
||||
const epoch = snapshots[0]?.id;
|
||||
useEffect(() => { setReplay(null); }, [epoch]);
|
||||
useEffect(() => {
|
||||
if (!replay || readyGraph !== replay.frames[replay.index].graph) return;
|
||||
// Keep a shared timeline instead of adding rendering time to every step.
|
||||
// Advance only after painting each snapshot, even when catching up.
|
||||
const remaining = replay.startedAt + (replay.index + 1) * replay.interval - performance.now();
|
||||
const timer = window.setTimeout(() => setReplay((current) => current && current.index + 1 < current.frames.length
|
||||
? { ...current, index: current.index + 1 } : null), Math.max(0, remaining));
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [replay, readyGraph]);
|
||||
const snapshot = replay ? replay.frames[replay.index] : snapshots.at(-1);
|
||||
const latestRound = rounds.at(-1);
|
||||
const tokens = snapshot ? snapshot.estimatedTokens ?? snapshot.usage?.context_tokens ?? snapshot.usage?.prompt_tokens : context?.contextTokens;
|
||||
const estimated = snapshot?.estimatedTokens !== undefined || (!snapshot?.usage && context?.estimated);
|
||||
const windowTokens = snapshot?.contextWindowTokens ?? context?.contextWindowTokens;
|
||||
const tokenNumbers = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 1 });
|
||||
const hasTokenUsage = tokens !== undefined || !!windowTokens;
|
||||
const used = tokens !== undefined && windowTokens ? Math.min(100, tokens / windowTokens * 100) : null;
|
||||
const cached = snapshot ? snapshot.usage?.cached_tokens : latestRound?.cachedTokens;
|
||||
const input = snapshot ? snapshot.usage?.prompt_tokens : latestRound?.inputTokens;
|
||||
const cachedWidth = cached !== undefined && windowTokens ? Math.min(used ?? 0, cached / windowTokens * 100) : 0;
|
||||
const duration = snapshot ? snapshot.usage?.generation_ms : latestRound?.generationMs;
|
||||
const toggleExpanded = useCallback(() => setExpanded((value) => !value), []);
|
||||
const openFileCallback = useRef(onOpenFile);
|
||||
openFileCallback.current = onOpenFile;
|
||||
const openFile = useCallback((path: string) => { setExpanded(false); openFileCallback.current?.(path); }, []);
|
||||
const content = (large: boolean) => <motion.div layoutId={layoutId} transition={{ duration: reducedMotion ? 0 : 0.25, ease: [0.2, 0, 0, 1] }} className={cn("flex flex-col gap-3", sidebar && !large && "h-full min-h-0")}>
|
||||
<Suspense fallback={<div aria-busy="true" className={cn(surface, "min-h-[300px]", sidebar && !large && "min-h-0 flex-1")} />}>
|
||||
<ContextGraphScene graph={snapshot?.graph ?? EMPTY_GRAPH} epoch={epoch} onReady={setReadyGraph} expanded={large} sidebar={sidebar && !large} onExpand={expandable ? toggleExpanded : undefined} onOpenFile={onOpenFile ? openFile : undefined} />
|
||||
</Suspense>
|
||||
<div className="flex shrink-0 items-center gap-3">
|
||||
<div onPointerEnter={() => setMeterHover(true)} onPointerLeave={() => setMeterHover(false)} className={cn(surface, "relative flex h-14 min-w-0 flex-1 items-center gap-4 px-4 transition-transform duration-150 ease-out motion-reduce:transition-none", meterHover && "scale-[1.015]")}>
|
||||
<div className="flex h-11 flex-1 items-center">
|
||||
<div role="progressbar" aria-label={t("thread.composer.context.contextTitle")} aria-valuemin={0} aria-valuemax={100} aria-valuenow={used === null ? undefined : Math.round(used)} className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
|
||||
<span className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground/45 transition-[width] duration-150 ease-out motion-reduce:transition-none" style={{ width: `${used ?? 0}%` }} />
|
||||
<span className="absolute inset-y-0 left-0 rounded-full bg-orange-500 transition-[width] duration-150 ease-out motion-reduce:transition-none" style={{ width: `${cachedWidth}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-sm tabular-nums">{used === null ? "—" : `${estimated ? "≈" : ""}${Math.round(used)}%`}</span>
|
||||
{meterHover && (hasTokenUsage || cached !== undefined || duration !== undefined || replay !== null) && <div className="pointer-events-none absolute bottom-full right-0 z-20 mb-2 min-w-48 rounded-xl bg-popover px-3 py-2.5 font-sans text-xs font-normal leading-5 shadow-lg">
|
||||
<dl className="grid grid-cols-[auto_auto] items-baseline gap-x-6 gap-y-1">
|
||||
{hasTokenUsage && <><dt className="whitespace-nowrap text-muted-foreground">{t("thread.composer.context.panelTitle")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{t("thread.composer.context.tokenUsage", {
|
||||
used: tokens === undefined ? "—" : `${estimated ? "≈" : ""}${tokenNumbers.format(tokens / 1000)}k`,
|
||||
limit: windowTokens ? `${tokenNumbers.format(windowTokens / 1000)}k` : "—",
|
||||
})}</dd></>}
|
||||
{cached !== undefined && !!input && <><dt className="text-muted-foreground">{t("thread.composer.context.cacheHitRate")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{Math.round(cached / input * 100)}%</dd></>}
|
||||
{duration !== undefined && <><dt className="text-muted-foreground">{t("thread.composer.context.duration")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{formatTurnLatency(duration)}</dd></>}
|
||||
{replay && <><dt className="text-muted-foreground">{t("thread.composer.context.history")}</dt>
|
||||
<dd className="text-right tabular-nums text-muted-foreground">{replay.index + 1}/{replay.frames.length}</dd></>}
|
||||
</dl>
|
||||
</div>}
|
||||
</div>
|
||||
<ContextReplayButton disabled={replay !== null || snapshots.length < 2}
|
||||
onPlay={() => {
|
||||
setMeterHover(false);
|
||||
// Scale by request count: our replay unit is a snapshot, not a graph edge.
|
||||
const stepsPerSecond = Math.min(20, Math.max(5, 0.5 * Math.sqrt(snapshots.length)));
|
||||
setReplay({ frames: [...snapshots], index: 0, startedAt: performance.now(), interval: 1000 / stepsPerSecond });
|
||||
}} />
|
||||
</div>
|
||||
</motion.div>;
|
||||
return <LayoutGroup>
|
||||
{!expanded && content(false)}
|
||||
<Dialog open={expanded} onOpenChange={setExpanded}>
|
||||
<DialogContent showCloseButton={false} aria-describedby={undefined} overlayClassName="context-expanded-overlay bg-background/30 backdrop-blur-md" className="w-[min(960px,calc(100vw-2rem))] max-w-none border-0 bg-transparent p-0 shadow-none !animate-none">
|
||||
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
|
||||
{content(true)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</LayoutGroup>;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { RotateCcw } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { HoverHint } from "@/components/ui/tooltip";
|
||||
|
||||
export function ContextReplayButton({ disabled, onPlay }: { disabled: boolean; onPlay: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const label = t("thread.composer.context.playHistory");
|
||||
return <HoverHint content={label} side="top" enabled={!disabled}><button type="button" aria-label={label} disabled={disabled} onClick={onPlay}
|
||||
className="context-inspector-surface grid size-14 shrink-0 place-items-center rounded-[20px] bg-card text-foreground/80 transition-colors enabled:hover:bg-muted enabled:hover:text-orange-500 disabled:cursor-default disabled:text-foreground/45 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
<RotateCcw className="size-[18px]" strokeWidth={2.25} aria-hidden="true" />
|
||||
</button></HoverHint>;
|
||||
}
|
||||
@@ -1,17 +1,12 @@
|
||||
import {
|
||||
PromptNavigationIcon,
|
||||
} from "@/components/icons/product-icons";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Search } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SearchInput } from "@/components/ui/input";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import {
|
||||
type PromptAnchor,
|
||||
userPromptAnchors,
|
||||
@@ -24,14 +19,16 @@ interface PromptNavigatorProps {
|
||||
messages: UIMessage[];
|
||||
prompts?: PromptAnchor[];
|
||||
onJumpToPrompt: (promptId: string) => void;
|
||||
shortcutEnabled?: boolean;
|
||||
}
|
||||
|
||||
const ROW_HEIGHT = 88;
|
||||
const ROW_HEIGHT = 64;
|
||||
|
||||
export function PromptNavigator({
|
||||
messages,
|
||||
prompts: suppliedPrompts,
|
||||
onJumpToPrompt,
|
||||
shortcutEnabled = true,
|
||||
}: PromptNavigatorProps) {
|
||||
const { i18n, t } = useTranslation();
|
||||
const prompts = useMemo(() => suppliedPrompts ?? userPromptAnchors(messages), [suppliedPrompts, messages]);
|
||||
@@ -39,6 +36,23 @@ export function PromptNavigator({
|
||||
const [query, setQuery] = useState("");
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const [listTop, setListTop] = useState(0);
|
||||
const [highlighted, setHighlighted] = useState(0);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const keyDown = (event: KeyboardEvent) => {
|
||||
if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing
|
||||
|| event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return;
|
||||
if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || document.querySelector("[role=dialog][data-state=open]"))) return;
|
||||
event.preventDefault();
|
||||
setListTop(0); setOpen(true);
|
||||
inputRef.current?.focus(); inputRef.current?.select();
|
||||
};
|
||||
window.addEventListener("keydown", keyDown);
|
||||
return () => window.removeEventListener("keydown", keyDown);
|
||||
}, [shortcutEnabled, prompts.length, open]);
|
||||
useEffect(() => { if (open) { setQuery(""); setHighlighted(0); setListTop(0); } }, [open]);
|
||||
|
||||
const filteredPrompts = useMemo(() => {
|
||||
const needle = query.trim().toLocaleLowerCase();
|
||||
@@ -60,6 +74,7 @@ export function PromptNavigator({
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
@@ -68,41 +83,53 @@ export function PromptNavigator({
|
||||
"hover:text-foreground",
|
||||
)}
|
||||
aria-label={t("thread.promptNavigator.open")}
|
||||
aria-keyshortcuts="Control+F Meta+F"
|
||||
onClick={() => { setListTop(0); setOpen(true); }}
|
||||
>
|
||||
<PromptNavigationIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetContent
|
||||
side="right"
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
aria-describedby={undefined}
|
||||
className="w-[min(92vw,24rem)] gap-0 p-0 sm:max-w-[24rem]"
|
||||
onOpenAutoFocus={(event) => { event.preventDefault(); inputRef.current?.focus(); }}
|
||||
onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}
|
||||
className="session-search-dialog flex max-h-[min(40rem,100%)] w-[calc(100vw-2rem)] max-w-[42rem] flex-col gap-0 overflow-hidden p-0"
|
||||
>
|
||||
<div className="border-b px-5 pb-4 pt-5">
|
||||
<SheetTitle className="text-base font-medium">
|
||||
<DialogTitle className="sr-only">
|
||||
{t("thread.promptNavigator.title")}
|
||||
</SheetTitle>
|
||||
<div className="relative mt-4">
|
||||
</DialogTitle>
|
||||
<div className="session-search-input flex h-[62px] shrink-0 items-center gap-3 border-b border-border px-[18px]">
|
||||
<Search
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
|
||||
className="h-[18px] w-[18px] shrink-0 text-muted-foreground"
|
||||
/>
|
||||
<SearchInput
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={query}
|
||||
onChange={(event) => {
|
||||
setQuery(event.target.value);
|
||||
setListTop(0);
|
||||
setHighlighted(0);
|
||||
if (listRef.current) listRef.current.scrollTop = 0;
|
||||
}}
|
||||
aria-label={t("thread.promptNavigator.search")}
|
||||
placeholder={t("thread.promptNavigator.search")}
|
||||
className="h-10 rounded-full border-border bg-background pl-9 pr-3 text-sm transition-colors"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && filteredPrompts[highlighted]) { event.preventDefault(); jump(filteredPrompts[highlighted].id); }
|
||||
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && filteredPrompts.length) {
|
||||
event.preventDefault();
|
||||
const next = (highlighted + (event.key === "ArrowDown" ? 1 : -1) + filteredPrompts.length) % filteredPrompts.length;
|
||||
setHighlighted(next);
|
||||
if (listRef.current) { listRef.current.scrollTop = next * ROW_HEIGHT; setListTop(next * ROW_HEIGHT); }
|
||||
}
|
||||
}}
|
||||
className="h-full min-w-0 flex-1 bg-transparent text-[19px] font-normal leading-none text-foreground outline-none placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref={listRef} className="min-h-0 flex-1 overflow-y-auto px-2 py-2"
|
||||
<div ref={listRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent"
|
||||
onScroll={(event) => setListTop(event.currentTarget.scrollTop)}
|
||||
onKeyDown={(event) => {
|
||||
const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-prompt-row]");
|
||||
@@ -125,6 +152,8 @@ export function PromptNavigator({
|
||||
<PromptNavigatorRow
|
||||
key={prompt.id}
|
||||
row={firstRow + offset}
|
||||
highlighted={highlighted === firstRow + offset}
|
||||
onHighlight={() => setHighlighted(firstRow + offset)}
|
||||
locale={i18n.resolvedLanguage || i18n.language}
|
||||
prompt={prompt}
|
||||
onJump={jump}
|
||||
@@ -137,8 +166,8 @@ export function PromptNavigator({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -148,6 +177,8 @@ interface PromptNavigatorRowProps {
|
||||
locale: string;
|
||||
onJump: (promptId: string) => void;
|
||||
prompt: PromptAnchor;
|
||||
highlighted: boolean;
|
||||
onHighlight: () => void;
|
||||
}
|
||||
|
||||
function PromptNavigatorRow({
|
||||
@@ -155,6 +186,8 @@ function PromptNavigatorRow({
|
||||
locale,
|
||||
onJump,
|
||||
prompt,
|
||||
highlighted,
|
||||
onHighlight,
|
||||
}: PromptNavigatorRowProps) {
|
||||
const { t } = useTranslation();
|
||||
const timestamp = fmtDateTime(prompt.createdAt, locale);
|
||||
@@ -163,17 +196,19 @@ function PromptNavigatorRow({
|
||||
type="button"
|
||||
data-prompt-row={row}
|
||||
className={cn(
|
||||
"h-[88px] w-full overflow-hidden rounded-control px-3 py-3 text-left transition",
|
||||
"hover:bg-accent focus-visible:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",
|
||||
"h-16 w-full overflow-hidden rounded-control px-3 py-2 text-left transition-colors",
|
||||
"hover:bg-muted focus-visible:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",
|
||||
highlighted && "bg-muted",
|
||||
)}
|
||||
aria-label={t("thread.promptNavigator.jumpTo", { label: prompt.label })}
|
||||
onClick={() => onJump(prompt.id)}
|
||||
onMouseEnter={onHighlight}
|
||||
>
|
||||
<div className="line-clamp-2 whitespace-pre-wrap break-words text-sm leading-5 text-foreground">
|
||||
<div className="truncate text-[14px] font-medium leading-5 text-foreground">
|
||||
{prompt.preview}
|
||||
</div>
|
||||
{timestamp ? (
|
||||
<div className="mt-1 text-[10px] leading-4 text-muted-foreground/75">
|
||||
<div className="mt-1 text-[12px] leading-4 text-muted-foreground">
|
||||
{timestamp}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -11,16 +11,15 @@ interface SessionInfoPopoverProps {
|
||||
client: WebUIMutationTransport;
|
||||
sessionKey: string;
|
||||
token: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export function SessionInfoPopover({ client, sessionKey, token, title }: SessionInfoPopoverProps) {
|
||||
export function SessionInfoPopover({ client, sessionKey, token }: SessionInfoPopoverProps) {
|
||||
const [surfacesOpen, setSurfacesOpen] = useState(false);
|
||||
const { jobs, loading, loadFailed, now } = useSessionAutomationJobs(surfacesOpen, token, sessionKey);
|
||||
const act = useCallback(async (action: AutomationAction, job: SessionAutomationJob) =>
|
||||
(await runAutomationAction(client, action, job.id)).jobs, [client]);
|
||||
const edit = useCallback(async (job: SessionAutomationJob, values: AutomationUpdatePayload) =>
|
||||
(await updateAutomation(client, job.id, values)).jobs, [client]);
|
||||
return <SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}
|
||||
return <SessionInfoPopoverView jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}
|
||||
onAction={act} onEdit={edit} onSurfacesOpenChange={setSurfacesOpen} calendarHref="#/automations" />;
|
||||
}
|
||||
@@ -49,9 +49,8 @@ const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
|
||||
[Number.POSITIVE_INFINITY, "year"],
|
||||
];
|
||||
|
||||
export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now, onAction, onEdit,
|
||||
export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onAction, onEdit,
|
||||
onSurfacesOpenChange, calendarHref, onOpenCalendar }: {
|
||||
title: string;
|
||||
jobs: SessionAutomationJob[];
|
||||
loading: boolean;
|
||||
loadFailed: boolean;
|
||||
@@ -201,16 +200,7 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,
|
||||
>
|
||||
<div className="flex max-h-[min(var(--radix-popover-content-available-height),32rem)] flex-col">
|
||||
<div className="px-4 pb-3 pt-3.5">
|
||||
<div className="min-w-0">
|
||||
<div className="text-[12px] font-normal text-muted-foreground/75">
|
||||
{t("thread.sessionInfo.title")}
|
||||
</div>
|
||||
<div className="mt-0.5 truncate text-[14px] font-medium text-foreground">
|
||||
{title || t("thread.sessionInfo.untitled")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-center justify-between gap-3 border-t border-border/45 pt-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="truncate text-[13px] font-medium text-foreground">
|
||||
{t("thread.sessionInfo.automations")}
|
||||
</span>
|
||||
|
||||
@@ -157,8 +157,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
|
||||
{children}
|
||||
<Sheet open={!!selected} onOpenChange={(open) => { if (!open) setSelectedId(null); }}>
|
||||
<SheetContent ref={detailPanel} tabIndex={-1}
|
||||
className="w-full gap-0 overflow-hidden border-l p-0 outline-none sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"
|
||||
overlayClassName="bg-black/20 backdrop-blur-[8px]"
|
||||
className="w-[calc(100vw-1rem)] gap-0 p-0 sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"
|
||||
closeButtonClassName="right-2 top-2 grid h-11 w-11 place-items-center rounded-full sm:right-3 sm:top-3 sm:h-9 sm:w-9"
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -241,6 +241,11 @@ interface ThreadComposerProps {
|
||||
onManageModels?: () => void;
|
||||
contextUsage?: ComposerContextUsage | null;
|
||||
recentRoundUsage?: readonly ComposerRoundUsage[];
|
||||
contextSnapshots?: readonly import("@/lib/types").ContextSnapshot[];
|
||||
onOpenContextFile?: (path: string) => void;
|
||||
contextSidebarHost?: HTMLElement | null;
|
||||
contextSidebarOpen?: boolean;
|
||||
onContextSidebarOpenChange?: (open: boolean) => void;
|
||||
variant?: "thread" | "hero";
|
||||
slashCommands?: SlashCommand[];
|
||||
onMentionSearch?: () => void;
|
||||
@@ -1080,6 +1085,11 @@ export function ThreadComposer({
|
||||
onManageModels,
|
||||
contextUsage = null,
|
||||
recentRoundUsage = [],
|
||||
contextSnapshots = [],
|
||||
onOpenContextFile,
|
||||
contextSidebarHost,
|
||||
contextSidebarOpen,
|
||||
onContextSidebarOpenChange,
|
||||
variant = "thread",
|
||||
slashCommands = [],
|
||||
onMentionSearch,
|
||||
@@ -1169,6 +1179,7 @@ export function ThreadComposer({
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const tabFocusRequested = useRef(false);
|
||||
const [compactControls, setCompactControls] = useState(false);
|
||||
const [usageTriggerHost, setUsageTriggerHost] = useState<HTMLSpanElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Automatic session focus should not open the hint; keyboard navigation should.
|
||||
@@ -2588,8 +2599,8 @@ export function ThreadComposer({
|
||||
/>
|
||||
) : null;
|
||||
const usageInMeta = mobileWorkspaceControls || compactControls;
|
||||
const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length) ? (
|
||||
<ComposerUsagePopover context={contextUsage} rounds={recentRoundUsage} showLabel={usageInMeta} compactLabel={mobileWorkspaceControls} bottomSheet={usageInMeta} />
|
||||
const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length || contextSnapshots.length) ? (
|
||||
<ComposerUsagePopover triggerHost={usageTriggerHost} context={contextUsage} rounds={recentRoundUsage} snapshots={contextSnapshots} onOpenFile={onOpenContextFile} showLabel={usageInMeta} compactLabel={mobileWorkspaceControls} sidebarHost={contextSidebarHost} open={contextSidebarOpen} onOpenChange={onContextSidebarOpenChange} />
|
||||
) : null;
|
||||
const inputTextClasses = cn(
|
||||
// Keep the overlay's CJK/Latin spacing aligned with the native textarea caret.
|
||||
@@ -2904,7 +2915,7 @@ export function ThreadComposer({
|
||||
)}
|
||||
>
|
||||
{modelControl}
|
||||
{!usageInMeta ? usageControl : null}
|
||||
{!usageInMeta && usageControl ? <span className="contents" ref={setUsageTriggerHost} /> : null}
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
@@ -2981,12 +2992,13 @@ export function ThreadComposer({
|
||||
</div>
|
||||
{usageInMeta && usageControl || mobileWorkspaceControls && accessControl ? (
|
||||
<div className={cn("ml-auto flex shrink-0 items-center gap-1", mobileWorkspaceControls && "h-11 max-w-[calc(100%-3rem)]")}>
|
||||
{usageInMeta ? usageControl : null}
|
||||
{usageInMeta && usageControl ? <span className="contents" ref={setUsageTriggerHost} /> : null}
|
||||
{mobileWorkspaceControls ? accessControl : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{usageControl}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -466,7 +466,7 @@ function MessageBlockMenu({
|
||||
data-message-block-menu data-message-mobile-sheet data-message-context-menu-block={contextBlockKey}
|
||||
className="gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))] outline-none"
|
||||
onCloseAutoFocus={(event) => { if (activity?.expanded) event.preventDefault(); }}>
|
||||
<DialogTitle className="px-2 pb-2 pe-10 text-sm font-medium text-muted-foreground">{label}</DialogTitle>
|
||||
<DialogTitle className="px-2 pb-2 text-sm font-medium text-muted-foreground">{label}</DialogTitle>
|
||||
{actions}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
|
||||
import type { CSSProperties, PointerEvent as ReactPointerEvent, ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request";
|
||||
@@ -76,13 +76,16 @@ import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import { providerDisplayLabel } from "@/lib/provider-brand";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { composerContextSnapshots } from "@/lib/context-graph";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
function latestComposerContextUsage(messages: ComposerUsageSnapshot[]): ComposerContextUsage | null {
|
||||
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
||||
const message = messages[index];
|
||||
if (message.compacted) {
|
||||
return null;
|
||||
return message.estimatedContextTokens !== undefined
|
||||
? { contextTokens: message.estimatedContextTokens, contextWindowTokens: message.contextWindowTokens, estimated: true }
|
||||
: null;
|
||||
}
|
||||
const contextTokens = message.usage?.context_tokens;
|
||||
if (
|
||||
@@ -107,6 +110,7 @@ function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRo
|
||||
const seenTurns = new Set<string>();
|
||||
for (let index = messages.length - 1; index >= 0 && recent.length < 8; index -= 1) {
|
||||
const message = messages[index];
|
||||
if (message.compacted) break;
|
||||
const turnKey = message.turnId || message.id;
|
||||
if (seenTurns.has(turnKey)) {
|
||||
continue;
|
||||
@@ -126,23 +130,13 @@ function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRo
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const outputTokens = round.completion_tokens;
|
||||
const cachedTokens = round.cached_tokens;
|
||||
const estimatedTokens = round.estimated_tokens;
|
||||
const generationMs = round.generation_ms;
|
||||
recent.push({
|
||||
id: `${turnKey}:${roundIndex}`,
|
||||
timestamp: message.completedAt ?? message.createdAt,
|
||||
inputTokens,
|
||||
...(typeof outputTokens === "number" && Number.isFinite(outputTokens)
|
||||
? { outputTokens }
|
||||
: {}),
|
||||
...(typeof cachedTokens === "number" && Number.isFinite(cachedTokens)
|
||||
? { cachedTokens }
|
||||
: {}),
|
||||
...(typeof estimatedTokens === "number" && Number.isFinite(estimatedTokens)
|
||||
? { estimatedTokens }
|
||||
: {}),
|
||||
...(typeof generationMs === "number" && Number.isFinite(generationMs)
|
||||
? { generationMs }
|
||||
: {}),
|
||||
@@ -540,11 +534,36 @@ export function ThreadShell({
|
||||
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
|
||||
const { state: previewState, openFile, resolveFile, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
|
||||
useFilePreviewState(previewSessionKey, filePreviewStore);
|
||||
const [contextSidebarOpen, setContextSidebarOpen] = useState(false);
|
||||
const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0);
|
||||
const [contextSidebarHost, setContextSidebarHost] = useState<HTMLElement | null>(null);
|
||||
const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []);
|
||||
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
|
||||
const filePreviewClosing = closingPreview?.key === previewSessionKey;
|
||||
const visiblePreview = filePreviewClosing ? closingPreview.state : previewState;
|
||||
const activePreview = visiblePreview.tabs.find((tab) => tab.id === visiblePreview.activeId);
|
||||
const previewOpen = Boolean(activePreview);
|
||||
const sidebarOpen = previewOpen || contextSidebarOpen;
|
||||
const [localComposerHost, setLocalComposerHost] = useState<HTMLDivElement | null>(null);
|
||||
const [composerMount] = useState(() => document.createElement("div"));
|
||||
const inlineComposer = composerPortalTarget === undefined || (sidebarOpen && composerActive);
|
||||
const composerDestination = inlineComposer ? localComposerHost : composerPortalTarget;
|
||||
useLayoutEffect(() => {
|
||||
// The inline host ref arrives on the next render. Keep the focused input
|
||||
// attached until that destination is ready.
|
||||
if (!composerDestination) { if (!inlineComposer) composerMount.remove(); return; }
|
||||
if (composerMount.parentElement === composerDestination) return;
|
||||
// Move the host, not the React subtree: drafts, graph replay and exit presence survive.
|
||||
const focused = document.activeElement instanceof HTMLElement && composerMount.contains(document.activeElement)
|
||||
? document.activeElement : null;
|
||||
const selection = document.getSelection();
|
||||
const range = focused && selection?.rangeCount && composerMount.contains(selection.getRangeAt(0).commonAncestorContainer)
|
||||
? selection.getRangeAt(0).cloneRange() : null;
|
||||
composerDestination.appendChild(composerMount);
|
||||
focused?.focus({ preventScroll: true });
|
||||
if (range && selection) { selection.removeAllRanges(); selection.addRange(range); }
|
||||
}, [composerDestination, composerMount, inlineComposer]);
|
||||
useLayoutEffect(() => () => composerMount.remove(), [composerMount]);
|
||||
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
|
||||
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
|
||||
const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");
|
||||
@@ -560,6 +579,23 @@ export function ThreadShell({
|
||||
const shellRef = useRef<HTMLElement | null>(null);
|
||||
const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);
|
||||
const composerSurfaceRef = useRef<HTMLDivElement | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const shell = contextSidebarHost;
|
||||
const surface = composerSurfaceRef.current;
|
||||
if (!sidebarOpen || !inlineComposer || !shell || !surface) return;
|
||||
// Metadata can wrap below the input card. Align sidebars to the visible
|
||||
// surface, rather than assuming a fixed composer/footer padding.
|
||||
const alignSidebar = () => {
|
||||
const inset = shell.getBoundingClientRect().bottom - surface.getBoundingClientRect().bottom;
|
||||
shell.style.setProperty("--sidebar-bottom-inset", `${Math.max(0, inset)}px`);
|
||||
};
|
||||
alignSidebar();
|
||||
const observer = new ResizeObserver(alignSidebar);
|
||||
observer.observe(shell);
|
||||
observer.observe(composerMount);
|
||||
observer.observe(surface);
|
||||
return () => observer.disconnect();
|
||||
}, [contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount]);
|
||||
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
|
||||
const filePreviewCloseTimerRef = useRef<number | null>(null);
|
||||
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
|
||||
@@ -704,6 +740,9 @@ export function ThreadShell({
|
||||
() => recentComposerRoundUsage(usageSnapshots),
|
||||
[usageSnapshots],
|
||||
);
|
||||
const contextGraphSnapshots = useMemo(
|
||||
() => composerContextSnapshots(messages, modelRequests), [messages, modelRequests],
|
||||
);
|
||||
const currentGoalState = messagesReady ? goalState : undefined;
|
||||
// Recovery decisions gate queued input, not the ledger-owned run state.
|
||||
const recoveryNeedsDecision = recoveryState?.status === "awaiting_user"
|
||||
@@ -1132,10 +1171,20 @@ export function ThreadShell({
|
||||
}, []);
|
||||
|
||||
const handleOpenFilePreview = useCallback((path: string) => {
|
||||
setSidebarEnterWidth(shellRef.current?.querySelector(".file-preview-pane")?.getBoundingClientRect().width ?? 0);
|
||||
setContextSidebarOpen(false);
|
||||
cancelPreviewClose();
|
||||
openFile(path);
|
||||
}, [cancelPreviewClose, openFile]);
|
||||
|
||||
const handleContextSidebarOpenChange = useCallback((open: boolean) => {
|
||||
if (open) {
|
||||
setSidebarEnterWidth(previewOpen ? filePreviewWidth : 0);
|
||||
cancelPreviewClose(); closePreview();
|
||||
}
|
||||
setContextSidebarOpen(open);
|
||||
}, [previewOpen, filePreviewWidth, cancelPreviewClose, closePreview]);
|
||||
|
||||
const handleClosePreviewTab = useCallback((id: string) => {
|
||||
if (previewState.tabs.length === 1) handleCloseFilePreview();
|
||||
else {
|
||||
@@ -1325,7 +1374,13 @@ export function ThreadShell({
|
||||
onManageModels={onOpenModelSettings}
|
||||
contextUsage={composerContextUsage}
|
||||
recentRoundUsage={composerRoundUsage}
|
||||
contextSnapshots={contextGraphSnapshots}
|
||||
onOpenContextFile={handleOpenFilePreview}
|
||||
contextSidebarHost={contextSidebarHost}
|
||||
contextSidebarOpen={contextSidebarOpen}
|
||||
onContextSidebarOpenChange={handleContextSidebarOpenChange}
|
||||
variant={composerVariant}
|
||||
surfaceRef={composerSurfaceRef}
|
||||
slashCommands={availableSlashCommands}
|
||||
onMentionSearch={requestMentionCatalogs}
|
||||
cliApps={cliApps}
|
||||
@@ -1379,6 +1434,11 @@ export function ThreadShell({
|
||||
onManageModels={onOpenModelSettings}
|
||||
contextUsage={composerContextUsage}
|
||||
recentRoundUsage={composerRoundUsage}
|
||||
contextSnapshots={contextGraphSnapshots}
|
||||
onOpenContextFile={handleOpenFilePreview}
|
||||
contextSidebarHost={contextSidebarHost}
|
||||
contextSidebarOpen={contextSidebarOpen}
|
||||
onContextSidebarOpenChange={handleContextSidebarOpenChange}
|
||||
variant="hero"
|
||||
slashCommands={availableSlashCommands}
|
||||
onMentionSearch={requestMentionCatalogs}
|
||||
@@ -1420,10 +1480,11 @@ export function ThreadShell({
|
||||
</div>
|
||||
);
|
||||
const sessionInfoAction = historyKey ? (
|
||||
<SessionInfoPopover client={client} sessionKey={historyKey} token={token} title={title} />
|
||||
<SessionInfoPopover client={client} sessionKey={historyKey} token={token} />
|
||||
) : undefined;
|
||||
const promptNavigatorAction = historyKey ? (
|
||||
<PromptNavigator
|
||||
shortcutEnabled={composerActive}
|
||||
messages={displayMessages}
|
||||
prompts={promptNavigation.prompts}
|
||||
onJumpToPrompt={(promptId) => viewportRef.current?.jumpToUserPrompt(promptId)}
|
||||
@@ -1460,7 +1521,7 @@ export function ThreadShell({
|
||||
historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}
|
||||
active={composerActive}
|
||||
enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
|
||||
<section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<section ref={setSidebarHost} style={{ "--sidebar-enter-width": `${sidebarEnterWidth}px`, "--sidebar-enter-mobile-width": sidebarEnterWidth ? "100%" : "0px" } as CSSProperties} data-preview-open={sidebarOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<div ref={setConversationElement} className={cn(
|
||||
"thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",
|
||||
headerPortalTarget === undefined && !hideHeader && "thread-workspace",
|
||||
@@ -1496,7 +1557,7 @@ export function ThreadShell({
|
||||
retryStatus={retryStatus}
|
||||
emptyState={emptyState}
|
||||
initialLoading={initialHistoryLoading}
|
||||
composer={composerPortalTarget === undefined ? composer : null}
|
||||
composer={inlineComposer ? <div ref={setLocalComposerHost} /> : null}
|
||||
activeTurnId={viewportTurnId}
|
||||
activeTurnStartedHere={activeTurnStartedHere}
|
||||
conversationKey={historyKey}
|
||||
@@ -1523,16 +1584,17 @@ export function ThreadShell({
|
||||
{headerPortalTarget && headerActive
|
||||
? createPortal(threadHeader, headerPortalTarget)
|
||||
: null}
|
||||
{composerPortalTarget ? createPortal(
|
||||
{createPortal(
|
||||
<div
|
||||
hidden={!composerActive}
|
||||
aria-hidden={!composerActive}
|
||||
data-testid={composerActive ? "active-pane-composer" : undefined}
|
||||
data-active-composer={composerActive || undefined}
|
||||
>
|
||||
{composer}
|
||||
</div>,
|
||||
composerPortalTarget,
|
||||
) : null}
|
||||
composerMount,
|
||||
)}
|
||||
{activePreview && previewSessionKey ? (
|
||||
<FileActionsProvider key={previewSessionKey} value={fileActions}>
|
||||
<PreviewPane
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { surfaceFocusProps } from "@/lib/surface-focus";
|
||||
import { FullAccessIcon, RestrictedAccessIcon, WorkspaceIcon } from "@/components/icons/product-icons";
|
||||
import type { HTMLAttributes, ReactElement, RefObject } from "react";
|
||||
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -636,8 +637,8 @@ export function WorkspaceProjectPicker({ disabled, scope, defaultScope, controls
|
||||
</nav>}
|
||||
<div className={cn("mr-[var(--picker-toolbar-inset)] flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[var(--picker-field-radius)] bg-[#fcfcfc] dark:bg-muted", compact && showLocations && canBrowse && "hidden")}>
|
||||
<div ref={attachColumns} data-workspace-columns className="sidebar-scrollbar flex flex-1 min-h-0 min-w-0 overflow-x-auto overscroll-x-contain">
|
||||
{columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && <WorkspaceDirectoryColumn key={columnIndex} options={column.options} selectedPath={column.selectedPath} initialScrollTop={previewingPath ? 0 : currentVisit.scrollTops[columnIndex] ?? 0} visitRevision={history.revision} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}
|
||||
id={`${optionsId}-${columnIndex}`} data-workspace-column={columnIndex} data-current-directory={columnIndex === currentColumnIndex ? "" : undefined} role="listbox" tabIndex={0} aria-activedescendant={highlightActive && columnIndex === activeColumn && column.options.length ? `${optionsId}-${columnIndex}-${activeOption}` : undefined} aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === currentColumnIndex && loading} style={{ width: `${compact ? 100 : 100 / columnCount}%` }} className="sidebar-scrollbar relative min-w-0 shrink-0 overflow-x-hidden overflow-y-auto px-2 outline-none [scrollbar-gutter:stable] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50"
|
||||
{columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && <WorkspaceDirectoryColumn key={columnIndex} {...surfaceFocusProps} options={column.options} selectedPath={column.selectedPath} initialScrollTop={previewingPath ? 0 : currentVisit.scrollTops[columnIndex] ?? 0} visitRevision={history.revision} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}
|
||||
id={`${optionsId}-${columnIndex}`} data-workspace-column={columnIndex} data-current-directory={columnIndex === currentColumnIndex ? "" : undefined} role="listbox" tabIndex={0} aria-activedescendant={highlightActive && columnIndex === activeColumn && column.options.length ? `${optionsId}-${columnIndex}-${activeOption}` : undefined} aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === currentColumnIndex && loading} style={{ width: `${compact ? 100 : 100 / columnCount}%` }} className="sidebar-scrollbar relative min-w-0 shrink-0 overflow-x-hidden overflow-y-auto px-2 outline-none [scrollbar-gutter:stable] data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring/50"
|
||||
onFocus={event => { if (event.target === event.currentTarget) { setActiveColumn(columnIndex); setActiveIndex(0); } }}
|
||||
onKeyDown={event => {
|
||||
if (event.target !== event.currentTarget || event.altKey || event.metaKey || event.ctrlKey || pickingFolder) return;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { GraphPosition } from "@/lib/context-graph-layout";
|
||||
import type { GraphPresentation } from "./graph-presentation";
|
||||
|
||||
type RGB = readonly [number, number, number];
|
||||
export interface GraphPalette { background: RGB; foreground: string; muted: RGB; font: string; labels: Map<string, string> }
|
||||
interface GraphCamera { x: number; y: number; k: number }
|
||||
const orange: RGB = [249, 115, 22];
|
||||
const blend = (a: RGB, b: RGB, amount: number): RGB => [a[0] + (b[0] - a[0]) * amount, a[1] + (b[1] - a[1]) * amount, a[2] + (b[2] - a[2]) * amount];
|
||||
const rgb = (value: RGB) => `rgb(${value.map(Math.round).join(" ")})`;
|
||||
export function readGraphPalette(element: HTMLElement): GraphPalette {
|
||||
const style = getComputedStyle(element);
|
||||
const parse = (color: string): RGB => {
|
||||
const values = color.match(/[\d.]+/g)?.map(Number) ?? [];
|
||||
return [values[0] ?? 0, values[1] ?? 0, values[2] ?? 0];
|
||||
};
|
||||
return { background: parse(style.backgroundColor), muted: parse(style.color), foreground: getComputedStyle(element.parentElement!).color, font: `10px ${style.fontFamily}`, labels: new Map() };
|
||||
}
|
||||
|
||||
export function fitGraphLabel(name: string, measure: (text: string) => number, maxWidth = 128): string {
|
||||
if (measure(name) <= maxWidth) return name;
|
||||
const characters = Array.from(name);
|
||||
let start = 0, end = characters.length;
|
||||
while (start < end) {
|
||||
const middle = Math.ceil((start + end) / 2);
|
||||
if (measure(`${characters.slice(0, middle).join("")}…`) <= maxWidth) start = middle;
|
||||
else end = middle - 1;
|
||||
}
|
||||
return `${characters.slice(0, start).join("")}…`;
|
||||
}
|
||||
|
||||
/** One bitmap paint; neither force ticks nor camera movement mutate per-node DOM. */
|
||||
export function paintGraph(context: CanvasRenderingContext2D, frame: GraphPresentation, positions: ReadonlyMap<string, GraphPosition>,
|
||||
view: GraphCamera, palette: GraphPalette, highlighted: string | null, focused: string | null,
|
||||
width: number, height: number, pixelRatio: number, discovered: ReadonlySet<string>) {
|
||||
context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
|
||||
context.clearRect(0, 0, width, height);
|
||||
const groups = new Map<string, { opacity: number; dashed: boolean; edges: GraphPresentation["edges"] }>();
|
||||
for (const edge of frame.edges) {
|
||||
const opacity = edge.presence * edge.emphasis * 0.7;
|
||||
const dashed = discovered.has(edge.target);
|
||||
const key = `${opacity}:${dashed}`;
|
||||
let group = groups.get(key);
|
||||
if (!group) { group = { opacity, dashed, edges: [] }; groups.set(key, group); }
|
||||
group.edges.push(edge);
|
||||
}
|
||||
context.strokeStyle = "#f97316";
|
||||
context.lineWidth = 1;
|
||||
for (const group of groups.values()) {
|
||||
context.globalAlpha = group.opacity;
|
||||
context.setLineDash(group.dashed ? [3, 5] : []);
|
||||
context.beginPath();
|
||||
for (const edge of group.edges) {
|
||||
const a = positions.get(edge.source), b = positions.get(edge.target);
|
||||
if (!a || !b) continue;
|
||||
context.moveTo(a.x * view.k + view.x, a.y * view.k + view.y);
|
||||
context.lineTo(b.x * view.k + view.x, b.y * view.k + view.y);
|
||||
}
|
||||
context.stroke();
|
||||
}
|
||||
context.setLineDash([]);
|
||||
context.font = palette.font;
|
||||
context.textAlign = "center";
|
||||
context.textBaseline = "middle";
|
||||
for (const node of frame.nodes) {
|
||||
const point = positions.get(node.path);
|
||||
if (!point) continue;
|
||||
const x = point.x * view.k + view.x, y = point.y * view.k + view.y;
|
||||
const alpha = node.presence * node.emphasis;
|
||||
const color = blend(palette.muted, orange, node.focus);
|
||||
context.globalAlpha = alpha;
|
||||
context.strokeStyle = rgb(color);
|
||||
context.fillStyle = rgb(blend(palette.background, color, node.loaded));
|
||||
context.beginPath(); context.arc(x, y, node.radius - 0.5, 0, Math.PI * 2); context.fill(); context.stroke();
|
||||
if (node.path === focused) {
|
||||
context.strokeStyle = palette.foreground;
|
||||
context.lineWidth = 2;
|
||||
context.beginPath(); context.roundRect(x - 22, y - 22, 44, 44, 4); context.stroke();
|
||||
context.lineWidth = 1;
|
||||
}
|
||||
// Introduce newly loaded files for one second, then fade to the usual zoom visibility.
|
||||
const labelOpacity = node.path === highlighted ? 1 : Math.max(0, Math.min(1, (view.k - 1) / 3.75), Math.min(1, node.labelRemaining / 600));
|
||||
if (labelOpacity > 0) {
|
||||
context.globalAlpha = alpha * labelOpacity;
|
||||
context.fillStyle = palette.foreground;
|
||||
let label = palette.labels.get(node.name);
|
||||
if (label === undefined) {
|
||||
label = fitGraphLabel(node.name, (text) => context.measureText(text).width);
|
||||
palette.labels.set(node.name, label);
|
||||
}
|
||||
context.fillText(label, x, y + 24);
|
||||
}
|
||||
}
|
||||
context.globalAlpha = 1;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { nodeRadius } from "@/lib/context-graph-layout";
|
||||
import type { ContextGraph, ContextGraphNode } from "@/lib/types";
|
||||
|
||||
type PresentedNode = ContextGraphNode & { presence: number; emphasis: number; focus: number; radius: number; loaded: number; labelRemaining: number };
|
||||
type PresentedEdge = ContextGraph["edges"][number] & { presence: number; emphasis: number };
|
||||
export type GraphPresentation = { nodes: PresentedNode[]; edges: PresentedEdge[] };
|
||||
const edgeKey = (edge: ContextGraph["edges"][number]) => JSON.stringify([edge.source, edge.target]);
|
||||
|
||||
/** Mutable animation state; request graphs remain immutable. The caller owns its clock. */
|
||||
export function createGraphPresentation() {
|
||||
const nodes = new Map<string, PresentedNode>();
|
||||
const edges = new Map<string, PresentedEdge>();
|
||||
let wanted = new Set<string>();
|
||||
let wantedEdges = new Set<string>();
|
||||
let related = new Set<string | null>();
|
||||
let highlighted: string | null = null;
|
||||
let frame: GraphPresentation = { nodes: [], edges: [] };
|
||||
let moving = false;
|
||||
return {
|
||||
get frame() { return frame; },
|
||||
update(graph: ContextGraph, focus: string | null) {
|
||||
highlighted = focus;
|
||||
const previouslyWanted = wanted;
|
||||
wanted = new Set(graph.nodes.map((node) => node.path));
|
||||
wantedEdges = new Set(graph.edges.map(edgeKey));
|
||||
related = new Set([focus]);
|
||||
for (const edge of graph.edges) {
|
||||
if (edge.source === focus) related.add(edge.target);
|
||||
if (edge.target === focus) related.add(edge.source);
|
||||
}
|
||||
for (const node of graph.nodes) {
|
||||
const previous = nodes.get(node.path);
|
||||
if (previous) {
|
||||
if (node.state !== "loaded") previous.labelRemaining = 0;
|
||||
// A replay can reintroduce a node before its exit animation removes it.
|
||||
else if (previous.state !== "loaded" || !previouslyWanted.has(node.path)) previous.labelRemaining = 1600;
|
||||
Object.assign(previous, node);
|
||||
}
|
||||
else nodes.set(node.path, { ...node, presence: 0, emphasis: 1, focus: 0, radius: nodeRadius(node), loaded: Number(node.state === "loaded"), labelRemaining: node.state === "loaded" ? 1600 : 0 });
|
||||
}
|
||||
for (const edge of graph.edges) if (!edges.has(edgeKey(edge))) edges.set(edgeKey(edge), { ...edge, presence: 0, emphasis: 1 });
|
||||
frame = { nodes: [...nodes.values()], edges: [...edges.values()] };
|
||||
moving = true;
|
||||
return frame;
|
||||
},
|
||||
advance(elapsed: number, reducedMotion: boolean) {
|
||||
if (!moving) return { moving: false, removed: false };
|
||||
const amount = reducedMotion ? 1 : 1 - Math.pow(0.9, Math.min(64, Math.max(0, elapsed)) / (1000 / 60));
|
||||
moving = false;
|
||||
let removed = false;
|
||||
const approach = (value: number, target: number) => {
|
||||
const next = value + (target - value) * amount;
|
||||
if (Math.abs(next - target) < 0.005) return target;
|
||||
moving = true;
|
||||
return next;
|
||||
};
|
||||
for (const [path, node] of nodes) {
|
||||
// Keep the clock alive after the layout settles so new labels can fade out.
|
||||
node.labelRemaining = Math.max(0, node.labelRemaining - Math.max(0, elapsed));
|
||||
if (node.labelRemaining > 0) moving = true;
|
||||
node.presence = approach(node.presence, wanted.has(path) ? 1 : 0);
|
||||
node.emphasis = approach(node.emphasis, highlighted && !related.has(path) ? 0.2 : 1);
|
||||
node.focus = approach(node.focus, path === highlighted ? 1 : 0);
|
||||
node.radius = approach(node.radius, nodeRadius(node));
|
||||
node.loaded = approach(node.loaded, Number(node.state === "loaded"));
|
||||
if (!wanted.has(path) && node.presence === 0) { nodes.delete(path); removed = true; }
|
||||
}
|
||||
for (const [key, edge] of edges) {
|
||||
edge.presence = approach(edge.presence, wantedEdges.has(key) ? 1 : 0);
|
||||
edge.emphasis = approach(edge.emphasis, highlighted && edge.source !== highlighted && edge.target !== highlighted ? 0.2 : 1);
|
||||
if (!wantedEdges.has(key) && edge.presence === 0) { edges.delete(key); removed = true; }
|
||||
}
|
||||
if (removed) frame = { nodes: [...nodes.values()], edges: [...edges.values()] };
|
||||
return { moving, removed };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -41,26 +41,29 @@ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
const DialogPositionedContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
|
||||
contained?: boolean;
|
||||
positionerStyle?: React.CSSProperties;
|
||||
placement?: "center" | "bottom";
|
||||
overlayClassName?: string;
|
||||
}
|
||||
>(({ positionerStyle, placement, overlayClassName, ...props }, ref) => (
|
||||
<DialogOverlay forceMount className={overlayClassName}>
|
||||
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overflow-y-auto overscroll-contain", placement !== "bottom" && "p-4")} style={{
|
||||
>(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => {
|
||||
const Overlay = contained ? "div" : DialogOverlay;
|
||||
return <Overlay data-dialog-backdrop {...(contained ? {} : { forceMount: true })} className={cn(contained && "absolute inset-0 z-50", overlayClassName)}>
|
||||
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overscroll-contain", placement === "bottom" ? "overflow-clip" : "overflow-y-auto p-4", contained && "absolute")} style={{
|
||||
top: "var(--app-viewport-top, 0px)",
|
||||
height: "var(--app-viewport-height, 100%)",
|
||||
bottom: "auto",
|
||||
...positionerStyle,
|
||||
...(contained ? { top: 0, height: "100%" } : positionerStyle),
|
||||
}}>
|
||||
<DialogPrimitive.Content ref={ref} {...props} />
|
||||
</div>
|
||||
</DialogOverlay>
|
||||
));
|
||||
</Overlay>;
|
||||
});
|
||||
DialogPositionedContent.displayName = "DialogPositionedContent";
|
||||
|
||||
interface DialogContentProps
|
||||
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
|
||||
portalContainer?: HTMLElement | null;
|
||||
showCloseButton?: boolean;
|
||||
overlayClassName?: string;
|
||||
layoutAnchor?: HTMLElement | null;
|
||||
@@ -71,10 +74,73 @@ interface DialogContentProps
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
DialogContentProps
|
||||
>(({ className, children, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {
|
||||
>(({ className, children, portalContainer, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [container, setContainer] = React.useState<HTMLDivElement | null>(null);
|
||||
const contentNode = React.useRef<HTMLDivElement | null>(null);
|
||||
const gesture = React.useRef<{ id: number; start: number; y: number; time: number; speed: number; moved: boolean } | null>(null);
|
||||
const suppressClick = React.useRef(false);
|
||||
const settleAnimation = React.useRef<Animation | null>(null);
|
||||
const backdropFrame = React.useRef<number | null>(null);
|
||||
const dragBackdrop = React.useRef<{ node: HTMLElement; color: string; blur: number } | null>(null);
|
||||
const paintBackdrop = (distance: number, height: number) => {
|
||||
const backdrop = dragBackdrop.current;
|
||||
if (!backdrop) return;
|
||||
const remaining = 1 - Math.min(1, Math.max(0, distance) / Math.max(1, height));
|
||||
backdrop.node.style.backgroundColor = `color-mix(in srgb, ${backdrop.color} ${remaining * 100}%, transparent)`;
|
||||
backdrop.node.style.backdropFilter = `blur(${backdrop.blur * remaining}px)`;
|
||||
};
|
||||
const cancelBackdropFrame = () => {
|
||||
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
|
||||
backdropFrame.current = null;
|
||||
};
|
||||
React.useEffect(() => () => {
|
||||
settleAnimation.current?.cancel();
|
||||
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
|
||||
}, []);
|
||||
const finishDrag = (button: HTMLButtonElement, pointerId: number, cancelled: boolean) => {
|
||||
const drag = gesture.current;
|
||||
const node = contentNode.current;
|
||||
if (!drag || drag.id !== pointerId || !node) return;
|
||||
gesture.current = null;
|
||||
suppressClick.current = drag.moved;
|
||||
if (!drag.moved) {
|
||||
if (dragBackdrop.current) {
|
||||
const style = dragBackdrop.current.node.style;
|
||||
for (const property of ["background-color", "backdrop-filter", "transition"]) style.removeProperty(property);
|
||||
dragBackdrop.current = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const distance = Math.max(0, drag.y - drag.start);
|
||||
const dismiss = !cancelled && (distance > Math.min(120, node.offsetHeight * 0.22)
|
||||
|| (distance > 24 && drag.speed > 0.65 && performance.now() - drag.time < 100));
|
||||
const destination = dismiss ? node.offsetHeight : 0;
|
||||
const animation = node.animate([{ translate: `0 ${distance}px` }, { translate: `0 ${destination}px` }], {
|
||||
duration: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : dismiss ? 180 : 260,
|
||||
easing: "cubic-bezier(0.2, 0, 0, 1)", fill: "forwards",
|
||||
});
|
||||
settleAnimation.current = animation;
|
||||
const follow = () => {
|
||||
paintBackdrop(parseFloat(getComputedStyle(node).getPropertyValue("translate").split(" ")[1]) || 0, node.offsetHeight);
|
||||
backdropFrame.current = requestAnimationFrame(follow);
|
||||
};
|
||||
backdropFrame.current = requestAnimationFrame(follow);
|
||||
animation.onfinish = () => {
|
||||
cancelBackdropFrame();
|
||||
node.style.translate = `0 ${destination}px`;
|
||||
paintBackdrop(destination, node.offsetHeight);
|
||||
if (!dismiss && dragBackdrop.current) {
|
||||
const style = dragBackdrop.current.node.style;
|
||||
for (const property of ["background-color", "backdrop-filter", "transition"]) style.removeProperty(property);
|
||||
dragBackdrop.current = null;
|
||||
}
|
||||
animation.cancel();
|
||||
settleAnimation.current = null;
|
||||
if (dismiss) { suppressClick.current = false; button.click(); }
|
||||
};
|
||||
};
|
||||
|
||||
const inheritedLayoutAnchor = React.useContext(DialogLayoutContext);
|
||||
const layoutAnchor = explicitLayoutAnchor ?? inheritedLayoutAnchor;
|
||||
const [layout, setLayout] = React.useState<React.CSSProperties>();
|
||||
@@ -114,13 +180,22 @@ const DialogContent = React.forwardRef<
|
||||
}, [layoutAnchor, placement, centerInLayoutAnchor]);
|
||||
const contentRef = React.useCallback((node: HTMLDivElement | null) => {
|
||||
contentNode.current = node;
|
||||
if (!node) {
|
||||
settleAnimation.current?.cancel();
|
||||
settleAnimation.current = null;
|
||||
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
|
||||
backdropFrame.current = null;
|
||||
dragBackdrop.current = null;
|
||||
gesture.current = null;
|
||||
}
|
||||
setContainer(node);
|
||||
if (typeof ref === "function") ref(node);
|
||||
else if (ref) ref.current = node;
|
||||
}, [ref]);
|
||||
return (
|
||||
<DialogPortal>
|
||||
<DialogPortal container={portalContainer}>
|
||||
<DialogPositionedContent
|
||||
contained={!!portalContainer}
|
||||
positionerStyle={layout}
|
||||
placement={placement}
|
||||
overlayClassName={overlayClassName}
|
||||
@@ -136,9 +211,10 @@ const DialogContent = React.forwardRef<
|
||||
modalSurfaceClassName,
|
||||
"relative grid w-full max-w-lg gap-4 p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 motion-reduce:animate-none",
|
||||
placement === "bottom"
|
||||
? "mt-auto max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-4 data-[state=closed]:slide-out-to-bottom-4"
|
||||
? "mt-auto max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-full data-[state=closed]:slide-out-to-bottom-full ease-[cubic-bezier(0.2,0,0,1)] duration-300"
|
||||
: "my-auto origin-center rounded-modal data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
|
||||
className,
|
||||
placement === "bottom" && "pt-9 transition-none",
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -146,8 +222,45 @@ const DialogContent = React.forwardRef<
|
||||
{children}
|
||||
</FloatingPortalContext.Provider>
|
||||
{showCloseButton ? (
|
||||
<DialogPrimitive.Close className={cn("absolute right-2.5 top-2.5 grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "h-11 w-11" : "h-7 w-7")}>
|
||||
<X className="h-4 w-4" />
|
||||
<DialogPrimitive.Close
|
||||
onPointerDown={(event) => {
|
||||
if (placement !== "bottom" || !event.isPrimary || event.button !== 0) return;
|
||||
const node = contentNode.current;
|
||||
const offset = node ? parseFloat(getComputedStyle(node).getPropertyValue("translate").split(" ")[1]) || 0 : 0;
|
||||
cancelBackdropFrame();
|
||||
settleAnimation.current?.cancel();
|
||||
if (node) node.style.translate = `0 ${offset}px`;
|
||||
const backdrop = node?.closest<HTMLElement>("[data-dialog-backdrop]");
|
||||
if (backdrop && !dragBackdrop.current) {
|
||||
const style = getComputedStyle(backdrop);
|
||||
dragBackdrop.current = { node: backdrop, color: style.backgroundColor,
|
||||
blur: parseFloat(style.getPropertyValue("backdrop-filter").match(/blur\(([^)]+)/)?.[1] ?? "0") || 0 };
|
||||
backdrop.style.transition = "none";
|
||||
backdrop.style.animation = "none";
|
||||
}
|
||||
suppressClick.current = false;
|
||||
gesture.current = { id: event.pointerId, start: event.clientY - offset, y: event.clientY, time: performance.now(), speed: 0, moved: offset > 5 };
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
const drag = gesture.current;
|
||||
if (!drag || drag.id !== event.pointerId) return;
|
||||
const now = performance.now();
|
||||
drag.speed = (event.clientY - drag.y) / Math.max(1, now - drag.time);
|
||||
drag.y = event.clientY; drag.time = now;
|
||||
drag.moved ||= Math.abs(drag.y - drag.start) > 5;
|
||||
if (contentNode.current) {
|
||||
const distance = Math.max(0, drag.y - drag.start);
|
||||
contentNode.current.style.translate = `0 ${distance}px`;
|
||||
paintBackdrop(distance, contentNode.current.offsetHeight);
|
||||
}
|
||||
}}
|
||||
onPointerUp={(event) => finishDrag(event.currentTarget, event.pointerId, false)}
|
||||
onPointerCancel={(event) => finishDrag(event.currentTarget, event.pointerId, true)}
|
||||
onLostPointerCapture={(event) => finishDrag(event.currentTarget, event.pointerId, true)}
|
||||
onClick={(event) => { if (suppressClick.current) { event.preventDefault(); suppressClick.current = false; } }}
|
||||
className={cn("absolute grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "left-1/2 top-0 h-8 w-16 -translate-x-1/2 touch-none cursor-grab active:cursor-grabbing" : "right-2.5 top-2.5 h-7 w-7")}>
|
||||
{placement === "bottom" ? <span aria-hidden="true" className="h-1 w-9 rounded-full bg-current opacity-40" /> : <X className="h-4 w-4" />}
|
||||
<span className="sr-only">{t("common.close")}</span>
|
||||
</DialogPrimitive.Close>
|
||||
) : null}
|
||||
|
||||
@@ -12,6 +12,9 @@ export const modalOverlayClassName =
|
||||
export const modalSurfaceClassName =
|
||||
"outline-none bg-background text-foreground shadow-[0_12px_36px_rgba(15,23,42,0.12)] dark:bg-popover dark:shadow-[0_18px_44px_rgba(0,0,0,0.32)]";
|
||||
|
||||
export const sidePanelSurfaceClassName =
|
||||
"side-panel-surface outline-none bg-background text-foreground dark:bg-popover overflow-hidden rounded-[24px]";
|
||||
|
||||
export const floatingSurfaceClassName =
|
||||
`${floatingSurfaceVisualClassName} z-50 overflow-x-hidden overflow-y-auto overscroll-contain scrollbar-thin`;
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { surfaceFocusProps } from "@/lib/surface-focus";
|
||||
import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react";
|
||||
import { Minus, Plus } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -121,8 +122,8 @@ export function ImageViewport({
|
||||
const buttonClass = "grid size-9 shrink-0 place-items-center rounded-full transition-colors hover:text-foreground disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
|
||||
|
||||
return <>
|
||||
<div ref={viewport} data-testid={testId} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
|
||||
className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}
|
||||
<div ref={viewport} data-testid={testId} {...surfaceFocusProps} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
|
||||
className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden outline-none data-[keyboard-focus]:ring-1 data-[keyboard-focus]:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}
|
||||
onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={endPointer} onPointerCancel={endPointer} onLostPointerCapture={endPointer}
|
||||
onDoubleClick={(event) => zoom(viewRef.current.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })}
|
||||
onKeyDown={(event) => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface";
|
||||
|
||||
const Sheet = DialogPrimitive.Root;
|
||||
const SheetTrigger = DialogPrimitive.Trigger;
|
||||
@@ -29,7 +30,7 @@ const SheetOverlay = React.forwardRef<
|
||||
SheetOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
const sheetVariants = cva(
|
||||
"fixed z-50 flex flex-col gap-4 bg-background outline-none transition ease-in-out",
|
||||
"fixed z-50 flex flex-col gap-4 bg-background outline-none ease-out",
|
||||
{
|
||||
variants: {
|
||||
side: {
|
||||
@@ -42,12 +43,14 @@ const sheetVariants = cva(
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||
),
|
||||
left: cn(
|
||||
"inset-y-0 left-0 h-full w-3/4 sm:max-w-sm",
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",
|
||||
"inset-y-2 left-2 w-3/4 max-w-[calc(100vw-1rem)] sm:max-w-sm",
|
||||
sidePanelSurfaceClassName,
|
||||
"data-[state=closed]:slide-out-to-left-4 data-[state=open]:slide-in-from-left-4",
|
||||
),
|
||||
right: cn(
|
||||
"inset-y-0 right-0 h-full w-3/4 sm:max-w-sm",
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",
|
||||
"inset-y-2 right-2 w-3/4 max-w-[calc(100vw-1rem)] sm:max-w-sm",
|
||||
sidePanelSurfaceClassName,
|
||||
"data-[state=closed]:slide-out-to-right-4 data-[state=open]:slide-in-from-right-4",
|
||||
),
|
||||
},
|
||||
},
|
||||
@@ -83,13 +86,13 @@ const SheetContent = React.forwardRef<
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay className={overlayClassName} />
|
||||
<SheetOverlay className={cn((side === "right" || side === "left") && modalOverlayClassName, overlayClassName)} />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
sheetVariants({ side }),
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||
"duration-300 motion-reduce:transition-none",
|
||||
"data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 duration-200 motion-reduce:transition-none",
|
||||
"motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none",
|
||||
className,
|
||||
)}
|
||||
@@ -99,7 +102,7 @@ const SheetContent = React.forwardRef<
|
||||
{showCloseButton ? (
|
||||
<DialogPrimitive.Close
|
||||
className={cn(
|
||||
"absolute right-4 top-4 rounded-mark opacity-70 ring-offset-background transition-opacity",
|
||||
"absolute right-2 top-2 grid size-10 place-items-center rounded-full opacity-70 ring-offset-background transition-opacity",
|
||||
"hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
"disabled:pointer-events-none",
|
||||
closeButtonClassName,
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { createContext, forwardRef, useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type HTMLAttributes, type ReactNode } from "react";
|
||||
import { useReducedMotion } from "motion/react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface SidebarPanelProps extends HTMLAttributes<HTMLElement> {
|
||||
header?: ReactNode;
|
||||
width: number;
|
||||
isClosing?: boolean;
|
||||
open?: boolean;
|
||||
floating?: boolean;
|
||||
contentClassName?: string;
|
||||
}
|
||||
|
||||
export const SidebarPanelActionsContext = createContext<HTMLElement | null>(null);
|
||||
|
||||
/** Retain the same surface through exit, including an interrupted close. */
|
||||
export const SidebarPanel = forwardRef<HTMLElement, SidebarPanelProps>(function SidebarPanel({
|
||||
open = true, isClosing, ...props
|
||||
}, ref) {
|
||||
const [present, setPresent] = useState(open);
|
||||
const reducedMotion = useReducedMotion();
|
||||
useEffect(() => {
|
||||
if (open) { setPresent(true); return; }
|
||||
const timer = window.setTimeout(() => setPresent(false), reducedMotion ? 0 : 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [open, reducedMotion]);
|
||||
return open || present ? <SidebarPanelContent {...props} ref={ref} isClosing={isClosing || !open} /> : null;
|
||||
});
|
||||
|
||||
/** Shared nonmodal side slot. Contents keep their final width while the slot opens. */
|
||||
const SidebarPanelContent = forwardRef<HTMLElement, SidebarPanelProps>(function SidebarPanelContent({
|
||||
width, isClosing = false, floating = false, header, contentClassName, className, style, children, ...props
|
||||
}, forwardedRef) {
|
||||
const panel = useRef<HTMLElement | null>(null);
|
||||
const [entered, setEntered] = useState(false);
|
||||
const [actionsHost, setActionsHost] = useState<HTMLElement | null>(null);
|
||||
const setPanel = useCallback((node: HTMLElement | null) => {
|
||||
panel.current = node;
|
||||
if (typeof forwardedRef === "function") forwardedRef(node);
|
||||
else if (forwardedRef) forwardedRef.current = node;
|
||||
}, [forwardedRef]);
|
||||
useLayoutEffect(() => {
|
||||
// Commit the outgoing slot width before transitioning to the replacement width.
|
||||
panel.current?.getBoundingClientRect();
|
||||
let frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => setEntered(true)); });
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, []);
|
||||
return <aside {...props} ref={setPanel} data-closing={isClosing || undefined}
|
||||
style={{
|
||||
"--file-preview-width": `${width}px`,
|
||||
"--file-preview-slot-width": isClosing ? "0px" : !entered ? "var(--sidebar-enter-width, 0px)" : `${width}px`,
|
||||
"--file-preview-mobile-width": isClosing ? "0px" : !entered ? "var(--sidebar-enter-mobile-width, 0px)" : "100%",
|
||||
...style,
|
||||
} as CSSProperties}
|
||||
className={cn("file-preview-pane z-30 min-h-0 w-[var(--file-preview-mobile-width)] overflow-hidden duration-300 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none",
|
||||
entered ? "transition-[width]" : "transition-none",
|
||||
floating ? "fixed inset-y-2 right-2 max-w-[420px]" : "absolute inset-y-0 right-0", isClosing && "pointer-events-none", className)}>
|
||||
<div className={cn("file-preview-content absolute inset-y-2 right-2 flex min-h-0 w-[calc(100cqw-1rem)] flex-col pb-[env(safe-area-inset-bottom)] transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none",
|
||||
floating && "w-[calc(min(420px,100vw)-1rem)]",
|
||||
!entered || isClosing ? "translate-x-2 opacity-0" : "translate-x-0 opacity-100", contentClassName)}>
|
||||
{header && <div className="flex min-h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2 pt-2">
|
||||
{header}
|
||||
<div ref={setActionsHost} className="shrink-0" />
|
||||
</div>}
|
||||
<SidebarPanelActionsContext.Provider value={actionsHost}>{children}</SidebarPanelActionsContext.Provider>
|
||||
</div>
|
||||
</aside>;
|
||||
});
|
||||
@@ -25,10 +25,8 @@ import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { HoverHint } from "@/components/ui/tooltip";
|
||||
@@ -634,10 +632,6 @@ export function PaneWorkbench({
|
||||
align="end"
|
||||
onCloseAutoFocus={(event) => event.preventDefault()}
|
||||
>
|
||||
<DropdownMenuLabel>
|
||||
{t("workbench.layout", { defaultValue: "Pane layout" })}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuRadioGroup
|
||||
value={layout}
|
||||
onValueChange={(value) => {
|
||||
@@ -701,8 +695,8 @@ export function PaneWorkbench({
|
||||
data-testid="pane-grid"
|
||||
data-layout={effectiveLayout}
|
||||
className={cn(
|
||||
"grid h-full min-h-0 min-w-0 overflow-hidden",
|
||||
chrome && displayedPanes.length > 1 && "gap-px bg-border/55",
|
||||
"grid h-full min-h-0 min-w-0 overflow-hidden bg-background",
|
||||
chrome && displayedPanes.length > 1 && "gap-px",
|
||||
)}
|
||||
style={gridStyle}
|
||||
>
|
||||
@@ -723,7 +717,10 @@ export function PaneWorkbench({
|
||||
data-testid={`workbench-pane-${pane.key}`}
|
||||
onPointerDownCapture={(event) => handlePanePointerDown(pane.key, event)}
|
||||
onFocusCapture={(event) => handlePaneFocus(pane.key, event)}
|
||||
className="workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background"
|
||||
className={cn(
|
||||
"workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background",
|
||||
chrome && displayedPanes.length > 1 && "shadow-[0_0_0_1px_hsl(var(--border)/0.55)]",
|
||||
)}
|
||||
style={layoutGeometry.paneStyles[index]}
|
||||
>
|
||||
{renderPane(pane, {
|
||||
|
||||
Reference in new issue
Block a user