@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
@@ -1,30 +1,134 @@
1
1
  'use client';
2
2
 
3
- import { Tooltip, TooltipContent, TooltipTrigger } from '@vendure-io/ui/components/atoms/tooltip';
4
- import { CopyButton } from '@vendure-io/ui/components/molecules/copyable-text';
3
+ import {
4
+ Tooltip,
5
+ TooltipContent,
6
+ TooltipLabelSwap,
7
+ TooltipTrigger,
8
+ } from '@vendure-io/ui/components/atoms/tooltip';
9
+ import { CopyButton, useCopyAction } from '@vendure-io/ui/components/molecules/copyable-text';
10
+ import { contentInsetPull } from '@vendure-io/ui/lib/content-inset';
5
11
  import { cn } from '@vendure-io/ui/lib/utils';
12
+ import type * as React from 'react';
6
13
 
7
14
  type TruncateMode = 'middle' | 'start' | 'none';
8
15
 
9
16
  /**
10
17
  * Shared chrome for the identifier-chip family (`IdChip`, `AnonymizedToken`,
11
- * `SecretValue`): a bordered, `bg-muted`, monospace `text-xs` pill sized to its
12
- * content. Kept in one place so the chips can't drift apart — only their
13
- * *contents* differ (a plain value, a blurred reveal-on-hover secret, or a
14
- * masked secret loaded on click).
18
+ * `SecretValue`): a borderless `bg-muted`, monospace `text-xs` chip, 24px
19
+ * tall, sized to its content. Its `--content-inset` (the 8px start padding)
20
+ * lets a DataTable cell line the value up with the column header. Kept in
21
+ * one place so the chips can't drift
22
+ * apart: only their *contents* differ (a plain value, a blurred
23
+ * reveal-on-hover secret, or a masked secret loaded on click).
24
+ *
25
+ * A chip that copies as a whole (see `chipCopyButtonProps`) gets the hover
26
+ * fill and the press feedback here, keyed on that button, so a chip with
27
+ * several controls (`SecretValue`) keeps a still surface.
15
28
  */
16
29
  function chipChromeClass(copyable: boolean, className?: string): string {
17
30
  return cn(
18
- 'inline-flex w-fit items-center gap-1 rounded-md border bg-muted py-0.5 pl-1.5 font-mono text-xs',
19
- copyable ? 'pr-0.5' : 'pr-1.5',
31
+ 'relative inline-flex min-h-6 w-fit items-center gap-1.5 rounded-lg bg-muted py-0.5 ps-2 [--content-inset:calc(var(--spacing)*2)] font-mono text-xs text-foreground-secondary',
32
+ 'transition-[background-color,color,scale] duration-quick ease-soft',
33
+ contentInsetPull,
34
+ 'has-data-chip-copy:cursor-pointer has-data-chip-copy:hover:bg-accent has-data-chip-copy:hover:text-foreground motion-safe:has-data-chip-copy:active:scale-[0.97]',
35
+ // The chip is the copy target, so the focus ring goes around the chip, not the 13px button.
36
+ 'has-[[data-chip-copy]:focus-visible]:outline-2 has-[[data-chip-copy]:focus-visible]:outline-offset-2 has-[[data-chip-copy]:focus-visible]:outline-ring has-[[data-chip-copy]:focus-visible]:outline-solid',
37
+ copyable ? 'pe-1.5' : 'pe-2',
20
38
  className,
21
39
  );
22
40
  }
23
41
 
