orbital-ds 0.9.0 → 0.10.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 (71) hide show
  1. package/AGENTS.md +22 -2
  2. package/components.manifest.json +388 -1
  3. package/contract.json +5 -0
  4. package/dist/hooks/use-ds-messages.d.ts +59 -1
  5. package/dist/hooks/use-ds-messages.js +6 -0
  6. package/dist/lib/echarts-presets.d.ts +153 -0
  7. package/dist/lib/echarts-presets.js +311 -0
  8. package/dist/lib/echarts-server.d.ts +15 -0
  9. package/dist/lib/echarts-server.js +15 -0
  10. package/dist/lib/echarts-setup.d.ts +8 -0
  11. package/dist/lib/echarts-setup.js +68 -0
  12. package/dist/lib/echarts-theme.d.ts +36 -0
  13. package/dist/lib/echarts-theme.js +142 -0
  14. package/dist/lib/i18n.d.ts +57 -1
  15. package/dist/lib/i18n.js +169 -3
  16. package/dist/styles.css +43 -5
  17. package/dist/themes/friendly.css +3 -1
  18. package/dist/themes/friendly.scoped.css +3 -1
  19. package/dist/themes/friendly.tokens.json +45 -0
  20. package/dist/themes/qratia.tokens.json +49 -0
  21. package/dist/themes/tactile.css +3 -1
  22. package/dist/themes/tactile.scoped.css +3 -1
  23. package/dist/themes/tactile.tokens.json +42 -0
  24. package/dist/themes/twitter.css +3 -1
  25. package/dist/themes/twitter.scoped.css +3 -1
  26. package/dist/themes/twitter.tokens.json +45 -0
  27. package/dist/themes/zyro.css +3 -1
  28. package/dist/themes/zyro.scoped.css +3 -1
  29. package/dist/themes/zyro.tokens.json +46 -0
  30. package/dist/ui/calendar.js +4 -0
  31. package/dist/ui/code-block.d.ts +14 -0
  32. package/dist/ui/code-block.js +106 -0
  33. package/dist/ui/data-table.d.ts +185 -0
  34. package/dist/ui/data-table.js +714 -0
  35. package/dist/ui/date-picker.d.ts +65 -0
  36. package/dist/ui/date-picker.js +362 -0
  37. package/dist/ui/dropzone.d.ts +42 -0
  38. package/dist/ui/dropzone.js +220 -0
  39. package/dist/ui/echart.d.ts +31 -0
  40. package/dist/ui/echart.js +88 -0
  41. package/dist/ui/eyebrow.d.ts +7 -0
  42. package/dist/ui/eyebrow.js +16 -0
  43. package/dist/ui/filter-bar.d.ts +36 -0
  44. package/dist/ui/filter-bar.js +193 -0
  45. package/dist/ui/heatmap-grid.d.ts +39 -0
  46. package/dist/ui/heatmap-grid.js +195 -0
  47. package/dist/ui/i18n-provider.js +3 -3
  48. package/dist/ui/legend.d.ts +30 -0
  49. package/dist/ui/legend.js +124 -0
  50. package/dist/ui/notifications.d.ts +69 -0
  51. package/dist/ui/notifications.js +335 -0
  52. package/dist/ui/page-header.d.ts +19 -0
  53. package/dist/ui/page-header.js +132 -0
  54. package/dist/ui/panel.d.ts +12 -0
  55. package/dist/ui/panel.js +41 -0
  56. package/dist/ui/proportion-bar.d.ts +27 -0
  57. package/dist/ui/proportion-bar.js +92 -0
  58. package/dist/ui/sparkline.d.ts +26 -0
  59. package/dist/ui/sparkline.js +97 -0
  60. package/dist/ui/stat.d.ts +61 -0
  61. package/dist/ui/stat.js +238 -0
  62. package/dist/ui/status-badge.d.ts +38 -0
  63. package/dist/ui/status-badge.js +153 -0
  64. package/dist/ui/stepper.d.ts +20 -0
  65. package/dist/ui/stepper.js +152 -0
  66. package/dist/ui/timeline.d.ts +29 -0
  67. package/dist/ui/timeline.js +157 -0
  68. package/docs/GRAFICOS.md +125 -0
  69. package/docs/adr/0001-rtl-clases-logicas.md +78 -0
  70. package/package.json +17 -4
  71. package/scripts/init.mjs +1 -0
