@camunda/design-system 0.76.0 → 0.78.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 (44) hide show
  1. package/dist/src/components/ui/accordion.d.ts +36 -0
  2. package/dist/src/components/ui/accordion.d.ts.map +1 -0
  3. package/dist/src/components/ui/accordion.js +34 -0
  4. package/dist/src/components/ui/accordion.js.map +1 -0
  5. package/dist/src/components/ui/alert-dialog.d.ts.map +1 -1
  6. package/dist/src/components/ui/alert-dialog.js +6 -3
  7. package/dist/src/components/ui/alert-dialog.js.map +1 -1
  8. package/dist/src/components/ui/calendar.d.ts +1 -1
  9. package/dist/src/components/ui/calendar.d.ts.map +1 -1
  10. package/dist/src/components/ui/calendar.js +74 -8
  11. package/dist/src/components/ui/calendar.js.map +1 -1
  12. package/dist/src/components/ui/date-range-picker.d.ts.map +1 -1
  13. package/dist/src/components/ui/date-range-picker.js +9 -6
  14. package/dist/src/components/ui/date-range-picker.js.map +1 -1
  15. package/dist/src/components/ui/date-time-range-picker.d.ts +66 -0
  16. package/dist/src/components/ui/date-time-range-picker.d.ts.map +1 -0
  17. package/dist/src/components/ui/date-time-range-picker.js +606 -0
  18. package/dist/src/components/ui/date-time-range-picker.js.map +1 -0
  19. package/dist/src/components/ui/dialog.d.ts.map +1 -1
  20. package/dist/src/components/ui/dialog.js +6 -3
  21. package/dist/src/components/ui/dialog.js.map +1 -1
  22. package/dist/src/components/ui/popover.d.ts +2 -2
  23. package/dist/src/components/ui/popover.d.ts.map +1 -1
  24. package/dist/src/components/ui/popover.js +4 -2
  25. package/dist/src/components/ui/popover.js.map +1 -1
  26. package/dist/src/hooks/use-overlay-backdrop.d.ts +8 -0
  27. package/dist/src/hooks/use-overlay-backdrop.d.ts.map +1 -0
  28. package/dist/src/hooks/use-overlay-backdrop.js +12 -0
  29. package/dist/src/hooks/use-overlay-backdrop.js.map +1 -0
  30. package/dist/src/index.d.ts +3 -0
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +3 -0
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/lib/backdrop-blur.d.ts +128 -0
  35. package/dist/src/lib/backdrop-blur.d.ts.map +1 -0
  36. package/dist/src/lib/backdrop-blur.js +468 -0
  37. package/dist/src/lib/backdrop-blur.js.map +1 -0
  38. package/dist/src/lib/i18n/dictionary.d.ts +25 -0
  39. package/dist/src/lib/i18n/dictionary.d.ts.map +1 -1
  40. package/dist/src/lib/i18n/dictionary.js +24 -0
  41. package/dist/src/lib/i18n/dictionary.js.map +1 -1
  42. package/dist/styles.css +200 -19
  43. package/dist/theme.css +17 -0
  44. package/package.json +2 -2
