@momoi-labs/kiso-react 0.22.1 → 0.23.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.
@@ -0,0 +1,102 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
5
+ import { Button } from "./button.js";
6
+ import { Popover, PopoverContent, PopoverTrigger } from "./popover.js";
7
+ import { dateFormat } from "./time-zone.js";
8
+ // Calendar dates are YYYY-MM-DD strings; arithmetic runs on UTC midnights so
9
+ // no time zone or daylight-saving change can shift a day.
10
+ const toDate = (day) => new Date(`${day}T00:00:00Z`);
11
+ const toDay = (date) => date.toISOString().slice(0, 10);
12
+ const addDays = (day, count) => {
13
+ const date = toDate(day);
14
+ date.setUTCDate(date.getUTCDate() + count);
15
+ return toDay(date);
16
+ };
17
+ const addMonths = (day, count) => {
18
+ const date = toDate(day);
19
+ const target = date.getUTCDate();
20
+ date.setUTCDate(1);
21
+ date.setUTCMonth(date.getUTCMonth() + count);
22
+ const last = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate();
23
+ date.setUTCDate(Math.min(target, last));
24
+ return toDay(date);
25
+ };
26
+ /** The first day of the week for a locale, 0 for Sunday; Monday when unknown. */
27
+ function weekStart(locale) {
28
+ try {
29
+ const info = new Intl.Locale(locale ?? "und");
30
+ const firstDay = (info.getWeekInfo?.() ?? info.weekInfo)?.firstDay;
31
+ return typeof firstDay === "number" ? firstDay % 7 : 1;
32
+ }
33
+ catch {
34
+ return 1;
35
+ }
36
+ }
37
+ /** A month grid that picks one day between `min` and `max`, opened from an icon button. */
38
+ export function RangeCalendar({ day, min, max, locale, label, text, onPick }) {
39
+ const [open, setOpen] = React.useState(false);
40
+ const [focus, setFocus] = React.useState(day);
41
+ const grid = React.useRef(null);
42
+ const clamp = (value) => value < min ? min : value > max ? max : value;
43
+ const first = weekStart(locale);
44
+ const month = focus.slice(0, 7);
45
+ const start = `${month}-01`;
46
+ const lead = (toDate(start).getUTCDay() - first + 7) % 7;
47
+ const weeks = [];
48
+ for (let cursor = addDays(start, -lead); weeks.length < 6 && (weeks.length < 4 || cursor.slice(0, 7) === month);) {
49
+ weeks.push(Array.from({ length: 7 }, (_, index) => addDays(cursor, index)));
50
+ cursor = addDays(cursor, 7);
51
+ }
52
+ const utc = (options) => dateFormat(locale, { timeZone: "UTC", ...options });
53
+ const title = utc({ month: "long", year: "numeric" }).format(toDate(start));
54
+ const allowed = (value) => value >= min && value <= max;
55
+ const moved = React.useRef(false);
56
+ React.useEffect(() => {
57
+ if (moved.current)
58
+ grid.current?.querySelector(`[data-day="${focus}"]`)?.focus();
59
+ moved.current = false;
60
+ }, [focus]);
61
+ const move = (next) => { moved.current = true; setFocus(next); };
62
+ const pick = (value) => {
63
+ if (!allowed(value))
64
+ return;
65
+ onPick(value);
66
+ setOpen(false);
67
+ };
68
+ const firstMonth = min.slice(0, 7), lastMonth = max.slice(0, 7);
69
+ // Keys stay in the months that hold retention; their unavailable days stay reachable.
70
+ const inMonths = (value) => value.slice(0, 7) < firstMonth ? `${firstMonth}-01`
71
+ : value.slice(0, 7) > lastMonth ? addDays(addMonths(`${lastMonth}-01`, 1), -1) : value;
72
+ const key = (event) => {
73
+ const dow = (toDate(focus).getUTCDay() - first + 7) % 7;
74
+ const next = {
75
+ ArrowLeft: () => addDays(focus, -1), ArrowRight: () => addDays(focus, 1),
76
+ ArrowUp: () => addDays(focus, -7), ArrowDown: () => addDays(focus, 7),
77
+ Home: () => addDays(focus, -dow), End: () => addDays(focus, 6 - dow),
78
+ PageUp: () => addMonths(focus, -1), PageDown: () => addMonths(focus, 1),
79
+ };
80
+ if (event.key === "Enter" || event.key === " ") {
81
+ event.preventDefault();
82
+ pick(focus);
83
+ }
84
+ else if (next[event.key]) {
85
+ event.preventDefault();
86
+ move(inMonths(next[event.key]()));
87
+ }
88
+ };
89
+ return _jsxs(Popover, { open: open, onOpenChange: next => { setOpen(next); if (next)
90
+ setFocus(clamp(day)); }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(Button, { type: "button", variant: "ghost", size: "sm", className: "btn-icon time-range-live-date", "aria-label": label, children: _jsx(CalendarDays, { className: "icon icon-sm", "aria-hidden": "true" }) }) }), _jsxs(PopoverContent, { className: "time-range-calendar", "aria-label": label, align: "end", onOpenAutoFocus: event => {
91
+ // Focus starts on the field's day, not the first button.
92
+ event.preventDefault();
93
+ const content = event.currentTarget;
94
+ requestAnimationFrame(() => content?.querySelector(`[data-day="${clamp(day)}"]`)?.focus());
95
+ }, children: [_jsxs("div", { className: "time-range-calendar-head", children: [_jsx(Button, { type: "button", variant: "ghost", size: "sm", className: "btn-icon", "aria-label": text.previousMonth, disabled: month <= firstMonth, onClick: () => move(clamp(addMonths(focus, -1))), children: _jsx(ChevronLeft, { className: "icon icon-sm", "aria-hidden": "true" }) }), _jsx("strong", { "aria-live": "polite", children: title }), _jsx(Button, { type: "button", variant: "ghost", size: "sm", className: "btn-icon", "aria-label": text.nextMonth, disabled: month >= lastMonth, onClick: () => move(clamp(addMonths(focus, 1))), children: _jsx(ChevronRight, { className: "icon icon-sm", "aria-hidden": "true" }) })] }), _jsxs("table", { ref: grid, role: "grid", "aria-label": title, onKeyDown: key, children: [_jsx("thead", { children: _jsx("tr", { children: weeks[0].map(value => _jsx("th", { scope: "col", abbr: utc({ weekday: "long" }).format(toDate(value)), children: utc({ weekday: "narrow" }).format(toDate(value)) }, value)) }) }), _jsx("tbody", { children: weeks.map(week => _jsx("tr", { children: week.map(value => {
96
+ const inside = allowed(value);
97
+ return _jsx("td", { role: "gridcell", "aria-selected": value === day, children: _jsx("button", { type: "button", className: "time-range-calendar-day", "data-day": value, "data-outside": value.slice(0, 7) !== month || undefined, tabIndex: value === focus ? 0 : -1, "aria-disabled": !inside || undefined, "aria-current": value === max ? "date" : undefined, "aria-label": `${utc({ weekday: "long", year: "numeric", month: "long", day: "numeric" }).format(toDate(value))}${inside ? "" : `, ${text.outsideRetention}`}`, onClick: () => { if (inside) {
98
+ setFocus(value);
99
+ pick(value);
100
+ } }, children: Number(value.slice(8)) }) }, value);
101
+ }) }, week[0])) })] })] })] });
102
+ }
@@ -1,18 +1,34 @@
1
1
  import * as React from "react";
