@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,297 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { 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, Layers, Search } from "lucide-react";
|
|
6
|
+
import { Popover as PopoverPrimitive, Slot } from "radix-ui";
|
|
7
|
+
import { Button } from "./button.js";
|
|
8
|
+
import { Skeleton } from "./skeleton.js";
|
|
9
|
+
import { Spinner } from "./spinner.js";
|
|
10
|
+
const NARROW = "(max-width: 699px)";
|
|
11
|
+
function subscribe(callback) {
|
|
12
|
+
const query = window.matchMedia(NARROW);
|
|
13
|
+
query.addEventListener("change", callback);
|
|
14
|
+
return () => query.removeEventListener("change", callback);
|
|
15
|
+
}
|
|
16
|
+
function useNarrow() {
|
|
17
|
+
return React.useSyncExternalStore(subscribe, () => window.matchMedia(NARROW).matches, () => false);
|
|
18
|
+
}
|
|
19
|
+
const ScopeContext = React.createContext({ compact: false, closeCompact: () => { }, tabOutCompact: () => { }, levelsRef: null });
|
|
20
|
+
const TABBABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
|
|
21
|
+
function tabbables(root) {
|
|
22
|
+
return Array.from(root.querySelectorAll(TABBABLE))
|
|
23
|
+
.filter((element) => !element.closest("[inert]") && element.getClientRects().length > 0);
|
|
24
|
+
}
|
|
25
|
+
// Focus the first tabbable after `from` in document order, skipping the
|
|
26
|
+
// popup that is closing. Radix portals popups to the end of the document,
|
|
27
|
+
// so plain Tab would leave focus there instead of after the trigger.
|
|
28
|
+
function nextTabbable(from, skip, within = document) {
|
|
29
|
+
if (!from)
|
|
30
|
+
return null;
|
|
31
|
+
const all = tabbables(within).filter((element) => !skip?.contains(element));
|
|
32
|
+
const index = all.indexOf(from);
|
|
33
|
+
return index === -1 ? null : all[index + 1] ?? null;
|
|
34
|
+
}
|
|
35
|
+
// Tab past the last control closes the popup and moves on from the trigger;
|
|
36
|
+
// Shift+Tab before the first closes it and returns to the trigger.
|
|
37
|
+
function boundaryTab(event, content) {
|
|
38
|
+
if (event.key !== "Tab" || !content || !content.contains(event.target))
|
|
39
|
+
return null;
|
|
40
|
+
const focusable = tabbables(content);
|
|
41
|
+
if (!event.shiftKey && document.activeElement === focusable[focusable.length - 1])
|
|
42
|
+
return "forward";
|
|
43
|
+
if (event.shiftKey && document.activeElement === focusable[0])
|
|
44
|
+
return "backward";
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
const SegmentContext = React.createContext(null);
|
|
48
|
+
function currentName(props) {
|
|
49
|
+
const { value, options, all, currentLabel, status = "ready", labels } = props;
|
|
50
|
+
if (all && value === all.value)
|
|
51
|
+
return all.label;
|
|
52
|
+
const option = options.find((item) => item.value === value);
|
|
53
|
+
if (option)
|
|
54
|
+
return option.label;
|
|
55
|
+
if (currentLabel)
|
|
56
|
+
return currentLabel;
|
|
57
|
+
if (status === "ready" && options.length === 0 && labels?.empty)
|
|
58
|
+
return labels.empty;
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
// Every character outside [A-Za-z0-9-] becomes _<code>_, so two values
|
|
62
|
+
// never share an id, and the -option- prefix keeps clear of the list id.
|
|
63
|
+
function optionId(base, value) {
|
|
64
|
+
return `${base}-option-${value.replace(/[^A-Za-z0-9-]/g, (c) => `_${c.codePointAt(0).toString(16)}_`)}`;
|
|
65
|
+
}
|
|
66
|
+
function matches(option, query) {
|
|
67
|
+
const needle = query.trim().toLocaleLowerCase();
|
|
68
|
+
return !needle
|
|
69
|
+
|| option.label.toLocaleLowerCase().includes(needle)
|
|
70
|
+
|| Boolean(option.description?.toLocaleLowerCase().includes(needle));
|
|
71
|
+
}
|
|
72
|
+
function ScopeSwitcher({ className, children, "aria-label": ariaLabel = "Scope", ...props }) {
|
|
73
|
+
const narrow = useNarrow();
|
|
74
|
+
const [open, setOpen] = React.useState(false);
|
|
75
|
+
const triggerRef = React.useRef(null);
|
|
76
|
+
const levelsRef = React.useRef(null);
|
|
77
|
+
const tabForward = React.useRef(false);
|
|
78
|
+
const tabOutCompact = () => { tabForward.current = true; setOpen(false); };
|
|
79
|
+
const segments = React.Children.toArray(children).filter((child) => React.isValidElement(child) && child.type === ScopeSegment);
|
|
80
|
+
const names = segments.map((segment) => currentName(segment.props) ?? "…");
|
|
81
|
+
const deepest = names[names.length - 1] ?? "";
|
|
82
|
+
if (narrow) {
|
|
83
|
+
return (_jsx("nav", { "data-slot": "scope-switcher", "data-compact": "", "aria-label": ariaLabel, className: cn("scope", className), ...props, children: _jsxs(PopoverPrimitive.Root, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverPrimitive.Trigger, { asChild: true, children: _jsxs(Button, { ref: triggerRef, variant: "ghost", className: "scope-compact", "aria-label": `${ariaLabel}: ${names.join(" / ")}`, children: [_jsx(Layers, { className: "icon icon-sm", "aria-hidden": "true" }), _jsx("span", { className: "scope-name", children: deepest }), _jsx(ChevronDown, { className: "icon icon-sm", "aria-hidden": "true" })] }) }), _jsx(PopoverPrimitive.Portal, { children: _jsx(PopoverPrimitive.Content, { ref: levelsRef, "aria-label": ariaLabel, align: "start", sideOffset: 4, collisionPadding: 16, className: "menu scope-popover kiso-react-floating", onKeyDown: (event) => {
|
|
84
|
+
const edge = boundaryTab(event, levelsRef.current);
|
|
85
|
+
if (!edge)
|
|
86
|
+
return;
|
|
87
|
+
event.preventDefault();
|
|
88
|
+
if (edge === "forward")
|
|
89
|
+
tabOutCompact();
|
|
90
|
+
else
|
|
91
|
+
setOpen(false);
|
|
92
|
+
}, onCloseAutoFocus: (event) => {
|
|
93
|
+
if (!tabForward.current)
|
|
94
|
+
return;
|
|
95
|
+
tabForward.current = false;
|
|
96
|
+
const next = nextTabbable(triggerRef.current, levelsRef.current);
|
|
97
|
+
if (next) {
|
|
98
|
+
event.preventDefault();
|
|
99
|
+
next.focus();
|
|
100
|
+
}
|
|
101
|
+
}, children: _jsx(ScopeContext.Provider, { value: { compact: true, closeCompact: () => setOpen(false), tabOutCompact, levelsRef }, children: _jsx("ol", { className: "scope-levels", children: children }) }) }) })] }) }));
|
|
102
|
+
}
|
|
103
|
+
return (_jsx("nav", { "data-slot": "scope-switcher", "aria-label": ariaLabel, className: cn("scope", className), ...props, children: _jsx(ScopeContext.Provider, { value: { compact: false, closeCompact: () => { }, tabOutCompact: () => { }, levelsRef: null }, children: _jsx("ol", { className: "scope-path", children: segments.map((segment, index) => (_jsxs(React.Fragment, { children: [index > 0 && _jsx("li", { className: "scope-sep", "aria-hidden": "true", children: "/" }), segment] }, segment.key ?? index))) }) }) }));
|
|
104
|
+
}
|
|
105
|
+
function ScopeSegment(props) {
|
|
106
|
+
const { level, value, options, all, searchable = false, status = "ready", onRetry, onValueChange, destinations, labels = {}, className, } = props;
|
|
107
|
+
const { compact, closeCompact, tabOutCompact, levelsRef } = React.useContext(ScopeContext);
|
|
108
|
+
const triggerRef = React.useRef(null);
|
|
109
|
+
const tabForward = React.useRef(false);
|
|
110
|
+
const [open, setOpen] = React.useState(false);
|
|
111
|
+
const [query, setQuery] = React.useState("");
|
|
112
|
+
const [activeValue, setActiveValue] = React.useState(null);
|
|
113
|
+
const base = React.useId();
|
|
114
|
+
const listId = `${base}-list`;
|
|
115
|
+
const statusId = `${base}-status`;
|
|
116
|
+
const contentRef = React.useRef(null);
|
|
117
|
+
const targetRef = React.useRef(null);
|
|
118
|
+
const composing = React.useRef(false);
|
|
119
|
+
const typed = React.useRef({ text: "", at: 0 });
|
|
120
|
+
const leavingCompact = React.useRef(false);
|
|
121
|
+
const listName = labels.list ?? level;
|
|
122
|
+
const name = currentName(props);
|
|
123
|
+
const ready = status === "ready";
|
|
124
|
+
const filtering = searchable && query.trim() !== "";
|
|
125
|
+
const named = ready ? options.filter((option) => matches(option, filtering ? query : "")) : [];
|
|
126
|
+
const showAll = Boolean(all) && ready && options.length > 0 && !filtering;
|
|
127
|
+
// Ungrouped options first, then each group in the order it first appears.
|
|
128
|
+
// Keyboard order follows this rendered order.
|
|
129
|
+
const grouped = [];
|
|
130
|
+
for (const option of named) {
|
|
131
|
+
const bucket = grouped.find((entry) => entry.group === option.group);
|
|
132
|
+
if (bucket)
|
|
133
|
+
bucket.items.push(option);
|
|
134
|
+
else
|
|
135
|
+
grouped.push({ group: option.group, items: [option] });
|
|
136
|
+
}
|
|
137
|
+
grouped.sort((a, b) => Number(a.group !== undefined) - Number(b.group !== undefined));
|
|
138
|
+
const visible = [...(showAll && all ? [all] : []), ...grouped.flatMap((entry) => entry.items)];
|
|
139
|
+
const visibleValues = visible.map((option) => option.value);
|
|
140
|
+
const active = activeValue !== null && visibleValues.includes(activeValue)
|
|
141
|
+
? activeValue
|
|
142
|
+
: value !== undefined && visibleValues.includes(value) ? value : visibleValues[0] ?? null;
|
|
143
|
+
const activeId = active === null ? undefined : optionId(base, active);
|
|
144
|
+
let statusText = "";
|
|
145
|
+
if (status === "loading")
|
|
146
|
+
statusText = labels.loading ?? `Loading ${listName.toLocaleLowerCase()}`;
|
|
147
|
+
else if (status === "error")
|
|
148
|
+
statusText = labels.error ?? `Couldn't load ${listName.toLocaleLowerCase()}.`;
|
|
149
|
+
else if (options.length === 0)
|
|
150
|
+
statusText = labels.empty ?? `No ${listName.toLocaleLowerCase()}.`;
|
|
151
|
+
else if (filtering && named.length === 0)
|
|
152
|
+
statusText = labels.noMatches?.(query.trim()) ?? `No ${listName.toLocaleLowerCase()} match "${query.trim()}"`;
|
|
153
|
+
function changeOpen(next) {
|
|
154
|
+
setOpen(next);
|
|
155
|
+
typed.current = { text: "", at: 0 };
|
|
156
|
+
if (!next) {
|
|
157
|
+
setQuery("");
|
|
158
|
+
setActiveValue(null);
|
|
159
|
+
}
|
|
160
|
+
else
|
|
161
|
+
setActiveValue(value ?? null);
|
|
162
|
+
}
|
|
163
|
+
function focusTarget() {
|
|
164
|
+
targetRef.current?.focus({ preventScroll: true });
|
|
165
|
+
}
|
|
166
|
+
function choose(next) {
|
|
167
|
+
leavingCompact.current = compact;
|
|
168
|
+
changeOpen(false);
|
|
169
|
+
if (next !== value)
|
|
170
|
+
onValueChange(next);
|
|
171
|
+
if (compact)
|
|
172
|
+
closeCompact();
|
|
173
|
+
}
|
|
174
|
+
// Status changes never move focus, but a focused element that disappears
|
|
175
|
+
// (Retry when loading starts) must not drop focus to the page.
|
|
176
|
+
React.useEffect(() => {
|
|
177
|
+
if (!open)
|
|
178
|
+
return;
|
|
179
|
+
const focused = document.activeElement;
|
|
180
|
+
if (!focused || focused === document.body)
|
|
181
|
+
focusTarget();
|
|
182
|
+
}, [open, status, visible.length]);
|
|
183
|
+
React.useEffect(() => {
|
|
184
|
+
if (!open || !activeId)
|
|
185
|
+
return;
|
|
186
|
+
document.getElementById(activeId)?.scrollIntoView({ block: "nearest" });
|
|
187
|
+
}, [open, activeId]);
|
|
188
|
+
function move(step) {
|
|
189
|
+
if (!visible.length)
|
|
190
|
+
return;
|
|
191
|
+
const index = active === null ? -1 : visibleValues.indexOf(active);
|
|
192
|
+
const next = index === -1
|
|
193
|
+
? (step > 0 ? 0 : visible.length - 1)
|
|
194
|
+
: (index + step + visible.length) % visible.length;
|
|
195
|
+
setActiveValue(visibleValues[next]);
|
|
196
|
+
}
|
|
197
|
+
function typeahead(key) {
|
|
198
|
+
const now = Date.now();
|
|
199
|
+
const text = now - typed.current.at > 500 ? key : typed.current.text + key;
|
|
200
|
+
typed.current = { text, at: now };
|
|
201
|
+
const needle = text.toLocaleLowerCase();
|
|
202
|
+
const start = active === null ? 0 : visibleValues.indexOf(active) + (text.length === 1 ? 1 : 0);
|
|
203
|
+
const order = [...visible.slice(start), ...visible.slice(0, start)];
|
|
204
|
+
const found = order.find((option) => option.label.toLocaleLowerCase().startsWith(needle));
|
|
205
|
+
if (found)
|
|
206
|
+
setActiveValue(found.value);
|
|
207
|
+
}
|
|
208
|
+
function onListKeyDown(event, inInput) {
|
|
209
|
+
if (composing.current || event.nativeEvent.isComposing || event.keyCode === 229)
|
|
210
|
+
return;
|
|
211
|
+
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
212
|
+
event.preventDefault();
|
|
213
|
+
move(event.key === "ArrowDown" ? 1 : -1);
|
|
214
|
+
}
|
|
215
|
+
else if (!inInput && (event.key === "Home" || event.key === "End")) {
|
|
216
|
+
event.preventDefault();
|
|
217
|
+
if (visible.length)
|
|
218
|
+
setActiveValue(visibleValues[event.key === "Home" ? 0 : visible.length - 1]);
|
|
219
|
+
}
|
|
220
|
+
else if (event.key === "Enter") {
|
|
221
|
+
event.preventDefault();
|
|
222
|
+
if (active !== null)
|
|
223
|
+
choose(active);
|
|
224
|
+
}
|
|
225
|
+
else if (!inInput && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey && event.key !== " ") {
|
|
226
|
+
typeahead(event.key);
|
|
227
|
+
}
|
|
228
|
+
else if (!inInput && event.key === " ") {
|
|
229
|
+
event.preventDefault();
|
|
230
|
+
if (active !== null)
|
|
231
|
+
choose(active);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
function onContentKeyDown(event) {
|
|
235
|
+
const edge = boundaryTab(event, contentRef.current);
|
|
236
|
+
if (!edge)
|
|
237
|
+
return;
|
|
238
|
+
event.preventDefault();
|
|
239
|
+
event.stopPropagation();
|
|
240
|
+
tabForward.current = edge === "forward";
|
|
241
|
+
changeOpen(false);
|
|
242
|
+
}
|
|
243
|
+
function renderOption(option, isAll = false) {
|
|
244
|
+
const id = optionId(base, option.value);
|
|
245
|
+
return (_jsxs("div", { id: id, role: "option", "aria-selected": option.value === value, "data-active": option.value === active ? "" : undefined, "data-all": isAll ? "" : undefined, className: "menu-item scope-option", onPointerMove: () => setActiveValue(option.value), onClick: () => choose(option.value), children: [_jsxs("span", { className: "scope-option-text", children: [_jsx("span", { children: option.label }), option.description && _jsx("span", { className: "scope-option-description", children: option.description })] }), _jsx(Check, { className: "icon icon-sm scope-check", "aria-hidden": "true" })] }, option.value));
|
|
246
|
+
}
|
|
247
|
+
const unknown = name === undefined;
|
|
248
|
+
const trigger = (_jsx(PopoverPrimitive.Trigger, { asChild: true, children: _jsxs(Button, { ref: triggerRef, variant: "ghost", className: "scope-trigger", "aria-label": unknown ? `${level}, ${labels.unknown ?? "loading"}` : `${level} ${name}`, onKeyDown: (event) => {
|
|
249
|
+
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
250
|
+
event.preventDefault();
|
|
251
|
+
changeOpen(true);
|
|
252
|
+
}
|
|
253
|
+
}, children: [unknown ? _jsx(Skeleton, {}) : _jsx("span", { className: "scope-name", children: name }), _jsx(ChevronDown, { className: "icon icon-sm", "aria-hidden": "true" })] }) }));
|
|
254
|
+
return (_jsx("li", { "data-slot": "scope-segment", className: cn(compact ? "scope-level" : "scope-segment", className), children: _jsxs(PopoverPrimitive.Root, { open: open, onOpenChange: changeOpen, children: [compact && _jsx("span", { className: "scope-level-label", "aria-hidden": "true", children: level }), trigger, _jsx(PopoverPrimitive.Portal, { children: _jsxs(PopoverPrimitive.Content, { ref: contentRef, "data-slot": "scope-segment-content", "aria-label": labels.dialog ?? `Switch ${level.toLocaleLowerCase()}`, align: "start", sideOffset: 4, collisionPadding: 16, className: "menu scope-popover kiso-react-floating", onOpenAutoFocus: (event) => { event.preventDefault(); focusTarget(); }, onCloseAutoFocus: (event) => {
|
|
255
|
+
// A choice made from the compact popup returns focus to the
|
|
256
|
+
// compact trigger, which the outer popover handles.
|
|
257
|
+
if (leavingCompact.current) {
|
|
258
|
+
event.preventDefault();
|
|
259
|
+
leavingCompact.current = false;
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (!tabForward.current)
|
|
263
|
+
return;
|
|
264
|
+
tabForward.current = false;
|
|
265
|
+
event.preventDefault();
|
|
266
|
+
// Inside the compact popup, move on to the next level, and
|
|
267
|
+
// past the last one leave the compact popup too.
|
|
268
|
+
const within = compact && levelsRef?.current ? levelsRef.current : document;
|
|
269
|
+
const next = nextTabbable(triggerRef.current, contentRef.current, within);
|
|
270
|
+
if (next)
|
|
271
|
+
next.focus();
|
|
272
|
+
else if (compact) {
|
|
273
|
+
triggerRef.current?.focus();
|
|
274
|
+
tabOutCompact();
|
|
275
|
+
}
|
|
276
|
+
else
|
|
277
|
+
triggerRef.current?.focus();
|
|
278
|
+
}, onEscapeKeyDown: (event) => {
|
|
279
|
+
if (composing.current || event.isComposing || event.keyCode === 229)
|
|
280
|
+
event.preventDefault();
|
|
281
|
+
}, onKeyDown: onContentKeyDown, children: [searchable && (_jsxs("div", { className: "scope-filter", children: [_jsx(Search, { className: "icon icon-sm muted", "aria-hidden": "true" }), _jsx("input", { ref: (element) => { targetRef.current = element; }, role: "combobox", "aria-label": labels.filter ?? `Filter ${listName.toLocaleLowerCase()}`, "aria-expanded": "true", "aria-controls": listId, "aria-autocomplete": "list", "aria-activedescendant": activeId, "aria-describedby": statusText ? statusId : undefined, autoComplete: "off", spellCheck: false, placeholder: labels.filter ?? `Filter ${listName.toLocaleLowerCase()}`, value: query, onChange: (event) => { setQuery(event.target.value); setActiveValue(null); }, onKeyDown: (event) => onListKeyDown(event, true), onCompositionStart: () => { composing.current = true; }, onCompositionEnd: () => { composing.current = false; } })] })), _jsxs("div", { id: listId, ref: searchable ? undefined : (element) => { targetRef.current = element; }, role: "listbox", "aria-label": listName, "aria-busy": status === "loading" || undefined, "aria-activedescendant": searchable ? undefined : activeId, "aria-describedby": !searchable && statusText ? statusId : undefined, tabIndex: searchable ? -1 : 0, className: "scope-list", onKeyDown: searchable ? undefined : (event) => onListKeyDown(event, false), children: [showAll && all && renderOption(all, true), grouped.map((entry, index) => entry.group === undefined
|
|
282
|
+
? entry.items.map((option) => renderOption(option))
|
|
283
|
+
: (_jsxs("div", { role: "group", "aria-labelledby": `${base}-g${index}`, className: "scope-group", children: [_jsx("div", { id: `${base}-g${index}`, role: "presentation", className: "scope-group-label t-caps", children: entry.group }), entry.items.map((option) => renderOption(option))] }, `group-${index}`)))] }), _jsxs("div", { id: statusId, role: "status", className: "scope-status", "data-tone": status === "error" ? "danger" : undefined, children: [status === "loading" && _jsx(Spinner, { size: "sm" }), statusText] }), status === "error" && onRetry && (_jsx(Button, { size: "sm", className: "scope-retry", onClick: () => { focusTarget(); onRetry(); }, children: labels.retry ?? "Retry" })), destinations && (_jsx(SegmentContext.Provider, { value: { close: () => { leavingCompact.current = compact; changeOpen(false); if (compact)
|
|
284
|
+
closeCompact(); } }, children: _jsx("div", { className: "scope-destinations", children: destinations }) }))] }) })] }) }));
|
|
285
|
+
}
|
|
286
|
+
// A page about the level, such as "Manage projects". A real link, so
|
|
287
|
+
// open-in-new-tab works; asChild takes a router link.
|
|
288
|
+
function ScopeDestination({ className, asChild = false, onClick, ...props }) {
|
|
289
|
+
const segment = React.useContext(SegmentContext);
|
|
290
|
+
const Comp = asChild ? Slot.Root : "a";
|
|
291
|
+
return (_jsx(Comp, { "data-slot": "scope-destination", className: cn("menu-item scope-destination", className), onClick: (event) => {
|
|
292
|
+
onClick?.(event);
|
|
293
|
+
if (!event.defaultPrevented && !event.metaKey && !event.ctrlKey && !event.shiftKey && event.button === 0)
|
|
294
|
+
segment?.close();
|
|
295
|
+
}, ...props }));
|
|
296
|
+
}
|
|
297
|
+
export { ScopeSwitcher, ScopeSegment, ScopeDestination };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import type { TimeRangeControlLabels } from "./time-range-shared.js";
|
|
3
|
+
/** A month grid that picks one day between `min` and `max`, opened from an icon button. */
|
|
4
|
+
export declare function RangeCalendar({ day, min, max, locale, label, text, onPick }: {
|
|
5
|
+
day: string;
|
|
6
|
+
min: string;
|
|
7
|
+
max: string;
|
|
8
|
+
locale: string | undefined;
|
|
9
|
+
label: string;
|
|
10
|
+
text: TimeRangeControlLabels;
|
|
11
|
+
onPick: (day: string) => void;
|
|
12
|
+
}): React.JSX.Element;
|
|
@@ -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
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
|
|
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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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", " ")
|
|
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:
|
|
47
|
+
}), _jsx(Button, { variant: "ghost", onClick: () => setCustom(true), children: text.custom })] }) })] });
|
|
39
48
|
}
|
|
40
|
-
function
|
|
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
|
-
|
|
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(
|
|
68
|
+
setError(text.error);
|
|
50
69
|
return;
|
|
51
70
|
}
|
|
52
71
|
onApply(range);
|
|
53
|
-
}, children: [_jsx("label", { htmlFor: `${id}-from`, children:
|
|
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;
|