@@ -0,0 +1,606 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { endOfDay, format as formatDate, isAfter, isBefore, isSameDay, isSameYear, isValid, parse, parseISO, setSeconds, addMonths, startOfDay, startOfMonth, subMonths, subMinutes, } from "date-fns";
5
+ import { CalendarIcon, XIcon } from "../../icons/lucide.js";
6
+ import { cn } from "../../lib/utils.js";
7
+ import { withRef } from "../../lib/with-ref.js";
8
+ import { useIsTruncated } from "../../hooks/use-is-truncated.js";
9
+ import { useMediaQuery } from "../../hooks/use-media-query.js";
10
+ import { useC4Dictionary } from "../../lib/i18n/context.js";
11
+ import { Button } from "./button.js";
12
+ import { Calendar } from "./calendar.js";
13
+ import { Input } from "./input.js";
14
+ import { Label } from "./label.js";
15
+ import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger, } from "./popover.js";
16
+ import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip.js";
17
+ import { Text } from "./typography.js";
18
+ const DEFAULT_DATE_TIME_RANGE_PRESETS = [
19
+ { id: "5m", minutes: 5 },
20
+ { id: "15m", minutes: 15 },
21
+ { id: "30m", minutes: 30 },
22
+ { id: "1h", minutes: 60 },
23
+ { id: "3h", minutes: 180 },
24
+ { id: "6h", minutes: 360 },
25
+ { id: "12h", minutes: 720 },
26
+ { id: "24h", minutes: 1440 },
27
+ { id: "2d", minutes: 2880 },
28
+ { id: "7d", minutes: 10080 },
29
+ { id: "30d", minutes: 43200 },
30
+ ];
31
+ function getTimeConfig(timeFormat) {
32
+ const hasSeconds = timeFormat === "HH:mm:ss";
33
+ return { hasSeconds, inputFormat: timeFormat, step: hasSeconds ? 1 : 60 };
34
+ }
35
+ function defaultTimeFor(end, hasSeconds) {
36
+ if (end === "from")
37
+ return hasSeconds ? "00:00:00" : "00:00";
38
+ return hasSeconds ? "23:59:59" : "23:59";
39
+ }
40
+ // A minute-resolution "to" is the inclusive end of that minute.
41
+ function finalize(date, end, hasSeconds) {
42
+ if (hasSeconds)
43
+ return date;
44
+ const next = setSeconds(date, end === "to" ? 59 : 0);
45
+ next.setMilliseconds(0);
46
+ return next;
47
+ }
48
+ function withTime(day, end, hasSeconds, source) {
49
+ const next = new Date(day);
50
+ if (source) {
51
+ next.setHours(source.getHours(), source.getMinutes(), source.getSeconds(), source.getMilliseconds());
52
+ }
53
+ else {
54
+ const [h, m, s] = defaultTimeFor(end, hasSeconds).split(":").map(Number);
55
+ next.setHours(h ?? 0, m ?? 0, s ?? 0, 0);
56
+ }
57
+ return finalize(next, end, hasSeconds);
58
+ }
59
+ // The native inputs show the OS clock, so the trigger shows it too.
60
+ function formatClock(date, hasSeconds, locale) {
61
+ return new Intl.DateTimeFormat(locale, {
62
+ hour: "2-digit",
63
+ minute: "2-digit",
64
+ second: hasSeconds ? "2-digit" : undefined,
65
+ }).format(date);
66
+ }
67
+ // Same default locale as the trigger's date-fns "PP" format.
68
+ function formatDayMonth(date, locale) {
69
+ return new Intl.DateTimeFormat(locale?.code ?? "en-US", {
70
+ day: "numeric",
71
+ month: "short",
72
+ }).format(date);
73
+ }
74
+ function isOutOfRange(date, fromDate, toDate) {
75
+ return ((fromDate !== undefined && isBefore(date, startOfDay(fromDate))) ||
76
+ (toDate !== undefined && isAfter(date, endOfDay(toDate))));
77
+ }
78
+ function toRange(from, to) {
79
+ const range = {};
80
+ if (from)
81
+ range.from = from;
82
+ if (to)
83
+ range.to = to;
84
+ return range;
85
+ }
86
+ function isRangeValid(range, fromDate, toDate) {
87
+ const { from, to } = range;
88
+ return (from !== undefined &&
89
+ to !== undefined &&
90
+ isAfter(to, from) &&
91
+ !isOutOfRange(from, fromDate, toDate) &&
92
+ !isOutOfRange(to, fromDate, toDate));
93
+ }
94
+ function fill(template, values) {
95
+ return Object.entries(values).reduce((text, [key, value]) => text.replaceAll(`{${key}}`, value), template);
96
+ }
97
+ function getTimeZoneLabel(locale) {
98
+ const { timeZone } = Intl.DateTimeFormat().resolvedOptions();
99
+ const offset = new Intl.DateTimeFormat(locale?.code, {
100
+ timeZoneName: "longOffset",
101
+ })
102
+ .formatToParts(new Date())
103
+ .find(({ type }) => type === "timeZoneName")?.value;
104
+ return offset === undefined ? timeZone : `${timeZone} (${offset})`;
105
+ }
106
+ function getPresetLabel(preset, t) {
107
+ if (preset.label !== undefined)
108
+ return preset.label;
109
+ const { minutes } = preset;
110
+ if (minutes >= 2880 && minutes % 1440 === 0) {
111
+ return t("dateTimeRangePicker.lastDays", { count: minutes / 1440 });
112
+ }
113
+ if (minutes >= 60 && minutes % 60 === 0) {
114
+ return t("dateTimeRangePicker.lastHours", { count: minutes / 60 });
115
+ }
116
+ return t("dateTimeRangePicker.lastMinutes", { count: minutes });
117
+ }
118
+ function TimeField({ id, label, end, date, timeFormat, showTimePickerIcon, locale, disabled, error, describedBy, emptyHint, onCommit, }) {
119
+ const { hasSeconds, inputFormat, step } = getTimeConfig(timeFormat);
120
+ const errorId = `${id}-error`;
121
+ const hintId = `${id}-hint`;
122
+ // Keeps a half-typed time (the browser reports "") from being overwritten.
123
+ const [typed, setTyped] = React.useState();
124
+ const commit = (value) => {
125
+ const match = /^(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(value);
126
+ if (!match || !date)
127
+ return;
128
+ const next = new Date(date);
129
+ next.setHours(Number(match[1]), Number(match[2]), Number(match[3] ?? 0), 0);
130
+ onCommit(finalize(next, end, hasSeconds));
131
+ };
132
+ return (_jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1.5", "data-slot": "date-time-range-picker-time", children: [_jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [_jsx(Label, { htmlFor: id, children: label }), date ? (_jsx(Text, { as: "span", variant: "helper", children: formatDayMonth(date, locale) })) : null] }), _jsx(Input, { id: id, type: "time", autoComplete: "off", step: step, disabled: disabled || !date, className: cn(!showTimePickerIcon &&
133
+ "[&::-webkit-calendar-picker-indicator]:hidden"), value: typed ?? (date ? formatDate(date, inputFormat) : ""), "aria-invalid": error !== undefined, "aria-describedby": [error ? errorId : undefined, date ? undefined : hintId, describedBy]
134
+ .filter(Boolean)
135
+ .join(" ") || undefined, onBlur: () => setTyped(undefined), onChange: (event) => {
136
+ setTyped(event.target.value);
137
+ commit(event.target.value);
138
+ } }), date ? null : (_jsx(Text, { as: "p", id: hintId, variant: "helper", children: emptyHint })), error ? (_jsx(Text, { as: "p", id: errorId, role: "alert", variant: "helper", className: "text-danger-foreground-subtle", children: error })) : null] }));
139
+ }
140
+ const DATE_TIME_LOCAL_PARTS = "yyyy-MM-dd'T'";
141
+ // Browsers omit the seconds from a datetime-local value when they are zero.
142
+ function parseDateTimeLocal(text) {
143
+ const parsed = parse(text, text.length > 16
144
+ ? `${DATE_TIME_LOCAL_PARTS}HH:mm:ss`
145
+ : `${DATE_TIME_LOCAL_PARTS}HH:mm`, new Date());
146
+ return isValid(parsed) ? parsed : undefined;
147
+ }
148
+ // A native `datetime-local` field: arrow keys step each segment, and the
149
+ // browser rejects malformed text, so only range checks remain. Its own picker
150
+ // icon is hidden because the popover is the picker.
151
+ function RangeInput({ id, label, end, date, timeFormat, fromDate, toDate, disabled, outOfRangeMessage, invalidYearMessage, resetKey, rangeError, rangeErrorText, onCommit, onRejectedChange, onOpenRequest, onFocusPopover, tabIntoPopover, popup, }) {
152
+ const [typed, setTyped] = React.useState();
153
+ // Text typed before the last reset is stale.
154
+ const draft = typed?.key === resetKey ? typed.text : undefined;
155
+ const setDraft = (text) => setTyped(text === undefined ? undefined : { text, key: resetKey });
156
+ const { hasSeconds, inputFormat, step } = getTimeConfig(timeFormat);
157
+ const valueFormat = `${DATE_TIME_LOCAL_PARTS}${inputFormat}`;
158
+ const candidate = draft ? parseDateTimeLocal(draft) : undefined;
159
+ // A fifth year digit never parses, so flag it instead of reverting on blur.
160
+ const hasOversizedYear = draft !== undefined && /^\d{5,}-/.test(draft);
161
+ const isOutside = hasOversizedYear ||
162
+ (candidate !== undefined && isOutOfRange(candidate, fromDate, toDate));
163
+ React.useEffect(() => {
164
+ onRejectedChange?.(end, isOutside);
165
+ }, [end, isOutside, onRejectedChange]);
166
+ return (_jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1.5", children: [_jsx(Label, { htmlFor: id, children: label }), _jsx(Input, { id: id, type: "datetime-local", autoComplete: "off", step: step, min: fromDate ? formatDate(startOfDay(fromDate), valueFormat) : undefined, max: toDate ? formatDate(endOfDay(toDate), valueFormat) : undefined, disabled: disabled, className: "w-full [&::-webkit-calendar-picker-indicator]:hidden", value: draft ?? (date ? formatDate(date, valueFormat) : ""), "aria-invalid": isOutside || rangeError, invalidText: hasOversizedYear
167
+ ? invalidYearMessage
168
+ : isOutside
169
+ ? outOfRangeMessage
170
+ : rangeErrorText, announceInvalidText: true, "aria-haspopup": popup ? "dialog" : undefined, "aria-controls": popup?.open ? popup.controls : undefined, onClick: () => onOpenRequest?.(false, id), onKeyDown: (event) => {
171
+ // Keyboard route into the popover when no calendar button is shown.
172
+ if (event.altKey && event.key === "ArrowDown" && onOpenRequest) {
173
+ event.preventDefault();
174
+ if (popup?.open)
175
+ onFocusPopover?.(id);
176
+ else
177
+ onOpenRequest(true, id);
178
+ }
179
+ if (tabIntoPopover && event.key === "Tab" && !event.shiftKey) {
180
+ const field = event.currentTarget;
181
+ // Runs after the browser moved focus: only redirect once it left the field.
182
+ setTimeout(() => {
183
+ if (document.activeElement !== field)
184
+ onFocusPopover?.(id);
185
+ }, 0);
186
+ }
187
+ }, onPaste: (event) => {
188
+ // Native date-time fields ignore pasted text, so accept ISO 8601 here.
189
+ const pasted = parseISO(event.clipboardData.getData("text").trim());
190
+ if (!isValid(pasted))
191
+ return;
192
+ event.preventDefault();
193
+ setDraft(undefined);
194
+ const next = finalize(pasted, end, hasSeconds);
195
+ if (isOutOfRange(next, fromDate, toDate)) {
196
+ setDraft(formatDate(next, valueFormat));
197
+ }
198
+ else {
199
+ onCommit(next);
200
+ }
201
+ }, onBlur: () => {
202
+ if (!isOutside)
203
+ setDraft(undefined);
204
+ }, onChange: (event) => {
205
+ const text = event.target.value;
206
+ // An incomplete entry reports "" with badInput; keep waiting for the rest.
207
+ if (text === "" && event.target.validity.badInput) {
208
+ setDraft("");
209
+ return;
210
+ }
211
+ setDraft(text);
212
+ if (text === "") {
213
+ onCommit(undefined);
214
+ return;
215
+ }
216
+ const next = parseDateTimeLocal(text);
217
+ // Skip partial years (0002, 0020, ...) while the year is being typed.
218
+ if (next &&
219
+ next.getFullYear() >= 1000 &&
220
+ next.getFullYear() <= 9999 &&
221
+ !isOutOfRange(next, fromDate, toDate)) {
222
+ onCommit(finalize(next, end, hasSeconds));
223
+ }
224
+ } })] }));
225
+ }
226
+ function mergeRefs(...refs) {
227
+ return (node) => {
228
+ for (const ref of refs) {
229
+ if (typeof ref === "function")
230
+ ref(node);
231
+ else if (ref)
232
+ ref.current = node;
233
+ }
234
+ };
235
+ }
236
+ function DateTimeRangePickerImpl({ ref, value, defaultValue, onChange, label, timeFormat = "HH:mm:ss", presets, showTimeZone = true, showTimePickerIcon = false, showApplyButton = false, showInputs = false, showCalendarButton: showCalendarButtonProp = false, fromDate, toDate, locale, disabled = false, messages, id, className, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, }) {
237
+ const { t } = useC4Dictionary();
238
+ const generatedId = React.useId();
239
+ const baseId = id ?? generatedId;
240
+ const headingId = `${baseId}-label`;
241
+ const [internalValue, setInternalValue] = React.useState(defaultValue);
242
+ const [open, setOpen] = React.useState(false);
243
+ const [pending, setPending] = React.useState();
244
+ const [pendingPresetId, setPendingPresetId] = React.useState();
245
+ const [lastPreset, setLastPreset] = React.useState();
246
+ const [month, setMonth] = React.useState();
247
+ const [inputsResetKey, setInputsResetKey] = React.useState(0);
248
+ const [keyboardOpen, setKeyboardOpen] = React.useState(false);
249
+ const [typingOpen, setTypingOpen] = React.useState(false);
250
+ const isNarrow = useMediaQuery("(width < 40rem)");
251
+ // Phone browsers open their own date-time picker from the fields, so the
252
+ // popover gets its own button there instead of opening from the fields.
253
+ const isCoarsePointer = useMediaQuery("(pointer: coarse)");
254
+ const { ref: labelRef, isTruncated: isLabelTruncated, measure: measureLabel, } = useIsTruncated();
255
+ // The room the trigger has can change without a label change.
256
+ React.useLayoutEffect(() => {
257
+ measureLabel();
258
+ });
259
+ const showCalendarButton = showCalendarButtonProp || (showInputs && isCoarsePointer);
260
+ const groupRef = React.useRef(null);
261
+ const calendarButtonRef = React.useRef(null);
262
+ const contentRef = React.useRef(null);
263
+ const closedByOutsideRef = React.useRef(false);
264
+ const openerIdRef = React.useRef(undefined);
265
+ const presetsRef = React.useRef(null);
266
+ const [presetsFade, setPresetsFade] = React.useState(false);
267
+ const isControlled = value !== undefined;
268
+ const committed = isControlled ? value : internalValue;
269
+ const { hasSeconds } = getTimeConfig(timeFormat);
270
+ const emit = (next, presetId) => {
271
+ if (!isControlled)
272
+ setInternalValue(next);
273
+ const info = {
274
+ isValid: isRangeValid(next, fromDate, toDate),
275
+ };
276
+ if (presetId !== undefined)
277
+ info.presetId = presetId;
278
+ setLastPreset(presetId !== undefined && next.from && next.to
279
+ ? { id: presetId, from: next.from.getTime(), to: next.to.getTime() }
280
+ : undefined);
281
+ onChange?.(next, info);
282
+ };
283
+ // The quick range stays marked while the committed range still equals it.
284
+ const committedPresetId = lastPreset &&
285
+ committed?.from?.getTime() === lastPreset.from &&
286
+ committed.to?.getTime() === lastPreset.to
287
+ ? lastPreset.id
288
+ : undefined;
289
+ // With the apply button the popover edits a draft; Apply commits it.
290
+ const current = showApplyButton && open ? (pending ?? committed) : committed;
291
+ const setDraft = (range, presetId) => {
292
+ setPending(range);
293
+ setPendingPresetId(presetId);
294
+ };
295
+ const update = showApplyButton ? setDraft : emit;
296
+ const draftChanged = pending?.from?.getTime() !== committed?.from?.getTime() ||
297
+ pending?.to?.getTime() !== committed?.to?.getTime();
298
+ // With the apply button, typed inputs always edit the draft (so fields and
299
+ // calendar agree); typing while closed opens the popover so Apply is in view.
300
+ const inputRange = current;
301
+ const inputUpdate = update;
302
+ // Keep the calendar showing the end that was typed.
303
+ const monthCount = isNarrow ? 1 : 2;
304
+ const [rejectedEnds, setRejectedEnds] = React.useState({
305
+ from: false,
306
+ to: false,
307
+ });
308
+ const handleRejectedChange = React.useCallback((end, rejected) => setRejectedEnds((prev) => prev[end] === rejected ? prev : { ...prev, [end]: rejected }), []);
309
+ const showInCalendar = (date, end, shown = month ?? current?.from) => {
310
+ if (!date)
311
+ return;
312
+ const first = shown ?? new Date();
313
+ const visible = !isBefore(date, startOfMonth(first)) &&
314
+ isBefore(date, startOfMonth(addMonths(first, monthCount)));
315
+ if (!visible)
316
+ setMonth(end === "to" ? subMonths(date, monthCount - 1) : date);
317
+ };
318
+ const updateInputs = (range, end) => {
319
+ const typed = range[end === "from" ? "from" : "to"];
320
+ if (showApplyButton && !open) {
321
+ openerIdRef.current = `${baseId}-${end === "from" ? "start" : "end"}`;
322
+ setKeyboardOpen(false);
323
+ // Opening repositions the calendar on the saved range; place the typed
324
+ // date relative to that, after it.
325
+ handleOpenChange(true);
326
+ showInCalendar(typed, end, committed?.from);
327
+ setTypingOpen(true);
328
+ }
329
+ else {
330
+ showInCalendar(typed, end);
331
+ }
332
+ inputUpdate(range);
333
+ };
334
+ // Typed text that never reached the draft must not outlive the popover.
335
+ const closePopover = () => {
336
+ setInputsResetKey((key) => key + 1);
337
+ setOpen(false);
338
+ };
339
+ const handleOpenChange = (next) => {
340
+ if (next) {
341
+ setTypingOpen(false);
342
+ setDraft(committed ?? {}, committedPresetId);
343
+ setMonth(committed?.from);
344
+ }
345
+ else {
346
+ setInputsResetKey((key) => key + 1);
347
+ }
348
+ setOpen(next);
349
+ };
350
+ const apply = () => {
351
+ // An emptied draft saves "no range", so a saved range can be removed.
352
+ emit(pending ?? {}, pendingPresetId);
353
+ closePopover();
354
+ };
355
+ const handleSelect = (range, triggerDate) => {
356
+ setInputsResetKey((key) => key + 1);
357
+ // `min={1}` makes react-day-picker clear the selection when the second
358
+ // click lands on the same day as `from`; commit a one-day range instead
359
+ // (same workaround as DateRangePicker, issue #593).
360
+ // A click on a complete range starts a new one rather than extending it.
361
+ const nextRange = current?.from && current.to
362
+ ? { from: triggerDate, to: undefined }
363
+ : !range && current?.from && isSameDay(current.from, triggerDate)
364
+ ? { from: current.from, to: triggerDate }
365
+ : range;
366
+ update(toRange(nextRange?.from &&
367
+ withTime(nextRange.from, "from", hasSeconds, current?.from), nextRange?.to && withTime(nextRange.to, "to", hasSeconds, current?.to)));
368
+ };
369
+ const handlePreset = (preset) => {
370
+ const now = new Date();
371
+ const next = {
372
+ from: finalize(subMinutes(now, preset.minutes), "from", hasSeconds),
373
+ to: finalize(now, "to", hasSeconds),
374
+ };
375
+ setInputsResetKey((key) => key + 1);
376
+ setMonth(next.from);
377
+ if (showApplyButton) {
378
+ setDraft(next, preset.id);
379
+ }
380
+ else {
381
+ emit(next, preset.id);
382
+ closePopover();
383
+ }
384
+ };
385
+ const timeZone = getTimeZoneLabel(locale);
386
+ const defaults = {
387
+ placeholder: t("dateTimeRangePicker.pickDateTimeRange"),
388
+ fromTime: t("dateTimeRangePicker.fromTime"),
389
+ toTime: t("dateTimeRangePicker.toTime"),
390
+ endBeforeStart: "",
391
+ quickRanges: t("dateTimeRangePicker.quickRanges"),
392
+ timeZone: t("dateTimeRangePicker.timeZone", { timeZone }),
393
+ apply: t("dateTimeRangePicker.apply"),
394
+ cancel: t("dateTimeRangePicker.cancel"),
395
+ clear: t("dateTimeRangePicker.clear"),
396
+ clearRange: t("dateTimeRangePicker.clearRange"),
397
+ selectEndDate: t("dateTimeRangePicker.selectEndDate"),
398
+ pickDayFirst: t("dateTimeRangePicker.pickDayFirst"),
399
+ pickEndDay: t("dateTimeRangePicker.pickEndDay"),
400
+ applyNeedsRange: t("dateTimeRangePicker.applyNeedsRange"),
401
+ openCalendar: t("dateTimeRangePicker.openCalendar"),
402
+ startInput: t("dateTimeRangePicker.startInput"),
403
+ endInput: t("dateTimeRangePicker.endInput"),
404
+ outOfRange: "",
405
+ };
406
+ const text = (key) => messages?.[key] ?? defaults[key];
407
+ const endBeforeStartText = (endLabel, startLabel) => messages?.endBeforeStart !== undefined
408
+ ? fill(messages.endBeforeStart, { end: endLabel, start: startLabel })
409
+ : t("dateTimeRangePicker.endBeforeStart", {
410
+ end: endLabel,
411
+ start: startLabel.toLocaleLowerCase(locale?.code),
412
+ });
413
+ const formatBound = (date) => formatDate(date, "PP", { locale });
414
+ const outOfRangeText = messages?.outOfRange !== undefined
415
+ ? fill(messages.outOfRange, {
416
+ min: fromDate ? formatBound(fromDate) : "",
417
+ max: toDate ? formatBound(toDate) : "",
418
+ })
419
+ : t("dateTimeRangePicker.outOfRange", {
420
+ bound: fromDate && toDate ? "both" : fromDate ? "min" : "max",
421
+ min: fromDate ? formatBound(fromDate) : "",
422
+ max: toDate ? formatBound(toDate) : "",
423
+ });
424
+ const disabledMatcher = React.useMemo(() => {
425
+ const matchers = [];
426
+ if (fromDate)
427
+ matchers.push({ before: fromDate });
428
+ if (toDate)
429
+ matchers.push({ after: toDate });
430
+ return matchers.length > 0 ? matchers : undefined;
431
+ }, [fromDate, toDate]);
432
+ // Phones get a shorter label (no seconds, year only when not this year) so
433
+ // the end of the range stays visible.
434
+ const formatEnd = (date) => isNarrow
435
+ ? `${formatDate(date, isSameYear(date, new Date()) ? "MMM d" : "PP", { locale })} ${formatClock(date, false, locale?.code)}`
436
+ : `${formatDate(date, "PP", { locale })} ${formatClock(date, hasSeconds, locale?.code)}`;
437
+ const triggerLabel = !committed?.from
438
+ ? text("placeholder")
439
+ : committed.to
440
+ ? `${formatEnd(committed.from)} – ${formatEnd(committed.to)}`
441
+ : `${formatEnd(committed.from)} – ${text("selectEndDate")}`;
442
+ const isEndBeforeStart = current?.from !== undefined &&
443
+ current.to !== undefined &&
444
+ !isAfter(current.to, current.from);
445
+ // Hide quick ranges that would reach outside fromDate / toDate.
446
+ const now = new Date();
447
+ const availablePresets = (presets ?? []).filter((preset) => !isOutOfRange(subMinutes(now, preset.minutes), fromDate, toDate) &&
448
+ !isOutOfRange(now, fromDate, toDate));
449
+ const activePresetId = showApplyButton && open ? pendingPresetId : committedPresetId;
450
+ const hasPresets = availablePresets.length > 0;
451
+ const contentId = `${baseId}-content`;
452
+ const presetsHeadingId = `${baseId}-presets`;
453
+ const applyHintId = `${baseId}-apply-hint`;
454
+ const timeZoneId = `${baseId}-time-zone`;
455
+ const startLabel = text("startInput");
456
+ const endLabel = text("endInput");
457
+ const triggerId = `${baseId}-trigger`;
458
+ const labelledBy = label
459
+ ? `${headingId} ${triggerId}`
460
+ : (ariaLabelledBy ?? undefined);
461
+ const committedReversed = committed?.from !== undefined &&
462
+ committed.to !== undefined &&
463
+ !isAfter(committed.to, committed.from);
464
+ const showClearButton = !disabled && !!committed?.from;
465
+ const reversedId = `${baseId}-reversed`;
466
+ // Fade the right edge of the narrow quick-range row while more remain.
467
+ const updatePresetsFade = () => {
468
+ const list = presetsRef.current;
469
+ setPresetsFade(list !== null &&
470
+ list.scrollLeft + list.clientWidth < list.scrollWidth - 1);
471
+ };
472
+ React.useEffect(() => {
473
+ if (open)
474
+ requestAnimationFrame(updatePresetsFade);
475
+ }, [open, isNarrow]);
476
+ const focusCalendarDay = () => {
477
+ const content = contentRef.current;
478
+ (content?.querySelector('[role="grid"] button[tabindex="0"]') ?? content?.querySelector("button:not([disabled])"))?.focus();
479
+ };
480
+ const handleClear = () => {
481
+ setInputsResetKey((key) => key + 1);
482
+ update({});
483
+ // Clear disables itself in apply mode; keep focus inside the popover.
484
+ if (showApplyButton)
485
+ focusCalendarDay();
486
+ if (!showApplyButton)
487
+ closePopover();
488
+ };
489
+ const clearsCommitted = !current?.from &&
490
+ !current?.to &&
491
+ (committed?.from !== undefined || committed?.to !== undefined);
492
+ const draftOutOfBounds = !!current?.from &&
493
+ !!current.to &&
494
+ (isOutOfRange(current.from, fromDate, toDate) ||
495
+ isOutOfRange(current.to, fromDate, toDate));
496
+ const needsRange = clearsCommitted ? false : !current?.from || !current.to;
497
+ const timeProps = {
498
+ timeFormat,
499
+ showTimePickerIcon,
500
+ locale,
501
+ disabled,
502
+ describedBy: showTimeZone ? timeZoneId : undefined,
503
+ };
504
+ const opensFromInputs = showInputs && !showCalendarButton;
505
+ const calendarIcon = (_jsx(CalendarIcon, { className: "size-4 shrink-0 opacity-60", "aria-hidden": "true" }));
506
+ const inputProps = {
507
+ timeFormat,
508
+ fromDate,
509
+ toDate,
510
+ disabled,
511
+ resetKey: inputsResetKey,
512
+ onRejectedChange: handleRejectedChange,
513
+ outOfRangeMessage: outOfRangeText,
514
+ invalidYearMessage: t("dateTimeRangePicker.invalidYear"),
515
+ onOpenRequest: opensFromInputs
516
+ ? (viaKeyboard, openerId) => {
517
+ openerIdRef.current = openerId;
518
+ setKeyboardOpen(viaKeyboard);
519
+ if (!open)
520
+ handleOpenChange(true);
521
+ }
522
+ : undefined,
523
+ onFocusPopover: opensFromInputs || showApplyButton
524
+ ? (openerId) => {
525
+ openerIdRef.current = openerId;
526
+ setKeyboardOpen(true);
527
+ focusCalendarDay();
528
+ }
529
+ : undefined,
530
+ popup: opensFromInputs ? { open, controls: contentId } : undefined,
531
+ };
532
+ const triggerButton = (_jsxs(Button, { ref: ref, onPointerEnter: measureLabel, onFocus: measureLabel, id: triggerId, variant: "secondary", disabled: disabled, "aria-label": labelledBy ? undefined : ariaLabel, "aria-labelledby": labelledBy, "aria-invalid": committedReversed || undefined, "aria-describedby": committedReversed ? reversedId : undefined, className: cn("w-full justify-between font-normal", isNarrow && "h-auto min-h-9 py-1.5", !committed?.from && "text-neutral-foreground-subtle", committedReversed && "border-danger-foreground-subtle"), "data-slot": "date-time-range-picker-trigger", children: [showCalendarButton ? calendarIcon : null, _jsx("span", { ref: labelRef, className: cn("min-w-0 flex-1 text-left", isNarrow ? "break-words whitespace-normal" : "truncate", showClearButton && "pr-8"), children: triggerLabel }), showCalendarButton ? null : calendarIcon] }));
533
+ // Tooltip only while the label is actually clipped.
534
+ const popoverTrigger = (_jsx(PopoverTrigger, { asChild: true, children: triggerButton }));
535
+ // Always mounted so the trigger is not remounted when the clipping changes.
536
+ const wrappedTrigger = (_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: popoverTrigger }), isLabelTruncated && !isNarrow ? (_jsx(TooltipContent, { children: triggerLabel })) : null] }));
537
+ const control = showInputs ? (_jsx(PopoverAnchor, { asChild: true, children: _jsxs("div", { ref: groupRef, role: "group", "aria-labelledby": label ? headingId : ariaLabelledBy, "aria-label": label || ariaLabelledBy ? undefined : ariaLabel, className: "flex items-start gap-2 max-[22rem]:flex-col", "data-slot": "date-time-range-picker-inputs", children: [showCalendarButton ? (_jsx(Button, { ref: mergeRefs(ref, calendarButtonRef), id: triggerId, type: "button", variant: "secondary", size: "icon", disabled: disabled, "aria-label": text("openCalendar"), title: text("openCalendar"), "aria-haspopup": "dialog", "aria-expanded": open, "aria-controls": open ? contentId : undefined, className: "mt-[1.625rem] max-[22rem]:mt-0", onClick: () => {
538
+ // An unsaved draft must survive this click; otherwise it toggles.
539
+ if (showApplyButton && open && draftChanged)
540
+ focusCalendarDay();
541
+ else
542
+ handleOpenChange(!open);
543
+ }, "data-slot": "date-time-range-picker-trigger", children: calendarIcon })) : null, _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2 max-[22rem]:w-full sm:flex-row", children: [_jsx(RangeInput, { id: `${baseId}-start`, label: startLabel, end: "from", date: inputRange?.from, rangeError: isEndBeforeStart, onCommit: (date) => updateInputs(toRange(date, inputRange?.to), "from"), ...inputProps }), _jsx(RangeInput, { id: `${baseId}-end`, tabIntoPopover: showApplyButton && open, label: endLabel, end: "to", date: inputRange?.to, rangeError: isEndBeforeStart, rangeErrorText: isEndBeforeStart
544
+ ? endBeforeStartText(endLabel, startLabel)
545
+ : undefined, onCommit: (date) => updateInputs(toRange(inputRange?.from, date), "to"), ...inputProps })] })] }) })) : (_jsxs("div", { className: "relative", children: [wrappedTrigger, showClearButton ? (_jsx("button", { type: "button", "aria-label": text("clearRange"), onClick: () => {
546
+ emit({});
547
+ closePopover();
548
+ document.getElementById(triggerId)?.focus();
549
+ }, title: text("clearRange"), className: cn("absolute top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded-sm text-neutral-foreground-subtle hover:text-neutral-foreground-strong focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none", showCalendarButton ? "right-2" : "right-9"), "data-slot": "date-time-range-picker-clear", children: _jsx(XIcon, { className: "size-4", "aria-hidden": "true" }) })) : null] }));
550
+ return (_jsxs("div", { className: cn("flex flex-col gap-1.5", className), "data-slot": "date-time-range-picker", children: [label ? (_jsx(Text, { as: "div", id: headingId, variant: "label-md-strong", className: "text-neutral-foreground-strong", children: label })) : null, _jsxs(Popover, { open: disabled ? false : open, onOpenChange: handleOpenChange, children: [control, committedReversed && !showInputs && !open ? (_jsx(Text, { as: "p", id: reversedId, role: "alert", variant: "helper", className: "text-danger-foreground-subtle", children: endBeforeStartText(endLabel, startLabel) })) : null, _jsx(PopoverContent, { id: contentId, "aria-labelledby": label ? headingId : ariaLabelledBy, "aria-label": label || ariaLabelledBy
551
+ ? undefined
552
+ : (ariaLabel ?? text("placeholder")), "data-slot": "date-time-range-picker-content", className: "max-h-(--radix-popover-content-available-height) w-auto max-w-[calc(100vw-2rem)] overflow-auto p-0", align: "start", collisionPadding: 16, ref: contentRef, onOpenAutoFocus: typingOpen || (opensFromInputs && !keyboardOpen)
553
+ ? (event) => event.preventDefault()
554
+ : undefined, onCloseAutoFocus: showInputs
555
+ ? (event) => {
556
+ event.preventDefault();
557
+ // Hand focus back, except after clicking elsewhere on the page.
558
+ const outside = closedByOutsideRef.current;
559
+ closedByOutsideRef.current = false;
560
+ if (!outside) {
561
+ (showCalendarButton
562
+ ? calendarButtonRef.current
563
+ : document.getElementById(openerIdRef.current ?? `${baseId}-start`))?.focus();
564
+ }
565
+ }
566
+ : undefined, onKeyDown: showApplyButton && showInputs
567
+ ? (event) => {
568
+ if (event.key !== "Tab")
569
+ return;
570
+ // The popover renders at the end of the page, so Tab at its
571
+ // edges would land far from the fields: return to them.
572
+ const items = Array.from(event.currentTarget.querySelectorAll('button:not([disabled]):not([tabindex="-1"]), input:not([disabled])'));
573
+ const edge = event.shiftKey ? items[0] : items.at(-1);
574
+ if (items.length > 0 && event.target === edge) {
575
+ event.preventDefault();
576
+ (showCalendarButton && !event.shiftKey
577
+ ? calendarButtonRef.current
578
+ : document.getElementById(`${baseId}-end`))?.focus();
579
+ }
580
+ }
581
+ : undefined, onInteractOutside: (event) => {
582
+ const viaFocus = event.detail.originalEvent.type === "focusin";
583
+ if (groupRef.current?.contains(event.target) ||
584
+ // Tabbing away must not discard a draft the user is still typing.
585
+ (showApplyButton && showInputs && viaFocus)) {
586
+ event.preventDefault();
587
+ }
588
+ else {
589
+ closedByOutsideRef.current = true;
590
+ }
591
+ }, children: _jsxs("div", { className: "flex flex-col sm:flex-row", children: [hasPresets ? (_jsxs("div", { className: "flex shrink-0 flex-col gap-1 border-b border-border p-2 sm:w-44 sm:border-r sm:border-b-0", "data-slot": "date-time-range-picker-presets", children: [_jsx(Text, { as: "div", id: presetsHeadingId, variant: "label-md-strong", className: "px-2 pt-1 text-neutral-foreground-strong", children: text("quickRanges") }), _jsx("ul", { ref: presetsRef, "aria-labelledby": presetsHeadingId, onScroll: updatePresetsFade, className: cn("flex gap-0.5 overflow-x-auto sm:max-h-[24rem] sm:flex-col sm:overflow-x-visible sm:overflow-y-auto", presetsFade &&
592
+ "mask-[linear-gradient(to_right,black_calc(100%-2.5rem),transparent)] sm:mask-none"), children: availablePresets.map((preset) => (_jsx("li", { className: "shrink-0", children: _jsx(Button, { variant: activePresetId === preset.id ? "secondary" : "ghost", size: "sm", "aria-pressed": activePresetId === preset.id, className: "w-full justify-start font-normal", onClick: () => handlePreset(preset), children: getPresetLabel(preset, t) }) }, preset.id))) })] })) : null, _jsxs("div", { className: "flex flex-col", children: [_jsx(Calendar, { mode: "range", selected: current?.from
593
+ ? isEndBeforeStart && current.to
594
+ ? { from: current.to, to: current.from }
595
+ : { from: current.from, to: current.to }
596
+ : undefined, onSelect: handleSelect, month: month ?? current?.from, onMonthChange: setMonth, numberOfMonths: monthCount, startMonth: fromDate, endMonth: toDate, disabled: disabledMatcher, locale: locale, min: 1, fixedWeeks: true, showOutsideDays: true, autoFocus: (!opensFromInputs || keyboardOpen) && !typingOpen }), _jsxs("div", { className: "flex gap-4 px-3 pb-3 max-[22rem]:flex-col", children: [_jsx(TimeField, { id: `${baseId}-from-time`, label: text("fromTime"), end: "from", emptyHint: text("pickDayFirst"), date: current?.from, onCommit: (date) => update(toRange(date, current?.to)), ...timeProps }), _jsx(TimeField, { id: `${baseId}-to-time`, label: text("toTime"), end: "to", emptyHint: current?.from ? text("pickEndDay") : text("pickDayFirst"), date: current?.to, error: isEndBeforeStart && !showInputs
597
+ ? endBeforeStartText(endLabel, startLabel)
598
+ : undefined, onCommit: (date) => update(toRange(current?.from, date)), ...timeProps })] }), showTimeZone ? (_jsx(Text, { as: "p", id: timeZoneId, variant: "helper", className: "px-3 pb-3", children: text("timeZone").replace("{timeZone}", timeZone) })) : null, _jsxs("div", { className: "sticky bottom-0 flex flex-wrap items-center gap-2 border-t border-border bg-popover p-3", "data-slot": "date-time-range-picker-footer", children: [_jsx(Button, { variant: "ghost", disabled: !current?.from && !current?.to, onClick: handleClear, children: text("clear") }), showApplyButton ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "flex-1" }), needsRange ? (_jsx(Text, { as: "p", id: applyHintId, variant: "helper", children: text("applyNeedsRange") })) : null, _jsx(Button, { variant: "secondary", onClick: () => closePopover(), children: text("cancel") }), _jsx(Button, { disabled: needsRange ||
599
+ isEndBeforeStart ||
600
+ draftOutOfBounds ||
601
+ rejectedEnds.from ||
602
+ rejectedEnds.to, "aria-describedby": needsRange ? applyHintId : undefined, onClick: apply, children: text("apply") })] })) : null] })] })] }) })] })] }));
603
+ }
604
+ const DateTimeRangePicker = withRef(DateTimeRangePickerImpl);
605
+ export { DateTimeRangePicker, DEFAULT_DATE_TIME_RANGE_PRESETS };
606
+ //# sourceMappingURL=date-time-range-picker.js.map