42
+ /**
43
+ * The look of an icon button inside an identifier chip: exactly the 13px
44
+ * icon, in the chip's text colour, with no fill on hover. The icon shows at
45
+ * 55%, quieter than the value beside it; a spinner (`role=status`) and the
46
+ * copied check keep full strength. The chip's 6px end padding is the visible
47
+ * inset. `IdChip`, `AnonymizedToken` and `SecretValue` all build on it, so
48
+ * their buttons cannot drift apart.
49
+ */
50
+ const chipIconButtonClass = cn(
51
+ "size-3.25 [&_svg:not([class*='size-'])]:size-3.25",
52
+ 'text-inherit hover:bg-transparent dark:hover:bg-transparent',
53
+ '[&>svg:not([role=status])]:opacity-55',
54
+ '[&_[data-slot=copy-state-icon]:not([data-copied])>svg:first-child]:opacity-55',
55
+ );
56
+
57
+ /**
58
+ * Props for a `CopyButton` that turns its whole chip into the copy target. Its
59
+ * `::after` stretches over the chip (the chip is `relative`), so a click
60
+ * anywhere on the chip copies, while the button stays the only tab stop and
61
+ * keeps its accessible name. The value text stays plain, readable text.
62
+ *
63
+ * It has the `chipIconButtonClass` look. Its focus ring moves to the chip
64
+ * (see `chipChromeClass`), and it keeps the chip's text colour on hover: the
65
+ * whole chip brightens instead.
66
+ *
67
+ * The button never scales on press (the chip does). Any `scale` other than
68
+ * `none` makes the button the containing block of its `::after`, which then
69
+ * shrinks to the 13px icon between mousedown and mouseup. A mouseup over the
70
+ * value text then lands outside the button, and the click goes to the chip
71
+ * instead of the button, so nothing is copied.
72
+ */
73
+ const chipCopyButtonProps = {
74
+ 'data-chip-copy': '',
75
+ className: cn(
76
+ chipIconButtonClass,
77
+ 'after:absolute after:inset-0 focus-visible:outline-none hover:text-inherit',
78
+ 'active:scale-none motion-reduce:active:scale-none',
79
+ ),
80
+ } as const;
81
+
82
+ /**
83
+ * Tooltip text of a whole-chip copy target: "Copy" until the copy succeeds,
84
+ * then "Copied", swapped in one motion by `TooltipLabelSwap`. Nothing else:
85
+ * the chip shows the start and end of its value, and a click copies all of it.
86
+ *
87
+ * The tooltip closes as soon as the pointer leaves the chip. In a list it can
88
+ * open below the chip and cover the chip in the next row; a tooltip that stays
89
+ * open while the pointer moves onto it would block that chip. Nothing in it
90
+ * needs the pointer.
91
+ */
92
+ function ChipCopyTooltip({
93
+ chip,
94
+ copied,
95
+ copyLabel,
96
+ copiedLabel,
97
+ }: {
98
+ chip: React.ReactElement;
99
+ copied: boolean;
100
+ copyLabel: string;
101
+ copiedLabel: string;
102
+ }) {
103
+ return (
104
+ <Tooltip disableHoverablePopup>
105
+ {/* The click that copies must not close the tooltip, or "Copied" is never seen. */}
106
+ <TooltipTrigger render={chip} closeOnClick={false} />
107
+ <TooltipContent>
108
+ <TooltipLabelSwap labels={[copyLabel, copiedLabel]} active={copied ? 1 : 0} />
109
+ </TooltipContent>
110
+ </Tooltip>
111
+ );
112
+ }
113
+
24
114
  // Middle truncation renders 13 chars (8 + ellipsis + 4), so anything at or
25
115
  // below that length would lose information without saving space — skip it.
26
116
  const TRUNCATE_THRESHOLD = 13;
27
117
 
