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

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 (120) hide show
  1. package/package.json +19 -5
  2. package/src/components/atoms/accordion.tsx +21 -6
  3. package/src/components/atoms/alert-dialog.tsx +31 -6
  4. package/src/components/atoms/alert.tsx +72 -18
  5. package/src/components/atoms/avatar.tsx +12 -4
  6. package/src/components/atoms/badge.tsx +7 -2
  7. package/src/components/atoms/breadcrumb.tsx +493 -4
  8. package/src/components/atoms/button-group.tsx +30 -6
  9. package/src/components/atoms/button.tsx +128 -18
  10. package/src/components/atoms/calendar.tsx +6 -6
  11. package/src/components/atoms/card.tsx +130 -16
  12. package/src/components/atoms/carousel.tsx +16 -9
  13. package/src/components/atoms/chart.tsx +87 -1
  14. package/src/components/atoms/checkbox.tsx +85 -7
  15. package/src/components/atoms/collapsible.tsx +2 -1
  16. package/src/components/atoms/combobox.tsx +358 -29
  17. package/src/components/atoms/command.tsx +336 -13
  18. package/src/components/atoms/context-menu.tsx +28 -23
  19. package/src/components/atoms/dialog.tsx +173 -29
  20. package/src/components/atoms/direction.tsx +23 -2
  21. package/src/components/atoms/drawer.tsx +15 -10
  22. package/src/components/atoms/dropdown-menu.tsx +43 -28
  23. package/src/components/atoms/empty.tsx +5 -1
  24. package/src/components/atoms/field.tsx +41 -15
  25. package/src/components/atoms/hover-card.tsx +61 -8
  26. package/src/components/atoms/input-group.tsx +19 -11
  27. package/src/components/atoms/input-otp.tsx +6 -6
  28. package/src/components/atoms/input.tsx +7 -1
  29. package/src/components/atoms/item.tsx +3 -3
  30. package/src/components/atoms/kbd.tsx +32 -3
  31. package/src/components/atoms/label-swap.tsx +113 -0
  32. package/src/components/atoms/label.tsx +1 -1
  33. package/src/components/atoms/menubar.tsx +28 -26
  34. package/src/components/atoms/native-select.tsx +3 -2
  35. package/src/components/atoms/navigation-menu.tsx +13 -8
  36. package/src/components/atoms/pagination.tsx +2 -2
  37. package/src/components/atoms/popover.tsx +29 -6
  38. package/src/components/atoms/progress.tsx +46 -33
  39. package/src/components/atoms/radio-group.tsx +9 -4
  40. package/src/components/atoms/resizable.tsx +1 -1
  41. package/src/components/atoms/scroll-area.tsx +2 -2
  42. package/src/components/atoms/select.tsx +258 -19
  43. package/src/components/atoms/sheet.tsx +76 -23
  44. package/src/components/atoms/sidebar.tsx +405 -23
  45. package/src/components/atoms/skeleton.tsx +1 -1
  46. package/src/components/atoms/slider.tsx +1 -1
  47. package/src/components/atoms/sonner.tsx +128 -38
  48. package/src/components/atoms/spinner.tsx +1 -1
  49. package/src/components/atoms/switch.tsx +10 -5
  50. package/src/components/atoms/table.tsx +147 -7
  51. package/src/components/atoms/tabs.tsx +3 -3
  52. package/src/components/atoms/textarea.tsx +3 -1
  53. package/src/components/atoms/toggle-group.tsx +4 -2
  54. package/src/components/atoms/toggle.tsx +28 -6
  55. package/src/components/atoms/tooltip.tsx +85 -15
  56. package/src/components/molecules/anonymized-token.tsx +24 -8
  57. package/src/components/molecules/app-shell.tsx +53 -20
  58. package/src/components/molecules/arrow-link.tsx +40 -0
  59. package/src/components/molecules/chip.tsx +43 -4
  60. package/src/components/molecules/code-block.tsx +54 -31
  61. package/src/components/molecules/collapsible-section.tsx +129 -0
  62. package/src/components/molecules/confirm-dialog.tsx +122 -9
  63. package/src/components/molecules/copyable-text.tsx +75 -11
  64. package/src/components/molecules/count-badge.tsx +115 -0
  65. package/src/components/molecules/data-table/data-table-bulk-actions.tsx +32 -4
  66. package/src/components/molecules/data-table/data-table-column-header.tsx +20 -3
  67. package/src/components/molecules/data-table/data-table-filters.tsx +62 -22
  68. package/src/components/molecules/data-table/data-table-helpers.tsx +88 -1
  69. package/src/components/molecules/data-table/data-table-selection-storage.tsx +115 -0
  70. package/src/components/molecules/data-table/data-table-types.tsx +160 -4
  71. package/src/components/molecules/data-table/data-table-view-options.tsx +2 -2
  72. package/src/components/molecules/data-table/data-table.tsx +869 -81
  73. package/src/components/molecules/data-table/table-pagination.tsx +2 -2
  74. package/src/components/molecules/date-picker.tsx +13 -7
  75. package/src/components/molecules/date-range-picker.tsx +13 -6
  76. package/src/components/molecules/date-time-picker.tsx +13 -7
  77. package/src/components/molecules/date-time.tsx +8 -1
  78. package/src/components/molecules/direction-link.tsx +130 -0
  79. package/src/components/molecules/elapsed-time.tsx +223 -0
  80. package/src/components/molecules/file-dropzone.tsx +2 -2
  81. package/src/components/molecules/id-chip.tsx +169 -32
  82. package/src/components/molecules/inline-code.tsx +4 -0
  83. package/src/components/molecules/issued-secret.tsx +318 -0
  84. package/src/components/molecules/list-row.tsx +349 -0
  85. package/src/components/molecules/live-indicator.tsx +83 -0
  86. package/src/components/molecules/page-header.tsx +117 -5
  87. package/src/components/molecules/password-input.tsx +2 -2
  88. package/src/components/molecules/relative-time.tsx +85 -56
  89. package/src/components/molecules/search-trigger.tsx +111 -0
  90. package/src/components/molecules/secret-value.tsx +29 -9
  91. package/src/components/molecules/skip-link.tsx +1 -1
  92. package/src/components/molecules/stat-card.tsx +4 -4
  93. package/src/components/molecules/state-views/empty-state.tsx +35 -17
  94. package/src/components/molecules/state-views/error-state.tsx +32 -14
  95. package/src/components/molecules/status-badge.tsx +415 -49
  96. package/src/components/molecules/time-tooltip.tsx +140 -0
  97. package/src/components/molecules/timeline.tsx +246 -0
  98. package/src/components/molecules/visibility-icon.tsx +89 -0
  99. package/src/hooks/use-active-label-size.ts +66 -0
  100. package/src/hooks/use-apple-platform.ts +26 -0
  101. package/src/hooks/use-pinned-height.ts +55 -0
  102. package/src/hooks/use-scrolled.ts +27 -0
  103. package/src/lib/content-inset.ts +17 -0
  104. package/src/lib/control-name.ts +55 -0
  105. package/src/lib/dialog-padding.ts +48 -0
  106. package/src/lib/field-surface.ts +31 -0
  107. package/src/lib/format-elapsed.ts +67 -0
  108. package/src/lib/format-relative.ts +29 -1
  109. package/src/lib/highlight.ts +3 -3
  110. package/src/lib/menu-item.tsx +72 -0
  111. package/src/lib/outline-edge.ts +21 -0
  112. package/src/lib/popup-align.ts +67 -0
  113. package/src/lib/popup-direction.ts +22 -0
  114. package/src/lib/popup-motion.ts +19 -0
  115. package/src/lib/state-dictionary.ts +42 -6
  116. package/src/lib/syntax-colors.ts +8 -0
  117. package/src/lib/tint-recipes.ts +68 -0
  118. package/src/lib/tone-icons.ts +24 -0
  119. package/src/lib/trigger-slot.ts +16 -0
  120. package/src/lib/utils.ts +97 -1