2
- export type TimeRange = {
3
- from: number;
4
- to: number;
2
+ import { type LiveTimeRange, type TimeRange, type TimeRangeControlLabels, type TimeRangePreset } from "./time-range-shared.js";
3
+ export type { LiveTimeRange, TimeRange, TimeRangeControlLabels, TimeRangePreset, TimeRangeState, TimeRangeUnit } from "./time-range-shared.js";
4
+ type SharedProps = {
5
+ label?: string;
6
+ disabled?: boolean;
7
+ className?: string;
8
+ presets?: readonly TimeRangePreset[];
9
+ /** IANA time zone. Live defaults to the browser's zone, artifact to UTC. */
10
+ timeZone?: string;
11
+ onTimeZoneChange?: (timeZone: string) => void;
12
+ /** Locale for live date formats. Defaults to the document's language. */
13
+ locale?: string;
14
+ labels?: Partial<TimeRangeControlLabels>;
5
15
  };
6
- export type TimeRangeControlProps = {
16
+ export type ArtifactTimeRangeControlProps = SharedProps & {
17
+ mode?: "artifact";
7
18
  value: TimeRange;
8
19
  bounds: TimeRange;
9
20
  onValueChange: (range: TimeRange) => void;
10
- label?: string;
11
- disabled?: boolean;
12
- className?: string;
13
- presets?: readonly {
14
- label: string;
15
- duration: number;
16
- }[];
17
21
  };
18
- export declare function TimeRangeControl({ value, bounds, onValueChange, label, disabled, className, presets }: TimeRangeControlProps): React.JSX.Element;
22
+ export type LiveTimeRangeControlProps = SharedProps & {
23
+ mode: "live";
24
+ value: LiveTimeRange;
25
+ /** Wall-clock epoch milliseconds of the consumer's last query. */
26
+ now: number;
27
+ /** Retention: presets and custom ranges stop at this span. */
28
+ maxDuration: number;
29
+ /** The relative duration "Back to live" applies. */
30
+ resumeDuration: number;
31
+ onValueChange: (value: LiveTimeRange) => void;
32
+ };
33
+ export type TimeRangeControlProps = ArtifactTimeRangeControlProps | LiveTimeRangeControlProps;
34
+ export declare function TimeRangeControl(props: TimeRangeControlProps): React.JSX.Element;
@@ -7,22 +7,20 @@ import { Button } from "./button.js";
7
7
  import { Form, FormActions } from "./form.js";
8
8
  import { Input } from "./input.js";
9
9
  import { Popover, PopoverContent, PopoverTrigger } from "./popover.js";
10
- const defaultPresets = [
11
- { label: "Last 5 minutes", duration: 300_000 },
12
- { label: "Last 15 minutes", duration: 900_000 },
13
- { label: "Last 30 minutes", duration: 1_800_000 },
14
- ];
15
- const dateInput = (value) => new Date(value).toISOString().slice(0, 23);
16
- const shortRange = (range) => {
17
- const from = dateInput(range.from);
18
- const to = dateInput(range.to);
19
- const sameDay = from.slice(0, 10) === to.slice(0, 10);
20
- const compact = (date) => (sameDay ? date.slice(11) : date.replace("T", " ")).replace(/:00\.000$/, "").replace(/\.000$/, "");
21
- return `${compact(from)} to ${compact(to)} UTC`;
10
+ import { parseWallTime, validTimeZone, wallString, zoneName } from "./time-zone.js";
11
+ import { LiveControl } from "./time-range-live.js";
12
+ import { defaultLabels, defaultPresets, validRange } from "./time-range-shared.js";
13
+ // Browsers drop zero seconds and milliseconds from a datetime-local value.
14
+ const wallKey = (text) => {
15
+ const [date, time = ""] = text.split("T");
16
+ const [clock = "", fraction = ""] = time.split(".");
17
+ return `${date}T${clock.length === 5 ? `${clock}:00` : clock}.${fraction.padEnd(3, "0")}`;
22
18
  };
23
- const validRange = (range) => Number.isFinite(range.from) && Number.isFinite(range.to)
24
- && Math.abs(range.from) <= 8.64e15 && Math.abs(range.to) <= 8.64e15 && range.from < range.to;
25
- export function TimeRangeControl({ value, bounds, onValueChange, label = "Time range", disabled, className, presets = defaultPresets }) {
19
+ export function TimeRangeControl(props) {
20
+ return props.mode === "live" ? _jsx(LiveControl, { ...props }) : _jsx(ArtifactControl, { ...props });
21
+ }
22
+ function ArtifactControl({ value, bounds, onValueChange, label = "Time range", disabled, className, presets = defaultPresets, timeZone = "UTC", labels }) {
23
+ const text = { ...defaultLabels, ...labels };
26
24
  const [open, setOpen] = React.useState(false);
27
25
  const [custom, setCustom] = React.useState(false);
28
26
  if (!validRange(bounds) || !validRange(value) || value.from < bounds.from || value.to > bounds.to) {
@@ -31,24 +29,45 @@ export function TimeRangeControl({ value, bounds, onValueChange, label = "Time r
31
29
  if (presets.some(preset => !Number.isFinite(preset.duration) || preset.duration <= 0)) {
32
30
  throw new RangeError("Time range preset durations must be positive milliseconds.");
33
31
  }
32
+ if (!validTimeZone(timeZone))
33
+ throw new RangeError("Time range time zone must be a valid IANA name.");
34
+ const zone = zoneName(value.from, timeZone);
35
+ const dateInput = (time) => wallString(time, timeZone, "millisecond");
36
+ const shortRange = (range) => {
37
+ const from = dateInput(range.from);
38
+ const to = dateInput(range.to);
39
+ const sameDay = from.slice(0, 10) === to.slice(0, 10);
40
+ const compact = (date) => (sameDay ? date.slice(11) : date.replace("T", " ")).replace(/:00\.000$/, "").replace(/\.000$/, "");
41
+ return text.range(compact(from), compact(to), zone);
42
+ };
34
43
  const apply = (range) => { onValueChange(range); setOpen(false); };
35
- return _jsxs(Popover, { open: open, onOpenChange: next => { setOpen(next); setCustom(false); }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { disabled: disabled, className: cn("time-range-trigger", className), "aria-label": `${label}: ${dateInput(value.from).replace("T", " ")} to ${dateInput(value.to).replace("T", " ")} UTC`, children: [shortRange(value), " ", _jsx(ChevronDown, { className: "icon icon-sm", "aria-hidden": "true" })] }) }), _jsx(PopoverContent, { className: "time-range-content", "aria-label": label, children: custom ? _jsxs("div", { className: "stack-sm", children: [_jsx(Button, { variant: "ghost", onClick: () => setCustom(false), children: "Back to presets" }), _jsx(TimeRangeForm, { value: value, bounds: bounds, onApply: apply }, `${value.from}-${value.to}-${open}`)] }) : _jsxs("div", { className: "time-range-presets", children: [_jsxs(Button, { variant: "ghost", onClick: () => apply(bounds), children: [_jsx("span", { children: "Entire run" }), _jsx("small", { children: shortRange(bounds) })] }), presets.map(preset => {
44
+ return _jsxs(Popover, { open: open, onOpenChange: next => { setOpen(next); setCustom(false); }, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { disabled: disabled, className: cn("time-range-trigger", className), "aria-label": `${label}: ${text.range(dateInput(value.from).replace("T", " "), dateInput(value.to).replace("T", " "), zone)}`, children: [shortRange(value), " ", _jsx(ChevronDown, { className: "icon icon-sm", "aria-hidden": "true" })] }) }), _jsx(PopoverContent, { className: "time-range-content", "aria-label": label, children: custom ? _jsxs("div", { className: "stack-sm", children: [_jsx(Button, { variant: "ghost", onClick: () => setCustom(false), children: text.backToPresets }), _jsx(ArtifactForm, { value: value, bounds: bounds, timeZone: timeZone, zone: zone, text: text, onApply: apply }, `${value.from}-${value.to}-${open}`)] }) : _jsxs("div", { className: "time-range-presets", children: [_jsxs(Button, { variant: "ghost", onClick: () => apply(bounds), children: [_jsx("span", { children: text.entireRun }), _jsx("small", { children: shortRange(bounds) })] }), presets.map(preset => {
36
45
  const range = { from: Math.max(bounds.from, bounds.to - preset.duration), to: bounds.to };
37
46
  return _jsxs(Button, { variant: "ghost", onClick: () => apply(range), children: [_jsx("span", { children: preset.label }), _jsx("small", { children: shortRange(range) })] }, preset.label);
38
- }), _jsx(Button, { variant: "ghost", onClick: () => setCustom(true), children: "Custom range" })] }) })] });
47
+ }), _jsx(Button, { variant: "ghost", onClick: () => setCustom(true), children: text.custom })] }) })] });
39
48
  }