118
+ /**
119
+ * `reveal="row"`: in a table row the chip reads as plain text, lined up with
120
+ * the column (it shifts back by its `--content-inset`, its 8px start padding). While the row
121
+ * (`group/row`) is hovered or holds keyboard focus, the fill and the copy icon
122
+ * fade in together, on one transition (150ms, ease-out). Nothing moves, so
123
+ * reduced motion keeps the fade. Without hover (touch), the chip always shows.
124
+ */
125
+ const ROW_REVEAL_CLASS = cn(
126
+ '-ms-(--content-inset) bg-transparent transition-[background-color,color,scale] duration-moderate ease-out',
127
+ 'group-hover/row:bg-muted group-has-[:focus-visible]/row:bg-muted [@media(hover:none)]:bg-muted',
128
+ '[&_[data-chip-copy]]:opacity-0 [&_[data-chip-copy]]:[transition:opacity_var(--transition-duration-moderate)_var(--ease-out)]',
129
+ 'group-hover/row:[&_[data-chip-copy]]:opacity-100 group-has-[:focus-visible]/row:[&_[data-chip-copy]]:opacity-100 [@media(hover:none)]:[&_[data-chip-copy]]:opacity-100',
130
+ );
131
+
28
132
  function truncateId(value: string, mode: TruncateMode): string {
29
133
  if (mode === 'none' || value.length <= TRUNCATE_THRESHOLD) return value;
30
134
  // Middle keeps a recognizable head + tail (proven `AnonymizedToken` pattern);
@@ -33,7 +137,7 @@ function truncateId(value: string, mode: TruncateMode): string {
33
137
  }
34
138
 
35
139
  interface IdChipProps {
36
- /** The full value: always copied in full, and shown in a tooltip when the chip shortens it. */
140
+ /** The full value: always copied in full. A chip without copy shows it in a tooltip when it shortens it. */
37
141
  value: string;
38
142
  /** Override the rendered text (e.g. a longer prefix). Bypasses `truncate`. */
39
143
  display?: string;
@@ -41,69 +145,102 @@ interface IdChipProps {
41
145
  truncate?: TruncateMode;
42
146
  /** Render the copy affordance. @default true */
43
147
  copyable?: boolean;
148
+ /**
149
+ * `'row'` shows the chip only while its table row is hovered or holds
150
+ * keyboard focus; at rest the value reads as plain text, lined up with the
151
+ * column. The row needs the `group/row` class (the `DataTable` rows have
152
+ * it). Over a stretched row link, stack the chip above the link (for
153
+ * example `z-10`). @default 'always'
154
+ */
155
+ reveal?: 'always' | 'row';
44
156
  className?: string;
45
157
  /** Called after a successful copy. Wire your toast here — the DS never toasts. Falls back to `CopyFeedbackProvider`. */
46
158
  onCopied?: () => void;
47
159
  /** Called when the clipboard write fails. Falls back to `CopyFeedbackProvider`. */
48
160
  onCopyError?: (error: Error) => void;
49
- /** Accessible label of the copy button before copying, e.g. "Copy commit SHA". @default "Copy" */
161
+ /**
162
+ * The tooltip text before copying, e.g. "Copy commit". Keep it short and
163
+ * leave the value out: the copy button's accessible name adds the shown
164
+ * text itself ("Copy commit 9f2c4e1"), so each button in a list has its own
165
+ * name. @default "Copy"
166
+ */
50
167
  copyLabel?: string;
51
- /** Accessible label of the copy button while the copied state is active. @default "Copied" */
168
+ /** The tooltip text and the copy button's accessible name while the copied state is active. @default "Copied" */
52
169
  copiedLabel?: string;
53
170
  /** How long the check-mark feedback stays visible, in ms. @default 2000 */
54
171
  timeout?: number;
55
172
  }
56
173
 
57
174
  /**
58
- * A bordered, monospace chip for IDs/tokens with a built-in copy affordance.
59
- * The rendered text is truncated for density while the full value is copied and
60
- * shown in a DS Tooltip on hover, or when the copy button has focus. The chip
61
- * adds no tab stop of its own; the copy button is its only interactive part.
175
+ * A monospace chip for IDs with a built-in copy action. The rendered text is
176
+ * truncated for density while the full value is copied. When copyable, the
177
+ * whole chip is the copy target: its tooltip says "Copy", then "Copied". The
178
+ * copy button inside is the only tab stop.
62
179
  */
63
180
  function IdChip({
64
181
  value,
65
182
  display,
66
183
  truncate = 'middle',
67
184
  copyable = true,
185
+ reveal = 'always',
68
186
  className,
69
187
  onCopied,
70
188
  onCopyError,
71
- copyLabel,
72
- copiedLabel,
189
+ copyLabel = 'Copy',
190
+ copiedLabel = 'Copied',
73
191
  timeout,
74
192
  }: IdChipProps) {
193
+ const action = useCopyAction({ timeout, onCopied, onCopyError });
75
194
  const text = display ?? truncateId(value, truncate);
195
+ const shortened = text !== value;
76
196
  const chip = (
77
- <span data-slot="id-chip" className={chipChromeClass(copyable, className)}>
78
- <span className="truncate">{text}</span>
79
- {/* 16px visual button to match the chip's density, but the ::after inset
80
- extends the hit target to 24px for the WCAG 2.2 AA minimum. */}
197
+ <span
198
+ data-slot="id-chip"
199
+ data-reveal={reveal === 'row' ? 'row' : undefined}
200
+ className={chipChromeClass(copyable, cn(reveal === 'row' && ROW_REVEAL_CLASS, className))}
201
+ >
202
+ {/* An id reads left to right in a right-to-left page too; the chip itself follows the page. */}
203
+ <span dir="ltr" className="truncate">
204
+ {text}
205
+ </span>
81
206
  {copyable ? (
82
207
  <CopyButton
83
208
  value={value}
84
- timeout={timeout}
85
- onCopied={onCopied}
86
- onCopyError={onCopyError}
87
- copyLabel={copyLabel}
209
+ copyAction={action}
210
+ copyLabel={`${copyLabel} ${text}`}
88
211
  copiedLabel={copiedLabel}
89
- className="relative size-4 after:absolute after:-inset-1"
212
+ {...chipCopyButtonProps}
90
213
  />
91
214
  ) : null}
92
215
  </span>
93
216
  );
94
217
 
218
+ if (copyable) {
219
+ // Focus on the copy button bubbles to the chip, so keyboard users get the
220
+ // tooltip too.
221
+ return (
222
+ <ChipCopyTooltip
223
+ chip={chip}
224
+ copied={action.copied}
225
+ copyLabel={copyLabel}
226
+ copiedLabel={copiedLabel}
227
+ />
228
+ );
229
+ }
230
+
95
231
  // Nothing is hidden when the chip shows the whole value.
96
- if (text === value) return chip;
232
+ if (!shortened) return chip;
97
233
 
98
- // The chip itself is the trigger, so hover anywhere on it opens the tooltip;
99
- // focus on the copy button bubbles to it for keyboard users.
234
+ // Closes when the pointer leaves the chip, like the copy tooltip.
100
235
  return (
101
- <Tooltip>
236
+ <Tooltip disableHoverablePopup>
102
237
  <TooltipTrigger render={chip} />
103
- <TooltipContent className="font-mono">{value}</TooltipContent>
238
+ <TooltipContent className="font-mono">
239
+ <span dir="ltr">{value}</span>
240
+ </TooltipContent>
104
241
  </Tooltip>
105
242
  );
106
243
  }
107
244
 
108
- export { chipChromeClass, IdChip };
245
+ export { ChipCopyTooltip, chipChromeClass, chipCopyButtonProps, chipIconButtonClass, IdChip };
109
246
  export type { IdChipProps };
@@ -9,11 +9,15 @@ import type * as React from 'react';
9
9
  *
10
10
  * Multi-line code uses `CodeBlock`. A value the user copies elsewhere uses
11
11
  * `CopyableText` or `IdChip`. A keystroke uses `Kbd`.
12
+ *
13
+ * Code reads left to right in a right-to-left page too, so a flag such as
14
+ * `--watch` keeps its dashes in front. Pass `dir` to override.
12
15
  */
13
16
  function InlineCode({ className, ...props }: React.ComponentProps<'code'>) {
14
17
  return (
15
18
  <code
16
19
  data-slot="inline-code"
20
+ dir="ltr"
17
21
  className={cn(
18
22
  'bg-code-inline border-code-inline-border text-foreground rounded border px-1 py-px font-mono',
19
23
  className,
@@ -0,0 +1,318 @@
1
+ 'use client';
2
+
3
+ import { Alert, AlertDescription, AlertTitle } from '@vendure-io/ui/components/atoms/alert';
4
+ import { Button, ButtonLabelSwap } from '@vendure-io/ui/components/atoms/button';
5
+ import { DialogFooter } from '@vendure-io/ui/components/atoms/dialog';
6
+ import { Field, FieldDescription, FieldLabel } from '@vendure-io/ui/components/atoms/field';
7
+ import { Input } from '@vendure-io/ui/components/atoms/input';
8
+ import { CopyStateIcon, useCopyAction } from '@vendure-io/ui/components/molecules/copyable-text';
9
+ import { cn } from '@vendure-io/ui/lib/utils';
10
+ import type * as React from 'react';
11
+ import { useEffect, useId, useRef, useState } from 'react';
12
+
13
+ /**
14
+ * The close guard of a dialog that holds a secret that was just issued. Before
15
+ * the first copy, a close request (Done, the ✕, Escape, the backdrop) shows a
16
+ * warning instead of closing, and only `closeAnyway` then closes. After a copy,
17
+ * a close request closes. Closing resets the guard for the next secret.
18
+ */
19
+ function useIssuedSecretGuard(onClose: () => void) {
20
+ const [copied, setCopied] = useState(false);
21
+ const [warned, setWarned] = useState(false);
22
+ const close = () => {
23
+ setCopied(false);
24
+ setWarned(false);
25
+ onClose();
26
+ };
27
+ const requestClose = () => (copied ? close() : setWarned(true));
28
+ return {
29
+ /** True once any format was copied, by a button or by hand. */
30
+ copied,
31
+ /** True after a close request before a copy, until a copy. */
32
+ warned: warned && !copied,
33
+ markCopied: () => setCopied(true),
34
+ requestClose,
35
+ closeAnyway: close,
36
+ /** For `Dialog`: a close of the dialog becomes a close request. */
37
+ onOpenChange: (open: boolean) => {
38
+ if (!open) requestClose();
39
+ },
40
+ };
41
+ }
42
+
43
+ type IssuedSecretGuard = ReturnType<typeof useIssuedSecretGuard>;
44
+
45
+ /** One way to copy the secret, for example the plain value or a command line. */
46
+ interface IssuedSecretFormat {
47
+ /** The button text. It says what the button copies. */
48
+ label: string;
49
+ /** Where the copy goes. It may show the form with a placeholder, never the secret. */
50
+ hint?: React.ReactNode;
51
+ /** The text the button copies. It contains the secret. */
52
+ value: string;
53
+ }
54
+
55
+ interface IssuedSecretOwnProps {
56
+ /** The guard from `useIssuedSecretGuard`, shared with `IssuedSecretFooter`. */
57
+ guard: IssuedSecretGuard;
58
+ /** The secret in words, for example "API key" or "password". The default texts use it. */
59
+ secretName: string;
60
+ /** The line that says what was issued, for example the key's name. */
61
+ name?: React.ReactNode;
62
+ /** Values of the issue that are not secret, for example a sign-in name. */
63
+ children?: React.ReactNode;
64
+ /** Text of the copy button when there is one value. @default `Copy ${secretName}` */
65
+ copyLabel?: string;
66
+ /** Text of a copy button just after a copy. @default "Copied" */
67
+ copiedLabel?: string;
68
+ /** The line under the buttons. @default `You can copy the ${secretName} only now.` */
69
+ notice?: React.ReactNode;
70
+ /** Label of the field that shows the value when the clipboard fails. @default secretName, capitalised */
71
+ fallbackLabel?: string;
72
+ /** @default `The clipboard is not available. Select the ${secretName} and copy it by hand.` */
73
+ fallbackDescription?: React.ReactNode;
74
+ /** Classes for that field, for example a session replay mask class. */
75
+ fallbackInputClassName?: string;
76
+ /** @default `The ${secretName} is not copied` */
77
+ warningTitle?: React.ReactNode;
78
+ /** @default "You cannot copy it after you close. Copy it now, or close without copying." */
79
+ warningDescription?: React.ReactNode;
80
+ /** Called after a copy by a button. Falls back to `CopyFeedbackProvider`. */
81
+ onCopied?: () => void;
82
+ /** Called when the clipboard write fails. Falls back to `CopyFeedbackProvider`. */
83
+ onCopyError?: (error: Error) => void;
84
+ }
85
+
86
+ type IssuedSecretProps = Omit<React.ComponentProps<'section'>, 'children'> &
87
+ IssuedSecretOwnProps &
88
+ (
89
+ | {
90
+ /** The secret. One button copies it. */
91
+ value: string;
92
+ formats?: never;
93
+ }
94
+ | {
95
+ /** One copy button per format of the secret. */
96
+ formats: IssuedSecretFormat[];
97
+ value?: never;
98
+ }
99
+ );
100
+
101
+ /**
102
+ * A secret that was just issued, such as a new API key: the user copies it
103
+ * once, and it never shows. One button copies it, or one button per format.
104
+ * The value shows only when the clipboard write fails, in a read-only field,
105
+ * selected, for a copy by hand. Before the first copy, a close request shows
106
+ * a warning (see `useIssuedSecretGuard` and `IssuedSecretFooter`).
107
+ */
108
+ function IssuedSecret({
109
+ guard,
110
+ secretName,
111
+ name,
112
+ children,
113
+ value,
114
+ formats,
115
+ copyLabel = `Copy ${secretName}`,
116
+ copiedLabel = 'Copied',
117
+ notice = `You can copy the ${secretName} only now.`,
118
+ fallbackLabel = capitalize(secretName),
119
+ fallbackDescription = `The clipboard is not available. Select the ${secretName} and copy it by hand.`,
120
+ fallbackInputClassName,
121
+ warningTitle = `The ${secretName} is not copied`,
122
+ warningDescription = 'You cannot copy it after you close. Copy it now, or close without copying.',
123
+ onCopied,
124
+ onCopyError,
125
+ className,
126
+ ...props
127
+ }: IssuedSecretProps) {
128
+ // The text of the copy the clipboard refused. It contains the secret.
129
+ const [manual, setManual] = useState<string | null>(null);
130
+ const firstButton = useRef<HTMLButtonElement>(null);
131
+ const field = useRef<HTMLInputElement>(null);
132
+ const fieldId = useId();
133
+ const buttons = formats ?? [{ label: copyLabel, value: value ?? '' }];
134
+
135
+ useEffect(() => {
136
+ firstButton.current?.focus();
137
+ }, []);
138
+
139
+ // After the warning, a second Enter on the focused button copies instead of
140
+ // reaching "Close without copying".
141
+ useEffect(() => {
142
+ if (guard.warned) firstButton.current?.focus();
143
+ }, [guard.warned]);
144
+
145
+ useEffect(() => {
146
+ if (manual === null) return;
147
+ field.current?.focus();
148
+ field.current?.select();
149
+ }, [manual]);
150
+
151
+ return (
152
+ <section
153
+ data-slot="issued-secret"
154
+ data-copied={guard.copied || undefined}
155
+ aria-label={capitalize(secretName)}
156
+ className={cn('flex flex-col gap-4', className)}
157
+ {...props}
158
+ >
159
+ {name != null || children != null ? (
160
+ <div className="flex flex-col gap-1">
161
+ {name != null ? (
162
+ <div data-slot="issued-secret-name" className="text-sm font-medium">
163
+ {name}
164
+ </div>
165
+ ) : null}
166
+ {children}
167
+ </div>
168
+ ) : null}
169
+ <div className="flex flex-col items-start gap-3">
170
+ {buttons.map((format, index) => (
171
+ <IssuedSecretCopyButton
172
+ key={format.label}
173
+ ref={index === 0 ? firstButton : undefined}
174
+ format={format}
175
+ copiedLabel={copiedLabel}
176
+ // One primary until the first copy; then Done takes it.
177
+ variant={index === 0 && !guard.copied ? 'default' : 'outline'}
178
+ onCopied={() => {
179
+ guard.markCopied();
180
+ setManual(null);
181
+ }}
182
+ onRefused={() => setManual(format.value)}
183
+ onCopiedCallback={onCopied}
184
+ onCopyError={onCopyError}
185
+ />
186
+ ))}
187
+ <p data-slot="issued-secret-notice" className="text-muted-foreground text-xs">
188
+ {notice}
189
+ </p>
190
+ </div>
191
+ {manual !== null ? (
192
+ <Field data-slot="issued-secret-fallback">
193
+ <FieldLabel htmlFor={fieldId}>{fallbackLabel}</FieldLabel>
194
+ <Input
195
+ ref={field}
196
+ id={fieldId}
197
+ readOnly
198
+ // The secret reads left to right in a right-to-left page too; the label follows the page.
199
+ dir="ltr"
200
+ value={manual}
201
+ className={cn('font-mono', fallbackInputClassName)}
202
+ onFocus={(event) => event.currentTarget.select()}
203
+ onCopy={guard.markCopied}
204
+ />
205
+ <FieldDescription>{fallbackDescription}</FieldDescription>
206
+ </Field>
207
+ ) : null}
208
+ {guard.warned ? (
209
+ <Alert data-slot="issued-secret-warning" variant="warning">
210
+ <AlertTitle>{warningTitle}</AlertTitle>
211
+ <AlertDescription>{warningDescription}</AlertDescription>
212
+ </Alert>
213
+ ) : null}
214
+ </section>
215
+ );
216
+ }
217
+
218
+ function IssuedSecretCopyButton({
219
+ format,
220
+ copiedLabel,
221
+ variant,
222
+ onCopied,
223
+ onRefused,
224
+ onCopiedCallback,
225
+ onCopyError,
226
+ ref,
227
+ }: {
228
+ format: IssuedSecretFormat;
229
+ copiedLabel: string;
230
+ variant: 'default' | 'outline';
231
+ onCopied: () => void;
232
+ onRefused: () => void;
233
+ onCopiedCallback?: () => void;
234
+ onCopyError?: (error: Error) => void;
235
+ ref?: React.Ref<HTMLButtonElement>;
236
+ }) {
237
+ const { copied, copy } = useCopyAction({ onCopied: onCopiedCallback, onCopyError });
238
+ const hintId = useId();
239
+
240
+ return (
241
+ <div className="flex flex-col items-start gap-1">
242
+ <Button
243
+ ref={ref}
244
+ type="button"
245
+ data-slot="issued-secret-copy"
246
+ variant={variant}
247
+ aria-describedby={format.hint != null ? hintId : undefined}
248
+ onClick={async () => {
249
+ if (await copy(format.value)) onCopied();
250
+ else onRefused();
251
+ }}
252
+ >
253
+ <CopyStateIcon copied={copied} />
254
+ <ButtonLabelSwap labels={[format.label, copiedLabel]} active={copied ? 1 : 0} />
255
+ </Button>
256
+ {format.hint != null ? (
257
+ <span id={hintId} className="text-muted-foreground text-xs">
258
+ {format.hint}
259
+ </span>
260
+ ) : null}
261
+ </div>
262
+ );
263
+ }
264
+
265
+ interface IssuedSecretFooterProps
266
+ extends Omit<React.ComponentProps<typeof DialogFooter>, 'children'> {
267
+ /** The guard from `useIssuedSecretGuard`, shared with `IssuedSecret`. */
268
+ guard: IssuedSecretGuard;
269
+ /** @default "Done" */
270
+ doneLabel?: string;
271
+ /** The second action after the warning. @default "Close without copying" */
272
+ closeAnywayLabel?: string;
273
+ }
274
+
275
+ /**
276
+ * The footer of an issued-secret dialog. Done closes after a copy. Before a
277
+ * copy it shows the warning, and "Close without copying" takes its place, as
278
+ * the quiet `destructive-outline` button: the copy stays the one filled button.
279
+ */
280
+ function IssuedSecretFooter({
281
+ guard,
282
+ doneLabel = 'Done',
283
+ closeAnywayLabel = 'Close without copying',
284
+ ...props
285
+ }: IssuedSecretFooterProps) {
286
+ return (
287
+ <DialogFooter data-slot="issued-secret-footer" {...props}>
288
+ {guard.warned ? (
289
+ <Button
290
+ key="close-anyway"
291
+ type="button"
292
+ data-slot="issued-secret-close-anyway"
293
+ variant="destructive-outline"
294
+ onClick={guard.closeAnyway}
295
+ >
296
+ {closeAnywayLabel}
297
+ </Button>
298
+ ) : (
299
+ <Button
300
+ key="done"
301
+ type="button"
302
+ data-slot="issued-secret-done"
303
+ variant={guard.copied ? 'default' : 'outline'}
304
+ onClick={guard.requestClose}
305
+ >
306
+ {doneLabel}
307
+ </Button>
308
+ )}
309
+ </DialogFooter>
310
+ );
311
+ }
312
+
313
+ function capitalize(text: string) {
314
+ return text.charAt(0).toUpperCase() + text.slice(1);
315
+ }
316
+
317
+ export { IssuedSecret, IssuedSecretFooter, useIssuedSecretGuard };
318
+ export type { IssuedSecretFooterProps, IssuedSecretFormat, IssuedSecretGuard, IssuedSecretProps };