🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feat(ui): sliding tab indicators and one segmented control for every toggle (#1258)
Goldflagfdd68242df0f
diff --git a/client/src/app/[site]/bots/page.tsx b/client/src/app/[site]/bots/page.tsxindex 881e2fb21..126fdc4a2 100644--- a/client/src/app/[site]/bots/page.tsx+++ b/client/src/app/[site]/bots/page.tsx@@ -1,8 +1,9 @@"use client";+import { useExtracted } from "next-intl";import { ReactNode } from "react";import { BOT_AVAILABLE_FILTERS } from "../../../api/analytics/hooks/bots/constants";-import { Tabs, TabsList, TabsTrigger } from "../../../components/ui/tabs";+import { SegmentedControl } from "../../../components/interior/segmented-control";import { useInView } from "../../../hooks/useInView";import { useSetPageTitle } from "../../../hooks/useSetPageTitle";import { useStore } from "../../../lib/store";@@ -20,7 +21,7 @@ import { BotDevices } from "./components/sections/BotDevices";import { BotMetadata } from "./components/sections/BotMetadata";import { BotPages } from "./components/sections/BotPages";import { BotReferrers } from "./components/sections/BotReferrers";-import { useBotsStore } from "./botsStore";+import { type BotsLens, useBotsStore } from "./botsStore";function LazySection({ children, height = "405px" }: { children: ReactNode; height?: string }) {const { ref, isInView } = useInView({ persistVisibility: true, rootMargin: "100px 0px" });@@ -86,6 +87,7 @@ function AllBotsLens() {}export default function BotsPage() {+ const t = useExtracted();const { site } = useStore();const { lens, setLens } = useBotsStore();useSetPageTitle("Bots");@@ -97,12 +99,15 @@ export default function BotsPage() {return (<div className="p-2 md:p-4 max-w-[1100px] mx-auto space-y-3"><SubHeader availableFilters={BOT_AVAILABLE_FILTERS} />- <Tabs value={lens} onValueChange={value => setLens(value as typeof lens)}>- <TabsList>- <TabsTrigger value="ai">AI & agents</TabsTrigger>- <TabsTrigger value="all">All bots</TabsTrigger>- </TabsList>- </Tabs>+ <SegmentedControl<BotsLens>+ aria-label={t("Bot traffic view")}+ options={[+ { value: "ai", label: t("AI & agents") },+ { value: "all", label: t("All bots") },+ ]}+ value={lens}+ onValueChange={setLens}+ />{lens === "ai" ? <AiLens /> : <AllBotsLens />}</div>);diff --git a/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx b/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsxindex e8cc57884..a08a35931 100644--- a/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx+++ b/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx@@ -6,11 +6,11 @@ import { useExtracted } from "next-intl";import { useRef, useState } from "react";import { useUserOrganizations } from "../../../../../api/admin/hooks/useOrganizations";import { useGetSite } from "../../../../../api/admin/hooks/useSites";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";import { Button } from "../../../../../components/ui/button";import { Popover, PopoverContent, PopoverTrigger } from "../../../../../components/ui/popover";import { authClient } from "../../../../../lib/auth";import { addFilter, useStore } from "../../../../../lib/store";-import { cn } from "../../../../../lib/utils";import { FilterPicker } from "./FilterPicker";import { SegmentDialog } from "./SegmentDialog";import { SegmentsTab } from "./SegmentsTab";@@ -72,23 +72,6 @@ export function NewFilterButton({ availableFilters }: { availableFilters?: FiltesetDialog(state);};- const tabButton = (value: Tab, label: string) => (- <button- type="button"- role="tab"- aria-selected={tab === value}- onClick={() => selectTab(value)}- className={cn(- "flex-1 py-2 text-xs font-medium border-b-2 -mb-px transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400",- tab === value- ? "border-neutral-900 dark:border-neutral-100 text-neutral-900 dark:text-neutral-50"- : "border-transparent text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200"- )}- >- {label}- </button>- );-return (<><Popover open={open} onOpenChange={handleOpenChange}>@@ -99,29 +82,37 @@ export function NewFilterButton({ availableFilters }: { availableFilters?: Filte</Button></PopoverTrigger><PopoverContent className="w-72 p-0" align="start">- <div role="tablist" className="flex border-b border-neutral-200 dark:border-neutral-700">- {tabButton("filters", t("Filters"))}- {tabButton("segments", t("Segments"))}- </div>- {tab === "filters" ? (- <FilterPicker- availableFilters={availableFilters}- onCommit={addFilter}- onClose={closePopover}- pendingRef={pendingRef}- parameter={parameter}- setParameter={setParameter}- />- ) : (- <SegmentsTab- siteId={site}- canWrite={canWrite}- onNew={() => openDialog({})}- onSaveCurrent={() => openDialog({ initialFilters: filters })}- onEdit={segment => openDialog({ segment })}- onApplied={closePopover}- />- )}+ <Tabs value={tab} onValueChange={value => selectTab(value as Tab)}>+ {/* Full-width underline tabs; -mb-px lays the underline over the list's hairline. */}+ <TabsList className="flex h-auto w-full space-x-0 border-b border-neutral-200 dark:border-neutral-700">+ <TabsTrigger value="filters" className="-mb-px flex-1 py-2 text-xs">+ {t("Filters")}+ </TabsTrigger>+ <TabsTrigger value="segments" className="-mb-px flex-1 py-2 text-xs">+ {t("Segments")}+ </TabsTrigger>+ </TabsList>+ <TabsContent value="filters" className="mt-0">+ <FilterPicker+ availableFilters={availableFilters}+ onCommit={addFilter}+ onClose={closePopover}+ pendingRef={pendingRef}+ parameter={parameter}+ setParameter={setParameter}+ />+ </TabsContent>+ <TabsContent value="segments" className="mt-0">+ <SegmentsTab+ siteId={site}+ canWrite={canWrite}+ onNew={() => openDialog({})}+ onSaveCurrent={() => openDialog({ initialFilters: filters })}+ onEdit={segment => openDialog({ segment })}+ onApplied={closePopover}+ />+ </TabsContent>+ </Tabs></PopoverContent></Popover><SegmentDialogdiff --git a/client/src/app/[site]/dashboards/components/DashboardCardEditor.tsx b/client/src/app/[site]/dashboards/components/DashboardCardEditor.tsxindex 049006152..b110c5f43 100644--- a/client/src/app/[site]/dashboards/components/DashboardCardEditor.tsx+++ b/client/src/app/[site]/dashboards/components/DashboardCardEditor.tsx@@ -1,8 +1,10 @@"use client";import type { DashboardCard, DashboardCardMapping, DashboardValueFormat, DashboardVizType } from "@rybbit/shared";+import { useExtracted } from "next-intl";import { useMemo, useState } from "react";import { useDashboardCard } from "../../../../api/analytics/hooks/useDashboardCard";+import { SegmentedControl } from "../../../../components/interior/segmented-control";import { Button } from "../../../../components/ui/button";import {DropdownMenu,@@ -41,7 +43,6 @@ import {Table2,X,} from "lucide-react";-import { cn } from "../../../../lib/utils";import { JsonEditor } from "../../feature-flags/components/JsonEditor";import { QueryEditor } from "../../query/components/QueryEditor";import { ResultsTable } from "../../query/components/ResultsTable";@@ -246,6 +247,7 @@ function FormatSelect({}export function DashboardCardEditor({ siteId, card, open, onClose, onSave }: DashboardCardEditorProps) {+ const t = useExtracted();const [title, setTitle] = useState(card.title);const [sql, setSql] = useState(card.sql);const [vizType, setVizType] = useState<DashboardVizType>(card.vizType);@@ -547,26 +549,27 @@ export function DashboardCardEditor({ siteId, card, open, onClose, onSave }: Dasdisabled={mode === "json"}className="min-w-0 flex-1 rounded-md bg-transparent px-2 py-1 text-base font-semibold text-neutral-900 outline-none transition-colors placeholder:text-neutral-400 hover:bg-neutral-100 focus:bg-neutral-100 focus-visible:ring-1 focus-visible:ring-neutral-300 disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:bg-transparent dark:text-neutral-50 dark:placeholder:text-neutral-600 dark:hover:bg-neutral-900 dark:focus:bg-neutral-900 dark:focus-visible:ring-neutral-700"/>- {/* Mode toggle: visual builder vs. the full card object as JSON. */}- <div className="flex shrink-0 items-center rounded-lg border border-neutral-150 p-0.5 dark:border-neutral-850">- {(["visual", "json"] as const).map(value => (- <button- key={value}- type="button"- onClick={() => switchMode(value)}- aria-pressed={mode === value}- className={cn(- "flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors",- mode === value- ? "bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100"- : "text-neutral-500 hover:text-neutral-800 dark:hover:text-neutral-300"- )}- >- {value === "json" && <Braces className="h-3.5 w-3.5" />}- {value === "visual" ? "Visual" : "JSON"}- </button>- ))}- </div>+ {/* Mode toggle: visual builder vs. the full card object as JSON. switchMode+ may refuse to leave JSON while it is invalid; the control follows `mode`. */}+ <SegmentedControl<EditorMode>+ aria-label={t("Editor mode")}+ size="sm"+ className="shrink-0"+ options={[+ { value: "visual", label: t("Visual") },+ {+ value: "json",+ label: (+ <>+ <Braces className="h-3.5 w-3.5" />+ {t("JSON")}+ </>+ ),+ },+ ]}+ value={mode}+ onValueChange={switchMode}+ /><SheetClose asChild><Button variant="ghost" size="smIcon" aria-label="Close editor" className="shrink-0 text-neutral-500"><X className="h-4 w-4" />diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsxindex 8d9b6fa4a..dc17e543b 100644--- a/client/src/app/[site]/funnels/components/Funnel.tsx+++ b/client/src/app/[site]/funnels/components/Funnel.tsx@@ -9,7 +9,7 @@ import { useGetFunnelStepSessions } from "../../../../api/analytics/hooks/funnelimport { EventTypeIcon } from "../../../../components/EventIcons";import { targetTypeToEventType } from "../../../../lib/events";import { SessionsList } from "../../../../components/Sessions/SessionsList";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components/ui/tabs";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components/ui/basic-tabs";import { useStore } from "../../../../lib/store";export type FunnelChartData = {diff --git a/client/src/app/[site]/globe/components/ModeSelector.tsx b/client/src/app/[site]/globe/components/ModeSelector.tsxindex 551dad6e3..e8706ffcd 100644--- a/client/src/app/[site]/globe/components/ModeSelector.tsx+++ b/client/src/app/[site]/globe/components/ModeSelector.tsx@@ -1,37 +1,22 @@-import { cn } from "@/lib/utils";import { Clock, Globe2, HouseIcon, Radio } from "lucide-react";import { useExtracted } from "next-intl";+import type { ReactNode } from "react";+import { SegmentedControl } from "@/components/interior/segmented-control";import { useGlobeStore } from "../globeStore";export type MapView = "countries" | "subdivisions" | "coordinates" | "timeline";-interface TabButtonProps {- active: boolean;- onClick: () => void;- icon?: React.ReactNode;- label: string;-}--function TabButton({ active, onClick, icon, label }: TabButtonProps) {- return (- <button- onClick={onClick}- className={cn(- "h-[24px] inline-flex items-center justify-center whitespace-nowrap rounded px-2 py-1 text-xs font-medium transition-all",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400",- active ? "bg-neutral-800/50 text-white" : "text-neutral-200 hover:text-neutral-100 hover:bg-neutral-800/50"- )}- >- {icon}- <div className="hidden md:block">{label}</div>- </button>- );-}-export default function MapViewSelector() {const { mapView, setMapView, mapMode, setMapMode } = useGlobeStore();const t = useExtracted();+ const views: { value: MapView; label: string; icon: ReactNode }[] = [+ { value: "timeline", label: t("Timeline"), icon: <Clock className="md:opacity-60" size={14} /> },+ { value: "coordinates", label: t("Coordinates"), icon: <Radio className="md:opacity-60" size={14} /> },+ { value: "countries", label: t("Countries"), icon: <Globe2 className="md:opacity-60" size={14} /> },+ { value: "subdivisions", label: t("Subdivisions"), icon: <HouseIcon className="md:opacity-60" size={14} /> },+ ];+return (<div className="flex items-center gap-2 overflow-x-auto w-full"><button@@ -40,32 +25,25 @@ export default function MapViewSelector() {>{mapMode === "2D" ? "2D" : "3D"}</button>- <div className="flex items-center gap-0.5 rounded-lg bg-neutral-900/50 backdrop-blur-sm p-0.5 border border-neutral-800/50">- <TabButton- active={mapView === "timeline"}- onClick={() => setMapView("timeline")}- icon={<Clock className="mr-1 md:opacity-60" size={14} />}- label={t("Timeline")}- />- <TabButton- active={mapView === "coordinates"}- onClick={() => setMapView("coordinates")}- icon={<Radio className="mr-1 md:opacity-60" size={14} />}- label={t("Coordinates")}- />- <TabButton- active={mapView === "countries"}- onClick={() => setMapView("countries")}- icon={<Globe2 className="mr-1 md:opacity-60" size={14} />}- label={t("Countries")}- />- <TabButton- active={mapView === "subdivisions"}- onClick={() => setMapView("subdivisions")}- icon={<HouseIcon className="mr-1 md:opacity-60" size={14} />}- label={t("Subdivisions")}- />- </div>+ <SegmentedControl<MapView>+ aria-label={t("Map view")}+ size="sm"+ variant="overlay"+ className="shrink-0"+ options={views.map(view => ({+ value: view.value,+ // The text hides below md, leaving the icon: name each segment explicitly.+ ariaLabel: view.label,+ label: (+ <>+ {view.icon}+ <span className="hidden md:inline">{view.label}</span>+ </>+ ),+ }))}+ value={mapView}+ onValueChange={setMapView}+ /></div>);}diff --git a/client/src/app/[site]/main/components/sections/Referrers.tsx b/client/src/app/[site]/main/components/sections/Referrers.tsxindex e5bbba78d..29eaaef70 100644--- a/client/src/app/[site]/main/components/sections/Referrers.tsx+++ b/client/src/app/[site]/main/components/sections/Referrers.tsx@@ -8,6 +8,7 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "../../../../../components/ui/dropdown-menu";+import { TabsUnderline } from "../../../../../components/interior/tabs-indicator";import { cn } from "../../../../../lib/utils";import {StandardSectionTabs,@@ -119,10 +120,10 @@ export function Referrers() {<DropdownMenuTrigger asChild unstyled><divclassName={cn(- "inline-flex items-center justify-center whitespace-nowrap border-b-2 py-1 text-sm font-medium transition-all cursor-pointer",+ "relative inline-flex items-center justify-center whitespace-nowrap border-b-2 border-transparent py-1 text-sm font-medium transition-colors cursor-pointer",value.startsWith("utm_")- ? "border-neutral-950 text-neutral-950 dark:border-neutral-100 dark:text-neutral-50"- : "border-transparent text-neutral-600 dark:text-neutral-400"+ ? "text-neutral-950 dark:text-neutral-50"+ : "text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-200")}>{value === "utm_source" && t("Source")}@@ -131,6 +132,8 @@ export function Referrers() {{value === "utm_term" && t("Term")}{value === "utm_content" && t("Content")}{!value.startsWith("utm_") && t("UTM")}+ {/* The tab strip's sliding underline lands here while a UTM view is active. */}+ {value.startsWith("utm_") && <TabsUnderline />}</div></DropdownMenuTrigger><DropdownMenuContent align="start" className="z-[10000]">diff --git a/client/src/app/[site]/performance/components/PercentileSelector.tsx b/client/src/app/[site]/performance/components/PercentileSelector.tsxindex 0b826f83e..32f6b99ec 100644--- a/client/src/app/[site]/performance/components/PercentileSelector.tsx+++ b/client/src/app/[site]/performance/components/PercentileSelector.tsx@@ -1,6 +1,7 @@"use client";-import { ToggleChip } from "@/components/ToggleChip";+import { useExtracted } from "next-intl";+import { SegmentedControl } from "@/components/interior/segmented-control";import { PercentileLevel, usePerformanceStore } from "../performanceStore";const PERCENTILE_OPTIONS: {@@ -15,19 +16,25 @@ const PERCENTILE_OPTIONS: {];export function PercentileSelector() {+ const t = useExtracted();const { selectedPercentile, setSelectedPercentile } = usePerformanceStore();return (- <div className="flex items-center space-x-2">- {PERCENTILE_OPTIONS.map(option => (- <ToggleChip- key={option.value}- isSelected={selectedPercentile === option.value}- onClick={() => setSelectedPercentile(option.value)}- swatchColor={option.color}- label={option.label}- />- ))}- </div>+ <SegmentedControl<PercentileLevel>+ aria-label={t("Percentile")}+ size="sm"+ options={PERCENTILE_OPTIONS.map(option => ({+ value: option.value,+ // The swatch matches this percentile's line in the chart below.+ label: (+ <>+ <span aria-hidden className="h-2.5 w-2.5 rounded-sm" style={{ backgroundColor: option.color }} />+ {option.label}+ </>+ ),+ }))}+ value={selectedPercentile}+ onValueChange={setSelectedPercentile}+ />);}diff --git a/client/src/app/[site]/retention/page.tsx b/client/src/app/[site]/retention/page.tsxindex 7916f0867..33997b475 100644--- a/client/src/app/[site]/retention/page.tsx+++ b/client/src/app/[site]/retention/page.tsx@@ -9,9 +9,9 @@ import { RetentionMode } from "../../../api/analytics/endpoints";import { DisabledOverlay } from "../../../components/DisabledOverlay";import { ThreeDotLoader } from "../../../components/Loaders";import { NothingFound } from "../../../components/NothingFound";+import { SegmentedControl } from "../../../components/interior/segmented-control";import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";-import { Tabs, TabsList, TabsTrigger } from "../../../components/ui/tabs";import { useSetPageTitle } from "../../../hooks/useSetPageTitle";import { MobileSidebar } from "../components/Sidebar/MobileSidebar";import { RetentionChart } from "./RetentionChart";@@ -116,23 +116,23 @@ export default function RetentionPage() {return mode === "day" ? t("Day {index}", { index: String(index) }) : t("Week {index}", { index: String(index) });};- const handleModeChange = (newMode: string) => {- setMode(newMode as RetentionMode);- };-const handleRangeChange = (value: string) => {setTimeRange(parseInt(value));};- // Common filters for both views- const FilterControls = () => (+ // Rendered above every state (data, empty, error) so the controls the empty+ // state points to are always there. An element, not an inline component:+ // an inline component remounts each render, dropping focus and the thumb's+ // slide. The controls stay live while a query loads (a new choice just+ // changes the query key); the loading region is marked aria-busy instead.+ const filterControls = (<div className="flex justify-between items-center"><div><MobileSidebar /></div><div className="flex items-center gap-3 flex-wrap justify-end"><div className="flex items-center gap-2">- <Select value={timeRange.toString()} onValueChange={handleRangeChange} disabled={isLoading}>+ <Select value={timeRange.toString()} onValueChange={handleRangeChange}><SelectTrigger id="time-range"><SelectValue /></SelectTrigger>@@ -147,48 +147,20 @@ export default function RetentionPage() {</SelectContent></Select></div>- <Tabs value={mode} onValueChange={handleModeChange}>- <TabsList>- <TabsTrigger value="day" disabled={isLoading}>- {t("Daily")}- </TabsTrigger>- <TabsTrigger value="week" disabled={isLoading}>- {t("Weekly")}- </TabsTrigger>- </TabsList>- </Tabs>+ <SegmentedControl<RetentionMode>+ aria-label={t("Cohort period")}+ options={[+ { value: "day", label: t("Daily") },+ { value: "week", label: t("Weekly") },+ ]}+ value={mode}+ onValueChange={setMode}+ /></div></div>);- // Render error state- if (isError) {- return (- <div className="pt-4">- <Card>- <CardContent>- <ErrorState- title={t("Failed to load retention data")}- message={t("There was a problem fetching the retention data. Please try again later.")}- />- </CardContent>- </Card>- </div>- );- }-- // Render empty state- if (data && (!data.cohorts || cohortKeys.length === 0)) {- return (- <div className="p-2 md:p-4 max-w-[1300px] mx-auto flex flex-col gap-3">- <NothingFound- icon={<ChartColumnDecreasing className="w-10 h-10" />}- title={t("No retention data available")}- description={t("Try selecting a different time range or make sure you have tracking data in the system.")}- />- </div>- );- }+ const isEmpty = !!data && (!data.cohorts || cohortKeys.length === 0);const periodHeaders =!isLoading && data ? Array.from({ length: data.maxPeriods + 1 }, (_, i) => getPeriodLabel(i)) : [];@@ -196,82 +168,100 @@ export default function RetentionPage() {return (<DisabledOverlay message="Retention" featurePath="retention"><div className="p-2 md:p-4 max-w-[1300px] mx-auto flex flex-col gap-3">- {/* Single Card containing both chart and grid */}- <FilterControls />- <Card className="overflow-visible">- <CardHeader className="flex flex-row items-center justify-between pb-2">- <CardTitle>{t("Retention")}</CardTitle>- </CardHeader>- <CardContent className="space-y-6 overflow-visible">- {isLoading ? (- <ThreeDotLoader />- ) : data ? (- <RetentionChart data={data} isLoading={false} mode={mode} />- ) : null}- </CardContent>- </Card>- <Card className="pt-3">- <CardContent className="space-y-6 px-2">- <div>- {isLoading ? (- <ThreeDotLoader />- ) : data ? (- <div className="overflow-x-auto">- <div- className="inline-grid gap-px bg-neutral-50 dark:bg-neutral-900 rounded-lg"- style={{- gridTemplateColumns: `minmax(120px, auto) repeat(${data.maxPeriods + 1}, minmax(80px, auto))`,- }}- >- {/* Header Row */}- <div className="p-2 text-sm font-semibold bg-white dark:bg-neutral-900 text-neutral-600 dark:text-neutral-100 text-center sticky left-0 z-10 border-b border-r border-neutral-50 dark:border-neutral-700">- {t("Cohort")}- </div>- {periodHeaders.map(header => (+ {filterControls}+ {isError ? (+ <Card>+ <CardContent>+ <ErrorState+ title={t("Failed to load retention data")}+ message={t("There was a problem fetching the retention data. Please try again later.")}+ />+ </CardContent>+ </Card>+ ) : isEmpty ? (+ <NothingFound+ icon={<ChartColumnDecreasing className="w-10 h-10" />}+ title={t("No retention data available")}+ description={t("Try selecting a different time range or make sure you have tracking data in the system.")}+ />+ ) : (+ <>+ <Card className="overflow-visible" aria-busy={isLoading}>+ <CardHeader className="flex flex-row items-center justify-between pb-2">+ <CardTitle>{t("Retention")}</CardTitle>+ </CardHeader>+ <CardContent className="space-y-6 overflow-visible">+ {isLoading ? (+ <ThreeDotLoader />+ ) : data ? (+ <RetentionChart data={data} isLoading={false} mode={mode} />+ ) : null}+ </CardContent>+ </Card>+ <Card className="pt-3" aria-busy={isLoading}>+ <CardContent className="space-y-6 px-2">+ <div>+ {isLoading ? (+ <ThreeDotLoader />+ ) : data ? (+ <div className="overflow-x-auto"><div- key={header}- className="p-2 text-sm bg-white dark:bg-neutral-900 text-neutral-600 dark:text-neutral-100 text-center border-b border-neutral-50 dark:border-neutral-700"+ className="inline-grid gap-px bg-neutral-50 dark:bg-neutral-900 rounded-lg"+ style={{+ gridTemplateColumns: `minmax(120px, auto) repeat(${data.maxPeriods + 1}, minmax(80px, auto))`,+ }}>- {header}- </div>- ))}-- {/* Data Rows */}- {cohortKeys.map(cohortPeriod => (- <Fragment key={cohortPeriod}>- {/* Cohort Info Cell */}- <div className="p-2 bg-white dark:bg-neutral-900 text-sm sticky left-0 z-10 border-r border-neutral-50 dark:border-neutral-800">- <div className="whitespace-nowrap text-neutral-700 dark:text-neutral-100">- {formatDate(cohortPeriod)}- </div>- <div className="text-xs text-neutral-500 dark:text-neutral-300 mt-1 whitespace-nowrap">- {t("{count} users", { count: data.cohorts[cohortPeriod].size.toLocaleString() })}- </div>+ {/* Header Row */}+ <div className="p-2 text-sm font-semibold bg-white dark:bg-neutral-900 text-neutral-600 dark:text-neutral-100 text-center sticky left-0 z-10 border-b border-r border-neutral-50 dark:border-neutral-700">+ {t("Cohort")}</div>- {/* Retention Cells */}- {data.cohorts[cohortPeriod].percentages.map((percentage: number | null, index: number) => {- const { backgroundColor, textColor } = getRetentionColor(percentage, isDark);- return (- <div- key={`${cohortPeriod}-period-${index}`}- className="m-[2px] text-center flex items-center justify-center font-medium transition-colors duration-150 bg-white dark:bg-neutral-900 rounded-md"- style={{- backgroundColor,- color: textColor,- }}- >- {percentage !== null ? `${percentage.toFixed(1)}%` : "-"}+ {periodHeaders.map(header => (+ <div+ key={header}+ className="p-2 text-sm bg-white dark:bg-neutral-900 text-neutral-600 dark:text-neutral-100 text-center border-b border-neutral-50 dark:border-neutral-700"+ >+ {header}+ </div>+ ))}++ {/* Data Rows */}+ {cohortKeys.map(cohortPeriod => (+ <Fragment key={cohortPeriod}>+ {/* Cohort Info Cell */}+ <div className="p-2 bg-white dark:bg-neutral-900 text-sm sticky left-0 z-10 border-r border-neutral-50 dark:border-neutral-800">+ <div className="whitespace-nowrap text-neutral-700 dark:text-neutral-100">+ {formatDate(cohortPeriod)}+ </div>+ <div className="text-xs text-neutral-500 dark:text-neutral-300 mt-1 whitespace-nowrap">+ {t("{count} users", { count: data.cohorts[cohortPeriod].size.toLocaleString() })}+ </div></div>- );- })}- </Fragment>- ))}- </div>+ {/* Retention Cells */}+ {data.cohorts[cohortPeriod].percentages.map((percentage: number | null, index: number) => {+ const { backgroundColor, textColor } = getRetentionColor(percentage, isDark);+ return (+ <div+ key={`${cohortPeriod}-period-${index}`}+ className="m-[2px] text-center flex items-center justify-center font-medium transition-colors duration-150 bg-white dark:bg-neutral-900 rounded-md"+ style={{+ backgroundColor,+ color: textColor,+ }}+ >+ {percentage !== null ? `${percentage.toFixed(1)}%` : "-"}+ </div>+ );+ })}+ </Fragment>+ ))}+ </div>+ </div>+ ) : null}</div>- ) : null}- </div>- </CardContent>- </Card>+ </CardContent>+ </Card>+ </>+ )}</div></DisabledOverlay>);diff --git a/client/src/app/rollup/components/sections/Referrers.tsx b/client/src/app/rollup/components/sections/Referrers.tsxindex 2b4cea0f3..9cc223719 100644--- a/client/src/app/rollup/components/sections/Referrers.tsx+++ b/client/src/app/rollup/components/sections/Referrers.tsx@@ -10,6 +10,7 @@ import {TabsList,TabsTrigger,} from "@/components/ui/basic-tabs";+import { TabsUnderline } from "@/components/interior/tabs-indicator";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -51,10 +52,10 @@ export function Referrers({ siteIds }: { siteIds: number[] }) {<DropdownMenu><DropdownMenuTrigger asChild unstyled><div- className={`inline-flex items-center justify-center whitespace-nowrap border-b-2 py-1 text-sm font-medium transition-all cursor-pointer ${+ className={`relative inline-flex items-center justify-center whitespace-nowrap border-b-2 border-transparent py-1 text-sm font-medium transition-colors cursor-pointer ${tab.startsWith("utm_")- ? "border-neutral-950 text-neutral-950 dark:border-neutral-100 dark:text-neutral-50"- : "border-transparent text-neutral-600 dark:text-neutral-400"+ ? "text-neutral-950 dark:text-neutral-50"+ : "text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-200"}`}>{tab === "utm_source" && t("Source")}@@ -63,6 +64,8 @@ export function Referrers({ siteIds }: { siteIds: number[] }) {{tab === "utm_term" && t("Term")}{tab === "utm_content" && t("Content")}{!tab.startsWith("utm_") && t("UTM")}+ {/* The tab strip's sliding underline lands here while a UTM view is active. */}+ {tab.startsWith("utm_") && <TabsUnderline />}</div></DropdownMenuTrigger><DropdownMenuContent align="start">diff --git a/client/src/app/signup/components/PlanStep.tsx b/client/src/app/signup/components/PlanStep.tsxindex db8d8291d..3d01c17fd 100644--- a/client/src/app/signup/components/PlanStep.tsx+++ b/client/src/app/signup/components/PlanStep.tsx@@ -1,10 +1,11 @@+import { SegmentedControl } from "@/components/interior/segmented-control";import { PlanRow } from "@/components/subscription/components/PlanRow";+import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Slider } from "@/components/ui/slider";import { ArrowRight } from "lucide-react";import { useExtracted } from "next-intl";-import { cn } from "../../../lib/utils";import { EVENT_TIERS, formatEventTier } from "../../subscribe/components/utils";interface PlanStepProps {@@ -33,37 +34,27 @@ export function PlanStep({return (<div>- <div className="flex items-center justify-between mb-6">+ {/* Wraps: when the heading, toggle and chip don't fit on one line, the+ toggle group drops under the heading instead of crowding it. */}+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-3 mb-6"><h2 className="text-2xl font-semibold">{t("Choose your plan")}</h2>- {/* Monthly/Annual toggle */}- <div className="relative flex bg-neutral-150 dark:bg-neutral-850 border border-neutral-250 dark:border-neutral-750 rounded-full p-0.5 text-sm">- <button- onClick={() => setIsAnnual(false)}- className={cn(- "px-2.5 py-1 rounded-full transition-colors cursor-pointer",- !isAnnual- ? "bg-white dark:bg-white/20 text-neutral-700 dark:text-neutral-100 font-medium"- : "text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-neutral-200"- )}- >- {t("Monthly")}- </button>- <button- onClick={() => setIsAnnual(true)}- className={cn(- "px-2.5 py-1 rounded-full transition-colors cursor-pointer",- isAnnual- ? "bg-white dark:bg-white/20 text-neutral-700 dark:text-neutral-100 font-medium"- : "text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-neutral-200"- )}- >- {t("Annual")}- </button>- {isAnnual && (- <span className="absolute -top-3 -right-12 text-[10px] text-white bg-emerald-500 px-1.5 py-0.5 rounded-full whitespace-nowrap">- {t("4 months free")}- </span>- )}+ {/* Monthly/Annual toggle. The savings chip sits beside it so it never+ covers a segment, and it keeps its place in both states so the+ toggle never shifts under the pointer: emerald while Annual is+ picked, neutral otherwise. */}+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5">+ <SegmentedControl+ aria-label={t("Billing period")}+ options={[+ { value: "monthly", label: t("Monthly") },+ { value: "annual", label: t("Annual") },+ ]}+ value={isAnnual ? "annual" : "monthly"}+ onValueChange={value => setIsAnnual(value === "annual")}+ />+ <Badge variant={isAnnual ? "success" : "secondary"} className="whitespace-nowrap">+ {t("4 months free")}+ </Badge></div></div><div className="space-y-6">diff --git a/client/src/app/subscribe/components/PricingCards.tsx b/client/src/app/subscribe/components/PricingCards.tsxindex 79082fcdd..989e889d4 100644--- a/client/src/app/subscribe/components/PricingCards.tsx+++ b/client/src/app/subscribe/components/PricingCards.tsx@@ -1,6 +1,8 @@"use client";+import { SegmentedControl } from "@/components/interior/segmented-control";import { PricingCard } from "@/components/pricing/PricingCard";+import { Badge } from "@/components/ui/badge";import { Slider } from "@/components/ui/slider";import { toast } from "@/components/ui/sonner";import { authClient } from "@/lib/auth";@@ -182,7 +184,8 @@ export function PricingCards({ isLoggedIn }: { isLoggedIn: boolean }) {<div className="max-w-[1300px] mx-auto">{/* Shared controls section */}<div className="max-w-xl mx-auto mb-8">- <div className="flex justify-between mb-6 items-center">+ {/* Wraps: on narrow screens the billing toggle drops under the count. */}+ <div className="flex flex-wrap justify-between gap-x-4 gap-y-3 mb-6 items-center"><div><h3 className="font-semibold mb-2">{t("Monthly pageviews")}</h3><div className="text-3xl font-bold text-emerald-400">@@ -190,35 +193,22 @@ export function PricingCards({ isLoggedIn }: { isLoggedIn: boolean }) {</div></div><div className="flex flex-col items-end">- {/* Billing toggle */}- <div className="relative flex items-center">- <div className="flex bg-neutral-150 dark:bg-neutral-850 border border-neutral-250 dark:border-neutral-750 rounded-full p-1 text-sm">- <button- onClick={() => setIsAnnual(false)}- className={cn(- "px-3 py-1 rounded-full transition-colors cursor-pointer",- !isAnnual- ? "bg-white dark:bg-white/20 text-neutral-700 dark:text-neutral-100 font-medium"- : "text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-neutral-200"- )}- >- {t("Monthly")}- </button>- <button- onClick={() => setIsAnnual(true)}- className={cn(- "px-3 py-1 rounded-full transition-colors cursor-pointer",- isAnnual- ? "bg-white dark:bg-white/20 text-neutral-700 dark:text-neutral-100 font-medium"- : "text-neutral-600 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-neutral-200"- )}- >- {t("Annual")}- </button>- </div>- <span className="absolute -top-3 -right-12 text-xs text-white bg-emerald-500 border border-emerald-500 rounded-full px-2 py-0.5 whitespace-nowrap">+ {/* Billing toggle. The savings chip sits beside it so it never+ covers a segment: emerald while Annual is picked, neutral+ otherwise. */}+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5">+ <SegmentedControl+ aria-label={t("Billing period")}+ options={[+ { value: "monthly", label: t("Monthly") },+ { value: "annual", label: t("Annual") },+ ]}+ value={isAnnual ? "annual" : "monthly"}+ onValueChange={value => setIsAnnual(value === "annual")}+ />+ <Badge variant={isAnnual ? "success" : "secondary"} className="whitespace-nowrap">{t("4 months free")}- </span>+ </Badge></div></div></div>diff --git a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails/SessionDetails.tsxindex 4b01fc43e..dbf4a084c 100644--- a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx+++ b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx@@ -1,5 +1,5 @@import { Alert, AlertDescription } from "@/components/ui/alert";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/basic-tabs";import { ArrowRight } from "lucide-react";import { useExtracted } from "next-intl";import Link from "next/link";diff --git a/client/src/components/interior/segmented-control.test.tsx b/client/src/components/interior/segmented-control.test.tsxnew file mode 100644index 000000000..2e8f33f08--- /dev/null+++ b/client/src/components/interior/segmented-control.test.tsx@@ -0,0 +1,297 @@+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { useState } from "react";+import { hydrateRoot } from "react-dom/client";+import { renderToString } from "react-dom/server";+import { afterEach, describe, expect, it, vi } from "vitest";++import { SegmentedControl, interpolateSegment, seekEnabled, type SegmentedControlOption } from "./segmented-control";++type Period = "day" | "week" | "month";++const OPTIONS: SegmentedControlOption<Period>[] = [+ { value: "day", label: "Daily" },+ { value: "week", label: "Weekly" },+ { value: "month", label: "Monthly" },+];++const radio = (name: string) => screen.getByRole("radio", { name });+const checkedNames = () =>+ screen+ .getAllByRole("radio")+ .filter(element => element.getAttribute("aria-checked") === "true")+ .map(element => element.textContent);++afterEach(() => {+ cleanup();+});++describe("SegmentedControl", () => {+ it("renders a labelled radio group with one checked radio and a single tab stop", () => {+ render(<SegmentedControl aria-label="Period" options={OPTIONS} defaultValue="week" />);++ expect(screen.getByRole("radiogroup", { name: "Period" })).toBeTruthy();+ expect(screen.getAllByRole("radio")).toHaveLength(3);+ expect(checkedNames()).toEqual(["Weekly"]);+ expect(radio("Weekly").tabIndex).toBe(0);+ expect(radio("Daily").tabIndex).toBe(-1);+ expect(radio("Monthly").tabIndex).toBe(-1);+ });++ it("defaults to the first enabled option when uncontrolled", () => {+ render(+ <SegmentedControl+ aria-label="Period"+ options={[{ value: "day", label: "Daily", disabled: true }, ...OPTIONS.slice(1)]}+ />+ );++ expect(checkedNames()).toEqual(["Weekly"]);+ });++ it("selects on click and reports the change", () => {+ const onValueChange = vi.fn();+ render(<SegmentedControl aria-label="Period" options={OPTIONS} defaultValue="day" onValueChange={onValueChange} />);++ fireEvent.click(radio("Monthly"));++ expect(onValueChange).toHaveBeenCalledExactlyOnceWith("month");+ expect(checkedNames()).toEqual(["Monthly"]);+ expect(radio("Monthly").tabIndex).toBe(0);+ expect(radio("Daily").tabIndex).toBe(-1);+ });++ it("ignores a click on the segment that is already checked", () => {+ const onValueChange = vi.fn();+ render(<SegmentedControl aria-label="Period" options={OPTIONS} defaultValue="day" onValueChange={onValueChange} />);++ fireEvent.click(radio("Daily"));++ expect(onValueChange).not.toHaveBeenCalled();+ });++ it("moves focus and selection with the arrow keys, wrapping at both ends", () => {+ const onValueChange = vi.fn();+ render(<SegmentedControl aria-label="Period" options={OPTIONS} defaultValue="day" onValueChange={onValueChange} />);++ fireEvent.keyDown(radio("Daily"), { key: "ArrowRight" });+ expect(checkedNames()).toEqual(["Weekly"]);+ expect(document.activeElement).toBe(radio("Weekly"));++ fireEvent.keyDown(radio("Weekly"), { key: "ArrowDown" });+ expect(checkedNames()).toEqual(["Monthly"]);++ fireEvent.keyDown(radio("Monthly"), { key: "ArrowRight" });+ expect(checkedNames()).toEqual(["Daily"]);+ expect(document.activeElement).toBe(radio("Daily"));++ fireEvent.keyDown(radio("Daily"), { key: "ArrowLeft" });+ expect(checkedNames()).toEqual(["Monthly"]);++ fireEvent.keyDown(radio("Monthly"), { key: "ArrowUp" });+ expect(checkedNames()).toEqual(["Weekly"]);++ expect(onValueChange.mock.calls.map(([value]) => value)).toEqual(["week", "month", "day", "month", "week"]);+ });++ it("jumps to the first and last enabled segment with Home and End", () => {+ const options: SegmentedControlOption<string>[] = [+ { value: "a", label: "A", disabled: true },+ { value: "b", label: "B" },+ { value: "c", label: "C" },+ { value: "d", label: "D", disabled: true },+ ];+ render(<SegmentedControl aria-label="Letters" options={options} defaultValue="c" />);++ fireEvent.keyDown(radio("C"), { key: "Home" });+ expect(checkedNames()).toEqual(["B"]);+ expect(document.activeElement).toBe(radio("B"));++ fireEvent.keyDown(radio("B"), { key: "End" });+ expect(checkedNames()).toEqual(["C"]);+ expect(document.activeElement).toBe(radio("C"));+ });++ it("leaves other keys and modified arrows to the browser", () => {+ render(<SegmentedControl aria-label="Period" options={OPTIONS} defaultValue="day" />);++ const tab = fireEvent.keyDown(radio("Daily"), { key: "Tab" });+ const altArrow = fireEvent.keyDown(radio("Daily"), { key: "ArrowRight", altKey: true });++ // fireEvent returns false when the handler called preventDefault.+ expect(tab).toBe(true);+ expect(altArrow).toBe(true);+ expect(checkedNames()).toEqual(["Daily"]);+ });++ it("skips disabled segments with the keyboard and ignores clicks on them", () => {+ const onValueChange = vi.fn();+ const options = OPTIONS.map(option => (option.value === "week" ? { ...option, disabled: true } : option));+ render(<SegmentedControl aria-label="Period" options={options} defaultValue="day" onValueChange={onValueChange} />);++ expect(radio("Weekly").getAttribute("aria-disabled")).toBe("true");++ fireEvent.click(radio("Weekly"));+ expect(checkedNames()).toEqual(["Daily"]);++ fireEvent.keyDown(radio("Daily"), { key: "ArrowRight" });+ expect(checkedNames()).toEqual(["Monthly"]);+ expect(onValueChange).toHaveBeenCalledExactlyOnceWith("month");+ });++ it("keeps a disabled control focusable but inert to clicks and keys", () => {+ const onValueChange = vi.fn();+ render(+ <SegmentedControl+ aria-label="Period"+ options={OPTIONS}+ defaultValue="day"+ onValueChange={onValueChange}+ disabled+ />+ );++ expect(screen.getByRole("radiogroup").getAttribute("aria-disabled")).toBe("true");+ expect(radio("Daily").tabIndex).toBe(0);++ fireEvent.click(radio("Weekly"));+ fireEvent.keyDown(radio("Daily"), { key: "ArrowRight" });++ expect(checkedNames()).toEqual(["Daily"]);+ expect(onValueChange).not.toHaveBeenCalled();+ });++ it("follows a controlled value and stays put when the parent refuses a change", () => {+ const onValueChange = vi.fn();+ function Controlled() {+ const [value, setValue] = useState<Period>("day");+ return (+ <SegmentedControl+ aria-label="Period"+ options={OPTIONS}+ value={value}+ onValueChange={next => {+ onValueChange(next);+ if (next !== "month") setValue(next);+ }}+ />+ );+ }+ render(<Controlled />);++ fireEvent.click(radio("Monthly"));+ expect(onValueChange).toHaveBeenLastCalledWith("month");+ expect(checkedNames()).toEqual(["Daily"]);++ fireEvent.click(radio("Weekly"));+ expect(checkedNames()).toEqual(["Weekly"]);+ });++ it("follows a change made by the parent", () => {+ const { rerender } = render(<SegmentedControl aria-label="Period" options={OPTIONS} value="day" />);++ rerender(<SegmentedControl aria-label="Period" options={OPTIONS} value="week" />);++ expect(checkedNames()).toEqual(["Weekly"]);+ });++ it("checks nothing when the value matches no option, and keeps a tab stop", () => {+ render(<SegmentedControl aria-label="Period" options={OPTIONS} value={"year" as Period} />);++ expect(checkedNames()).toEqual([]);+ expect(radio("Daily").tabIndex).toBe(0);+ });++ it("names a segment by its ariaLabel when the label is not plain text", () => {+ render(+ <SegmentedControl+ aria-label="Map view"+ options={[+ { value: "countries", label: <svg aria-hidden />, ariaLabel: "Countries" },+ { value: "cities", label: <svg aria-hidden />, ariaLabel: "Cities" },+ ]}+ defaultValue="cities"+ />+ );++ expect(radio("Cities").getAttribute("aria-checked")).toBe("true");+ expect(radio("Countries").getAttribute("aria-checked")).toBe("false");+ });++ it("hydrates its server render without a mismatch", async () => {+ const element = <SegmentedControl aria-label="Period" options={OPTIONS} defaultValue="week" />;+ const container = document.createElement("div");+ container.innerHTML = renderToString(element);+ document.body.appendChild(container);++ // Before hydration the checked segment carries its own thumb and the+ // sliding one is clipped away.+ const checked = container.querySelector('[role="radio"][aria-checked="true"]');+ expect(checked?.textContent).toBe("Weekly");+ expect(checked?.className).toContain("bg-white");+ expect(container.querySelector<HTMLElement>("[aria-hidden]")?.style.clipPath).toBe("inset(0px 100% 0px 0px)");++ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ const onRecoverableError = vi.fn();+ let root: ReturnType<typeof hydrateRoot> | undefined;+ await act(async () => {+ root = hydrateRoot(container, element, { onRecoverableError });+ });++ expect(onRecoverableError).not.toHaveBeenCalled();+ expect(consoleError).not.toHaveBeenCalled();+ consoleError.mockRestore();+ act(() => root?.unmount());+ container.remove();+ });++ it("paints the thumb on the checked segment until the row can be measured", () => {+ // jsdom has no layout, so the control stays in its server-render state.+ render(<SegmentedControl aria-label="Period" options={OPTIONS} defaultValue="week" />);++ expect(radio("Weekly").className).toContain("bg-white");+ expect(radio("Daily").className).not.toContain("bg-white");+ });+});++describe("interpolateSegment", () => {+ const rects = [+ { left: 0, width: 40 },+ { left: 40, width: 80 },+ { left: 120, width: 60 },+ ];++ it("returns a segment's own box at whole positions", () => {+ expect(interpolateSegment(rects, 0)).toEqual({ left: 0, width: 40 });+ expect(interpolateSegment(rects, 2)).toEqual({ left: 120, width: 60 });+ });++ it("blends offset and width between neighbours", () => {+ expect(interpolateSegment(rects, 0.5)).toEqual({ left: 20, width: 60 });+ expect(interpolateSegment(rects, 1.25)).toEqual({ left: 60, width: 75 });+ });++ it("clamps positions outside the row and handles an empty row", () => {+ expect(interpolateSegment(rects, -0.3)).toEqual({ left: 0, width: 40 });+ expect(interpolateSegment(rects, 2.4)).toEqual({ left: 120, width: 60 });+ expect(interpolateSegment([], 1)).toEqual({ left: 0, width: 0 });+ });+});++describe("seekEnabled", () => {+ const options = [{}, { disabled: true }, {}, {}];++ it("steps in either direction and wraps", () => {+ expect(seekEnabled(options, 2, 1)).toBe(3);+ expect(seekEnabled(options, 3, 1)).toBe(0);+ expect(seekEnabled(options, 0, -1)).toBe(3);+ });++ it("skips disabled options", () => {+ expect(seekEnabled(options, 0, 1)).toBe(2);+ expect(seekEnabled(options, 2, -1)).toBe(0);+ });++ it("returns -1 when every option is disabled", () => {+ expect(seekEnabled([{ disabled: true }, { disabled: true }], 0, 1)).toBe(-1);+ });+});diff --git a/client/src/components/interior/segmented-control.tsx b/client/src/components/interior/segmented-control.tsxnew file mode 100644index 000000000..3251f0f36--- /dev/null+++ b/client/src/components/interior/segmented-control.tsx@@ -0,0 +1,318 @@+// Adapted from interior.dev "SegmentedControl" (MIT). See ./THIRD_PARTY_LICENSES.md+"use client";++import { animate, useIsomorphicLayoutEffect, useMotionValue, useReducedMotionConfig } from "framer-motion";+import { type KeyboardEvent, type ReactNode, useRef, useState } from "react";++import { SPRING_CELL } from "@/lib/motion";+import { cn } from "@/lib/utils";++// A radio group drawn as a segmented control. One motion value (a fractional+// segment index) drives the thumb: it clips a second, active-coloured copy of+// the labels that sits over the muted ones, so the thumb fill and the label+// colour move as one and the colour wipes across a label as the thumb passes.+// Upstream used equal-width segments; these are measured, so labels of any+// length keep their natural width.+//+// The clip is written to the DOM from the motion value's change events rather+// than through a motion component's style: this install pairs framer-motion+// 12.11 with motion-dom 12.23, which no longer emits the "renderRequest" event+// that 12.11's motion components wait for, so a style motion value would only+// paint on the next React render. Writing it here also keeps the slide off+// React entirely.++export type SegmentedControlOption<T extends string = string> = {+ value: T;+ label: ReactNode;+ // Accessible name for labels that are not plain text: icon-only segments,+ // or text hidden at some breakpoints.+ ariaLabel?: string;+ disabled?: boolean;+};++export type SegmentedControlProps<T extends string = string> = {+ options: readonly SegmentedControlOption<T>[];+ value?: T;+ defaultValue?: T;+ onValueChange?: (value: T) => void;+ "aria-label"?: string;+ "aria-labelledby"?: string;+ // sm matches the 28px compact controls, md the 36px default (ui/tabs).+ size?: "sm" | "md";+ // "overlay" floats over a map or image (the globe).+ variant?: "default" | "overlay";+ disabled?: boolean;+ className?: string;+};++type SegmentRect = { left: number; width: number };+type SegmentLayout = { width: number; rects: SegmentRect[] };++const SIZES = {+ sm: { track: "p-0.5", segment: "h-6 gap-1.5 px-2 text-xs" },+ md: { track: "p-1", segment: "h-7 gap-2 px-3 text-sm" },+} as const;++// Same palette as ui/tabs so every segmented surface reads the same. Neutral+// thumb: the selection is carried by tone, not by the emerald accent.+const VARIANTS = {+ default: {+ track: "bg-neutral-100 dark:bg-neutral-800",+ thumb: "bg-white dark:bg-neutral-950",+ label: "text-neutral-600 dark:text-neutral-400",+ hover: "hover:text-neutral-900 dark:hover:text-neutral-200",+ active: "text-neutral-950 dark:text-neutral-50",+ disabled: "text-neutral-400 dark:text-neutral-600",+ ring: "focus-visible:after:ring-neutral-950 dark:focus-visible:after:ring-neutral-300",+ },+ overlay: {+ track: "border border-neutral-800/50 bg-neutral-900/70 backdrop-blur-sm",+ thumb: "bg-neutral-800",+ label: "text-neutral-300",+ hover: "hover:text-white",+ active: "text-white",+ disabled: "text-neutral-600",+ ring: "focus-visible:after:ring-neutral-300",+ },+} as const;++const SEGMENT = "inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-md font-medium";+// rounded-md, the thumb's corner.+const THUMB_RADIUS = "calc(var(--radius) - 2px)";+const HIDDEN_CLIP = "inset(0px 100% 0px 0px)";+// Hundredths of a pixel: plenty, and no float noise like 2.8e-14px.+const toPx = (value: number) => `${Math.round(value * 100) / 100}px`;++// Thumb box at a fractional segment index: between two segments it blends+// their offsets and widths, so it also resizes as it travels.+export function interpolateSegment(rects: readonly SegmentRect[], position: number): SegmentRect {+ const last = rects.length - 1;+ if (last < 0) return { left: 0, width: 0 };+ const clamped = Math.min(Math.max(position, 0), last);+ const from = Math.floor(clamped);+ const to = Math.min(from + 1, last);+ const progress = clamped - from;+ return {+ left: rects[from].left + (rects[to].left - rects[from].left) * progress,+ width: rects[from].width + (rects[to].width - rects[from].width) * progress,+ };+}++// Next enabled index from `from` in `step` direction, wrapping; -1 if none.+export function seekEnabled(options: readonly { disabled?: boolean }[], from: number, step: 1 | -1): number {+ const count = options.length;+ for (let k = 1; k <= count; k++) {+ const i = (((from + step * k) % count) + count) % count;+ if (!options[i]?.disabled) return i;+ }+ return -1;+}++function sameLayout(a: SegmentLayout, b: SegmentLayout) {+ return (+ a.width === b.width &&+ a.rects.length === b.rects.length &&+ a.rects.every((rect, i) => rect.left === b.rects[i].left && rect.width === b.rects[i].width)+ );+}++export function SegmentedControl<T extends string>({+ options,+ value,+ defaultValue,+ onValueChange,+ "aria-label": ariaLabel,+ "aria-labelledby": ariaLabelledby,+ size = "md",+ variant = "default",+ disabled = false,+ className,+}: SegmentedControlProps<T>) {+ const [internal, setInternal] = useState<T | undefined>(+ () => defaultValue ?? options.find(option => !option.disabled)?.value+ );+ const isControlled = value !== undefined;+ const current = isControlled ? value : internal;+ const index = options.findIndex(option => option.value === current);+ // Roving tabindex: the checked radio, else the first enabled one.+ const firstEnabled = options.findIndex(option => !option.disabled);+ const tabStop = index >= 0 ? index : Math.max(0, firstEnabled);++ const rowRef = useRef<HTMLDivElement>(null);+ const buttonsRef = useRef<(HTMLButtonElement | null)[]>([]);+ const [layout, setLayout] = useState<SegmentLayout | null>(null);+ // Unmeasured (server render, hidden parent): the checked segment paints its+ // own thumb until the sliding one can be placed.+ const ready = layout !== null && layout.width > 0 && layout.rects.length === options.length;++ const optionsKey = options.map(option => option.value).join("\u0000");+ useIsomorphicLayoutEffect(() => {+ const row = rowRef.current;+ if (!row) return;+ const count = options.length;+ const measure = () => {+ // Fractional boxes (offset* round to whole pixels), with any transform+ // scale divided out so a control in a zooming popover measures true.+ const rowBox = row.getBoundingClientRect();+ const width = parseFloat(getComputedStyle(row).width) || row.offsetWidth;+ const scale = width > 0 && rowBox.width > 0 ? rowBox.width / width : 1;+ const rects = buttonsRef.current.slice(0, count).map(button => {+ if (!button) return { left: 0, width: 0 };+ const box = button.getBoundingClientRect();+ return { left: (box.left - rowBox.left) / scale, width: box.width / scale };+ });+ const next = { width, rects };+ setLayout(previous => (previous && sameLayout(previous, next) ? previous : next));+ };+ measure();+ if (typeof ResizeObserver === "undefined") return;+ // Each segment too: a label can change width while the row does not.+ const observer = new ResizeObserver(measure);+ observer.observe(row);+ buttonsRef.current.slice(0, count).forEach(button => button && observer.observe(button));+ return () => observer.disconnect();+ }, [optionsKey]);++ const reduceMotion = useReducedMotionConfig();+ const position = useMotionValue(Math.max(index, 0));++ // The overlay's clip at a fractional segment position, for this render's+ // measurements. React only ever renders HIDDEN_CLIP (server render, first+ // paint); from then on the clip is written here and React leaves it alone.+ const overlayRef = useRef<HTMLDivElement>(null);+ const paint = useRef<(latest: number) => void>(() => {});+ useIsomorphicLayoutEffect(() => {+ paint.current = latest => {+ const overlay = overlayRef.current;+ if (!overlay) return;+ if (!ready || !layout || index < 0) {+ overlay.style.clipPath = HIDDEN_CLIP;+ return;+ }+ const { left, width } = interpolateSegment(layout.rects, latest);+ const right = Math.max(0, layout.width - left - width);+ overlay.style.clipPath = `inset(0px ${toPx(right)} 0px ${toPx(left)} round ${THUMB_RADIUS})`;+ };+ paint.current(position.get());+ });+ // Subscribing also keeps the spring running: motion values stop animating+ // once they have no change listeners.+ useIsomorphicLayoutEffect(() => position.on("change", latest => paint.current(latest)), [position]);++ const placedIndex = useRef(index);+ useIsomorphicLayoutEffect(() => {+ const from = placedIndex.current;+ placedIndex.current = index;+ if (index < 0) return;+ // First placement, a selection appearing from none, and reduced motion+ // jump; only a change from one segment to another slides.+ if (!ready || reduceMotion || from < 0 || position.get() === index) {+ position.jump(index);+ return;+ }+ const controls = animate(position, index, SPRING_CELL);+ return () => controls.stop();+ }, [index, ready, reduceMotion, position]);++ const select = (i: number) => {+ const option = options[i];+ if (!option || option.disabled || disabled || option.value === current) return;+ if (!isControlled) setInternal(option.value);+ onValueChange?.(option.value);+ };++ const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>, i: number) => {+ if (event.altKey || event.ctrlKey || event.metaKey) return;+ let next: number;+ switch (event.key) {+ case "ArrowRight":+ case "ArrowDown":+ next = seekEnabled(options, i, 1);+ break;+ case "ArrowLeft":+ case "ArrowUp":+ next = seekEnabled(options, i, -1);+ break;+ case "Home":+ next = seekEnabled(options, options.length - 1, 1);+ break;+ case "End":+ next = seekEnabled(options, 0, -1);+ break;+ default:+ return;+ }+ event.preventDefault();+ if (disabled || next < 0) return;+ // Radio semantics: selection follows focus.+ buttonsRef.current[next]?.focus();+ select(next);+ };++ const sizing = SIZES[size];+ const tone = VARIANTS[variant];++ return (+ <div+ role="radiogroup"+ aria-label={ariaLabel}+ aria-labelledby={ariaLabelledby}+ aria-disabled={disabled || undefined}+ className={cn(+ // isolate keeps the focus ring's z-index local to the control.+ "isolate inline-flex touch-manipulation select-none rounded-lg",+ sizing.track,+ tone.track,+ disabled && "opacity-50",+ className+ )}+ >+ <div ref={rowRef} className="relative flex">+ {options.map((option, i) => {+ const checked = i === index;+ const blocked = disabled || option.disabled;+ return (+ <button+ key={option.value}+ ref={node => {+ buttonsRef.current[i] = node;+ }}+ type="button"+ role="radio"+ aria-checked={checked}+ aria-label={option.ariaLabel}+ aria-disabled={blocked || undefined}+ tabIndex={i === tabStop ? 0 : -1}+ onClick={() => select(i)}+ onKeyDown={event => onKeyDown(event, i)}+ className={cn(+ SEGMENT,+ sizing.segment,+ // The focus ring is drawn by ::after above the thumb layer.+ "relative transition-colors after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-md after:content-[''] focus-visible:outline-none focus-visible:after:ring-1",+ tone.ring,+ option.disabled ? tone.disabled : tone.label,+ blocked ? "cursor-not-allowed" : checked ? "cursor-default" : cn("cursor-pointer", tone.hover),+ checked && !ready && cn(tone.thumb, tone.active)+ )}+ >+ {option.label}+ </button>+ );+ })}+ <div+ ref={overlayRef}+ aria-hidden+ className={cn("pointer-events-none absolute inset-0 flex", tone.thumb)}+ style={{ clipPath: HIDDEN_CLIP }}+ >+ {options.map(option => (+ <span key={option.value} className={cn(SEGMENT, sizing.segment, tone.active)}>+ {option.label}+ </span>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/interior/tabs-indicator.test.tsx b/client/src/components/interior/tabs-indicator.test.tsxnew file mode 100644index 000000000..3a6033919--- /dev/null+++ b/client/src/components/interior/tabs-indicator.test.tsx@@ -0,0 +1,188 @@+import * as TabsPrimitive from "@radix-ui/react-tabs";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { useState } from "react";+import { hydrateRoot } from "react-dom/client";+import { renderToString } from "react-dom/server";+import { afterEach, describe, expect, it, vi } from "vitest";++import * as Basic from "@/components/ui/basic-tabs";+import * as Pill from "@/components/ui/tabs";++// The indicator lives in components/interior/tabs-indicator and is exercised+// through the two public tab families that use it.++const tab = (name: string) => screen.getByRole("tab", { name });+const indicators = () => Array.from(document.querySelectorAll<HTMLElement>("[data-tabs-indicator]"));+// Radix selects on mousedown (primary button, no ctrl), not on click.+const press = (name: string) => fireEvent.mouseDown(tab(name));++afterEach(() => {+ cleanup();+});++function BasicTabs(props: React.ComponentProps<typeof Basic.Tabs>) {+ return (+ <Basic.Tabs {...props}>+ <Basic.TabsList>+ <Basic.TabsTrigger value="pages">Pages</Basic.TabsTrigger>+ <Basic.TabsTrigger value="countries">Countries</Basic.TabsTrigger>+ <Basic.TabsTrigger value="devices">Devices</Basic.TabsTrigger>+ </Basic.TabsList>+ <Basic.TabsContent value="pages">Pages panel</Basic.TabsContent>+ <Basic.TabsContent value="countries">Countries panel</Basic.TabsContent>+ <Basic.TabsContent value="devices">Devices panel</Basic.TabsContent>+ </Basic.Tabs>+ );+}++describe("tabs indicator", () => {+ it("draws one underline in the active trigger and moves it with an uncontrolled selection", () => {+ const onValueChange = vi.fn();+ render(<BasicTabs defaultValue="pages" onValueChange={onValueChange} />);++ expect(indicators()).toHaveLength(1);+ expect(tab("Pages").contains(indicators()[0])).toBe(true);+ expect(indicators()[0].dataset.tabsIndicator).toBe("underline");++ press("Devices");++ expect(onValueChange).toHaveBeenCalledExactlyOnceWith("devices");+ expect(indicators()).toHaveLength(1);+ expect(tab("Devices").contains(indicators()[0])).toBe(true);+ expect(tab("Devices").getAttribute("aria-selected")).toBe("true");+ expect(tab("Pages").getAttribute("aria-selected")).toBe("false");+ expect(screen.getByRole("tabpanel").textContent).toBe("Devices panel");+ });++ it("follows a controlled value and stays put when the parent keeps it", () => {+ function Controlled() {+ const [value, setValue] = useState("pages");+ return <BasicTabs value={value} onValueChange={setValue} />;+ }+ const { unmount } = render(<Controlled />);++ press("Countries");+ expect(tab("Countries").contains(indicators()[0])).toBe(true);+ expect(screen.getByRole("tabpanel").textContent).toBe("Countries panel");+ unmount();++ // Weekdays.tsx pins value without onValueChange: the selection never moves.+ render(<BasicTabs defaultValue="pages" value="pages" />);+ press("Countries");+ expect(tab("Pages").contains(indicators()[0])).toBe(true);+ expect(tab("Pages").getAttribute("aria-selected")).toBe("true");+ });++ it("keeps Radix keyboard navigation (automatic activation)", async () => {+ render(<BasicTabs defaultValue="pages" />);++ tab("Pages").focus();+ fireEvent.keyDown(tab("Pages"), { key: "ArrowRight" });++ await waitFor(() => expect(tab("Countries").getAttribute("aria-selected")).toBe("true"));+ expect(document.activeElement).toBe(tab("Countries"));+ expect(tab("Countries").contains(indicators()[0])).toBe(true);+ });++ it("selects nothing and draws nothing without a value", () => {+ render(<BasicTabs />);++ expect(indicators()).toHaveLength(0);+ expect(screen.getAllByRole("tab").every(element => element.getAttribute("aria-selected") === "false")).toBe(true);+ });++ it("gives every Tabs instance its own indicator", () => {+ render(+ <>+ <BasicTabs defaultValue="pages" />+ <BasicTabs defaultValue="devices" />+ </>+ );++ const [first, second] = indicators();+ expect(indicators()).toHaveLength(2);+ expect(screen.getAllByRole("tab", { name: "Pages" })[0].contains(first)).toBe(true);+ expect(screen.getAllByRole("tab", { name: "Devices" })[1].contains(second)).toBe(true);+ });++ it("draws a flat pill thumb for ui/tabs", () => {+ render(+ <Pill.Tabs defaultValue="timeline">+ <Pill.TabsList>+ <Pill.TabsTrigger value="timeline">Timeline</Pill.TabsTrigger>+ <Pill.TabsTrigger value="info">Session Info</Pill.TabsTrigger>+ </Pill.TabsList>+ </Pill.Tabs>+ );++ expect(indicators()).toHaveLength(1);+ expect(indicators()[0].dataset.tabsIndicator).toBe("thumb");+ expect(tab("Timeline").contains(indicators()[0])).toBe(true);+ expect(tab("Timeline").className).not.toMatch(/shadow/);++ press("Session Info");+ expect(tab("Session Info").contains(indicators()[0])).toBe(true);+ });++ it("slides the underline under the ui/tabs root too (UserTopPages mixes the two)", () => {+ render(+ <Pill.Tabs defaultValue="pages">+ <Basic.TabsList>+ <Basic.TabsTrigger value="pages">Top Pages</Basic.TabsTrigger>+ <Basic.TabsTrigger value="events">Events</Basic.TabsTrigger>+ </Basic.TabsList>+ </Pill.Tabs>+ );++ expect(indicators()[0].dataset.tabsIndicator).toBe("underline");+ press("Events");+ expect(tab("Events").contains(indicators()[0])).toBe(true);+ });++ it("hydrates its server render without a mismatch", async () => {+ const element = (+ <>+ <BasicTabs defaultValue="countries" />+ <Pill.Tabs defaultValue="info">+ <Pill.TabsList>+ <Pill.TabsTrigger value="timeline">Timeline</Pill.TabsTrigger>+ <Pill.TabsTrigger value="info">Session Info</Pill.TabsTrigger>+ </Pill.TabsList>+ </Pill.Tabs>+ </>+ );+ const container = document.createElement("div");+ container.innerHTML = renderToString(element);+ document.body.appendChild(container);++ // The server already draws each indicator in its active trigger.+ expect(container.querySelectorAll("[data-tabs-indicator]")).toHaveLength(2);++ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ const onRecoverableError = vi.fn();+ let root: ReturnType<typeof hydrateRoot> | undefined;+ await act(async () => {+ root = hydrateRoot(container, element, { onRecoverableError });+ });++ expect(onRecoverableError).not.toHaveBeenCalled();+ expect(consoleError).not.toHaveBeenCalled();+ consoleError.mockRestore();+ act(() => root?.unmount());+ container.remove();+ });++ it("falls back to the static active style under a plain Radix root", () => {+ render(+ <TabsPrimitive.Root defaultValue="pages">+ <Basic.TabsList>+ <Basic.TabsTrigger value="pages">Pages</Basic.TabsTrigger>+ <Basic.TabsTrigger value="countries">Countries</Basic.TabsTrigger>+ </Basic.TabsList>+ </TabsPrimitive.Root>+ );++ expect(indicators()).toHaveLength(0);+ expect(tab("Pages").className).toContain("data-[state=active]:border-neutral-950");+ });+});diff --git a/client/src/components/interior/tabs-indicator.tsx b/client/src/components/interior/tabs-indicator.tsxnew file mode 100644index 000000000..c19d0ead5--- /dev/null+++ b/client/src/components/interior/tabs-indicator.tsx@@ -0,0 +1,109 @@+// Adapted from interior.dev "Tabs" (MIT). See ./THIRD_PARTY_LICENSES.md+"use client";++import * as TabsPrimitive from "@radix-ui/react-tabs";+import { LayoutGroup, motion } from "framer-motion";+import * as React from "react";++import { SPRING_CELL } from "@/lib/motion";++// One sliding indicator per Tabs instance, shared by ui/tabs (pill thumb) and+// ui/basic-tabs (underline). Radix keeps the tab semantics, roving focus and+// keyboard handling. The root mirrors the active value into context so each+// trigger knows whether it is active; the active trigger renders the indicator+// and framer's shared layout (layoutId) slides it over from the trigger that+// had it. Upstream measured the active tab by hand; layoutId does that for us.++type TabsIndicatorContextValue = {+ // useId(): unique per Tabs instance, so two instances (the card and its+ // expanded dialog, say) never trade indicators.+ id: string;+ value: string;+};++const TabsIndicatorContext = React.createContext<TabsIndicatorContextValue | null>(null);++// Drop-in for TabsPrimitive.Root. Radix is always driven as controlled so the+// indicator and Radix's data-state change in the same render (in uncontrolled+// mode Radix reports changes from an effect, one render late). "" is Radix's+// own value for "nothing selected" (its default is `defaultValue ?? ""`).+export const TabsIndicatorRoot = React.forwardRef<+ React.ElementRef<typeof TabsPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.Root>+>(({ value, defaultValue, onValueChange, children, ...props }, ref) => {+ const id = React.useId();+ const [uncontrolledValue, setUncontrolledValue] = React.useState(defaultValue ?? "");+ const isControlled = value !== undefined;+ const activeValue = isControlled ? value : uncontrolledValue;++ const handleValueChange = React.useCallback(+ (next: string) => {+ if (!isControlled) setUncontrolledValue(next);+ onValueChange?.(next);+ },+ [isControlled, onValueChange]+ );++ const context = React.useMemo(() => ({ id, value: activeValue }), [id, activeValue]);++ return (+ <TabsPrimitive.Root ref={ref} value={activeValue} onValueChange={handleValueChange} {...props}>+ <TabsIndicatorContext.Provider value={context}>{children}</TabsIndicatorContext.Provider>+ </TabsPrimitive.Root>+ );+});+TabsIndicatorRoot.displayName = TabsPrimitive.Root.displayName;++// Wraps a TabsList's children. The LayoutGroup namespaces the layoutId by+// instance and keeps these nodes out of any ancestor group's layout updates.+export function TabsIndicatorGroup({ children }: { children?: React.ReactNode }) {+ const context = React.useContext(TabsIndicatorContext);+ if (!context) return <>{children}</>;+ return (+ <LayoutGroup id={context.id} inherit="id">+ {children}+ </LayoutGroup>+ );+}++// null when the trigger sits under a plain Radix root with no indicator+// context; the trigger then falls back to a static data-state style.+export function useTabsIndicator(value: string): { isActive: boolean } | null {+ const context = React.useContext(TabsIndicatorContext);+ if (!context) return null;+ return { isActive: context.value === value };+}++// Render inside the active trigger only. `kind` keeps the pill thumb and the+// underline from ever morphing into each other.+export function TabsIndicator({ kind, className }: { kind: "thumb" | "underline"; className?: string }) {+ const context = React.useContext(TabsIndicatorContext);+ if (!context) return null;+ return (+ <motion.span+ aria-hidden+ data-tabs-indicator={kind}+ layoutId={`${context.id}-${kind}`}+ // Measure only when the selection changes: a label whose width changes+ // with fresh data (a count, say) should not set the indicator moving.+ layoutDependency={context.value}+ transition={SPRING_CELL}+ className={className}+ />+ );+}++// For a custom trigger that lives inside a basic-tabs list but isn't a+// TabsTrigger (e.g. a dropdown that picks one of several tab values). Render it+// inside that trigger (position: relative) while its value is active: the+// shared underline slides over to it, or, under a plain Radix root, a static+// underline is drawn in the same spot.+export function TabsUnderline() {+ const context = React.useContext(TabsIndicatorContext);+ const className = "pointer-events-none absolute inset-x-0 -bottom-0.5 h-0.5 bg-neutral-950 dark:bg-neutral-100";+ return context ? (+ <TabsIndicator kind="underline" className={className} />+ ) : (+ <span aria-hidden className={className} />+ );+}diff --git a/client/src/components/replay/ReplayBreadcrumbs.tsx b/client/src/components/replay/ReplayBreadcrumbs.tsxindex 876ea260c..adb2fa21d 100644--- a/client/src/components/replay/ReplayBreadcrumbs.tsx+++ b/client/src/components/replay/ReplayBreadcrumbs.tsx@@ -36,6 +36,7 @@ import { useShallow } from "zustand/react/shallow";import { useGetSessionReplayEvents } from "@/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents";import { Avatar } from "@/components/Avatar";import { IdentifiedBadge } from "@/components/IdentifiedBadge";+import { SegmentedControl } from "@/components/interior/segmented-control";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";import { ThreeDotLoader } from "@/components/Loaders";@@ -269,38 +270,17 @@ export function ReplayBreadcrumbs() {? t("{count} groups", { count: String(technical.length) }): t("{count} key events", { count: String(meaningful.length) })}</div>- <div- className="flex items-center rounded-md border border-neutral-150 dark:border-neutral-800 p-0.5 text-xs shrink-0"- role="tablist"+ <SegmentedControlaria-label={t("Event detail level")}- >- <button- role="tab"- aria-selected={!showTechnical}- onClick={() => setShowTechnical(false)}- className={cn(- "rounded px-2 py-0.5 transition-colors",- !showTechnical- ? "bg-neutral-100 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100"- : "text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200"- )}- >- {t("Key")}- </button>- <button- role="tab"- aria-selected={showTechnical}- onClick={() => setShowTechnical(true)}- className={cn(- "rounded px-2 py-0.5 transition-colors",- showTechnical- ? "bg-neutral-100 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100"- : "text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200"- )}- >- {t("All")}- </button>- </div>+ size="sm"+ className="shrink-0"+ options={[+ { value: "key", label: t("Key") },+ { value: "all", label: t("All") },+ ]}+ value={showTechnical ? "all" : "key"}+ onValueChange={value => setShowTechnical(value === "all")}+ /></div>{isLoading || !data ? (diff --git a/client/src/components/ui/basic-tabs.tsx b/client/src/components/ui/basic-tabs.tsxindex 4b81e2d34..4311be385 100644--- a/client/src/components/ui/basic-tabs.tsx+++ b/client/src/components/ui/basic-tabs.tsx@@ -3,35 +3,64 @@import * as React from "react";import * as TabsPrimitive from "@radix-ui/react-tabs";+import {+ TabsIndicator,+ TabsIndicatorGroup,+ TabsIndicatorRoot,+ useTabsIndicator,+} from "@/components/interior/tabs-indicator";import { cn } from "@/lib/utils";-const Tabs = TabsPrimitive.Root;+// Underline tabs. One underline per Tabs instance slides between triggers+// (see components/interior/tabs-indicator).+const Tabs = TabsIndicatorRoot;const TabsList = React.forwardRef<React.ElementRef<typeof TabsPrimitive.List>,React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>->(({ className, ...props }, ref) => (+>(({ className, children, ...props }, ref) => (<TabsPrimitive.Listref={ref}className={cn("inline-flex h-8 items-center justify-start space-x-3", className)}{...props}- />+ >+ <TabsIndicatorGroup>{children}</TabsIndicatorGroup>+ </TabsPrimitive.List>));TabsList.displayName = TabsPrimitive.List.displayName;const TabsTrigger = React.forwardRef<React.ElementRef<typeof TabsPrimitive.Trigger>,React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>->(({ className, ...props }, ref) => (- <TabsPrimitive.Trigger- ref={ref}- className={cn(- "inline-flex items-center justify-center whitespace-nowrap border-b-2 border-transparent py-1 text-sm font-medium text-neutral-600 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-950 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:border-neutral-950 data-[state=active]:text-neutral-950 dark:text-neutral-400 dark:focus-visible:ring-neutral-300 dark:data-[state=active]:border-neutral-100 dark:data-[state=active]:text-neutral-50",- className- )}- {...props}- />-));+>(({ className, children, value, asChild, ...props }, ref) => {+ const indicator = useTabsIndicator(value);+ // asChild hands rendering to a single child, so there is nowhere to put the+ // underline; that case (and a plain Radix root) keeps the static border.+ const sliding = indicator !== null && !asChild;++ return (+ <TabsPrimitive.Trigger+ ref={ref}+ value={value}+ asChild={asChild}+ className={cn(+ "inline-flex items-center justify-center whitespace-nowrap border-b-2 border-transparent py-1 text-sm font-medium text-neutral-600 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:text-neutral-950 data-[state=inactive]:hover:text-neutral-900 dark:text-neutral-400 dark:focus-visible:ring-neutral-300 dark:data-[state=active]:text-neutral-50 dark:data-[state=inactive]:hover:text-neutral-200",+ sliding ? "relative" : "data-[state=active]:border-neutral-950 dark:data-[state=active]:border-neutral-100",+ className+ )}+ {...props}+ >+ {children}+ {sliding && indicator.isActive && (+ // Sits exactly on the trigger's transparent 2px bottom border.+ <TabsIndicator+ kind="underline"+ className="pointer-events-none absolute inset-x-0 -bottom-0.5 h-0.5 bg-neutral-950 dark:bg-neutral-100"+ />+ )}+ </TabsPrimitive.Trigger>+ );+});TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;const TabsContent = React.forwardRef<diff --git a/client/src/components/ui/tabs.tsx b/client/src/components/ui/tabs.tsxindex f64a8e039..35b89c326 100644--- a/client/src/components/ui/tabs.tsx+++ b/client/src/components/ui/tabs.tsx@@ -3,38 +3,68 @@import * as React from "react";import * as TabsPrimitive from "@radix-ui/react-tabs";+import {+ TabsIndicator,+ TabsIndicatorGroup,+ TabsIndicatorRoot,+ useTabsIndicator,+} from "@/components/interior/tabs-indicator";import { cn } from "@/lib/utils";-const Tabs = TabsPrimitive.Root;+// Pill tabs. One flat thumb per Tabs instance slides between triggers (see+// components/interior/tabs-indicator); no resting shadow, per the Flat rule.+const Tabs = TabsIndicatorRoot;const TabsList = React.forwardRef<React.ElementRef<typeof TabsPrimitive.List>,React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>->(({ className, ...props }, ref) => (+>(({ className, children, ...props }, ref) => (<TabsPrimitive.Listref={ref}className={cn(- "inline-flex h-9 items-center justify-center rounded-lg bg-neutral-100 p-1 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400",+ "inline-flex h-9 items-center justify-center rounded-lg bg-neutral-100 p-1 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-400",className)}{...props}- />+ >+ <TabsIndicatorGroup>{children}</TabsIndicatorGroup>+ </TabsPrimitive.List>));TabsList.displayName = TabsPrimitive.List.displayName;const TabsTrigger = React.forwardRef<React.ElementRef<typeof TabsPrimitive.Trigger>,React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>->(({ className, ...props }, ref) => (- <TabsPrimitive.Trigger- ref={ref}- className={cn(- "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-950 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-neutral-950 data-[state=active]:shadow dark:ring-offset-neutral-950 dark:focus-visible:ring-neutral-300 dark:data-[state=active]:bg-neutral-950 dark:data-[state=active]:text-neutral-50",- className- )}- {...props}- />-));+>(({ className, children, value, asChild, ...props }, ref) => {+ const indicator = useTabsIndicator(value);+ // asChild hands rendering to a single child, so there is nowhere to put the+ // thumb; that case (and a plain Radix root) keeps the static active fill.+ const sliding = indicator !== null && !asChild;++ return (+ <TabsPrimitive.Trigger+ ref={ref}+ value={value}+ asChild={asChild}+ className={cn(+ "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:text-neutral-950 data-[state=inactive]:hover:text-neutral-900 dark:focus-visible:ring-neutral-300 dark:data-[state=active]:text-neutral-50 dark:data-[state=inactive]:hover:text-neutral-200",+ // isolate + -z-10 paints the thumb under the label without wrapping+ // the consumer's children (which may rely on the trigger's flex).+ sliding ? "relative isolate" : "data-[state=active]:bg-white dark:data-[state=active]:bg-neutral-950",+ className+ )}+ {...props}+ >+ {children}+ {sliding && indicator.isActive && (+ <TabsIndicator+ kind="thumb"+ className="pointer-events-none absolute inset-0 -z-10 rounded-md bg-white dark:bg-neutral-950"+ />+ )}+ </TabsPrimitive.Trigger>+ );+});TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;const TabsContent = React.forwardRef<