@@ -0,0 +1,129 @@
1
+ 'use client';
2
+
3
+ import { Card, CardCount, type CardCountTone } from '@vendure-io/ui/components/atoms/card';
4
+ import {
5
+ Collapsible,
6
+ CollapsibleContent,
7
+ CollapsibleTrigger,
8
+ } from '@vendure-io/ui/components/atoms/collapsible';
9
+ import { cn } from '@vendure-io/ui/lib/utils';
10
+ import { ChevronDown } from 'lucide-react';
11
+ import type { ComponentProps, ReactNode } from 'react';
12
+
13
+ // The count says how many rows the section holds, open and closed. It is a
14
+ // CardCount, the same count as beside a card title. `detail` adds a short
15
+ // fact after it ("2 · 1 failed"). The tone goes to the CardCount of the
16
+ // detail when there is one, and to the whole count otherwise: the number stays
17
+ // muted beside a toned fact, and the section itself stays neutral (accent
18
+ // rationing).
19
+
20
+ type CollapsibleSectionProps = Omit<
21
+ ComponentProps<typeof Collapsible>,
22
+ 'title' | 'render' | 'className' | 'children'
23
+ > & {
24
+ /** The section title. Also the name of the toggle button. */
25
+ title: ReactNode;
26
+ /** How many rows the section holds, beside the title. */
27
+ count?: number | string;
28
+ /** A short fact after the count, such as "1 failed". Renders as "{count} · {detail}". */
29
+ detail?: string;
30
+ /**
31
+ * Colours the detail, or the whole count when there is no detail. `warning`:
32
+ * rows wait on the user. `critical`: rows have failed. Default `neutral`.
33
+ */
34
+ tone?: CardCountTone;
35
+ /** Heading level of the title in the page outline. Default `2`. */
36
+ headingLevel?: 2 | 3 | 4 | 5 | 6;
37
+ className?: string;
38
+ /** The rows. Usually ListRow elements. */
39
+ children?: ReactNode;
40
+ };
41
+
42
+ /**
43
+ * A card-surface section whose header opens and closes its rows. The header
44
+ * is one full-width button, filled on hover like a row: title, count, and a
45
+ * down chevron that turns over when open. A disabled section shows no hover.
46
+ */
47
+ function CollapsibleSection({
48
+ title,
49
+ count,
50
+ detail,
51
+ tone = 'neutral',
52
+ headingLevel = 2,
53
+ className,
54
+ children,
55
+ ...props
56
+ }: CollapsibleSectionProps) {
57
+ const Heading = `h${headingLevel}` as const;
58
+
59
+ return (
60
+ <Collapsible
61
+ data-slot="collapsible-section"
62
+ render={<Card />}
63
+ className={cn('gap-0 py-0', className)}
64
+ {...props}
65
+ >
66
+ <Heading data-slot="collapsible-section-heading" className="m-0">
67
+ <CollapsibleTrigger
68
+ data-slot="collapsible-section-trigger"
69
+ className="group/collapsible-section-trigger flex min-h-12 w-full cursor-pointer items-center gap-2 ps-4.5 pe-4 text-start outline-none transition-colors duration-fast ease-default not-data-disabled:hover:bg-muted data-disabled:cursor-default focus-visible:outline-solid focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
70
+ >
71
+ {/* The title is quieter than the rows it labels. */}
72
+ <span
73
+ data-slot="collapsible-section-title"
74
+ className="min-w-0 text-sm font-semibold text-foreground-secondary"
75
+ >
76
+ {title}
77
+ </span>
78
+ {count != null ? (
79
+ <CardCount
80
+ data-slot="collapsible-section-count"
81
+ tone={detail ? 'neutral' : tone}
82
+ className="ms-0 inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap"
83
+ >
84
+ {count}
85
+ {detail ? (
86
+ <>
87
+ <span aria-hidden="true">·</span>
88
+ <span className="sr-only">, </span>
89
+ <CardCount
90
+ data-slot="collapsible-section-count-detail"
91
+ tone={tone}
92
+ className="ms-0"
93
+ >
94
+ {detail}
95
+ </CardCount>
96
+ </>
97
+ ) : null}
98
+ </CardCount>
99
+ ) : null}
100
+ {/* The chevron turns on the panel's height timing, so both settle
101
+ together; its colour and opacity follow the hover on the fill's
102
+ timing. A disabled header shows no hover. */}
103
+ <ChevronDown
104
+ aria-hidden="true"
105
+ strokeWidth={1.75}
106
+ className="ms-auto size-3.75 shrink-0 text-muted-foreground opacity-70 [transition:rotate_var(--transition-duration-slow)_var(--ease-height),color_var(--transition-duration-fast)_var(--ease-default),opacity_var(--transition-duration-fast)_var(--ease-default)] group-[:hover:not([data-disabled])]/collapsible-section-trigger:text-foreground group-[:hover:not([data-disabled])]/collapsible-section-trigger:opacity-100 group-data-panel-open/collapsible-section-trigger:rotate-180 motion-reduce:[transition:color_var(--transition-duration-fast)_var(--ease-default),opacity_var(--transition-duration-fast)_var(--ease-default)]"
107
+ />
108
+ </CollapsibleTrigger>
109
+ </Heading>
110
+ {/* Height runs on the height curve; under reduced motion it snaps and
111
+ only the rows fade. */}
112
+ <CollapsibleContent
113
+ data-slot="collapsible-section-panel"
114
+ className="group/collapsible-section-panel h-(--collapsible-panel-height) overflow-hidden border-t border-border data-ending-style:h-0 data-starting-style:h-0 motion-safe:transition-[height] motion-safe:duration-slow motion-safe:ease-height"
115
+ >
116
+ {/* Opening, the rows fade in over the second half of the height;
117
+ closing, they leave at once so the height settles on nothing. */}
118
+ <div
119
+ data-slot="collapsible-section-rows"
120
+ className="transition-opacity delay-(--transition-duration-moderate) duration-moderate ease-out group-data-ending-style/collapsible-section-panel:opacity-0 group-data-ending-style/collapsible-section-panel:delay-0 group-data-ending-style/collapsible-section-panel:duration-fast group-data-starting-style/collapsible-section-panel:opacity-0"
121
+ >
122
+ {children}
123
+ </div>
124
+ </CollapsibleContent>
125
+ </Collapsible>
126
+ );
127
+ }
128
+
129
+ export { CollapsibleSection, type CollapsibleSectionProps };
@@ -12,11 +12,53 @@ import {
12
12
  AlertDialogTrigger,
13
13
  } from '@vendure-io/ui/components/atoms/alert-dialog';
