@enablo/swirlcn-ui 0.0.0-stage → 0.5.0

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 (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -2
  3. package/dist/chunk-3DJWDNQL.js +77 -0
  4. package/dist/chunk-7XUCETA6.js +447 -0
  5. package/dist/chunk-KZESIYUN.js +18 -0
  6. package/dist/flip.d.ts +98 -0
  7. package/dist/flip.js +158 -0
  8. package/dist/fonts/Inter-italic.var.woff2 +0 -0
  9. package/dist/fonts/Inter.var.woff2 +0 -0
  10. package/dist/fonts/OFL.txt +96 -0
  11. package/dist/index.d.ts +2459 -0
  12. package/dist/index.js +8439 -0
  13. package/dist/server.d.ts +144 -0
  14. package/dist/server.js +88 -0
  15. package/dist/spacing-BQaEPbUv.d.ts +59 -0
  16. package/dist/theme.css +146 -0
  17. package/package.json +84 -3
  18. package/src/components/accordion.tsx +102 -0
  19. package/src/components/action-list.tsx +294 -0
  20. package/src/components/alert-dialog.tsx +155 -0
  21. package/src/components/autocomplete.tsx +313 -0
  22. package/src/components/avatar.tsx +258 -0
  23. package/src/components/badge.tsx +100 -0
  24. package/src/components/banner.tsx +112 -0
  25. package/src/components/button-group.tsx +87 -0
  26. package/src/components/button.tsx +362 -0
  27. package/src/components/card.tsx +186 -0
  28. package/src/components/carousel.tsx +245 -0
  29. package/src/components/checkbox.tsx +125 -0
  30. package/src/components/chip.tsx +153 -0
  31. package/src/components/color-input.tsx +98 -0
  32. package/src/components/data-cell.tsx +230 -0
  33. package/src/components/date-input.tsx +223 -0
  34. package/src/components/date-picker.tsx +276 -0
  35. package/src/components/description-list.tsx +97 -0
  36. package/src/components/dialog.tsx +405 -0
  37. package/src/components/empty-state.tsx +63 -0
  38. package/src/components/file-chip.tsx +206 -0
  39. package/src/components/file-uploader.tsx +148 -0
  40. package/src/components/flip-app-header.tsx +104 -0
  41. package/src/components/flip-brand.tsx +77 -0
  42. package/src/components/flip-theme.tsx +95 -0
  43. package/src/components/form-control.tsx +397 -0
  44. package/src/components/form-group.tsx +26 -0
  45. package/src/components/heading.tsx +70 -0
  46. package/src/components/icon.tsx +119 -0
  47. package/src/components/image-grid.tsx +285 -0
  48. package/src/components/inline-notification.tsx +167 -0
  49. package/src/components/inline-status.tsx +100 -0
  50. package/src/components/input.tsx +390 -0
  51. package/src/components/label.tsx +28 -0
  52. package/src/components/lightbox.tsx +314 -0
  53. package/src/components/link.tsx +46 -0
  54. package/src/components/list.tsx +40 -0
  55. package/src/components/menu.tsx +530 -0
  56. package/src/components/option-list.tsx +582 -0
  57. package/src/components/pagination.tsx +336 -0
  58. package/src/components/popover.tsx +194 -0
  59. package/src/components/progress.tsx +158 -0
  60. package/src/components/radio-group.tsx +136 -0
  61. package/src/components/resource-list.tsx +686 -0
  62. package/src/components/search.tsx +127 -0
  63. package/src/components/select.tsx +456 -0
  64. package/src/components/separator.tsx +93 -0
  65. package/src/components/skeleton-box.tsx +63 -0
  66. package/src/components/skeleton-text.tsx +66 -0
  67. package/src/components/spinner.tsx +83 -0
  68. package/src/components/stack.tsx +86 -0
  69. package/src/components/status-indicator.tsx +31 -0
  70. package/src/components/switch.tsx +90 -0
  71. package/src/components/table.tsx +242 -0
  72. package/src/components/tabs.tsx +147 -0
  73. package/src/components/tag.tsx +169 -0
  74. package/src/components/text.tsx +126 -0
  75. package/src/components/textarea.tsx +130 -0
  76. package/src/components/theme-provider.tsx +115 -0
  77. package/src/components/thumbnail.tsx +250 -0
  78. package/src/components/time-input.tsx +123 -0
  79. package/src/components/toast.tsx +217 -0
  80. package/src/components/toggle-group.tsx +124 -0
  81. package/src/components/toolbar.tsx +105 -0
  82. package/src/components/tooltip.tsx +97 -0
  83. package/src/components/tree-navigation.tsx +194 -0
  84. package/src/components/tree-view.tsx +292 -0
  85. package/src/flip.ts +12 -0
  86. package/src/index.ts +317 -0
  87. package/src/lib/date-mask.ts +176 -0
  88. package/src/lib/field-context.ts +86 -0
  89. package/src/lib/flip-app-script.ts +38 -0
  90. package/src/lib/flip-host.ts +84 -0
  91. package/src/lib/flip-theme-css.ts +90 -0
  92. package/src/lib/focus.ts +18 -0
  93. package/src/lib/glyphs.ts +137 -0
  94. package/src/lib/spacing.ts +93 -0
  95. package/src/lib/theme-context.ts +27 -0
  96. package/src/lib/theme-script.ts +49 -0
  97. package/src/lib/use-mobile.ts +17 -0
  98. package/src/lib/utils.ts +28 -0
  99. package/src/server.ts +20 -0
  100. package/src/styles/fonts/Inter-italic.var.woff2 +0 -0
  101. package/src/styles/fonts/Inter.var.woff2 +0 -0
  102. package/src/styles/fonts/OFL.txt +96 -0
  103. package/src/styles/theme.css +146 -0
@@ -0,0 +1,250 @@
1
+ import * as React from "react";
2
+ import { cn } from "../lib/utils";
3
+ import { Glyph } from "../lib/glyphs";
4
+ import { ActionList, ActionListItem } from "./action-list";
5
+ import { Button } from "./button";
6
+ import { ButtonGroup } from "./button-group";
7
+ import { Popover, PopoverContent, PopoverTrigger } from "./popover";
8
+ import { Progress } from "./progress";
9
+
10
+ const HOVER = "(hover: hover)";
11
+ const subscribeHover = (onChange: () => void) => {
12
+ const query = window.matchMedia(HOVER);
13
+ query.addEventListener("change", onChange);
14
+ return () => query.removeEventListener("change", onChange);
15
+ };
16
+
17
+ /** Whether the device can hover. Assumed true on the server, as Swirl does. */
18
+ function useCanHover() {
19
+ return React.useSyncExternalStore(
20
+ subscribeHover,
21
+ () => window.matchMedia(HOVER).matches,
22
+ () => true,
23
+ );
24
+ }
25
+
26
+ const sizes = {
27
+ s: { box: "[--thumbnail-size:2.5rem] [--thumbnail-button:1.5rem]", compact: true },
28
+ m: { box: "[--thumbnail-size:3rem] [--thumbnail-button:1.5rem]", compact: true },
29
+ l: { box: "[--thumbnail-size:4rem] [--thumbnail-button:1.5rem]", compact: true },
30
+ xl: { box: "rounded-sm [--thumbnail-size:5.5rem] [--thumbnail-button:1.75rem]", compact: false },
31
+ "2xl": { box: "rounded-sm [--thumbnail-size:7.5rem]", compact: false },
32
+ };
33
+
34
+ const formats = {
35
+ landscape: "w-(--thumbnail-size) aspect-[4/3]",
36
+ portrait: "h-(--thumbnail-size) aspect-[3/4]",
37
+ square: "size-(--thumbnail-size)",
38
+ };
39
+
40
+ export interface ThumbnailProps extends Omit<React.ComponentProps<"span">, "onClick"> {
41
+ src: string;
42
+ alt: string;
43
+ size?: keyof typeof sizes;
44
+ format?: keyof typeof formats;
45
+ /** Makes the image a button; it calls `onClick`. */
46
+ interactive?: boolean;
47
+ onClick?: () => void;
48
+ /** Upload progress, 0 to 100. Shows a bar, or a ring on small sizes. */
49
+ progress?: number;
50
+ progressLabel?: string;
51
+ /** Show an error over the image. */
52
+ error?: boolean;
53
+ /** Text in the bottom corner, such as a video's length. Hidden at size `s`. */
54
+ timestamp?: React.ReactNode;
55
+ showEditButton?: boolean;
56
+ showRemoveButton?: boolean;
57
+ onEdit?: () => void;
58
+ onRemove?: () => void;
59
+ editButtonIcon?: React.ReactNode;
60
+ editButtonLabel?: string;
61
+ removeButtonIcon?: React.ReactNode;
62
+ removeButtonLabel?: string;
63
+ openButtonIcon?: React.ReactNode;
64
+ openButtonLabel?: string;
65
+ menuButtonLabel?: string;
66
+ /** The cursor over an interactive image. */
67
+ cursor?: React.CSSProperties["cursor"];
68
+ }
69
+
70
+ /**
71
+ * Swirl's thumbnail: a small image with optional upload progress, an error,
72
+ * a timestamp, and edit and remove actions. With a mouse the actions appear
73
+ * on hover; on touch screens tapping the image opens them in a menu.
74
+ */
75
+ export function Thumbnail({
76
+ src,
77
+ alt,
78
+ size = "m",
79
+ format = "landscape",
80
+ interactive = false,
81
+ onClick,
82
+ progress,
83
+ progressLabel = "Loading progress",
84
+ error = false,
85
+ timestamp,
86
+ showEditButton = false,
87
+ showRemoveButton = false,
88
+ onEdit,
89
+ onRemove,
90
+ editButtonIcon = <Glyph name="crop" />,
91
+ editButtonLabel = "Edit",
92
+ removeButtonIcon = <Glyph name="delete" />,
93
+ removeButtonLabel = "Remove",
94
+ openButtonIcon = <Glyph name="visibility" />,
95
+ openButtonLabel = "Open",
96
+ menuButtonLabel = "More actions",
97
+ cursor = "pointer",
98
+ className,
99
+ ...props
100
+ }: ThumbnailProps) {
101
+ const canHover = useCanHover();
102
+ const [menuOpen, setMenuOpen] = React.useState(false);
103
+ const compact = sizes[size].compact;
104
+ const uploading = progress !== undefined;
105
+ const hasAction = showEditButton || showRemoveButton;
106
+ // On touch screens the image itself opens the actions.
107
+ const imageOpensMenu = !canHover && hasAction;
108
+ const compactMenu = compact && canHover && showEditButton && showRemoveButton;
109
+ const compactEdit = compact && canHover && showEditButton && !showRemoveButton;
110
+ const compactRemove = compact && canHover && showRemoveButton && !showEditButton;
111
+ const segmented = !compact && canHover && hasAction;
112
+ const showTimestamp = timestamp !== undefined && size !== "s" && !(uploading && compact);
113
+ const imageIsButton = interactive || imageOpensMenu;
114
+
115
+ const act = (fn?: () => void) => () => {
116
+ setMenuOpen(false);
117
+ fn?.();
118
+ };
119
+
120
+ const image = (
121
+ <img alt={alt} src={src} loading="lazy" className="size-full object-cover" />
122
+ );
123
+ const imageClasses = cn(
124
+ "relative size-full overflow-hidden rounded-[inherit] border-0 bg-transparent p-0",
125
+ "shadow-[inset_0_0_0_0.03125rem_rgba(0,0,0,0.1)]",
126
+ "outline-focus -outline-offset-2 focus:not-focus-visible:outline-none focus-visible:outline-2 focus-visible:outline-solid",
127
+ interactive &&
128
+ "cursor-pointer hover:after:absolute hover:after:inset-0 hover:after:bg-black/15 hover:after:content-[''] active:after:absolute active:after:inset-0 active:after:bg-black/30 active:after:content-['']",
129
+ );
130
+ const wrapper = imageIsButton ? (
131
+ <button
132
+ type="button"
133
+ className={imageClasses}
134
+ style={interactive && cursor !== "pointer" ? { cursor } : undefined}
135
+ onClick={imageOpensMenu ? undefined : () => onClick?.()}
136
+ >
137
+ {image}
138
+ </button>
139
+ ) : (
140
+ <span className={imageClasses}>{image}</span>
141
+ );
142
+
143
+ const compactButton =
144
+ "size-(--thumbnail-button) cursor-pointer rounded-bl-s border-0 p-0 inline-flex items-center justify-center text-on-image bg-[var(--s-surface-on-image-default)] outline-focus -outline-offset-2 focus:not-focus-visible:outline-none focus-visible:outline-2 focus-visible:outline-solid [&>svg]:size-5";
145
+ const revealOnHover = "opacity-0 group-hover/thumb:opacity-100 group-focus-within/thumb:opacity-100";
146
+
147
+ const menu = (
148
+ <ActionList>
149
+ {imageOpensMenu && interactive && (
150
+ <ActionListItem icon={openButtonIcon} label={openButtonLabel} onClick={act(onClick)} />
151
+ )}
152
+ {showEditButton && <ActionListItem icon={editButtonIcon} label={editButtonLabel} onClick={act(onEdit)} />}
153
+ {showRemoveButton && (
154
+ <ActionListItem icon={removeButtonIcon} intent="critical" label={removeButtonLabel} onClick={act(onRemove)} />
155
+ )}
156
+ </ActionList>
157
+ );
158
+
159
+ return (
160
+ <span
161
+ role="group"
162
+ className={cn(
163
+ "group/thumb relative inline-flex overflow-hidden rounded-s",
164
+ sizes[size].box,
165
+ formats[format],
166
+ className,
167
+ )}
168
+ {...props}
169
+ >
170
+ {imageOpensMenu || compactMenu ? (
171
+ <Popover open={menuOpen} onOpenChange={setMenuOpen}>
172
+ {imageOpensMenu && <PopoverTrigger asChild>{wrapper}</PopoverTrigger>}
173
+ {!imageOpensMenu && wrapper}
174
+ {compactMenu && (
175
+ <span className={cn("absolute top-0 right-0 z-2", revealOnHover)}>
176
+ <PopoverTrigger asChild>
177
+ <button type="button" aria-label={menuButtonLabel} className={compactButton}>
178
+ <Glyph name="moreHorizontal" />
179
+ </button>
180
+ </PopoverTrigger>
181
+ </span>
182
+ )}
183
+ <PopoverContent label={menuButtonLabel} align="end" padded={false}>
184
+ {menu}
185
+ </PopoverContent>
186
+ </Popover>
187
+ ) : (
188
+ wrapper
189
+ )}
190
+
191
+ {uploading && !error && (
192
+ <span
193
+ className={cn(
194
+ "absolute inset-x-0 bottom-0 z-1",
195
+ compact && "inset-0 flex items-center justify-center bg-[var(--s-surface-on-image-default)]",
196
+ )}
197
+ >
198
+ <Progress
199
+ label={progressLabel}
200
+ value={progress}
201
+ variant={compact ? "circle" : "bar"}
202
+ size={compact ? "s" : undefined}
203
+ />
204
+ </span>
205
+ )}
206
+
207
+ {error && (
208
+ <span className="absolute inset-0 z-1 flex items-center justify-center bg-[var(--s-surface-on-image-default)] text-critical [&>svg]:size-6">
209
+ <Glyph name="error" />
210
+ </span>
211
+ )}
212
+
213
+ {segmented && (
214
+ <ButtonGroup segmented={showEditButton && showRemoveButton} className={cn("absolute top-1 right-1 z-1", revealOnHover)}>
215
+ {showEditButton && (
216
+ <Button variant="on-image" hideLabel icon={editButtonIcon} label={editButtonLabel} onClick={onEdit} />
217
+ )}
218
+ {showRemoveButton && (
219
+ <Button variant="on-image" hideLabel icon={removeButtonIcon} label={removeButtonLabel} onClick={onRemove} />
220
+ )}
221
+ </ButtonGroup>
222
+ )}
223
+
224
+ {(compactEdit || compactRemove) && (
225
+ <span className={cn("absolute top-0 right-0 z-2", revealOnHover)}>
226
+ <button
227
+ type="button"
228
+ aria-label={compactEdit ? editButtonLabel : removeButtonLabel}
229
+ className={compactButton}
230
+ onClick={compactEdit ? onEdit : onRemove}
231
+ >
232
+ {compactEdit ? editButtonIcon : removeButtonIcon}
233
+ </button>
234
+ </span>
235
+ )}
236
+
237
+ {showTimestamp && (
238
+ <span
239
+ className={cn(
240
+ "pointer-events-none absolute bottom-0 left-0 z-1 block h-5 max-w-[calc(100%-0.5rem)] truncate rounded-s px-1",
241
+ "bg-[var(--s-surface-on-image-default)] text-sm leading-5 text-on-image",
242
+ uploading && !compact && "bottom-2",
243
+ )}
244
+ >
245
+ {timestamp}
246
+ </span>
247
+ )}
248
+ </span>
249
+ );
250
+ }
@@ -0,0 +1,123 @@
1
+ import * as React from "react";
2
+ import { format as formatDate, isValid, parse } from "date-fns";
3
+ import { cn } from "../lib/utils";
4
+ import { FieldContext, useField } from "../lib/field-context";
5
+ import { Glyph } from "../lib/glyphs";
6
+ import { isComplete, maskDate, normalizePattern } from "../lib/date-mask";
7
+ import { Input, type InputProps } from "./input";
8
+
9
+ const INTERNAL = "HH:mm:ss";
10
+
11
+ export interface TimeInputProps
12
+ extends Omit<InputProps, "value" | "defaultValue" | "onChange" | "type" | "prefix" | "suffix" | "clearable"> {
13
+ /** The time as `HH:mm:ss`, or "" for none. */
14
+ value?: string;
15
+ defaultValue?: string;
16
+ /** Called with `HH:mm:ss` once a whole time is typed, and with "" when cleared. */
17
+ onValueChange?: (value: string) => void;
18
+ /** How the time is shown and typed, as a date-fns pattern: "HH:mm", "hh:mm aa", "HH:mm:ss". Defaults to "HH:mm". */
19
+ format?: string;
20
+ /** Defaults to "hh:mm". */
21
+ placeholder?: string;
22
+ }
23
+
24
+ const display = (value: string, pattern: string) => {
25
+ if (!value) return "";
26
+ const date = parse(value, INTERNAL, new Date());
27
+ return isValid(date) ? formatDate(date, pattern) : "";
28
+ };
29
+
30
+ /**
31
+ * Swirl's time input: a masked time field with a clock icon. Put it in a
32
+ * `FormControl`. Typing fills in the colons, pads single digits and ignores
33
+ * digits out of range; with an `aa` format, "a" or "p" fills in AM or PM.
34
+ * The value is always `HH:mm:ss`, whatever the display `format`.
35
+ */
36
+ export function TimeInput({
37
+ value: valueProp,
38
+ defaultValue,
39
+ onValueChange,
40
+ format = "HH:mm",
41
+ placeholder = "hh:mm",
42
+ id,
43
+ className,
44
+ ...props
45
+ }: TimeInputProps) {
46
+ const field = useField();
47
+ const pattern = normalizePattern(format);
48
+
49
+ const [uncontrolled, setUncontrolled] = React.useState(defaultValue ?? "");
50
+ const value = valueProp ?? uncontrolled;
51
+ const [text, setText] = React.useState(() => display(value, pattern));
52
+ // Follow a new value from outside; React's "adjust state on prop change" pattern.
53
+ const [shown, setShown] = React.useState(value);
54
+ if (value !== shown) {
55
+ setShown(value);
56
+ setText(display(value, pattern));
57
+ }
58
+
59
+ const commit = (next: string) => {
60
+ setShown(next);
61
+ if (valueProp === undefined) setUncontrolled(next);
62
+ if (next !== value) onValueChange?.(next);
63
+ };
64
+
65
+ const onTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
66
+ const raw = event.target.value;
67
+ const masked = maskDate(raw, pattern, { eager: raw.length > text.length });
68
+ setText(masked);
69
+ if (masked === "") commit("");
70
+ else if (isComplete(masked, pattern)) {
71
+ const time = parse(masked, pattern, new Date());
72
+ if (isValid(time)) commit(formatDate(time, INTERNAL));
73
+ }
74
+ };
75
+
76
+ const compact = field ? field.inline || field.labelPosition === "outside" : true;
77
+ const collapsed = Boolean(field && !compact && field.labelAsPlaceholder);
78
+ // As with DateInput, Swirl's label still sits in the empty box despite the placeholder.
79
+ const innerField = React.useMemo(
80
+ () => (field ? { ...field, setHasPlaceholder: () => {} } : null),
81
+ [field],
82
+ );
83
+
84
+ const icon = (
85
+ <span
86
+ aria-hidden
87
+ className={cn(
88
+ "pointer-events-none inline-flex size-6 text-icon-default desktop:size-5 [&>svg]:size-full",
89
+ field &&
90
+ cn(
91
+ "absolute right-0",
92
+ compact ? "-top-px desktop:top-0" : "-top-3 desktop:-top-2.5",
93
+ collapsed && "invisible",
94
+ ),
95
+ )}
96
+ >
97
+ <Glyph name="time" />
98
+ </span>
99
+ );
100
+
101
+ const input = (
102
+ <Input
103
+ {...props}
104
+ id={id}
105
+ type="text"
106
+ inputMode="numeric"
107
+ autoComplete="off"
108
+ value={text}
109
+ onChange={onTextChange}
110
+ placeholder={placeholder}
111
+ suffix={field ? undefined : icon}
112
+ // Unlike a text input, Swirl greys this one out fully when disabled.
113
+ className={cn(field && "w-[calc(100%-1.75rem)] disabled:text-disabled", className)}
114
+ />
115
+ );
116
+
117
+ return (
118
+ <div className="relative flex w-full items-center">
119
+ {innerField ? <FieldContext.Provider value={innerField}>{input}</FieldContext.Provider> : input}
120
+ {field && icon}
121
+ </div>
122
+ );
123
+ }
@@ -0,0 +1,217 @@
1
+ import * as React from "react";
2
+ import { Toast as ToastPrimitive } from "radix-ui";
3
+ import { cva, type VariantProps } from "class-variance-authority";
4
+ import { cn } from "../lib/utils";
5
+ import { Button } from "./button";
6
+
7
+ const toastVariants = cva(
8
+ [
9
+ // Swirl's toast: a 16px-padded panel up to 28rem wide, sized to its text.
10
+ "group pointer-events-auto relative flex w-auto max-w-[28rem] items-start overflow-hidden",
11
+ "rounded-sm p-4 leading-6 shadow-level-2 desktop:text-sm desktop:leading-5",
12
+ "data-[state=open]:animate-in data-[state=open]:slide-in-from-bottom-4 data-[state=open]:fade-in-0",
13
+ "data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
14
+ // Radix drives these while the toast is being swiped away.
15
+ "data-[swipe=move]:translate-x-(--radix-toast-swipe-move-x) data-[swipe=move]:transition-none",
16
+ "data-[swipe=cancel]:translate-x-0",
17
+ "data-[swipe=end]:animate-out data-[swipe=end]:slide-out-to-right-full",
18
+ ],
19
+ {
20
+ variants: {
21
+ intent: {
22
+ default: "bg-surface-neutral text-on-status",
23
+ success: "bg-surface-success text-on-status",
24
+ critical: "bg-surface-critical text-on-status",
25
+ warning: "bg-surface-warning text-dark",
26
+ info: "bg-surface-info text-on-status",
27
+ },
28
+ },
29
+ defaultVariants: { intent: "default" },
30
+ },
31
+ );
32
+
33
+ export type ToastIntent = NonNullable<VariantProps<typeof toastVariants>["intent"]>;
34
+
35
+ export interface ToastOptions {
36
+ /** A bold first line. Swirl's toasts usually have only `description`. */
37
+ title?: React.ReactNode;
38
+ description?: React.ReactNode;
39
+ /** Leading icon, 24px or 20px with the desktop layout. */
40
+ icon?: React.ReactNode;
41
+ /** Swirl has `default`, `critical` and `success`; `warning` and `info` are extras. */
42
+ intent?: ToastIntent;
43
+ /** Milliseconds before auto-dismiss. `Infinity` keeps it until dismissed. */
44
+ duration?: number;
45
+ /** A single action, rendered as a plain text button inside the toast. */
46
+ action?: { label: string; onClick: () => void };
47
+ /** Put the action beside the text (`inline`) or under it (`bottom`). */
48
+ actionPosition?: "inline" | "bottom";
49
+ /** Text for the dismiss button in place of the close icon, such as "OK". */
50
+ dismissLabel?: string;
51
+ }
52
+
53
+ interface ToastRecord extends ToastOptions {
54
+ id: number;
55
+ open: boolean;
56
+ }
57
+
58
+ interface ToastContextValue {
59
+ toast: (options: ToastOptions) => number;
60
+ dismiss: (id: number) => void;
61
+ /** Dismiss every open toast. */
62
+ clearAll: () => void;
63
+ }
64
+
65
+ const ToastContext = React.createContext<ToastContextValue | null>(null);
66
+
67
+ /**
68
+ * Imperative handle for showing toasts.
69
+ *
70
+ * Throws when used outside `ToastProvider` rather than silently doing nothing,
71
+ * since a missing provider is always a wiring mistake.
72
+ */
73
+ export function useToast() {
74
+ const context = React.useContext(ToastContext);
75
+ if (!context) throw new Error("useToast must be used within a <ToastProvider>");
76
+ return context;
77
+ }
78
+
79
+ export interface ToastProviderProps {
80
+ children: React.ReactNode;
81
+ /** Default auto-dismiss delay, in milliseconds. */
82
+ duration?: number;
83
+ /** Where the stack is anchored. Swirl centres it at the bottom. */
84
+ position?: "bottom-right" | "bottom-center" | "bottom-left" | "top-right" | "top-center";
85
+ /** Accessible label for the toast region's hotkey hint. */
86
+ label?: string;
87
+ }
88
+
89
+ const positions = {
90
+ "bottom-right": "bottom-4 items-end",
91
+ "bottom-center": "bottom-4 items-center",
92
+ "bottom-left": "bottom-4 items-start",
93
+ "top-right": "top-4 items-end",
94
+ "top-center": "top-4 items-center",
95
+ } as const;
96
+
97
+ /** Wrap the app once, then call `useToast().toast(...)` from anywhere below. */
98
+ export function ToastProvider({
99
+ children,
100
+ duration = 5000,
101
+ position = "bottom-center",
102
+ label = "Notifications",
103
+ }: ToastProviderProps) {
104
+ const [toasts, setToasts] = React.useState<ToastRecord[]>([]);
105
+ const nextId = React.useRef(0);
106
+
107
+ const dismiss = React.useCallback((id: number) => {
108
+ setToasts((current) => current.map((t) => (t.id === id ? { ...t, open: false } : t)));
109
+ }, []);
110
+
111
+ const toast = React.useCallback((options: ToastOptions) => {
112
+ const id = nextId.current++;
113
+ setToasts((current) => [...current, { ...options, id, open: true }]);
114
+ return id;
115
+ }, []);
116
+
117
+ // Drop closed toasts only once Radix has finished animating them out.
118
+ const remove = React.useCallback((id: number) => {
119
+ setToasts((current) => current.filter((t) => t.id !== id));
120
+ }, []);
121
+
122
+ const clearAll = React.useCallback(() => {
123
+ setToasts((current) => current.map((t) => ({ ...t, open: false })));
124
+ }, []);
125
+
126
+ const value = React.useMemo(() => ({ toast, dismiss, clearAll }), [toast, dismiss, clearAll]);
127
+
128
+ return (
129
+ <ToastContext.Provider value={value}>
130
+ <ToastPrimitive.Provider duration={duration} label={label} swipeDirection="right">
131
+ {children}
132
+
133
+ {toasts.map((item) => (
134
+ <ToastPrimitive.Root
135
+ key={item.id}
136
+ open={item.open}
137
+ duration={item.duration === Infinity ? Number.MAX_SAFE_INTEGER : item.duration}
138
+ onOpenChange={(open) => {
139
+ if (!open) dismiss(item.id);
140
+ }}
141
+ // `forceMount` is off, so unmount is safe once the exit animation ends.
142
+ onAnimationEnd={() => {
143
+ if (!item.open) remove(item.id);
144
+ }}
145
+ className={cn(toastVariants({ intent: item.intent }))}
146
+ >
147
+ {item.icon && (
148
+ <span className="mr-2.5 inline-flex size-6 shrink-0 desktop:size-5 [&>svg]:size-full">
149
+ {item.icon}
150
+ </span>
151
+ )}
152
+
153
+ <div
154
+ className={cn(
155
+ "flex min-w-0 grow",
156
+ item.actionPosition === "bottom" && "flex-col",
157
+ )}
158
+ >
159
+ <div className="flex grow basis-[min-content] flex-col self-start text-left">
160
+ {item.title && (
161
+ <ToastPrimitive.Title className="font-semibold">{item.title}</ToastPrimitive.Title>
162
+ )}
163
+ {item.description && (
164
+ <ToastPrimitive.Description>{item.description}</ToastPrimitive.Description>
165
+ )}
166
+ </div>
167
+
168
+ {item.action && (
169
+ <ToastPrimitive.Action altText={item.action.label} asChild>
170
+ <Button
171
+ variant="plain"
172
+ label={item.action.label}
173
+ onClick={item.action.onClick}
174
+ className={cn(
175
+ "min-w-0 shrink text-current hover:text-current active:text-current",
176
+ item.actionPosition === "bottom"
177
+ ? "mt-2 self-start"
178
+ : "ml-4 desktop:-mt-px",
179
+ )}
180
+ />
181
+ </ToastPrimitive.Action>
182
+ )}
183
+ </div>
184
+
185
+ <ToastPrimitive.Close
186
+ aria-label={item.dismissLabel ?? "Dismiss"}
187
+ className={cn(
188
+ "ml-4 inline-flex h-6 min-w-6 shrink-0 cursor-pointer items-center justify-center border-none bg-transparent p-0",
189
+ "font-semibold text-current desktop:-mt-0.5 [&>svg]:size-6 desktop:[&>svg]:size-5",
190
+ "outline-current focus:not-focus-visible:outline-none",
191
+ )}
192
+ >
193
+ {item.dismissLabel ?? (
194
+ <svg viewBox="0 0 24 24" aria-hidden focusable={false}>
195
+ <path
196
+ d="M12 13.6L7.19999 18.4C6.98333 18.6167 6.71666 18.725 6.39999 18.725C6.08333 18.725 5.81666 18.6167 5.59999 18.4C5.38333 18.1834 5.27499 17.9167 5.27499 17.6C5.27499 17.2834 5.38333 17.0167 5.59999 16.8L10.4 12L5.59999 7.20002C5.38333 6.98336 5.27499 6.71669 5.27499 6.40002C5.27499 6.08336 5.38333 5.81669 5.59999 5.60002C5.81666 5.38336 6.08333 5.27502 6.39999 5.27502C6.71666 5.27502 6.98333 5.38336 7.19999 5.60002L12 10.4L16.8 5.60002C17.0167 5.38336 17.2833 5.27502 17.6 5.27502C17.9167 5.27502 18.1833 5.38336 18.4 5.60002C18.6167 5.81669 18.725 6.08336 18.725 6.40002C18.725 6.71669 18.6167 6.98336 18.4 7.20002L13.6 12L18.4 16.8C18.6167 17.0167 18.725 17.2834 18.725 17.6C18.725 17.9167 18.6167 18.1834 18.4 18.4C18.1833 18.6167 17.9167 18.725 17.6 18.725C17.2833 18.725 17.0167 18.6167 16.8 18.4L12 13.6Z"
197
+ fill="currentColor"
198
+ />
199
+ </svg>
200
+ )}
201
+ </ToastPrimitive.Close>
202
+ </ToastPrimitive.Root>
203
+ ))}
204
+
205
+ <ToastPrimitive.Viewport
206
+ className={cn(
207
+ // Swirl's stack: 12px apart, 24px in from the sides.
208
+ "pointer-events-none fixed inset-x-6 z-100 m-0 flex max-h-screen list-none flex-col gap-3 p-0",
209
+ positions[position],
210
+ )}
211
+ />
212
+ </ToastPrimitive.Provider>
213
+ </ToastContext.Provider>
214
+ );
215
+ }
216
+
217
+ export { toastVariants };