@lablup/ui-common 0.1.0-alpha.2 → 0.1.0-alpha.20
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/README.md +1 -1
- package/dist/assets/components/BaseCard/BaseCard.css +1 -1
- package/dist/assets/components/Button/Button.css +1 -1
- package/dist/assets/components/DataTable/DataTable.css +1 -1
- package/dist/assets/components/Drawer/Drawer.css +1 -1
- package/dist/assets/components/EmptyState/EmptyState.css +1 -1
- package/dist/assets/components/ErrorState/ErrorState.css +1 -1
- package/dist/assets/components/PageHeader/PageHeader.css +1 -1
- package/dist/assets/components/Select/Select.css +1 -0
- package/dist/assets/components/StatCard/StatCard.css +1 -1
- package/dist/assets/components/Tabs/Tabs.css +1 -1
- package/dist/assets/components/Tooltip/Tooltip.css +1 -1
- package/dist/components/DataTable/DataTable.d.ts +30 -6
- package/dist/components/DataTable/DataTable2.js +85 -92
- package/dist/components/DataTable/DataTable2.js.map +1 -1
- package/dist/components/Drawer/Drawer.d.ts +12 -1
- package/dist/components/Drawer/Drawer2.js +69 -51
- package/dist/components/Drawer/Drawer2.js.map +1 -1
- package/dist/components/EmptyState/EmptyState.d.ts +10 -3
- package/dist/components/EmptyState/EmptyState2.js +31 -48
- package/dist/components/EmptyState/EmptyState2.js.map +1 -1
- package/dist/components/EmptyState/index.d.ts +6 -1
- package/dist/components/ErrorState/ErrorState.d.ts +17 -4
- package/dist/components/ErrorState/ErrorState2.js +20 -23
- package/dist/components/ErrorState/ErrorState2.js.map +1 -1
- package/dist/components/ErrorState/index.d.ts +1 -1
- package/dist/components/PageHeader/PageHeader.d.ts +14 -1
- package/dist/components/PageHeader/PageHeader2.js +40 -24
- package/dist/components/PageHeader/PageHeader2.js.map +1 -1
- package/dist/components/Select/Select.d.ts +38 -0
- package/dist/components/Select/Select2.js +313 -0
- package/dist/components/Select/Select2.js.map +1 -0
- package/dist/components/Select/index.d.ts +2 -0
- package/dist/components/Select/index.js +2 -0
- package/dist/components/Skeleton/Skeleton.d.ts +11 -1
- package/dist/components/Skeleton/Skeleton2.js +8 -6
- package/dist/components/Skeleton/Skeleton2.js.map +1 -1
- package/dist/components/Skeleton/SkeletonCard.d.ts +3 -1
- package/dist/components/Skeleton/SkeletonCard2.js +13 -3
- package/dist/components/Skeleton/SkeletonCard2.js.map +1 -1
- package/dist/components/Skeleton/SkeletonChart2.js +5 -0
- package/dist/components/Skeleton/SkeletonChart2.js.map +1 -1
- package/dist/components/Skeleton/SkeletonRow.d.ts +3 -1
- package/dist/components/Skeleton/SkeletonRow2.js +9 -3
- package/dist/components/Skeleton/SkeletonRow2.js.map +1 -1
- package/dist/components/Skeleton/SkeletonText.d.ts +3 -1
- package/dist/components/Skeleton/SkeletonText2.js +7 -5
- package/dist/components/Skeleton/SkeletonText2.js.map +1 -1
- package/dist/components/StatCard/StatCard.d.ts +10 -1
- package/dist/components/StatCard/StatCard2.js +30 -30
- package/dist/components/StatCard/StatCard2.js.map +1 -1
- package/dist/components/Tabs/Tabs.d.ts +10 -23
- package/dist/components/Tabs/Tabs2.js +127 -146
- package/dist/components/Tabs/Tabs2.js.map +1 -1
- package/dist/components/Tabs/index.d.ts +2 -2
- package/dist/components/Tabs/index.js +2 -3
- package/dist/components/Tooltip/Tooltip.d.ts +15 -1
- package/dist/components/Tooltip/Tooltip2.js +77 -47
- package/dist/components/Tooltip/Tooltip2.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +6 -6
- package/dist/styles/base.css +101 -10
- package/dist/styles/themes/orange-dark.css +3 -0
- package/dist/styles/themes/orange-light.css +6 -1
- package/package.json +1 -1
- package/dist/components/EmptyState/illustrations.d.ts +0 -51
- package/dist/components/EmptyState/illustrations.js +0 -571
- package/dist/components/EmptyState/illustrations.js.map +0 -1
- package/dist/components/Tabs/tabTags.d.ts +0 -9
- package/dist/components/Tabs/tabTags.js +0 -11
- package/dist/components/Tabs/tabTags.js.map +0 -1
|
@@ -2,44 +2,29 @@
|
|
|
2
2
|
import { memo as e, useCallback as t, useEffect as n, useMemo as r, useRef as i, useState as a } from "react";
|
|
3
3
|
import { jsx as o, jsxs as s } from "react/jsx-runtime";
|
|
4
4
|
//#region src/components/DataTable/DataTable.tsx
|
|
5
|
-
var c =
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
widths: {},
|
|
23
|
-
visibility: {}
|
|
24
|
-
};
|
|
25
|
-
let r = n;
|
|
26
|
-
return {
|
|
27
|
-
widths: typeof r.widths == "object" && r.widths !== null ? r.widths : {},
|
|
28
|
-
visibility: typeof r.visibility == "object" && r.visibility !== null ? r.visibility : {}
|
|
29
|
-
};
|
|
30
|
-
} catch {
|
|
31
|
-
return {
|
|
32
|
-
widths: {},
|
|
33
|
-
visibility: {}
|
|
34
|
-
};
|
|
35
|
-
}
|
|
5
|
+
var c = [
|
|
6
|
+
"a",
|
|
7
|
+
"button",
|
|
8
|
+
"input",
|
|
9
|
+
"select",
|
|
10
|
+
"textarea",
|
|
11
|
+
"summary",
|
|
12
|
+
"label",
|
|
13
|
+
"[contenteditable='true']",
|
|
14
|
+
"[role='button']",
|
|
15
|
+
"[role='link']",
|
|
16
|
+
"[tabindex]:not([tabindex='-1'])"
|
|
17
|
+
].join(",");
|
|
18
|
+
function l(e, t) {
|
|
19
|
+
if (!(e instanceof Element) || !(t instanceof Element)) return !1;
|
|
20
|
+
let n = e.closest(c);
|
|
21
|
+
return n !== null && n !== t && t.contains(n);
|
|
36
22
|
}
|
|
23
|
+
var u = {
|
|
24
|
+
widths: {},
|
|
25
|
+
visibility: {}
|
|
26
|
+
};
|
|
37
27
|
function d(e, t) {
|
|
38
|
-
if (!(!e || typeof window > "u")) try {
|
|
39
|
-
window.localStorage.setItem(l(e), JSON.stringify(t));
|
|
40
|
-
} catch {}
|
|
41
|
-
}
|
|
42
|
-
function f(e, t) {
|
|
43
28
|
let n = e.map((e, t) => ({
|
|
44
29
|
row: e,
|
|
45
30
|
i: t
|
|
@@ -49,7 +34,7 @@ function f(e, t) {
|
|
|
49
34
|
return r === 0 ? e.i - n.i : r;
|
|
50
35
|
}), n.map(({ row: e }) => e);
|
|
51
36
|
}
|
|
52
|
-
function
|
|
37
|
+
function f(e, t) {
|
|
53
38
|
let { sortComparator: n } = e;
|
|
54
39
|
if (n) return (e, r) => n(e, r, t);
|
|
55
40
|
let r = e.sortValueAccessor;
|
|
@@ -62,10 +47,10 @@ function p(e, t) {
|
|
|
62
47
|
return o = typeof i == "number" && typeof a == "number" ? i - a : String(i).localeCompare(String(a)), t === "asc" ? o : -o;
|
|
63
48
|
} : () => 0;
|
|
64
49
|
}
|
|
65
|
-
function
|
|
50
|
+
function p(e, t, n) {
|
|
66
51
|
if (e.sortable) return e.id === t ? n === "asc" ? "ascending" : "descending" : "none";
|
|
67
52
|
}
|
|
68
|
-
function
|
|
53
|
+
function m({ direction: e }) {
|
|
69
54
|
return e === "none" ? /* @__PURE__ */ o("span", {
|
|
70
55
|
className: "data-table__sort-icon data-table__sort-icon--none",
|
|
71
56
|
"aria-hidden": "true",
|
|
@@ -123,36 +108,36 @@ function h({ direction: e }) {
|
|
|
123
108
|
})
|
|
124
109
|
});
|
|
125
110
|
}
|
|
126
|
-
function
|
|
127
|
-
let [
|
|
111
|
+
function h({ columns: e, rows: c, getRowKey: h, emptyState: g, loadingState: _, loading: v = !1, columnState: y, onColumnStateChange: b, className: x = "", ariaLabel: S = "Data table", testId: C, onRowClick: w, isRowClickable: T, rowClassName: E, sortColumnId: D, sortDirection: O, onSortChange: k }) {
|
|
112
|
+
let [A, j] = a(() => y ?? u);
|
|
128
113
|
n(() => {
|
|
129
|
-
|
|
114
|
+
y && j(y);
|
|
130
115
|
}, [y]);
|
|
131
|
-
let
|
|
116
|
+
let M = D !== void 0 || O !== void 0, [N, P] = a(void 0), [F, I] = a(void 0), L = M ? D : N, R = M ? O : F, z = t((e) => {
|
|
132
117
|
if (!e.sortable) return;
|
|
133
118
|
let t, n;
|
|
134
|
-
|
|
119
|
+
L === e.id ? R === (e.defaultSortDirection ?? "asc") ? (t = e.id, n = R === "asc" ? "desc" : "asc") : (t = void 0, n = void 0) : (t = e.id, n = e.defaultSortDirection ?? "asc"), M || (P(t), I(n)), k?.(t, n);
|
|
135
120
|
}, [
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
]),
|
|
141
|
-
let t =
|
|
142
|
-
return
|
|
143
|
-
}, [
|
|
121
|
+
L,
|
|
122
|
+
R,
|
|
123
|
+
M,
|
|
124
|
+
k
|
|
125
|
+
]), B = r(() => e.filter((e) => e.alwaysVisible ? !0 : A.visibility[e.id] !== !1), [e, A.visibility]), V = t((e) => {
|
|
126
|
+
let t = A.widths[e.id], n = typeof t == "number" && t > 0 ? t : e.initialWidth;
|
|
127
|
+
return n === void 0 ? void 0 : Math.max(n, e.minWidth ?? 0);
|
|
128
|
+
}, [A.widths]), H = i(null), U = t((e, t, n) => {
|
|
144
129
|
if (t.noResize) return;
|
|
145
|
-
e.preventDefault(), e.stopPropagation(),
|
|
130
|
+
e.preventDefault(), e.stopPropagation(), H.current = {
|
|
146
131
|
columnId: t.id,
|
|
147
132
|
startX: e.clientX,
|
|
148
133
|
startWidth: n,
|
|
149
134
|
minWidth: t.minWidth ?? 80
|
|
150
135
|
};
|
|
151
136
|
let r = (e) => {
|
|
152
|
-
let t =
|
|
137
|
+
let t = H.current;
|
|
153
138
|
if (!t) return;
|
|
154
139
|
let n = e.clientX - t.startX, r = Math.max(t.minWidth, t.startWidth + n);
|
|
155
|
-
|
|
140
|
+
j((e) => ({
|
|
156
141
|
...e,
|
|
157
142
|
widths: {
|
|
158
143
|
...e.widths,
|
|
@@ -160,36 +145,36 @@ function g({ columns: e, rows: c, getRowKey: l, emptyState: g, loadingState: _,
|
|
|
160
145
|
}
|
|
161
146
|
}));
|
|
162
147
|
}, i = () => {
|
|
163
|
-
|
|
148
|
+
H.current = null, window.removeEventListener("mousemove", r), window.removeEventListener("mouseup", i);
|
|
164
149
|
};
|
|
165
150
|
window.addEventListener("mousemove", r), window.addEventListener("mouseup", i);
|
|
166
|
-
}, []);
|
|
151
|
+
}, []), W = i(A);
|
|
167
152
|
n(() => {
|
|
168
|
-
|
|
169
|
-
}, [
|
|
170
|
-
let
|
|
171
|
-
if (!
|
|
172
|
-
let t = e.find((e) => e.id ===
|
|
173
|
-
return t?.sortable ?
|
|
153
|
+
W.current !== A && (W.current = A, b?.(A));
|
|
154
|
+
}, [A, b]);
|
|
155
|
+
let G = r(() => {
|
|
156
|
+
if (!L || !R) return c;
|
|
157
|
+
let t = e.find((e) => e.id === L);
|
|
158
|
+
return t?.sortable ? d(c, f(t, R)) : c;
|
|
174
159
|
}, [
|
|
175
160
|
c,
|
|
176
161
|
e,
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
]),
|
|
162
|
+
L,
|
|
163
|
+
R
|
|
164
|
+
]), K = ["data-table", x].filter(Boolean).join(" ");
|
|
180
165
|
return /* @__PURE__ */ o("div", {
|
|
181
|
-
className:
|
|
182
|
-
"data-testid":
|
|
166
|
+
className: K,
|
|
167
|
+
"data-testid": C,
|
|
183
168
|
children: /* @__PURE__ */ s("table", {
|
|
184
169
|
className: "data-table__table",
|
|
185
|
-
"aria-label":
|
|
170
|
+
"aria-label": S,
|
|
186
171
|
role: "table",
|
|
187
172
|
children: [/* @__PURE__ */ o("thead", {
|
|
188
173
|
className: "data-table__head",
|
|
189
174
|
children: /* @__PURE__ */ o("tr", {
|
|
190
175
|
className: "data-table__row data-table__row--head",
|
|
191
|
-
children:
|
|
192
|
-
let t =
|
|
176
|
+
children: B.map((e) => {
|
|
177
|
+
let t = V(e), n = e.sortable && e.id === L;
|
|
193
178
|
return /* @__PURE__ */ s("th", {
|
|
194
179
|
scope: "col",
|
|
195
180
|
className: [
|
|
@@ -200,13 +185,16 @@ function g({ columns: e, rows: c, getRowKey: l, emptyState: g, loadingState: _,
|
|
|
200
185
|
e.className,
|
|
201
186
|
e.align && `data-table__cell--align-${e.align}`
|
|
202
187
|
].filter(Boolean).join(" "),
|
|
203
|
-
style:
|
|
204
|
-
|
|
188
|
+
style: {
|
|
189
|
+
width: t === void 0 ? void 0 : `${String(t)}px`,
|
|
190
|
+
minWidth: e.minWidth
|
|
191
|
+
},
|
|
192
|
+
"aria-sort": p(e, L, R),
|
|
205
193
|
onClick: e.sortable ? () => {
|
|
206
|
-
|
|
194
|
+
z(e);
|
|
207
195
|
} : void 0,
|
|
208
196
|
onKeyDown: e.sortable ? (t) => {
|
|
209
|
-
(t.key === "Enter" || t.key === " ") && (t.preventDefault(),
|
|
197
|
+
(t.key === "Enter" || t.key === " ") && (t.preventDefault(), z(e));
|
|
210
198
|
} : void 0,
|
|
211
199
|
tabIndex: e.sortable ? 0 : void 0,
|
|
212
200
|
children: [
|
|
@@ -214,13 +202,13 @@ function g({ columns: e, rows: c, getRowKey: l, emptyState: g, loadingState: _,
|
|
|
214
202
|
className: "data-table__head-label",
|
|
215
203
|
children: e.header
|
|
216
204
|
}),
|
|
217
|
-
e.sortable && /* @__PURE__ */ o(
|
|
205
|
+
e.sortable && /* @__PURE__ */ o(m, { direction: n && R ? R : "none" }),
|
|
218
206
|
!e.noResize && /* @__PURE__ */ o("div", {
|
|
219
207
|
role: "separator",
|
|
220
208
|
"aria-orientation": "vertical",
|
|
221
209
|
className: "data-table__resize-handle",
|
|
222
210
|
onMouseDown: (n) => {
|
|
223
|
-
|
|
211
|
+
U(n, e, t ?? e.minWidth ?? 120);
|
|
224
212
|
}
|
|
225
213
|
})
|
|
226
214
|
]
|
|
@@ -232,35 +220,40 @@ function g({ columns: e, rows: c, getRowKey: l, emptyState: g, loadingState: _,
|
|
|
232
220
|
children: v ? /* @__PURE__ */ o("tr", {
|
|
233
221
|
className: "data-table__row data-table__row--state",
|
|
234
222
|
children: /* @__PURE__ */ o("td", {
|
|
235
|
-
colSpan:
|
|
223
|
+
colSpan: B.length || 1,
|
|
236
224
|
className: "data-table__state-cell",
|
|
237
225
|
children: _ ?? /* @__PURE__ */ o("div", { className: "data-table__loading" })
|
|
238
226
|
})
|
|
239
|
-
}) :
|
|
227
|
+
}) : G.length === 0 ? /* @__PURE__ */ o("tr", {
|
|
240
228
|
className: "data-table__row data-table__row--state",
|
|
241
229
|
children: /* @__PURE__ */ o("td", {
|
|
242
|
-
colSpan:
|
|
230
|
+
colSpan: B.length || 1,
|
|
243
231
|
className: "data-table__state-cell",
|
|
244
232
|
children: g
|
|
245
233
|
})
|
|
246
|
-
}) :
|
|
247
|
-
let n =
|
|
234
|
+
}) : G.map((e, t) => {
|
|
235
|
+
let n = h(e, t), r = !!(w && (T?.(e, t) ?? !0)), i = E?.(e, t);
|
|
248
236
|
return /* @__PURE__ */ o("tr", {
|
|
249
|
-
className: [
|
|
250
|
-
|
|
251
|
-
|
|
237
|
+
className: [
|
|
238
|
+
"data-table__row",
|
|
239
|
+
r && "data-table__row--clickable",
|
|
240
|
+
i
|
|
241
|
+
].filter(Boolean).join(" "),
|
|
242
|
+
onClick: r ? (t) => {
|
|
243
|
+
l(t.target, t.currentTarget) || w?.(e);
|
|
252
244
|
} : void 0,
|
|
253
|
-
onKeyDown:
|
|
254
|
-
(t.key === "Enter" || t.key === " ") && (t.preventDefault(),
|
|
245
|
+
onKeyDown: r ? (t) => {
|
|
246
|
+
(t.key === "Enter" || t.key === " ") && (l(t.target, t.currentTarget) || (t.preventDefault(), w?.(e)));
|
|
255
247
|
} : void 0,
|
|
256
|
-
tabIndex:
|
|
257
|
-
role:
|
|
258
|
-
children:
|
|
248
|
+
tabIndex: r ? 0 : void 0,
|
|
249
|
+
role: r ? "button" : void 0,
|
|
250
|
+
children: B.map((n) => /* @__PURE__ */ o("td", {
|
|
259
251
|
className: [
|
|
260
252
|
"data-table__cell",
|
|
261
253
|
n.className,
|
|
262
254
|
n.align && `data-table__cell--align-${n.align}`
|
|
263
255
|
].filter(Boolean).join(" "),
|
|
256
|
+
style: { minWidth: n.minWidth },
|
|
264
257
|
children: n.render(e, t)
|
|
265
258
|
}, n.id))
|
|
266
259
|
}, n);
|
|
@@ -269,9 +262,9 @@ function g({ columns: e, rows: c, getRowKey: l, emptyState: g, loadingState: _,
|
|
|
269
262
|
})
|
|
270
263
|
});
|
|
271
264
|
}
|
|
272
|
-
var
|
|
265
|
+
var g = e(h);
|
|
273
266
|
//#endregion
|
|
274
|
-
export {
|
|
267
|
+
export { g as DataTable, g as default };
|
|
275
268
|
|
|
276
269
|
//# sourceMappingURL=DataTable2.js.map
|
|
277
270
|
import "../../assets/components/DataTable/DataTable.css";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTable2.js","names":[],"sources":["../../../src/components/DataTable/DataTable.tsx"],"sourcesContent":["/**\n * DataTable Component (epic #2730 / issue #2738 · sort: epic #2859 / issue #2861)\n *\n * Generic, type-safe table primitive modeled after the Backend.AI WebUI\n * `BAITable`. Designed so future menus (Models, Sessions, Data, ...)\n * can share one tabular surface instead of inventing a new one each\n * time.\n *\n * Features (V1 — additional capabilities planned for follow-up issues):\n * - Type-safe column definitions with custom cell renderers\n * - Optional column-visibility persistence via `localStorage` when\n * `persistKey` is supplied\n * - Optional resizable columns (drag the right edge of a header cell)\n * with widths persisted alongside visibility\n * - Empty-state slot rendered when `rows` is empty\n * - Loading-state slot rendered when `loading` is `true`\n * - Stable `getRowKey` accessor so rows with the same identifier remain\n * referentially identical across event-driven updates\n *\n * Sorting (V2 — epic #2859 / issue #2861):\n * - Optional per-column sortable flag with sort value accessor or\n * custom comparator\n * - Optional defaultSortDirection per column\n * - Controlled (`sortColumnId` + `sortDirection` + `onSortChange`) and\n * uncontrolled (internal state) modes\n * - Accessible `aria-sort` attributes on header cells\n * - Keyboard activation (Enter / Space) for sortable headers\n * - Stable sort — equal-valued rows retain their original order\n * - Sorting never mutates the original `rows` prop\n *\n * The component is intentionally domain-agnostic — it MUST NOT carry\n * Session, Model, or Agent-specific knowledge. The first consumer is\n * `SessionListTable` (epic #2730 / #2738) but the API is generic.\n */\n\nimport {\n memo,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport \"./DataTable.css\";\n\n// ============================================================================\n// Public types\n// ============================================================================\n\n/** Direction a column is currently sorted. */\nexport type SortDirection = \"asc\" | \"desc\";\n\nexport interface DataTableColumn<T> {\n /** Unique identifier for the column. Used for visibility + width persistence. */\n id: string;\n /** Header label. */\n header: ReactNode;\n /**\n * Cell renderer. Receives the row and returns a React node. Pure\n * functions are encouraged so memoization stays effective.\n */\n render: (row: T, index: number) => ReactNode;\n /** Optional minimum column width in pixels. Defaults to 80. */\n minWidth?: number;\n /** Optional initial width in pixels (only honored on the first paint). */\n initialWidth?: number;\n /** When `true`, the column cannot be resized. Defaults to `false`. */\n noResize?: boolean;\n /** When `true`, the column cannot be hidden by the user. Defaults to `false`. */\n alwaysVisible?: boolean;\n /** Extra `class` for the column's `<th>` and `<td>` cells. */\n className?: string;\n /**\n * When provided, the value is exposed via the `align` style on the\n * column's cells. Useful for right-aligned numeric columns.\n */\n align?: \"left\" | \"right\" | \"center\";\n\n // ---- Sorting API (added epic #2859 / issue #2861) -------------------------\n\n /**\n * When `true`, the column header renders a sort affordance and clicking\n * (or pressing Enter / Space) cycles through ascending → descending →\n * unsorted states. Defaults to `false`.\n */\n sortable?: boolean;\n /**\n * Extracts a primitive comparable value from a row for sorting purposes.\n * Used when the default ascending/descending behavior is sufficient.\n * Mutually exclusive with `sortComparator` — if both are provided,\n * `sortComparator` takes precedence.\n *\n * @example\n * ```tsx\n * sortValueAccessor: (row) => row.name.toLowerCase()\n * ```\n */\n sortValueAccessor?: (row: T) => string | number | boolean | null | undefined;\n /**\n * Custom comparator used for sorting. Receives two rows and the active\n * sort direction. Return a negative number if `a` should come first, a\n * positive number if `b` should come first, or `0` if they are equal.\n * The table applies a stable fallback on `0` to preserve original order.\n *\n * @example\n * ```tsx\n * sortComparator: (a, b, dir) =>\n * dir === \"asc\"\n * ? a.createdAt - b.createdAt\n * : b.createdAt - a.createdAt\n * ```\n */\n sortComparator?: (a: T, b: T, direction: SortDirection) => number;\n /**\n * The sort direction applied when this column is first activated.\n * Defaults to `\"asc\"`.\n */\n defaultSortDirection?: SortDirection;\n}\n\nexport interface DataTablePersistedState {\n /** column id → user-overridden width in pixels. */\n widths: Record<string, number>;\n /** column id → visibility flag. Missing keys count as visible. */\n visibility: Record<string, boolean>;\n}\n\nexport interface DataTableProps<T> {\n /** Column definitions, in display order. */\n columns: DataTableColumn<T>[];\n /** Row data. */\n rows: T[];\n /**\n * Stable identifier accessor — used as the React key for each row.\n * Must be deterministic for the lifetime of the row.\n */\n getRowKey: (row: T, index: number) => string;\n /** Render this node when `rows` is empty. */\n emptyState?: ReactNode;\n /** Render this node when `loading` is `true`. */\n loadingState?: ReactNode;\n /** When `true`, the loading slot replaces the table body. */\n loading?: boolean;\n /**\n * When provided, column widths and visibility settings are persisted\n * to `localStorage` under this key. Use a stable, namespaced string\n * (e.g. `\"sessions.activeTab\"`).\n */\n persistKey?: string;\n /** Extra class for the table's wrapping element. */\n className?: string;\n /** ARIA label for the table. Defaults to \"Data table\". */\n ariaLabel?: string;\n /** Test ID for testing harnesses. */\n testId?: string;\n /**\n * Callback invoked when a row is clicked. When provided, rows render\n * with a clickable affordance (cursor: pointer + keyboard binding).\n */\n onRowClick?: (row: T) => void;\n\n // ---- Sorting props (added epic #2859 / issue #2861) -----------------------\n\n /**\n * Controlled — the column currently being sorted. Pass `undefined` to\n * indicate no active sort. When this prop is present, the component\n * operates in controlled mode: the caller is responsible for updating\n * the sort state via `onSortChange`.\n */\n sortColumnId?: string;\n /**\n * Controlled — the direction of the active sort. Ignored when\n * `sortColumnId` is `undefined`.\n */\n sortDirection?: SortDirection;\n /**\n * Called when the user activates a sortable column header. In\n * controlled mode the caller must propagate this back as\n * `sortColumnId` / `sortDirection`. In uncontrolled mode this prop is\n * purely observational.\n *\n * @param columnId The column being sorted, or `undefined` when the\n * sort is cleared.\n * @param direction The new direction.\n */\n onSortChange?: (\n columnId: string | undefined,\n direction: SortDirection | undefined,\n ) => void;\n}\n\n// ============================================================================\n// Storage helpers\n// ============================================================================\n\nconst STORAGE_NAMESPACE = \"dataTable\";\n\nfunction buildStorageKey(persistKey: string): string {\n return `${STORAGE_NAMESPACE}.${persistKey}`;\n}\n\n/**\n * Load persisted state from `localStorage`. Returns an empty state on\n * any failure (missing storage, malformed JSON, schema drift) so the\n * component degrades gracefully.\n */\nfunction loadPersistedState(persistKey: string | undefined): DataTablePersistedState {\n if (!persistKey || typeof window === \"undefined\") {\n return { widths: {}, visibility: {} };\n }\n try {\n const raw = window.localStorage.getItem(buildStorageKey(persistKey));\n if (!raw) return { widths: {}, visibility: {} };\n const parsed = JSON.parse(raw) as unknown;\n if (typeof parsed !== \"object\" || parsed === null) {\n return { widths: {}, visibility: {} };\n }\n const obj = parsed as { widths?: unknown; visibility?: unknown };\n const widths =\n typeof obj.widths === \"object\" && obj.widths !== null\n ? (obj.widths as Record<string, number>)\n : {};\n const visibility =\n typeof obj.visibility === \"object\" && obj.visibility !== null\n ? (obj.visibility as Record<string, boolean>)\n : {};\n return { widths, visibility };\n } catch {\n return { widths: {}, visibility: {} };\n }\n}\n\nfunction savePersistedState(\n persistKey: string | undefined,\n state: DataTablePersistedState,\n): void {\n if (!persistKey || typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(buildStorageKey(persistKey), JSON.stringify(state));\n } catch {\n // Quota exceeded / disabled storage — silently ignore.\n }\n}\n\n// ============================================================================\n// Sorting helpers\n// ============================================================================\n\n/**\n * Stable sort — rows with equal comparison result keep their original\n * relative order. We achieve stability by augmenting each row with its\n * original index and using that as a tie-breaker.\n *\n * The input array is never mutated.\n */\nfunction stableSort<T>(rows: T[], comparator: (a: T, b: T) => number): T[] {\n const indexed = rows.map((row, i) => ({ row, i }));\n indexed.sort((a, b) => {\n const result = comparator(a.row, b.row);\n return result !== 0 ? result : a.i - b.i;\n });\n return indexed.map(({ row }) => row);\n}\n\n/**\n * Builds a comparator from a `DataTableColumn` + active sort direction.\n * Falls back to string comparison when neither `sortComparator` nor\n * `sortValueAccessor` is provided on the column.\n */\nfunction buildComparator<T>(\n col: DataTableColumn<T>,\n direction: SortDirection,\n): (a: T, b: T) => number {\n const { sortComparator } = col;\n if (sortComparator) {\n return (a, b) => sortComparator(a, b, direction);\n }\n const accessor = col.sortValueAccessor;\n if (accessor) {\n return (a, b) => {\n const av = accessor(a);\n const bv = accessor(b);\n // Nullish values sort last regardless of direction.\n if (av == null && bv == null) return 0;\n if (av == null) return 1;\n if (bv == null) return -1;\n let cmp: number;\n if (typeof av === \"number\" && typeof bv === \"number\") {\n cmp = av - bv;\n } else {\n cmp = String(av).localeCompare(String(bv));\n }\n return direction === \"asc\" ? cmp : -cmp;\n };\n }\n // No accessor — unsortable in practice (column should not be sortable).\n return () => 0;\n}\n\n/**\n * Returns the `aria-sort` attribute value for a column header cell.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort\n */\nfunction ariaSortValue(\n col: DataTableColumn<unknown>,\n activeSortColumnId: string | undefined,\n activeSortDirection: SortDirection | undefined,\n): \"ascending\" | \"descending\" | \"none\" | undefined {\n if (!col.sortable) return undefined;\n if (col.id === activeSortColumnId) {\n return activeSortDirection === \"asc\" ? \"ascending\" : \"descending\";\n }\n return \"none\";\n}\n\n// Sort indicator icons rendered as inline SVG so there is no external\n// asset dependency. They intentionally reuse design-token colours so they\n// automatically adapt to light / dark themes.\n\nfunction SortIcon({ direction }: { direction: SortDirection | \"none\" }) {\n if (direction === \"none\") {\n // Neutral chevron stack — both arrows in muted colour\n return (\n <span\n className=\"data-table__sort-icon data-table__sort-icon--none\"\n aria-hidden=\"true\"\n >\n <svg\n width=\"10\"\n height=\"14\"\n viewBox=\"0 0 10 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M5 1L1 5H9L5 1Z\" fill=\"currentColor\" opacity=\"0.35\" />\n <path d=\"M5 13L9 9H1L5 13Z\" fill=\"currentColor\" opacity=\"0.35\" />\n </svg>\n </span>\n );\n }\n if (direction === \"asc\") {\n return (\n <span\n className=\"data-table__sort-icon data-table__sort-icon--asc\"\n aria-hidden=\"true\"\n >\n <svg\n width=\"10\"\n height=\"14\"\n viewBox=\"0 0 10 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M5 1L1 5H9L5 1Z\" fill=\"currentColor\" />\n <path d=\"M5 13L9 9H1L5 13Z\" fill=\"currentColor\" opacity=\"0.25\" />\n </svg>\n </span>\n );\n }\n return (\n <span\n className=\"data-table__sort-icon data-table__sort-icon--desc\"\n aria-hidden=\"true\"\n >\n <svg\n width=\"10\"\n height=\"14\"\n viewBox=\"0 0 10 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M5 1L1 5H9L5 1Z\" fill=\"currentColor\" opacity=\"0.25\" />\n <path d=\"M5 13L9 9H1L5 13Z\" fill=\"currentColor\" />\n </svg>\n </span>\n );\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nfunction DataTableInner<T>({\n columns,\n rows,\n getRowKey,\n emptyState,\n loadingState,\n loading = false,\n persistKey,\n className = \"\",\n ariaLabel = \"Data table\",\n testId,\n onRowClick,\n // Sorting (controlled)\n sortColumnId: controlledSortColumnId,\n sortDirection: controlledSortDirection,\n onSortChange,\n}: DataTableProps<T>) {\n // ---- Persisted state (widths + visibility) -------------------------------\n const [persisted, setPersisted] = useState<DataTablePersistedState>(() =>\n loadPersistedState(persistKey),\n );\n\n // Refresh persisted state when the storage key changes (defensive — the\n // expected use case is a stable key).\n useEffect(() => {\n setPersisted(loadPersistedState(persistKey));\n }, [persistKey]);\n\n // ---- Sorting state (uncontrolled fallback) -------------------------------\n //\n // Controlled mode is detected by the presence of `sortColumnId` as a prop\n // (the caller explicitly manages the sort column). Using only this prop as\n // the signal (rather than OR-ing with `sortDirection`) avoids a\n // pathological state where `sortDirection` is set but `sortColumnId` is\n // not, which would enter controlled mode with no sort effect.\n //\n // Note: TypeScript cannot distinguish \"prop not passed\" from \"prop passed\n // as undefined\", so we rely on the convention that controlled callers\n // always pass both `sortColumnId` and `sortDirection` together.\n const isControlled =\n controlledSortColumnId !== undefined || controlledSortDirection !== undefined;\n\n const [internalSortColumnId, setInternalSortColumnId] = useState<string | undefined>(\n undefined,\n );\n const [internalSortDirection, setInternalSortDirection] = useState<\n SortDirection | undefined\n >(undefined);\n\n const activeSortColumnId = isControlled\n ? controlledSortColumnId\n : internalSortColumnId;\n const activeSortDirection = isControlled\n ? controlledSortDirection\n : internalSortDirection;\n\n /** Handle a click / keypress on a sortable column header. */\n const handleSortToggle = useCallback(\n (col: DataTableColumn<T>) => {\n if (!col.sortable) return;\n\n let nextColumnId: string | undefined;\n let nextDirection: SortDirection | undefined;\n\n if (activeSortColumnId !== col.id) {\n // Activate this column in its default direction.\n nextColumnId = col.id;\n nextDirection = col.defaultSortDirection ?? \"asc\";\n } else if (activeSortDirection === (col.defaultSortDirection ?? \"asc\")) {\n // Flip to the opposite direction.\n nextColumnId = col.id;\n nextDirection = activeSortDirection === \"asc\" ? \"desc\" : \"asc\";\n } else {\n // Already in the non-default direction — clear the sort.\n nextColumnId = undefined;\n nextDirection = undefined;\n }\n\n if (!isControlled) {\n setInternalSortColumnId(nextColumnId);\n setInternalSortDirection(nextDirection);\n }\n onSortChange?.(nextColumnId, nextDirection);\n },\n [activeSortColumnId, activeSortDirection, isControlled, onSortChange],\n );\n\n // ---- Visibility computation (column always-visible wins) -----------------\n const visibleColumns = useMemo(\n () =>\n columns.filter((col) => {\n if (col.alwaysVisible) return true;\n const flag = persisted.visibility[col.id];\n return flag !== false;\n }),\n [columns, persisted.visibility],\n );\n\n // ---- Width resolution ----------------------------------------------------\n const resolveWidth = useCallback(\n (col: DataTableColumn<T>): number | undefined => {\n const persistedWidth = persisted.widths[col.id];\n if (typeof persistedWidth === \"number\" && persistedWidth > 0) {\n return persistedWidth;\n }\n return col.initialWidth;\n },\n [persisted.widths],\n );\n\n // ---- Resize handling -----------------------------------------------------\n const resizeRef = useRef<{\n columnId: string;\n startX: number;\n startWidth: number;\n minWidth: number;\n } | null>(null);\n\n const beginResize = useCallback(\n (\n ev: React.MouseEvent<HTMLDivElement>,\n col: DataTableColumn<T>,\n currentWidth: number,\n ) => {\n if (col.noResize) return;\n ev.preventDefault();\n ev.stopPropagation();\n resizeRef.current = {\n columnId: col.id,\n startX: ev.clientX,\n startWidth: currentWidth,\n minWidth: col.minWidth ?? 80,\n };\n\n const onMove = (e: MouseEvent) => {\n const ref = resizeRef.current;\n if (!ref) return;\n const delta = e.clientX - ref.startX;\n const next = Math.max(ref.minWidth, ref.startWidth + delta);\n setPersisted((prev) => ({\n ...prev,\n widths: { ...prev.widths, [ref.columnId]: next },\n }));\n };\n const onUp = () => {\n resizeRef.current = null;\n window.removeEventListener(\"mousemove\", onMove);\n window.removeEventListener(\"mouseup\", onUp);\n };\n window.addEventListener(\"mousemove\", onMove);\n window.addEventListener(\"mouseup\", onUp);\n },\n [],\n );\n\n // Persist when state changes\n useEffect(() => {\n savePersistedState(persistKey, persisted);\n }, [persistKey, persisted]);\n\n // ---- Sorted rows --------------------------------------------------------\n const sortedRows = useMemo(() => {\n if (!activeSortColumnId || !activeSortDirection) return rows;\n const col = columns.find((c) => c.id === activeSortColumnId);\n if (!col?.sortable) return rows;\n return stableSort(rows, buildComparator(col, activeSortDirection));\n }, [rows, columns, activeSortColumnId, activeSortDirection]);\n\n // ---- Body rendering ------------------------------------------------------\n const composedClassName = [\"data-table\", className].filter(Boolean).join(\" \");\n\n const renderBody = () => {\n if (loading) {\n return (\n <tr className=\"data-table__row data-table__row--state\">\n <td colSpan={visibleColumns.length || 1} className=\"data-table__state-cell\">\n {loadingState ?? <div className=\"data-table__loading\" />}\n </td>\n </tr>\n );\n }\n if (sortedRows.length === 0) {\n return (\n <tr className=\"data-table__row data-table__row--state\">\n <td colSpan={visibleColumns.length || 1} className=\"data-table__state-cell\">\n {emptyState}\n </td>\n </tr>\n );\n }\n return sortedRows.map((row, index) => {\n const key = getRowKey(row, index);\n return (\n <tr\n key={key}\n className={[\"data-table__row\", onRowClick && \"data-table__row--clickable\"]\n .filter(Boolean)\n .join(\" \")}\n onClick={\n onRowClick\n ? () => {\n onRowClick(row);\n }\n : undefined\n }\n onKeyDown={\n onRowClick\n ? (e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n e.preventDefault();\n onRowClick(row);\n }\n }\n : undefined\n }\n tabIndex={onRowClick ? 0 : undefined}\n role={onRowClick ? \"button\" : undefined}\n >\n {visibleColumns.map((col) => (\n <td\n key={col.id}\n className={[\n \"data-table__cell\",\n col.className,\n col.align && `data-table__cell--align-${col.align}`,\n ]\n .filter(Boolean)\n .join(\" \")}\n >\n {col.render(row, index)}\n </td>\n ))}\n </tr>\n );\n });\n };\n\n return (\n <div className={composedClassName} data-testid={testId}>\n <table className=\"data-table__table\" aria-label={ariaLabel} role=\"table\">\n <thead className=\"data-table__head\">\n <tr className=\"data-table__row data-table__row--head\">\n {visibleColumns.map((col) => {\n const width = resolveWidth(col);\n const isSortActive = col.sortable && col.id === activeSortColumnId;\n\n return (\n <th\n key={col.id}\n scope=\"col\"\n className={[\n \"data-table__cell\",\n \"data-table__cell--head\",\n col.sortable && \"data-table__cell--sortable\",\n isSortActive && \"data-table__cell--sort-active\",\n col.className,\n col.align && `data-table__cell--align-${col.align}`,\n ]\n .filter(Boolean)\n .join(\" \")}\n style={width ? { width: `${String(width)}px` } : undefined}\n aria-sort={ariaSortValue(\n col as DataTableColumn<unknown>,\n activeSortColumnId,\n activeSortDirection,\n )}\n onClick={\n col.sortable\n ? () => {\n handleSortToggle(col);\n }\n : undefined\n }\n onKeyDown={\n col.sortable\n ? (e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n e.preventDefault();\n handleSortToggle(col);\n }\n }\n : undefined\n }\n tabIndex={col.sortable ? 0 : undefined}\n >\n <span className=\"data-table__head-label\">{col.header}</span>\n {col.sortable && (\n <SortIcon\n direction={\n isSortActive && activeSortDirection\n ? activeSortDirection\n : \"none\"\n }\n />\n )}\n {!col.noResize && (\n <div\n role=\"separator\"\n aria-orientation=\"vertical\"\n className=\"data-table__resize-handle\"\n onMouseDown={(e) => {\n beginResize(e, col, width ?? col.minWidth ?? 120);\n }}\n />\n )}\n </th>\n );\n })}\n </tr>\n </thead>\n <tbody className=\"data-table__body\">{renderBody()}</tbody>\n </table>\n </div>\n );\n}\n\n// Memoize while preserving the generic signature.\nexport const DataTable = memo(DataTableInner) as typeof DataTableInner;\n\nexport default DataTable;\n"],"mappings":";;;;AAoMA,IAAM,IAAoB;AAE1B,SAAS,EAAgB,GAA4B;CACnD,OAAO,GAAG,EAAkB,GAAG;AACjC;AAOA,SAAS,EAAmB,GAAyD;CACnF,IAAI,CAAC,KAAc,OAAO,SAAW,KACnC,OAAO;EAAE,QAAQ,CAAC;EAAG,YAAY,CAAC;CAAE;CAEtC,IAAI;EACF,IAAM,IAAM,OAAO,aAAa,QAAQ,EAAgB,CAAU,CAAC;EACnE,IAAI,CAAC,GAAK,OAAO;GAAE,QAAQ,CAAC;GAAG,YAAY,CAAC;EAAE;EAC9C,IAAM,IAAS,KAAK,MAAM,CAAG;EAC7B,IAAI,OAAO,KAAW,aAAY,GAChC,OAAO;GAAE,QAAQ,CAAC;GAAG,YAAY,CAAC;EAAE;EAEtC,IAAM,IAAM;EASZ,OAAO;GAAE,QAPP,OAAO,EAAI,UAAW,YAAY,EAAI,WAAW,OAC5C,EAAI,SACL,CAAC;GAKU,YAHf,OAAO,EAAI,cAAe,YAAY,EAAI,eAAe,OACpD,EAAI,aACL,CAAC;EACqB;CAC9B,QAAQ;EACN,OAAO;GAAE,QAAQ,CAAC;GAAG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IAAa,WAAW,KAAA;MAE7B,UAAA,EAAe,KAAK,MACnB,kBAAC,MAAD;OAEE,WAAW;QACT;QACA,EAAI;QACJ,EAAI,SAAS,2BAA2B,EAAI;OAC9C,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;OAEV,UAAA,EAAI,OAAO,GAAK,CAAK;MACpB,GAVG,EAAI,EAUP,CACL;KACC,GAtCG,CAsCH;IAER,CAAC;GA4E4D,CAAA,CACpD;;CACJ,CAAA;AAET;AAGA,IAAa,IAAY,EAAK,CAAc"}
|
|
1
|
+
{"version":3,"file":"DataTable2.js","names":[],"sources":["../../../src/components/DataTable/DataTable.tsx"],"sourcesContent":["/**\n * DataTable Component (epic #2730 / issue #2738 · sort: epic #2859 / issue #2861)\n *\n * Generic, type-safe table primitive modeled after the Backend.AI WebUI\n * `BAITable`. Designed so future menus (Models, Sessions, Data, ...)\n * can share one tabular surface instead of inventing a new one each\n * time.\n *\n * Features (V1 — additional capabilities planned for follow-up issues):\n * - Type-safe column definitions with custom cell renderers\n * - Optional column-visibility persistence via `localStorage` when\n * `persistKey` is supplied\n * - Optional resizable columns (drag the right edge of a header cell)\n * with widths persisted alongside visibility\n * - Empty-state slot rendered when `rows` is empty\n * - Loading-state slot rendered when `loading` is `true`\n * - Stable `getRowKey` accessor so rows with the same identifier remain\n * referentially identical across event-driven updates\n *\n * Sorting (V2 — epic #2859 / issue #2861):\n * - Optional per-column sortable flag with sort value accessor or\n * custom comparator\n * - Optional defaultSortDirection per column\n * - Controlled (`sortColumnId` + `sortDirection` + `onSortChange`) and\n * uncontrolled (internal state) modes\n * - Accessible `aria-sort` attributes on header cells\n * - Keyboard activation (Enter / Space) for sortable headers\n * - Stable sort — equal-valued rows retain their original order\n * - Sorting never mutates the original `rows` prop\n *\n * The component is intentionally domain-agnostic — it MUST NOT carry\n * Session, Model, or Agent-specific knowledge. The first consumer is\n * `SessionListTable` (epic #2730 / #2738) but the API is generic.\n */\n\nimport {\n memo,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport \"./DataTable.css\";\n\n// ============================================================================\n// Public types\n// ============================================================================\n\n/** Direction a column is currently sorted. */\nexport type SortDirection = \"asc\" | \"desc\";\n\nexport interface DataTableColumn<T> {\n /** Unique identifier for the column. Used for visibility + width persistence. */\n id: string;\n /** Header label. */\n header: ReactNode;\n /**\n * Cell renderer. Receives the row and returns a React node. Pure\n * functions are encouraged so memoization stays effective.\n */\n render: (row: T, index: number) => ReactNode;\n /** Optional minimum column width in pixels. */\n minWidth?: number;\n /** Optional initial width in pixels (only honored on the first paint). */\n initialWidth?: number;\n /** When `true`, the column cannot be resized. Defaults to `false`. */\n noResize?: boolean;\n /** When `true`, the column cannot be hidden by the user. Defaults to `false`. */\n alwaysVisible?: boolean;\n /** Extra `class` for the column's `<th>` and `<td>` cells. */\n className?: string;\n /**\n * When provided, the value is exposed via the `align` style on the\n * column's cells. Useful for right-aligned numeric columns.\n */\n align?: \"left\" | \"right\" | \"center\";\n\n // ---- Sorting API (added epic #2859 / issue #2861) -------------------------\n\n /**\n * When `true`, the column header renders a sort affordance and clicking\n * (or pressing Enter / Space) cycles through ascending → descending →\n * unsorted states. Defaults to `false`.\n */\n sortable?: boolean;\n /**\n * Extracts a primitive comparable value from a row for sorting purposes.\n * Used when the default ascending/descending behavior is sufficient.\n * Mutually exclusive with `sortComparator` — if both are provided,\n * `sortComparator` takes precedence.\n *\n * @example\n * ```tsx\n * sortValueAccessor: (row) => row.name.toLowerCase()\n * ```\n */\n sortValueAccessor?: (row: T) => string | number | boolean | null | undefined;\n /**\n * Custom comparator used for sorting. Receives two rows and the active\n * sort direction. Return a negative number if `a` should come first, a\n * positive number if `b` should come first, or `0` if they are equal.\n * The table applies a stable fallback on `0` to preserve original order.\n *\n * @example\n * ```tsx\n * sortComparator: (a, b, dir) =>\n * dir === \"asc\"\n * ? a.createdAt - b.createdAt\n * : b.createdAt - a.createdAt\n * ```\n */\n sortComparator?: (a: T, b: T, direction: SortDirection) => number;\n /**\n * The sort direction applied when this column is first activated.\n * Defaults to `\"asc\"`.\n */\n defaultSortDirection?: SortDirection;\n}\n\nexport interface DataTablePersistedState {\n /** column id → user-overridden width in pixels. */\n widths: Record<string, number>;\n /** column id → visibility flag. Missing keys count as visible. */\n visibility: Record<string, boolean>;\n}\n\n/**\n * The controls a row can contain that are actions in their own right. A click\n * or an Enter on one of these is that control's business, not the row's.\n */\nconst INTERACTIVE_DESCENDANT_SELECTOR = [\n \"a\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"label\",\n \"[contenteditable='true']\",\n \"[role='button']\",\n \"[role='link']\",\n \"[tabindex]:not([tabindex='-1'])\",\n].join(\",\");\n\n/**\n * Whether an event inside a clickable row came from a control nested in it.\n *\n * A row that is itself clickable and contains an Edit button has two actions\n * competing for one click. Without this, both fire: the button edits and the\n * row also navigates away from the thing just edited. The row is the fallback,\n * so anything more specific wins.\n */\nfunction fromInteractiveDescendant(\n target: EventTarget | null,\n currentTarget: EventTarget,\n): boolean {\n if (!(target instanceof Element) || !(currentTarget instanceof Element)) {\n return false;\n }\n const control = target.closest(INTERACTIVE_DESCENDANT_SELECTOR);\n return (\n control !== null && control !== currentTarget && currentTarget.contains(control)\n );\n}\n\nexport interface DataTableProps<T> {\n /** Column definitions, in display order. */\n columns: DataTableColumn<T>[];\n /** Row data. */\n rows: T[];\n /**\n * Stable identifier accessor — used as the React key for each row.\n * Must be deterministic for the lifetime of the row.\n */\n getRowKey: (row: T, index: number) => string;\n /** Render this node when `rows` is empty. */\n emptyState?: ReactNode;\n /** Render this node when `loading` is `true`. */\n loadingState?: ReactNode;\n /** When `true`, the loading slot replaces the table body. */\n loading?: boolean;\n /**\n * Column widths and visibility, controlled by the caller.\n *\n * This component used to take a `persistKey` and write to `localStorage`\n * itself. Storage is a policy decision that belongs to the consumer: where\n * it goes, under which key, whether it is per user or per workspace, and\n * whether it exists at all in a host that has no `localStorage`. A\n * rendering component that answers those questions on its own cannot be\n * reused by a consumer that answers them differently.\n */\n columnState?: DataTablePersistedState;\n /**\n * Called whenever the user resizes a column or toggles its visibility.\n * Pair it with `columnState` to persist wherever the consumer keeps\n * preferences; omit both to get a table that forgets on unmount.\n */\n onColumnStateChange?: (state: DataTablePersistedState) => void;\n /** Extra class for the table's wrapping element. */\n className?: string;\n /** ARIA label for the table. Defaults to \"Data table\". */\n ariaLabel?: string;\n /** Test ID for testing harnesses. */\n testId?: string;\n /**\n * Callback invoked when a row is clicked. When provided, rows render\n * with a clickable affordance (cursor: pointer + keyboard binding).\n */\n onRowClick?: (row: T) => void;\n /**\n * Narrows `onRowClick` to the rows that can actually act on it, for a table\n * that mixes actionable and informational rows. A row this returns `false`\n * for gets no pointer affordance, no tab stop, and no keyboard binding, so it\n * is not announced as a button it cannot be.\n */\n isRowClickable?: (row: T, index: number) => boolean;\n /**\n * Extra class for one row, for flagging a specific row without forking the\n * table: a transient deep-link highlight, a stale entry, a row being removed.\n * A falsy return adds nothing.\n */\n rowClassName?: (row: T, index: number) => string | undefined | false | null;\n\n // ---- Sorting props (added epic #2859 / issue #2861) -----------------------\n\n /**\n * Controlled — the column currently being sorted. Pass `undefined` to\n * indicate no active sort. When this prop is present, the component\n * operates in controlled mode: the caller is responsible for updating\n * the sort state via `onSortChange`.\n */\n sortColumnId?: string;\n /**\n * Controlled — the direction of the active sort. Ignored when\n * `sortColumnId` is `undefined`.\n */\n sortDirection?: SortDirection;\n /**\n * Called when the user activates a sortable column header. In\n * controlled mode the caller must propagate this back as\n * `sortColumnId` / `sortDirection`. In uncontrolled mode this prop is\n * purely observational.\n *\n * @param columnId The column being sorted, or `undefined` when the\n * sort is cleared.\n * @param direction The new direction.\n */\n onSortChange?: (\n columnId: string | undefined,\n direction: SortDirection | undefined,\n ) => void;\n}\n\nconst EMPTY_COLUMN_STATE: DataTablePersistedState = { widths: {}, visibility: {} };\n\n// ============================================================================\n// Sorting helpers\n// ============================================================================\n\n/**\n * Stable sort — rows with equal comparison result keep their original\n * relative order. We achieve stability by augmenting each row with its\n * original index and using that as a tie-breaker.\n *\n * The input array is never mutated.\n */\nfunction stableSort<T>(rows: T[], comparator: (a: T, b: T) => number): T[] {\n const indexed = rows.map((row, i) => ({ row, i }));\n indexed.sort((a, b) => {\n const result = comparator(a.row, b.row);\n return result !== 0 ? result : a.i - b.i;\n });\n return indexed.map(({ row }) => row);\n}\n\n/**\n * Builds a comparator from a `DataTableColumn` + active sort direction.\n * Falls back to string comparison when neither `sortComparator` nor\n * `sortValueAccessor` is provided on the column.\n */\nfunction buildComparator<T>(\n col: DataTableColumn<T>,\n direction: SortDirection,\n): (a: T, b: T) => number {\n const { sortComparator } = col;\n if (sortComparator) {\n return (a, b) => sortComparator(a, b, direction);\n }\n const accessor = col.sortValueAccessor;\n if (accessor) {\n return (a, b) => {\n const av = accessor(a);\n const bv = accessor(b);\n // Nullish values sort last regardless of direction.\n if (av == null && bv == null) return 0;\n if (av == null) return 1;\n if (bv == null) return -1;\n let cmp: number;\n if (typeof av === \"number\" && typeof bv === \"number\") {\n cmp = av - bv;\n } else {\n cmp = String(av).localeCompare(String(bv));\n }\n return direction === \"asc\" ? cmp : -cmp;\n };\n }\n // No accessor — unsortable in practice (column should not be sortable).\n return () => 0;\n}\n\n/**\n * Returns the `aria-sort` attribute value for a column header cell.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort\n */\nfunction ariaSortValue(\n col: DataTableColumn<unknown>,\n activeSortColumnId: string | undefined,\n activeSortDirection: SortDirection | undefined,\n): \"ascending\" | \"descending\" | \"none\" | undefined {\n if (!col.sortable) return undefined;\n if (col.id === activeSortColumnId) {\n return activeSortDirection === \"asc\" ? \"ascending\" : \"descending\";\n }\n return \"none\";\n}\n\n// Sort indicator icons rendered as inline SVG so there is no external\n// asset dependency. They intentionally reuse design-token colours so they\n// automatically adapt to light / dark themes.\n\nfunction SortIcon({ direction }: { direction: SortDirection | \"none\" }) {\n if (direction === \"none\") {\n // Neutral chevron stack — both arrows in muted colour\n return (\n <span\n className=\"data-table__sort-icon data-table__sort-icon--none\"\n aria-hidden=\"true\"\n >\n <svg\n width=\"10\"\n height=\"14\"\n viewBox=\"0 0 10 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M5 1L1 5H9L5 1Z\" fill=\"currentColor\" opacity=\"0.35\" />\n <path d=\"M5 13L9 9H1L5 13Z\" fill=\"currentColor\" opacity=\"0.35\" />\n </svg>\n </span>\n );\n }\n if (direction === \"asc\") {\n return (\n <span\n className=\"data-table__sort-icon data-table__sort-icon--asc\"\n aria-hidden=\"true\"\n >\n <svg\n width=\"10\"\n height=\"14\"\n viewBox=\"0 0 10 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M5 1L1 5H9L5 1Z\" fill=\"currentColor\" />\n <path d=\"M5 13L9 9H1L5 13Z\" fill=\"currentColor\" opacity=\"0.25\" />\n </svg>\n </span>\n );\n }\n return (\n <span\n className=\"data-table__sort-icon data-table__sort-icon--desc\"\n aria-hidden=\"true\"\n >\n <svg\n width=\"10\"\n height=\"14\"\n viewBox=\"0 0 10 14\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path d=\"M5 1L1 5H9L5 1Z\" fill=\"currentColor\" opacity=\"0.25\" />\n <path d=\"M5 13L9 9H1L5 13Z\" fill=\"currentColor\" />\n </svg>\n </span>\n );\n}\n\n// ============================================================================\n// Component\n// ============================================================================\n\nfunction DataTableInner<T>({\n columns,\n rows,\n getRowKey,\n emptyState,\n loadingState,\n loading = false,\n columnState,\n onColumnStateChange,\n className = \"\",\n ariaLabel = \"Data table\",\n testId,\n onRowClick,\n isRowClickable,\n rowClassName,\n // Sorting (controlled)\n sortColumnId: controlledSortColumnId,\n sortDirection: controlledSortDirection,\n onSortChange,\n}: DataTableProps<T>) {\n // ---- Column state (widths + visibility) ----------------------------------\n //\n // Held internally so a caller that does not care about persistence gets a\n // working table, and re-seeded whenever the caller supplies a new one.\n const [persisted, setPersisted] = useState<DataTablePersistedState>(\n () => columnState ?? EMPTY_COLUMN_STATE,\n );\n\n useEffect(() => {\n if (columnState) setPersisted(columnState);\n }, [columnState]);\n\n // ---- Sorting state (uncontrolled fallback) -------------------------------\n //\n // Controlled mode is detected by the presence of `sortColumnId` as a prop\n // (the caller explicitly manages the sort column). Using only this prop as\n // the signal (rather than OR-ing with `sortDirection`) avoids a\n // pathological state where `sortDirection` is set but `sortColumnId` is\n // not, which would enter controlled mode with no sort effect.\n //\n // Note: TypeScript cannot distinguish \"prop not passed\" from \"prop passed\n // as undefined\", so we rely on the convention that controlled callers\n // always pass both `sortColumnId` and `sortDirection` together.\n const isControlled =\n controlledSortColumnId !== undefined || controlledSortDirection !== undefined;\n\n const [internalSortColumnId, setInternalSortColumnId] = useState<string | undefined>(\n undefined,\n );\n const [internalSortDirection, setInternalSortDirection] = useState<\n SortDirection | undefined\n >(undefined);\n\n const activeSortColumnId = isControlled\n ? controlledSortColumnId\n : internalSortColumnId;\n const activeSortDirection = isControlled\n ? controlledSortDirection\n : internalSortDirection;\n\n /** Handle a click / keypress on a sortable column header. */\n const handleSortToggle = useCallback(\n (col: DataTableColumn<T>) => {\n if (!col.sortable) return;\n\n let nextColumnId: string | undefined;\n let nextDirection: SortDirection | undefined;\n\n if (activeSortColumnId !== col.id) {\n // Activate this column in its default direction.\n nextColumnId = col.id;\n nextDirection = col.defaultSortDirection ?? \"asc\";\n } else if (activeSortDirection === (col.defaultSortDirection ?? \"asc\")) {\n // Flip to the opposite direction.\n nextColumnId = col.id;\n nextDirection = activeSortDirection === \"asc\" ? \"desc\" : \"asc\";\n } else {\n // Already in the non-default direction — clear the sort.\n nextColumnId = undefined;\n nextDirection = undefined;\n }\n\n if (!isControlled) {\n setInternalSortColumnId(nextColumnId);\n setInternalSortDirection(nextDirection);\n }\n onSortChange?.(nextColumnId, nextDirection);\n },\n [activeSortColumnId, activeSortDirection, isControlled, onSortChange],\n );\n\n // ---- Visibility computation (column always-visible wins) -----------------\n const visibleColumns = useMemo(\n () =>\n columns.filter((col) => {\n if (col.alwaysVisible) return true;\n const flag = persisted.visibility[col.id];\n return flag !== false;\n }),\n [columns, persisted.visibility],\n );\n\n // ---- Width resolution ----------------------------------------------------\n const resolveWidth = useCallback(\n (col: DataTableColumn<T>): number | undefined => {\n const persistedWidth = persisted.widths[col.id];\n const width =\n typeof persistedWidth === \"number\" && persistedWidth > 0\n ? persistedWidth\n : col.initialWidth;\n return width === undefined ? undefined : Math.max(width, col.minWidth ?? 0);\n },\n [persisted.widths],\n );\n\n // ---- Resize handling -----------------------------------------------------\n const resizeRef = useRef<{\n columnId: string;\n startX: number;\n startWidth: number;\n minWidth: number;\n } | null>(null);\n\n const beginResize = useCallback(\n (\n ev: React.MouseEvent<HTMLDivElement>,\n col: DataTableColumn<T>,\n currentWidth: number,\n ) => {\n if (col.noResize) return;\n ev.preventDefault();\n ev.stopPropagation();\n resizeRef.current = {\n columnId: col.id,\n startX: ev.clientX,\n startWidth: currentWidth,\n minWidth: col.minWidth ?? 80,\n };\n\n const onMove = (e: MouseEvent) => {\n const ref = resizeRef.current;\n if (!ref) return;\n const delta = e.clientX - ref.startX;\n const next = Math.max(ref.minWidth, ref.startWidth + delta);\n setPersisted((prev) => ({\n ...prev,\n widths: { ...prev.widths, [ref.columnId]: next },\n }));\n };\n const onUp = () => {\n resizeRef.current = null;\n window.removeEventListener(\"mousemove\", onMove);\n window.removeEventListener(\"mouseup\", onUp);\n };\n window.addEventListener(\"mousemove\", onMove);\n window.addEventListener(\"mouseup\", onUp);\n },\n [],\n );\n\n // Report changes so the caller can persist them. Skipped while `persisted`\n // still holds what the caller last handed in, so echoing the callback back\n // through `columnState` does not loop.\n const reported = useRef(persisted);\n useEffect(() => {\n if (reported.current === persisted) return;\n reported.current = persisted;\n onColumnStateChange?.(persisted);\n }, [persisted, onColumnStateChange]);\n\n // ---- Sorted rows --------------------------------------------------------\n const sortedRows = useMemo(() => {\n if (!activeSortColumnId || !activeSortDirection) return rows;\n const col = columns.find((c) => c.id === activeSortColumnId);\n if (!col?.sortable) return rows;\n return stableSort(rows, buildComparator(col, activeSortDirection));\n }, [rows, columns, activeSortColumnId, activeSortDirection]);\n\n // ---- Body rendering ------------------------------------------------------\n const composedClassName = [\"data-table\", className].filter(Boolean).join(\" \");\n\n const renderBody = () => {\n if (loading) {\n return (\n <tr className=\"data-table__row data-table__row--state\">\n <td colSpan={visibleColumns.length || 1} className=\"data-table__state-cell\">\n {loadingState ?? <div className=\"data-table__loading\" />}\n </td>\n </tr>\n );\n }\n if (sortedRows.length === 0) {\n return (\n <tr className=\"data-table__row data-table__row--state\">\n <td colSpan={visibleColumns.length || 1} className=\"data-table__state-cell\">\n {emptyState}\n </td>\n </tr>\n );\n }\n return sortedRows.map((row, index) => {\n const key = getRowKey(row, index);\n // A row is interactive only if the table has a handler AND this row is\n // not excluded, so the affordance, the tab stop and the role move\n // together. Splitting them would announce a button that does nothing.\n const clickable = Boolean(onRowClick && (isRowClickable?.(row, index) ?? true));\n const extraClass = rowClassName?.(row, index);\n return (\n <tr\n key={key}\n className={[\n \"data-table__row\",\n clickable && \"data-table__row--clickable\",\n extraClass,\n ]\n .filter(Boolean)\n .join(\" \")}\n onClick={\n clickable\n ? (e) => {\n if (fromInteractiveDescendant(e.target, e.currentTarget)) return;\n onRowClick?.(row);\n }\n : undefined\n }\n onKeyDown={\n clickable\n ? (e) => {\n if (e.key !== \"Enter\" && e.key !== \" \") return;\n if (fromInteractiveDescendant(e.target, e.currentTarget)) return;\n e.preventDefault();\n onRowClick?.(row);\n }\n : undefined\n }\n tabIndex={clickable ? 0 : undefined}\n role={clickable ? \"button\" : undefined}\n >\n {visibleColumns.map((col) => (\n <td\n key={col.id}\n className={[\n \"data-table__cell\",\n col.className,\n col.align && `data-table__cell--align-${col.align}`,\n ]\n .filter(Boolean)\n .join(\" \")}\n style={{ minWidth: col.minWidth }}\n >\n {col.render(row, index)}\n </td>\n ))}\n </tr>\n );\n });\n };\n\n return (\n <div className={composedClassName} data-testid={testId}>\n <table className=\"data-table__table\" aria-label={ariaLabel} role=\"table\">\n <thead className=\"data-table__head\">\n <tr className=\"data-table__row data-table__row--head\">\n {visibleColumns.map((col) => {\n const width = resolveWidth(col);\n const isSortActive = col.sortable && col.id === activeSortColumnId;\n\n return (\n <th\n key={col.id}\n scope=\"col\"\n className={[\n \"data-table__cell\",\n \"data-table__cell--head\",\n col.sortable && \"data-table__cell--sortable\",\n isSortActive && \"data-table__cell--sort-active\",\n col.className,\n col.align && `data-table__cell--align-${col.align}`,\n ]\n .filter(Boolean)\n .join(\" \")}\n style={{\n width: width === undefined ? undefined : `${String(width)}px`,\n minWidth: col.minWidth,\n }}\n aria-sort={ariaSortValue(\n col as DataTableColumn<unknown>,\n activeSortColumnId,\n activeSortDirection,\n )}\n onClick={\n col.sortable\n ? () => {\n handleSortToggle(col);\n }\n : undefined\n }\n onKeyDown={\n col.sortable\n ? (e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n e.preventDefault();\n handleSortToggle(col);\n }\n }\n : undefined\n }\n tabIndex={col.sortable ? 0 : undefined}\n >\n <span className=\"data-table__head-label\">{col.header}</span>\n {col.sortable && (\n <SortIcon\n direction={\n isSortActive && activeSortDirection\n ? activeSortDirection\n : \"none\"\n }\n />\n )}\n {!col.noResize && (\n <div\n role=\"separator\"\n aria-orientation=\"vertical\"\n className=\"data-table__resize-handle\"\n onMouseDown={(e) => {\n beginResize(e, col, width ?? col.minWidth ?? 120);\n }}\n />\n )}\n </th>\n );\n })}\n </tr>\n </thead>\n <tbody className=\"data-table__body\">{renderBody()}</tbody>\n </table>\n </div>\n );\n}\n\n// Memoize while preserving the generic signature.\nexport const DataTable = memo(DataTableInner) as typeof DataTableInner;\n\nexport default DataTable;\n"],"mappings":";;;;AAoIA,IAAM,IAAkC;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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AAa,IAAe,GAAK,CAAK;KAC5C,OACE,kBAAC,MAAD;MAEE,WAAW;OACT;OACA,KAAa;OACb;MACF,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;MACX,SACE,KACK,MAAM;OACD,EAA0B,EAAE,QAAQ,EAAE,aAAa,KACvD,IAAa,CAAG;MAClB,IACA,KAAA;MAEN,WACE,KACK,MAAM;OACD,GAAE,QAAQ,WAAW,EAAE,QAAQ,SAC/B,EAA0B,EAAE,QAAQ,EAAE,aAAa,MACvD,EAAE,eAAe,GACjB,IAAa,CAAG;MAClB,IACA,KAAA;MAEN,UAAU,IAAY,IAAI,KAAA;MAC1B,MAAM,IAAY,WAAW,KAAA;MAE5B,UAAA,EAAe,KAAK,MACnB,kBAAC,MAAD;OAEE,WAAW;QACT;QACA,EAAI;QACJ,EAAI,SAAS,2BAA2B,EAAI;OAC9C,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;OACX,OAAO,EAAE,UAAU,EAAI,SAAS;OAE/B,UAAA,EAAI,OAAO,GAAK,CAAK;MACpB,GAXG,EAAI,EAWP,CACL;KACC,GA5CG,CA4CH;IAER,CAAC;GA+E4D,CAAA,CACpD;;CACJ,CAAA;AAET;AAGA,IAAa,IAAY,EAAK,CAAc"}
|
|
@@ -21,5 +21,16 @@ export interface DrawerProps {
|
|
|
21
21
|
ariaDescribedBy?: string;
|
|
22
22
|
/** Accessible label for the close button. Default: "Close" */
|
|
23
23
|
closeLabel?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Refuse dismissal by Escape or a backdrop click, shaking the panel instead.
|
|
26
|
+
* The close button and any footer control still call `onClose` directly, so
|
|
27
|
+
* route those through the same guard when they also need confirming.
|
|
28
|
+
*/
|
|
29
|
+
preventDismiss?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Called when `preventDismiss` blocked a dismissal, so the consumer can offer
|
|
32
|
+
* an explicit way out (a discard confirmation, for instance).
|
|
33
|
+
*/
|
|
34
|
+
onDismissAttempt?: () => void;
|
|
24
35
|
}
|
|
25
|
-
export declare function Drawer({ isOpen, onClose, title, subtitle, width, children, footer, className, ariaLabelledBy, ariaDescribedBy, closeLabel, }: DrawerProps): import("react").JSX.Element;
|
|
36
|
+
export declare function Drawer({ isOpen, onClose, title, subtitle, width, children, footer, className, ariaLabelledBy, ariaDescribedBy, closeLabel, preventDismiss, onDismissAttempt, }: DrawerProps): import("react").JSX.Element;
|