14
14
  import { Spinner } from '@vendure-io/ui/components/atoms/spinner';
15
- import { type ReactElement, type ReactNode, useId, useRef, useState } from 'react';
15
+ import { cn } from '@vendure-io/ui/lib/utils';
16
+ import {
17
+ type ComponentProps,
18
+ type ReactElement,
19
+ type ReactNode,
20
+ useId,
21
+ useRef,
22
+ useState,
23
+ } from 'react';
24
+
25
+ // The dialog's buttons show the ring on any focus, not only keyboard focus:
26
+ // the dialog moves focus itself when it opens, and after a mouse click some
27
+ // browsers do not match :focus-visible. With two buttons, the ring is how you
28
+ // see which one Enter presses.
29
+ const focusRing = 'focus:outline-solid focus:outline-2 focus:outline-offset-2 focus:outline-ring';
30
+
31
+ // The fields in `body` that can take focus when the dialog opens. Checkbox,
32
+ // Switch and Select render a span or button with the role, plus a hidden form
33
+ // input that `isTabbable` skips.
34
+ const FIELD_SELECTOR =
35
+ 'input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [contenteditable="true"], [role=checkbox], [role=switch], [role=combobox], [role=radio]';
36
+
37
+ // A field the user can reach with Tab. A hidden input (a DatePicker `name`, a
38
+ // form value) or a field inside an aria-hidden subtree would take focus
39
+ // nowhere visible, so Enter would do nothing.
40
+ function isTabbable(element: HTMLElement) {
41
+ if (element.tabIndex < 0) return false;
42
+ if (element instanceof HTMLInputElement && element.type === 'hidden') return false;
43
+ if (element.closest('[aria-hidden="true"]')) return false;
44
+ if (element.getAttribute('aria-disabled') === 'true') return false;
45
+ return element.checkVisibility?.() ?? true;
46
+ }
16
47
 
