fix(webui): polish mobile settings and context interactions
This commit is contained in:
1 parent
827dbe137b
commit
f5c6be2608
5 files changed
+553
-80
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { useRef } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import {
|
||||
Activity,
|
||||
Info,
|
||||
@@ -23,12 +23,8 @@ import {
|
||||
} from "@/components/SidebarSelectionHighlight";
|
||||
import { isCapabilitySection, type SettingsSectionKey } from "@/components/settings/contracts";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const SETTINGS_NAV_ITEMS: Array<{ key: SettingsSectionKey; icon: LucideIcon; fallback: string }> = [
|
||||
@@ -49,17 +45,7 @@ export function standaloneSectionTitle(section: SettingsSectionKey): string {
|
||||
return SETTINGS_NAV_ITEMS.find((item) => item.key === section)?.fallback ?? "Settings";
|
||||
}
|
||||
|
||||
export function SettingsSidebar({
|
||||
activeSection,
|
||||
onSelectSection,
|
||||
onBackToChat,
|
||||
onLogout,
|
||||
hostChromeInset,
|
||||
onRestart,
|
||||
isRestarting,
|
||||
restartPending,
|
||||
isNativeHost,
|
||||
}: {
|
||||
interface SettingsSidebarProps {
|
||||
activeSection: SettingsSectionKey;
|
||||
onSelectSection: (section: SettingsSectionKey) => void;
|
||||
onBackToChat: () => void;
|
||||
@@ -69,8 +55,22 @@ export function SettingsSidebar({
|
||||
isRestarting?: boolean;
|
||||
restartPending?: boolean;
|
||||
isNativeHost?: boolean;
|
||||
}) {
|
||||
}
|
||||
|
||||
export function SettingsSidebar(props: SettingsSidebarProps) {
|
||||
const {
|
||||
activeSection,
|
||||
onSelectSection,
|
||||
onBackToChat,
|
||||
onLogout,
|
||||
hostChromeInset,
|
||||
onRestart,
|
||||
isRestarting,
|
||||
restartPending,
|
||||
isNativeHost,
|
||||
} = props;
|
||||
const { t } = useTranslation();
|
||||
const mobile = useMediaQuery("(max-width: 1023px)");
|
||||
const restartLabel = isRestarting
|
||||
? t(isNativeHost ? "app.system.restartingEngine" : "app.system.restarting")
|
||||
: t("app.system.restartAction");
|
||||
@@ -78,11 +78,15 @@ export function SettingsSidebar({
|
||||
const activeNavItemRef = useRef<HTMLButtonElement>(null);
|
||||
const activeItem = SETTINGS_NAV_ITEMS.find((item) => item.key === navSection)
|
||||
?? SETTINGS_NAV_ITEMS[0];
|
||||
const ActiveIcon = activeItem.icon;
|
||||
const activeLabel = t(`settings.nav.${activeItem.key}`, {
|
||||
defaultValue: activeItem.fallback,
|
||||
});
|
||||
|
||||
if (mobile) {
|
||||
return <MobileSettingsNavigation {...props} navSection={navSection}
|
||||
activeLabel={activeLabel} restartLabel={restartLabel} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
@@ -106,46 +110,6 @@ export function SettingsSidebar({
|
||||
aria-label={t("settings.sidebar.ariaLabel")}
|
||||
className="w-full"
|
||||
>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${t("settings.sidebar.title")}: ${activeLabel}`}
|
||||
className="touch-target flex h-11 w-full items-center gap-2.5 rounded-control bg-sidebar-accent px-3 text-left text-[13px] leading-5 font-normal text-foreground transition-colors settings-hover lg:hidden"
|
||||
>
|
||||
<ActiveIcon className="h-4 w-4 shrink-0" strokeWidth={2} aria-hidden />
|
||||
<span className="min-w-0 flex-1 truncate">{activeLabel}</span>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-sidebar-content" aria-hidden />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
sideOffset={6}
|
||||
className="w-[var(--radix-dropdown-menu-trigger-width)] max-w-[calc(100vw-1.5rem)]"
|
||||
>
|
||||
{SETTINGS_NAV_ITEMS.map(({ key, icon: Icon, fallback }) => {
|
||||
const active = key === navSection;
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={key}
|
||||
aria-current={active ? "page" : undefined}
|
||||
onSelect={() => onSelectSection(key)}
|
||||
className={cn(
|
||||
"flex h-10 cursor-default items-center gap-2.5 px-2.5 text-[13px] leading-5 font-normal",
|
||||
active && "bg-sidebar-accent text-foreground focus:bg-sidebar-accent",
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 shrink-0" strokeWidth={2} aria-hidden />
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{t(`settings.nav.${key}`, { defaultValue: fallback })}
|
||||
</span>
|
||||
{active ? <Check className="h-4 w-4 shrink-0" aria-hidden /> : null}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<SidebarSelectionHighlight
|
||||
targetRef={activeNavItemRef}
|
||||
activeId={navSection}
|
||||
@@ -219,3 +183,102 @@ export function SettingsSidebar({
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
// Mount only on narrow screens so switching to desktop also releases the sheet's focus/pointer lock.
|
||||
function MobileSettingsNavigation({
|
||||
navSection,
|
||||
activeLabel,
|
||||
restartLabel,
|
||||
onSelectSection,
|
||||
onBackToChat,
|
||||
hostChromeInset,
|
||||
onRestart,
|
||||
isRestarting,
|
||||
restartPending,
|
||||
}: SettingsSidebarProps & {
|
||||
navSection: SettingsSectionKey;
|
||||
activeLabel: string;
|
||||
restartLabel: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const restartAction = onRestart ? (
|
||||
<Button type="button" variant="ghost" disabled={isRestarting}
|
||||
onClick={() => { setOpen(false); onRestart(); }}
|
||||
className={cn("h-11 shrink-0 gap-2 px-3 text-sm font-normal",
|
||||
restartPending && !isRestarting
|
||||
? "text-orange-600 hover:text-orange-700 dark:text-orange-400 dark:hover:text-orange-300"
|
||||
: "text-muted-foreground hover:text-foreground")}
|
||||
>
|
||||
{isRestarting ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
|
||||
: <RotateCcw className="h-4 w-4" aria-hidden />}
|
||||
{restartLabel}
|
||||
</Button>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<aside className={cn("shrink-0 border-b border-border/50 bg-settings-canvas",
|
||||
hostChromeInset ? "pt-10" : "pt-[env(safe-area-inset-top)]")}
|
||||
>
|
||||
<div className="grid h-14 grid-cols-[2.75rem_minmax(0,1fr)_2.75rem] items-center px-3">
|
||||
<Button type="button" variant="ghost" onClick={onBackToChat}
|
||||
aria-label={t("settings.backToChat")}
|
||||
className="h-11 w-11 rounded-full p-0 text-sidebar-content"
|
||||
>
|
||||
<ChevronLeft className="h-5 w-5" aria-hidden />
|
||||
</Button>
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button type="button" variant="ghost"
|
||||
aria-label={`${t("settings.sidebar.title")}: ${activeLabel}`}
|
||||
className="h-11 min-w-0 max-w-full justify-self-center gap-1.5 px-2 text-base font-medium"
|
||||
>
|
||||
<span className="truncate">{activeLabel}</span>
|
||||
<ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="bottom" showCloseButton={false} aria-describedby={undefined}
|
||||
className="mx-auto max-h-[85dvh] max-w-md gap-0 rounded-t-3xl px-3 pt-2 pb-[max(0.75rem,env(safe-area-inset-bottom))] data-[state=open]:duration-300 data-[state=closed]:duration-200"
|
||||
>
|
||||
<div className="flex shrink-0 items-center justify-between gap-3 px-3 pb-2">
|
||||
<SheetTitle className="text-base font-medium">{t("settings.sidebar.title")}</SheetTitle>
|
||||
<Button type="button" variant="ghost" onClick={() => setOpen(false)}
|
||||
className="-mr-2 h-11 px-2 text-sm font-normal text-muted-foreground"
|
||||
>{t("common.close")}</Button>
|
||||
</div>
|
||||
<div className="min-h-0 overflow-y-auto overscroll-contain">
|
||||
<nav aria-label={t("settings.sidebar.ariaLabel")} className="space-y-0.5">
|
||||
{SETTINGS_NAV_ITEMS.map(({ key, icon: Icon, fallback }) => {
|
||||
const active = key === navSection;
|
||||
return (
|
||||
<Button key={key} type="button" variant="ghost"
|
||||
aria-current={active ? "page" : undefined}
|
||||
onClick={() => { setOpen(false); onSelectSection(key); }}
|
||||
className={cn("h-11 w-full justify-start gap-3 rounded-xl px-3 text-sm font-normal",
|
||||
active ? "bg-sidebar-accent text-foreground" : "text-sidebar-content")}
|
||||
>
|
||||
<Icon className="h-[18px] w-[18px] shrink-0" aria-hidden />
|
||||
<span className="min-w-0 flex-1 truncate text-left">
|
||||
{t(`settings.nav.${key}`, { defaultValue: fallback })}
|
||||
</span>
|
||||
{active ? <Check className="h-4 w-4 shrink-0" aria-hidden /> : null}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
{restartAction ? <div className="mt-2 border-t border-border/50 pt-2">{restartAction}</div> : null}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
{onRestart && (restartPending || isRestarting) ? (
|
||||
<div className="flex min-h-11 items-center justify-between gap-2 px-4 pb-1">
|
||||
<p role="status" className="text-xs leading-5 text-muted-foreground">
|
||||
{isRestarting ? restartLabel : t("settings.status.savedRestartApply")}
|
||||
</p>
|
||||
{restartAction}
|
||||
</div>
|
||||
) : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Fragment, useMemo, useRef, type ReactNode } from "react";
|
||||
import { Fragment, useCallback, useMemo, useRef, useState, type PointerEvent, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
|
||||
import { FloatingPortalContext } from "@/components/ui/floating-portal";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
@@ -65,6 +66,7 @@ export function ComposerUsagePopover({
|
||||
bottomSheet?: boolean;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const normalizedRounds = useMemo(() => normalizeRounds(rounds), [rounds]);
|
||||
const hasContext = !!context
|
||||
&& Number.isFinite(context.contextTokens)
|
||||
@@ -116,6 +118,10 @@ export function ComposerUsagePopover({
|
||||
|
||||
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 trigger = (
|
||||
<Trigger asChild>
|
||||
<button
|
||||
@@ -178,7 +184,7 @@ export function ComposerUsagePopover({
|
||||
);
|
||||
|
||||
return (
|
||||
<Root>
|
||||
<Root open={open} onOpenChange={setOpen}>
|
||||
<TooltipProvider>
|
||||
{bottomSheet ? trigger : (
|
||||
<Tooltip>
|
||||
@@ -194,7 +200,7 @@ export function ComposerUsagePopover({
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
<UsagePanel bottomSheet={bottomSheet}>
|
||||
<UsagePanel bottomSheet={bottomSheet} onDismiss={() => setOpen(false)}>
|
||||
<div className="px-4 pb-4 pt-3.5">
|
||||
{contextPercentage !== null ? (
|
||||
<>
|
||||
@@ -330,16 +336,18 @@ export function ComposerUsagePopover({
|
||||
index === normalizedRounds.length - 1 && "opacity-100",
|
||||
)}
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
role="img"
|
||||
<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",
|
||||
bottomSheet && "data-[state=open]:ring-2 data-[state=open]:ring-foreground/20",
|
||||
)}
|
||||
style={{ height: `${barHeight}px` }}
|
||||
>
|
||||
@@ -361,12 +369,16 @@ export function ComposerUsagePopover({
|
||||
) : (
|
||||
<span className="block h-full w-full bg-muted-foreground/25" />
|
||||
)}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
</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"
|
||||
@@ -392,8 +404,8 @@ export function ComposerUsagePopover({
|
||||
{detailNote}
|
||||
</span>
|
||||
) : null}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</RoundContent>
|
||||
</RoundRoot>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
@@ -408,34 +420,109 @@ export function ComposerUsagePopover({
|
||||
);
|
||||
}
|
||||
|
||||
function UsagePanel({ bottomSheet, children }: { bottomSheet: boolean; children: ReactNode }) {
|
||||
function UsagePanel({ bottomSheet, onDismiss, children }: {
|
||||
bottomSheet: boolean;
|
||||
onDismiss: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
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);
|
||||
};
|
||||
|
||||
if (bottomSheet) {
|
||||
return (
|
||||
<SheetContent
|
||||
ref={panelRef}
|
||||
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",
|
||||
)}
|
||||
closeButtonClassName="right-3 top-5 flex size-11 items-center justify-center rounded-full"
|
||||
>
|
||||
<div aria-hidden="true" className="mx-auto mt-2.5 h-1 w-8 shrink-0 rounded-full bg-foreground/15" />
|
||||
<div className="shrink-0 px-5 pb-2 pt-5 pr-16">
|
||||
<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))]">
|
||||
{children}
|
||||
<FloatingPortalContext.Provider value={panelNode}>
|
||||
{children}
|
||||
</FloatingPortalContext.Provider>
|
||||
</div>
|
||||
</SheetContent>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { createEvent, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover";
|
||||
|
||||
function pointer(
|
||||
target: HTMLElement,
|
||||
type: "pointerDown" | "pointerMove" | "pointerUp" | "pointerCancel" | "lostPointerCapture",
|
||||
{ y, x = 160, time = 1000, id = 1 }: { y: number; x?: number; time?: number; id?: number },
|
||||
) {
|
||||
const event = createEvent[type](target, {
|
||||
pointerId: id, pointerType: "touch", isPrimary: true, button: 0, clientX: x, clientY: y,
|
||||
});
|
||||
Object.defineProperty(event, "timeStamp", { value: time });
|
||||
fireEvent(target, event);
|
||||
}
|
||||
|
||||
async function openSheet() {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ComposerUsagePopover
|
||||
bottomSheet
|
||||
showLabel
|
||||
context={{ contextTokens: 10000, contextWindowTokens: 200000 }}
|
||||
rounds={[
|
||||
{ id: "round", timestamp: 0, inputTokens: 10000, cachedTokens: 8000 },
|
||||
{ id: "round-2", timestamp: 60000, inputTokens: 14000, outputTokens: 280 },
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
const trigger = screen.getByTestId("composer-context-usage");
|
||||
await user.click(trigger);
|
||||
const sheet = screen.getByRole("dialog", { name: "Context usage" });
|
||||
const handle = within(sheet).getByRole("button", { name: "Close" });
|
||||
return { user, trigger, sheet, handle };
|
||||
}
|
||||
|
||||
describe("Mobile context usage sheet", () => {
|
||||
it("replaces the X with a keyboard-accessible drag handle", async () => {
|
||||
const { user, handle, sheet, trigger } = await openSheet();
|
||||
expect(within(sheet).getAllByRole("button", { name: "Close" })).toEqual([handle]);
|
||||
expect(handle.querySelector("svg")).toBeNull();
|
||||
expect(handle).toHaveClass("touch-none", "h-11");
|
||||
handle.focus();
|
||||
await user.keyboard("{Enter}");
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(trigger).toHaveFocus();
|
||||
});
|
||||
|
||||
it("keeps tapped round details open, switches rounds, and toggles the same bar closed", async () => {
|
||||
const { user, sheet } = await openSheet();
|
||||
const [first, second] = within(sheet).getAllByTestId("round-usage-bar");
|
||||
const tap = (target: HTMLElement) => user.pointer([
|
||||
{ keys: "[TouchA>]", target },
|
||||
{ keys: "[/TouchA]", target },
|
||||
]);
|
||||
|
||||
expect(first.tagName).toBe("BUTTON");
|
||||
await tap(first);
|
||||
const details = within(sheet).getByRole("dialog");
|
||||
expect(details).toHaveTextContent("10,000");
|
||||
expect(details).toHaveTextContent("80%");
|
||||
expect(first).toHaveAttribute("aria-expanded", "true");
|
||||
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
|
||||
fireEvent.pointerLeave(first, { pointerType: "touch" });
|
||||
expect(details).toBeVisible();
|
||||
|
||||
await tap(second);
|
||||
await waitFor(() => expect(within(sheet).getAllByRole("dialog")).toHaveLength(1));
|
||||
expect(within(sheet).getByRole("dialog")).toHaveTextContent("14,000");
|
||||
expect(within(sheet).getByRole("dialog")).toHaveTextContent("280");
|
||||
expect(first).toHaveAttribute("aria-expanded", "false");
|
||||
expect(second).toHaveAttribute("aria-expanded", "true");
|
||||
|
||||
await tap(second);
|
||||
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(sheet).toBeVisible();
|
||||
await tap(first);
|
||||
await tap(within(sheet).getByRole("heading", { name: "Context usage" }));
|
||||
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(sheet).toBeVisible();
|
||||
});
|
||||
|
||||
it("dismisses nested round details with Escape before the sheet, and supports dragging with details open", async () => {
|
||||
const { user, sheet, handle, trigger } = await openSheet();
|
||||
const first = within(sheet).getAllByTestId("round-usage-bar")[0];
|
||||
first.focus();
|
||||
await user.keyboard("{Enter}");
|
||||
expect(within(sheet).getByRole("dialog")).toBeVisible();
|
||||
await user.keyboard("{Escape}");
|
||||
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(sheet).toBeVisible();
|
||||
expect(first).toHaveFocus();
|
||||
|
||||
await user.click(first);
|
||||
pointer(handle, "pointerDown", { y: 400 });
|
||||
pointer(handle, "pointerMove", { y: 520, time: 1400 });
|
||||
pointer(handle, "pointerUp", { y: 520, time: 1500 });
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
|
||||
expect(trigger).toHaveFocus();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[100, 500], // Deliberate pull.
|
||||
[32, 40], // Short, quick downward flick.
|
||||
])("dismisses after dragging %dpx in %dms and opens at the original position", async (distance, duration) => {
|
||||
const { user, handle, sheet, trigger } = await openSheet();
|
||||
pointer(handle, "pointerDown", { y: 400 });
|
||||
pointer(handle, "pointerMove", { y: 400 + distance, time: 1000 + duration });
|
||||
// happy-dom doesn't expose individual transforms through getComputedStyle.
|
||||
expect(sheet.style.translate).toBe(`0 ${distance}px`);
|
||||
expect(sheet).toHaveStyle({ transition: "none" });
|
||||
pointer(handle, "pointerUp", { y: 400 + distance, time: 1000 + duration });
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
|
||||
expect(trigger).toHaveFocus();
|
||||
|
||||
await user.click(trigger);
|
||||
expect(screen.getByRole("dialog").style.translate).toBe("0 0px");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ end: "pointerUp" as const, y: 432, x: 160 },
|
||||
{ end: "pointerUp" as const, y: 370, x: 160 },
|
||||
{ end: "pointerUp" as const, y: 460, x: 260 },
|
||||
{ end: "pointerCancel" as const, y: 500, x: 160 },
|
||||
{ end: "lostPointerCapture" as const, y: 500, x: 160 },
|
||||
])("snaps back without a click-through on $end at ($x, $y)", async ({ end, y, x }) => {
|
||||
const { user, handle, sheet } = await openSheet();
|
||||
pointer(handle, "pointerDown", { y: 400 });
|
||||
pointer(handle, "pointerMove", { y, x, time: 1400 });
|
||||
pointer(handle, end, { y, x, time: 1500 });
|
||||
expect(sheet.style.translate).toBe("0 0px");
|
||||
expect(sheet.style.transition).toBe("");
|
||||
fireEvent.click(handle, { detail: 1 });
|
||||
expect(screen.getByRole("dialog")).toBeVisible();
|
||||
// A real subsequent tap must still close the sheet.
|
||||
await user.click(handle);
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
|
||||
});
|
||||
|
||||
it("does not capture content scrolling or let another pointer finish the drag", async () => {
|
||||
const { user, handle, sheet } = await openSheet();
|
||||
const content = within(sheet).getByRole("group", { name: "Input tokens" });
|
||||
pointer(content, "pointerDown", { y: 480 });
|
||||
pointer(content, "pointerMove", { y: 580 });
|
||||
pointer(content, "pointerUp", { y: 580, time: 1500 });
|
||||
expect(sheet.style.translate).toBe("0 0px");
|
||||
|
||||
pointer(handle, "pointerDown", { y: 400 });
|
||||
pointer(handle, "pointerMove", { y: 412 });
|
||||
pointer(handle, "pointerDown", { y: 412, id: 2 });
|
||||
pointer(handle, "pointerUp", { y: 600, id: 2 });
|
||||
expect(sheet.style.translate).toBe("0 12px");
|
||||
pointer(handle, "pointerUp", { y: 412, time: 1500 });
|
||||
expect(sheet.style.translate).toBe("0 0px");
|
||||
await user.keyboard("{Escape}");
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useState, type ComponentProps } from "react";
|
||||
import { act, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { SettingsSidebar } from "@/components/settings/SettingsSidebar";
|
||||
import {
|
||||
installSettingsViewTestHooks,
|
||||
renderSettingsView,
|
||||
settingsPayload,
|
||||
} from "@/tests/settings-test-utils";
|
||||
|
||||
function mockMobileMedia(initial = true) {
|
||||
const target = new EventTarget();
|
||||
const media = {
|
||||
matches: initial,
|
||||
media: "(max-width: 1023px)",
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: target.addEventListener.bind(target),
|
||||
removeEventListener: target.removeEventListener.bind(target),
|
||||
dispatchEvent: target.dispatchEvent.bind(target),
|
||||
};
|
||||
vi.stubGlobal("matchMedia", vi.fn(() => media));
|
||||
return (matches: boolean) => act(() => {
|
||||
media.matches = matches;
|
||||
target.dispatchEvent(new Event("change"));
|
||||
});
|
||||
}
|
||||
|
||||
function Sidebar(props: Partial<ComponentProps<typeof SettingsSidebar>>) {
|
||||
const [section, setSection] = useState(props.activeSection ?? "models");
|
||||
return <SettingsSidebar activeSection={section} onSelectSection={setSection}
|
||||
onBackToChat={() => {}} {...props} />;
|
||||
}
|
||||
|
||||
describe("Settings navigation on mobile", () => {
|
||||
installSettingsViewTestHooks();
|
||||
|
||||
it("keeps only back and the current section in the header; selects sections in a sheet", async () => {
|
||||
mockMobileMedia();
|
||||
const user = userEvent.setup();
|
||||
const restart = vi.fn();
|
||||
const back = vi.fn();
|
||||
render(<Sidebar onRestart={restart} onBackToChat={back} />);
|
||||
const header = screen.getByRole("complementary");
|
||||
expect(within(header).getAllByRole("button")).toHaveLength(2);
|
||||
const trigger = screen.getByRole("button", { name: "Settings: Models" });
|
||||
await user.click(trigger);
|
||||
const sheet = screen.getByRole("dialog", { name: "Settings" });
|
||||
expect(within(sheet).getByRole("button", { name: "Models", exact: true }))
|
||||
.toHaveAttribute("aria-current", "page");
|
||||
expect(within(sheet).getByRole("navigation", { name: "Settings sections" })).toBeVisible();
|
||||
expect(within(sheet).getByRole("button", { name: "Restart" })).toBeVisible();
|
||||
await user.click(within(sheet).getByRole("button", { name: "Appearance" }));
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(screen.getByRole("button", { name: "Settings: Appearance" })).toHaveFocus();
|
||||
expect(document.body.style.pointerEvents).not.toBe("none");
|
||||
expect(restart).not.toHaveBeenCalled();
|
||||
await user.click(screen.getByRole("button", { name: "Back to chat" }));
|
||||
expect(back).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("treats capability subpages as the same navigation section", async () => {
|
||||
mockMobileMedia();
|
||||
const user = userEvent.setup();
|
||||
render(<Sidebar activeSection="image" />);
|
||||
await user.click(screen.getByRole("button", { name: "Settings: Capabilities" }));
|
||||
expect(screen.getByRole("button", { name: "Capabilities", exact: true }))
|
||||
.toHaveAttribute("aria-current", "page");
|
||||
expect(screen.queryByRole("button", { name: "Restart" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(["close", "escape", "outside"])("dismisses with %s and restores focus and pointer events", async (method) => {
|
||||
mockMobileMedia();
|
||||
const user = userEvent.setup();
|
||||
render(<Sidebar />);
|
||||
const trigger = screen.getByRole("button", { name: "Settings: Models" });
|
||||
await user.click(trigger);
|
||||
if (method === "close") await user.click(screen.getByRole("button", { name: "Close" }));
|
||||
else if (method === "escape") await user.keyboard("{Escape}");
|
||||
else {
|
||||
// The real overlay is outside the modal content; ignore the locked page behind it.
|
||||
const overlay = document.querySelector<HTMLElement>('[data-state="open"][aria-hidden="true"]');
|
||||
expect(overlay).not.toBeNull();
|
||||
await user.click(overlay!);
|
||||
}
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(trigger).toHaveFocus();
|
||||
expect(document.body.style.pointerEvents).not.toBe("none");
|
||||
});
|
||||
|
||||
it("keeps manual restart in the sheet and closes it before handing off", async () => {
|
||||
mockMobileMedia();
|
||||
const user = userEvent.setup();
|
||||
const restart = vi.fn();
|
||||
render(<Sidebar onRestart={restart} />);
|
||||
expect(screen.queryByRole("button", { name: "Restart" })).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Settings: Models" }));
|
||||
await user.click(screen.getByRole("button", { name: "Restart" }));
|
||||
expect(restart).toHaveBeenCalledOnce();
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(document.body.style.pointerEvents).not.toBe("none");
|
||||
});
|
||||
|
||||
it("shows pending changes inline, disables restart while running, and clears the prompt after restart", async () => {
|
||||
mockMobileMedia();
|
||||
const user = userEvent.setup();
|
||||
const restart = vi.fn();
|
||||
const { rerender } = render(<Sidebar onRestart={restart} restartPending />);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Saved. Restart to apply changes.");
|
||||
await user.click(screen.getByRole("button", { name: "Restart", exact: true }));
|
||||
expect(restart).toHaveBeenCalledOnce();
|
||||
rerender(<Sidebar onRestart={restart} restartPending isRestarting />);
|
||||
const runningLabel = screen.getByRole("status").textContent!;
|
||||
expect(screen.getByRole("button", { name: runningLabel, exact: true })).toBeDisabled();
|
||||
await user.click(screen.getByRole("button", { name: "Settings: Models" }));
|
||||
expect(within(screen.getByRole("dialog")).getByRole("button", { name: runningLabel })).toBeDisabled();
|
||||
await user.keyboard("{Escape}");
|
||||
rerender(<Sidebar onRestart={restart} restartPending={false} />);
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Restart" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("releases the open sheet when crossing to desktop and does not reopen on return", async () => {
|
||||
const resize = mockMobileMedia();
|
||||
const user = userEvent.setup();
|
||||
const restart = vi.fn();
|
||||
render(<Sidebar onRestart={restart} />);
|
||||
await user.click(screen.getByRole("button", { name: "Settings: Models" }));
|
||||
resize(false);
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(document.body.style.pointerEvents).not.toBe("none");
|
||||
expect(screen.queryByRole("button", { name: "Settings: Models" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Models", exact: true })).toBeVisible();
|
||||
await user.click(screen.getByRole("button", { name: "Restart" }));
|
||||
expect(restart).toHaveBeenCalledOnce();
|
||||
resize(true);
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Settings: Models" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("still asks before leaving saved changes that need a restart", async () => {
|
||||
mockMobileMedia();
|
||||
const user = userEvent.setup();
|
||||
const back = vi.fn();
|
||||
renderSettingsView({ initialSection: "models", initialSettings: {
|
||||
...settingsPayload(), requires_restart: true,
|
||||
}, onBackToChat: back });
|
||||
await user.click(screen.getByRole("button", { name: "Settings: Models" }));
|
||||
await user.click(screen.getByRole("button", { name: "Appearance", exact: true }));
|
||||
await user.click(screen.getByRole("button", { name: "Back to chat" }));
|
||||
const dialog = screen.getByRole("dialog", { name: "Restart before leaving?" });
|
||||
expect(back).not.toHaveBeenCalled();
|
||||
await user.click(within(dialog).getByRole("button", { name: "Restart later" }));
|
||||
expect(back).toHaveBeenCalledOnce();
|
||||
await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none"));
|
||||
});
|
||||
});
|
||||
@@ -1190,7 +1190,7 @@ describe("ThreadComposer", () => {
|
||||
expect(onWorkspaceScopeChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["close button", "Escape"])("opens narrow context usage as a bottom sheet and restores interaction after %s", async (dismissal) => {
|
||||
it.each(["handle tap", "Escape"])("opens narrow context usage as a bottom sheet and restores interaction after %s", async (dismissal) => {
|
||||
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue(
|
||||
rect({ width: 390, height: 160 }),
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user