@vendure-io/ui 3.0.0-next.1 → 3.0.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/THIRD_PARTY_NOTICES.md +38 -0
  2. package/package.json +6 -4
  3. package/src/components/atoms/breadcrumb.tsx +67 -9
  4. package/src/components/atoms/button.tsx +106 -9
  5. package/src/components/atoms/calendar.tsx +11 -2
  6. package/src/components/atoms/card.tsx +47 -0
  7. package/src/components/atoms/collapsible.tsx +22 -2
  8. package/src/components/atoms/field.tsx +4 -1
  9. package/src/components/atoms/label-swap.tsx +27 -2
  10. package/src/components/atoms/sonner.tsx +1 -1
  11. package/src/components/atoms/switch.tsx +59 -3
  12. package/src/components/atoms/table.tsx +133 -10
  13. package/src/components/atoms/text-link.tsx +125 -0
  14. package/src/components/molecules/app-shell.tsx +24 -2
  15. package/src/components/molecules/checklist/checklist.tsx +891 -0
  16. package/src/components/molecules/choice-card.tsx +377 -0
  17. package/src/components/molecules/collapsible-section.tsx +6 -5
  18. package/src/components/molecules/data-table/data-table-helpers.tsx +6 -1
  19. package/src/components/molecules/data-table/data-table-types.tsx +27 -2
  20. package/src/components/molecules/data-table/data-table.tsx +154 -30
  21. package/src/components/molecules/direction-link.tsx +1 -1
  22. package/src/components/molecules/format-provider.tsx +12 -2
  23. package/src/components/molecules/interactive-card.tsx +45 -0
  24. package/src/components/molecules/page-header.tsx +1 -1
  25. package/src/components/molecules/search-trigger.tsx +1 -1
  26. package/src/components/molecules/state-views/loading-state.tsx +37 -7
  27. package/src/components/molecules/state-views/skeleton-parts.tsx +245 -0
  28. package/src/components/molecules/status-badge.tsx +49 -16
  29. package/src/components/molecules/step-indicator.tsx +341 -0
  30. package/src/components/molecules/timeline.tsx +1 -1
  31. package/src/hooks/use-user-toggle-motion.ts +50 -0
  32. package/src/lib/state-dictionary.ts +9 -7
