mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
refactor(ui): one Segmented control instead of four
The timeline's Segmented, the document sources' SegmentedChoice, the medication detail's SegmentedToggle and the icon-only ViewToggle were four implementations of the same control in two looks, two at 36 px on a phone. ui/segmented.tsx replaces all four, plus the hand-rolled range rows above the lab and custom metric charts, the mood dimension window and the inventory quantity mode: a muted track with the chosen segment raised, radio semantics with roving focus by default, pressed-button semantics for view switches and form sheets, icon-only segments, and 44 px per segment on a coarse pointer. A test holds the definition to that one module.
This commit is contained in:
1 parent
c849619bee
commit
ab3f21c58c
26 files changed
+428
-139
No files matched your search
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { isValidElement, type ReactElement, type ReactNode } from "react";
|
||||
import { LayoutGrid, Table } from "lucide-react";
|
||||
|
||||
import { Segmented, type SegmentedProps } from "../segmented";
|
||||
|
||||
const OPTIONS = [
|
||||
{ value: "recent", label: "Last 90 days" },
|
||||
{ value: "all", label: "All" },
|
||||
] as const;
|
||||
|
||||
type Props = SegmentedProps<"recent" | "all">;
|
||||
|
||||
function html(props: Partial<Props> = {}) {
|
||||
return renderToStaticMarkup(
|
||||
<Segmented
|
||||
options={OPTIONS}
|
||||
value="recent"
|
||||
onChange={() => {}}
|
||||
label="History"
|
||||
slot="history-view"
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
/** The segment buttons of a rendered tree, for driving their handlers. */
|
||||
function buttons(node: ReactNode): ReactElement<{ onClick: () => void }>[] {
|
||||
const out: ReactElement<{ onClick: () => void }>[] = [];
|
||||
const walk = (n: ReactNode) => {
|
||||
if (Array.isArray(n)) return n.forEach(walk);
|
||||
if (!isValidElement(n)) return;
|
||||
const el = n as ReactElement<{ children?: ReactNode; onClick: () => void }>;
|
||||
if (el.type === "button") out.push(el);
|
||||
walk(el.props.children);
|
||||
};
|
||||
walk(node);
|
||||
return out;
|
||||
}
|
||||
|
||||
vi.mock("@/hooks/use-roving-radio-group", () => ({
|
||||
useRovingRadioGroup: () => ({
|
||||
getRadioProps: (i: number) => ({ tabIndex: i === 0 ? 0 : -1 }),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("<Segmented>", () => {
|
||||
it("is a radiogroup with one checked radio by default", () => {
|
||||
const out = html();
|
||||
expect(out).toContain('role="radiogroup"');
|
||||
expect(out).toContain('aria-label="History"');
|
||||
expect(out.match(/role="radio"/g)?.length).toBe(2);
|
||||
expect(out.match(/aria-checked="true"/g)?.length).toBe(1);
|
||||
expect(out).toContain('data-slot="history-view-all"');
|
||||
});
|
||||
|
||||
it("gives every segment the 44 px floor on a coarse pointer", () => {
|
||||
const out = html();
|
||||
expect(out.match(/pointer-coarse:min-h-11/g)?.length).toBe(2);
|
||||
expect(out).toContain("min-h-9");
|
||||
});
|
||||
|
||||
it("renders pressed buttons in toggle mode", () => {
|
||||
const out = html({ mode: "toggle" });
|
||||
expect(out).toContain('role="group"');
|
||||
expect(out).not.toContain('role="radio"');
|
||||
expect(out).toContain('aria-pressed="true"');
|
||||
expect(out).toContain('aria-pressed="false"');
|
||||
});
|
||||
|
||||
it("names icon-only segments and sizes them square", () => {
|
||||
const out = renderToStaticMarkup(
|
||||
<Segmented
|
||||
mode="toggle"
|
||||
iconOnly
|
||||
options={[
|
||||
{ value: "cards", label: "Cards", icon: LayoutGrid },
|
||||
{ value: "table", label: "Table", icon: Table },
|
||||
]}
|
||||
value="cards"
|
||||
onChange={() => {}}
|
||||
label="View"
|
||||
optionSlot={(v) => `medications-view-${v}`}
|
||||
/>,
|
||||
);
|
||||
expect(out).toContain('aria-label="Cards"');
|
||||
expect(out).toContain('title="Table"');
|
||||
expect(out.match(/pointer-coarse:size-11/g)?.length).toBe(2);
|
||||
expect(out).toContain('data-slot="medications-view-table"');
|
||||
expect(out).not.toContain(">Cards<");
|
||||
});
|
||||
|
||||
it("re-fires the chosen segment in radio mode, which can open something", () => {
|
||||
const onChange = vi.fn();
|
||||
const tree = Segmented({
|
||||
options: OPTIONS,
|
||||
value: "recent",
|
||||
onChange,
|
||||
label: "History",
|
||||
});
|
||||
buttons(tree)[0].props.onClick();
|
||||
expect(onChange).toHaveBeenCalledWith("recent");
|
||||
});
|
||||
|
||||
it("ignores a press on the active segment in toggle mode", () => {
|
||||
const onChange = vi.fn();
|
||||
const tree = Segmented({
|
||||
options: OPTIONS,
|
||||
value: "recent",
|
||||
onChange,
|
||||
label: "History",
|
||||
mode: "toggle",
|
||||
});
|
||||
const [active, other] = buttons(tree);
|
||||
active.props.onClick();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
other.props.onClick();
|
||||
expect(onChange).toHaveBeenCalledWith("all");
|
||||
});
|
||||
});
|
||||
|
||||
describe("one segmented control", () => {
|
||||
it("is the only segmented-control component in the tree", async () => {
|
||||
const { readFileSync } = await import("node:fs");
|
||||
const { join } = await import("node:path");
|
||||
const { walkSourceFiles } =
|
||||
await import("@/__tests__/helpers/source-files");
|
||||
const src = join(__dirname, "../../..");
|
||||
const defining = walkSourceFiles(src, { floor: 2000 })
|
||||
.filter((p) => !p.includes("__tests__/"))
|
||||
.filter((p) =>
|
||||
/export function (?:Segmented\w*|ViewToggle|\w*SegmentedToggle)\b/.test(
|
||||
readFileSync(join(src, p), "utf8"),
|
||||
),
|
||||
);
|
||||
expect(defining).toEqual(["components/ui/segmented.tsx"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* The segmented control: a short row of mutually exclusive choices on one
|
||||
* track (zoom level, chronicle grouping, cards or table, recent or all,
|
||||
* Paperless-ngx or Papra). One look everywhere: a muted track, the chosen
|
||||
* segment raised on the background colour, never coloured.
|
||||
*
|
||||
* Two semantics, one chrome:
|
||||
*
|
||||
* - `mode="radio"` (default): an ARIA radiogroup with one tab stop and arrow
|
||||
* keys through the shared roving helper. `onChange` fires on every press,
|
||||
* the chosen segment included, because a segment can open something (the
|
||||
* timeline's custom range re-opens its popover).
|
||||
* - `mode="toggle"`: buttons with `aria-pressed`, for a view switch and for a
|
||||
* choice inside a form sheet (the sheets' discard guard reads any checked
|
||||
* radio as the person's input, and a precision that starts on "Day" is a
|
||||
* default, not an answer). Pressing the active segment does nothing, so a
|
||||
* setter that saves a preference is not called twice.
|
||||
*
|
||||
* Touch: every segment is at least 44 px on a coarse pointer and 36 px under
|
||||
* a mouse, the same floor `Button` carries. The four controls this replaced
|
||||
* sat at 36, 36, 44 and 44.
|
||||
*
|
||||
* An option with an `icon` and `iconOnly` on the control renders the icon and
|
||||
* names the segment through `aria-label` and `title`.
|
||||
*/
|
||||
import { Fragment, type ReactElement, type ReactNode } from "react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { useRovingRadioGroup } from "@/hooks/use-roving-radio-group";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface SegmentedOption<T extends string> {
|
||||
value: T;
|
||||
label: string;
|
||||
icon?: LucideIcon;
|
||||
/** Rendered after the label (a connected check beside a system name). */
|
||||
trailing?: ReactNode;
|
||||
}
|
||||
|
||||
export interface SegmentedProps<T extends string> {
|
||||
options: ReadonlyArray<SegmentedOption<T>>;
|
||||
value: T;
|
||||
onChange: (next: T) => void;
|
||||
/** Accessible name of the group. */
|
||||
label: string;
|
||||
/** `data-slot` of the group. */
|
||||
slot?: string;
|
||||
/**
|
||||
* `data-slot` of one segment. Defaults to `${slot}-${value}` when the group
|
||||
* has a slot.
|
||||
*/
|
||||
optionSlot?: (value: T) => string;
|
||||
mode?: "radio" | "toggle";
|
||||
/** Render the options' icons only; the label becomes the accessible name. */
|
||||
iconOnly?: boolean;
|
||||
/** Spread the segments over the full width. */
|
||||
stretch?: boolean;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
/**
|
||||
* Wraps one segment's button, for a popover anchored to it (the range
|
||||
* segment). Returns the button itself for every other segment.
|
||||
*/
|
||||
wrapOption?: (value: T, button: ReactElement) => ReactNode;
|
||||
}
|
||||
|
||||
export function Segmented<T extends string>({
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
label,
|
||||
slot,
|
||||
optionSlot,
|
||||
mode = "radio",
|
||||
iconOnly = false,
|
||||
stretch = false,
|
||||
disabled = false,
|
||||
className,
|
||||
wrapOption,
|
||||
}: SegmentedProps<T>) {
|
||||
const selectedIndex = options.findIndex((o) => o.value === value);
|
||||
const { getRadioProps } = useRovingRadioGroup({
|
||||
count: options.length,
|
||||
selectedIndex,
|
||||
onSelect: (index) => {
|
||||
if (!disabled) onChange(options[index].value);
|
||||
},
|
||||
});
|
||||
const segmentSlot =
|
||||
optionSlot ?? (slot ? (v: T) => `${slot}-${v}` : undefined);
|
||||
|
||||
return (
|
||||
<div
|
||||
role={mode === "toggle" ? "group" : "radiogroup"}
|
||||
aria-label={label}
|
||||
aria-disabled={disabled || undefined}
|
||||
data-slot={slot}
|
||||
className={cn(
|
||||
"bg-muted inline-flex shrink-0 items-center gap-0.5 rounded-lg p-0.5",
|
||||
stretch && "flex w-full",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{options.map((option, index) => {
|
||||
const checked = option.value === value;
|
||||
const Icon = option.icon;
|
||||
const button = (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
{...(mode === "toggle"
|
||||
? { "aria-pressed": checked }
|
||||
: {
|
||||
role: "radio",
|
||||
"aria-checked": checked,
|
||||
...getRadioProps(index),
|
||||
})}
|
||||
{...(iconOnly
|
||||
? { "aria-label": option.label, title: option.label }
|
||||
: {})}
|
||||
disabled={disabled}
|
||||
data-value={option.value}
|
||||
data-slot={segmentSlot?.(option.value)}
|
||||
onClick={() => {
|
||||
if (mode === "toggle" && checked) return;
|
||||
onChange(option.value);
|
||||
}}
|
||||
className={cn(
|
||||
"focus-visible:ring-ring/50 inline-flex items-center justify-center gap-1.5 rounded-md text-sm font-medium transition-colors outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none",
|
||||
iconOnly
|
||||
? "size-9 pointer-coarse:size-11"
|
||||
: "min-h-9 px-3 pointer-coarse:min-h-11",
|
||||
stretch && "flex-1",
|
||||
checked
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{Icon ? (
|
||||
<Icon className="size-4 shrink-0" aria-hidden="true" />
|
||||
) : null}
|
||||
{iconOnly ? null : option.label}
|
||||
{iconOnly ? null : option.trailing}
|
||||
</button>
|
||||
);
|
||||
return wrapOption ? (
|
||||
<Fragment key={option.value}>
|
||||
{wrapOption(option.value, button)}
|
||||
</Fragment>
|
||||
) : (
|
||||
button
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user