@seip/bluebird-js 0.1.7 → 0.2.1

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.
Files changed (151) hide show
  1. package/AGENTS.md +727 -620
  2. package/README.md +670 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +55 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/table.html +15 -0
  8. package/app/resources/html/terms.html +46 -0
  9. package/app/resources/index.html +27 -0
  10. package/app/resources/layouts/AppLayout.jsx +92 -0
  11. package/app/resources/main.jsx +18 -0
  12. package/app/resources/pages/Dashboard.jsx +93 -0
  13. package/app/resources/pages/Home.jsx +140 -0
  14. package/app/resources/pages/Login.jsx +35 -0
  15. package/app/resources/pages/NotFound.jsx +16 -0
  16. package/app/resources/pages/Register.jsx +55 -0
  17. package/app/resources/pages/TableDemo.jsx +85 -0
  18. package/app/resources/routes.jsx +59 -0
  19. package/app/resources/spa.js +73 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +129 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +89 -47
  24. package/core/ai.js +30 -10
  25. package/core/app.d.ts +2 -18
  26. package/core/app.js +987 -801
  27. package/core/auth.d.ts +2 -13
  28. package/core/auth.js +444 -326
  29. package/core/cli/build.js +37 -0
  30. package/core/cli/dev.js +155 -0
  31. package/core/cli/doctor.js +37 -2
  32. package/core/cli/export.js +191 -0
  33. package/core/cli/init.js +91 -322
  34. package/core/cli/nginx.js +1 -1
  35. package/core/cli/templates.js +139 -0
  36. package/core/cli/view.js +98 -161
  37. package/core/config.js +44 -2
  38. package/core/csrf.js +156 -24
  39. package/core/database.js +1184 -1131
  40. package/core/debug.js +1 -1
  41. package/core/html.js +8 -1
  42. package/core/index.d.ts +126 -310
  43. package/core/paths.js +55 -0
  44. package/core/ratelimit.js +10 -1
  45. package/core/react/client/api.js +239 -0
  46. package/core/react/client/auth.js +236 -0
  47. package/core/react/client/components.js +1321 -0
  48. package/core/react/client/datatable.js +595 -0
  49. package/core/react/client/i18n.js +440 -0
  50. package/core/react/client/index.d.ts +314 -0
  51. package/core/react/client/index.js +50 -0
  52. package/core/react/client/router.js +26 -0
  53. package/core/react/client/theme.css +512 -0
  54. package/core/render-cache.js +250 -212
  55. package/core/render.d.ts +25 -21
  56. package/core/render.js +738 -736
  57. package/core/router.d.ts +2 -3
  58. package/core/router.js +171 -171
  59. package/core/seo.js +10 -0
  60. package/core/spa.js +599 -0
  61. package/core/view-loader.js +155 -613
  62. package/core/vite-plugin.d.ts +18 -0
  63. package/core/vite-plugin.js +162 -0
  64. package/core/vite.js +250 -145
  65. package/index.js +22 -18
  66. package/jsconfig.json +5 -3
  67. package/package.json +114 -92
  68. package/production.md +8 -3
  69. package/public/js/bluebird.js +1886 -0
  70. package/templates/_auth/app/database.js +19 -0
  71. package/templates/_auth/app/models/user.js +22 -0
  72. package/templates/_auth/app/routes/auth-router.js +304 -0
  73. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  74. package/templates/_base/app/resources/html/notFound.html +14 -0
  75. package/templates/_base/app/resources/index.html +27 -0
  76. package/templates/_base/app/resources/styles.css +9 -0
  77. package/templates/api/app/models/note.js +18 -0
  78. package/templates/api/app/routes/api.js +82 -0
  79. package/templates/api/app/routes/auth.js +11 -0
  80. package/templates/api/index.js +19 -0
  81. package/templates/api/template.json +13 -0
  82. package/templates/auth/app/mail.js +11 -0
  83. package/templates/auth/app/models/password_reset.js +18 -0
  84. package/templates/auth/app/resources/html/home.html +21 -0
  85. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  86. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  87. package/templates/auth/app/resources/main.jsx +18 -0
  88. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  89. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  90. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  91. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  92. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  93. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  94. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  95. package/templates/auth/app/resources/routes.jsx +54 -0
  96. package/templates/auth/app/resources/spa.js +29 -0
  97. package/templates/auth/app/routes/api.js +17 -0
  98. package/templates/auth/app/routes/auth.js +13 -0
  99. package/templates/auth/app/routes/web.js +21 -0
  100. package/templates/auth/index.js +19 -0
  101. package/templates/auth/template.json +15 -0
  102. package/templates/blank/app/models/.gitkeep +0 -0
  103. package/templates/blank/app/resources/html/home.html +27 -0
  104. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  105. package/templates/blank/app/resources/main.jsx +16 -0
  106. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  107. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  108. package/templates/blank/app/resources/routes.jsx +15 -0
  109. package/templates/blank/app/resources/spa.js +24 -0
  110. package/templates/blank/app/routes/api.js +11 -0
  111. package/templates/blank/app/routes/web.js +21 -0
  112. package/templates/blank/index.js +13 -0
  113. package/templates/blank/template.json +12 -0
  114. package/templates/blog/app/lib/blog.js +149 -0
  115. package/templates/blog/app/models/post.js +22 -0
  116. package/templates/blog/app/resources/html/home.html +28 -0
  117. package/templates/blog/app/resources/html/not-found.html +5 -0
  118. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  119. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  120. package/templates/blog/app/resources/html/post.html +8 -0
  121. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  122. package/templates/blog/app/resources/main.jsx +18 -0
  123. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  124. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  125. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  126. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  127. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  128. package/templates/blog/app/resources/routes.jsx +51 -0
  129. package/templates/blog/app/resources/spa.js +25 -0
  130. package/templates/blog/app/resources/styles.css +40 -0
  131. package/templates/blog/app/routes/api.js +77 -0
  132. package/templates/blog/app/routes/auth.js +10 -0
  133. package/templates/blog/app/routes/web.js +114 -0
  134. package/templates/blog/index.js +21 -0
  135. package/templates/blog/template.json +14 -0
  136. package/vite.config.js +11 -0
  137. package/app/views/components/Header.jsx +0 -42
  138. package/app/views/components/LiveCounter.jsx +0 -67
  139. package/app/views/layouts/main/view.jsx +0 -201
  140. package/app/views/legal/terms.html +0 -29
  141. package/app/views/pages/about.jsx +0 -98
  142. package/app/views/pages/dashboard.jsx +0 -278
  143. package/app/views/pages/index.jsx +0 -123
  144. package/app/views/pages/login.jsx +0 -141
  145. package/core/actions.d.ts +0 -4
  146. package/core/actions.js +0 -355
  147. package/core/jsx.d.ts +0 -38
  148. package/core/jsx.js +0 -1597
  149. package/core/vite.d.ts +0 -3
  150. package/public/js/bluebird-client.js +0 -3265
  151. package/public/js/tailwind.js +0 -8
@@ -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
+ });