@seip/bluebird-js 0.2.0 → 0.2.2

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.
@@ -164,6 +164,7 @@ function resolveUrl(url) {
164
164
  * @param {Record<string, string>} [options.headers]
165
165
  * @param {RequestCredentials} [options.credentials]
166
166
  * @param {AbortSignal} [options.signal]
167
+ * @param {boolean} [options.raw=false] - Return the whole JSON body (e.g. `{ data, pagination }` from `res.paginate`) instead of only `data`.
167
168
  * @returns {Promise<T>}
168
169
  */
169
170
  export async function api(url, options = {}) {
@@ -225,6 +226,7 @@ export async function api(url, options = {}) {
225
226
  });
226
227
  }
227
228
 
229
+ if (options.raw) return data;
228
230
  return data && typeof data === "object" && "data" in data ? data.data : data;
229
231
  }
230
232
 
@@ -378,9 +378,12 @@ export const Button = forwardRef(function Button(props, ref) {
378
378
  const isLoading = Boolean(loading || busy);
379
379
 
380
380
  const handleClick = async (e) => {
381
+ if (confirm && typeof window !== "undefined" && !window.confirm(confirm)) {
382
+ e.preventDefault();
383
+ return;
384
+ }
381
385
  onClick?.(e);
382
386
  if (e.defaultPrevented || !url) return;
383
- if (confirm && typeof window !== "undefined" && !window.confirm(confirm)) return;
384
387
  setBusy(true);
385
388
  try {
386
389
  const data = await api(url, { method, body: payload });
@@ -0,0 +1,595 @@
1
+ import {
2
+ createElement as h,
3
+ forwardRef,
4
+ useCallback,
5
+ useEffect,
6
+ useId,
7
+ useImperativeHandle,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ } from "react";
12
+ import { api } from "./api.js";
13
+ import { Button, Link, Modal, Skeleton, cn, toast } from "./components.js";
14
+ import { useLocale } from "./i18n.js";
15
+
16
+ const ICON = {
17
+ viewBox: "0 0 24 24",
18
+ fill: "none",
19
+ stroke: "currentColor",
20
+ strokeWidth: 2,
21
+ strokeLinecap: "round",
22
+ strokeLinejoin: "round",
23
+ "aria-hidden": "true",
24
+ className: "size-4 shrink-0",
25
+ };
26
+
27
+ /**
28
+ * Inline SVG icon from one or more path definitions.
29
+ * @param {string[]} paths
30
+ * @param {string} [className]
31
+ */
32
+ function icon(paths, className) {
33
+ return h("svg", { ...ICON, className: cn(ICON.className, className) }, ...paths.map((d, i) => h("path", { key: i, d })));
34
+ }
35
+
36
+ const ICONS = {
37
+ search: () => icon(["m21 21-4.34-4.34", "M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z"]),
38
+ view: () => icon(["M2.06 12.35a1 1 0 0 1 0-.7 10.75 10.75 0 0 1 19.88 0 1 1 0 0 1 0 .7 10.75 10.75 0 0 1-19.88 0", "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"]),
39
+ edit: () => icon(["M21.17 6.81a1 1 0 0 0-3.99-3.99L3.84 16.17a2 2 0 0 0-.5.83l-1.32 4.35a.5.5 0 0 0 .62.62l4.35-1.32a2 2 0 0 0 .83-.5Z", "m15 5 4 4"]),
40
+ delete: () => icon(["M3 6h18", "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6", "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2", "M10 11v6", "M14 11v6"]),
41
+ prev: () => icon(["m15 18-6-6 6-6"]),
42
+ next: () => icon(["m9 18 6-6-6-6"]),
43
+ sortNone: () => icon(["m7 15 5 5 5-5", "m7 9 5-5 5 5"], "size-3.5 opacity-40"),
44
+ sortAsc: () => icon(["m5 12 7-7 7 7", "M12 19V5"], "size-3.5"),
45
+ sortDesc: () => icon(["M12 5v14", "m19 12-7 7-7-7"], "size-3.5"),
46
+ chevron: (open) => icon(["m6 9 6 6 6-6"], cn("size-3.5 transition-transform", open && "rotate-180")),
47
+ };
48
+
49
+ /**
50
+ * Builds a link from a pattern such as `/users/:id` or `/users/{id}/edit` using the row values.
51
+ * @param {string|((row: any) => string)} pattern
52
+ * @param {Record<string, any>} row
53
+ * @returns {string}
54
+ */
55
+ function resolveHref(pattern, row) {
56
+ if (typeof pattern === "function") return pattern(row);
57
+ return String(pattern).replace(/:(\w+)|\{(\w+)\}/g, (_, a, b) => encodeURIComponent(String(row?.[a || b] ?? "")));
58
+ }
59
+
60
+ /**
61
+ * Reads the raw value of a column (used for search and sorting).
62
+ * @param {Record<string, any>} row
63
+ * @param {{ key: string, value?: (row: any) => any }} column
64
+ */
65
+ function cellValue(row, column) {
66
+ if (typeof column.value === "function") return column.value(row);
67
+ return column.key.split(".").reduce((acc, part) => (acc == null ? acc : acc[part]), row);
68
+ }
69
+
70
+ /**
71
+ * Renders the visible content of a cell.
72
+ * @param {Record<string, any>} row
73
+ * @param {Object} column
74
+ * @param {number} index
75
+ */
76
+ function renderCell(row, column, index) {
77
+ if (typeof column.render === "function") return column.render(row, index);
78
+ const value = cellValue(row, column);
79
+ if (value === null || value === undefined || value === "") return h("span", { className: "text-muted-foreground" }, "—");
80
+ if (typeof value === "boolean") return value ? "✓" : "—";
81
+ return String(value);
82
+ }
83
+
84
+ /**
85
+ * Compares two cell values for sorting (numbers, dates, and natural string order).
86
+ * @param {any} a
87
+ * @param {any} b
88
+ * @returns {number}
89
+ */
90
+ function compareValues(a, b) {
91
+ if (a === b) return 0;
92
+ if (a === null || a === undefined || a === "") return 1;
93
+ if (b === null || b === undefined || b === "") return -1;
94
+ if (typeof a === "number" && typeof b === "number") return a - b;
95
+ if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
96
+ return String(a).localeCompare(String(b), undefined, { numeric: true, sensitivity: "base" });
97
+ }
98
+
99
+ /**
100
+ * Normalizes a server response into rows and a total: `res.paginate()` (`{ data, pagination }`),
101
+ * `res.ok(await Model.paginate())` (`{ data: { data, total } }`), or a plain array.
102
+ * @param {any} body
103
+ * @returns {{ rows: any[], total: number }}
104
+ */
105
+ export function normalizeTableResponse(body) {
106
+ if (Array.isArray(body)) return { rows: body, total: body.length };
107
+ const data = body?.data;
108
+ if (Array.isArray(data)) return { rows: data, total: Number(body.pagination?.total ?? body.total ?? data.length) };
109
+ if (data && Array.isArray(data.data)) {
110
+ return { rows: data.data, total: Number(data.total ?? data.pagination?.total ?? data.data.length) };
111
+ }
112
+ return { rows: [], total: 0 };
113
+ }
114
+
115
+ /**
116
+ * Responsive data table: search, sortable columns, pagination with page sizes, row actions (view, edit, delete with
117
+ * confirmation, and custom ones), loading skeletons, and an empty state. Wide containers show a table; narrow ones
118
+ * (phones, sidebars) switch to cards with the primary column as the title and expandable details. Works with local
119
+ * `rows` or a server `url` that returns `res.paginate()` / `Model.paginate()` results (`?page&limit&search&sort&order`).
120
+ *
121
+ * @example
122
+ * <DataTable
123
+ * rows={users}
124
+ * columns={[
125
+ * { key: "name", label: "Name", sortable: true, primary: true },
126
+ * { key: "email", label: "Email", sortable: true },
127
+ * { key: "role", label: "Role", render: (u) => <Badge>{u.role}</Badge> },
128
+ * { key: "created_at", label: "Joined", mobile: "details" },
129
+ * ]}
130
+ * onView="/users/:id"
131
+ * onEdit={(user) => openEditor(user)}
132
+ * onDelete={(user) => api.delete(`/api/users/${user.id}`)}
133
+ * />
134
+ *
135
+ * @param {Object} props
136
+ * @param {Array<Record<string, any>>} [props.rows] - Local data (client-side search, sort, and pagination).
137
+ * @param {string} [props.url] - Server endpoint (server-side search, sort, and pagination).
138
+ * @param {Record<string, any>} [props.params] - Extra query parameters for `url`.
139
+ * @param {Array<{ key: string, label: any, sortable?: boolean, searchable?: boolean, primary?: boolean, mobile?: boolean|"details", align?: "left"|"right"|"center", numeric?: boolean, render?: (row: any, index: number) => any, value?: (row: any) => any, className?: string }>} props.columns
140
+ * @param {boolean} [props.searchable=true]
141
+ * @param {string} [props.searchPlaceholder]
142
+ * @param {number} [props.pageSize=10]
143
+ * @param {number[]} [props.pageSizes=[10, 25, 50]]
144
+ * @param {{ key: string, dir?: "asc"|"desc" }} [props.defaultSort]
145
+ * @param {((row: any) => any)|string} [props.onView] - Handler or link pattern (`"/users/:id"`).
146
+ * @param {((row: any) => any)|string} [props.onEdit] - Handler or link pattern (`"/users/:id/edit"`).
147
+ * @param {(row: any) => any} [props.onDelete] - Async handler; confirmed in a dialog first. Server tables reload after it.
148
+ * @param {boolean|string} [props.deleteConfirm=true] - `false` skips the dialog; a string replaces its text.
149
+ * @param {Array<{ key?: string, label: string, icon?: any, onClick?: (row: any) => any, href?: string|((row: any) => string), variant?: "default"|"danger", confirm?: string|boolean, hidden?: (row: any) => boolean }>} [props.actions]
150
+ * @param {(row: any) => void} [props.onRowClick]
151
+ * @param {(row: any, index: number) => string|number} [props.rowKey]
152
+ * @param {boolean} [props.loading]
153
+ * @param {any} [props.empty]
154
+ * @param {any} [props.toolbar] - Extra controls next to the search box (e.g. a "New" button).
155
+ * @param {string} [props.caption] - Accessible table caption.
156
+ * @param {string} [props.className]
157
+ */
158
+ export const DataTable = forwardRef(function DataTable(props, ref) {
159
+ const {
160
+ rows,
161
+ url,
162
+ params,
163
+ columns = [],
164
+ searchable = true,
165
+ searchPlaceholder,
166
+ pageSize: initialPageSize = 10,
167
+ pageSizes = [10, 25, 50],
168
+ defaultSort,
169
+ onView,
170
+ onEdit,
171
+ onDelete,
172
+ deleteConfirm = true,
173
+ actions = [],
174
+ onRowClick,
175
+ rowKey,
176
+ loading = false,
177
+ empty,
178
+ toolbar,
179
+ caption,
180
+ className,
181
+ } = props;
182
+
183
+ const i18n = useLocale();
184
+ const searchId = useId();
185
+ const serverMode = Boolean(url);
186
+ const [query, setQuery] = useState("");
187
+ const [debouncedQuery, setDebouncedQuery] = useState("");
188
+ const [sort, setSort] = useState(defaultSort?.key ? { key: defaultSort.key, dir: defaultSort.dir === "desc" ? -1 : 1 } : { key: null, dir: 1 });
189
+ const [page, setPage] = useState(1);
190
+ const [limit, setLimit] = useState(initialPageSize);
191
+ const [remote, setRemote] = useState({ rows: [], total: 0, loaded: false });
192
+ const [fetching, setFetching] = useState(false);
193
+ const [reloadTick, setReloadTick] = useState(0);
194
+ const [pending, setPending] = useState(null);
195
+ const [busy, setBusy] = useState(false);
196
+ const [expanded, setExpanded] = useState(() => new Set());
197
+ const paramsKey = JSON.stringify(params || {});
198
+
199
+ useImperativeHandle(ref, () => ({ reload: () => setReloadTick((n) => n + 1) }), []);
200
+
201
+ useEffect(() => {
202
+ if (!serverMode) return undefined;
203
+ const timer = setTimeout(() => setDebouncedQuery(query.trim()), 300);
204
+ return () => clearTimeout(timer);
205
+ }, [query, serverMode]);
206
+
207
+ useEffect(() => {
208
+ if (!serverMode) return undefined;
209
+ const ctrl = new AbortController();
210
+ const qs = new URLSearchParams({ ...JSON.parse(paramsKey), page: String(page), limit: String(limit) });
211
+ if (debouncedQuery) qs.set("search", debouncedQuery);
212
+ if (sort.key) {
213
+ qs.set("sort", sort.key);
214
+ qs.set("order", sort.dir === -1 ? "desc" : "asc");
215
+ }
216
+ setFetching(true);
217
+ api
218
+ .get(`${url}${url.includes("?") ? "&" : "?"}${qs.toString()}`, { raw: true, signal: ctrl.signal })
219
+ .then((body) => {
220
+ const result = normalizeTableResponse(body);
221
+ setRemote({ ...result, loaded: true });
222
+ })
223
+ .catch((err) => {
224
+ if (err?.name === "AbortError" || ctrl.signal.aborted) return;
225
+ setRemote((prev) => ({ ...prev, loaded: true }));
226
+ toast.error(err?.message || i18n.t("request.failed"));
227
+ })
228
+ .finally(() => {
229
+ if (!ctrl.signal.aborted) setFetching(false);
230
+ });
231
+ return () => ctrl.abort();
232
+ }, [serverMode, url, paramsKey, page, limit, debouncedQuery, sort.key, sort.dir, reloadTick]);
233
+
234
+ const searchColumns = useMemo(() => columns.filter((c) => c.searchable !== false), [columns]);
235
+
236
+ const localResult = useMemo(() => {
237
+ if (serverMode) return null;
238
+ const list = Array.isArray(rows) ? rows : [];
239
+ const q = query.trim().toLowerCase();
240
+ let filtered = q
241
+ ? list.filter((row) => searchColumns.some((c) => String(cellValue(row, c) ?? "").toLowerCase().includes(q)))
242
+ : list;
243
+ if (sort.key) {
244
+ const column = columns.find((c) => c.key === sort.key) || { key: sort.key };
245
+ filtered = [...filtered].sort((a, b) => compareValues(cellValue(a, column), cellValue(b, column)) * sort.dir);
246
+ }
247
+ return filtered;
248
+ }, [serverMode, rows, query, searchColumns, sort, columns]);
249
+
250
+ const total = serverMode ? remote.total : localResult.length;
251
+ const pageCount = Math.max(1, Math.ceil(total / limit));
252
+ const currentPage = Math.min(page, pageCount);
253
+ const visible = serverMode ? remote.rows : localResult.slice((currentPage - 1) * limit, currentPage * limit);
254
+ const showSkeleton = loading || (serverMode && !remote.loaded);
255
+
256
+ useEffect(() => {
257
+ if (page > pageCount) setPage(pageCount);
258
+ }, [page, pageCount]);
259
+
260
+ const keyOf = (row, index) => (rowKey ? rowKey(row, index) : row?.id ?? `${currentPage}-${index}`);
261
+
262
+ const rowActions = useMemo(() => {
263
+ const list = [];
264
+ if (onView) list.push({ key: "view", label: i18n.t("table.view"), icon: ICONS.view(), ...(typeof onView === "string" ? { href: onView } : { onClick: onView }) });
265
+ if (onEdit) list.push({ key: "edit", label: i18n.t("table.edit"), icon: ICONS.edit(), ...(typeof onEdit === "string" ? { href: onEdit } : { onClick: onEdit }) });
266
+ for (const action of actions) list.push(action);
267
+ if (onDelete) {
268
+ list.push({
269
+ key: "delete",
270
+ label: i18n.t("table.delete"),
271
+ icon: ICONS.delete(),
272
+ onClick: onDelete,
273
+ variant: "danger",
274
+ confirm: deleteConfirm === false ? false : typeof deleteConfirm === "string" ? deleteConfirm : true,
275
+ reload: true,
276
+ });
277
+ }
278
+ return list;
279
+ }, [onView, onEdit, onDelete, deleteConfirm, actions, i18n.locale]);
280
+
281
+ const runAction = useCallback(
282
+ async (action, row) => {
283
+ setBusy(true);
284
+ try {
285
+ await action.onClick?.(row);
286
+ if (serverMode && (action.reload || action.confirm)) setReloadTick((n) => n + 1);
287
+ } catch (err) {
288
+ toast.error(err?.message || i18n.t("request.failed"));
289
+ } finally {
290
+ setBusy(false);
291
+ setPending(null);
292
+ }
293
+ },
294
+ [serverMode, i18n.locale]
295
+ );
296
+
297
+ const triggerAction = (action, row, event) => {
298
+ event?.stopPropagation();
299
+ if (action.confirm) setPending({ action, row });
300
+ else runAction(action, row);
301
+ };
302
+
303
+ const toggleSort = (key) => {
304
+ setSort((s) => (s.key !== key ? { key, dir: 1 } : s.dir === 1 ? { key, dir: -1 } : { key: null, dir: 1 }));
305
+ setPage(1);
306
+ };
307
+
308
+ const toggleExpanded = (key) =>
309
+ setExpanded((prev) => {
310
+ const next = new Set(prev);
311
+ if (next.has(key)) next.delete(key);
312
+ else next.add(key);
313
+ return next;
314
+ });
315
+
316
+ const primaryColumn = columns.find((c) => c.primary) || columns[0];
317
+ const mobileColumns = columns.filter((c) => c !== primaryColumn && c.mobile !== false);
318
+ const summaryColumns = mobileColumns.filter((c) => c.mobile !== "details").slice(0, 4);
319
+ const detailColumns = mobileColumns.filter((c) => !summaryColumns.includes(c));
320
+ const alignClass = (c) => (c.align === "right" || c.numeric ? "text-right" : c.align === "center" ? "text-center" : "text-left");
321
+
322
+ /**
323
+ * Renders the action buttons of a row.
324
+ * @param {Record<string, any>} row
325
+ */
326
+ const renderActions = (row) => {
327
+ const available = rowActions.filter((a) => !(typeof a.hidden === "function" && a.hidden(row)));
328
+ if (!available.length) return null;
329
+ return h(
330
+ "div",
331
+ { className: "flex items-center justify-end gap-0.5" },
332
+ available.map((action, i) => {
333
+ const iconOnly = Boolean(action.icon);
334
+ const btnClass = cn(
335
+ "btn btn-ghost btn-sm",
336
+ iconOnly && "btn-icon",
337
+ action.variant === "danger" ? "text-destructive hover:bg-destructive/10 hover:text-destructive" : "text-muted-foreground hover:text-foreground"
338
+ );
339
+ const content = iconOnly ? action.icon : action.label;
340
+ if (action.href) {
341
+ return h(
342
+ Link,
343
+ { key: action.key || i, to: resolveHref(action.href, row), className: btnClass, "aria-label": action.label, title: action.label, onClick: (e) => e.stopPropagation() },
344
+ content
345
+ );
346
+ }
347
+ return h(
348
+ "button",
349
+ { key: action.key || i, type: "button", className: btnClass, "aria-label": action.label, title: action.label, disabled: busy, onClick: (e) => triggerAction(action, row, e) },
350
+ content
351
+ );
352
+ })
353
+ );
354
+ };
355
+
356
+ const emptyNode = h(
357
+ "div",
358
+ { className: "flex flex-col items-center justify-center gap-1 px-6 py-12 text-center" },
359
+ h("span", { className: "inline-flex size-10 items-center justify-center rounded-full bg-muted text-muted-foreground" }, ICONS.search()),
360
+ h("p", { className: "mt-2 text-sm font-medium text-foreground" }, empty || i18n.t("table.empty")),
361
+ query ? h("p", { className: "text-xs text-muted-foreground" }, `"${query}"`) : null
362
+ );
363
+
364
+ const skeletonRows = Array.from({ length: Math.min(limit, 5) }, (_, i) => i);
365
+ const hasActions = rowActions.length > 0;
366
+ const from = total === 0 ? 0 : (currentPage - 1) * limit + 1;
367
+ const to = Math.min(total, currentPage * limit);
368
+
369
+ const table = h(
370
+ "div",
371
+ { className: "hidden overflow-x-auto @2xl:block" },
372
+ h(
373
+ "table",
374
+ { className: "w-full border-collapse text-sm" },
375
+ caption ? h("caption", { className: "sr-only" }, caption) : null,
376
+ h(
377
+ "thead",
378
+ null,
379
+ h(
380
+ "tr",
381
+ { className: "border-b border-border bg-muted/40" },
382
+ columns.map((c) =>
383
+ h(
384
+ "th",
385
+ {
386
+ key: c.key,
387
+ scope: "col",
388
+ "aria-sort": sort.key === c.key ? (sort.dir === 1 ? "ascending" : "descending") : undefined,
389
+ className: cn("h-10 px-4 text-xs font-medium whitespace-nowrap text-muted-foreground", alignClass(c), c.className),
390
+ },
391
+ c.sortable
392
+ ? h(
393
+ "button",
394
+ {
395
+ type: "button",
396
+ onClick: () => toggleSort(c.key),
397
+ title: i18n.t("table.sortBy", { column: typeof c.label === "string" ? c.label : c.key }),
398
+ className: cn(
399
+ "-mx-2 inline-flex h-7 items-center gap-1 rounded-md px-2 transition-colors hover:bg-accent hover:text-foreground",
400
+ sort.key === c.key && "text-foreground"
401
+ ),
402
+ },
403
+ c.label,
404
+ sort.key === c.key ? (sort.dir === 1 ? ICONS.sortAsc() : ICONS.sortDesc()) : ICONS.sortNone()
405
+ )
406
+ : c.label
407
+ )
408
+ ),
409
+ hasActions ? h("th", { scope: "col", className: "h-10 w-px px-4 text-right text-xs font-medium text-muted-foreground" }, h("span", { className: "sr-only" }, i18n.t("table.actions"))) : null
410
+ )
411
+ ),
412
+ h(
413
+ "tbody",
414
+ { className: cn("divide-y divide-border/70 transition-opacity", fetching && remote.loaded && "opacity-60") },
415
+ showSkeleton
416
+ ? skeletonRows.map((i) =>
417
+ h(
418
+ "tr",
419
+ { key: `sk-${i}` },
420
+ columns.map((c) => h("td", { key: c.key, className: "px-4 py-3" }, h(Skeleton, { className: "h-4 w-3/4 rounded-md" }))),
421
+ hasActions ? h("td", { className: "px-4 py-3" }, h(Skeleton, { className: "ml-auto h-4 w-16 rounded-md" })) : null
422
+ )
423
+ )
424
+ : visible.length
425
+ ? visible.map((row, index) =>
426
+ h(
427
+ "tr",
428
+ {
429
+ key: keyOf(row, index),
430
+ onClick: onRowClick ? () => onRowClick(row) : undefined,
431
+ className: cn("transition-colors hover:bg-accent/40", onRowClick && "cursor-pointer"),
432
+ },
433
+ columns.map((c) =>
434
+ h(
435
+ "td",
436
+ { key: c.key, className: cn("px-4 py-3 align-middle", alignClass(c), c.numeric && "font-mono tabular-nums", c === primaryColumn && "font-medium text-foreground", c.className) },
437
+ renderCell(row, c, index)
438
+ )
439
+ ),
440
+ hasActions ? h("td", { className: "px-2 py-1.5 text-right" }, renderActions(row)) : null
441
+ )
442
+ )
443
+ : h("tr", null, h("td", { colSpan: columns.length + (hasActions ? 1 : 0) }, emptyNode))
444
+ )
445
+ )
446
+ );
447
+
448
+ const cards = h(
449
+ "ul",
450
+ { className: cn("divide-y divide-border/70 @2xl:hidden", fetching && remote.loaded && "opacity-60") },
451
+ showSkeleton
452
+ ? skeletonRows.map((i) =>
453
+ h("li", { key: `sk-${i}`, className: "space-y-2 p-4" }, h(Skeleton, { className: "h-4 w-1/2 rounded-md" }), h(Skeleton, { className: "h-3 w-3/4 rounded-md" }))
454
+ )
455
+ : visible.length
456
+ ? visible.map((row, index) => {
457
+ const key = keyOf(row, index);
458
+ const open = expanded.has(key);
459
+ const field = (c) =>
460
+ h(
461
+ "div",
462
+ { key: c.key, className: "min-w-0" },
463
+ h("dt", { className: "text-xs text-muted-foreground" }, c.label),
464
+ h("dd", { className: cn("mt-0.5 truncate text-sm text-foreground", c.numeric && "font-mono tabular-nums") }, renderCell(row, c, index))
465
+ );
466
+ return h(
467
+ "li",
468
+ { key, className: "p-4" },
469
+ h(
470
+ "div",
471
+ { className: "flex items-start justify-between gap-3" },
472
+ h(
473
+ "div",
474
+ {
475
+ className: cn("min-w-0 flex-1 font-medium text-foreground", onRowClick && "cursor-pointer"),
476
+ onClick: onRowClick ? () => onRowClick(row) : undefined,
477
+ },
478
+ primaryColumn ? renderCell(row, primaryColumn, index) : null
479
+ ),
480
+ hasActions ? h("div", { className: "-mr-2 -mt-1 shrink-0" }, renderActions(row)) : null
481
+ ),
482
+ summaryColumns.length ? h("dl", { className: "mt-3 grid grid-cols-2 gap-x-4 gap-y-3" }, summaryColumns.map(field)) : null,
483
+ detailColumns.length
484
+ ? h(
485
+ "div",
486
+ { className: "mt-3" },
487
+ open ? h("dl", { className: "mb-3 grid grid-cols-2 gap-x-4 gap-y-3 border-t border-border/70 pt-3" }, detailColumns.map(field)) : null,
488
+ h(
489
+ "button",
490
+ { type: "button", onClick: () => toggleExpanded(key), "aria-expanded": open, className: "inline-flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground" },
491
+ i18n.t(open ? "table.less" : "table.more"),
492
+ ICONS.chevron(open)
493
+ )
494
+ )
495
+ : null
496
+ );
497
+ })
498
+ : h("li", null, emptyNode)
499
+ );
500
+
501
+ const header =
502
+ searchable || toolbar
503
+ ? h(
504
+ "div",
505
+ { className: "flex flex-wrap items-center justify-between gap-3 border-b border-border p-3" },
506
+ searchable
507
+ ? h(
508
+ "div",
509
+ { className: "relative w-full sm:w-72" },
510
+ h("label", { htmlFor: searchId, className: "sr-only" }, searchPlaceholder || i18n.t("table.search")),
511
+ h("span", { className: "pointer-events-none absolute inset-y-0 left-3 flex items-center text-muted-foreground" }, ICONS.search()),
512
+ h("input", {
513
+ id: searchId,
514
+ type: "search",
515
+ value: query,
516
+ placeholder: searchPlaceholder || i18n.t("table.search"),
517
+ onChange: (e) => {
518
+ setQuery(e.target.value);
519
+ setPage(1);
520
+ },
521
+ className: "field h-9 pl-9",
522
+ })
523
+ )
524
+ : h("span"),
525
+ toolbar ? h("div", { className: "flex flex-wrap items-center gap-2" }, toolbar) : null
526
+ )
527
+ : null;
528
+
529
+ const footer =
530
+ !showSkeleton && total > 0
531
+ ? h(
532
+ "div",
533
+ { className: "flex flex-wrap items-center justify-between gap-3 border-t border-border px-4 py-2.5 text-xs text-muted-foreground" },
534
+ h("span", { className: "tabular-nums" }, i18n.t("table.range", { from, to, total })),
535
+ h(
536
+ "div",
537
+ { className: "flex items-center gap-3" },
538
+ pageSizes.length > 1
539
+ ? h(
540
+ "label",
541
+ { className: "hidden items-center gap-2 sm:flex" },
542
+ i18n.t("table.rowsPerPage"),
543
+ h(
544
+ "select",
545
+ {
546
+ value: limit,
547
+ onChange: (e) => {
548
+ setLimit(Number(e.target.value));
549
+ setPage(1);
550
+ },
551
+ className: "field h-8 w-auto py-0 pr-7 text-xs",
552
+ },
553
+ [...new Set([...pageSizes, initialPageSize])].sort((a, b) => a - b).map((n) => h("option", { key: n, value: n }, n))
554
+ )
555
+ )
556
+ : null,
557
+ h("span", { className: "tabular-nums" }, i18n.t("table.page", { n: currentPage, total: pageCount })),
558
+ h(
559
+ "div",
560
+ { className: "flex items-center gap-1" },
561
+ h(Button, { variant: "outline", size: "icon", className: "size-8", disabled: currentPage <= 1, onClick: () => setPage(currentPage - 1), "aria-label": i18n.t("table.prev") }, ICONS.prev()),
562
+ h(Button, { variant: "outline", size: "icon", className: "size-8", disabled: currentPage >= pageCount, onClick: () => setPage(currentPage + 1), "aria-label": i18n.t("table.next") }, ICONS.next())
563
+ )
564
+ )
565
+ )
566
+ : null;
567
+
568
+ const confirmText = pending ? (typeof pending.action.confirm === "string" ? pending.action.confirm : i18n.t("table.confirmText")) : "";
569
+
570
+ return h(
571
+ "div",
572
+ { className: cn("@container overflow-hidden rounded-2xl border border-border bg-card text-card-foreground shadow-xs", className) },
573
+ header,
574
+ table,
575
+ cards,
576
+ footer,
577
+ h(Modal, {
578
+ open: Boolean(pending),
579
+ onClose: () => (busy ? null : setPending(null)),
580
+ size: "sm",
581
+ title: pending?.action.key === "delete" ? i18n.t("table.confirmTitle") : pending?.action.label,
582
+ description: confirmText,
583
+ footer: h(
584
+ "div",
585
+ { className: "flex justify-end gap-2" },
586
+ h(Button, { variant: "outline", disabled: busy, onClick: () => setPending(null) }, i18n.t("table.cancel")),
587
+ h(
588
+ Button,
589
+ { variant: pending?.action.variant === "danger" ? "danger" : "primary", loading: busy, onClick: () => pending && runAction(pending.action, pending.row) },
590
+ pending?.action.label
591
+ )
592
+ ),
593
+ })
594
+ );
595
+ });