@momoi-labs/kiso-react 0.22.1 → 0.24.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.
- package/dist/accent-selector.d.ts +1 -1
- package/dist/accent-selector.js +3 -0
- package/dist/chart.d.ts +6 -2
- package/dist/chart.js +17 -3
- package/dist/code-block.d.ts +21 -0
- package/dist/code-block.js +148 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/scope-switcher.d.ts +49 -0
- package/dist/scope-switcher.js +297 -0
- package/dist/time-range-calendar.d.ts +12 -0
- package/dist/time-range-calendar.js +102 -0
- package/dist/time-range-control.d.ts +28 -12
- package/dist/time-range-control.js +41 -22
- package/dist/time-range-live.d.ts +18 -0
- package/dist/time-range-live.js +305 -0
- package/dist/time-range-shared.d.ts +91 -0
- package/dist/time-range-shared.js +87 -0
- package/dist/time-range-text.d.ts +13 -0
- package/dist/time-range-text.js +44 -0
- package/dist/time-zone.d.ts +15 -0
- package/dist/time-zone.js +121 -0
- package/package.json +2 -2
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export type TimeRange = {
|
|
2
|
+
from: number;
|
|
3
|
+
to: number;
|
|
4
|
+
};
|
|
5
|
+
/** A live value: relative follows the wall clock, absolute is paused. */
|
|
6
|
+
export type LiveTimeRange = {
|
|
7
|
+
kind: "relative";
|
|
8
|
+
duration: number;
|
|
9
|
+
} | {
|
|
10
|
+
kind: "absolute";
|
|
11
|
+
from: number;
|
|
12
|
+
to: number;
|
|
13
|
+
};
|
|
14
|
+
export type TimeRangePreset = {
|
|
15
|
+
label: string;
|
|
16
|
+
duration: number;
|
|
17
|
+
};
|
|
18
|
+
export type TimeRangeUnit = "second" | "minute" | "hour" | "day";
|
|
19
|
+
export type TimeRangeState = "live" | "paused";
|
|
20
|
+
export declare const defaultLabels: {
|
|
21
|
+
entireRun: string;
|
|
22
|
+
custom: string;
|
|
23
|
+
backToPresets: string;
|
|
24
|
+
backToLive: string;
|
|
25
|
+
apply: string;
|
|
26
|
+
from: (zone: string) => string;
|
|
27
|
+
to: (zone: string) => string;
|
|
28
|
+
error: string;
|
|
29
|
+
presets: string;
|
|
30
|
+
live: string;
|
|
31
|
+
paused: string;
|
|
32
|
+
pause: string;
|
|
33
|
+
resume: string;
|
|
34
|
+
reset: string;
|
|
35
|
+
relative: (count: number, unit: TimeRangeUnit) => string;
|
|
36
|
+
duration: (count: number, unit: TimeRangeUnit) => string;
|
|
37
|
+
/** Visible range text: short times and the zone name. */
|
|
38
|
+
range: (from: string, to: string, zone: string) => string;
|
|
39
|
+
/** Full timestamps for the tooltip and the accessible name. */
|
|
40
|
+
fullRange: (from: string, to: string) => string;
|
|
41
|
+
triggerName: ({ label, state, text, range }: {
|
|
42
|
+
label: string;
|
|
43
|
+
state: string;
|
|
44
|
+
text: string;
|
|
45
|
+
range: string;
|
|
46
|
+
}) => string;
|
|
47
|
+
now: string;
|
|
48
|
+
keeps: (duration: string) => string;
|
|
49
|
+
olderThanRetention: string;
|
|
50
|
+
releaseToLive: (text: string) => string;
|
|
51
|
+
fieldHint: string;
|
|
52
|
+
resolvedHint: (time: string, followsClock: boolean) => string;
|
|
53
|
+
invalidStart: string;
|
|
54
|
+
invalidEnd: string;
|
|
55
|
+
order: string;
|
|
56
|
+
retention: string;
|
|
57
|
+
future: string;
|
|
58
|
+
moveRange: string;
|
|
59
|
+
rangeStart: string;
|
|
60
|
+
rangeEnd: string;
|
|
61
|
+
chooseStartDate: string;
|
|
62
|
+
chooseEndDate: string;
|
|
63
|
+
previousMonth: string;
|
|
64
|
+
nextMonth: string;
|
|
65
|
+
outsideRetention: string;
|
|
66
|
+
timeZone: string;
|
|
67
|
+
timeZoneButton: (zone: string) => string;
|
|
68
|
+
browserTimeZone: (zone: string) => string;
|
|
69
|
+
utc: string;
|
|
70
|
+
searchTimeZones: string;
|
|
71
|
+
noTimeZones: string;
|
|
72
|
+
unavailable: string;
|
|
73
|
+
};
|
|
74
|
+
export type TimeRangeControlLabels = typeof defaultLabels;
|
|
75
|
+
export declare const defaultPresets: {
|
|
76
|
+
label: string;
|
|
77
|
+
duration: number;
|
|
78
|
+
}[];
|
|
79
|
+
export declare const validRange: (range: TimeRange) => boolean;
|
|
80
|
+
export declare const units: [TimeRangeUnit, number][];
|
|
81
|
+
export declare const positive: (value: number) => boolean;
|
|
82
|
+
export declare const ceilSecond: (value: number) => number;
|
|
83
|
+
export declare const floorSecond: (value: number) => number;
|
|
84
|
+
export declare function documentLocale(): string | undefined;
|
|
85
|
+
export declare function validLocale(locale: string | undefined): string | undefined;
|
|
86
|
+
/** A duration in the largest unit that divides it, through a label template. */
|
|
87
|
+
export declare function durationText(duration: number, template: (count: number, unit: TimeRangeUnit) => string): string;
|
|
88
|
+
/** The smallest span a drag or slider keeps: one second, or all of a shorter retention. */
|
|
89
|
+
export declare const minimumSpan: (maxDuration: number) => number;
|
|
90
|
+
/** A drag released at now: the minute when it fits retention, else the second. */
|
|
91
|
+
export declare function snapDuration(span: number, maxDuration: number): number;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { validInstant } from "./time-zone.js";
|
|
2
|
+
export const defaultLabels = {
|
|
3
|
+
entireRun: "Entire run",
|
|
4
|
+
custom: "Custom range",
|
|
5
|
+
backToPresets: "Back to presets",
|
|
6
|
+
backToLive: "Back to live",
|
|
7
|
+
apply: "Apply range",
|
|
8
|
+
from: (zone) => `From (${zone})`,
|
|
9
|
+
to: (zone) => `To (${zone})`,
|
|
10
|
+
error: "Choose a start before the end, within the collection window.",
|
|
11
|
+
presets: "Presets",
|
|
12
|
+
live: "Live",
|
|
13
|
+
paused: "Paused",
|
|
14
|
+
pause: "Pause",
|
|
15
|
+
resume: "Resume live",
|
|
16
|
+
reset: "Reset",
|
|
17
|
+
relative: (count, unit) => `Last ${count} ${unit}${count === 1 ? "" : "s"}`,
|
|
18
|
+
duration: (count, unit) => `${count} ${unit}${count === 1 ? "" : "s"}`,
|
|
19
|
+
/** Visible range text: short times and the zone name. */
|
|
20
|
+
range: (from, to, zone) => `${from} to ${to} ${zone}`,
|
|
21
|
+
/** Full timestamps for the tooltip and the accessible name. */
|
|
22
|
+
fullRange: (from, to) => `${from} to ${to}`,
|
|
23
|
+
triggerName: ({ label, state, text, range }) => `${label}, ${state}: ${text}, ${range}`,
|
|
24
|
+
now: "now",
|
|
25
|
+
keeps: (duration) => `Keeps ${duration}.`,
|
|
26
|
+
olderThanRetention: "This range is older than the data kept.",
|
|
27
|
+
releaseToLive: (text) => `Release to follow the clock: ${text}.`,
|
|
28
|
+
fieldHint: "Use now-15m, a time like 16:37, or 2026-10-28 16:37:05.",
|
|
29
|
+
resolvedHint: (time, followsClock) => followsClock ? `${time}, follows the clock` : time,
|
|
30
|
+
invalidStart: "Enter a start like now-15m, 16:37, or 2026-10-28 16:37:05.",
|
|
31
|
+
invalidEnd: "Enter an end like now, 16:37, or 2026-10-28 16:37:05.",
|
|
32
|
+
order: "The start must be before the end.",
|
|
33
|
+
retention: "The start must be within the data kept.",
|
|
34
|
+
future: "The end cannot be in the future.",
|
|
35
|
+
moveRange: "Move range",
|
|
36
|
+
rangeStart: "Range start",
|
|
37
|
+
rangeEnd: "Range end",
|
|
38
|
+
chooseStartDate: "Choose start date",
|
|
39
|
+
chooseEndDate: "Choose end date",
|
|
40
|
+
previousMonth: "Previous month",
|
|
41
|
+
nextMonth: "Next month",
|
|
42
|
+
outsideRetention: "outside the data kept",
|
|
43
|
+
timeZone: "Time zone",
|
|
44
|
+
timeZoneButton: (zone) => `Time zone: ${zone}`,
|
|
45
|
+
browserTimeZone: (zone) => `Browser time zone (${zone})`,
|
|
46
|
+
utc: "UTC",
|
|
47
|
+
searchTimeZones: "Search time zones",
|
|
48
|
+
noTimeZones: "No matching time zones.",
|
|
49
|
+
unavailable: "Time unavailable",
|
|
50
|
+
};
|
|
51
|
+
export const defaultPresets = [
|
|
52
|
+
{ label: "Last 5 minutes", duration: 300_000 },
|
|
53
|
+
{ label: "Last 15 minutes", duration: 900_000 },
|
|
54
|
+
{ label: "Last 30 minutes", duration: 1_800_000 },
|
|
55
|
+
];
|
|
56
|
+
export const validRange = (range) => validInstant(range.from) && validInstant(range.to) && range.from < range.to;
|
|
57
|
+
export const units = [["day", 86_400_000], ["hour", 3_600_000], ["minute", 60_000], ["second", 1000]];
|
|
58
|
+
export const positive = (value) => Number.isFinite(value) && value > 0;
|
|
59
|
+
export const ceilSecond = (value) => Math.ceil(value / 1000) * 1000;
|
|
60
|
+
export const floorSecond = (value) => Math.floor(value / 1000) * 1000;
|
|
61
|
+
export function documentLocale() {
|
|
62
|
+
return typeof document === "undefined" ? undefined : document.documentElement.lang || undefined;
|
|
63
|
+
}
|
|
64
|
+
export function validLocale(locale) {
|
|
65
|
+
if (locale === undefined)
|
|
66
|
+
return undefined;
|
|
67
|
+
try {
|
|
68
|
+
return Intl.getCanonicalLocales(locale)[0];
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** A duration in the largest unit that divides it, through a label template. */
|
|
75
|
+
export function durationText(duration, template) {
|
|
76
|
+
const [unit, size] = units.find(([, size]) => duration % size === 0) ?? ["second", 1000];
|
|
77
|
+
return template(Math.max(1, Math.round(duration / size)), unit);
|
|
78
|
+
}
|
|
79
|
+
/** The smallest span a drag or slider keeps: one second, or all of a shorter retention. */
|
|
80
|
+
export const minimumSpan = (maxDuration) => Math.min(1000, maxDuration);
|
|
81
|
+
/** A drag released at now: the minute when it fits retention, else the second. */
|
|
82
|
+
export function snapDuration(span, maxDuration) {
|
|
83
|
+
const minute = Math.round(span / 60_000) * 60_000;
|
|
84
|
+
if (minute >= 60_000 && minute <= maxDuration)
|
|
85
|
+
return minute;
|
|
86
|
+
return Math.min(maxDuration, Math.max(minimumSpan(maxDuration), Math.round(span / 1000) * 1000));
|
|
87
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type RangeText = {
|
|
2
|
+
kind: "relative";
|
|
3
|
+
offset: number;
|
|
4
|
+
} | {
|
|
5
|
+
kind: "absolute";
|
|
6
|
+
at: number;
|
|
7
|
+
};
|
|
8
|
+
/** Reads field text; `now` gives today's date for a time of day. Null when invalid. */
|
|
9
|
+
export declare function parseRangeText(text: string, zone: string, now: number): RangeText | null;
|
|
10
|
+
export declare const resolveRangeText: (text: RangeText, now: number) => number;
|
|
11
|
+
/** `now-30m`, in the largest unit that divides the duration. */
|
|
12
|
+
export declare function relativeRangeText(duration: number): string;
|
|
13
|
+
export declare const absoluteRangeText: (instant: number, zone: string) => string;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Text for the live range fields: `now`, `now-15m`, `16:37[:05]`, or
|
|
2
|
+
// `2026-10-28 16:37[:05]`, read in a time zone. Values stay epoch milliseconds.
|
|
3
|
+
import { parseWallTime, validInstant, wallString } from "./time-zone.js";
|
|
4
|
+
const unitSizes = { d: 86_400_000, h: 3_600_000, m: 60_000, s: 1000 };
|
|
5
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
6
|
+
const daysIn = (year, month) => {
|
|
7
|
+
const date = new Date(0);
|
|
8
|
+
date.setUTCFullYear(year, month, 0);
|
|
9
|
+
return date.getUTCDate();
|
|
10
|
+
};
|
|
11
|
+
function wallInstant(date, hour, minute, second, zone) {
|
|
12
|
+
const [year, month, day] = date.split("-").map(Number);
|
|
13
|
+
if (month < 1 || month > 12 || day < 1 || day > daysIn(year, month))
|
|
14
|
+
return NaN;
|
|
15
|
+
if (hour > 23 || minute > 59 || second > 59)
|
|
16
|
+
return NaN;
|
|
17
|
+
return parseWallTime(`${date}T${pad(hour)}:${pad(minute)}:${pad(second)}`, zone);
|
|
18
|
+
}
|
|
19
|
+
/** Reads field text; `now` gives today's date for a time of day. Null when invalid. */
|
|
20
|
+
export function parseRangeText(text, zone, now) {
|
|
21
|
+
const value = text.trim().toLowerCase();
|
|
22
|
+
const relative = /^now(?:\s*-\s*(\d+)\s*([smhd]))?$/.exec(value);
|
|
23
|
+
if (relative) {
|
|
24
|
+
const offset = relative[1] ? Number(relative[1]) * unitSizes[relative[2]] : 0;
|
|
25
|
+
return Number.isSafeInteger(offset) ? { kind: "relative", offset } : null;
|
|
26
|
+
}
|
|
27
|
+
const full = /^(\d{4}-\d{2}-\d{2})[ t](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value);
|
|
28
|
+
const clock = full ? null : /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value);
|
|
29
|
+
if (!full && !clock)
|
|
30
|
+
return null;
|
|
31
|
+
if (clock && !validInstant(now))
|
|
32
|
+
return null;
|
|
33
|
+
const date = full ? full[1] : wallString(now, zone, "second").slice(0, 10);
|
|
34
|
+
const [hour, minute, second = "0"] = (full ? full.slice(2) : clock.slice(1)).map(part => part ?? "0");
|
|
35
|
+
const at = wallInstant(date, Number(hour), Number(minute), Number(second), zone);
|
|
36
|
+
return validInstant(at) ? { kind: "absolute", at } : null;
|
|
37
|
+
}
|
|
38
|
+
export const resolveRangeText = (text, now) => text.kind === "relative" ? now - text.offset : text.at;
|
|
39
|
+
/** `now-30m`, in the largest unit that divides the duration. */
|
|
40
|
+
export function relativeRangeText(duration) {
|
|
41
|
+
const unit = Object.keys(unitSizes).find(key => duration % unitSizes[key] === 0);
|
|
42
|
+
return unit ? `now-${duration / unitSizes[unit]}${unit}` : `now-${Math.max(1, Math.round(duration / 1000))}s`;
|
|
43
|
+
}
|
|
44
|
+
export const absoluteRangeText = (instant, zone) => validInstant(instant) ? wallString(instant, zone, "second").replace("T", " ") : "";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare function dateFormat(locale: string | undefined, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat;
|
|
2
|
+
export declare const browserTimeZone: () => string;
|
|
3
|
+
export declare const validTimeZone: (zone: unknown) => zone is string;
|
|
4
|
+
export declare const validInstant: (value: number) => boolean;
|
|
5
|
+
export declare function timeZones(): string[];
|
|
6
|
+
/** The zone's offset from UTC at an instant, in milliseconds. */
|
|
7
|
+
export declare function zoneOffset(value: number, zone: string): number;
|
|
8
|
+
/** Wall-clock time of an instant in a zone, as a datetime-local value. */
|
|
9
|
+
export declare function wallString(value: number, zone: string, precision: "second" | "millisecond"): string;
|
|
10
|
+
/** Instant of a datetime-local wall time in a zone. A wall time inside a
|
|
11
|
+
daylight-saving gap moves forward to the first valid instant; one inside an
|
|
12
|
+
overlap takes the earlier instant. Returns NaN for unparsable input. */
|
|
13
|
+
export declare function parseWallTime(text: string, zone: string): number;
|
|
14
|
+
/** A short zone name at an instant, such as "UTC" or "GMT-3". */
|
|
15
|
+
export declare function zoneName(value: number, zone: string, locale?: string): string;
|