40
- function TimeRangeForm({ value, bounds, onApply }) {
49
+ function ArtifactForm({ value, bounds, timeZone, zone, text, onApply }) {
41
50
  const id = React.useId();
51
+ const dateInput = (time) => wallString(time, timeZone, "millisecond");
42
52
  const [from, setFrom] = React.useState(dateInput(value.from));
43
53
  const [to, setTo] = React.useState(dateInput(value.to));
44
54
  const [error, setError] = React.useState("");
45
- return _jsxs(Form, { className: "stack-sm", onSubmit: event => {
55
+ const utc = timeZone === "UTC";
56
+ const min = dateInput(bounds.from);
57
+ const max = dateInput(bounds.to);
58
+ // Outside UTC, a DST overlap repeats wall times: an unchanged field keeps
59
+ // its instant, and native constraints, which compare wall times, are hints.
60
+ const [start] = React.useState({ from, to });
61
+ const read = (text, initial, original) => wallKey(text) === wallKey(initial) ? original : parseWallTime(text, timeZone);
62
+ const hint = utc || min < max ? { min, max } : {};
63
+ return _jsxs(Form, { className: "stack-sm", noValidate: !utc, onSubmit: event => {
46
64
  event.preventDefault();
47
- const range = { from: Date.parse(`${from}Z`), to: Date.parse(`${to}Z`) };
65
+ const range = utc ? { from: Date.parse(`${from}Z`), to: Date.parse(`${to}Z`) }
66
+ : { from: read(from, start.from, value.from), to: read(to, start.to, value.to) };
48
67
  if (!validRange(range) || range.from < bounds.from || range.to > bounds.to) {
49
- setError("Choose a start before the end, within the collection window.");
68
+ setError(text.error);
50
69
  return;
51
70
  }
52
71
  onApply(range);
53
- }, children: [_jsx("label", { htmlFor: `${id}-from`, children: "From (UTC)" }), _jsx(Input, { id: `${id}-from`, type: "datetime-local", step: "0.001", required: true, value: from, min: dateInput(bounds.from), max: dateInput(bounds.to), onChange: event => { setFrom(event.target.value); setError(""); }, "aria-invalid": !!error, "aria-describedby": error ? `${id}-error` : undefined }), _jsx("label", { htmlFor: `${id}-to`, children: "To (UTC)" }), _jsx(Input, { id: `${id}-to`, type: "datetime-local", step: "0.001", required: true, value: to, min: dateInput(bounds.from), max: dateInput(bounds.to), onChange: event => { setTo(event.target.value); setError(""); }, "aria-invalid": !!error, "aria-describedby": error ? `${id}-error` : undefined }), error && _jsx("p", { id: `${id}-error`, role: "alert", className: "field-error", children: error }), _jsx(FormActions, { children: _jsx(Button, { type: "submit", variant: "primary", children: "Apply range" }) })] });
72
+ }, children: [_jsx("label", { htmlFor: `${id}-from`, children: text.from(zone) }), _jsx(Input, { id: `${id}-from`, type: "datetime-local", step: "0.001", required: true, value: from, ...hint, onChange: event => { setFrom(event.target.value); setError(""); }, "aria-invalid": !!error, "aria-describedby": error ? `${id}-error` : undefined }), _jsx("label", { htmlFor: `${id}-to`, children: text.to(zone) }), _jsx(Input, { id: `${id}-to`, type: "datetime-local", step: "0.001", required: true, value: to, ...hint, onChange: event => { setTo(event.target.value); setError(""); }, "aria-invalid": !!error, "aria-describedby": error ? `${id}-error` : undefined }), error && _jsx("p", { id: `${id}-error`, role: "alert", className: "field-error", children: error }), _jsx(FormActions, { children: _jsx(Button, { type: "submit", variant: "primary", children: text.apply }) })] });
54
73
  }
@@ -0,0 +1,18 @@
1
+ import * as React from "react";
2
+ import { type LiveTimeRange, type TimeRangeControlLabels, type TimeRangePreset } from "./time-range-shared.js";
3
+ export type LiveControlProps = {
4
+ value: LiveTimeRange;
5
+ now: number;
6
+ maxDuration: number;
7
+ resumeDuration: number;
8
+ onValueChange: (value: LiveTimeRange) => void;
9
+ label?: string;
10
+ disabled?: boolean;
11
+ className?: string;
12
+ presets?: readonly TimeRangePreset[];
13
+ timeZone?: string;
14
+ onTimeZoneChange?: (timeZone: string) => void;
15
+ locale?: string;
16
+ labels?: Partial<TimeRangeControlLabels>;
17
+ };
18
+ export declare function LiveControl({ value, now, maxDuration, resumeDuration, onValueChange, label, disabled, className, presets, timeZone, onTimeZoneChange, locale, labels }: LiveControlProps): React.JSX.Element;
@@ -0,0 +1,305 @@
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { clsx as cn } from "clsx";
5
+ import { Check, ChevronDown, Globe, Pause, Play, Radio } from "lucide-react";
6
+ import { Button } from "./button.js";
7
+ import { Label } from "./label.js";
8
+ import { RangeCalendar } from "./time-range-calendar.js";
9
+ import { ValidationMessage } from "./validation-message.js";
10
+ import { Input } from "./input.js";
11
+ import { Popover, PopoverContent, PopoverTrigger } from "./popover.js";
12
+ import { Search } from "./search.js";
13
+ import { Separator } from "./separator.js";
14
+ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip.js";
15
+ import { browserTimeZone, dateFormat, timeZones, validInstant, validTimeZone, wallString, zoneName } from "./time-zone.js";
16
+ import { absoluteRangeText, parseRangeText, relativeRangeText, resolveRangeText } from "./time-range-text.js";
17
+ import { ceilSecond, defaultLabels, defaultPresets, documentLocale, durationText, floorSecond, minimumSpan, positive, snapDuration, validLocale, validRange } from "./time-range-shared.js";
18
+ export function LiveControl({ value, now, maxDuration, resumeDuration, onValueChange, label = "Time range", disabled, className, presets = defaultPresets, timeZone, onTimeZoneChange, locale, labels }) {
19
+ const text = { ...defaultLabels, ...labels };
20
+ const [open, setOpen] = React.useState(false);
21
+ const [view, setView] = React.useState("main");
22
+ const [chosenZone, setChosenZone] = React.useState();
23
+ const escape = React.useRef({});
24
+ // The fields' edit lives here so the time zone view does not discard it.
25
+ // Pause, resume, a drag, a zone change, and closing the popover do.
26
+ const [fields, setFields] = React.useState(cleanFields);
27
+ const zone = validTimeZone(timeZone) ? timeZone : validTimeZone(chosenZone) ? chosenZone : browserTimeZone();
28
+ const language = validLocale(locale ?? documentLocale());
29
+ const valid = presets.filter(preset => positive(preset.duration));
30
+ const shown = valid.filter(preset => preset.duration <= maxDuration);
31
+ const relative = value?.kind === "relative";
32
+ const state = relative ? "live" : "paused";
33
+ const resolved = relative ? { from: now - value.duration, to: now }
34
+ : { from: value?.kind === "absolute" ? value.from : NaN, to: value?.kind === "absolute" ? value.to : NaN };
35
+ const resolvable = validRange(resolved);
36
+ const sameDay = (a, b) => wallString(a, zone, "second").slice(0, 10) === wallString(b, zone, "second").slice(0, 10);
37
+ const formats = {
38
+ zone, language, text, sameDay,
39
+ time: (instant, withDate) => dateFormat(language, { timeZone: zone, hour: "2-digit", minute: "2-digit",
40
+ second: "2-digit", ...(withDate ? { month: "short", day: "numeric" } : {}) }).format(instant),
41
+ full: instant => dateFormat(language, { timeZone: zone, year: "numeric", month: "short", day: "numeric",
42
+ hour: "numeric", minute: "2-digit", second: "2-digit", timeZoneName: "longOffset" }).format(instant),
43
+ hint: instant => dateFormat(language, { timeZone: zone, month: "short", day: "numeric", hour: "numeric",
44
+ minute: "2-digit", second: "2-digit", timeZoneName: "short" }).format(instant),
45
+ axis: (instant, withDate) => dateFormat(language, { timeZone: zone, hour: "numeric", minute: "2-digit",
46
+ ...(withDate ? { month: "short", day: "numeric" } : {}) }).format(instant),
47
+ };
48
+ const shortRange = (range) => {
49
+ if (!validRange(range))
50
+ return text.unavailable;
51
+ const crosses = !sameDay(range.from, range.to);
52
+ return text.range(formats.time(range.from, crosses), formats.time(range.to, crosses), zoneName(range.from, zone, language));
53
+ };
54
+ const relativeText = (duration) => {
55
+ if (!positive(duration))
56
+ return text.unavailable;
57
+ return valid.find(item => item.duration === duration)?.label ?? durationText(duration, text.relative);
58
+ };
59
+ const triggerText = relative ? relativeText(value.duration) : shortRange(resolved);
60
+ const fullText = resolvable ? text.fullRange(formats.full(resolved.from), formats.full(resolved.to)) : text.unavailable;
61
+ const StateIcon = relative ? Radio : Pause;
62
+ if (fields.draft && fields.draft.zone !== zone)
63
+ setFields(cleanFields);
64
+ const act = (next) => { setFields(cleanFields); onValueChange(next); };
65
+ const pause = () => { if (resolvable)
66
+ act({ kind: "absolute", ...resolved }); };
67
+ const resume = () => act({ kind: "relative", duration: resumeDuration });
68
+ const toggle = relative ? pause : resume;
69
+ const chooseZone = (next) => {
70
+ setChosenZone(next);
71
+ onTimeZoneChange?.(next);
72
+ setView("main");
73
+ };
74
+ return _jsx(TooltipProvider, { children: _jsxs("div", { className: cn("time-range-live", className), role: "group", "aria-label": label, children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { className: "btn-icon time-range-live-pause", disabled: disabled || (relative && !resolvable), "aria-label": relative ? text.pause : text.resume, onClick: toggle, children: relative ? _jsx(Pause, { className: "icon icon-sm", "aria-hidden": "true" }) : _jsx(Play, { className: "icon icon-sm", "aria-hidden": "true" }) }) }), _jsx(TooltipContent, { children: relative ? text.pause : text.resume })] }), _jsxs(Popover, { open: open, onOpenChange: next => { setOpen(next); setView("main"); setFields(cleanFields); }, children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { disabled: disabled, className: "time-range-trigger", "data-time-range-state": state, "aria-label": text.triggerName({ label, state: relative ? text.live : text.paused, text: triggerText, range: fullText }), children: [_jsx(StateIcon, { className: "icon icon-sm", "aria-hidden": "true" }), " ", triggerText, " ", _jsx(ChevronDown, { className: "icon icon-sm", "aria-hidden": "true" })] }) }) }), _jsx(TooltipContent, { className: "time-range-live-tip", children: resolvable ? _jsxs(_Fragment, { children: [_jsx(Timeline, { range: resolved, now: now, maxDuration: maxDuration, live: relative, formats: formats }), _jsxs("div", { className: "time-range-live-ends", children: [_jsx("span", { children: formats.time(resolved.from, !sameDay(resolved.from, resolved.to)) }), _jsx("span", { children: formats.time(resolved.to, !sameDay(resolved.from, resolved.to)) })] }), _jsx("small", { children: retentionNote(resolved, maxDuration, formats) })] }) : text.unavailable })] }), _jsx(PopoverContent, { className: "time-range-live-content", "aria-label": label, onEscapeKeyDown: event => {
75
+ if (escape.current.drag?.() || escape.current.fields?.())
76
+ event.preventDefault();
77
+ }, children: view === "zone" ? _jsx(TimeZoneView, { zone: zone, text: text, onBack: () => setView("main"), onChoose: chooseZone })
78
+ : _jsxs("div", { className: "time-range-live-panel", children: [_jsxs("div", { className: "time-range-live-main", children: [_jsxs("div", { className: "time-range-live-state", children: [_jsxs("span", { className: "time-range-live-status", children: [_jsx(StateIcon, { className: "icon icon-sm", "aria-hidden": "true" }), " ", relative ? text.live : text.paused] }), _jsxs(Button, { size: "sm", disabled: relative && !resolvable, onClick: toggle, children: [relative ? _jsx(Pause, { className: "icon icon-sm", "aria-hidden": "true" }) : _jsx(Play, { className: "icon icon-sm", "aria-hidden": "true" }), relative ? text.pause : text.backToLive] })] }), _jsx(RangeTimeline, { range: resolvable ? resolved : null, now: now, maxDuration: maxDuration, live: relative, formats: formats, escape: escape, onCommit: act }), _jsx(Separator, {}), _jsx(LiveFields, { state: fields, setState: setFields, value: value, now: now, maxDuration: maxDuration, formats: formats, escape: escape, onApply: onValueChange }), _jsx(Separator, {}), _jsxs(Button, { variant: "ghost", className: "time-range-zone", onClick: () => setView("zone"), children: [_jsx(Globe, { className: "icon icon-sm", "aria-hidden": "true" }), " ", text.timeZoneButton(zone)] })] }), _jsx("div", { className: "time-range-presets time-range-live-presets", role: "group", "aria-label": text.presets, children: shown.map(preset => {
79
+ const selected = relative && value.duration === preset.duration;
80
+ return _jsxs(Button, { variant: "ghost", className: "time-range-option", "aria-pressed": selected, onClick: () => { onValueChange({ kind: "relative", duration: preset.duration }); setOpen(false); }, children: [_jsx("span", { children: preset.label }), selected && _jsx(Check, { className: "icon icon-sm", "aria-hidden": "true" })] }, `${preset.label}-${preset.duration}`);
81
+ }) })] }) })] })] }) });
82
+ }
83
+ function retentionNote(range, maxDuration, { text, zone, language, sameDay }) {
84
+ const date = dateFormat(language, { timeZone: zone, year: "numeric", month: "short", day: "numeric" });
85
+ const keeps = positive(maxDuration) ? ` ${text.keeps(durationText(maxDuration, text.duration))}` : "";
86
+ return `${sameDay(range.from, range.to) ? `${date.format(range.to)}, ` : ""}${zoneName(range.to, zone, language)}.${keeps}`;
87
+ }
88
+ /** The retention window, [now - maxDuration, now], with the range on it. */
89
+ function Timeline({ range, now, maxDuration, live, formats }) {
90
+ const start = now - maxDuration;
91
+ const usable = validInstant(now) && positive(maxDuration) && validInstant(start);
92
+ const older = usable && range && range.to < start;
93
+ const left = usable && range ? Math.min(1, Math.max(0, (range.from - start) / maxDuration)) : 0;
94
+ const right = usable && range ? Math.min(1, Math.max(0, (range.to - start) / maxDuration)) : 0;
95
+ return _jsxs("div", { className: "time-range-live-timeline", children: [older ? _jsx("p", { className: "time-range-live-note", children: formats.text.olderThanRetention })
96
+ : _jsx("div", { className: "time-range-live-track", "data-state": live ? "live" : "paused", "aria-hidden": "true", children: usable && range && _jsx("span", { className: "time-range-live-segment", style: { left: `${left * 100}%`, width: `${Math.max(right - left, 0.015) * 100}%` } }) }), usable && _jsxs("div", { className: "time-range-live-axis", "aria-hidden": "true", children: [_jsx("span", { children: formats.axis(start, maxDuration >= 86_400_000) }), _jsx("span", { children: formats.text.now })] })] });
97
+ }
98
+ /** Moves or resizes `range` by `delta` inside [start, end], keeping the minimum span. */
99
+ function shift(mode, range, delta, start, end, span) {
100
+ if (mode === "move") {
101
+ const clamped = Math.max(start - range.from, Math.min(end - range.to, delta));
102
+ return { from: range.from + clamped, to: range.to + clamped };
103
+ }
104
+ if (mode === "from")
105
+ return { from: Math.max(start, Math.min(range.to - span, range.from + delta)), to: range.to };
106
+ return { from: range.from, to: Math.min(end, Math.max(range.from + span, range.to + delta)) };
107
+ }
108
+ /** The popover's timeline: drag the range or its ends, or use the three sliders. */
109
+ function RangeTimeline({ range: value, now, maxDuration, live, formats, escape, onCommit }) {
110
+ const track = React.useRef(null);
111
+ const dragRef = React.useRef(null);
112
+ const [drag, setDrag] = React.useState(null);
113
+ const start = now - maxDuration;
114
+ const usable = validInstant(now) && positive(maxDuration) && validInstant(start);
115
+ if (!usable || !value || value.to < start) {
116
+ return _jsx(Timeline, { range: value, now: now, maxDuration: maxDuration, live: live, formats: formats });
117
+ }
118
+ const span = minimumSpan(maxDuration);
119
+ // The sliders and drags work on the part of the range inside retention.
120
+ const from = Math.min(now - span, Math.max(start, value.from));
121
+ const range = { from, to: Math.min(now, Math.max(from + span, value.to)) };
122
+ // Pointer precision follows a short retention; keyboard steps stay whole seconds.
123
+ const unit = maxDuration >= 2000 ? 1000 : 1;
124
+ const step = Math.max(1000, Math.round(maxDuration / 120_000) * 1000);
125
+ const { text } = formats;
126
+ const update = (next) => { dragRef.current = next; setDrag(next); };
127
+ const cancel = () => {
128
+ if (!dragRef.current)
129
+ return false;
130
+ track.current?.releasePointerCapture?.(dragRef.current.pointer);
131
+ update(null);
132
+ return true;
133
+ };
134
+ escape.current.drag = cancel;
135
+ // During a drag the window stays at the `now` the drag started with.
136
+ const shown = drag ? drag.preview : range;
137
+ const windowNow = drag ? drag.now : now;
138
+ const windowStart = windowNow - maxDuration;
139
+ const left = Math.min(1, Math.max(0, (shown.from - windowStart) / maxDuration));
140
+ const right = Math.min(1, Math.max(0, (shown.to - windowStart) / maxDuration));
141
+ // Three targets that never overlap and stay on the track: the move target
142
+ // covers the segment and is at least --time-range-hit wide; each handle
143
+ // takes --time-range-hit beside it. The middle keeps room for both handles.
144
+ const width = Math.max(right - left, 0.015);
145
+ const hit = "var(--time-range-hit)";
146
+ const middle = `clamp(calc(${hit} * 1.5), ${(left + width / 2) * 100}%, calc(100% - ${hit} * 1.5))`;
147
+ const moveStart = `max(${hit}, min(${left * 100}%, calc(${middle} - ${hit} / 2)))`;
148
+ const moveEnd = `min(calc(100% - ${hit}), max(${(left + width) * 100}%, calc(${middle} + ${hit} / 2)))`;
149
+ const crosses = !formats.sameDay(shown.from, shown.to);
150
+ const time = (instant) => formats.time(instant, crosses);
151
+ const begin = (mode) => (event) => {
152
+ if (event.button !== 0 || !track.current)
153
+ return;
154
+ event.preventDefault();
155
+ event.stopPropagation();
156
+ track.current.setPointerCapture?.(event.pointerId);
157
+ const width = track.current.getBoundingClientRect().width;
158
+ update({ mode, pointer: event.pointerId, x: event.clientX, width, now, from: range.from, to: range.to,
159
+ preview: range, snap: false });
160
+ };
161
+ const move = (event) => {
162
+ const current = dragRef.current;
163
+ if (!current || event.pointerId !== current.pointer || !current.width)
164
+ return;
165
+ const delta = Math.round((event.clientX - current.x) / current.width * maxDuration / unit) * unit;
166
+ let preview = shift(current.mode, current, delta, current.now - maxDuration, current.now, span);
167
+ const snap = preview.to >= current.now - maxDuration * 0.015;
168
+ if (snap)
169
+ preview = { from: preview.from, to: current.now };
170
+ update({ ...current, preview, snap });
171
+ };
172
+ const end = (event) => {
173
+ const current = dragRef.current;
174
+ if (!current || event.pointerId !== current.pointer)
175
+ return;
176
+ update(null);
177
+ track.current?.releasePointerCapture?.(current.pointer);
178
+ if (current.preview.from === current.from && current.preview.to === current.to)
179
+ return;
180
+ if (current.snap)
181
+ return onCommit({ kind: "relative", duration: snapDuration(current.preview.to - current.preview.from, maxDuration) });
182
+ // Checked against the retention of the current `now`.
183
+ const from = Math.max(current.preview.from, now - maxDuration);
184
+ const to = Math.min(current.preview.to, now);
185
+ if (to - from >= span)
186
+ onCommit({ kind: "absolute", from, to });
187
+ };
188
+ const key = (mode) => (event) => {
189
+ const limits = mode === "move" ? [start, now - (range.to - range.from)] : mode === "from" ? [start, range.to - span] : [range.from + span, now];
190
+ const current = mode === "to" ? range.to : range.from;
191
+ const big = step * 10;
192
+ const deltas = { ArrowLeft: -step, ArrowDown: -step, ArrowRight: step, ArrowUp: step,
193
+ PageDown: -big, PageUp: big, Home: limits[0] - current, End: limits[1] - current };
194
+ if (!(event.key in deltas))
195
+ return;
196
+ event.preventDefault();
197
+ const delta = event.shiftKey && event.key.startsWith("Arrow") ? deltas[event.key] * 10 : deltas[event.key];
198
+ const next = shift(mode, range, delta, start, now, span);
199
+ if (next.from !== range.from || next.to !== range.to)
200
+ onCommit({ kind: "absolute", ...next });
201
+ };
202
+ const slider = (mode, name, min, max, value, valueText) => ({
203
+ role: "slider", tabIndex: 0, "aria-label": name, "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": value,
204
+ "aria-valuetext": valueText, "aria-orientation": "horizontal", onKeyDown: key(mode), onPointerDown: begin(mode),
205
+ });
206
+ return _jsxs("div", { className: "time-range-live-timeline", children: [_jsxs("div", { ref: track, className: "time-range-live-track", "data-state": live && (!drag || drag.snap) ? "live" : "paused", "data-dragging": drag ? drag.mode : undefined, onPointerMove: move, onPointerUp: end, onPointerCancel: cancel, onLostPointerCapture: () => { if (dragRef.current)
207
+ update(null); }, children: [_jsx("span", { className: "time-range-live-segment", "aria-hidden": "true", style: { left: `${left * 100}%`, width: `${width * 100}%` } }), _jsx("span", { className: "time-range-live-handle", "data-edge": "start", style: { left: moveStart }, ...slider("from", text.rangeStart, start, range.to - span, range.from, time(range.from)) }), _jsx("span", { className: "time-range-live-move", style: { left: moveStart, width: `calc(${moveEnd} - ${moveStart})` }, ...slider("move", text.moveRange, start, now - (range.to - range.from), range.from, text.fullRange(time(range.from), time(range.to))) }), _jsx("span", { className: "time-range-live-handle", "data-edge": "end", style: { left: moveEnd }, ...slider("to", text.rangeEnd, range.from + span, now, range.to, time(range.to)) })] }), _jsxs("div", { className: "time-range-live-axis", "aria-hidden": "true", children: [_jsx("span", { children: formats.axis(windowStart, maxDuration >= 86_400_000) }), _jsx("span", { children: text.now })] }), drag?.snap && _jsx("p", { className: "time-range-live-note", role: "status", children: text.releaseToLive(durationText(snapDuration(drag.preview.to - drag.preview.from, maxDuration), text.relative)) })] });
208
+ }
209
+ const cleanFields = { draft: null, error: null };
210
+ function LiveFields({ state, setState, value, now, maxDuration, formats, escape, onApply }) {
211
+ const { zone, text } = formats;
212
+ const form = React.useRef(null);
213
+ const baseId = React.useId();
214
+ const { draft, error } = state;
215
+ const setDraft = (next) => setState(current => ({ ...current, draft: next }));
216
+ const setError = (next) => setState(current => ({ ...current, error: next }));
217
+ const shown = value?.kind === "relative"
218
+ ? (positive(value.duration) ? [relativeRangeText(value.duration), "now"] : ["", ""])
219
+ : value?.kind === "absolute" ? [absoluteRangeText(ceilSecond(value.from), zone), absoluteRangeText(floorSecond(value.to), zone)]
220
+ : ["", ""];
221
+ // An edit belongs to the zone it was typed in; LiveControl discards it on a zone change.
222
+ const edit = draft && draft.zone === zone ? draft : null;
223
+ const from = edit?.from ?? shown[0];
224
+ const to = edit?.to ?? shown[1];
225
+ const dirty = from !== shown[0] || to !== shown[1];
226
+ const reset = () => setState(cleanFields);
227
+ escape.current.fields = () => {
228
+ if (!dirty || !form.current?.contains(document.activeElement))
229
+ return false;
230
+ reset();
231
+ return true;
232
+ };
233
+ const change = (field, next) => {
234
+ setDraft({ ...edit, zone, [field]: next });
235
+ setError(null);
236
+ };
237
+ // Text that still shows an absolute value's end keeps its exact instant.
238
+ const read = (field, input) => {
239
+ if (value?.kind === "absolute" && input === shown[field === "from" ? 0 : 1])
240
+ return { kind: "absolute", at: value[field] };
241
+ return parseRangeText(input, zone, now);
242
+ };
243
+ const submit = (event) => {
244
+ event.preventDefault();
245
+ const start = read("from", from);
246
+ const end = read("to", to);
247
+ if (!start)
248
+ return setError({ field: "from", message: text.invalidStart });
249
+ if (!end)
250
+ return setError({ field: "to", message: text.invalidEnd });
251
+ if (start.kind === "relative" && end.kind === "relative" && end.offset === 0) {
252
+ if (start.offset <= 0)
253
+ return setError({ field: "from", message: text.order });
254
+ if (start.offset > maxDuration)
255
+ return setError({ field: "from", message: text.retention });
256
+ reset();
257
+ return onApply({ kind: "relative", duration: start.offset });
258
+ }
259
+ const range = { from: resolveRangeText(start, now), to: resolveRangeText(end, now) };
260
+ if (!(range.from < range.to))
261
+ return setError({ field: "from", message: text.order });
262
+ if (!(range.from >= now - maxDuration))
263
+ return setError({ field: "from", message: text.retention });
264
+ if (!(range.to <= now))
265
+ return setError({ field: "to", message: text.future });
266
+ reset();
267
+ onApply({ kind: "absolute", ...range });
268
+ };
269
+ const hint = (input) => {
270
+ const parsed = parseRangeText(input, zone, now);
271
+ if (!parsed)
272
+ return text.fieldHint;
273
+ const at = resolveRangeText(parsed, now);
274
+ return validInstant(at) ? text.resolvedHint(formats.hint(at), parsed.kind === "relative") : text.fieldHint;
275
+ };
276
+ const fieldZone = zoneName(validInstant(now) ? now : Date.now(), zone, formats.language);
277
+ const day = (instant) => wallString(instant, zone, "second").slice(0, 10);
278
+ // The calendar appears when retention covers more than one calendar day.
279
+ const days = validInstant(now) && positive(maxDuration) && validInstant(now - maxDuration)
280
+ ? { min: day(now - maxDuration), max: day(now) } : null;
281
+ // A picked day keeps the field's time; a relative expression resolves first.
282
+ const pickDay = (field, input, picked) => {
283
+ const parsed = parseRangeText(input, zone, now);
284
+ const at = parsed ? resolveRangeText(parsed, now) : now;
285
+ change(field, `${picked} ${wallString(validInstant(at) ? at : now, zone, "second").slice(11)}`);
286
+ };
287
+ return _jsxs("form", { ref: form, className: "time-range-live-fields", noValidate: true, onSubmit: submit, children: [["from", "to"].map(field => {
288
+ const input = field === "from" ? from : to;
289
+ const id = `${baseId}-${field}`;
290
+ const failed = error?.field === field;
291
+ const parsed = parseRangeText(input, zone, now);
292
+ const at = parsed ? resolveRangeText(parsed, now) : NaN;
293
+ return _jsxs("div", { className: "field", children: [_jsx(Label, { htmlFor: id, children: text[field](fieldZone) }), _jsxs("div", { className: "field-control", children: [_jsx(Input, { id: id, value: input, autoComplete: "off", spellCheck: false, "aria-invalid": failed || undefined, "aria-describedby": failed ? `${id}-help ${id}-error` : `${id}-help`, onChange: event => change(field, event.target.value) }), days && days.min !== days.max && _jsx(RangeCalendar, { min: days.min, max: days.max, locale: formats.language, day: validInstant(at) ? day(at) : days.max, text: text, label: field === "from" ? text.chooseStartDate : text.chooseEndDate, onPick: picked => pickDay(field, input, picked) })] }), _jsx("small", { className: "field-hint", id: `${id}-help`, children: hint(input) }), failed && _jsx(ValidationMessage, { id: `${id}-error`, role: "alert", children: error.message })] }, field);
294
+ }), dirty && _jsxs("div", { className: "time-range-live-actions", children: [_jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: reset, children: text.reset }), _jsx(Button, { type: "submit", variant: "primary", size: "sm", children: text.apply })] })] });
295
+ }
296
+ function TimeZoneView({ zone, text, onBack, onChoose }) {
297
+ const [query, setQuery] = React.useState("");
298
+ const browser = browserTimeZone();
299
+ const search = query.trim().toLowerCase();
300
+ const matches = search ? timeZones().filter(item => item.toLowerCase().includes(search)).slice(0, 50) : [];
301
+ const option = (item, name) => _jsxs(Button, { variant: "ghost", className: "time-range-option", "aria-pressed": item === zone, onClick: () => onChoose(item), children: [_jsx("span", { children: name }), item === zone && _jsx(Check, { className: "icon icon-sm", "aria-hidden": "true" })] }, item);
302
+ return _jsxs("div", { className: "stack-sm", children: [_jsx(Button, { variant: "ghost", onClick: onBack, children: text.backToPresets }), _jsxs("div", { className: "time-range-presets", role: "group", "aria-label": text.timeZone, children: [option(browser, text.browserTimeZone(browser)), browser !== "UTC" && option("UTC", text.utc)] }), _jsx(Search, { "aria-label": text.searchTimeZones, placeholder: text.searchTimeZones, value: query, onChange: event => setQuery(event.target.value) }), search && (matches.length
303
+ ? _jsx("div", { className: "time-range-presets time-range-zones", role: "group", "aria-label": text.searchTimeZones, children: matches.map(item => option(item, item)) })
304
+ : _jsx("p", { className: "time-range-empty", children: text.noTimeZones }))] });
305
+ }