Skip to content

Your lightweight open-source personal agent.

refactor(webui): animate segmented control indicator

chengyongru0c4583b7f53d
diff --git a/webui/src/components/settings/models/ModelsSettings.tsx b/webui/src/components/settings/models/ModelsSettings.tsx
index d99ec31f4..1e83f09e7 100644
--- a/webui/src/components/settings/models/ModelsSettings.tsx
+++ b/webui/src/components/settings/models/ModelsSettings.tsx
@@ -954,6 +954,7 @@ function ModelAdvancedFields({
</span>
<SegmentedControl
value={String(contextWindowTokens)}
+ animateIndicator={false}
options={contextWindowOptions.map((tokens) => ({
value: String(tokens),
label: formatModelContextWindow(tokens),
diff --git a/webui/src/components/settings/overview/OverviewSettings.tsx b/webui/src/components/settings/overview/OverviewSettings.tsx
index 01c96b480..cbb514cac 100644
--- a/webui/src/components/settings/overview/OverviewSettings.tsx
+++ b/webui/src/components/settings/overview/OverviewSettings.tsx
@@ -38,7 +38,6 @@ import type {
} from "@/lib/local-preferences";
import { providerBrand, providerDisplayLabel } from "@/lib/provider-brand";
import type { SettingsPayload } from "@/lib/types";
-import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
export function OverviewSettings({
@@ -275,30 +274,19 @@ export function AppearanceSettings({
<SettingsSectionTitle>{t("settings.sections.interface")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow title={t("settings.rows.theme")}>
- <button
- type="button"
- onClick={onToggleTheme}
- className="inline-flex h-8 items-center rounded-full bg-muted p-0.5 text-[12px] font-medium text-muted-foreground"
- >
- <span
- className={cn(
- "rounded-full px-3 py-1 transition-colors",
- theme === "light" &&
- "bg-background text-foreground ring-1 ring-inset ring-border/45",
- )}
- >
- {t("settings.values.light")}
- </span>
- <span
- className={cn(
- "rounded-full px-3 py-1 transition-colors",
- theme === "dark" &&
- "bg-background text-foreground ring-1 ring-inset ring-border/45",
- )}
- >
- {t("settings.values.dark")}
- </span>
- </button>
+ <SegmentedControl
+ value={theme}
+ ariaLabel={t("settings.rows.theme")}
+ className="bg-muted p-0.5"
+ itemClassName="px-3"
+ options={[
+ { value: "light", label: t("settings.values.light") },
+ { value: "dark", label: t("settings.values.dark") },
+ ]}
+ onChange={(nextTheme) => {
+ if (nextTheme !== theme) onToggleTheme();
+ }}
+ />
</SettingsRow>
<SettingsRow title={t("settings.rows.language")}>
diff --git a/webui/src/components/settings/system/AutomationsSettings.tsx b/webui/src/components/settings/system/AutomationsSettings.tsx
index e9f600750..c5f47c9b9 100644
--- a/webui/src/components/settings/system/AutomationsSettings.tsx
+++ b/webui/src/components/settings/system/AutomationsSettings.tsx
@@ -254,6 +254,7 @@ export function AutomationsSettings({
value={view}
className="rounded-[var(--radius-panel)] bg-[var(--automation-view-track)]"
itemClassName="min-h-8 rounded-[calc(var(--radius-panel)-0.25rem)]"
+ indicatorClassName="rounded-[calc(var(--radius-panel)-0.25rem)]"
options={[
{ value: "tasks", label: tx("settings.automations.views.tasks", "Tasks") },
{ value: "calendar", label: tx("settings.automations.views.calendar", "Calendar") },
diff --git a/webui/src/components/ui/segmented-control.tsx b/webui/src/components/ui/segmented-control.tsx
index 59a3d2a10..841cff6a6 100644
--- a/webui/src/components/ui/segmented-control.tsx
+++ b/webui/src/components/ui/segmented-control.tsx
@@ -1,4 +1,10 @@
-import type { ReactNode } from "react";
+import {
+ useLayoutEffect,
+ useRef,
+ useState,
+ type KeyboardEvent,
+ type ReactNode,
+} from "react";
import { cn } from "@/lib/utils";
@@ -15,6 +21,26 @@ interface SegmentedControlProps<T extends string> {
mode?: "buttons" | "tabs";
className?: string;
itemClassName?: string;
+ indicatorClassName?: string;
+ animateIndicator?: boolean;
+}
+
+interface IndicatorGeometry {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ animate: boolean;
+}
+
+function sameGeometry(
+ previous: IndicatorGeometry,
+ next: Omit<IndicatorGeometry, "animate">,
+): boolean {
+ return previous.left === next.left
+ && previous.top === next.top
+ && previous.width === next.width
+ && previous.height === next.height;
}
export function SegmentedControl<T extends string>({
@@ -25,30 +51,123 @@ export function SegmentedControl<T extends string>({
mode = "buttons",
className,
itemClassName,
+ indicatorClassName,
+ animateIndicator = true,
}: SegmentedControlProps<T>) {
const tabs = mode === "tabs";
+ const rootRef = useRef<HTMLDivElement>(null);
+ const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);
+ const previousValueRef = useRef<T | undefined>(undefined);
+ const [indicator, setIndicator] = useState<IndicatorGeometry | null>(null);
+ const selectedIndex = options.findIndex((option) => option.value === value);
+ const optionValuesKey = options.map((option) => option.value).join("\u0000");
+
+ useLayoutEffect(() => {
+ const measure = (animate: boolean) => {
+ const item = itemRefs.current[selectedIndex];
+ if (!item) {
+ setIndicator(null);
+ return;
+ }
+
+ const next = {
+ left: item.offsetLeft,
+ top: item.offsetTop,
+ width: item.offsetWidth,
+ height: item.offsetHeight,
+ };
+ setIndicator((previous) => {
+ if (previous && sameGeometry(previous, next)) return previous;
+ return { ...next, animate: Boolean(previous) && animate };
+ });
+ };
+
+ const valueChanged = previousValueRef.current !== undefined
+ && previousValueRef.current !== value;
+ measure(valueChanged);
+ previousValueRef.current = value;
+
+ const handleResize = () => measure(false);
+ window.addEventListener("resize", handleResize);
+
+ const observer = typeof ResizeObserver === "undefined"
+ ? null
+ : new ResizeObserver(handleResize);
+ if (observer) {
+ if (rootRef.current) observer.observe(rootRef.current);
+ itemRefs.current.forEach((item) => {
+ if (item) observer.observe(item);
+ });
+ }
+
+ return () => {
+ window.removeEventListener("resize", handleResize);
+ observer?.disconnect();
+ };
+ }, [optionValuesKey, selectedIndex, value]);
+
+ const handleTabKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
+ if (!tabs) return;
+
+ let nextIndex: number | null = null;
+ if (event.key === "ArrowRight") nextIndex = (index + 1) % options.length;
+ if (event.key === "ArrowLeft") nextIndex = (index - 1 + options.length) % options.length;
+ if (event.key === "Home") nextIndex = 0;
+ if (event.key === "End") nextIndex = options.length - 1;
+ if (nextIndex === null) return;
+
+ event.preventDefault();
+ const next = options[nextIndex];
+ if (!next) return;
+ onChange(next.value);
+ itemRefs.current[nextIndex]?.focus();
+ };
+
return (
<div
- role={tabs ? "tablist" : undefined}
+ ref={rootRef}
+ role={tabs ? "tablist" : ariaLabel ? "group" : undefined}
aria-label={ariaLabel}
className={cn(
- "segmented-control inline-flex min-h-8 max-w-full flex-nowrap items-center gap-1 rounded-full bg-muted/65 p-1 text-[12px] font-medium text-muted-foreground",
+ "segmented-control relative isolate inline-flex min-h-8 max-w-full flex-nowrap items-center gap-1 rounded-full bg-muted/65 p-1 text-[12px] font-medium text-muted-foreground",
className,
)}
>
- {options.map((option) => {
+ {indicator ? (
+ <span
+ aria-hidden
+ data-segmented-control-indicator
+ data-animate={indicator.animate && animateIndicator ? "true" : "false"}
+ className={cn(
+ "segmented-control-indicator pointer-events-none absolute left-0 z-0 rounded-full bg-background shadow-[0_1px_2px_hsl(var(--foreground)/0.08)] ring-1 ring-inset ring-border/25",
+ indicatorClassName,
+ )}
+ style={{
+ top: indicator.top,
+ width: indicator.width,
+ height: indicator.height,
+ transform: `translate3d(${indicator.left}px, 0, 0)`,
+ }}
+ />
+ ) : null}
+ {options.map((option, index) => {
const selected = value === option.value;
return (
<button
+ ref={(item) => {
+ itemRefs.current[index] = item;
+ }}
key={option.value}
type="button"
role={tabs ? "tab" : undefined}
aria-selected={tabs ? selected : undefined}
aria-pressed={tabs ? undefined : selected}
+ tabIndex={tabs ? (selected || (selectedIndex < 0 && index === 0) ? 0 : -1) : undefined}
onClick={() => onChange(option.value)}
+ onKeyDown={(event) => handleTabKeyDown(event, index)}
className={cn(
- "min-w-0 truncate whitespace-nowrap rounded-full px-2 py-1 text-muted-foreground transition-colors",
- selected ? "bg-background text-foreground" : "hover:text-foreground",
+ "relative z-[1] min-w-0 truncate whitespace-nowrap rounded-full px-2 py-1 text-muted-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ selected ? "text-foreground" : "hover:text-foreground",
itemClassName,
)}
>
diff --git a/webui/src/globals.css b/webui/src/globals.css
index dccf1d491..522ab22a8 100644
--- a/webui/src/globals.css
+++ b/webui/src/globals.css
@@ -1004,6 +1004,18 @@
}
}
+@layer components {
+ @media (prefers-reduced-motion: no-preference) {
+ .segmented-control-indicator[data-animate="true"] {
+ transition-property: transform, width;
+ transition-duration: 220ms, 160ms;
+ transition-timing-function:
+ cubic-bezier(0.2, 0.95, 0.25, 1.08),
+ cubic-bezier(0.2, 0, 0, 1);
+ }
+ }
+}
+
/* Settings grid: 4px baseline; 720px frame; 12 columns / 24px gutter on
desktop, 4 columns / 16px gutter on mobile. Rows share the same tracks. */
@layer components {
diff --git a/webui/src/tests/segmented-control.test.tsx b/webui/src/tests/segmented-control.test.tsx
new file mode 100644
index 000000000..df318de03
--- /dev/null
+++ b/webui/src/tests/segmented-control.test.tsx
@@ -0,0 +1,118 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
+import { describe, expect, it, vi } from "vitest";
+
+import { SegmentedControl } from "@/components/ui/segmented-control";
+
+function setGeometry(
+ item: HTMLElement,
+ geometry: { left: number; top?: number; width: number; height?: number },
+) {
+ Object.defineProperties(item, {
+ offsetLeft: { configurable: true, value: geometry.left },
+ offsetTop: { configurable: true, value: geometry.top ?? 4 },
+ offsetWidth: { configurable: true, value: geometry.width },
+ offsetHeight: { configurable: true, value: geometry.height ?? 24 },
+ });
+}
+
+function Example({
+ mode = "buttons",
+ animateIndicator = true,
+}: {
+ mode?: "buttons" | "tabs";
+ animateIndicator?: boolean;
+}) {
+ const [value, setValue] = useState("summary");
+ return (
+ <SegmentedControl
+ value={value}
+ mode={mode}
+ animateIndicator={animateIndicator}
+ ariaLabel="File edit display"
+ options={[
+ { value: "summary", label: "Summary" },
+ { value: "diff", label: "Diff" },
+ { value: "collapsed", label: "Collapsed diff" },
+ ]}
+ onChange={setValue}
+ />
+ );
+}
+
+describe("SegmentedControl", () => {
+ it("moves one shared indicator while the segment labels stay in place", () => {
+ const { container } = render(<Example />);
+ const summary = screen.getByRole("button", { name: "Summary" });
+ const diff = screen.getByRole("button", { name: "Diff" });
+ const collapsed = screen.getByRole("button", { name: "Collapsed diff" });
+ setGeometry(summary, { left: 4, width: 64 });
+ setGeometry(diff, { left: 72, width: 48 });
+ setGeometry(collapsed, { left: 124, width: 92 });
+
+ fireEvent(window, new Event("resize"));
+ const indicator = container.querySelector<HTMLElement>(
+ "[data-segmented-control-indicator]",
+ );
+ expect(indicator).not.toBeNull();
+ expect(indicator).toHaveStyle({
+ top: "4px",
+ width: "64px",
+ height: "24px",
+ transform: "translate3d(4px, 0, 0)",
+ });
+ expect(indicator).toHaveAttribute("aria-hidden", "true");
+ expect(indicator).toHaveAttribute("data-animate", "false");
+
+ fireEvent.click(diff);
+
+ expect(indicator).toHaveStyle({
+ width: "48px",
+ transform: "translate3d(72px, 0, 0)",
+ });
+ expect(indicator).toHaveAttribute("data-animate", "true");
+ expect(summary).toHaveAttribute("aria-pressed", "false");
+ expect(diff).toHaveAttribute("aria-pressed", "true");
+ });
+
+ it("uses roving focus and arrow-key activation for tabs", () => {
+ const onChange = vi.fn();
+ render(
+ <SegmentedControl
+ value="summary"
+ mode="tabs"
+ ariaLabel="Views"
+ options={[
+ { value: "summary", label: "Summary" },
+ { value: "diff", label: "Diff" },
+ ]}
+ onChange={onChange}
+ />,
+ );
+ const summary = screen.getByRole("tab", { name: "Summary" });
+ const diff = screen.getByRole("tab", { name: "Diff" });
+ expect(summary).toHaveAttribute("tabindex", "0");
+ expect(diff).toHaveAttribute("tabindex", "-1");
+
+ summary.focus();
+ fireEvent.keyDown(summary, { key: "ArrowRight" });
+
+ expect(onChange).toHaveBeenCalledWith("diff");
+ expect(diff).toHaveFocus();
+ });
+
+ it("can disable motion when the set of segments is dynamic", () => {
+ const { container } = render(<Example animateIndicator={false} />);
+ const summary = screen.getByRole("button", { name: "Summary" });
+ const diff = screen.getByRole("button", { name: "Diff" });
+ setGeometry(summary, { left: 4, width: 64 });
+ setGeometry(diff, { left: 72, width: 48 });
+
+ fireEvent(window, new Event("resize"));
+ fireEvent.click(diff);
+
+ expect(
+ container.querySelector("[data-segmented-control-indicator]"),
+ ).toHaveAttribute("data-animate", "false");
+ });
+});