@@ -0,0 +1,891 @@
1
+ // Portions adapted from paragonhq/stealth-ui@b7f23382e7dbbac3815dee70cb1b4759c040205c (components/ui/checklist.tsx), MIT, Copyright (c) 2026 Paragon.
2
+ 'use client';
3
+
4
+ import { Button } from '@vendure-io/ui/components/atoms/button';
5
+ import { Card, CardCount } from '@vendure-io/ui/components/atoms/card';
6
+ import { Checkbox } from '@vendure-io/ui/components/atoms/checkbox';
7
+ import { Progress } from '@vendure-io/ui/components/atoms/progress';
8
+ import { ArrowLink } from '@vendure-io/ui/components/molecules/arrow-link';
9
+ import { cn } from '@vendure-io/ui/lib/utils';
10
+ import { ChevronDown, X } from 'lucide-react';
11
+ import { AnimatePresence, LayoutGroup, motion, useIsPresent, useReducedMotion } from 'motion/react';
12
+ import * as React from 'react';
13
+
14
+ // What was taken from Stealth UI's Checklist: the two lists (open steps, then
15
+ // a "Completed" group) joined by a shared `layoutId`, so a finished step flies
16
+ // into the group; the strike as a 1px background that sweeps across the
17
+ // label; the hold that keeps a step in place until it may move. The look,
18
+ // the tokens, the parts, the system mode, the hold rule and the rolling count
19
+ // are ours.
20
+ //
21
+ // The motion, in tokens. Motion for React takes numbers, so the values are
22
+ // named here after their token, as Tooltip does for `tooltip-delay`:
23
+ // - A step moves to its new list on a spring with no bounce that settles in
24
+ // `slow` (300ms). So do the lists around it.
25
+ // - The strike sweeps in `slow` on the strong ease-out; the label greys in the
26
+ // same time. Unchecked, the strike draws back quicker, in `moderate`. The
27
+ // count's digits roll in `slow` on the strong ease-out.
28
+ // - A row that appears or leaves without a place to go fades in `moderate`
29
+ // (150ms) on `soft`. A row that turns done while the Completed group is
30
+ // closed also folds its height in `slow` on `height`, so the card and the
31
+ // group under it close up with it rather than jump.
32
+ // - The Completed group opens and closes its height in `slow` on `height`.
33
+ // - The Completed header and the dismiss button fade in `moderate` on `soft`
34
+ // when they first show after the Checklist mounted.
35
+ // Reduced motion: nothing moves and nothing sweeps. Rows, the strike and the
36
+ // group change at once; rows, the header, the dismiss button and the system
37
+ // tick fade.
38
+ const MOVE = { type: 'spring', visualDuration: 0.3, bounce: 0 } as const;
39
+ const FADE = { duration: 0.15, ease: [0.25, 0.1, 0.25, 1] } as const;
40
+ const HEIGHT = { duration: 0.3, ease: [0.25, 1, 0.5, 1] } as const;
41
+ const INSTANT = { duration: 0 } as const;
42
+
43
+ /**
44
+ * On a touch screen there is no hover: a step the user checks off waits this
45
+ * long after the tap, then moves. Long enough to see the tick and the strike,
46
+ * and to tap again to undo; short enough that the list does not feel stuck.
47
+ */
48
+ const TOUCH_SETTLE_MS = 700;
49
+
50
+ // ── The hold rule ───────────────────────────────────────────────────────────
51
+
52
+ /** Which list a step shows in. */
53
+ type ChecklistSection = 'open' | 'done';
54
+
55
+ /** How the user checked a step off, which decides what lets it move. */
56
+ type ChecklistInput = 'mouse' | 'pen' | 'touch' | 'keyboard';
57
+
58
+ /**
59
+ * A step the user just checked or unchecked stays in the list it was in until
60
+ * `release` happens: `pointer` when the pointer leaves the row, `focus` when
61
+ * focus leaves it, `timer` after the touch pause.
62
+ */
63
+ type ChecklistHold = { from: ChecklistSection; release: 'pointer' | 'focus' | 'timer' };
64
+
65
+ type ChecklistHoldEvent =
66
+ | { type: 'toggle'; id: string; from: ChecklistSection; input: ChecklistInput }
67
+ | { type: 'pointerleave'; id: string }
68
+ | { type: 'focusout'; id: string }
69
+ | { type: 'timer'; id: string };
70
+
71
+ /**
72
+ * The hold rule of a manual Checklist, as a pure function: the held steps
73
+ * after an event. Exported for its tests.
74
+ *
75
+ * - A toggle holds the step in the list it was in. A second toggle before the
76
+ * step moved keeps the first list, so checking and unchecking again cancels
77
+ * the move.
78
+ * - A mouse or pen toggle lets go when the pointer leaves the row; a keyboard
79
+ * toggle when focus leaves it; a touch toggle after the touch pause.
80
+ * - Any other event leaves the holds as they are.
81
+ */
82
+ function reduceChecklistHold(
83
+ holds: Readonly<Record<string, ChecklistHold>>,
84
+ event: ChecklistHoldEvent,
85
+ ): Record<string, ChecklistHold> {
86
+ const hold = holds[event.id];
87
+ if (event.type === 'toggle') {
88
+ const release =
89
+ event.input === 'keyboard' ? 'focus' : event.input === 'touch' ? 'timer' : 'pointer';
90
+ return { ...holds, [event.id]: { from: hold?.from ?? event.from, release } };
91
+ }
92
+ const releases = { pointerleave: 'pointer', focusout: 'focus', timer: 'timer' } as const;
93
+ if (!hold || hold.release !== releases[event.type]) return holds;
94
+ const { [event.id]: _released, ...rest } = holds;
95
+ return rest;
96
+ }
97
+
98
+ /** The list a step shows in: the held list while it is held, else its state. */
99
+ function checklistSection(done: boolean, hold: ChecklistHold | undefined): ChecklistSection {
100
+ return hold?.from ?? (done ? 'done' : 'open');
101
+ }
102
+
103
+ // ── Contexts ────────────────────────────────────────────────────────────────
104
+
105
+ type ChecklistContextValue = {
106
+ mode: 'system' | 'manual';
107
+ groupId: string;
108
+ reduce: boolean;
109
+ isDone: (id: string) => boolean;
110
+ /** Whether the step was in the Checklist before this render: a step that moves keeps it. */
111
+ isKnown: (id: string) => boolean;
112
+ /** Whether the step turned done since the last render: it strikes and ticks as it arrives. */
113
+ justDone: (id: string) => boolean;
114
+ doneLabel: string;
115
+ openLabel: string;
116
+ toggle: (id: string, checked: boolean, input: ChecklistInput) => void;
117
+ release: (id: string, event: 'pointerleave' | 'focusout') => void;
118
+ };
119
+
120
+ const ChecklistContext = React.createContext<ChecklistContextValue | null>(null);
121
+
122
+ function useChecklist(part: string) {
123
+ const context = React.useContext(ChecklistContext);
124
+ if (!context) throw new Error(`${part} must be used inside a Checklist.`);
125
+ return context;
126
+ }
127
+
128
+ type StepContextValue = {
129
+ id: string;
130
+ done: boolean;
131
+ /** The step mounted done right after it turned done: its strike and tick play on arrival. */
132
+ arrived: boolean;
133
+ labelId: string;
134
+ controlId: string;
135
+ };
136
+
137
+ const StepContext = React.createContext<StepContextValue | null>(null);
138
+
139
+ function useStep(part: string) {
140
+ const context = React.useContext(StepContext);
141
+ if (!context) throw new Error(`${part} must be used inside a ChecklistStep.`);
142
+ return context;
143
+ }
144
+
145
+ // ── Checklist ───────────────────────────────────────────────────────────────
146
+
147
+ type ChecklistProps = Omit<React.ComponentProps<'div'>, 'title' | 'children'> & {
148
+ /** The checklist title, such as "Set up your project". Also names the list. */
149
+ title: React.ReactNode;
150
+ /** Heading level of the title in the page outline. Default `2`. */
151
+ headingLevel?: 2 | 3 | 4 | 5 | 6;
152
+ /**
153
+ * Who marks a step done.
154
+ *
155
+ * - `'system'` (default): the app, from its own data. Each step shows a
156
+ * tick, not a checkbox. A step that turns done moves to Completed at once.
157
+ * - `'manual'`: the user, with a checkbox on each step. A step the user
158
+ * checks off stays in place until the pointer leaves the row (focus, for
159
+ * the keyboard; a short pause, on touch), so a mis-click can be undone.
160
+ */
161
+ mode?: 'system' | 'manual';
162
+ /** Manual mode: called when the user checks or unchecks a step. */
163
+ onStepCheckedChange?: (id: string, checked: boolean) => void;
164
+ /**
165
+ * Shows a dismiss button once every step is done. The Checklist does not
166
+ * hide itself: remove it in this callback.
167
+ */
168
+ onDismiss?: () => void;
169
+ /** Accessible name of the dismiss button. Default "Dismiss checklist". */
170
+ dismissLabel?: string;
171
+ /** Label of the group of finished steps. Default "Completed". */
172
+ completedLabel?: string;
173
+ /** Whether the Completed group is open (controlled). */
174
+ completedOpen?: boolean;
175
+ /** Whether the Completed group starts open. Default `true`. */
176
+ defaultCompletedOpen?: boolean;
177
+ onCompletedOpenChange?: (open: boolean) => void;
178
+ /** What a screen reader hears after a done step's label in system mode. Default "done". */
179
+ stepDoneLabel?: string;
180
+ /** What a screen reader hears after an open step's label in system mode. Default "not done". */
181
+ stepOpenLabel?: string;
182
+ /** The count beside the title. Default "2 of 6". */
183
+ formatCount?: (done: number, total: number) => string;
184
+ /** What a screen reader hears when the count changes. Default "2 of 6 steps done". */
185
+ formatAnnouncement?: (done: number, total: number) => string;
186
+ /** The steps: ChecklistStep elements, as direct children (fragments and arrays are fine). */
187
+ children?: React.ReactNode;
188
+ };
189
+
190
+ type StepElement = React.ReactElement<ChecklistStepProps>;
191
+
192
+ /** The ChecklistStep elements among the children, through fragments and arrays. */
193
+ function collectSteps(children: React.ReactNode): StepElement[] {
194
+ const steps: StepElement[] = [];
195
+ React.Children.forEach(children, (child) => {
196
+ if (!React.isValidElement(child)) return;
197
+ if (child.type === React.Fragment) {
198
+ steps.push(...collectSteps((child.props as { children?: React.ReactNode }).children));
199
+ } else if (child.type === ChecklistStep) {
200
+ steps.push(child as StepElement);
201
+ }
202
+ });
203
+ return steps;
204
+ }
205
+
206
+ /**
207
+ * A short list of steps a person completes, with its progress: a title, a
208
+ * count ("2 of 6") that rolls when it changes, a thin bar, the open steps,
209
+ * then the finished ones in a Completed group that opens and closes. A step
210
+ * that turns done strikes through and moves into the group.
211
+ *
212
+ * Compound: put a ChecklistStep per step as a direct child, and build each
213
+ * step from its parts (label, description, detail, action, guide, body).
214
+ * Renders a card, a region named by the title.
215
+ */
216
+ function Checklist({
217
+ title,
218
+ headingLevel = 2,
219
+ mode = 'system',
220
+ onStepCheckedChange,
221
+ onDismiss,
222
+ dismissLabel = 'Dismiss checklist',
223
+ completedLabel = 'Completed',
224
+ stepDoneLabel = 'done',
225
+ stepOpenLabel = 'not done',
226
+ completedOpen: completedOpenProp,
227
+ defaultCompletedOpen = true,
228
+ onCompletedOpenChange,
229
+ formatCount = (done, total) => `${done} of ${total}`,
230
+ formatAnnouncement = (done, total) => `${done} of ${total} steps done`,
231
+ className,
232
+ children,
233
+ ...props
234
+ }: ChecklistProps) {
235
+ const reduce = useReducedMotion() ?? false;
236
+ const groupId = React.useId();
237
+ const titleId = React.useId();
238
+ const completedId = React.useId();
239
+ const Heading = `h${headingLevel}` as const;
240
+
241
+ const steps = collectSteps(children);
242
+ // Uncontrolled steps (`defaultDone`) keep the user's toggles here.
243
+ const [toggled, setToggled] = React.useState<Record<string, boolean>>({});
244
+ const doneOf = (step: StepElement) =>
245
+ step.props.done ?? toggled[step.props.id] ?? step.props.defaultDone ?? false;
246
+ const doneById = new Map(steps.map((step) => [step.props.id, doneOf(step)]));
247
+
248
+ // The steps of the last render. A step that mounts in the other list is
249
+ // moving there and arrives whole; only a new step fades in.
250
+ // A step that was open in the last render and arrives done in Completed
251
+ // mounts there with its strike and tick already set: it replays them from
252
+ // the start (see `data-arrived`).
253
+ const known = React.useRef(new Map<string, boolean>());
254
+ const knownBefore = known.current;
255
+ React.useEffect(() => {
256
+ known.current = doneById;
257
+ });
258
+ // False in the first render: what shows then is there on arrival and does
259
+ // not fade in.
260
+ const mounted = React.useRef(false);
261
+ React.useEffect(() => {
262
+ mounted.current = true;
263
+ }, []);
264
+ const arriving = mounted.current ? '' : undefined;
265
+
266
+ const [holds, setHolds] = React.useState<Record<string, ChecklistHold>>({});
267
+ const holdsRef = React.useRef(holds);
268
+ holdsRef.current = holds;
269
+ const timers = React.useRef(new Map<string, ReturnType<typeof setTimeout>>());
270
+ // The step whose row had focus when it moved: its control gets focus back
271
+ // in its new list.
272
+ const refocus = React.useRef<string | null>(null);
273
+ const rootRef = React.useRef<HTMLDivElement>(null);
274
+
275
+ const dispatch = React.useCallback((event: ChecklistHoldEvent) => {
276
+ const next = reduceChecklistHold(holdsRef.current, event);
277
+ if (next === holdsRef.current) return;
278
+ const root = rootRef.current;
279
+ const row = root?.querySelector(`[data-step-id="${CSS.escape(event.id)}"]`);
280
+ if (!(event.id in next) && row?.contains(document.activeElement)) refocus.current = event.id;
281
+ holdsRef.current = next;
282
+ setHolds(next);
283
+ }, []);
284
+
285
+ React.useEffect(() => {
286
+ const map = timers.current;
287
+ return () => {
288
+ for (const timer of Array.from(map.values())) clearTimeout(timer);
289
+ };
290
+ }, []);
291
+
292
+ const [completedOpenState, setCompletedOpenState] = React.useState(defaultCompletedOpen);
293
+ const completedOpen = completedOpenProp ?? completedOpenState;
294
+ const setCompletedOpen = (open: boolean) => {
295
+ setCompletedOpenState(open);
296
+ onCompletedOpenChange?.(open);
297
+ };
298
+
299
+ const context: ChecklistContextValue = {
300
+ mode,
301
+ groupId,
302
+ reduce,
303
+ isDone: (id) => doneById.get(id) ?? false,
304
+ isKnown: (id) => knownBefore.has(id),
305
+ justDone: (id) => knownBefore.get(id) === false && doneById.get(id) === true,
306
+ doneLabel: stepDoneLabel,
307
+ openLabel: stepOpenLabel,
308
+ toggle: (id, checked, input) => {
309
+ const from = checklistSection(!checked, holdsRef.current[id]);
310
+ setToggled((prev) => ({ ...prev, [id]: checked }));
311
+ onStepCheckedChange?.(id, checked);
312
+ dispatch({ type: 'toggle', id, from, input });
313
+ clearTimeout(timers.current.get(id));
314
+ if (input === 'touch') {
315
+ timers.current.set(
316
+ id,
317
+ setTimeout(() => {
318
+ timers.current.delete(id);
319
+ dispatch({ type: 'timer', id });
320
+ }, TOUCH_SETTLE_MS),
321
+ );
322
+ }
323
+ },
324
+ release: (id, event) => dispatch({ type: event, id }),
325
+ };
326
+
327
+ const open: StepElement[] = [];
328
+ const finished: StepElement[] = [];
329
+ for (const step of steps) {
330
+ const section = checklistSection(doneOf(step), holds[step.props.id]);
331
+ (section === 'done' ? finished : open).push(step);
332
+ }
333
+ const total = steps.length;
334
+ const complete = steps.filter(doneOf).length;
335
+ const allDone = total > 0 && complete === total;
336
+
337
+ // After a step moved, give its control focus back, or the Completed toggle
338
+ // when the step went into a closed group.
339
+ React.useEffect(() => {
340
+ const id = refocus.current;
341
+ if (!id) return;
342
+ refocus.current = null;
343
+ const root = rootRef.current;
344
+ // The row that leaves fades out for a moment beside its new copy: look in
345
+ // the list the step moved to.
346
+ const list = open.some((step) => step.props.id === id)
347
+ ? 'checklist-steps'
348
+ : 'checklist-completed-steps';
349
+ const control = root?.querySelector<HTMLElement>(
350
+ `[data-slot=${list}] [data-step-id="${CSS.escape(id)}"] [data-slot=checklist-step-control]`,
351
+ );
352
+ (
353
+ control ?? root?.querySelector<HTMLElement>('[data-slot=checklist-completed-trigger]')
354
+ )?.focus();
355
+ });
356
+
357
+ // The polite announcement: only for a change, never on mount.
358
+ const [announcement, setAnnouncement] = React.useState('');
359
+ const lastCount = React.useRef({ complete, total });
360
+ React.useEffect(() => {
361
+ if (lastCount.current.complete === complete && lastCount.current.total === total) return;
362
+ lastCount.current = { complete, total };
363
+ setAnnouncement(formatAnnouncement(complete, total));
364
+ }, [complete, total, formatAnnouncement]);
365
+
366
+ const layout = reduce ? false : 'position';
367
+
368
+ return (
369
+ <ChecklistContext.Provider value={context}>
370
+ {/* A card that is a labelled region: the title names it. */}
371
+ <Card
372
+ ref={rootRef}
373
+ role="region"
374
+ data-slot="checklist"
375
+ data-mode={mode}
376
+ aria-labelledby={titleId}
377
+ className={cn('gap-0 pb-0', className)}
378
+ {...props}
379
+ >
380
+ <div
381
+ data-slot="checklist-header"
382
+ className="flex flex-col gap-3 ps-(--card-ps) pe-(--card-px) pb-3"
383
+ >
384
+ <div className="flex min-h-7 items-center gap-3">
385
+ <Heading
386
+ id={titleId}
387
+ data-slot="checklist-title"
388
+ className="m-0 min-w-0 flex-1 truncate text-sm font-semibold"
389
+ >
390
+ {title}
391
+ </Heading>
392
+ <span
393
+ data-slot="checklist-count"
394
+ aria-hidden="true"
395
+ className="text-muted-foreground shrink-0 text-xs font-semibold tabular-nums"
396
+ >
397
+ <RollingCount value={complete} format={(value) => formatCount(value, total)} />
398
+ </span>
399
+ {allDone && onDismiss ? (
400
+ <span
401
+ data-arrived={arriving}
402
+ className="flex transition-opacity duration-moderate ease-soft data-arrived:starting:opacity-0"
403
+ >
404
+ <Button
405
+ data-slot="checklist-dismiss"
406
+ variant="ghost"
407
+ size="icon-sm"
408
+ aria-label={dismissLabel}
409
+ onClick={onDismiss}
410
+ className="-me-1.5"
411
+ >
412
+ <X />
413
+ </Button>
414
+ </span>
415
+ ) : null}
416
+ </div>
417
+ <Progress
418
+ data-slot="checklist-progress"
419
+ value={complete}
420
+ max={Math.max(total, 1)}
421
+ aria-labelledby={titleId}
422
+ getAriaValueText={() => formatCount(complete, total)}
423
+ tone={allDone ? 'success' : 'default'}
424
+ />
425
+ <span role="status" className="sr-only">
426
+ {announcement}
427
+ </span>
428
+ </div>
429
+
430
+ <LayoutGroup id={groupId}>
431
+ <ul
432
+ data-slot="checklist-steps"
433
+ aria-labelledby={titleId}
434
+ className="relative flex flex-col border-t border-border empty:hidden"
435
+ >
436
+ {/* With the Completed group open, a row that turns done flies to
437
+ it and leaves no gap. With it closed, the row has nowhere to
438
+ go: it stays in the flow and folds (see ChecklistStep). */}
439
+ <AnimatePresence
440
+ initial={false}
441
+ mode={completedOpen ? 'popLayout' : 'sync'}
442
+ custom={!completedOpen}
443
+ >
444
+ {open.map((step) => React.cloneElement(step, { key: step.props.id }))}
445
+ </AnimatePresence>
446
+ </ul>
447
+
448
+ {finished.length > 0 ? (
449
+ <motion.div
450
+ layout={layout}
451
+ transition={MOVE}
452
+ data-slot="checklist-completed"
453
+ className="border-t border-border"
454
+ >
455
+ <button
456
+ type="button"
457
+ data-slot="checklist-completed-trigger"
458
+ data-arrived={arriving}
459
+ aria-expanded={completedOpen}
460
+ aria-controls={completedOpen ? completedId : undefined}
461
+ onClick={() => setCompletedOpen(!completedOpen)}
462
+ className="group/checklist-completed text-foreground-secondary flex min-h-11 w-full cursor-pointer items-center gap-2 ps-(--card-ps) pe-(--card-px) text-start text-sm font-medium outline-none [transition:color_var(--transition-duration-fast)_var(--ease-default),background-color_var(--transition-duration-fast)_var(--ease-default),opacity_var(--transition-duration-moderate)_var(--ease-soft)] data-arrived:starting:opacity-0 hover:bg-muted focus-visible:outline-solid focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
463
+ >
464
+ {completedLabel}
465
+ <CardCount className="ms-0">{finished.length}</CardCount>
466
+ <ChevronDown
467
+ aria-hidden="true"
468
+ strokeWidth={1.75}
469
+ className={cn(
470
+ 'text-muted-foreground ms-auto size-3.75 shrink-0 opacity-70 [transition:rotate_var(--transition-duration-slow)_var(--ease-height),opacity_var(--transition-duration-fast)_var(--ease-default)] group-hover/checklist-completed:opacity-100 motion-reduce:[transition:opacity_var(--transition-duration-fast)_var(--ease-default)]',
471
+ completedOpen && 'rotate-180',
472
+ )}
473
+ />
474
+ </button>
475
+ <CompletedPanel open={completedOpen} reduce={reduce}>
476
+ <ul
477
+ id={completedId}
478
+ data-slot="checklist-completed-steps"
479
+ aria-label={completedLabel}
480
+ className="relative flex flex-col"
481
+ >
482
+ <AnimatePresence initial={false} mode="popLayout">
483
+ {finished.map((step) => React.cloneElement(step, { key: step.props.id }))}
484
+ </AnimatePresence>
485
+ </ul>
486
+ </CompletedPanel>
487
+ </motion.div>
488
+ ) : null}
489
+ </LayoutGroup>
490
+ </Card>
491
+ </ChecklistContext.Provider>
492
+ );
493
+ }
494
+
495
+ /**
496
+ * The Completed group's rows. Its height opens and closes; it clips only while
497
+ * it does, so a step that flies in from the open list is never cut off.
498
+ */
499
+ function CompletedPanel({
500
+ open,
501
+ reduce,
502
+ children,
503
+ }: {
504
+ open: boolean;
505
+ reduce: boolean;
506
+ children: React.ReactNode;
507
+ }) {
508
+ const [clip, setClip] = React.useState(false);
509
+ return (
510
+ <AnimatePresence initial={false}>
511
+ {open ? (
512
+ <motion.div
513
+ key="completed"
514
+ initial={{ height: 0, opacity: 0 }}
515
+ animate={{ height: 'auto', opacity: 1 }}
516
+ exit={{ height: 0, opacity: 0 }}
517
+ transition={reduce ? { height: INSTANT, opacity: FADE } : { ...HEIGHT, opacity: FADE }}
518
+ onAnimationStart={() => setClip(true)}
519
+ onAnimationComplete={() => setClip(false)}
520
+ className={clip ? 'overflow-hidden' : undefined}
521
+ >
522
+ {children}
523
+ </motion.div>
524
+ ) : null}
525
+ </AnimatePresence>
526
+ );
527
+ }
528
+
529
+ // ── Rolling count ───────────────────────────────────────────────────────────
530
+
531
+ /**
532
+ * The count beside the title. Each digit is a column of 0–9 that slides to
533
+ * its value, so a change rolls digit by digit. The text around the number
534
+ * comes from `format`. Decorative: the Checklist announces the count itself.
535
+ */
536
+ function RollingCount({ value, format }: { value: number; format: (value: number) => string }) {
537
+ const text = format(value);
538
+ const number = String(value);
539
+ const at = text.indexOf(number);
540
+ if (at < 0) return text;
541
+ const digits = number.split('');
542
+ return (
543
+ <>
544
+ {text.slice(0, at)}
545
+ <span data-slot="checklist-count-value" className="inline-flex">
546
+ {digits.map((digit, index) => (
547
+ // Keyed from the right, so the ones column stays the ones column
548
+ // when the number gains a digit.
549
+ <span
550
+ key={digits.length - index}
551
+ className="relative inline-block h-[1lh] overflow-hidden"
552
+ >
553
+ <span
554
+ className="flex flex-col transition-[translate] duration-slow ease-out motion-reduce:transition-none"
555
+ style={{ translate: `0 ${-Number(digit) * 10}%` }}
556
+ >
557
+ {'0123456789'.split('').map((d) => (
558
+ <span key={d}>{d}</span>
559
+ ))}
560
+ </span>
561
+ </span>
562
+ ))}
563
+ </span>
564
+ {text.slice(at + number.length)}
565
+ </>
566
+ );
567
+ }
568
+
569
+ // ── Steps ───────────────────────────────────────────────────────────────────
570
+
571
+ type ChecklistStepProps = Omit<React.ComponentProps<'li'>, 'id' | 'children'> & {
572
+ /** A stable id, unique in the Checklist. */
573
+ id: string;
574
+ /** Whether the step is done (controlled). In system mode, set it from the app's data. */
575
+ done?: boolean;
576
+ /** Manual mode: whether the step starts done, when the Checklist keeps the state. */
577
+ defaultDone?: boolean;
578
+ /** The step's parts: ChecklistStepLabel, and optionally the others. */
579
+ children?: React.ReactNode;
580
+ };
581
+
582
+ // The row grid. The label and the detail share the first line; the
583
+ // description and the guide stack under the label. The detail ends at the
584
+ // row's end edge, so it lines up on every row. From a 448px row (`@md`) the
585
+ // action sits in the same end column, under the detail; on a narrower row it
586
+ // goes under the text, at its start. The body spans the row under it all. Empty
587
+ // rows take no space: every part brings its own top margin.
588
+ const STEP_GRID =
589
+ 'grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 [grid-template-areas:"label_detail""description_description""guide_guide""action_action""body_body"] @md:[grid-template-areas:"label_detail""description_action""guide_action""body_body"]';
590
+
591
+ /**
592
+ * One step of a Checklist: the tick or the checkbox, then its parts. Must be
593
+ * a direct child of the Checklist (fragments and arrays are fine), which
594
+ * places it in the open list or in Completed.
595
+ */
596
+ function ChecklistStep({
597
+ id,
598
+ done: _done,
599
+ defaultDone: _defaultDone,
600
+ className,
601
+ children,
602
+ onPointerDown,
603
+ onPointerEnter,
604
+ onPointerLeave,
605
+ onKeyDown,
606
+ onBlur,
607
+ ...props
608
+ }: ChecklistStepProps) {
609
+ const checklist = useChecklist('ChecklistStep');
610
+ const done = checklist.isDone(id);
611
+ const labelId = React.useId();
612
+ const controlId = React.useId();
613
+ // How the user last pressed on this row: the toggle that follows lets go
614
+ // by the same means.
615
+ const input = React.useRef<ChecklistInput>('keyboard');
616
+ // Latched at mount: a row that arrives done right after the step turned
617
+ // done plays its strike and tick as it lands.
618
+ const [arrived] = React.useState(() => checklist.justDone(id));
619
+ const present = useIsPresent();
620
+ const reduce = checklist.reduce;
621
+ const step = React.useMemo(
622
+ () => ({ id, done, arrived: arrived && done, labelId, controlId }),
623
+ [id, done, arrived, labelId, controlId],
624
+ );
625
+
626
+ return (
627
+ <StepContext.Provider value={step}>
628
+ <motion.li
629
+ layout={reduce ? false : 'position'}
630
+ layoutId={reduce ? undefined : `${checklist.groupId}-${id}`}
631
+ // The row flies whole: no crossfade with the copy it leaves behind,
632
+ // so the rows it passes never show through it.
633
+ layoutCrossfade={false}
634
+ initial={checklist.isKnown(id) ? false : { opacity: 0 }}
635
+ animate={{ opacity: 1 }}
636
+ // `fold` comes from the list's AnimatePresence: true when the row
637
+ // leaves with no place to go and the rows under it must close up.
638
+ variants={{
639
+ exit: (fold: boolean) =>
640
+ fold
641
+ ? {
642
+ opacity: 0,
643
+ height: 0,
644
+ paddingTop: 0,
645
+ paddingBottom: 0,
646
+ borderTopWidth: 0,
647
+ transition: reduce ? { ...INSTANT, opacity: FADE } : { ...HEIGHT, opacity: FADE },
648
+ }
649
+ : { opacity: 0, transition: FADE },
650
+ }}
651
+ exit="exit"
652
+ transition={reduce ? { ...INSTANT, opacity: FADE } : { ...MOVE, opacity: FADE }}
653
+ data-slot="checklist-step"
654
+ data-step-id={id}
655
+ data-done={done ? '' : undefined}
656
+ className={cn(
657
+ 'bg-card relative flex items-start gap-3 border-t border-border py-3 ps-(--card-ps) pe-(--card-px) first:border-t-0',
658
+ !present && 'overflow-hidden',
659
+ className,
660
+ )}
661
+ onPointerDown={(event) => {
662
+ input.current = event.pointerType as ChecklistInput;
663
+ onPointerDown?.(event);
664
+ }}
665
+ onPointerEnter={onPointerEnter}
666
+ onPointerLeave={(event) => {
667
+ // A finger "leaves" as it lifts, before the tap's click: touch lets
668
+ // go on the pause instead.
669
+ if (event.pointerType !== 'touch') checklist.release(id, 'pointerleave');
670
+ onPointerLeave?.(event);
671
+ }}
672
+ onKeyDown={(event) => {
673
+ input.current = 'keyboard';
674
+ onKeyDown?.(event);
675
+ }}
676
+ onBlur={(event) => {
677
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
678
+ checklist.release(id, 'focusout');
679
+ }
680
+ onBlur?.(event);
681
+ }}
682
+ {...(props as React.ComponentProps<typeof motion.li>)}
683
+ >
684
+ <span className="flex h-5 shrink-0 items-center">
685
+ {checklist.mode === 'manual' ? (
686
+ // A native button, so the label's `htmlFor` reaches it and a
687
+ // click on the label toggles the step.
688
+ <Checkbox
689
+ nativeButton
690
+ render={<button type="button" />}
691
+ id={controlId}
692
+ data-slot="checklist-step-control"
693
+ aria-labelledby={labelId}
694
+ checked={done}
695
+ onCheckedChange={(checked) => checklist.toggle(id, checked, input.current)}
696
+ />
697
+ ) : (
698
+ <SystemTick done={done} arrived={step.arrived} />
699
+ )}
700
+ </span>
701
+ <div className="@container min-w-0 flex-1">
702
+ <div className={STEP_GRID}>{children}</div>
703
+ </div>
704
+ </motion.li>
705
+ </StepContext.Provider>
706
+ );
707
+ }
708
+
709
+ /**
710
+ * System mode: a round tick, not a control. Open, an empty ring; done, the
711
+ * ring fills and the tick draws in. A row that arrives done in Completed
712
+ * starts from the open look (`@starting-style`), so the fill and the draw play
713
+ * as it lands. Reduced motion: the fill and the tick fade.
714
+ */
715
+ function SystemTick({ done, arrived }: { done: boolean; arrived: boolean }) {
716
+ return (
717
+ <span
718
+ data-slot="checklist-step-tick"
719
+ data-done={done ? '' : undefined}
720
+ data-arrived={arrived ? '' : undefined}
721
+ aria-hidden="true"
722
+ className="group/tick border-control-border relative grid size-4 place-items-center rounded-full border transition-[border-color] duration-slow ease-out data-done:border-primary data-arrived:starting:border-control-border"
723
+ >
724
+ <span className="bg-primary absolute -inset-px rounded-full opacity-0 transition-opacity duration-moderate ease-soft group-data-done/tick:opacity-100 group-data-arrived/tick:starting:opacity-0" />
725
+ <svg
726
+ aria-hidden="true"
727
+ viewBox="0 0 24 24"
728
+ fill="none"
729
+ stroke="currentColor"
730
+ strokeWidth="2.5"
731
+ strokeLinecap="round"
732
+ strokeLinejoin="round"
733
+ className="text-primary-foreground relative size-3"
734
+ >
735
+ <path
736
+ d="M5 12.5l4.5 4.5L19 7.5"
737
+ pathLength={1}
738
+ className="[stroke-dasharray:1] [stroke-dashoffset:1] transition-[stroke-dashoffset] duration-fast ease-soft group-data-done/tick:[stroke-dashoffset:0] group-data-done/tick:delay-(--transition-duration-fast) group-data-done/tick:duration-slow group-data-done/tick:ease-out motion-safe:group-data-arrived/tick:starting:[stroke-dashoffset:1] motion-reduce:transition-opacity motion-reduce:[stroke-dashoffset:0] motion-reduce:opacity-0 motion-reduce:group-data-done/tick:opacity-100"
739
+ />
740
+ </svg>
741
+ </span>
742
+ );
743
+ }
744
+
745
+ /**
746
+ * The step's name. In manual mode it labels the checkbox, and a click on it
747
+ * toggles the step. A done step strikes through: the line sweeps across from
748
+ * the start edge, over every wrapped line. A row that arrives done in
749
+ * Completed sweeps as it lands.
750
+ */
751
+ function ChecklistStepLabel({ className, children, ...props }: React.ComponentProps<'span'>) {
752
+ const checklist = useChecklist('ChecklistStepLabel');
753
+ const step = useStep('ChecklistStepLabel');
754
+ const Tag = checklist.mode === 'manual' ? 'label' : 'span';
755
+ return (
756
+ <Tag
757
+ id={step.labelId}
758
+ htmlFor={checklist.mode === 'manual' ? step.controlId : undefined}
759
+ data-slot="checklist-step-label"
760
+ className={cn(
761
+ 'min-w-0 font-medium leading-5 [grid-area:label]',
762
+ checklist.mode === 'manual' && 'cursor-pointer',
763
+ className,
764
+ )}
765
+ {...(props as React.ComponentProps<'label'>)}
766
+ >
767
+ <span
768
+ data-done={step.done ? '' : undefined}
769
+ data-arrived={step.arrived ? '' : undefined}
770
+ className="data-arrived:starting:text-foreground motion-safe:data-arrived:starting:[background-size:0%_1px] text-foreground data-done:text-muted-foreground bg-linear-to-r from-current to-current bg-no-repeat [background-position:0_55%] rtl:[background-position:100%_55%] [background-size:0%_1px] [transition:background-size_var(--transition-duration-moderate)_var(--ease-out),color_var(--transition-duration-moderate)_var(--ease-out)] data-done:[background-size:100%_1px] motion-safe:data-done:[transition:background-size_var(--transition-duration-slow)_var(--ease-out),color_var(--transition-duration-slow)_var(--ease-out)] motion-reduce:[transition:color_var(--transition-duration-moderate)_var(--ease-soft)]"
771
+ >
772
+ {children}
773
+ </span>
774
+ {checklist.mode === 'system' ? (
775
+ <span className="sr-only">, {step.done ? checklist.doneLabel : checklist.openLabel}</span>
776
+ ) : null}
777
+ </Tag>
778
+ );
779
+ }
780
+
781
+ /** A sentence under the label: what the step does or why it matters. */
782
+ function ChecklistStepDescription({ className, ...props }: React.ComponentProps<'p'>) {
783
+ return (
784
+ <p
785
+ data-slot="checklist-step-description"
786
+ className={cn('text-muted-foreground m-0 mt-0.5 [grid-area:description]', className)}
787
+ {...props}
788
+ />
789
+ );
790
+ }
791
+
792
+ /** A short fact at the end of the label's line: an estimate, a date, an owner. */
793
+ function ChecklistStepDetail({ className, ...props }: React.ComponentProps<'span'>) {
794
+ return (
795
+ <span
796
+ data-slot="checklist-step-detail"
797
+ className={cn(
798
+ 'text-muted-foreground justify-self-end text-xs leading-5 tabular-nums whitespace-nowrap [grid-area:detail]',
799
+ className,
800
+ )}
801
+ {...props}
802
+ />
803
+ );
804
+ }
805
+
806
+ /**
807
+ * The one thing that does the step: a Button (pass `render` for a router
808
+ * link) or a link styled as one. Shows while the step is open only.
809
+ */
810
+ function ChecklistStepAction({ className, ...props }: React.ComponentProps<'div'>) {
811
+ const step = useStep('ChecklistStepAction');
812
+ if (step.done) return null;
813
+ return (
814
+ <div
815
+ data-slot="checklist-step-action"
816
+ className={cn(
817
+ 'mt-3 flex shrink-0 items-center justify-self-start [grid-area:action] @md:mt-0 @md:self-center @md:justify-self-end',
818
+ className,
819
+ )}
820
+ {...props}
821
+ />
822
+ );
823
+ }
824
+
825
+ /**
826
+ * A link to the guide that explains the step: an external ArrowLink. It opens
827
+ * a new tab unless you pass `target`; a screen reader then hears
828
+ * `newTabLabel` after the text. Shows on open and done steps.
829
+ */
830
+ function ChecklistStepGuide({
831
+ className,
832
+ children,
833
+ target = '_blank',
834
+ rel = target === '_blank' ? 'noreferrer' : undefined,
835
+ newTabLabel = '(opens in a new tab)',
836
+ ...props
837
+ }: React.ComponentProps<'a'> & {
838
+ /** Read after the text when the link opens a new tab. Default "(opens in a new tab)". */
839
+ newTabLabel?: string;
840
+ }) {
841
+ return (
842
+ <ArrowLink
843
+ direction="external"
844
+ data-slot="checklist-step-guide"
845
+ target={target}
846
+ rel={rel}
847
+ className={cn('mt-1 w-fit [grid-area:guide]', className)}
848
+ {...props}
849
+ >
850
+ {children}
851
+ {target === '_blank' ? <span className="sr-only"> {newTabLabel}</span> : null}
852
+ </ArrowLink>
853
+ );
854
+ }
855
+
856
+ /**
857
+ * More content under an open step, across the row: the commands to run, a
858
+ * short form. Shows while the step is open only.
859
+ */
860
+ function ChecklistStepBody({ className, ...props }: React.ComponentProps<'div'>) {
861
+ const step = useStep('ChecklistStepBody');
862
+ if (step.done) return null;
863
+ return (
864
+ <div
865
+ data-slot="checklist-step-body"
866
+ className={cn('mt-3 min-w-0 [grid-area:body]', className)}
867
+ {...props}
868
+ />
869
+ );
870
+ }
871
+
872
+ export {
873
+ Checklist,
874
+ ChecklistStep,
875
+ ChecklistStepLabel,
876
+ ChecklistStepDescription,
877
+ ChecklistStepDetail,
878
+ ChecklistStepAction,
879
+ ChecklistStepGuide,
880
+ ChecklistStepBody,
881
+ reduceChecklistHold,
882
+ checklistSection,
883
+ };
884
+ export type {
885
+ ChecklistProps,
886
+ ChecklistStepProps,
887
+ ChecklistHold,
888
+ ChecklistHoldEvent,
889
+ ChecklistInput,
890
+ ChecklistSection,
891
+ };