next-data-kit 11.0.0 → 12.0.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/ui.js ADDED
@@ -0,0 +1,696 @@
1
+ 'use client';
2
+ import {
3
+ dataKitUrlEncode,
4
+ useDataKit
5
+ } from "./chunk-BERW2A2B.js";
6
+
7
+ // src/ui/action-bar.tsx
8
+ import { useEffect, useId, useRef, useState } from "react";
9
+ import { createPortal } from "react-dom";
10
+
11
+ // src/ui/icon.tsx
12
+ import { jsx, jsxs } from "react/jsx-runtime";
13
+ var dataKitIconPath = {
14
+ plus: "M12 8v8M8 12h8",
15
+ clear: "m15 9-6 6M9 9l6 6",
16
+ x: "M18 6 6 18M6 6l12 12",
17
+ up: "m5 12 7-7 7 7M12 19V5",
18
+ down: "M12 5v14m7-7-7 7-7-7",
19
+ sort: "m7 15 5 5 5-5M7 9l5-5 5 5",
20
+ chevronDown: "m6 9 6 6 6-6",
21
+ chevronLeft: "m15 18-6-6 6-6",
22
+ chevronRight: "m9 18 6-6-6-6"
23
+ };
24
+ var DataKitIcon = (props) => {
25
+ const { name } = props;
26
+ return /* @__PURE__ */ jsxs("svg", { "data-slot": "data-kit-icon", "aria-hidden": true, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", children: [
27
+ (name === "plus" || name === "clear") && /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10" }),
28
+ /* @__PURE__ */ jsx("path", { d: dataKitIconPath[name] })
29
+ ] });
30
+ };
31
+
32
+ // src/ui/labels.tsx
33
+ import { createContext, useContext } from "react";
34
+ import { jsx as jsx2 } from "react/jsx-runtime";
35
+ var dataKitLabels = {
36
+ search: { placeholder: "Search\u2026" },
37
+ filter: { yes: "Yes", no: "No", min: "Min", max: "Max", find: "Find\u2026", reset: "Reset", clear: "Clear filter", empty: "No options", selected: (count) => `${count} selected` },
38
+ date: {
39
+ from: "From",
40
+ to: "To",
41
+ // ** "1h" → Last hour, "24h" → Last 24 hours, "7d" → Last 7 days
42
+ preset: (value) => value.slice(0, -1) === "1" ? `Last ${value.endsWith("h") ? "hour" : "day"}` : `Last ${value.slice(0, -1)} ${value.endsWith("h") ? "hours" : "days"}`,
43
+ format: (date) => date.toLocaleDateString(),
44
+ formatTime: (date) => date.toLocaleString(void 0, { dateStyle: "medium", timeStyle: "short" }),
45
+ formatClock: (date) => date.toLocaleTimeString(void 0, { timeStyle: "short" }),
46
+ zone: (zone) => `Times in ${zone}`
47
+ },
48
+ compare: {
49
+ eq: { symbol: "=", label: "equals" },
50
+ ne: { symbol: "\u2260", label: "not equal to" },
51
+ gt: { symbol: ">", label: "greater than" },
52
+ gte: { symbol: "\u2265", label: "at least" },
53
+ lt: { symbol: "<", label: "less than" },
54
+ lte: { symbol: "\u2264", label: "at most" }
55
+ },
56
+ exists: { has: "Has value", empty: "Is empty" },
57
+ tags: { placeholder: "Add\u2026", remove: (value) => `Remove ${value}` },
58
+ table: { empty: "No results.", all: "Select all", row: "Select row" },
59
+ pagination: {
60
+ label: "Pagination",
61
+ previous: "Previous",
62
+ next: "Next",
63
+ size: (size) => `${size} / page`,
64
+ summary: (props) => props.count === null ? `Page ${props.number}` : `Page ${props.number} of ${props.count} \xB7 ${props.total} total`
65
+ },
66
+ selection: { label: "Actions for the selected rows", selected: (count) => `${count} selected`, clear: "Clear selection" },
67
+ infinite: { loading: "Loading\u2026", end: "That's everything" }
68
+ };
69
+ var DataKitLabelsContext = createContext(dataKitLabels);
70
+ var DataKitLabelsProvider = (props) => {
71
+ const { labels, children } = props;
72
+ const outer = useContext(DataKitLabelsContext);
73
+ const merged = Object.fromEntries(Object.entries(outer).map(([part, value]) => [part, { ...value, ...labels[part] }]));
74
+ return /* @__PURE__ */ jsx2(DataKitLabelsContext.Provider, { value: merged, children });
75
+ };
76
+ var useDataKitLabels = () => useContext(DataKitLabelsContext);
77
+
78
+ // src/ui/action-bar.tsx
79
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
80
+ var dataKitActionBarLast = "";
81
+ var useDataKitActionBar = (props) => {
82
+ const { table } = props;
83
+ const id = useId();
84
+ const ref = useRef(null);
85
+ const [stack, setStack] = useState(null);
86
+ const count = table.selection.count;
87
+ useEffect(() => {
88
+ let element = document.querySelector('[data-slot="data-kit-action-bars"]');
89
+ if (!element) {
90
+ element = Object.assign(document.createElement("div"), { role: "presentation" });
91
+ element.dataset.slot = "data-kit-action-bars";
92
+ element.style.cssText = "position:fixed;inset-inline:0;bottom:1.5rem;z-index:50;display:flex;flex-direction:column;align-items:center;gap:.5rem;pointer-events:none";
93
+ document.body.append(element);
94
+ }
95
+ setStack(element);
96
+ }, []);
97
+ useEffect(() => {
98
+ if (count) dataKitActionBarLast = id;
99
+ }, [count]);
100
+ useEffect(() => {
101
+ if (!count) return;
102
+ const listener = (event) => {
103
+ if (event.key !== "Escape" || event.defaultPrevented || document.querySelector(":popover-open") || document.activeElement?.closest('[popover], [role="dialog"], [role="menu"], [role="listbox"], [data-slot="popover-content"]')) return;
104
+ const focused = document.activeElement?.closest('[data-slot="data-kit-action-bars"]') ? ref.current?.contains(document.activeElement) : dataKitActionBarLast === id;
105
+ if (focused) table.selection.clear();
106
+ };
107
+ window.addEventListener("keydown", listener);
108
+ return () => window.removeEventListener("keydown", listener);
109
+ });
110
+ return { ref, stack, count };
111
+ };
112
+ var DataKitActionBar = (props) => {
113
+ const { table, children } = props;
114
+ const labels = useDataKitLabels();
115
+ const bar = useDataKitActionBar({ table });
116
+ if (!bar.stack || !bar.count) return null;
117
+ return createPortal(
118
+ /* @__PURE__ */ jsxs2("div", { ref: bar.ref, role: "toolbar", "aria-label": labels.selection.label, "data-slot": "data-kit-action-bar", children: [
119
+ /* @__PURE__ */ jsxs2("div", { "data-slot": "data-kit-action-bar-count", children: [
120
+ /* @__PURE__ */ jsx3("span", { "aria-live": "polite", children: labels.selection.selected(bar.count) }),
121
+ /* @__PURE__ */ jsx3("button", { type: "button", "aria-label": labels.selection.clear, onClick: table.selection.clear, children: /* @__PURE__ */ jsx3(DataKitIcon, { name: "x" }) })
122
+ ] }),
123
+ /* @__PURE__ */ jsx3("div", { "data-slot": "data-kit-action-bar-actions", children })
124
+ ] }),
125
+ bar.stack
126
+ );
127
+ };
128
+
129
+ // src/ui/pagination.tsx
130
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
131
+ var DataKitPagination = (props) => {
132
+ const { table, size } = props;
133
+ const labels = useDataKitLabels();
134
+ const page = table.page;
135
+ return /* @__PURE__ */ jsxs3("div", { "data-slot": "data-kit-pagination", children: [
136
+ /* @__PURE__ */ jsx4("span", { "data-slot": "data-kit-summary", children: labels.pagination.summary({ number: page.number, count: page.count, total: page.total }) }),
137
+ size && /* @__PURE__ */ jsxs3("span", { "data-slot": "data-kit-select", children: [
138
+ /* @__PURE__ */ jsx4("select", { "data-slot": "data-kit-size", "aria-label": labels.pagination.size(page.size.value), value: page.size.value, onChange: (event) => page.size.set(Number(event.target.value)), children: [.../* @__PURE__ */ new Set([...size, page.size.value])].sort((a, b) => a - b).map((option) => /* @__PURE__ */ jsx4("option", { value: option, children: labels.pagination.size(option) }, option)) }),
139
+ /* @__PURE__ */ jsx4(DataKitIcon, { name: "chevronDown" })
140
+ ] }),
141
+ /* @__PURE__ */ jsxs3("nav", { "aria-label": labels.pagination.label, children: [
142
+ /* @__PURE__ */ jsxs3("a", { "data-slot": "data-kit-page", ...page.link(page.number - 1, page.number > 1), children: [
143
+ /* @__PURE__ */ jsx4(DataKitIcon, { name: "chevronLeft" }),
144
+ labels.pagination.previous
145
+ ] }),
146
+ page.list.map(
147
+ (item, index) => item === "gap" ? /* @__PURE__ */ jsx4("span", { "data-slot": "data-kit-gap", "aria-hidden": true, children: "\u2026" }, `gap-${index}`) : /* @__PURE__ */ jsx4("a", { "data-slot": "data-kit-page", ...page.link(item), children: item }, item)
148
+ ),
149
+ /* @__PURE__ */ jsxs3("a", { "data-slot": "data-kit-page", ...page.link(page.number + 1, page.next), children: [
150
+ labels.pagination.next,
151
+ /* @__PURE__ */ jsx4(DataKitIcon, { name: "chevronRight" })
152
+ ] })
153
+ ] })
154
+ ] });
155
+ };
156
+
157
+ // src/ui/table/hook.ts
158
+ import { useEffect as useEffect2, useRef as useRef2, useSyncExternalStore } from "react";
159
+ import { usePathname, useRouter, useSearchParams } from "next/navigation.js";
160
+ var dataKitTableMounted = /* @__PURE__ */ new Map();
161
+ var useDataKitTable = (props) => {
162
+ const { data, columns = [], source, append, refetch, selection } = props;
163
+ const router = useRouter();
164
+ const pathname = usePathname();
165
+ const searchParams = useSearchParams();
166
+ const labels = useDataKitLabels();
167
+ const order = useRef2([]);
168
+ const busy = typeof document !== "undefined" && Boolean(document.activeElement?.closest('[data-slot="data-kit-toolbar"], [data-slot="data-kit-popover"], [data-slot="popover-content"], [data-radix-popper-content-wrapper]') || document.querySelector('[data-slot="data-kit-popover"]:popover-open'));
169
+ const kit = useDataKit({ data, source: source ?? { navigate: (url) => router.push(url, { scroll: false }), refresh: () => router.refresh() }, append, refetch });
170
+ const mounted = useSyncExternalStore(
171
+ () => () => {
172
+ },
173
+ () => true,
174
+ () => false
175
+ );
176
+ useEffect2(() => {
177
+ if (process.env.NODE_ENV === "production") return;
178
+ const name = kit.prefix ?? "";
179
+ dataKitTableMounted.set(name, (dataKitTableMounted.get(name) ?? 0) + 1);
180
+ if (dataKitTableMounted.get(name) > 1) console.warn(`[next-data-kit] two tables on this page share the prefix "${name}"; give each query({ prefix }) its own.`);
181
+ return () => void dataKitTableMounted.set(name, dataKitTableMounted.get(name) - 1);
182
+ }, [kit.prefix]);
183
+ const ids = kit.selection.ids;
184
+ const selectable = Boolean(selection);
185
+ const enabled = kit.rows.filter((row) => selectable && (selection?.enabled?.({ row }) ?? true));
186
+ const pageChecked = enabled.length > 0 && enabled.every((row) => ids.includes(row.id));
187
+ const shown = columns.filter((column) => column.table !== false);
188
+ const { number, count } = kit.page;
189
+ const pages = count === null ? [] : [.../* @__PURE__ */ new Set([1, number - 1, number, number + 1, count])].filter((page) => page >= 1 && page <= count).sort((a, b) => a - b);
190
+ return {
191
+ kit,
192
+ header: shown.map((column) => {
193
+ const direction = kit.sort.find((sort) => sort.column === column.id)?.direction ?? false;
194
+ return {
195
+ id: column.id,
196
+ className: column.className,
197
+ content: column.header ?? column.id,
198
+ sort: {
199
+ can: Boolean(kit.meta.column[column.id]?.sort),
200
+ direction,
201
+ aria: !kit.meta.column[column.id]?.sort ? void 0 : direction === "asc" ? "ascending" : direction === "desc" ? "descending" : "none",
202
+ // ** asc → desc → off; the default column goes desc ⇄ asc, since "off" would only land back on it
203
+ toggle: () => {
204
+ const next = direction === false ? "asc" : direction === "asc" ? "desc" : kit.meta.sort.some((sort) => sort.column === column.id) ? "asc" : void 0;
205
+ kit.set.sort(next ? [{ column: column.id, direction: next }] : []);
206
+ }
207
+ }
208
+ };
209
+ }),
210
+ row: kit.rows.map((row) => ({
211
+ id: row.id,
212
+ row,
213
+ selected: ids.includes(row.id),
214
+ disabled: !enabled.includes(row),
215
+ toggle: () => kit.selection.set((current) => current.includes(row.id) ? current.filter((id) => id !== row.id) : [...current, row.id]),
216
+ cell: shown.map((column) => ({
217
+ id: column.id,
218
+ className: column.className,
219
+ content: column.cell ? column.cell({ row }) : String(row[column.id] ?? "")
220
+ }))
221
+ })),
222
+ selection: {
223
+ // ** Rows can be selected at all (a `selection` prop was given)
224
+ active: selectable,
225
+ rows: kit.rows.filter((row) => ids.includes(row.id)),
226
+ count: ids.length,
227
+ clear: kit.selection.clear,
228
+ // ** The header checkbox: only rows `enabled` allows, and it reads the latest ids so quick clicks build on each other
229
+ page: {
230
+ checked: pageChecked,
231
+ indeterminate: !pageChecked && enabled.some((row) => ids.includes(row.id)),
232
+ toggle: () => kit.selection.set(
233
+ (current) => enabled.every((row) => current.includes(row.id)) ? current.filter((id) => !enabled.some((row) => row.id === id)) : [.../* @__PURE__ */ new Set([...current, ...enabled.map((row) => row.id)])]
234
+ )
235
+ }
236
+ },
237
+ filter: {
238
+ active: Object.keys(kit.filter).length > 0 || Boolean(kit.search),
239
+ reset: kit.reset,
240
+ // ** The server's filterable columns (custom and URL-only ones have no control), active ones first so what narrows the table reads left to right
241
+ list: Object.entries(kit.meta.column).flatMap(
242
+ ([id, meta]) => meta.filter && meta.filter.variant !== "custom" && !meta.filter.hidden ? [{ id, variant: meta.filter.variant, option: meta.filter.option ?? [], preset: meta.filter.preset ?? [], bound: meta.filter.bound, compare: meta.filter.compare ?? [] }] : []
243
+ ).sort(
244
+ (a, b) => (
245
+ // ** While a filter is being used (focus in a toolbar or a popover open), the order holds: a pill that moved would close its popover or drop focus mid-typing
246
+ busy && order.current.length ? (order.current.indexOf(a.id) + 1 || Infinity) - (order.current.indexOf(b.id) + 1 || Infinity) : Number(b.id in kit.filter) - Number(a.id in kit.filter)
247
+ )
248
+ ).map((declared, index, list) => {
249
+ if (index === 0) order.current = list.map((item) => item.id);
250
+ const { id, variant, preset, bound, compare } = declared;
251
+ const column = columns.find((item) => item.id === id);
252
+ const value = kit.filter[id] ?? "";
253
+ const option = variant === "boolean" ? [{ value: "true", label: labels.filter.yes }, { value: "false", label: labels.filter.no }] : variant === "exists" ? [{ value: "true", label: labels.exists.has }, { value: "false", label: labels.exists.empty }] : declared.option.map((item) => ({ value: item, label: column?.filter?.option?.[item] ?? item }));
254
+ const selected = !value ? [] : variant === "multiSelect" || variant === "tags" ? value.split(",") : [value];
255
+ const [, min = "", max = ""] = (variant === "range" || variant === "slider") && /^(-?\d+(?:\.\d+)?)?-(-?\d+(?:\.\d+)?)?$/.exec(value) || [];
256
+ const [, operator = compare[0] ?? "eq", number2 = ""] = variant === "numberCompare" ? /^(\w+)\.(.+)$/.exec(value) ?? [] : [];
257
+ const [from, to] = /^\d+-\d+$/.test(value) ? value.split("-").map((part) => new Date(Number(part))) : [];
258
+ const timed = variant === "dateTimeRange";
259
+ const edge = (date, end) => timed ? new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), end ? 59 : 0, end ? 999 : 0).getTime() : new Date(date.getFullYear(), date.getMonth(), date.getDate(), end ? 23 : 0, end ? 59 : 0, end ? 59 : 0, end ? 999 : 0).getTime();
260
+ const format = (date) => timed ? labels.date.formatTime(date) : labels.date.format(date);
261
+ const set = (next) => kit.set.filter({ [id]: next || void 0 });
262
+ return {
263
+ id,
264
+ variant,
265
+ label: column?.filter?.label ?? (typeof column?.header === "string" ? column.header : id),
266
+ option,
267
+ preset,
268
+ bound,
269
+ compare: compare.map((item) => ({ value: item, ...labels.compare[item] })),
270
+ state: {
271
+ value,
272
+ active: Boolean(value),
273
+ selected,
274
+ range: { min, max },
275
+ compare: { operator, value: number2 },
276
+ date: { from, to },
277
+ // ** What the filter's button shows once set (dates only after hydration: they print in the browser's locale and zone)
278
+ badge: variant === "range" || variant === "slider" ? value ? [`${min || (bound?.min ?? "\u2026")}\u2013${max || (bound?.max ?? "\u2026")}`] : [] : variant === "numberCompare" ? value ? [`${labels.compare[operator]?.symbol ?? operator} ${number2}`] : [] : variant === "date" || variant === "dateRange" || timed ? preset.includes(value) ? [labels.date.preset(value)] : from && to && mounted ? [
279
+ variant === "date" || format(from) === format(to) ? format(from) : (
280
+ // ** A same-day time range names the day once: "Nov 26, 2026, 9:00 AM – 5:30 PM"
281
+ timed && from.toDateString() === to.toDateString() ? `${format(from)} \u2013 ${labels.date.formatClock(to)}` : `${format(from)} \u2013 ${format(to)}`
282
+ )
283
+ ] : [] : variant === "text" || variant === "number" ? [] : selected.map((item) => option.find((choice) => choice.value === item)?.label ?? item)
284
+ },
285
+ set: {
286
+ // ** text, number, a preset: the URL string itself
287
+ value: set,
288
+ // ** select / boolean / exists replace (or clear when picked again), multiSelect adds or removes
289
+ toggle: (choice) => set(variant === "multiSelect" ? (selected.includes(choice) ? selected.filter((item) => item !== choice) : [...selected, choice]).join(",") : selected.includes(choice) ? void 0 : choice),
290
+ // ** range and slider: either end may stay empty; a slider's server snaps it to its step and bounds
291
+ range: (next) => set(next.min || next.max ? `${next.min}-${next.max}` : void 0),
292
+ date: (next) => set(next.from ? `${edge(next.from)}-${edge(next.to ?? next.from, true)}` : void 0),
293
+ compare: (next) => set(next.value.trim() ? `${next.operator}.${next.value.trim()}` : void 0),
294
+ // ** tags: the whole list; commas split values, so they never end up inside one
295
+ tags: (next) => set([...new Set(next.flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean))].join(","))
296
+ },
297
+ clear: () => set(void 0)
298
+ };
299
+ })
300
+ },
301
+ page: {
302
+ number,
303
+ count,
304
+ next: kit.page.next,
305
+ size: { value: kit.page.size, set: kit.set.page.size },
306
+ total: kit.total,
307
+ list: pages.flatMap((page, index) => index > 0 && page - pages[index - 1] > 1 ? ["gap", page] : [page]),
308
+ // ** A real link (new tab works); a plain click changes page in place. Disabled links get no href, so they can't be focused or opened
309
+ link: (page, linkEnabled = true) => ({
310
+ href: linkEnabled ? `${pathname}?${dataKitUrlEncode({ input: { ...kit.input, page: { number: page, size: kit.page.size } }, prefix: kit.prefix, search: searchParams.toString() })}` : void 0,
311
+ "aria-disabled": !linkEnabled || void 0,
312
+ "aria-current": page === number && linkEnabled ? "page" : void 0,
313
+ onClick: (event) => {
314
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
315
+ event.preventDefault();
316
+ if (linkEnabled) kit.set.page.number(page);
317
+ }
318
+ })
319
+ }
320
+ };
321
+ };
322
+
323
+ // src/ui/table/index.tsx
324
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
325
+ var DataKitTable = (props) => {
326
+ const { table, row } = props;
327
+ const labels = useDataKitLabels();
328
+ const isPending = table.kit.state.isPending;
329
+ return /* @__PURE__ */ jsx5("div", { "data-slot": "data-kit-scroll", children: /* @__PURE__ */ jsxs4("table", { "data-slot": "data-kit-table", "aria-busy": isPending, "data-state": isPending ? "pending" : void 0, children: [
330
+ /* @__PURE__ */ jsx5("thead", { children: /* @__PURE__ */ jsxs4("tr", { children: [
331
+ table.selection.active && /* @__PURE__ */ jsx5("th", { "data-slot": "data-kit-check", children: /* @__PURE__ */ jsx5(
332
+ "input",
333
+ {
334
+ type: "checkbox",
335
+ "aria-label": labels.table.all,
336
+ checked: table.selection.page.checked,
337
+ ref: (input) => void (input && (input.indeterminate = table.selection.page.indeterminate)),
338
+ onChange: table.selection.page.toggle
339
+ }
340
+ ) }),
341
+ table.header.map((header) => /* @__PURE__ */ jsx5("th", { "data-slot": "data-kit-header", className: header.className, "aria-sort": header.sort.aria, children: header.sort.can ? /* @__PURE__ */ jsxs4("button", { type: "button", "data-slot": "data-kit-sort", "data-sort": header.sort.direction || "none", onClick: header.sort.toggle, children: [
342
+ header.content,
343
+ /* @__PURE__ */ jsx5(DataKitIcon, { name: header.sort.direction === "asc" ? "up" : header.sort.direction === "desc" ? "down" : "sort" })
344
+ ] }) : header.content }, header.id))
345
+ ] }) }),
346
+ /* @__PURE__ */ jsx5("tbody", { children: table.row.length === 0 ? /* @__PURE__ */ jsx5("tr", { children: /* @__PURE__ */ jsx5("td", { "data-slot": "data-kit-empty", colSpan: table.header.length + (table.selection.active ? 1 : 0), children: labels.table.empty }) }) : table.row.map((item) => /* @__PURE__ */ jsxs4("tr", { "data-slot": "data-kit-row", "data-state": item.selected ? "selected" : void 0, "data-click": row?.onClick ? "" : void 0, onClick: row?.onClick ? () => row.onClick({ row: item.row }) : void 0, children: [
347
+ table.selection.active && /* @__PURE__ */ jsx5("td", { "data-slot": "data-kit-check", onClick: (event) => event.stopPropagation(), children: /* @__PURE__ */ jsx5("input", { type: "checkbox", "aria-label": labels.table.row, checked: item.selected, disabled: item.disabled, onChange: item.toggle }) }),
348
+ item.cell.map((cell) => /* @__PURE__ */ jsx5("td", { "data-slot": "data-kit-cell", className: cell.className, children: cell.content }, cell.id))
349
+ ] }, item.id)) })
350
+ ] }) });
351
+ };
352
+
353
+ // src/ui/toolbar/compare.tsx
354
+ import { useEffect as useEffect3, useState as useState2 } from "react";
355
+
356
+ // src/ui/toolbar/button.tsx
357
+ import { useId as useId2 } from "react";
358
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
359
+ var DataKitToolbarButton = (props) => {
360
+ const { filter, children } = props;
361
+ const labels = useDataKitLabels();
362
+ const id = `ndk-${useId2().replace(/[^a-zA-Z0-9_-]/g, "")}`;
363
+ const badge = filter.state.badge;
364
+ return /* @__PURE__ */ jsxs5("div", { "data-slot": "data-kit-filter", "data-state": filter.state.active ? "active" : "idle", style: { anchorName: `--${id}` }, children: [
365
+ filter.state.active && /* @__PURE__ */ jsx6("button", { type: "button", "data-slot": "data-kit-filter-clear", "aria-label": `${labels.filter.clear}: ${filter.label}`, onClick: filter.clear, children: /* @__PURE__ */ jsx6(DataKitIcon, { name: "clear" }) }),
366
+ /* @__PURE__ */ jsxs5("button", { type: "button", "data-slot": "data-kit-filter-trigger", popoverTarget: id, children: [
367
+ !filter.state.active && /* @__PURE__ */ jsx6(DataKitIcon, { name: "plus" }),
368
+ filter.label,
369
+ badge.length > 0 && /* @__PURE__ */ jsx6("span", { "data-slot": "data-kit-filter-badges", children: (badge.length > 2 ? [labels.filter.selected(badge.length)] : badge).map((item) => /* @__PURE__ */ jsx6("span", { "data-slot": "data-kit-filter-badge", title: item, children: item }, item)) })
370
+ ] }),
371
+ /* @__PURE__ */ jsx6(
372
+ "div",
373
+ {
374
+ id,
375
+ popover: "auto",
376
+ "data-slot": "data-kit-popover",
377
+ style: { positionAnchor: `--${id}` },
378
+ onToggle: (event) => {
379
+ const popover = event.currentTarget;
380
+ if (event.nativeEvent.newState !== "open") return;
381
+ popover.querySelector("input, select, button")?.focus();
382
+ if (CSS.supports("position-area: block-end")) return;
383
+ const place = () => {
384
+ const anchor = popover.parentElement.getBoundingClientRect();
385
+ const below = anchor.bottom + 4 + popover.offsetHeight <= window.innerHeight;
386
+ Object.assign(popover.style, {
387
+ top: `${below ? anchor.bottom + 4 : Math.max(4, anchor.top - 4 - popover.offsetHeight)}px`,
388
+ left: `${Math.max(4, Math.min(anchor.left, window.innerWidth - popover.offsetWidth - 4))}px`
389
+ });
390
+ };
391
+ place();
392
+ window.addEventListener("scroll", place, true);
393
+ window.addEventListener("resize", place);
394
+ popover.addEventListener("toggle", () => (window.removeEventListener("scroll", place, true), window.removeEventListener("resize", place)), { once: true });
395
+ },
396
+ children
397
+ }
398
+ )
399
+ ] });
400
+ };
401
+
402
+ // src/ui/toolbar/compare.tsx
403
+ import { jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
404
+ var DataKitToolbarCompare = (props) => {
405
+ const { filter } = props;
406
+ const [compare, setCompare] = useState2(filter.state.compare);
407
+ useEffect3(() => setCompare(filter.state.compare), [filter.state.value]);
408
+ useEffect3(() => {
409
+ if (compare.operator === filter.state.compare.operator && compare.value === filter.state.compare.value) return;
410
+ const timeout = setTimeout(() => filter.set.compare(compare), compare.operator === filter.state.compare.operator ? 300 : 0);
411
+ return () => clearTimeout(timeout);
412
+ }, [compare]);
413
+ return /* @__PURE__ */ jsx7(DataKitToolbarButton, { filter, children: /* @__PURE__ */ jsxs6("div", { role: "group", "aria-label": filter.label, "data-slot": "data-kit-compare", children: [
414
+ /* @__PURE__ */ jsxs6("span", { "data-slot": "data-kit-select", children: [
415
+ /* @__PURE__ */ jsx7("select", { "aria-label": filter.label, value: compare.operator, onChange: (event) => setCompare({ ...compare, operator: event.target.value }), children: filter.compare.map((item) => /* @__PURE__ */ jsxs6("option", { value: item.value, children: [
416
+ item.symbol,
417
+ " ",
418
+ item.label
419
+ ] }, item.value)) }),
420
+ /* @__PURE__ */ jsx7(DataKitIcon, { name: "chevronDown" })
421
+ ] }),
422
+ /* @__PURE__ */ jsx7("input", { "data-slot": "data-kit-input", type: "number", inputMode: "decimal", "aria-label": filter.label, value: compare.value, onChange: (event) => setCompare({ ...compare, value: event.target.value }) })
423
+ ] }) });
424
+ };
425
+
426
+ // src/ui/toolbar/date.tsx
427
+ import { useEffect as useEffect4, useState as useState3 } from "react";
428
+ import { jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
429
+ var DataKitToolbarDate = (props) => {
430
+ const { filter } = props;
431
+ const labels = useDataKitLabels();
432
+ const { from, to } = filter.state.date;
433
+ const timed = filter.variant === "dateTimeRange";
434
+ const ranged = filter.variant !== "date";
435
+ const [zone, setZone] = useState3("");
436
+ useEffect4(() => setZone(Intl.DateTimeFormat().resolvedOptions().timeZone), []);
437
+ const pad = (number) => String(number).padStart(2, "0");
438
+ const local = (date) => date ? `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}${timed ? `T${pad(date.getHours())}:${pad(date.getMinutes())}` : ""}` : "";
439
+ const parse = (value) => value ? new Date(Number(value.slice(0, 4)), Number(value.slice(5, 7)) - 1, Number(value.slice(8, 10)), Number(value.slice(11, 13) || 0), Number(value.slice(14, 16) || 0)) : void 0;
440
+ return /* @__PURE__ */ jsx8(DataKitToolbarButton, { filter, children: /* @__PURE__ */ jsxs7("div", { "data-slot": "data-kit-date", children: [
441
+ filter.preset.length > 0 && /* @__PURE__ */ jsx8("div", { role: "group", "aria-label": filter.label, "data-slot": "data-kit-presets", children: filter.preset.map((preset) => /* @__PURE__ */ jsx8("button", { type: "button", "data-slot": "data-kit-preset", "aria-pressed": filter.state.value === preset, onClick: () => filter.set.value(filter.state.value === preset ? void 0 : preset), children: labels.date.preset(preset) }, preset)) }),
442
+ /* @__PURE__ */ jsxs7("div", { "data-slot": "data-kit-fields", "data-columns": ranged ? 2 : 1, children: [
443
+ /* @__PURE__ */ jsxs7("label", { "data-slot": "data-kit-field", children: [
444
+ /* @__PURE__ */ jsx8("span", { children: ranged ? labels.date.from : filter.label }),
445
+ /* @__PURE__ */ jsx8(
446
+ "input",
447
+ {
448
+ "data-slot": "data-kit-input",
449
+ type: timed ? "datetime-local" : "date",
450
+ max: ranged ? local(to) : void 0,
451
+ value: local(from),
452
+ onChange: (event) => {
453
+ const next = parse(event.target.value);
454
+ filter.set.date({ from: next, to: ranged && to && next && to >= next ? to : void 0 });
455
+ }
456
+ }
457
+ )
458
+ ] }),
459
+ ranged && /* @__PURE__ */ jsxs7("label", { "data-slot": "data-kit-field", children: [
460
+ /* @__PURE__ */ jsx8("span", { children: labels.date.to }),
461
+ /* @__PURE__ */ jsx8("input", { "data-slot": "data-kit-input", type: timed ? "datetime-local" : "date", min: local(from), value: local(to), onChange: (event) => filter.set.date({ from: from ?? parse(event.target.value), to: parse(event.target.value) }) })
462
+ ] })
463
+ ] }),
464
+ timed && zone && /* @__PURE__ */ jsx8("p", { "data-slot": "data-kit-hint", children: labels.date.zone(zone) })
465
+ ] }) });
466
+ };
467
+
468
+ // src/ui/toolbar/range.tsx
469
+ import { useEffect as useEffect5, useState as useState4 } from "react";
470
+ import { jsx as jsx9, jsxs as jsxs8 } from "react/jsx-runtime";
471
+ var DataKitToolbarRange = (props) => {
472
+ const { filter } = props;
473
+ const labels = useDataKitLabels();
474
+ const { min, max } = filter.state.range;
475
+ const [range, setRange] = useState4({ min, max });
476
+ useEffect5(() => setRange({ min, max }), [min, max]);
477
+ useEffect5(() => {
478
+ if (range.min === min && range.max === max) return;
479
+ const timeout = setTimeout(() => filter.set.range(range.min && range.max && Number(range.min) > Number(range.max) ? { min: range.max, max: range.min } : range), 300);
480
+ return () => clearTimeout(timeout);
481
+ }, [range]);
482
+ return /* @__PURE__ */ jsx9(DataKitToolbarButton, { filter, children: /* @__PURE__ */ jsxs8("div", { "data-slot": "data-kit-range", children: [
483
+ /* @__PURE__ */ jsx9("input", { "data-slot": "data-kit-input", type: "number", inputMode: "decimal", "aria-label": labels.filter.min, placeholder: labels.filter.min, value: range.min, onChange: (event) => setRange({ ...range, min: event.target.value }) }),
484
+ /* @__PURE__ */ jsx9("span", { "aria-hidden": true, children: "\u2013" }),
485
+ /* @__PURE__ */ jsx9("input", { "data-slot": "data-kit-input", type: "number", inputMode: "decimal", "aria-label": labels.filter.max, placeholder: labels.filter.max, value: range.max, onChange: (event) => setRange({ ...range, max: event.target.value }) })
486
+ ] }) });
487
+ };
488
+
489
+ // src/ui/toolbar/select.tsx
490
+ import { useState as useState5 } from "react";
491
+ import { jsx as jsx10, jsxs as jsxs9 } from "react/jsx-runtime";
492
+ var DataKitToolbarSelect = (props) => {
493
+ const { filter } = props;
494
+ const labels = useDataKitLabels();
495
+ const [find, setFind] = useState5("");
496
+ const shown = filter.option.filter((choice) => choice.label.toLowerCase().includes(find.trim().toLowerCase()));
497
+ return /* @__PURE__ */ jsxs9(DataKitToolbarButton, { filter, children: [
498
+ filter.option.length > 7 && /* @__PURE__ */ jsx10("input", { "data-slot": "data-kit-input", type: "search", "aria-label": labels.filter.find, placeholder: labels.filter.find, value: find, onChange: (event) => setFind(event.target.value) }),
499
+ /* @__PURE__ */ jsxs9("div", { role: "group", "aria-label": filter.label, "data-slot": "data-kit-options", children: [
500
+ shown.length === 0 && /* @__PURE__ */ jsx10("p", { "data-slot": "data-kit-empty", children: labels.filter.empty }),
501
+ shown.map((choice) => /* @__PURE__ */ jsxs9("label", { "data-slot": "data-kit-option", children: [
502
+ /* @__PURE__ */ jsx10("input", { type: "checkbox", checked: filter.state.selected.includes(choice.value), onChange: () => filter.set.toggle(choice.value) }),
503
+ choice.label
504
+ ] }, choice.value))
505
+ ] })
506
+ ] });
507
+ };
508
+
509
+ // src/ui/toolbar/slider.tsx
510
+ import { useEffect as useEffect6, useRef as useRef3, useState as useState6 } from "react";
511
+ import { jsx as jsx11, jsxs as jsxs10 } from "react/jsx-runtime";
512
+ var DataKitToolbarSlider = (props) => {
513
+ const { filter } = props;
514
+ const labels = useDataKitLabels();
515
+ const bound = filter.bound ?? { min: 0, max: 100, step: 1 };
516
+ const applied = { min: filter.state.range.min === "" ? bound.min : Number(filter.state.range.min), max: filter.state.range.max === "" ? bound.max : Number(filter.state.range.max) };
517
+ const [range, setRange] = useState6(applied);
518
+ const timeout = useRef3(void 0);
519
+ useEffect6(() => setRange(applied), [filter.state.value]);
520
+ const commit = (next, delay) => {
521
+ clearTimeout(timeout.current);
522
+ timeout.current = setTimeout(() => filter.set.range({ min: next.min <= bound.min ? "" : String(next.min), max: next.max >= bound.max ? "" : String(next.max) }), delay);
523
+ };
524
+ const percent = (value) => (value - bound.min) / (bound.max - bound.min) * 100;
525
+ const thumb = (side) => ({
526
+ type: "range",
527
+ min: bound.min,
528
+ max: bound.max,
529
+ step: bound.step,
530
+ value: range[side],
531
+ "aria-label": side === "min" ? labels.filter.min : labels.filter.max,
532
+ "aria-valuetext": String(range[side]),
533
+ onChange: (event) => setRange(side === "min" ? { ...range, min: Math.min(Number(event.target.value), range.max) } : { ...range, max: Math.max(Number(event.target.value), range.min) }),
534
+ onPointerUp: () => commit(range, 0),
535
+ onKeyUp: () => commit(range, 300)
536
+ });
537
+ const typed = (side, value) => {
538
+ const number = value === "" ? bound[side] : Math.min(bound.max, Math.max(bound.min, Number(value)));
539
+ const next = side === "min" ? { ...range, min: Math.min(number, range.max) } : { ...range, max: Math.max(number, range.min) };
540
+ setRange(next);
541
+ commit(next, 300);
542
+ };
543
+ return /* @__PURE__ */ jsx11(DataKitToolbarButton, { filter, children: /* @__PURE__ */ jsxs10("div", { role: "group", "aria-label": filter.label, "data-slot": "data-kit-slider", children: [
544
+ /* @__PURE__ */ jsxs10("div", { "data-slot": "data-kit-slider-track", style: { "--ndk-from": `${percent(range.min)}%`, "--ndk-to": `${percent(range.max)}%` }, children: [
545
+ /* @__PURE__ */ jsx11("input", { ...thumb("min"), "data-top": range.min > (bound.min + bound.max) / 2 ? "" : void 0 }),
546
+ /* @__PURE__ */ jsx11("input", { ...thumb("max") })
547
+ ] }),
548
+ /* @__PURE__ */ jsxs10("div", { "data-slot": "data-kit-range", children: [
549
+ /* @__PURE__ */ jsx11("input", { "data-slot": "data-kit-input", type: "number", inputMode: "decimal", min: bound.min, max: bound.max, step: bound.step, "aria-label": labels.filter.min, value: range.min, onChange: (event) => typed("min", event.target.value) }),
550
+ /* @__PURE__ */ jsx11("span", { "aria-hidden": true, children: "\u2013" }),
551
+ /* @__PURE__ */ jsx11("input", { "data-slot": "data-kit-input", type: "number", inputMode: "decimal", min: bound.min, max: bound.max, step: bound.step, "aria-label": labels.filter.max, value: range.max, onChange: (event) => typed("max", event.target.value) })
552
+ ] })
553
+ ] }) });
554
+ };
555
+
556
+ // src/ui/toolbar/tags.tsx
557
+ import { useEffect as useEffect7, useState as useState7 } from "react";
558
+ import { jsx as jsx12, jsxs as jsxs11 } from "react/jsx-runtime";
559
+ var DataKitToolbarTags = (props) => {
560
+ const { filter } = props;
561
+ const labels = useDataKitLabels();
562
+ const [list, setList] = useState7(filter.state.selected);
563
+ const [text, setText] = useState7("");
564
+ useEffect7(() => setList(filter.state.selected), [filter.state.value]);
565
+ const change = (next) => {
566
+ const clean = [...new Set(next.flatMap((item) => item.split(/[,\n]/)).map((item) => item.trim()).filter(Boolean))];
567
+ setList(clean);
568
+ filter.set.tags(clean);
569
+ };
570
+ return /* @__PURE__ */ jsx12(DataKitToolbarButton, { filter, children: /* @__PURE__ */ jsxs11("div", { "data-slot": "data-kit-tags", children: [
571
+ list.length > 0 && /* @__PURE__ */ jsx12("ul", { "aria-label": filter.label, "data-slot": "data-kit-tags-list", children: list.map((item) => /* @__PURE__ */ jsxs11("li", { "data-slot": "data-kit-tag", children: [
572
+ /* @__PURE__ */ jsx12("span", { title: item, children: item }),
573
+ /* @__PURE__ */ jsx12("button", { type: "button", "aria-label": labels.tags.remove(item), onClick: () => change(list.filter((value) => value !== item)), children: /* @__PURE__ */ jsx12(DataKitIcon, { name: "x" }) })
574
+ ] }, item)) }),
575
+ /* @__PURE__ */ jsx12(
576
+ "input",
577
+ {
578
+ "data-slot": "data-kit-input",
579
+ "aria-label": filter.label,
580
+ placeholder: labels.tags.placeholder,
581
+ value: text,
582
+ onChange: (event) => {
583
+ if (!/[,\n]/.test(event.target.value)) return setText(event.target.value);
584
+ change([...list, event.target.value]);
585
+ setText("");
586
+ },
587
+ onKeyDown: (event) => {
588
+ if (event.key === "Enter") {
589
+ event.preventDefault();
590
+ if (text.trim()) change([...list, text]);
591
+ setText("");
592
+ }
593
+ if (event.key === "Backspace" && !text && list.length) change(list.slice(0, -1));
594
+ },
595
+ onPaste: (event) => {
596
+ const pasted = event.clipboardData.getData("text");
597
+ if (!/[,\n]/.test(pasted)) return;
598
+ event.preventDefault();
599
+ change([...list, text + pasted]);
600
+ setText("");
601
+ },
602
+ onBlur: () => {
603
+ if (!text.trim()) return;
604
+ change([...list, text]);
605
+ setText("");
606
+ }
607
+ }
608
+ )
609
+ ] }) });
610
+ };
611
+
612
+ // src/ui/toolbar/text.tsx
613
+ import { useEffect as useEffect8, useState as useState8 } from "react";
614
+ import { jsx as jsx13 } from "react/jsx-runtime";
615
+ var DataKitToolbarText = (props) => {
616
+ const { value, onChange, label, type = "search" } = props;
617
+ const [text, setText] = useState8(value);
618
+ useEffect8(() => setText(value), [value]);
619
+ useEffect8(() => {
620
+ if (text === value) return;
621
+ const timeout = setTimeout(() => onChange(text.trim()), 300);
622
+ return () => clearTimeout(timeout);
623
+ }, [text]);
624
+ return /* @__PURE__ */ jsx13("input", { "data-slot": "data-kit-input", type, inputMode: type === "number" ? "decimal" : void 0, "aria-label": label, placeholder: label, value: text, onChange: (event) => setText(event.target.value) });
625
+ };
626
+
627
+ // src/ui/toolbar/index.tsx
628
+ import { jsx as jsx14, jsxs as jsxs12 } from "react/jsx-runtime";
629
+ var DataKitToolbar = (props) => {
630
+ const { table, children } = props;
631
+ const labels = useDataKitLabels();
632
+ return /* @__PURE__ */ jsxs12("div", { "data-slot": "data-kit-toolbar", children: [
633
+ table.kit.meta.search && /* @__PURE__ */ jsx14(DataKitToolbarText, { label: labels.search.placeholder, value: table.kit.search, onChange: (value) => table.kit.set.search(value) }),
634
+ table.filter.list.map(
635
+ (filter) => filter.variant === "text" || filter.variant === "number" ? /* @__PURE__ */ jsx14(DataKitToolbarText, { label: filter.label, type: filter.variant === "number" ? "number" : "search", value: filter.state.value, onChange: filter.set.value }, filter.id) : filter.variant === "range" ? /* @__PURE__ */ jsx14(DataKitToolbarRange, { filter }, filter.id) : filter.variant === "slider" ? /* @__PURE__ */ jsx14(DataKitToolbarSlider, { filter }, filter.id) : filter.variant === "numberCompare" ? /* @__PURE__ */ jsx14(DataKitToolbarCompare, { filter }, filter.id) : filter.variant === "tags" ? /* @__PURE__ */ jsx14(DataKitToolbarTags, { filter }, filter.id) : filter.variant === "date" || filter.variant === "dateRange" || filter.variant === "dateTimeRange" ? /* @__PURE__ */ jsx14(DataKitToolbarDate, { filter }, filter.id) : /* @__PURE__ */ jsx14(DataKitToolbarSelect, { filter }, filter.id)
636
+ ),
637
+ table.filter.active && /* @__PURE__ */ jsxs12("button", { type: "button", "data-slot": "data-kit-reset", onClick: table.filter.reset, children: [
638
+ labels.filter.reset,
639
+ /* @__PURE__ */ jsx14(DataKitIcon, { name: "x" })
640
+ ] }),
641
+ children
642
+ ] });
643
+ };
644
+
645
+ // src/ui/infinite.tsx
646
+ import { useEffect as useEffect9, useRef as useRef4 } from "react";
647
+ import { jsx as jsx15 } from "react/jsx-runtime";
648
+ var DataKitInfinite = (props) => {
649
+ const { table } = props;
650
+ const kit = table.kit;
651
+ const labels = useDataKitLabels();
652
+ const sentinel = useRef4(null);
653
+ useEffect9(() => {
654
+ if (!sentinel.current || !kit.page.next || kit.state.isPending) return;
655
+ const observer = new IntersectionObserver((entries) => entries[0]?.isIntersecting && kit.set.page.number(kit.page.number + 1));
656
+ observer.observe(sentinel.current);
657
+ return () => observer.disconnect();
658
+ });
659
+ return /* @__PURE__ */ jsx15("div", { ref: sentinel, "data-slot": "data-kit-infinite", "aria-live": "polite", children: kit.state.isPending ? labels.infinite.loading : !kit.page.next && kit.rows.length > 0 ? labels.infinite.end : null });
660
+ };
661
+
662
+ // src/ui/index.tsx
663
+ import { jsx as jsx16, jsxs as jsxs13 } from "react/jsx-runtime";
664
+ var DataKit = (props) => {
665
+ const { data, columns, source, refetch, selection, row, toolbar = true, pagination = true, labels, className } = props;
666
+ const table = useDataKitTable({ data, columns, source, refetch, selection });
667
+ const body = /* @__PURE__ */ jsxs13("div", { "data-slot": "data-kit", className, children: [
668
+ toolbar && /* @__PURE__ */ jsx16(DataKitToolbar, { table, children: toolbar !== true && toolbar.control }),
669
+ /* @__PURE__ */ jsx16(DataKitTable, { table, row }),
670
+ pagination && /* @__PURE__ */ jsx16(DataKitPagination, { table, size: pagination === true ? void 0 : pagination.size }),
671
+ selection?.action && /* @__PURE__ */ jsx16(DataKitActionBar, { table, children: selection.action({ rows: table.selection.rows, clear: table.selection.clear }) })
672
+ ] });
673
+ return labels ? /* @__PURE__ */ jsx16(DataKitLabelsProvider, { labels, children: body }) : body;
674
+ };
675
+ export {
676
+ DataKit,
677
+ DataKitActionBar,
678
+ DataKitInfinite,
679
+ DataKitLabelsProvider,
680
+ DataKitPagination,
681
+ DataKitTable,
682
+ DataKitToolbar,
683
+ DataKitToolbarButton,
684
+ DataKitToolbarCompare,
685
+ DataKitToolbarDate,
686
+ DataKitToolbarRange,
687
+ DataKitToolbarSelect,
688
+ DataKitToolbarSlider,
689
+ DataKitToolbarTags,
690
+ DataKitToolbarText,
691
+ dataKitLabels,
692
+ useDataKitActionBar,
693
+ useDataKitLabels,
694
+ useDataKitTable
695
+ };
696
+ //# sourceMappingURL=ui.js.map