17
48
  interface ConfirmDialogProps {
18
49
  title: ReactNode;
50
+ /**
51
+ * An icon shown inline before the title, e.g. `<Trash2Icon />`. It is
52
+ * neutral, and takes the destructive tone when `variant="destructive"`.
53
+ */
54
+ icon?: ReactNode;
19
55
  description?: ReactNode;
56
+ /**
57
+ * Content between the description and the buttons. Use it for a field the
58
+ * user must fill before confirming ("type the name to confirm"), and pair it
59
+ * with `confirmDisabled` until the value matches.
60
+ */
61
+ body?: ReactNode;
20
62
  /**
21
63
  * May return a promise: the dialog then keeps itself open, disables both
22
64
  * buttons, shows a pending spinner on the action, and closes only on resolve.
@@ -25,7 +67,14 @@ interface ConfirmDialogProps {
25
67
  onConfirm: () => void | Promise<void>;
26
68
  confirmLabel?: ReactNode;
27
69
  cancelLabel?: ReactNode;
28
- variant?: 'default' | 'destructive';
70
+ /**
71
+ * `default`: Confirm is the filled primary and takes the focus.
72
+ * `caution`: a costly action that is not destructive ("Deploy anyway" after
73
+ * a failed check). Cancel takes the focus and Confirm is an outline button,
74
+ * so the dialog points one way.
75
+ * `destructive`: a loss. Cancel takes the focus and Confirm is solid red.
76
+ */
77
+ variant?: 'default' | 'caution' | 'destructive';
29
78
  /**
30
79
  * Hold the confirm button disabled while the dialog cannot be confirmed yet,
31
80
  * e.g. while the consequences it describes are still loading. Cancel stays
@@ -34,6 +83,22 @@ interface ConfirmDialogProps {
34
83
  confirmDisabled?: boolean;
35
84
  /** Why confirm is disabled, shown beside the buttons while `confirmDisabled` is set. */
36
85
  confirmDisabledReason?: ReactNode;
86
+ /**
87
+ * The element that takes focus when the dialog opens. By default the first
88
+ * field in `body` that a user can tab to takes it; hidden inputs never do.
89
+ * Without one, Confirm takes it, so Enter confirms. A
90
+ * caution or destructive dialog, or one whose Confirm is disabled, focuses
91
+ * Cancel, so Enter never starts a costly action by accident. The focused button shows its ring at
92
+ * once, also when a mouse click opened the dialog.
93
+ */
94
+ initialFocus?: ComponentProps<typeof AlertDialogContent>['initialFocus'];
95
+ /**
96
+ * The element that takes focus when the dialog closes. By default focus goes
97
+ * back to the element that opened it. Set it when that element is gone after
98
+ * a confirm, e.g. the row of a deleted item: return the next row, or the
99
+ * list's main action. Same type as Base UI's `Dialog.Popup` `finalFocus`.
100
+ */
101
+ finalFocus?: ComponentProps<typeof AlertDialogContent>['finalFocus'];
37
102
  /** Uncontrolled mode — the element that opens the dialog. */
38
103
  children?: ReactElement;
39
104
  /** Controlled mode — supply with `onOpenChange`. */
@@ -43,13 +108,17 @@ interface ConfirmDialogProps {
43
108
 
44
109
  function ConfirmDialog({
45
110
  title,
111
+ icon,
46
112
  description,
113
+ body,
47
114
  onConfirm,
48
115
  confirmLabel = 'Confirm',
49
116
  cancelLabel = 'Cancel',
50
117
  variant = 'default',
51
118
  confirmDisabled = false,
52
119
  confirmDisabledReason,
120
+ initialFocus,
121
+ finalFocus,
53
122
  children,
54
123
  open,
55
124
  onOpenChange,
@@ -62,6 +131,17 @@ function ConfirmDialog({
62
131
  const pendingRef = useRef(false);
63
132
  const actualOpen = isControlled ? open : internalOpen;
64
133
  const reasonId = useId();
134
+ const bodyRef = useRef<HTMLDivElement>(null);
135
+ const cancelRef = useRef<HTMLButtonElement>(null);
136
+ const confirmRef = useRef<HTMLButtonElement>(null);
137
+
138
+ const defaultInitialFocus = () => {
139
+ const fields = bodyRef.current?.querySelectorAll<HTMLElement>(FIELD_SELECTOR) ?? [];
140
+ const field = Array.from(fields).find(isTabbable);
141
+ if (field) return field;
142
+ if (variant !== 'default' || confirmDisabled) return cancelRef.current ?? true;
143
+ return confirmRef.current ?? true;
144
+ };
65
145
  const showReason = confirmDisabled && !pending && Boolean(confirmDisabledReason);
66
146
 
67
147
  const setOpen = (next: boolean) => {
@@ -93,33 +173,66 @@ function ConfirmDialog({
93
173
  }}
94
174
  >
95
175
  {children ? <AlertDialogTrigger render={children} /> : null}
96
- <AlertDialogContent data-slot="confirm-dialog">
176
+ <AlertDialogContent
177
+ data-slot="confirm-dialog"
178
+ initialFocus={initialFocus ?? defaultInitialFocus}
179
+ finalFocus={finalFocus}
180
+ >
97
181
  <AlertDialogHeader>
98
- <AlertDialogTitle>{title}</AlertDialogTitle>
182
+ {icon ? (
183
+ <AlertDialogTitle className="flex items-center gap-2.5">
184
+ <span
185
+ data-slot="confirm-dialog-icon"
186
+ aria-hidden="true"
187
+ className={cn(
188
+ "flex shrink-0 [&_svg:not([class*='size-'])]:size-4.5 [&_svg:not([class*='stroke-'])]:stroke-[1.75]",
189
+ variant === 'destructive' ? 'text-destructive-text' : 'text-muted-foreground',
190
+ )}
191
+ >
192
+ {icon}
193
+ </span>
194
+ <span>{title}</span>
195
+ </AlertDialogTitle>
196
+ ) : (
197
+ <AlertDialogTitle>{title}</AlertDialogTitle>
198
+ )}
99
199
  {description ? <AlertDialogDescription>{description}</AlertDialogDescription> : null}
100
200
  </AlertDialogHeader>
201
+ {body ? (
202
+ <div ref={bodyRef} data-slot="confirm-dialog-body">
203
+ {body}
204
+ </div>
205
+ ) : null}
101
206
  <AlertDialogFooter>
102
207
  {showReason ? (
103
208
  <p
104
209
  id={reasonId}
105
210
  data-slot="confirm-dialog-disabled-reason"
106
- className="text-muted-foreground self-center text-sm group-data-[size=sm]/alert-dialog-content:col-span-2 sm:mr-auto"
211
+ className="text-muted-foreground self-center text-sm group-data-[size=sm]/alert-dialog-content:col-span-2 sm:me-auto"
107
212
  >
108
213
  {confirmDisabledReason}
109
214
  </p>
110
215
  ) : null}
111
- <AlertDialogCancel disabled={pending}>{cancelLabel}</AlertDialogCancel>
216
+ <AlertDialogCancel ref={cancelRef} disabled={pending} className={focusRing}>
217
+ {cancelLabel}
218
+ </AlertDialogCancel>
112
219
  {/* AlertDialogAction is a plain Button (not a Close), so closing stays
113
220
  under our control — the promise decides when the dialog leaves. */}
221
+ {/* While pending, the spinner takes the label's place. The label stays
222
+ in the layout (and the accessible name), so the button keeps its width. */}
114
223
  <AlertDialogAction
115
- variant={variant}
224
+ variant={variant === 'caution' ? 'outline' : variant}
116
225
  disabled={pending || confirmDisabled}
117
226
  aria-busy={pending || undefined}
118
227
  aria-describedby={showReason ? reasonId : undefined}
119
228
  onClick={handleConfirm}
229
+ ref={confirmRef}
230
+ className={cn('relative', focusRing)}
120
231
  >
121
- {pending ? <Spinner /> : null}
122
- {confirmLabel}
232
+ <span data-slot="confirm-dialog-label" className={cn(pending && 'opacity-0')}>
233
+ {confirmLabel}
234
+ </span>
235
+ {pending ? <Spinner className="absolute inset-0 m-auto" /> : null}
123
236
  </AlertDialogAction>
124
237
  </AlertDialogFooter>
125
238
  </AlertDialogContent>
@@ -8,6 +8,67 @@ import { cn } from '@vendure-io/ui/lib/utils';
8
8
  import { CheckIcon, CopyIcon } from 'lucide-react';
9
9
  import type * as React from 'react';
10
10
 
11
+ interface UseCopyActionOptions {
12
+ /** How long `copied` stays true after a successful copy, in ms. @default 2000 */
13
+ timeout?: number;
14
+ /** Called after a successful copy. Falls back to `CopyFeedbackProvider`. */
15
+ onCopied?: () => void;
16
+ /** Called when the clipboard write fails. Falls back to `CopyFeedbackProvider`. */
17
+ onCopyError?: (error: Error) => void;
18
+ }
19
+
20
+ interface CopyAction {
21
+ /** True for `timeout` ms after the last successful copy. */
22
+ copied: boolean;
23
+ /** Writes `value` to the clipboard and reports the result through the callbacks. */
24
+ copy: (value: ClipboardSource) => Promise<boolean>;
25
+ }
26
+
27
+ /**
28
+ * The copy behaviour of `CopyButton` without the button: clipboard write,
29
+ * transient `copied` flag, and the callback → `CopyFeedbackProvider` fallback.
30
+ * Use it when a parent must know the copied state, for example to change a
31
+ * tooltip from "Copy" to "Copied". Pass the result to `CopyButton` as
32
+ * `copyAction` so the button and the parent share one state.
33
+ */
34
+ function useCopyAction({ timeout, onCopied, onCopyError }: UseCopyActionOptions = {}): CopyAction {
35
+ const { copied, copy } = useCopy({ timeout });
36
+ const copyFeedback = useCopyFeedback();
37
+
38
+ return {
39
+ copied,
40
+ copy: async (value) => {
41
+ const ok = await copy(value);
42
+ if (ok) (onCopied ?? copyFeedback.onCopied)?.();
43
+ else
44
+ (onCopyError ?? copyFeedback.onCopyError)?.(new Error('Failed to copy to the clipboard'));
45
+ return ok;
46
+ },
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The copy icon that turns into a check-mark while `copied` is true. The two
52
+ * icons cross-fade; with motion allowed, the outgoing icon also shrinks and
53
+ * blurs. The check uses the text-safe `success-text` slot, never a raw green.
54
+ */
55
+ function CopyStateIcon({ copied, className }: { copied: boolean; className?: string }) {
56
+ const swap =
57
+ 'col-start-1 row-start-1 transition-[opacity,scale,filter] duration-moderate ease-out';
58
+ const out = 'opacity-0 motion-safe:scale-25 motion-safe:blur-[4px]';
59
+ return (
60
+ <span
61
+ aria-hidden
62
+ data-slot="copy-state-icon"
63
+ data-copied={copied || undefined}
64
+ className={cn('grid shrink-0 place-items-center', className)}
65
+ >
66
+ <CopyIcon className={cn(swap, copied && out)} />
67
+ <CheckIcon className={cn(swap, 'text-success-text', !copied && out)} />
68
+ </span>
69
+ );
70
+ }
71
+
11
72
  interface CopyButtonProps extends Omit<React.ComponentProps<typeof Button>, 'value' | 'children'> {
12
73
  /**
13
74
  * The text written to the clipboard, or a callback that loads it when the
@@ -31,12 +92,17 @@ interface CopyButtonProps extends Omit<React.ComponentProps<typeof Button>, 'val
31
92
  copyLabel?: string;
32
93
  /** Accessible label shown while the copied state is active. @default "Copied" */
33
94
  copiedLabel?: string;
95
+ /**
96
+ * A shared copy state from `useCopyAction`. When set, the button uses it
97
+ * instead of its own, and `timeout`, `onCopied` and `onCopyError` belong on
98
+ * the hook call.
99
+ */
100
+ copyAction?: CopyAction;
34
101
  }
35
102
 
36
103
  /**
37
104
  * Ghost icon button that copies `value` and swaps its icon to a check-mark for a
38
- * short window. Colours the confirmation with the semantic `text-success` token
39
- * (never a raw green), per ADR 0003.
105
+ * short window (see `CopyStateIcon`).
40
106
  */
41
107
  function CopyButton({
42
108
  value,
@@ -49,10 +115,11 @@ function CopyButton({
49
115
  size = 'icon-xs',
50
116
  className,
51
117
  onClick,
118
+ copyAction,
52
119
  ...props
53
120
  }: CopyButtonProps) {
54
- const { copied, copy } = useCopy({ timeout });
55
- const copyFeedback = useCopyFeedback();
121
+ const ownAction = useCopyAction({ timeout, onCopied, onCopyError });
122
+ const { copied, copy } = copyAction ?? ownAction;
56
123
 
57
124
  return (
58
125
  <Button
@@ -65,14 +132,11 @@ function CopyButton({
65
132
  onClick={async (event) => {
66
133
  onClick?.(event);
67
134
  if (event.defaultPrevented) return;
68
- const ok = await copy(value);
69
- if (ok) (onCopied ?? copyFeedback.onCopied)?.();
70
- else
71
- (onCopyError ?? copyFeedback.onCopyError)?.(new Error('Failed to copy to the clipboard'));
135
+ await copy(value);
72
136
  }}
73
137
  {...props}
74
138
  >
75
- {copied ? <CheckIcon className="text-success" /> : <CopyIcon />}
139
+ <CopyStateIcon copied={copied} />
76
140
  </Button>
77
141
  );
78
142
  }
@@ -125,5 +189,5 @@ function CopyableText({
125
189
  );
126
190
  }
127
191
 
128
- export { CopyButton, CopyableText };
129
- export type { CopyButtonProps, CopyableTextProps };
192
+ export { CopyButton, CopyableText, CopyStateIcon, useCopyAction };
193
+ export type { CopyAction, CopyButtonProps, CopyableTextProps, UseCopyActionOptions };
@@ -0,0 +1,115 @@
1
+ import type { Tone } from '@vendure-io/ui/lib/state-dictionary';
2
+ import { cn } from '@vendure-io/ui/lib/utils';
3
+ import { cva } from 'class-variance-authority';
4
+ import type * as React from 'react';
5
+
6
+ type CountBadgeTone = Tone | 'brand';
7
+ type CountBadgePlacement = 'inline' | 'corner';
8
+
9
+ // A small solid count: unread notifications or alerts on an icon button, the
10
+ // number of active filters inside a button. The number is the whole content,
11
+ // so the fill is solid, not a tint: a tint at 11px does not read.
12
+ //
13
+ // `tone` takes every shared tone, so a `maxTone()` result passes in as it is,
14
+ // plus `brand`. `critical` takes the `destructive` slots and `progress` the
15
+ // `info` slots, as on StatusBadge. `neutral` is the `primary` ink (near black
16
+ // in light mode, light grey in dark mode): every hand-built count in the apps
17
+ // used it. `brand` follows accent rationing: an opt-in, not the default for
18
+ // unread items. Each pair is held to 4.5:1 by the tokens' contrast test.
19
+ //
20
+ // `corner` sits on the top end corner of an icon button, 16px high. Its start
21
+ // edge is pinned to the middle of the button, so a wider count ("99+") grows
22
+ // away from the icon, not over it, and mirrors in RTL. The button must be the
23
+ // containing block: add `relative` to it. A 2px ring in the
24
+ // page background cuts the count out of the icon under it. `inline` sits in
25
+ // the flow of a button label, 20px high, the button's gap spacing it.
26
+ const countBadgeVariants = cva(
27
+ [
28
+ 'inline-flex shrink-0 items-center justify-center rounded-full font-medium tabular-nums whitespace-nowrap',
29
+ // Forced colours drop the fill; an outline keeps the pill visible.
30
+ 'outline-1 outline-transparent -outline-offset-1',
31
+ ],
32
+ {
33
+ variants: {
34
+ tone: {
35
+ neutral: 'bg-primary text-primary-foreground',
36
+ brand: 'bg-brand text-brand-foreground',
37
+ info: 'bg-info text-info-foreground',
38
+ success: 'bg-success text-success-foreground',
39
+ warning: 'bg-warning text-warning-foreground',
40
+ critical: 'bg-destructive text-destructive-foreground',
41
+ progress: 'bg-info text-info-foreground',
42
+ } satisfies Record<CountBadgeTone, string>,
43
+ placement: {
44
+ inline: 'h-5 min-w-5 px-1.5 text-xs/none',
45
+ corner:
46
+ 'pointer-events-none absolute start-1/2 -top-1 h-4 min-w-4 px-1 text-2xs/none ring-2 ring-background',
47
+ } satisfies Record<CountBadgePlacement, string>,
48
+ },
49
+ defaultVariants: {
50
+ tone: 'neutral',
51
+ placement: 'inline',
52
+ },
53
+ },
54
+ );
55
+
56
+ /** The visible text: the count, or `${max}+` above the cap. */
57
+ function formatCount(count: number, max: number) {
58
+ return count > max ? `${max}+` : String(count);
59
+ }
60
+
61
+ interface CountBadgeProps extends Omit<React.ComponentProps<'span'>, 'children'> {
62
+ /** The number to show. Nothing renders at 0, below 0 or for a non-finite value. */
63
+ count: number;
64
+ /** The highest number shown as is. Above it the badge reads "99+". Default 99. */
65
+ max?: number;
66
+ tone?: CountBadgeTone;
67
+ placement?: CountBadgePlacement;
68
+ /**
69
+ * What the count means to a screen reader, with the real number: "3 unread",
70
+ * "120 unread". The visible number is then hidden from it. The design system
71
+ * does not know the noun, so the caller writes (and translates) it. Leave it
72
+ * out where the text around the count already names it ("Active filters").
73
+ * An `aria-label` on the button replaces its content: put the count in that
74
+ * label instead.
75
+ */
76
+ label?: string;
77
+ }
78
+
79
+ function CountBadge({
80
+ count,
81
+ max = 99,
82
+ tone = 'neutral',
83
+ placement = 'inline',
84
+ label,
85
+ className,
86
+ ...props
87
+ }: CountBadgeProps) {
88
+ if (!Number.isFinite(count) || count <= 0) {
89
+ return null;
90
+ }
91
+
92
+ const text = formatCount(Math.floor(count), max);
93
+
94
+ return (
95
+ <span
96
+ data-slot="count-badge"
97
+ data-tone={tone}
98
+ data-placement={placement}
99
+ className={cn(countBadgeVariants({ tone, placement }), className)}
100
+ {...props}
101
+ >
102
+ {label ? (
103
+ <>
104
+ <span aria-hidden="true">{text}</span>
105
+ <span className="sr-only">{label}</span>
106
+ </>
107
+ ) : (
108
+ text
109
+ )}
110
+ </span>
111
+ );
112
+ }
113
+
114
+ export { CountBadge, countBadgeVariants, formatCount };
115
+ export type { CountBadgePlacement, CountBadgeProps, CountBadgeTone };
@@ -14,6 +14,27 @@ import { getSelectedOriginals, getSelectedRowIds } from './data-table-helpers.ts
14
14
  // `row.original` by id as pages are seen, letting `bulkActions` receive every
15
15
  // selected original — not just the ones still on screen.
16
16
 
17
+ /**
18
+ * Keep the latest border-box height of an element. DataTable no longer uses
19
+ * it (the bulk bar shares the controls row's grid cell); it stays exported
20
+ * for consumers. Example: hold a bulk bar at the height of the row it
21
+ * replaces, so the table below does not move. A
22
+ * ResizeObserver follows the row while it shows (it can wrap on a narrow
23
+ * card); the last height stays once the row has left.
24
+ */
25
+ function useHeldHeight(): [React.RefCallback<HTMLElement>, number | undefined] {
26
+ const [height, setHeight] = React.useState<number>();
27
+ const ref = React.useCallback((node: HTMLElement | null) => {
28
+ if (!node) return;
29
+ setHeight(node.offsetHeight);
30
+ if (typeof ResizeObserver === 'undefined') return;
31
+ const observer = new ResizeObserver(() => setHeight(node.offsetHeight));
32
+ observer.observe(node);
33
+ return () => observer.disconnect();
34
+ }, []);
35
+ return [ref, height];
36
+ }
37
+
17
38
  /**
18
39
  * Accumulate `row.original` keyed by row id across page changes. Populated during
19
40
  * render (idempotent map writes) so the current render's `bulkActions` can
@@ -44,17 +65,24 @@ function DataTableBulkActions<TData>({
44
65
  const selectedRowIds = getSelectedRowIds(selection);
45
66
  if (selectedRowIds.length === 0) return null;
46
67
 
68
+ const loaded = getSelectedOriginals(selection, cache);
47
69
  const ctx: DataTableBulkActionContext<TData> = {
48
- selection: getSelectedOriginals(selection, cache),
70
+ selection: loaded,
49
71
  selectedRowIds,
72
+ selectedCount: selectedRowIds.length,
73
+ // The cache holds a row once the table has shown it, so an id it lacks is on
74
+ // a page not seen yet, still loading, or no longer exists.
75
+ missingRowIds:
76
+ loaded.length === selectedRowIds.length ? [] : selectedRowIds.filter((id) => !cache.has(id)),
50
77
  table,
51
78
  clearSelection: () => table.resetRowSelection(),
52
79
  };
53
80
 
54
81
  return (
55
82
  // A plain band row, not a box: it takes the controls row's place inside
56
- // the header band, so it carries no chrome of its own. min-h-9 matches
57
- // the controls row's h-9 inputs so the swap holds the band height steady.
83
+ // the header band, so it carries no chrome of its own. min-h-9 is the
84
+ // height of a bar on its own; DataTable sets min-h-0 and takes the height
85
+ // of the row the bar covers (the controls row or the column header row).
58
86
  <div
59
87
  data-slot="data-table-bulk-actions"
60
88
  className={cn('flex min-h-9 flex-wrap items-center gap-2', className)}
@@ -65,4 +93,4 @@ function DataTableBulkActions<TData>({
65
93
  );
66
94
  }
67
95
 
68
- export { DataTableBulkActions, useSelectionCache };
96
+ export { DataTableBulkActions, useHeldHeight, useSelectionCache };