@enablo/swirlcn-ui 0.0.0-stage → 0.5.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 (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,313 @@
1
+ import * as React from "react";
2
+ import { Popover as PopoverPrimitive } from "radix-ui";
3
+ import { cn } from "../lib/utils";
4
+ import { FieldContext, useField } from "../lib/field-context";
5
+ import { Input } from "./input";
6
+ import { OptionList, OptionListItem } from "./option-list";
7
+ import { Spinner } from "./spinner";
8
+ import { Tag } from "./tag";
9
+
10
+ export interface AutocompleteSuggestion {
11
+ id: string;
12
+ label: string;
13
+ disabled?: boolean;
14
+ }
15
+
16
+ interface AutocompleteBaseProps
17
+ extends Omit<
18
+ React.ComponentProps<typeof Input>,
19
+ "value" | "defaultValue" | "onChange" | "onValueChange" | "type" | "prefix" | "suffix"
20
+ > {
21
+ /**
22
+ * Returns the suggestions for a term; "" when the field is focused while
23
+ * empty. Called 250ms after the user stops typing.
24
+ */
25
+ generateSuggestions: (term: string) => Promise<AutocompleteSuggestion[]>;
26
+ /** Accessible name of the list of suggestions. */
27
+ menuLabel?: string;
28
+ }
29
+
30
+ export interface SingleAutocompleteProps extends AutocompleteBaseProps {
31
+ multiSelect?: false;
32
+ value?: AutocompleteSuggestion;
33
+ defaultValue?: AutocompleteSuggestion;
34
+ /** Called with the chosen suggestion, or `undefined` when the field is emptied. */
35
+ onValueChange?: (value: AutocompleteSuggestion | undefined) => void;
36
+ }
37
+
38
+ export interface MultiAutocompleteProps extends AutocompleteBaseProps {
39
+ /** Let several suggestions be chosen; they show as tags above the input. */
40
+ multiSelect: true;
41
+ value?: AutocompleteSuggestion[];
42
+ defaultValue?: AutocompleteSuggestion[];
43
+ onValueChange?: (value: AutocompleteSuggestion[]) => void;
44
+ }
45
+
46
+ export type AutocompleteProps = SingleAutocompleteProps | MultiAutocompleteProps;
47
+
48
+ const DEBOUNCE = 250;
49
+
50
+ /**
51
+ * Swirl's autocomplete: a text field that suggests values as you type. Put it
52
+ * in a `FormControl`, and return the suggestions for a term from
53
+ * `generateSuggestions`.
54
+ *
55
+ * <FormControl label="Assignee">
56
+ * <Autocomplete generateSuggestions={async (term) => search(term)} />
57
+ * </FormControl>
58
+ *
59
+ * Arrow Down moves into the suggestions and Escape closes them. A single
60
+ * choice fills the field with its label; with `multiSelect` the choices show
61
+ * as removable tags above it.
62
+ */
63
+ export function Autocomplete(props: AutocompleteProps) {
64
+ const {
65
+ generateSuggestions,
66
+ menuLabel = "Suggestions",
67
+ multiSelect: multiSelectProp,
68
+ value: valueProp,
69
+ defaultValue,
70
+ onValueChange,
71
+ clearable = true,
72
+ clearButtonLabel = "Clear input",
73
+ disabled: disabledProp,
74
+ id,
75
+ className,
76
+ onFocus,
77
+ onKeyDown,
78
+ onBlur,
79
+ ...inputProps
80
+ } = props;
81
+ const multiSelect = multiSelectProp === true;
82
+ const field = useField();
83
+ const disabled = disabledProp ?? field?.disabled ?? false;
84
+
85
+ const [uncontrolled, setUncontrolled] = React.useState<AutocompleteSuggestion | AutocompleteSuggestion[] | undefined>(
86
+ () => defaultValue ?? (multiSelect ? [] : undefined),
87
+ );
88
+ const value = valueProp !== undefined ? valueProp : uncontrolled;
89
+ const chosen: AutocompleteSuggestion[] = Array.isArray(value) ? value : value ? [value] : [];
90
+ const single = !multiSelect && !Array.isArray(value) ? value : undefined;
91
+
92
+ const update = (next: AutocompleteSuggestion | AutocompleteSuggestion[] | undefined) => {
93
+ if (valueProp === undefined) setUncontrolled(next);
94
+ (onValueChange as ((v: typeof next) => void) | undefined)?.(next);
95
+ };
96
+
97
+ // The text in the input. A single choice shows its label.
98
+ const [text, setText] = React.useState(() => single?.label ?? "");
99
+ const [open, setOpen] = React.useState(false);
100
+ const [loading, setLoading] = React.useState(false);
101
+ const [suggestions, setSuggestions] = React.useState<AutocompleteSuggestion[]>([]);
102
+
103
+ const generatedId = React.useId();
104
+ const inputId = id ?? field?.id ?? generatedId;
105
+ const listId = `${inputId}-suggestions`;
106
+ const getInput = () => document.getElementById(inputId) as HTMLInputElement | null;
107
+
108
+ // The newest request wins: answers to older terms are dropped.
109
+ const request = React.useRef(0);
110
+ const updateSuggestions = async (term: string) => {
111
+ const current = ++request.current;
112
+ setLoading(true);
113
+ setSuggestions([]);
114
+ const next = await generateSuggestions(term);
115
+ if (current !== request.current) return;
116
+ setSuggestions(next);
117
+ setLoading(false);
118
+ };
119
+
120
+ // Anchored to the field box, as Swirl's list is, or to the input alone.
121
+ const [anchor, setAnchor] = React.useState<{ current: HTMLElement } | null>(null);
122
+ const [geometry, setGeometry] = React.useState({ width: 0, sideOffset: 0, alignOffset: 0 });
123
+ const compact = field ? field.inline || field.labelPosition === "outside" : true;
124
+
125
+ const show = () => {
126
+ if (open || disabled) return;
127
+ const input = getInput();
128
+ const box = input?.closest<HTMLElement>("[data-field-box]") ?? input;
129
+ if (!input || !box) return;
130
+ // Swirl places the list 16px under the input and 16px to its left, 32px
131
+ // wider than it, which in a field box with a floating label lines it up
132
+ // with the box.
133
+ // The row spans the input and its clear button; tags above don't count.
134
+ const row = input.closest<HTMLElement>("[data-field-row]")?.getBoundingClientRect() ?? input.getBoundingClientRect();
135
+ const inputBottom = input.getBoundingClientRect().bottom;
136
+ const boxRect = box.getBoundingClientRect();
137
+ setAnchor({ current: box });
138
+ setGeometry({
139
+ width: row.width + 32,
140
+ sideOffset: inputBottom + 16 - boxRect.bottom,
141
+ alignOffset: row.left - 16 - boxRect.left,
142
+ });
143
+ setOpen(true);
144
+ };
145
+
146
+ const close = () => {
147
+ if (!open) return;
148
+ setText(multiSelect ? "" : (single?.label ?? ""));
149
+ setOpen(false);
150
+ };
151
+
152
+ const debounce = React.useRef<ReturnType<typeof setTimeout>>(undefined);
153
+ React.useEffect(() => () => clearTimeout(debounce.current), []);
154
+
155
+ const onTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
156
+ const term = event.target.value;
157
+ setText(term);
158
+ clearTimeout(debounce.current);
159
+ debounce.current = setTimeout(() => {
160
+ void updateSuggestions(term);
161
+ show();
162
+ if (!multiSelect && term === "") update(undefined);
163
+ }, DEBOUNCE);
164
+ };
165
+
166
+ const choose = (ids: string[]) => {
167
+ if (multiSelect) {
168
+ // Keep chosen values that aren't in this list, and add the newly chosen ones.
169
+ const shownIds = suggestions.map((s) => s.id);
170
+ const kept = chosen.filter((item) => !shownIds.includes(item.id) || ids.includes(item.id));
171
+ const added = suggestions.filter((s) => ids.includes(s.id) && !chosen.some((item) => item.id === s.id));
172
+ update([...kept, ...added]);
173
+ setText("");
174
+ void updateSuggestions("");
175
+ setOpen(false);
176
+ } else {
177
+ const suggestion = suggestions.find((s) => s.id === ids[0]);
178
+ if (!suggestion) return;
179
+ update(suggestion);
180
+ setText(suggestion.label);
181
+ setOpen(false);
182
+ }
183
+ getInput()?.focus();
184
+ };
185
+
186
+ // The field's label floats while there are tags, even with no text.
187
+ const parentSetFilled = field?.setFilled;
188
+ const [textFilled, setTextFilled] = React.useState(false);
189
+ const filled = textFilled || chosen.length > 0;
190
+ React.useEffect(() => {
191
+ parentSetFilled?.(filled);
192
+ }, [parentSetFilled, filled]);
193
+ const innerField = React.useMemo(
194
+ () => (field ? { ...field, setFilled: setTextFilled } : null),
195
+ [field],
196
+ );
197
+
198
+ const tags = multiSelect && chosen.length > 0 && (
199
+ <div className={cn("mb-1 flex flex-wrap gap-2", !compact && "mt-1")}>
200
+ {chosen.map((item) => (
201
+ <Tag
202
+ key={item.id}
203
+ label={item.label}
204
+ removable={!disabled}
205
+ onRemove={() => update(chosen.filter((c) => c.id !== item.id))}
206
+ />
207
+ ))}
208
+ </div>
209
+ );
210
+
211
+ const input = (
212
+ <Input
213
+ {...inputProps}
214
+ id={inputId}
215
+ role="combobox"
216
+ aria-autocomplete="list"
217
+ aria-controls={open ? listId : undefined}
218
+ aria-expanded={open}
219
+ autoComplete="off"
220
+ value={text}
221
+ onChange={onTextChange}
222
+ disabled={disabled}
223
+ clearable={clearable && !multiSelect}
224
+ clearButtonLabel={clearButtonLabel}
225
+ className={className}
226
+ onFocus={(event) => {
227
+ onFocus?.(event);
228
+ void updateSuggestions(event.target.value);
229
+ show();
230
+ }}
231
+ onBlur={(event) => {
232
+ onBlur?.(event);
233
+ // Leaving for somewhere other than the list closes it.
234
+ const next = event.relatedTarget as Node | null;
235
+ if (next && !document.getElementById(listId)?.parentElement?.contains(next)) close();
236
+ }}
237
+ onKeyDown={(event) => {
238
+ onKeyDown?.(event);
239
+ if (event.key === "ArrowDown") {
240
+ event.preventDefault();
241
+ if (!open) show();
242
+ document.getElementById(listId)?.querySelector<HTMLElement>('[tabindex="0"]')?.focus();
243
+ }
244
+ }}
245
+ />
246
+ );
247
+
248
+ return (
249
+ <PopoverPrimitive.Root open={open} onOpenChange={(next) => (next ? show() : close())}>
250
+ {anchor && <PopoverPrimitive.Anchor virtualRef={anchor} />}
251
+ <div data-field-row="" className="flex w-full min-w-0 flex-col">
252
+ {tags}
253
+ {innerField ? <FieldContext.Provider value={innerField}>{input}</FieldContext.Provider> : input}
254
+ </div>
255
+ <PopoverPrimitive.Portal>
256
+ <PopoverPrimitive.Content
257
+ // A plain container: the listbox inside carries the semantics.
258
+ role="presentation"
259
+ side="bottom"
260
+ align="start"
261
+ sideOffset={geometry.sideOffset}
262
+ alignOffset={geometry.alignOffset}
263
+ avoidCollisions={false}
264
+ style={{ width: geometry.width }}
265
+ onOpenAutoFocus={(event) => event.preventDefault()}
266
+ onCloseAutoFocus={(event) => event.preventDefault()}
267
+ onInteractOutside={(event) => {
268
+ // Clicks in the field keep the list open.
269
+ const target = event.target as Node;
270
+ if (anchor?.current.contains(target)) event.preventDefault();
271
+ }}
272
+ onEscapeKeyDown={(event) => {
273
+ event.preventDefault();
274
+ getInput()?.focus();
275
+ close();
276
+ }}
277
+ className={cn(
278
+ "relative z-40 max-h-[18rem] overflow-x-hidden overflow-y-auto rounded-sm py-2 shadow-level-1 outline-none",
279
+ "bg-translucent-low backdrop-blur-l",
280
+ "duration-100 data-[state=open]:animate-in data-[state=open]:fade-in-0 motion-reduce:animate-none",
281
+ // Swirl hides the container when it has nothing to show.
282
+ !loading && suggestions.length === 0 && "hidden",
283
+ )}
284
+ >
285
+ {loading && (
286
+ <div className="flex items-center justify-center p-4">
287
+ <Spinner label="Loading" />
288
+ </div>
289
+ )}
290
+ {suggestions.length > 0 && (
291
+ <OptionList
292
+ id={listId}
293
+ label={menuLabel}
294
+ multiSelect={multiSelect}
295
+ allowDeselect={multiSelect}
296
+ value={chosen.map((item) => item.id)}
297
+ onValueChange={choose}
298
+ >
299
+ {suggestions.map((suggestion) => (
300
+ <OptionListItem
301
+ key={suggestion.id}
302
+ value={suggestion.id}
303
+ label={suggestion.label}
304
+ disabled={suggestion.disabled}
305
+ />
306
+ ))}
307
+ </OptionList>
308
+ )}
309
+ </PopoverPrimitive.Content>
310
+ </PopoverPrimitive.Portal>
311
+ </PopoverPrimitive.Root>
312
+ );
313
+ }
@@ -0,0 +1,258 @@
1
+ import * as React from "react";
2
+ import { Avatar as AvatarPrimitive } from "radix-ui";
3
+ import { cva, type VariantProps } from "class-variance-authority";
4
+ import { cn } from "../lib/utils";
5
+ import { focusRing } from "../lib/focus";
6
+
7
+ const avatarVariants = cva(
8
+ // No overflow-hidden here: it would clip the badge, which sits over the edge.
9
+ // The image and fallback inherit the radius and clip themselves, as in Swirl.
10
+ "relative inline-flex shrink-0 items-center justify-center select-none",
11
+ {
12
+ variants: {
13
+ size: {
14
+ "3xs": "size-5 text-[0.625rem]",
15
+ "2xs": "size-6 text-[0.625rem]",
16
+ xs: "size-7 text-xs",
17
+ s: "size-8 text-xs",
18
+ m: "size-10 text-base",
19
+ l: "size-12 text-lg",
20
+ xl: "size-16 text-xl",
21
+ "2xl": "size-36 text-[3.375rem]",
22
+ },
23
+ variant: { round: "rounded-full", square: "rounded-base" },
24
+ /** Swirl's decorative hues, used to give a person a stable colour. */
25
+ color: {
26
+ neutral: "bg-surface-neutral-subdued text-foreground",
27
+ chilli: "bg-chilli-subdued text-chilli-text",
28
+ pumpkin: "bg-pumpkin-subdued text-pumpkin-text",
29
+ banana: "bg-banana-subdued text-banana-text",
30
+ radish: "bg-radish-subdued text-radish-text",
31
+ grape: "bg-grape-subdued text-grape-text",
32
+ kiwi: "bg-kiwi-subdued text-kiwi-text",
33
+ blueberry: "bg-blueberry-subdued text-blueberry-text",
34
+ },
35
+ interactive: { true: cn("cursor-pointer", focusRing), false: "" },
36
+ },
37
+ defaultVariants: { size: "m", variant: "round", color: "neutral", interactive: false },
38
+ },
39
+ );
40
+
41
+ /** Swirl insets an icon by these, per size, so a 40px avatar has a 20px icon. */
42
+ const iconPadding: Record<AvatarSize, string> = {
43
+ "3xs": "px-0.5",
44
+ "2xs": "px-0.5",
45
+ xs: "px-[0.4375rem]",
46
+ s: "px-2",
47
+ m: "px-2.5",
48
+ l: "px-3",
49
+ xl: "px-4",
50
+ "2xl": "px-8",
51
+ };
52
+
53
+ export type AvatarColor = NonNullable<VariantProps<typeof avatarVariants>["color"]>;
54
+ export type AvatarSize = NonNullable<VariantProps<typeof avatarVariants>["size"]>;
55
+
56
+ const palette: AvatarColor[] = [
57
+ "chilli",
58
+ "pumpkin",
59
+ "banana",
60
+ "radish",
61
+ "grape",
62
+ "kiwi",
63
+ "blueberry",
64
+ ];
65
+
66
+ /**
67
+ * Picks a stable decorative colour from a name, so the same person always gets
68
+ * the same avatar colour without that colour having to be stored anywhere.
69
+ */
70
+ export function avatarColorFor(seed: string): AvatarColor {
71
+ let hash = 0;
72
+ for (let i = 0; i < seed.length; i++) hash = (hash * 31 + seed.charCodeAt(i)) | 0;
73
+ return palette[Math.abs(hash) % palette.length]!;
74
+ }
75
+
76
+ /** Derives up to two initials from a display name. */
77
+ export function initialsFor(name: string): string {
78
+ const parts = name.trim().split(/\s+/).filter(Boolean);
79
+ if (parts.length === 0) return "";
80
+ if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();
81
+ return (parts[0]![0]! + parts[parts.length - 1]![0]!).toUpperCase();
82
+ }
83
+
84
+ export interface AvatarProps
85
+ extends Omit<React.ComponentProps<"span">, "color">,
86
+ Omit<VariantProps<typeof avatarVariants>, "color"> {
87
+ /**
88
+ * Decorative hue. Defaults to `kiwi`, matching Swirl.
89
+ * `"auto"` derives a stable hue from `label`, so the same person always gets
90
+ * the same colour without it having to be stored anywhere.
91
+ */
92
+ color?: AvatarColor | "auto";
93
+ /**
94
+ * Accessible name for the person or entity. Required.
95
+ * Also the seed for `color="auto"`.
96
+ */
97
+ label: string;
98
+ src?: string;
99
+ /** Initials to show when there is no image. Derived from `label` if omitted. */
100
+ initials?: string;
101
+ /** Icon fallback, used in place of initials. */
102
+ icon?: React.ReactNode;
103
+ /** Status dot or small badge, positioned over the avatar. */
104
+ badge?: React.ReactNode;
105
+ badgePosition?: "top" | "bottom";
106
+ /** Show `label` as text beside the avatar. */
107
+ showLabel?: boolean;
108
+ loading?: "eager" | "lazy";
109
+ }
110
+
111
+ /**
112
+ * A person or entity marker.
113
+ *
114
+ * Falls back from image to initials to icon. `color` defaults to `kiwi` as it
115
+ * does in Swirl; pass `color="auto"` to derive a stable hue from `label`.
116
+ */
117
+ export function Avatar({
118
+ className,
119
+ size,
120
+ variant,
121
+ color,
122
+ interactive,
123
+ label,
124
+ src,
125
+ initials,
126
+ icon,
127
+ badge,
128
+ badgePosition = "bottom",
129
+ showLabel = false,
130
+ loading = "lazy",
131
+ ...props
132
+ }: AvatarProps) {
133
+ const resolvedColor = color === "auto" ? avatarColorFor(label) : (color ?? "kiwi");
134
+ const resolvedInitials = initials ?? initialsFor(label);
135
+ const dotBadge =
136
+ React.isValidElement<{ variant?: unknown }>(badge) && badge.props.variant === "dot";
137
+
138
+ const avatar = (
139
+ <AvatarPrimitive.Root
140
+ className={cn(
141
+ avatarVariants({ size, variant, color: resolvedColor, interactive }),
142
+ // An icon avatar ignores the colour, as in Swirl: a quiet grey with a default-coloured icon.
143
+ icon && "bg-surface-raised text-icon-default",
144
+ className,
145
+ )}
146
+ // Lets a container restyle icon avatars, as Swirl does through a CSS variable.
147
+ data-avatar-icon={icon ? "" : undefined}
148
+ {...props}
149
+ >
150
+ {src && (
151
+ <AvatarPrimitive.Image
152
+ src={src}
153
+ alt={showLabel ? "" : label}
154
+ loading={loading}
155
+ className="size-full rounded-[inherit] object-cover"
156
+ />
157
+ )}
158
+ <AvatarPrimitive.Fallback
159
+ // Without a delay the fallback flashes before a cached image paints.
160
+ delayMs={src ? 300 : 0}
161
+ className={cn(
162
+ "flex size-full items-center justify-center overflow-hidden rounded-[inherit] font-medium",
163
+ icon && cn(iconPadding[size ?? "m"], "[&>svg]:h-auto [&>svg]:w-full"),
164
+ )}
165
+ >
166
+ {icon ?? resolvedInitials}
167
+ {!icon && !resolvedInitials && <span className="sr-only">{label}</span>}
168
+ </AvatarPrimitive.Fallback>
169
+
170
+ {badge && (
171
+ <span
172
+ className={cn(
173
+ // The ring goes on the badge itself, so it traces a dot or a pill
174
+ // whatever the avatar's shape.
175
+ "absolute flex *:rounded-full *:ring-2 *:ring-surface",
176
+ dotBadge
177
+ ? // A status dot is centred on the outline at 45deg: 85.4% across
178
+ // a circle, nearer the corner of a square.
179
+ cn(
180
+ "-translate-x-1/2 -translate-y-1/2",
181
+ variant === "square" ? "left-[92%]" : "left-[85.4%]",
182
+ badgePosition === "top"
183
+ ? variant === "square" ? "top-[8%]" : "top-[14.6%]"
184
+ : variant === "square" ? "top-[92%]" : "top-[85.4%]",
185
+ )
186
+ : // Swirl's count geometry: a 24px slot whose left edge sits at
187
+ // 55%, nudged a quarter of its height past the edge, so a count
188
+ // grows rightwards, away from the avatar, instead of across it.
189
+ cn(
190
+ "left-[55%] h-6 min-w-6 items-center",
191
+ badgePosition === "top" ? "top-0 -translate-y-1/4" : "bottom-0 translate-y-1/4",
192
+ ),
193
+ )}
194
+ >
195
+ {badge}
196
+ </span>
197
+ )}
198
+ </AvatarPrimitive.Root>
199
+ );
200
+
201
+ if (!showLabel) return avatar;
202
+
203
+ return (
204
+ <span className="inline-flex items-center gap-2">
205
+ {avatar}
206
+ <span className="truncate text-sm text-foreground">{label}</span>
207
+ </span>
208
+ );
209
+ }
210
+
211
+ export interface AvatarGroupProps extends React.ComponentProps<"div"> {
212
+ /** Show at most N avatars, then a `+n` overflow marker. */
213
+ max?: number;
214
+ size?: AvatarSize;
215
+ }
216
+
217
+ const overflowSizes: Record<AvatarSize, string> = {
218
+ "3xs": "size-5 text-[0.625rem]",
219
+ "2xs": "size-6 text-[0.625rem]",
220
+ xs: "size-7 text-xs",
221
+ s: "size-8 text-xs",
222
+ m: "size-10 text-base",
223
+ l: "size-12 text-lg",
224
+ xl: "size-16 text-xl",
225
+ "2xl": "size-36 text-[3.375rem]",
226
+ };
227
+
228
+ /** Overlapping avatars with an optional overflow count. */
229
+ export function AvatarGroup({
230
+ className,
231
+ max,
232
+ size = "m",
233
+ children,
234
+ ...props
235
+ }: AvatarGroupProps) {
236
+ const items = React.Children.toArray(children);
237
+ const shown = max ? items.slice(0, max) : items;
238
+ const hidden = items.length - shown.length;
239
+
240
+ return (
241
+ <div
242
+ className={cn("flex items-center -space-x-2 [&>*]:ring-2 [&>*]:ring-surface", className)}
243
+ {...props}
244
+ >
245
+ {shown}
246
+ {hidden > 0 && (
247
+ <span
248
+ className={cn(
249
+ "inline-flex items-center justify-center rounded-full bg-surface-neutral-subdued font-medium text-subdued",
250
+ overflowSizes[size],
251
+ )}
252
+ >
253
+ +{hidden}
254
+ </span>
255
+ )}
256
+ </div>
257
+ );
258
+ }
@@ -0,0 +1,100 @@
1
+ import { cva, type VariantProps } from "class-variance-authority";
2
+ import { cn } from "../lib/utils";
3
+
4
+ /**
5
+ * Swirl's badge intents: five status colours, `strong`/`neutral`, and the seven
6
+ * decorative fruit hues used for categorisation.
7
+ */
8
+ const badgeVariants = cva(
9
+ // Swirl rings every badge in the page colour, so badges that touch or sit
10
+ // over something (a stack, an avatar's corner) stay separate. Pass another
11
+ // ring-* colour on a different surface.
12
+ "inline-flex shrink-0 items-center justify-center gap-1 rounded-full font-medium whitespace-nowrap ring-2 ring-background [&_svg]:shrink-0",
13
+ {
14
+ variants: {
15
+ intent: {
16
+ strong: "bg-surface-neutral text-on-status",
17
+ neutral: "bg-surface-neutral-subdued text-foreground",
18
+ critical: "bg-surface-critical text-on-status",
19
+ warning: "bg-surface-warning text-dark",
20
+ success: "bg-surface-success text-on-status",
21
+ info: "bg-surface-info text-on-status",
22
+ chilli: "bg-chilli text-on-status",
23
+ pumpkin: "bg-pumpkin text-dark",
24
+ banana: "bg-banana text-dark",
25
+ radish: "bg-radish text-on-status",
26
+ grape: "bg-grape text-on-status",
27
+ kiwi: "bg-kiwi text-on-status",
28
+ blueberry: "bg-blueberry text-on-status",
29
+ },
30
+ size: {
31
+ xs: "h-4 min-w-4 px-1 text-xs leading-4",
32
+ s: "h-5 min-w-5 px-1.5 text-xs leading-4",
33
+ m: "h-6 min-w-6 px-2 text-sm leading-5",
34
+ },
35
+ variant: { default: "", dot: "p-0" },
36
+ },
37
+ compoundVariants: [
38
+ // A dot badge is a bare status marker with no label.
39
+ { variant: "dot", size: "xs", class: "size-2 min-w-0" },
40
+ { variant: "dot", size: "s", class: "size-2.5 min-w-0" },
41
+ { variant: "dot", size: "m", class: "size-3 min-w-0" },
42
+ ],
43
+ defaultVariants: { intent: "strong", size: "m", variant: "default" },
44
+ },
45
+ );
46
+
47
+ /** shadcn's badge variants, mapped onto Swirl intents. */
48
+ const shadcnIntents = {
49
+ default: "strong",
50
+ secondary: "neutral",
51
+ destructive: "critical",
52
+ outline: "neutral",
53
+ } as const;
54
+
55
+ export type BadgeIntent = NonNullable<VariantProps<typeof badgeVariants>["intent"]>;
56
+
57
+ export interface BadgeProps
58
+ extends React.ComponentProps<"span">,
59
+ Omit<VariantProps<typeof badgeVariants>, "intent"> {
60
+ /** Swirl intent, or one of shadcn's `default`/`secondary`/`destructive`/`outline`. */
61
+ intent?: BadgeIntent | keyof typeof shadcnIntents;
62
+ /** Badge text. Interchangeable with `children`. */
63
+ label?: string;
64
+ icon?: React.ReactNode;
65
+ }
66
+
67
+ /** A small count or status marker. Use `variant="dot"` for a bare indicator. */
68
+ export function Badge({
69
+ className,
70
+ intent,
71
+ size,
72
+ variant,
73
+ label,
74
+ icon,
75
+ children,
76
+ ...props
77
+ }: BadgeProps) {
78
+ const resolved = (intent && intent in shadcnIntents
79
+ ? shadcnIntents[intent as keyof typeof shadcnIntents]
80
+ : intent) as BadgeIntent | undefined;
81
+
82
+ const content = children ?? label;
83
+ const isDot = variant === "dot";
84
+
85
+ return (
86
+ <span
87
+ className={cn(badgeVariants({ intent: resolved, size, variant }), className)}
88
+ // A dot carries no text, so it needs a name or to be hidden outright.
89
+ aria-label={isDot ? label : undefined}
90
+ role={isDot && label ? "img" : undefined}
91
+ aria-hidden={isDot && !label ? true : undefined}
92
+ {...props}
93
+ >
94
+ {!isDot && icon}
95
+ {!isDot && content}
96
+ </span>
97
+ );
98
+ }
99
+
100
+ export { badgeVariants };