@@ -0,0 +1,65 @@
1
+ import * as React from 'react';
2
+ import { DateRange } from 'react-day-picker';
3
+ export { DateRange } from 'react-day-picker';
4
+ import { DsMessages } from '../lib/i18n.js';
5
+ import { Calendar } from './calendar.js';
6
+ import './button.js';
7
+ import 'class-variance-authority/types';
8
+ import '@base-ui/react/use-render';
9
+ import 'class-variance-authority';
10
+
11
+ type DateRangePreset = {
12
+ label: string;
13
+ range: DateRange;
14
+ };
15
+ declare function DatePicker({ value, onChange, placeholder, min, max, disabled, align, formatOptions, className, id, "aria-invalid": ariaInvalid, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby, calendarProps, }: {
16
+ value?: Date;
17
+ onChange?: (date: Date | undefined) => void;
18
+ /** Texto sin valor; por defecto, «Elige una fecha». */
19
+ placeholder?: string;
20
+ /** Primer día elegible. */
21
+ min?: Date;
22
+ /** Último día elegible (p. ej. ayer). */
23
+ max?: Date;
24
+ disabled?: boolean;
25
+ align?: "start" | "center" | "end";
26
+ /** Formato del botón (Intl.DateTimeFormat). */
27
+ formatOptions?: Intl.DateTimeFormatOptions;
28
+ className?: string;
29
+ id?: string;
30
+ "aria-invalid"?: boolean;
31
+ "aria-label"?: string;
32
+ "aria-labelledby"?: string;
33
+ /** Props extra del calendario (p. ej. `captionLayout="dropdown"`). */
34
+ calendarProps?: Omit<React.ComponentProps<typeof Calendar>, "mode" | "selected" | "onSelect">;
35
+ }): React.JSX.Element;
36
+ /** Atajos por defecto: hoy, ayer y últimos 7/30/90 días (hasta `max` si es anterior a hoy). */
37
+ declare function defaultDatePresets(t: DsMessages, { today, max }?: {
38
+ today?: Date;
39
+ max?: Date;
40
+ }): DateRangePreset[];
41
+ declare function DateRangePicker({ value, onChange, presets, placeholder, min, max, maxSpan, numberOfMonths, disabled, align, formatOptions, className, id, "aria-invalid": ariaInvalid, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby, }: {
42
+ value?: DateRange;
43
+ /** Se llama al «Aplicar» (con el rango) o al «Borrar» (con undefined). */
44
+ onChange?: (range: DateRange | undefined) => void;
45
+ /** Atajos: `true` = hoy, ayer, últimos 7/30/90 días; o una lista propia. */
46
+ presets?: boolean | DateRangePreset[];
47
+ /** Texto sin valor; por defecto, «Elige un rango de fechas». */
48
+ placeholder?: string;
49
+ min?: Date;
50
+ /** Último día elegible (p. ej. ayer). */
51
+ max?: Date;
52
+ /** Duración máxima del rango en días (ambos extremos incluidos). */
53
+ maxSpan?: number;
54
+ numberOfMonths?: number;
55
+ disabled?: boolean;
56
+ align?: "start" | "center" | "end";
57
+ formatOptions?: Intl.DateTimeFormatOptions;
58
+ className?: string;
59
+ id?: string;
60
+ "aria-invalid"?: boolean;
61
+ "aria-label"?: string;
62
+ "aria-labelledby"?: string;
63
+ }): React.JSX.Element;
64
+
65
+ export { DatePicker, DateRangePicker, type DateRangePreset, defaultDatePresets };
@@ -0,0 +1,362 @@
1
+ "use client";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ import { CalendarIcon } from "lucide-react";
4
+ import * as React from "react";
5
+ import { useDsLocale, useDsMessages } from "../hooks/use-ds-messages";
6
+ import { dsFormat } from "../lib/i18n";
7
+ import { cn } from "../lib/utils";
8
+ import { Button } from "./button";
9
+ import { Calendar } from "./calendar";
10
+ import { Popover, PopoverContent, PopoverTrigger } from "./popover";
11
+ const DAY = 864e5;
12
+ const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
13
+ const addDays = (d, n) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
14
+ const addMonths = (d, n) => new Date(d.getFullYear(), d.getMonth() + n, 1);
15
+ const diffDays = (a, b) => Math.round(
16
+ (Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()) - Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) / DAY
17
+ );
18
+ const sameDay = (a, b) => !!a && !!b && diffDays(a, b) === 0;
19
+ const spanOf = (r) => r?.from ? diffDays(r.from, r.to ?? r.from) + 1 : 0;
20
+ function useIntlCalendar(locale) {
21
+ return React.useMemo(() => {
22
+ const caption = new Intl.DateTimeFormat(locale, {
23
+ month: "long",
24
+ year: "numeric"
25
+ });
26
+ const weekday = new Intl.DateTimeFormat(locale, { weekday: "short" });
27
+ const weekdayLong = new Intl.DateTimeFormat(locale, { weekday: "long" });
28
+ const full = new Intl.DateTimeFormat(locale, { dateStyle: "full" });
29
+ const month = new Intl.DateTimeFormat(locale, { month: "short" });
30
+ let weekStartsOn;
31
+ try {
32
+ const loc = new Intl.Locale(locale);
33
+ const first = (loc.getWeekInfo?.() ?? loc.weekInfo)?.firstDay;
34
+ if (first) weekStartsOn = first % 7;
35
+ } catch {
36
+ }
37
+ return {
38
+ locale: { code: locale },
39
+ weekStartsOn,
40
+ formatters: {
41
+ formatCaption: (d) => caption.format(d),
42
+ formatWeekdayName: (d) => weekday.format(d),
43
+ formatMonthDropdown: (d) => month.format(d)
44
+ },
45
+ labels: {
46
+ labelDayButton: (d) => full.format(d),
47
+ labelWeekday: (d) => weekdayLong.format(d),
48
+ labelGrid: (d) => caption.format(d)
49
+ }
50
+ };
51
+ }, [locale]);
52
+ }
53
+ function boundsMatcher(min, max) {
54
+ const out = [];
55
+ if (min) out.push({ before: startOfDay(min) });
56
+ if (max) out.push({ after: startOfDay(max) });
57
+ return out;
58
+ }
59
+ const triggerClass = "w-full justify-start gap-2 text-start font-normal data-empty:text-muted-foreground";
60
+ function DatePicker({
61
+ value,
62
+ onChange,
63
+ placeholder,
64
+ min,
65
+ max,
66
+ disabled,
67
+ align = "start",
68
+ formatOptions = { dateStyle: "medium" },
69
+ className,
70
+ id,
71
+ "aria-invalid": ariaInvalid,
72
+ "aria-label": ariaLabel,
73
+ "aria-labelledby": ariaLabelledby,
74
+ calendarProps
75
+ }) {
76
+ const t = useDsMessages();
77
+ const locale = useDsLocale();
78
+ const intl = useIntlCalendar(locale);
79
+ const [open, setOpen] = React.useState(false);
80
+ const fmt = React.useMemo(
81
+ () => new Intl.DateTimeFormat(locale, formatOptions),
82
+ [locale, formatOptions]
83
+ );
84
+ return /* @__PURE__ */ jsx(
85
+ "div",
86
+ {
87
+ "data-slot": "date-picker",
88
+ "data-state": open ? "open" : "closed",
89
+ "data-empty": !value || void 0,
90
+ className: cn("inline-flex", className),
91
+ children: /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: (o) => setOpen(o), children: [
92
+ /* @__PURE__ */ jsxs(
93
+ PopoverTrigger,
94
+ {
95
+ render: /* @__PURE__ */ jsx(
96
+ Button,
97
+ {
98
+ id,
99
+ variant: "outline",
100
+ disabled,
101
+ "aria-invalid": ariaInvalid,
102
+ "aria-label": ariaLabel,
103
+ "aria-labelledby": ariaLabelledby,
104
+ "data-empty": !value || void 0,
105
+ className: triggerClass
106
+ }
107
+ ),
108
+ children: [
109
+ /* @__PURE__ */ jsx(CalendarIcon, {}),
110
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: value ? fmt.format(value) : placeholder ?? t.datePickerPlaceholder })
111
+ ]
112
+ }
113
+ ),
114
+ /* @__PURE__ */ jsx(
115
+ PopoverContent,
116
+ {
117
+ "data-slot": "date-picker-content",
118
+ align,
119
+ className: "w-auto gap-0 p-0",
120
+ children: /* @__PURE__ */ jsx(
121
+ Calendar,
122
+ {
123
+ ...intl,
124
+ ...calendarProps,
125
+ mode: "single",
126
+ selected: value,
127
+ defaultMonth: value ?? max,
128
+ startMonth: min,
129
+ endMonth: max,
130
+ disabled: boundsMatcher(min, max),
131
+ onSelect: (d) => {
132
+ onChange?.(d);
133
+ if (d) setOpen(false);
134
+ }
135
+ }
136
+ )
137
+ }
138
+ )
139
+ ] })
140
+ }
141
+ );
142
+ }
143
+ function defaultDatePresets(t, { today = /* @__PURE__ */ new Date(), max } = {}) {
144
+ const now = startOfDay(today);
145
+ const end = max && startOfDay(max) < now ? startOfDay(max) : now;
146
+ const yesterday = addDays(now, -1);
147
+ const last = (n) => ({
148
+ label: dsFormat(t.datePresetLastDays, { n }),
149
+ range: { from: addDays(end, -(n - 1)), to: end }
150
+ });
151
+ return [
152
+ { label: t.datePresetToday, range: { from: now, to: now } },
153
+ { label: t.datePresetYesterday, range: { from: yesterday, to: yesterday } },
154
+ last(7),
155
+ last(30),
156
+ last(90)
157
+ ];
158
+ }
159
+ function DateRangePicker({
160
+ value,
161
+ onChange,
162
+ presets,
163
+ placeholder,
164
+ min,
165
+ max,
166
+ maxSpan,
167
+ numberOfMonths = 2,
168
+ disabled,
169
+ align = "start",
170
+ formatOptions = { dateStyle: "medium" },
171
+ className,
172
+ id,
173
+ "aria-invalid": ariaInvalid,
174
+ "aria-label": ariaLabel,
175
+ "aria-labelledby": ariaLabelledby
176
+ }) {
177
+ const t = useDsMessages();
178
+ const locale = useDsLocale();
179
+ const intl = useIntlCalendar(locale);
180
+ const hintId = React.useId();
181
+ const [open, setOpen] = React.useState(false);
182
+ const [draft, setDraft] = React.useState(value);
183
+ const lastMonth = (r) => {
184
+ const anchor = r?.to ?? r?.from ?? max ?? /* @__PURE__ */ new Date();
185
+ return addMonths(anchor, -(numberOfMonths - 1));
186
+ };
187
+ const [month, setMonth] = React.useState(() => lastMonth(value));
188
+ const fmt = React.useMemo(
189
+ () => new Intl.DateTimeFormat(locale, formatOptions),
190
+ [locale, formatOptions]
191
+ );
192
+ const list = React.useMemo(
193
+ () => presets === true ? defaultDatePresets(t, { max }) : Array.isArray(presets) ? presets : [],
194
+ [presets, t, max]
195
+ );
196
+ const inBounds = (r) => !!r.from && (!min || diffDays(startOfDay(min), r.from) >= 0) && (!max || diffDays(r.to ?? r.from, startOfDay(max)) >= 0);
197
+ const overSpan = !!maxSpan && spanOf(draft) > maxSpan;
198
+ const canApply = !!draft?.from && !overSpan && inBounds(draft);
199
+ const disabledDays = React.useMemo(() => {
200
+ const out = boundsMatcher(min, max);
201
+ const from = draft?.from;
202
+ if (maxSpan && from && (!draft?.to || sameDay(from, draft.to))) {
203
+ out.push((d) => Math.abs(diffDays(from, d)) >= maxSpan);
204
+ }
205
+ return out;
206
+ }, [min, max, maxSpan, draft]);
207
+ const label = value?.from ? fmt.formatRange(value.from, value.to ?? value.from) : placeholder ?? t.dateRangePlaceholder;
208
+ return /* @__PURE__ */ jsx(
209
+ "div",
210
+ {
211
+ "data-slot": "date-range-picker",
212
+ "data-state": open ? "open" : "closed",
213
+ "data-empty": !value?.from || void 0,
214
+ className: cn("inline-flex", className),
215
+ children: /* @__PURE__ */ jsxs(
216
+ Popover,
217
+ {
218
+ open,
219
+ onOpenChange: (o) => {
220
+ if (o) {
221
+ setDraft(value);
222
+ setMonth(lastMonth(value));
223
+ }
224
+ setOpen(o);
225
+ },
226
+ children: [
227
+ /* @__PURE__ */ jsxs(
228
+ PopoverTrigger,
229
+ {
230
+ render: /* @__PURE__ */ jsx(
231
+ Button,
232
+ {
233
+ id,
234
+ variant: "outline",
235
+ disabled,
236
+ "aria-invalid": ariaInvalid,
237
+ "aria-label": ariaLabel,
238
+ "aria-labelledby": ariaLabelledby,
239
+ "data-empty": !value?.from || void 0,
240
+ className: triggerClass
241
+ }
242
+ ),
243
+ children: [
244
+ /* @__PURE__ */ jsx(CalendarIcon, {}),
245
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: label })
246
+ ]
247
+ }
248
+ ),
249
+ /* @__PURE__ */ jsxs(
250
+ PopoverContent,
251
+ {
252
+ "data-slot": "date-range-picker-content",
253
+ align,
254
+ className: "w-auto max-w-(--available-width) gap-0 p-0",
255
+ children: [
256
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row", children: [
257
+ list.length ? /* @__PURE__ */ jsx(
258
+ "div",
259
+ {
260
+ "data-slot": "date-range-presets",
261
+ className: "flex flex-row flex-wrap gap-1 border-b border-border p-(--ds-popover-p) sm:flex-col sm:flex-nowrap sm:border-e sm:border-b-0",
262
+ children: list.map((p) => {
263
+ const ok = inBounds(p.range) && (!maxSpan || spanOf(p.range) <= maxSpan);
264
+ const active = sameDay(p.range.from, draft?.from) && sameDay(p.range.to ?? p.range.from, draft?.to ?? draft?.from);
265
+ return /* @__PURE__ */ jsx(
266
+ Button,
267
+ {
268
+ variant: "ghost",
269
+ size: "sm",
270
+ disabled: !ok,
271
+ "data-active": active || void 0,
272
+ "aria-pressed": active,
273
+ className: "justify-start data-active:bg-muted data-active:text-foreground",
274
+ onClick: () => {
275
+ setDraft(p.range);
276
+ setMonth(lastMonth(p.range));
277
+ },
278
+ children: p.label
279
+ },
280
+ p.label
281
+ );
282
+ })
283
+ }
284
+ ) : null,
285
+ /* @__PURE__ */ jsx(
286
+ Calendar,
287
+ {
288
+ ...intl,
289
+ mode: "range",
290
+ resetOnSelect: true,
291
+ numberOfMonths,
292
+ month,
293
+ onMonthChange: setMonth,
294
+ startMonth: min,
295
+ endMonth: max,
296
+ selected: draft,
297
+ onSelect: (r) => setDraft(r),
298
+ disabled: disabledDays
299
+ }
300
+ )
301
+ ] }),
302
+ /* @__PURE__ */ jsxs(
303
+ "div",
304
+ {
305
+ "data-slot": "date-range-footer",
306
+ className: "flex flex-wrap items-center justify-end gap-2 border-t border-border p-(--ds-popover-p)",
307
+ children: [
308
+ maxSpan ? /* @__PURE__ */ jsx(
309
+ "p",
310
+ {
311
+ id: hintId,
312
+ "data-slot": "date-range-hint",
313
+ "data-state": overSpan ? "error" : "idle",
314
+ "aria-live": "polite",
315
+ className: "me-auto text-xs text-muted-foreground data-[state=error]:text-danger",
316
+ children: dsFormat(t.dateMaxSpan, { n: maxSpan })
317
+ }
318
+ ) : null,
319
+ /* @__PURE__ */ jsx(
320
+ Button,
321
+ {
322
+ variant: "ghost",
323
+ size: "sm",
324
+ onClick: () => {
325
+ setDraft(void 0);
326
+ onChange?.(void 0);
327
+ setOpen(false);
328
+ },
329
+ children: t.dateClear
330
+ }
331
+ ),
332
+ /* @__PURE__ */ jsx(
333
+ Button,
334
+ {
335
+ size: "sm",
336
+ disabled: !canApply,
337
+ "aria-describedby": maxSpan ? hintId : void 0,
338
+ onClick: () => {
339
+ if (!draft?.from) return;
340
+ onChange?.({ from: draft.from, to: draft.to ?? draft.from });
341
+ setOpen(false);
342
+ },
343
+ children: t.dateApply
344
+ }
345
+ )
346
+ ]
347
+ }
348
+ )
349
+ ]
350
+ }
351
+ )
352
+ ]
353
+ }
354
+ )
355
+ }
356
+ );
357
+ }
358
+ export {
359
+ DatePicker,
360
+ DateRangePicker,
361
+ defaultDatePresets
362
+ };
@@ -0,0 +1,42 @@
1
+ import * as React from 'react';
2
+
3
+ type DropzoneRejectReason = "too-large" | "wrong-type" | "too-many";
4
+ type DropzoneRejection = {
5
+ file: File;
6
+ reason: DropzoneRejectReason;
7
+ /** Texto del motivo en el idioma activo (vacío si falta su texto en el catálogo). */
8
+ message: string;
9
+ };
10
+ type DropzoneState = "idle" | "drag-over" | "error" | "disabled";
11
+ /** Tamaño legible en el idioma activo: 10485760 → «10 MB». */
12
+ declare function formatBytes(bytes: number, locale: string): string;
13
+ declare function Dropzone({ className, accept, maxSize, maxFiles, multiple, disabled, invalid, onFiles, onReject, title, hint, description, icon, children, id, name, ...props }: Omit<React.ComponentProps<"div">, "title"> & {
14
+ /** Tipos admitidos, con la sintaxis de `<input accept>`: «.pdf,image/*». */
15
+ accept?: string;
16
+ /** Tamaño máximo por fichero, en bytes. */
17
+ maxSize?: number;
18
+ /** Número máximo de ficheros por entrega (con `multiple`). */
19
+ maxFiles?: number;
20
+ multiple?: boolean;
21
+ disabled?: boolean;
22
+ /** Fuerza el estado de error (p. ej. un campo obligatorio vacío). */
23
+ invalid?: boolean;
24
+ /** Ficheros aceptados. */
25
+ onFiles?: (files: File[]) => void;
26
+ /** Ficheros rechazados, con su motivo. */
27
+ onReject?: (rejections: DropzoneRejection[]) => void;
28
+ /** Título; por defecto, el del idioma activo. */
29
+ title?: React.ReactNode;
30
+ /** Pista bajo el título; por defecto, «o haz clic para buscarlos». */
31
+ hint?: React.ReactNode;
32
+ /** Texto de la app (p. ej. «CSV, hasta 10 MB»). */
33
+ description?: React.ReactNode;
34
+ /** Icono de la baldosa; por defecto, subir. */
35
+ icon?: React.ReactNode;
36
+ /** id del `input type=file`. */
37
+ id?: string;
38
+ /** name del `input type=file` (formularios). */
39
+ name?: string;
40
+ }): React.JSX.Element;
41
+
42
+ export { Dropzone, type DropzoneRejectReason, type DropzoneRejection, type DropzoneState, formatBytes };
@@ -0,0 +1,220 @@
1
+ "use client";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { UploadIcon } from "lucide-react";
4
+ import * as React from "react";
5
+ import { useDsLocale, useDsMessages } from "../hooks/use-ds-messages";
6
+ import { dsFormat } from "../lib/i18n";
7
+ import { cn } from "../lib/utils";
8
+ import { IconTile } from "./icon-tile";
9
+ function formatBytes(bytes, locale) {
10
+ const units = ["byte", "kilobyte", "megabyte", "gigabyte"];
11
+ let value = bytes;
12
+ let i = 0;
13
+ while (value >= 1024 && i < units.length - 1) {
14
+ value /= 1024;
15
+ i++;
16
+ }
17
+ try {
18
+ return new Intl.NumberFormat(locale, {
19
+ style: "unit",
20
+ unit: units[i],
21
+ unitDisplay: "short",
22
+ maximumFractionDigits: 1
23
+ }).format(value);
24
+ } catch {
25
+ return String(bytes);
26
+ }
27
+ }
28
+ function matchesAccept(file, accept) {
29
+ if (!accept) return true;
30
+ const name = file.name.toLowerCase();
31
+ const type = file.type.toLowerCase();
32
+ return accept.split(",").map((a) => a.trim().toLowerCase()).filter(Boolean).some((rule) => {
33
+ if (rule.startsWith(".")) return name.endsWith(rule);
34
+ if (rule.endsWith("/*")) return type.startsWith(rule.slice(0, -1));
35
+ return type === rule;
36
+ });
37
+ }
38
+ function Dropzone({
39
+ className,
40
+ accept,
41
+ maxSize,
42
+ maxFiles,
43
+ multiple = true,
44
+ disabled = false,
45
+ invalid = false,
46
+ onFiles,
47
+ onReject,
48
+ title,
49
+ hint,
50
+ description,
51
+ icon,
52
+ children,
53
+ id,
54
+ name,
55
+ ...props
56
+ }) {
57
+ const t = useDsMessages();
58
+ const locale = useDsLocale();
59
+ const autoId = React.useId();
60
+ const inputId = id ?? `${autoId}-input`;
61
+ const hintId = `${autoId}-hint`;
62
+ const errorsId = `${autoId}-errors`;
63
+ const [dragOver, setDragOver] = React.useState(false);
64
+ const [rejections, setRejections] = React.useState([]);
65
+ const dragDepth = React.useRef(0);
66
+ const state = disabled ? "disabled" : dragOver ? "drag-over" : invalid || rejections.length ? "error" : "idle";
67
+ const tooMany = t.dropzoneTooMany;
68
+ const handle = (list) => {
69
+ if (disabled || !list) return;
70
+ const accepted = [];
71
+ const rejected = [];
72
+ const limit = multiple ? maxFiles : 1;
73
+ for (const file of Array.from(list)) {
74
+ const vars = { name: file.name };
75
+ if (!matchesAccept(file, accept)) {
76
+ rejected.push({
77
+ file,
78
+ reason: "wrong-type",
79
+ message: dsFormat(t.dropzoneWrongType, vars)
80
+ });
81
+ } else if (maxSize != null && file.size > maxSize) {
82
+ rejected.push({
83
+ file,
84
+ reason: "too-large",
85
+ message: dsFormat(t.dropzoneTooLarge, {
86
+ ...vars,
87
+ max: formatBytes(maxSize, locale)
88
+ })
89
+ });
90
+ } else if (limit != null && accepted.length >= limit) {
91
+ rejected.push({
92
+ file,
93
+ reason: "too-many",
94
+ message: tooMany ? dsFormat(tooMany, { ...vars, n: limit }) : ""
95
+ });
96
+ } else {
97
+ accepted.push(file);
98
+ }
99
+ }
100
+ setRejections(rejected);
101
+ if (accepted.length) onFiles?.(accepted);
102
+ if (rejected.length) onReject?.(rejected);
103
+ };
104
+ const visibleErrors = rejections.filter((r) => r.message);
105
+ return /* @__PURE__ */ jsxs(
106
+ "div",
107
+ {
108
+ "data-slot": "dropzone",
109
+ "data-state": state,
110
+ className: cn("flex w-full flex-col gap-2", className),
111
+ ...props,
112
+ children: [
113
+ /* @__PURE__ */ jsxs(
114
+ "label",
115
+ {
116
+ htmlFor: inputId,
117
+ "data-slot": "dropzone-area",
118
+ "data-state": state,
119
+ onDragEnter: (e) => {
120
+ if (disabled) return;
121
+ e.preventDefault();
122
+ dragDepth.current += 1;
123
+ setDragOver(true);
124
+ },
125
+ onDragOver: (e) => {
126
+ if (disabled) return;
127
+ e.preventDefault();
128
+ e.dataTransfer.dropEffect = "copy";
129
+ },
130
+ onDragLeave: (e) => {
131
+ if (disabled) return;
132
+ e.preventDefault();
133
+ dragDepth.current = Math.max(0, dragDepth.current - 1);
134
+ if (dragDepth.current === 0) setDragOver(false);
135
+ },
136
+ onDrop: (e) => {
137
+ if (disabled) return;
138
+ e.preventDefault();
139
+ dragDepth.current = 0;
140
+ setDragOver(false);
141
+ handle(e.dataTransfer.files);
142
+ },
143
+ className: cn(
144
+ "flex cursor-pointer flex-col items-center justify-center gap-2 rounded-card border-(length:--ds-rule-w) border-dashed border-border bg-(--ds-field-bg) p-(--ds-dropzone-p) text-center text-sm transition-colors duration-(--ds-motion-snap) hover:bg-muted/50",
145
+ "has-[input:focus-visible]:border-ring has-[input:focus-visible]:ring-(length:--ds-ring-width) has-[input:focus-visible]:ring-(--ds-ring-color)",
146
+ "data-[state=drag-over]:border-primary data-[state=drag-over]:bg-accent data-[state=drag-over]:text-accent-foreground",
147
+ "data-[state=error]:border-danger data-[state=error]:bg-danger-soft",
148
+ "data-[state=disabled]:cursor-not-allowed data-[state=disabled]:opacity-(--ds-disabled-opacity) data-[state=disabled]:hover:bg-(--ds-field-bg)"
149
+ ),
150
+ children: [
151
+ /* @__PURE__ */ jsx(
152
+ "input",
153
+ {
154
+ id: inputId,
155
+ name,
156
+ type: "file",
157
+ className: "sr-only",
158
+ accept,
159
+ multiple,
160
+ disabled,
161
+ "aria-describedby": [children ? "" : hintId, visibleErrors.length ? errorsId : ""].filter(Boolean).join(" ") || void 0,
162
+ "aria-invalid": state === "error" || void 0,
163
+ onChange: (e) => {
164
+ handle(e.currentTarget.files);
165
+ e.currentTarget.value = "";
166
+ }
167
+ }
168
+ ),
169
+ children ?? /* @__PURE__ */ jsxs(Fragment, { children: [
170
+ /* @__PURE__ */ jsx(
171
+ IconTile,
172
+ {
173
+ "data-slot": "dropzone-icon",
174
+ tone: state === "error" ? "danger" : "neutral",
175
+ size: "md",
176
+ children: icon ?? /* @__PURE__ */ jsx(UploadIcon, {})
177
+ }
178
+ ),
179
+ /* @__PURE__ */ jsx(
180
+ "span",
181
+ {
182
+ "data-slot": "dropzone-title",
183
+ className: "font-(--ds-label-weight) text-foreground",
184
+ children: title ?? t.dropzoneTitle
185
+ }
186
+ ),
187
+ /* @__PURE__ */ jsxs(
188
+ "span",
189
+ {
190
+ id: hintId,
191
+ "data-slot": "dropzone-hint",
192
+ className: "flex flex-col gap-0.5 text-muted-foreground",
193
+ children: [
194
+ /* @__PURE__ */ jsx("span", { children: hint ?? t.dropzoneHint }),
195
+ description ? /* @__PURE__ */ jsx("span", { "data-slot": "dropzone-description", className: "text-xs", children: description }) : null
196
+ ]
197
+ }
198
+ )
199
+ ] })
200
+ ]
201
+ }
202
+ ),
203
+ /* @__PURE__ */ jsx(
204
+ "ul",
205
+ {
206
+ id: errorsId,
207
+ "data-slot": "dropzone-errors",
208
+ "aria-live": "polite",
209
+ className: "flex flex-col gap-1 text-start text-xs text-danger empty:hidden",
210
+ children: visibleErrors.map((r, i) => /* @__PURE__ */ jsx("li", { children: r.message }, `${r.file.name}-${i}`))
211
+ }
212
+ )
213
+ ]
214
+ }
215
+ );
216
+ }
217
+ export {
218
+ Dropzone,
219
+ formatBytes
220
+ };