@alepha/ui 0.36.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/$pageAccount.d.ts +1 -1
- package/dist/account/$pageAccount.d.ts.map +1 -1
- package/dist/account/$pageAccount.js.map +1 -1
- package/dist/account/AccountDisplay.d.ts +13 -0
- package/dist/account/AccountDisplay.d.ts.map +1 -0
- package/dist/account/AccountDisplay.js +48 -0
- package/dist/account/AccountDisplay.js.map +1 -0
- package/dist/account/AccountProfile.d.ts.map +1 -1
- package/dist/account/AccountProfile.js +14 -10
- package/dist/account/AccountProfile.js.map +1 -1
- package/dist/account/AccountRouter.d.ts +6 -6
- package/dist/account/AccountRouter.d.ts.map +1 -1
- package/dist/account/index.d.ts +5 -0
- package/dist/account/index.d.ts.map +1 -1
- package/dist/account/index.js +2 -1
- package/dist/admin/$pageAdmin.d.ts +1 -1
- package/dist/admin/$pageAdmin.d.ts.map +1 -1
- package/dist/admin/$pageAdmin.js.map +1 -1
- package/dist/admin/AdminAudits.js.map +1 -1
- package/dist/admin/AdminJobDetail.js.map +1 -1
- package/dist/admin/AdminJobs.js.map +1 -1
- package/dist/admin/AdminNotifications.js.map +1 -1
- package/dist/admin/AdminRouter.d.ts +14 -14
- package/dist/admin/AdminRouter.d.ts.map +1 -1
- package/dist/admin/AdminUserDetail.js.map +1 -1
- package/dist/admin/AdminUsers.js.map +1 -1
- package/dist/admin/ParameterHistoryItem.js.map +1 -1
- package/dist/ai/AiChat.d.ts +26 -39
- package/dist/ai/AiChat.d.ts.map +1 -1
- package/dist/ai/AiChat.js +65 -123
- package/dist/ai/AiChat.js.map +1 -1
- package/dist/ai/AiChatDock.d.ts +23 -0
- package/dist/ai/AiChatDock.d.ts.map +1 -0
- package/dist/ai/AiChatDock.js +90 -0
- package/dist/ai/AiChatDock.js.map +1 -0
- package/dist/ai/AiChatDockSlot.d.ts +15 -0
- package/dist/ai/AiChatDockSlot.d.ts.map +1 -0
- package/dist/ai/AiChatDockSlot.js +20 -0
- package/dist/ai/AiChatDockSlot.js.map +1 -0
- package/dist/ai/AiChatLauncher.d.ts +17 -0
- package/dist/ai/AiChatLauncher.d.ts.map +1 -0
- package/dist/ai/AiChatLauncher.js +42 -0
- package/dist/ai/AiChatLauncher.js.map +1 -0
- package/dist/ai/AiChatMessage.d.ts +7 -1
- package/dist/ai/AiChatMessage.d.ts.map +1 -1
- package/dist/ai/AiChatMessage.js +27 -7
- package/dist/ai/AiChatMessage.js.map +1 -1
- package/dist/ai/AiChatPanel.d.ts +71 -0
- package/dist/ai/AiChatPanel.d.ts.map +1 -0
- package/dist/ai/AiChatPanel.js +143 -0
- package/dist/ai/AiChatPanel.js.map +1 -0
- package/dist/ai/index.d.ts +8 -4
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +5 -1
- package/dist/ai/useAiChat.d.ts +17 -0
- package/dist/ai/useAiChat.d.ts.map +1 -1
- package/dist/ai/useAiChat.js +38 -17
- package/dist/ai/useAiChat.js.map +1 -1
- package/dist/auth/AuthLogin.d.ts +9 -0
- package/dist/auth/AuthLogin.d.ts.map +1 -1
- package/dist/auth/AuthLogin.js +2 -2
- package/dist/auth/AuthLogin.js.map +1 -1
- package/dist/auth/AuthRegister.d.ts +4 -1
- package/dist/auth/AuthRegister.d.ts.map +1 -1
- package/dist/auth/AuthRegister.js +1 -1
- package/dist/auth/AuthRegister.js.map +1 -1
- package/dist/auth/AuthResetPassword.d.ts +8 -0
- package/dist/auth/AuthResetPassword.d.ts.map +1 -1
- package/dist/auth/AuthResetPassword.js +2 -2
- package/dist/auth/AuthResetPassword.js.map +1 -1
- package/dist/auth/AuthRouter.d.ts +4 -4
- package/dist/auth/AuthRouter.d.ts.map +1 -1
- package/dist/core/Badge.d.ts.map +1 -1
- package/dist/core/Badge.js +7 -3
- package/dist/core/Badge.js.map +1 -1
- package/dist/core/Collapsible.d.ts +50 -0
- package/dist/core/Collapsible.d.ts.map +1 -0
- package/dist/core/Collapsible.js +70 -0
- package/dist/core/Collapsible.js.map +1 -0
- package/dist/core/Combobox.d.ts +7 -1
- package/dist/core/Combobox.d.ts.map +1 -1
- package/dist/core/Combobox.js +2 -2
- package/dist/core/Combobox.js.map +1 -1
- package/dist/core/PaneRail.d.ts +24 -7
- package/dist/core/PaneRail.d.ts.map +1 -1
- package/dist/core/PaneRail.js +24 -19
- package/dist/core/PaneRail.js.map +1 -1
- package/dist/core/Stepper.d.ts +36 -0
- package/dist/core/Stepper.d.ts.map +1 -0
- package/dist/core/Stepper.js +54 -0
- package/dist/core/Stepper.js.map +1 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +3 -1
- package/dist/core/useToast.js +13 -13
- package/dist/core/useToast.js.map +1 -1
- package/dist/form/AutoForm.d.ts.map +1 -1
- package/dist/form/AutoForm.js +29 -0
- package/dist/form/AutoForm.js.map +1 -1
- package/dist/form/AutoFormErrorPopover.js +13 -3
- package/dist/form/AutoFormErrorPopover.js.map +1 -1
- package/dist/form/Control.d.ts +14 -1
- package/dist/form/Control.d.ts.map +1 -1
- package/dist/form/Control.js +12 -2
- package/dist/form/Control.js.map +1 -1
- package/dist/form/ControlDate.d.ts.map +1 -1
- package/dist/form/ControlDate.js +3 -0
- package/dist/form/ControlDate.js.map +1 -1
- package/dist/form/ControlDateRange.d.ts +12 -1
- package/dist/form/ControlDateRange.d.ts.map +1 -1
- package/dist/form/ControlDateRange.js +11 -1
- package/dist/form/ControlDateRange.js.map +1 -1
- package/dist/form/ControlNumber.d.ts.map +1 -1
- package/dist/form/ControlNumber.js +2 -0
- package/dist/form/ControlNumber.js.map +1 -1
- package/dist/form/ControlObject.d.ts.map +1 -1
- package/dist/form/ControlObject.js +15 -1
- package/dist/form/ControlObject.js.map +1 -1
- package/dist/form/ControlPassword.d.ts +4 -0
- package/dist/form/ControlPassword.d.ts.map +1 -1
- package/dist/form/ControlPassword.js +1 -0
- package/dist/form/ControlPassword.js.map +1 -1
- package/dist/form/ControlSelect.d.ts +23 -1
- package/dist/form/ControlSelect.d.ts.map +1 -1
- package/dist/form/ControlSelect.js +5 -0
- package/dist/form/ControlSelect.js.map +1 -1
- package/dist/form/ControlSelectCombobox.d.ts +11 -1
- package/dist/form/ControlSelectCombobox.d.ts.map +1 -1
- package/dist/form/ControlSelectCombobox.js +9 -1
- package/dist/form/ControlSelectCombobox.js.map +1 -1
- package/dist/form/ControlUpload.d.ts.map +1 -1
- package/dist/form/ControlUpload.js +1 -0
- package/dist/form/ControlUpload.js.map +1 -1
- package/dist/form/FormField.d.ts +5 -0
- package/dist/form/FormField.d.ts.map +1 -1
- package/dist/form/FormField.js +7 -0
- package/dist/form/FormField.js.map +1 -1
- package/dist/i18n/fr/uiFr.d.ts.map +1 -1
- package/dist/i18n/fr/uiFr.js +15 -0
- package/dist/i18n/fr/uiFr.js.map +1 -1
- package/dist/shell/$pageNav.d.ts +2 -2
- package/dist/shell/$pageNav.d.ts.map +1 -1
- package/dist/shell/$pageNav.js.map +1 -1
- package/dist/shell/AppShell.d.ts +6 -0
- package/dist/shell/AppShell.d.ts.map +1 -1
- package/dist/shell/AppShell.js +31 -27
- package/dist/shell/AppShell.js.map +1 -1
- package/dist/shell/ButtonSettings.d.ts +6 -2
- package/dist/shell/ButtonSettings.d.ts.map +1 -1
- package/dist/shell/ButtonSettings.js +17 -3
- package/dist/shell/ButtonSettings.js.map +1 -1
- package/dist/shell/ButtonSettingsVisionMenuItem.d.ts +16 -0
- package/dist/shell/ButtonSettingsVisionMenuItem.d.ts.map +1 -0
- package/dist/shell/ButtonSettingsVisionMenuItem.js +24 -0
- package/dist/shell/ButtonSettingsVisionMenuItem.js.map +1 -0
- package/dist/shell/ButtonVision.d.ts +28 -0
- package/dist/shell/ButtonVision.d.ts.map +1 -0
- package/dist/shell/ButtonVision.js +46 -0
- package/dist/shell/ButtonVision.js.map +1 -0
- package/dist/shell/index.d.ts +6 -3
- package/dist/shell/index.d.ts.map +1 -1
- package/dist/shell/index.js +2 -1
- package/dist/styles.css +57 -0
- package/dist/table/DataTable.d.ts.map +1 -1
- package/dist/table/DataTable.js +29 -4
- package/dist/table/DataTable.js.map +1 -1
- package/dist/table/DataTableColumnPicker.d.ts.map +1 -1
- package/dist/table/DataTableColumnPicker.js +1 -0
- package/dist/table/DataTableColumnPicker.js.map +1 -1
- package/dist/table/DataTableFilterBar.d.ts +1 -1
- package/dist/table/DataTableFilterBar.d.ts.map +1 -1
- package/dist/table/DataTableFilterBar.js +5 -108
- package/dist/table/DataTableFilterBar.js.map +1 -1
- package/dist/table/DataTableHeaderFilter.d.ts +51 -0
- package/dist/table/DataTableHeaderFilter.d.ts.map +1 -0
- package/dist/table/DataTableHeaderFilter.js +113 -0
- package/dist/table/DataTableHeaderFilter.js.map +1 -0
- package/dist/table/DataTableHeaderRow.d.ts +7 -0
- package/dist/table/DataTableHeaderRow.d.ts.map +1 -1
- package/dist/table/DataTableHeaderRow.js +92 -74
- package/dist/table/DataTableHeaderRow.js.map +1 -1
- package/dist/table/DataTableTabs.d.ts +42 -0
- package/dist/table/DataTableTabs.d.ts.map +1 -0
- package/dist/table/DataTableTabs.js +55 -0
- package/dist/table/DataTableTabs.js.map +1 -0
- package/dist/table/dataTableBaseProps.d.ts +12 -0
- package/dist/table/dataTableBaseProps.d.ts.map +1 -1
- package/dist/table/dataTablePersistence.d.ts.map +1 -1
- package/dist/table/dataTablePersistence.js +4 -2
- package/dist/table/dataTablePersistence.js.map +1 -1
- package/dist/table/dataTableTypes.d.ts +18 -0
- package/dist/table/dataTableTypes.d.ts.map +1 -1
- package/dist/table/index.d.ts +5 -2
- package/dist/table/index.d.ts.map +1 -1
- package/dist/table/index.js +2 -1
- package/dist/table/useDataTableColumns.d.ts.map +1 -1
- package/dist/table/useDataTableColumns.js +1 -0
- package/dist/table/useDataTableColumns.js.map +1 -1
- package/dist/table/useDataTableFilterModel.d.ts +110 -0
- package/dist/table/useDataTableFilterModel.d.ts.map +1 -0
- package/dist/table/useDataTableFilterModel.js +154 -0
- package/dist/table/useDataTableFilterModel.js.map +1 -0
- package/docs/packages-alepha-ui-account.md +4 -0
- package/docs/packages-alepha-ui-ai.md +5 -5
- package/docs/packages-alepha-ui-shell.md +4 -3
- package/docs/packages-alepha-ui-table.md +4 -2
- package/package.json +8 -8
- package/src/account/$pageAccount.tsx +5 -4
- package/src/account/AccountDisplay.tsx +58 -0
- package/src/account/AccountProfile.tsx +30 -42
- package/src/account/__tests__/AccountProfile.browser.spec.tsx +141 -0
- package/src/account/__tests__/AccountRecoveryCodes.browser.spec.tsx +1 -1
- package/src/account/index.ts +5 -0
- package/src/admin/$pageAdmin.tsx +5 -4
- package/src/admin/AdminAudits.tsx +1 -1
- package/src/admin/AdminJobDetail.tsx +1 -1
- package/src/admin/AdminJobs.tsx +1 -1
- package/src/admin/AdminNotifications.tsx +1 -1
- package/src/admin/AdminUserDetail.tsx +1 -1
- package/src/admin/AdminUsers.tsx +1 -1
- package/src/admin/ParameterHistoryItem.tsx +1 -1
- package/src/admin/__tests__/AdminFilesUsageCard.browser.spec.tsx +17 -9
- package/src/ai/AiChat.tsx +94 -183
- package/src/ai/AiChatDock.tsx +129 -0
- package/src/ai/AiChatDockSlot.tsx +23 -0
- package/src/ai/AiChatLauncher.tsx +58 -0
- package/src/ai/AiChatMessage.tsx +48 -9
- package/src/ai/AiChatPanel.tsx +252 -0
- package/src/ai/__tests__/AiChat.browser.spec.tsx +197 -5
- package/src/ai/index.ts +8 -4
- package/src/ai/useAiChat.ts +80 -14
- package/src/auth/AuthLogin.tsx +19 -4
- package/src/auth/AuthRegister.tsx +6 -3
- package/src/auth/AuthResetPassword.tsx +18 -8
- package/src/auth/__tests__/AuthCancel.browser.spec.tsx +129 -0
- package/src/core/Badge.tsx +7 -3
- package/src/core/Collapsible.tsx +95 -0
- package/src/core/Combobox.tsx +11 -3
- package/src/core/PaneRail.tsx +36 -20
- package/src/core/Stepper.tsx +118 -0
- package/src/core/__tests__/Badge.browser.spec.tsx +5 -5
- package/src/core/__tests__/Collapsible.browser.spec.tsx +88 -0
- package/src/core/__tests__/PaneRail.browser.spec.tsx +48 -0
- package/src/core/__tests__/Stepper.browser.spec.tsx +39 -0
- package/src/core/__tests__/primitiveSlots.spec.ts +7 -0
- package/src/core/index.ts +15 -0
- package/src/form/AutoForm.tsx +32 -0
- package/src/form/AutoFormErrorPopover.tsx +27 -6
- package/src/form/Control.tsx +22 -0
- package/src/form/ControlDate.tsx +3 -0
- package/src/form/ControlDateRange.tsx +87 -58
- package/src/form/ControlNumber.tsx +2 -0
- package/src/form/ControlObject.tsx +20 -1
- package/src/form/ControlPassword.tsx +5 -0
- package/src/form/ControlSelect.tsx +32 -1
- package/src/form/ControlSelectCombobox.tsx +82 -56
- package/src/form/ControlUpload.tsx +1 -0
- package/src/form/FormField.tsx +23 -1
- package/src/form/__tests__/ControlFieldErrors.browser.spec.tsx +253 -0
- package/src/form/__tests__/ControlValidateMode.browser.spec.tsx +217 -0
- package/src/form/__tests__/ControlVariantErrors.browser.spec.tsx +133 -0
- package/src/i18n/fr/uiFr.ts +19 -1
- package/src/markdown/css.d.ts +11 -0
- package/src/shell/$pageNav.tsx +6 -4
- package/src/shell/AppShell.tsx +7 -0
- package/src/shell/ButtonSettings.tsx +20 -5
- package/src/shell/ButtonSettingsVisionMenuItem.tsx +40 -0
- package/src/shell/ButtonVision.tsx +73 -0
- package/src/shell/__tests__/ButtonSettings.browser.spec.tsx +42 -2
- package/src/shell/__tests__/ButtonVision.browser.spec.tsx +73 -0
- package/src/shell/__tests__/visionTokens.spec.ts +104 -0
- package/src/shell/index.ts +6 -3
- package/src/styles.css +57 -0
- package/src/table/DataTable.tsx +52 -4
- package/src/table/DataTableColumnPicker.tsx +3 -0
- package/src/table/DataTableFilterBar.tsx +18 -191
- package/src/table/DataTableHeaderFilter.tsx +156 -0
- package/src/table/DataTableHeaderRow.tsx +78 -40
- package/src/table/DataTableTabs.tsx +114 -0
- package/src/table/__tests__/DataTableHeaderFilter.browser.spec.tsx +174 -0
- package/src/table/__tests__/DataTableStaleColumns.browser.spec.tsx +80 -0
- package/src/table/__tests__/DataTableTabs.browser.spec.tsx +72 -0
- package/src/table/dataTableBaseProps.ts +12 -0
- package/src/table/dataTablePersistence.ts +11 -5
- package/src/table/dataTableTypes.ts +18 -0
- package/src/table/index.ts +9 -2
- package/src/table/useDataTableColumns.ts +1 -0
- package/src/table/useDataTableFilterModel.tsx +240 -0
package/dist/table/DataTable.js
CHANGED
|
@@ -5,11 +5,14 @@ import { cn } from "../core/utils.js";
|
|
|
5
5
|
import { DataTableBody } from "./DataTableBody.js";
|
|
6
6
|
import { DataTableBulkBar } from "./DataTableBulkBar.js";
|
|
7
7
|
import { DATA_TABLE_CELL_PADDING } from "./dataTableCellPadding.js";
|
|
8
|
+
import { dataTableFilterBarFields } from "./dataTableFilterFields.js";
|
|
8
9
|
import { DataTableFooter, PAGE_SIZES } from "./DataTableFooter.js";
|
|
10
|
+
import { DataTableHeaderFilter } from "./DataTableHeaderFilter.js";
|
|
9
11
|
import { DataTableHeaderRow } from "./DataTableHeaderRow.js";
|
|
10
12
|
import { persistedColumns, persistedOrder, persistedSize, persistedSort } from "./dataTablePersistence.js";
|
|
11
13
|
import { DATA_TABLE_SQUARE_RIGHT } from "./dataTableSquareRight.js";
|
|
12
14
|
import { DataTableSummaryPanel } from "./DataTableSummaryPanel.js";
|
|
15
|
+
import { DataTableTabs } from "./DataTableTabs.js";
|
|
13
16
|
import { DataTableToolbar } from "./DataTableToolbar.js";
|
|
14
17
|
import { cleanFilterValues } from "./queryFilters.js";
|
|
15
18
|
import { useDataTableColumns } from "./useDataTableColumns.js";
|
|
@@ -83,6 +86,21 @@ const DataTable = (props) => {
|
|
|
83
86
|
definition: filterDefinition,
|
|
84
87
|
filtersKey
|
|
85
88
|
});
|
|
89
|
+
const headerFilters = {};
|
|
90
|
+
if (untyped.filters && !untyped.filters.render && filterDefinition) for (const field of dataTableFilterBarFields(untyped.filters.fields, filterDefinition)) {
|
|
91
|
+
if (!field.column || field.hidden) continue;
|
|
92
|
+
if (!(field.column in headerFilters)) headerFilters[field.column] = field;
|
|
93
|
+
}
|
|
94
|
+
const headerFilter = (columnKey) => {
|
|
95
|
+
const field = headerFilters[columnKey];
|
|
96
|
+
if (!field || !form) return void 0;
|
|
97
|
+
return /* @__PURE__ */ jsx(DataTableHeaderFilter, {
|
|
98
|
+
form,
|
|
99
|
+
field,
|
|
100
|
+
shown: filterVisibility.shown,
|
|
101
|
+
onShownChange: filterVisibility.setShown
|
|
102
|
+
});
|
|
103
|
+
};
|
|
86
104
|
const { page, setPage, sizeForm, sort, setSort, data: serverData, meta, rowFilters, loading, loadedRequestId, lastRequestId, isStatic, refreshKey, setRefreshKey, isRefreshing, setIsRefreshing, toggleSort, setSortTo } = useDataTableData({
|
|
87
105
|
props: untyped,
|
|
88
106
|
size,
|
|
@@ -277,6 +295,8 @@ const DataTable = (props) => {
|
|
|
277
295
|
const flatRows = props.flat && "rounded-none border-x-0 border-t-0 border-b-0";
|
|
278
296
|
const flatBottom = props.flat && "rounded-none border-x-0 border-b-0";
|
|
279
297
|
const showFooter = !(props.pagination === false && Boolean(props.data)) && ((props.pageSizes ?? PAGE_SIZES).length > 0 || Boolean(meta?.totalPages && meta.totalPages > 1));
|
|
298
|
+
const showTabs = Boolean(props.tabs?.length);
|
|
299
|
+
const underTabs = showTabs && "-mt-2 rounded-t-none border-t-0";
|
|
280
300
|
const showColumnPicker = !props.hideColumnPicker && allColumnKeys.length > 0;
|
|
281
301
|
const showActionsMenu = !props.hideActionsMenu;
|
|
282
302
|
return /* @__PURE__ */ jsx(ClientOnly, { children: /* @__PURE__ */ jsxs("div", {
|
|
@@ -289,6 +309,10 @@ const DataTable = (props) => {
|
|
|
289
309
|
children: props.header
|
|
290
310
|
})
|
|
291
311
|
}),
|
|
312
|
+
showTabs && /* @__PURE__ */ jsx(DataTableTabs, {
|
|
313
|
+
tabs: props.tabs,
|
|
314
|
+
className: cn(squareRight?.top, flatTop, props.chromeClassName)
|
|
315
|
+
}),
|
|
292
316
|
showSummary && /* @__PURE__ */ jsx(DataTableSummaryPanel, {
|
|
293
317
|
title: props.summary?.title ?? tr("dataTable.summary", { default: "Summary" }),
|
|
294
318
|
open: summary.open,
|
|
@@ -296,7 +320,7 @@ const DataTable = (props) => {
|
|
|
296
320
|
cards: summary.cards,
|
|
297
321
|
loading: summary.loading,
|
|
298
322
|
content: hasSummaryContent ? summaryContent : void 0,
|
|
299
|
-
className: cn(squareRight?.top, flatTop, props.chromeClassName)
|
|
323
|
+
className: cn(showTabs ? underTabs : squareRight?.top, flatTop, props.chromeClassName)
|
|
300
324
|
}),
|
|
301
325
|
showToolbar && /* @__PURE__ */ jsx(DataTableToolbar, {
|
|
302
326
|
columns: props.columns,
|
|
@@ -323,7 +347,7 @@ const DataTable = (props) => {
|
|
|
323
347
|
reorderColumn,
|
|
324
348
|
isRefreshing,
|
|
325
349
|
handleRefreshClick,
|
|
326
|
-
className: cn(showSummary ? "-mt-2 rounded-t-none border-t-0" : squareRight?.top, flatTop, props.chromeClassName)
|
|
350
|
+
className: cn(showSummary || showTabs ? "-mt-2 rounded-t-none border-t-0" : squareRight?.top, flatTop, props.chromeClassName)
|
|
327
351
|
}),
|
|
328
352
|
hasCheckbox && selection.size > 0 && visibleBulkActions.length > 0 && /* @__PURE__ */ jsx(DataTableBulkBar, {
|
|
329
353
|
selection,
|
|
@@ -333,7 +357,7 @@ const DataTable = (props) => {
|
|
|
333
357
|
clearSelection
|
|
334
358
|
}),
|
|
335
359
|
/* @__PURE__ */ jsx("div", {
|
|
336
|
-
className: cn("flex min-h-0 flex-1 flex-col overflow-auto rounded-md border", (showToolbar || showSummary) && "-mt-2 rounded-t-none border-t-0", showFooter ? "rounded-b-none border-b-0" : squareRight?.bottom, flatRows, !showToolbar && !showSummary && squareRight?.top, "[&>[data-slot=table-container]]:grow"),
|
|
360
|
+
className: cn("flex min-h-0 flex-1 flex-col overflow-auto rounded-md border", (showToolbar || showSummary || showTabs) && "-mt-2 rounded-t-none border-t-0", showFooter ? "rounded-b-none border-b-0" : squareRight?.bottom, flatRows, !showToolbar && !showSummary && !showTabs && squareRight?.top, "[&>[data-slot=table-container]]:grow"),
|
|
337
361
|
children: /* @__PURE__ */ jsxs(Table, {
|
|
338
362
|
className: cn(isEmptyState && "h-full"),
|
|
339
363
|
children: [/* @__PURE__ */ jsx(TableHeader, {
|
|
@@ -350,7 +374,8 @@ const DataTable = (props) => {
|
|
|
350
374
|
toggleSort,
|
|
351
375
|
setSortTo,
|
|
352
376
|
moveColumn,
|
|
353
|
-
toggleColumn
|
|
377
|
+
toggleColumn,
|
|
378
|
+
headerFilter
|
|
354
379
|
})
|
|
355
380
|
}), /* @__PURE__ */ jsx(DataTableBody, {
|
|
356
381
|
cellClassName: cellPadding.cell,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTable.js","names":[],"sources":["../../src/table/DataTable.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { ClientOnly, useAlepha } from \"alepha/react\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\nimport { Table, TableHeader } from \"../core/Table.tsx\";\nimport { useIsMobile } from \"../core/useIsMobile.ts\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { cn } from \"../core/utils.ts\";\nimport type { DataTableBaseProps } from \"./dataTableBaseProps.ts\";\nimport { DataTableBody } from \"./DataTableBody.tsx\";\nimport { DataTableBulkBar } from \"./DataTableBulkBar.tsx\";\nimport { DATA_TABLE_CELL_PADDING } from \"./dataTableCellPadding.ts\";\nimport { DataTableFooter, PAGE_SIZES } from \"./DataTableFooter.tsx\";\nimport { DataTableHeaderRow } from \"./DataTableHeaderRow.tsx\";\nimport {\n persistedColumns,\n persistedOrder,\n persistedSize,\n persistedSort,\n} from \"./dataTablePersistence.ts\";\nimport { DATA_TABLE_SQUARE_RIGHT } from \"./dataTableSquareRight.ts\";\nimport { DataTableSummaryPanel } from \"./DataTableSummaryPanel.tsx\";\nimport { DataTableToolbar } from \"./DataTableToolbar.tsx\";\nimport type {\n DataTableCellContext,\n DataTableFilterFields,\n DataTableNoFilterFields,\n DataTableSource,\n BulkActionContext,\n ColumnDef,\n RowActionContext,\n} from \"./dataTableTypes.ts\";\nimport { cleanFilterValues } from \"./queryFilters.ts\";\nimport { useDataTableColumns } from \"./useDataTableColumns.ts\";\nimport { useDataTableData } from \"./useDataTableData.ts\";\nimport { useDataTableFilterForm } from \"./useDataTableFilterForm.ts\";\nimport { useDataTableFilterVisibility } from \"./useDataTableFilterVisibility.ts\";\nimport { useDataTableRefresh } from \"./useDataTableRefresh.ts\";\nimport { useDataTableSummary } from \"./useDataTableSummary.ts\";\nimport { useOptimisticRows } from \"./useOptimisticRows.ts\";\nimport { useTableSelection } from \"./useTableSelection.ts\";\n\nexport type DataTableProps<\n T,\n F extends DataTableFilterFields = DataTableNoFilterFields,\n> = DataTableBaseProps<T, F> & DataTableSource<T, F>;\n\n/**\n * A data table: server-side or static rows, sorting, filters, row and bulk\n * actions, persisted preferences.\n *\n * `T` is the row. `F` is the type of `filters.fields`, written as\n * `typeof filterFields` beside the row type, which is what types `fetch`'s\n * filters, the `data` predicate, `initialValues`, `seedValues` and\n * `fromQuery`. It defaults to no filters at all, so a table given `fields`\n * without it does not compile.\n */\nexport const DataTable = <\n T,\n const F extends DataTableFilterFields = DataTableNoFilterFields,\n>(\n props: DataTableProps<T, F>,\n) => {\n /**\n * The props, with their filters read untyped. The parts below enumerate\n * filter keys at runtime and never read one by name, so the type of `F` is\n * the call site's business and one cast here keeps it out of every hook.\n */\n const untyped = props as unknown as DataTableProps<T, DataTableFilterFields>;\n\n /**\n * `persistenceKey`, once per facet.\n *\n * A facet that is off gets `undefined`, which is the same value every\n * persistence helper here already treats as \"do not store\" - so turning one\n * off takes the branch a table with no key has always taken, rather than a\n * new one. That is what keeps the default behaviour of `persistenceKey`\n * exactly as it was: with `persist` absent, all three of these ARE\n * `props.persistenceKey`.\n *\n * Primitives, so they go straight into the dependency arrays and `useState`\n * initializers below without giving any of them a new identity per render.\n */\n const filtersKey =\n props.persist?.filters === false ? undefined : props.persistenceKey;\n const columnsKey =\n props.persist?.columns === false ? undefined : props.persistenceKey;\n const sortKey =\n props.persist?.sort === false ? undefined : props.persistenceKey;\n // `pageSizes={[]}` hides the picker, and with it the reader's say in the\n // size: a size stored while the picker was still there must not outlive\n // it, or a reader who once chose 50 is stuck at 50 with no control left to\n // change it. The call site's `defaultSize` is the size, full stop.\n const sizeKey =\n props.pageSizes?.length === 0 ? undefined : props.persistenceKey;\n\n // State, not a constant. It was `props.defaultSize ?? 20` read once, so a\n // reader had no way to see more rows than the call site had decided for\n // them. Already in `load`'s dependency array, so changing it refetches.\n const [size, setSize] = useState<number>(() =>\n persistedSize(sizeKey, props.defaultSize),\n );\n const alepha = useAlepha();\n const { tr } = useI18n();\n const toast = useToast();\n /**\n * The whole of the phone layout, and deliberately one switch rather than a\n * scattering of `max-md:` classes: the filter controls have to be rendered\n * in exactly ONE of the two places (see `DataTableFilterDialog`), which\n * CSS cannot express. Everything else below the breakpoint follows the same\n * flag so the two halves of the layout cannot disagree.\n *\n * Safe against hydration because the whole table sits inside `ClientOnly`,\n * and `useIsMobile` reads the same `MediaQueryList` it subscribes to.\n */\n const isMobile = useIsMobile();\n\n const { form, definition: filterDefinition } = useDataTableFilterForm({\n props: untyped,\n filtersKey,\n alepha,\n });\n\n const filterVisibility = useDataTableFilterVisibility({\n definition: filterDefinition,\n filtersKey,\n });\n\n const {\n page,\n setPage,\n sizeForm,\n sort,\n setSort,\n data: serverData,\n meta,\n rowFilters,\n loading,\n loadedRequestId,\n lastRequestId,\n isStatic,\n refreshKey,\n setRefreshKey,\n isRefreshing,\n setIsRefreshing,\n toggleSort,\n setSortTo,\n } = useDataTableData({\n props: untyped,\n size,\n setSize,\n sortKey,\n form,\n alepha,\n });\n\n const {\n refresh,\n reload,\n handleRefreshClick,\n resetFilters,\n canShare,\n shareFilters,\n } = useDataTableRefresh({\n props: untyped,\n form,\n filterKeys: filterDefinition?.keys ?? [],\n resetShownFilters: filterVisibility.resetShown,\n filtersKey,\n alepha,\n toast,\n tr,\n setPage,\n setRefreshKey,\n setIsRefreshing,\n });\n\n const summary = useDataTableSummary({\n summary: untyped.summary,\n persistenceKey: props.persistenceKey,\n refreshKey,\n form,\n alepha,\n });\n\n // -- Row identity ----------------------------------------------------------\n\n /**\n * A row's key, in order of preference: the caller's `rowKey`, the row's own\n * `id`, then where the row sits.\n *\n * The last one used to be `Math.random()`, which is not an identity at all.\n * Every render produced a new key, so React saw every id-less row as a new\n * row and remounted it: focus in an inline input was lost the moment\n * anything else re-rendered, and the list re-animated on every keystroke.\n * Selection was broken by the same thing - `selection.has(rowKey(item))`\n * compared against a key generated one render earlier, so it never matched.\n */\n /**\n * A row's key from the row alone, so a row redrawn by an optimistic patch\n * (a new object) keeps the key of the one it replaces.\n */\n const keyOf = useCallback(\n (item: T, index: number): string => {\n if (props.rowKey) return props.rowKey(item);\n const id = (item as { id?: unknown })?.id;\n // Coercion at a boundary: the value is a form/route/chart primitive\n // whose declared type is wider than what can reach here.\n // oxlint-disable-next-line typescript/no-base-to-string -- a coercion at a boundary, see the comment above\n return id != null ? String(id) : `page-${page}-row-${index}`;\n },\n [page, props.rowKey],\n );\n\n const serverRowKeys = useMemo(\n () => serverData.map((item, index) => keyOf(item, index)),\n [serverData, keyOf],\n );\n\n // -- Optimistic overlay ----------------------------------------------------\n\n const serverKeyByItem = useMemo(() => {\n const map = new Map<T, string>();\n serverData.forEach((item, index) => map.set(item, serverRowKeys[index]));\n return map;\n }, [serverData, serverRowKeys]);\n\n const overlayKey = useCallback(\n (item: T) => serverKeyByItem.get(item) ?? keyOf(item, -1),\n [serverKeyByItem, keyOf],\n );\n\n const overlay = useOptimisticRows<T>({\n data: serverData,\n rowKeys: serverRowKeys,\n rowKey: overlayKey,\n loadedRequestId,\n lastRequestId,\n reload,\n isStatic,\n });\n const data = overlay.data;\n const rowKeys = overlay.rowKeys;\n\n /**\n * Selection asks for a key by item, not by index. Every item it can ask\n * about is one of `data`'s, so a lookup keyed on identity covers it without\n * an O(n) scan per call.\n */\n const rowKeyByItem = useMemo(() => {\n const map = new Map<T, string>();\n data.forEach((item, index) => map.set(item, rowKeys[index]));\n return map;\n }, [data, rowKeys]);\n\n const rowKey = useCallback(\n (item: T): string => rowKeyByItem.get(item) ?? \"\",\n [rowKeyByItem],\n );\n\n // -- Selection -------------------------------------------------------------\n\n const {\n selection,\n selectedItems,\n allSelected,\n someSelected,\n toggleRow,\n toggleAll,\n clearSelection,\n } = useTableSelection(data, rowKey);\n\n // The bulk actions offered for THIS selection: an action's `visible`\n // predicate reads the selected rows. Computed once, here, so the pill's\n // contents and the pill's own presence come from the same list.\n const visibleBulkActions = useMemo(\n () =>\n (props.bulkActions ?? []).filter(\n (action) => action.visible?.(selectedItems) ?? true,\n ),\n [props.bulkActions, selectedItems],\n );\n\n const {\n allColumnKeys,\n visibleColumns,\n setVisibleColumns,\n orderedKeys,\n setColumnOrder,\n moveColumn,\n reorderColumn,\n toggleColumn,\n orderAnnouncement,\n } = useDataTableColumns({ props: untyped, columnsKey, tr });\n\n /**\n * ⚠️ A changed `persistenceKey` is a changed SCOPE, and this is where that\n * is handled.\n *\n * Every caller encodes its scope in that key - `lor.activity.${project.id}`,\n * `lor.epics.${project.id}` - so switching project changes it. Nothing acted\n * on that before, and `load` re-runs only on `[page, size, sortParam,\n * refreshKey, form, alepha]`, none of which a project switch touches. The\n * router does not remount on a param-only navigation either, so the table\n * kept serving the PREVIOUS project's rows under the new project's name\n * (feedback #2096).\n *\n * `refreshKey` is bumped rather than relying on the re-read: two projects\n * can share a stored sort and size, and then no dependency of `load` would\n * change and nothing would refetch. That equality is the bug's whole\n * mechanism, so the refetch cannot be a side effect of the values moving.\n *\n * ⚠️ Adjusted during RENDER, not in an effect, and that is load-bearing.\n * The sort effect (`useDataTableData`) and the column writes\n * (`useDataTableColumns`) are keyed on `persistenceKey` too, so on the\n * render where it changes they would fire in the same flush and write the\n * OUTGOING scope's state under the INCOMING key - silently\n * overwriting the project you just opened with the one you just left. React\n * re-renders before committing this, so by the time those effects run the\n * state is already the new scope's and they write back what was just read.\n *\n * ⚠️ `props.fetch` is still NOT a dependency of `load`. That is the loop\n * `fetchRef` exists to prevent, and several callers write a store atom from\n * inside their fetcher.\n *\n * Filter VALUES are deliberately not reset here: `useForm` captures its\n * `initialValues` once, so resetting them is form surgery rather than a\n * state assignment. They are also not clobbered - the filter-persist effect\n * writes only on `form:changed` / `form:submit:success`, never on mount - so\n * the stored filters of the project you left stay its own.\n */\n const scopeRef = useRef(props.persistenceKey);\n if (scopeRef.current !== props.persistenceKey) {\n scopeRef.current = props.persistenceKey;\n setPage(0);\n setSize(persistedSize(sizeKey, props.defaultSize));\n setSort(persistedSort(sortKey, props.defaultSort));\n setVisibleColumns(persistedColumns(columnsKey, props.columns));\n // Same render pass as the rest, and for the identical reason: the effects\n // keyed on `persistenceKey` fire in one flush, so an order left behind\n // here would be written back under the INCOMING key.\n setColumnOrder(persistedOrder(columnsKey, props.columns));\n // Which filters are on the bar is the scope's too, and read here for the\n // same reason: the project just opened must not show the bar of the one\n // just left.\n filterVisibility.rereadShown(filtersKey);\n // The panel's open state is the scope's like the size is, and its cards\n // are the scope's figures: they go now, and the bump below refetches.\n summary.resetScope(props.persistenceKey);\n setRefreshKey((k) => k + 1);\n }\n\n // -- Render ---------------------------------------------------------------\n\n // The reader's order, not the declaration's.\n const cols = orderedKeys.map((key) => [key, props.columns[key]!]) as Array<\n [string, ColumnDef<T>]\n >;\n const visibleCols = cols.filter(([key]) => visibleColumns.has(key));\n const hasCheckbox = Boolean(props.bulkActions?.length);\n const hasRowActions = Boolean(props.rowActions);\n\n const rowCtx: RowActionContext<T> = useMemo(\n () => ({ refresh, reload, clearSelection, optimistic: overlay.optimistic }),\n [refresh, reload, clearSelection, overlay.optimistic],\n );\n const bulkCtx: BulkActionContext<T> = useMemo(\n () => ({ refresh, reload, clearSelection, optimistic: overlay.optimistic }),\n [refresh, reload, clearSelection, overlay.optimistic],\n );\n\n /**\n * How many filters currently narrow the list — a count rather than the\n * boolean this used to be, because on a phone the bar is behind a button\n * and the trigger's badge is the only thing that says the table is\n * filtered at all.\n */\n const activeFilterCount = useMemo(() => {\n if (!props.filters || !form) return 0;\n return Object.keys(cleanFilterValues(form.currentValues ?? {})).length;\n }, [props.filters, form, refreshKey]);\n const hasActiveFilters = activeFilterCount > 0;\n\n // What every cell is told beside its row: the search the rows on screen\n // answer, from the first `preset: \"search\"` field holding one.\n const searchKey = Object.entries(props.filters?.fields ?? {}).find(\n ([, field]) => field.preset === \"search\",\n )?.[0];\n const rowSearch = searchKey ? rowFilters?.[searchKey] : undefined;\n const cellContext: DataTableCellContext = {\n search:\n typeof rowSearch === \"string\" && rowSearch.trim() !== \"\"\n ? rowSearch.trim()\n : undefined,\n };\n /**\n * Whether Reset filters would change anything: a value set, or a bar that\n * is not the one the table declares. Not the count alone, or a reader who\n * removed a default filter would have no way to bring it back.\n */\n const canResetFilters =\n hasActiveFilters || filterVisibility.differsFromDeclaration;\n\n // The empty state is showing, as opposed to the skeleton that also renders\n // on `data.length === 0`. Read by the `<Table>` height as well as the body,\n // so the two cannot disagree.\n const isEmptyState = !loading && data.length === 0;\n\n // A node that draws nothing is no help and no content: the `?` and the\n // band would open on an empty card. Decided here, once, and handed down\n // as `undefined` when it is empty.\n const hasHelp =\n props.help != null && props.help !== false && props.help !== \"\";\n const showToolbar =\n Boolean(props.filters) ||\n Boolean(props.leading) ||\n Boolean(props.toolbar) ||\n Boolean(props.actions?.length) ||\n hasHelp ||\n !props.hideColumnPicker ||\n !props.hideActionsMenu;\n // Drawn while a first fetch is out (its placeholders), and after that only\n // with something in it: a summary with no card and no content is no band.\n // A function is called on every render, which only builds its element: the\n // panel mounts it while open, and the counter is what tells it to reload.\n const rawSummaryContent = props.summary?.content;\n const summaryContent =\n typeof rawSummaryContent === \"function\"\n ? rawSummaryContent({ refreshKey })\n : rawSummaryContent;\n const hasSummaryContent =\n summaryContent != null && summaryContent !== false && summaryContent !== \"\";\n const showSummary =\n Boolean(props.summary) &&\n (summary.cards === undefined ||\n summary.cards.length > 0 ||\n hasSummaryContent);\n const cellPadding = DATA_TABLE_CELL_PADDING[props.cellPadding ?? \"normal\"];\n const squareRight = props.squareRight\n ? DATA_TABLE_SQUARE_RIGHT[`${props.squareRight}`]\n : undefined;\n // `flat` drops the outer frame and keeps the lines between the bands: the\n // toolbar keeps its bottom border, the footer its top one, and the rows\n // lose the sides. Applied after `squareRight`, which has nothing left to\n // square once the corners are gone.\n const flatTop = props.flat && \"rounded-none border-x-0 border-t-0\";\n const flatRows =\n props.flat && \"rounded-none border-x-0 border-t-0 border-b-0\";\n const flatBottom = props.flat && \"rounded-none border-x-0 border-b-0\";\n // The footer holds two controls, the size picker and the page links, and\n // the count beside them. A table that hid the picker (`pageSizes={[]}`)\n // and fits on one page has neither, and \"Page 1 of 1\" alone is a bar\n // saying nothing, so it goes. The links' condition is the footer's own.\n // `pagination={false}` holds for static rows only: a fetched table is\n // paged by the server, and hiding its pager would hide rows.\n const unpaged = props.pagination === false && Boolean(props.data);\n const showFooter =\n !unpaged &&\n ((props.pageSizes ?? PAGE_SIZES).length > 0 ||\n Boolean(meta?.totalPages && meta.totalPages > 1));\n const showColumnPicker = !props.hideColumnPicker && allColumnKeys.length > 0;\n const showActionsMenu = !props.hideActionsMenu;\n\n return (\n <ClientOnly>\n <div className={cn(\"flex flex-col gap-2\", props.className)}>\n {props.header && (\n <div className=\"flex items-center gap-2\">\n <div className=\"min-w-0 flex-1\">{props.header}</div>\n </div>\n )}\n\n {/*\n The summary opens the frame when it is there, so it takes the top\n corners `squareRight` squares, and whatever follows it (the filter\n bar, or the rows when there is none) joins under it the way the rows\n join the filter bar: flattened top, no top border, `-mt-2` against\n the wrapper's gap. The panel's own bottom border is the line\n between them.\n */}\n {showSummary && (\n <DataTableSummaryPanel\n title={\n props.summary?.title ??\n tr(\"dataTable.summary\", { default: \"Summary\" })\n }\n open={summary.open}\n onOpenChange={summary.setOpen}\n cards={summary.cards}\n loading={summary.loading}\n content={hasSummaryContent ? summaryContent : undefined}\n className={cn(squareRight?.top, flatTop, props.chromeClassName)}\n />\n )}\n\n {showToolbar && (\n <DataTableToolbar<T>\n columns={props.columns}\n filters={untyped.filters}\n form={form}\n filterDefinition={filterDefinition}\n shownFilters={filterVisibility.shown}\n onShownFiltersChange={filterVisibility.setShown}\n canResetFilters={canResetFilters}\n leading={props.leading}\n toolbar={props.toolbar}\n actions={props.actions}\n help={hasHelp ? props.help : undefined}\n isMobile={isMobile}\n showColumnPicker={showColumnPicker}\n showActionsMenu={showActionsMenu}\n activeFilterCount={activeFilterCount}\n canShare={canShare}\n resetFilters={resetFilters}\n shareFilters={shareFilters}\n orderedKeys={orderedKeys}\n visibleColumns={visibleColumns}\n toggleColumn={toggleColumn}\n reorderColumn={reorderColumn}\n isRefreshing={isRefreshing}\n handleRefreshClick={handleRefreshClick}\n className={cn(\n showSummary\n ? \"-mt-2 rounded-t-none border-t-0\"\n : squareRight?.top,\n flatTop,\n props.chromeClassName,\n )}\n />\n )}\n\n {hasCheckbox && selection.size > 0 && visibleBulkActions.length > 0 && (\n <DataTableBulkBar<T>\n selection={selection}\n selectedItems={selectedItems}\n visibleBulkActions={visibleBulkActions}\n bulkCtx={bulkCtx}\n clearSelection={clearSelection}\n />\n )}\n\n {/*\n The toolbar, the rows and the footer are one panel: each facing edge\n is flattened and its border dropped so no double line appears, and\n `-mt-2` cancels the wrapper's `gap-2`. The footer half follows\n `showFooter`, which is true for every table that keeps its size\n picker: gating the footer on `meta` alone would pop the bar in and\n flip this bottom border on every load, since `meta` starts null and\n only fills after the fetch. Only a table that hid the picker can\n lose it, and then the rows close the panel themselves.\n */}\n <div\n className={cn(\n \"flex min-h-0 flex-1 flex-col overflow-auto rounded-md border\",\n (showToolbar || showSummary) && \"-mt-2 rounded-t-none border-t-0\",\n showFooter ? \"rounded-b-none border-b-0\" : squareRight?.bottom,\n flatRows,\n // With no toolbar and no summary the rows open the table, so\n // their top-right corner is the one `squareRight` squares.\n !showToolbar && !showSummary && squareRight?.top,\n // `<Table>` wraps the table in a container div whose classes it\n // hardcodes, and only this table needs that container to grow,\n // so the one class it needs is set from out here instead.\n //\n // `grow`, NOT `flex-1`: `flex-1` sets the basis to 0, and in the\n // ordinary case this wrapper has no height of its own, so a 0\n // basis with nothing to grow into collapses the table to nothing.\n // `grow` keeps the content basis and only spends space that is\n // actually free, which is the full-height case.\n \"[&>[data-slot=table-container]]:grow\",\n )}\n >\n {/* `h-full` ONLY while the empty state is what is in the body.\n It is what lets that one row take the height the scroller grew\n into, so `align-middle` can centre the state in it.\n\n ⚠️ Never unconditionally. A CSS table given a height larger\n than its content does not leave the surplus at the bottom, it\n DISTRIBUTES IT ACROSS THE ROWS - so an unconditional `h-full`\n silently turns a short table into a tall one: Lore's Apps page,\n two rows in a full-height pane, rendered them 239px each. No\n unit test sees it (jsdom computes no layout) and it is invisible\n on a table long enough to fill its own container, which is why\n it reached e2e rather than review. */}\n <Table className={cn(isEmptyState && \"h-full\")}>\n {/* `bg-muted`, fully opaque, NOT the base header's `bg-muted/50`:\n this header is sticky, so anything translucent lets the rows\n scroll visibly through the column labels. Same tint, no\n transparency.\n\n Two inset lines, not one. The bottom is the divider against the\n first row; the top is the `--bevel` highlight, which is what\n gives the band its thickness. Inset shadows rather than borders\n because a border on a sticky `<thead>` is dropped by the\n collapsed table border model, and because the two lines have to\n sit INSIDE the header's own height: it is pinned at `top-0`\n against a scrolling body, so anything painted outside it is\n painted over. */}\n <TableHeader\n className={cn(\n // ⚠️ `[&_tr]:border-b-0` or the bottom rule is drawn TWICE: `TableHeader`\n // gives its rows a `border-b`, and the inset shadow above draws\n // the same line, so the band closed with 2px where it opens with\n // 1px. The inset one wins because it is what survives the sticky\n // header being painted over.\n \"bg-muted sticky top-0 z-10 shadow-[inset_0_1px_0_0_var(--bevel),inset_0_-1px_0_0_var(--border)] [&_tr]:border-b-0\",\n props.chromeClassName,\n )}\n >\n <DataTableHeaderRow<T>\n headClassName={cellPadding.head}\n visibleCols={visibleCols}\n hasCheckbox={hasCheckbox}\n hasRowActions={hasRowActions}\n allSelected={allSelected}\n someSelected={someSelected}\n toggleAll={toggleAll}\n sort={sort}\n toggleSort={toggleSort}\n setSortTo={setSortTo}\n moveColumn={moveColumn}\n toggleColumn={toggleColumn}\n />\n </TableHeader>\n <DataTableBody<T>\n cellClassName={cellPadding.cell}\n data={data}\n cellContext={cellContext}\n rowKeys={rowKeys}\n leaving={overlay.leaving}\n flash={overlay.flash}\n loading={loading}\n visibleCols={visibleCols}\n hasCheckbox={hasCheckbox}\n hasRowActions={hasRowActions}\n hasActiveFilters={hasActiveFilters}\n selection={selection}\n toggleRow={toggleRow}\n rowCtx={rowCtx}\n rowActions={props.rowActions}\n rowActionsDisplay={props.rowActionsDisplay}\n striped={props.striped}\n onRowClick={props.onRowClick}\n onRowHover={props.onRowHover}\n empty={props.empty}\n emptyMessage={props.emptyMessage}\n emptyState={props.emptyState}\n noMatchState={props.noMatchState}\n />\n </Table>\n </div>\n\n {/* A move is otherwise silent: nothing about a reordered table is\n spoken, and the visual change is the only feedback. Outside the\n table so it is not read as a cell. */}\n <span aria-live=\"polite\" className=\"sr-only\">\n {orderAnnouncement}\n </span>\n\n {showFooter && (\n <DataTableFooter\n pageSizes={props.pageSizes}\n sizeForm={sizeForm}\n meta={meta}\n isMobile={isMobile}\n setPage={setPage}\n className={cn(\n squareRight?.bottom,\n flatBottom,\n props.chromeClassName,\n )}\n />\n )}\n </div>\n </ClientOnly>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAa,aAIX,UACG;;;;;;CAMH,MAAM,UAAU;;;;;;;;;;;;;;CAehB,MAAM,aACJ,MAAM,SAAS,YAAY,QAAQ,KAAA,IAAY,MAAM;CACvD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,MAAM;MACf,YAAY,MAAM;MAClB,YAAY,MAAM;MAClB,OAAO,MAAM;MACb,cAAc,MAAM;MACpB,YAAY,MAAM;MAClB,cAAc,MAAM;KACrB,CAAA,CACI;;GACJ,CAAA;GAKL,oBAAC,QAAD;IAAM,aAAU;IAAS,WAAU;IAChC,UAAA;GACG,CAAA;GAEL,cACC,oBAAC,iBAAD;IACE,WAAW,MAAM;IACP;IACJ;IACI;IACD;IACT,WAAW,GACT,aAAa,QACb,YACA,MAAM,eACR;GACD,CAAA;EAEA;CACK,CAAA,EAAA,CAAA;AAEhB"}
|
|
1
|
+
{"version":3,"file":"DataTable.js","names":[],"sources":["../../src/table/DataTable.tsx"],"sourcesContent":["import * as React from \"react\";\n\nvoid React;\n\nimport { ClientOnly, useAlepha } from \"alepha/react\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\nimport { Table, TableHeader } from \"../core/Table.tsx\";\nimport { useIsMobile } from \"../core/useIsMobile.ts\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { cn } from \"../core/utils.ts\";\nimport type { DataTableBaseProps } from \"./dataTableBaseProps.ts\";\nimport { DataTableBody } from \"./DataTableBody.tsx\";\nimport { DataTableBulkBar } from \"./DataTableBulkBar.tsx\";\nimport { DATA_TABLE_CELL_PADDING } from \"./dataTableCellPadding.ts\";\nimport type { DataTableFilterBarField } from \"./DataTableFilterBar.tsx\";\nimport { dataTableFilterBarFields } from \"./dataTableFilterFields.ts\";\nimport { DataTableFooter, PAGE_SIZES } from \"./DataTableFooter.tsx\";\nimport { DataTableHeaderFilter } from \"./DataTableHeaderFilter.tsx\";\nimport { DataTableHeaderRow } from \"./DataTableHeaderRow.tsx\";\nimport {\n persistedColumns,\n persistedOrder,\n persistedSize,\n persistedSort,\n} from \"./dataTablePersistence.ts\";\nimport { DATA_TABLE_SQUARE_RIGHT } from \"./dataTableSquareRight.ts\";\nimport { DataTableSummaryPanel } from \"./DataTableSummaryPanel.tsx\";\nimport { DataTableTabs } from \"./DataTableTabs.tsx\";\nimport { DataTableToolbar } from \"./DataTableToolbar.tsx\";\nimport type {\n DataTableCellContext,\n DataTableFilterFields,\n DataTableNoFilterFields,\n DataTableSource,\n BulkActionContext,\n ColumnDef,\n RowActionContext,\n} from \"./dataTableTypes.ts\";\nimport { cleanFilterValues } from \"./queryFilters.ts\";\nimport { useDataTableColumns } from \"./useDataTableColumns.ts\";\nimport { useDataTableData } from \"./useDataTableData.ts\";\nimport { useDataTableFilterForm } from \"./useDataTableFilterForm.ts\";\nimport { useDataTableFilterVisibility } from \"./useDataTableFilterVisibility.ts\";\nimport { useDataTableRefresh } from \"./useDataTableRefresh.ts\";\nimport { useDataTableSummary } from \"./useDataTableSummary.ts\";\nimport { useOptimisticRows } from \"./useOptimisticRows.ts\";\nimport { useTableSelection } from \"./useTableSelection.ts\";\n\nexport type DataTableProps<\n T,\n F extends DataTableFilterFields = DataTableNoFilterFields,\n> = DataTableBaseProps<T, F> & DataTableSource<T, F>;\n\n/**\n * A data table: server-side or static rows, sorting, filters, row and bulk\n * actions, persisted preferences.\n *\n * `T` is the row. `F` is the type of `filters.fields`, written as\n * `typeof filterFields` beside the row type, which is what types `fetch`'s\n * filters, the `data` predicate, `initialValues`, `seedValues` and\n * `fromQuery`. It defaults to no filters at all, so a table given `fields`\n * without it does not compile.\n */\nexport const DataTable = <\n T,\n const F extends DataTableFilterFields = DataTableNoFilterFields,\n>(\n props: DataTableProps<T, F>,\n) => {\n /**\n * The props, with their filters read untyped. The parts below enumerate\n * filter keys at runtime and never read one by name, so the type of `F` is\n * the call site's business and one cast here keeps it out of every hook.\n */\n const untyped = props as unknown as DataTableProps<T, DataTableFilterFields>;\n\n /**\n * `persistenceKey`, once per facet.\n *\n * A facet that is off gets `undefined`, which is the same value every\n * persistence helper here already treats as \"do not store\" - so turning one\n * off takes the branch a table with no key has always taken, rather than a\n * new one. That is what keeps the default behaviour of `persistenceKey`\n * exactly as it was: with `persist` absent, all three of these ARE\n * `props.persistenceKey`.\n *\n * Primitives, so they go straight into the dependency arrays and `useState`\n * initializers below without giving any of them a new identity per render.\n */\n const filtersKey =\n props.persist?.filters === false ? undefined : props.persistenceKey;\n const columnsKey =\n props.persist?.columns === false ? undefined : props.persistenceKey;\n const sortKey =\n props.persist?.sort === false ? undefined : props.persistenceKey;\n // `pageSizes={[]}` hides the picker, and with it the reader's say in the\n // size: a size stored while the picker was still there must not outlive\n // it, or a reader who once chose 50 is stuck at 50 with no control left to\n // change it. The call site's `defaultSize` is the size, full stop.\n const sizeKey =\n props.pageSizes?.length === 0 ? undefined : props.persistenceKey;\n\n // State, not a constant. It was `props.defaultSize ?? 20` read once, so a\n // reader had no way to see more rows than the call site had decided for\n // them. Already in `load`'s dependency array, so changing it refetches.\n const [size, setSize] = useState<number>(() =>\n persistedSize(sizeKey, props.defaultSize),\n );\n const alepha = useAlepha();\n const { tr } = useI18n();\n const toast = useToast();\n /**\n * The whole of the phone layout, and deliberately one switch rather than a\n * scattering of `max-md:` classes: the filter controls have to be rendered\n * in exactly ONE of the two places (see `DataTableFilterDialog`), which\n * CSS cannot express. Everything else below the breakpoint follows the same\n * flag so the two halves of the layout cannot disagree.\n *\n * Safe against hydration because the whole table sits inside `ClientOnly`,\n * and `useIsMobile` reads the same `MediaQueryList` it subscribes to.\n */\n const isMobile = useIsMobile();\n\n const { form, definition: filterDefinition } = useDataTableFilterForm({\n props: untyped,\n filtersKey,\n alepha,\n });\n\n const filterVisibility = useDataTableFilterVisibility({\n definition: filterDefinition,\n filtersKey,\n });\n\n // The filters that sit in a column's header, by column: the first field\n // naming a column wins it. Only for the bar the table draws itself - a\n // caller's `filters.render` owns where its filters go, and the bar's rule\n // that a set filter shows on it is what makes a header filter safe.\n const headerFilters: Record<string, DataTableFilterBarField> = {};\n if (untyped.filters && !untyped.filters.render && filterDefinition) {\n for (const field of dataTableFilterBarFields(\n untyped.filters.fields,\n filterDefinition,\n )) {\n if (!field.column || field.hidden) continue;\n if (!(field.column in headerFilters)) headerFilters[field.column] = field;\n }\n }\n const headerFilter = (columnKey: string) => {\n const field = headerFilters[columnKey];\n if (!field || !form) return undefined;\n return (\n <DataTableHeaderFilter\n form={form}\n field={field}\n shown={filterVisibility.shown}\n onShownChange={filterVisibility.setShown}\n />\n );\n };\n\n const {\n page,\n setPage,\n sizeForm,\n sort,\n setSort,\n data: serverData,\n meta,\n rowFilters,\n loading,\n loadedRequestId,\n lastRequestId,\n isStatic,\n refreshKey,\n setRefreshKey,\n isRefreshing,\n setIsRefreshing,\n toggleSort,\n setSortTo,\n } = useDataTableData({\n props: untyped,\n size,\n setSize,\n sortKey,\n form,\n alepha,\n });\n\n const {\n refresh,\n reload,\n handleRefreshClick,\n resetFilters,\n canShare,\n shareFilters,\n } = useDataTableRefresh({\n props: untyped,\n form,\n filterKeys: filterDefinition?.keys ?? [],\n resetShownFilters: filterVisibility.resetShown,\n filtersKey,\n alepha,\n toast,\n tr,\n setPage,\n setRefreshKey,\n setIsRefreshing,\n });\n\n const summary = useDataTableSummary({\n summary: untyped.summary,\n persistenceKey: props.persistenceKey,\n refreshKey,\n form,\n alepha,\n });\n\n // -- Row identity ----------------------------------------------------------\n\n /**\n * A row's key, in order of preference: the caller's `rowKey`, the row's own\n * `id`, then where the row sits.\n *\n * The last one used to be `Math.random()`, which is not an identity at all.\n * Every render produced a new key, so React saw every id-less row as a new\n * row and remounted it: focus in an inline input was lost the moment\n * anything else re-rendered, and the list re-animated on every keystroke.\n * Selection was broken by the same thing - `selection.has(rowKey(item))`\n * compared against a key generated one render earlier, so it never matched.\n */\n /**\n * A row's key from the row alone, so a row redrawn by an optimistic patch\n * (a new object) keeps the key of the one it replaces.\n */\n const keyOf = useCallback(\n (item: T, index: number): string => {\n if (props.rowKey) return props.rowKey(item);\n const id = (item as { id?: unknown })?.id;\n // Coercion at a boundary: the value is a form/route/chart primitive\n // whose declared type is wider than what can reach here.\n // oxlint-disable-next-line typescript/no-base-to-string -- a coercion at a boundary, see the comment above\n return id != null ? String(id) : `page-${page}-row-${index}`;\n },\n [page, props.rowKey],\n );\n\n const serverRowKeys = useMemo(\n () => serverData.map((item, index) => keyOf(item, index)),\n [serverData, keyOf],\n );\n\n // -- Optimistic overlay ----------------------------------------------------\n\n const serverKeyByItem = useMemo(() => {\n const map = new Map<T, string>();\n serverData.forEach((item, index) => map.set(item, serverRowKeys[index]));\n return map;\n }, [serverData, serverRowKeys]);\n\n const overlayKey = useCallback(\n (item: T) => serverKeyByItem.get(item) ?? keyOf(item, -1),\n [serverKeyByItem, keyOf],\n );\n\n const overlay = useOptimisticRows<T>({\n data: serverData,\n rowKeys: serverRowKeys,\n rowKey: overlayKey,\n loadedRequestId,\n lastRequestId,\n reload,\n isStatic,\n });\n const data = overlay.data;\n const rowKeys = overlay.rowKeys;\n\n /**\n * Selection asks for a key by item, not by index. Every item it can ask\n * about is one of `data`'s, so a lookup keyed on identity covers it without\n * an O(n) scan per call.\n */\n const rowKeyByItem = useMemo(() => {\n const map = new Map<T, string>();\n data.forEach((item, index) => map.set(item, rowKeys[index]));\n return map;\n }, [data, rowKeys]);\n\n const rowKey = useCallback(\n (item: T): string => rowKeyByItem.get(item) ?? \"\",\n [rowKeyByItem],\n );\n\n // -- Selection -------------------------------------------------------------\n\n const {\n selection,\n selectedItems,\n allSelected,\n someSelected,\n toggleRow,\n toggleAll,\n clearSelection,\n } = useTableSelection(data, rowKey);\n\n // The bulk actions offered for THIS selection: an action's `visible`\n // predicate reads the selected rows. Computed once, here, so the pill's\n // contents and the pill's own presence come from the same list.\n const visibleBulkActions = useMemo(\n () =>\n (props.bulkActions ?? []).filter(\n (action) => action.visible?.(selectedItems) ?? true,\n ),\n [props.bulkActions, selectedItems],\n );\n\n const {\n allColumnKeys,\n visibleColumns,\n setVisibleColumns,\n orderedKeys,\n setColumnOrder,\n moveColumn,\n reorderColumn,\n toggleColumn,\n orderAnnouncement,\n } = useDataTableColumns({ props: untyped, columnsKey, tr });\n\n /**\n * ⚠️ A changed `persistenceKey` is a changed SCOPE, and this is where that\n * is handled.\n *\n * Every caller encodes its scope in that key - `lor.activity.${project.id}`,\n * `lor.epics.${project.id}` - so switching project changes it. Nothing acted\n * on that before, and `load` re-runs only on `[page, size, sortParam,\n * refreshKey, form, alepha]`, none of which a project switch touches. The\n * router does not remount on a param-only navigation either, so the table\n * kept serving the PREVIOUS project's rows under the new project's name\n * (feedback #2096).\n *\n * `refreshKey` is bumped rather than relying on the re-read: two projects\n * can share a stored sort and size, and then no dependency of `load` would\n * change and nothing would refetch. That equality is the bug's whole\n * mechanism, so the refetch cannot be a side effect of the values moving.\n *\n * ⚠️ Adjusted during RENDER, not in an effect, and that is load-bearing.\n * The sort effect (`useDataTableData`) and the column writes\n * (`useDataTableColumns`) are keyed on `persistenceKey` too, so on the\n * render where it changes they would fire in the same flush and write the\n * OUTGOING scope's state under the INCOMING key - silently\n * overwriting the project you just opened with the one you just left. React\n * re-renders before committing this, so by the time those effects run the\n * state is already the new scope's and they write back what was just read.\n *\n * ⚠️ `props.fetch` is still NOT a dependency of `load`. That is the loop\n * `fetchRef` exists to prevent, and several callers write a store atom from\n * inside their fetcher.\n *\n * Filter VALUES are deliberately not reset here: `useForm` captures its\n * `initialValues` once, so resetting them is form surgery rather than a\n * state assignment. They are also not clobbered - the filter-persist effect\n * writes only on `form:changed` / `form:submit:success`, never on mount - so\n * the stored filters of the project you left stay its own.\n */\n const scopeRef = useRef(props.persistenceKey);\n if (scopeRef.current !== props.persistenceKey) {\n scopeRef.current = props.persistenceKey;\n setPage(0);\n setSize(persistedSize(sizeKey, props.defaultSize));\n setSort(persistedSort(sortKey, props.defaultSort));\n setVisibleColumns(persistedColumns(columnsKey, props.columns));\n // Same render pass as the rest, and for the identical reason: the effects\n // keyed on `persistenceKey` fire in one flush, so an order left behind\n // here would be written back under the INCOMING key.\n setColumnOrder(persistedOrder(columnsKey, props.columns));\n // Which filters are on the bar is the scope's too, and read here for the\n // same reason: the project just opened must not show the bar of the one\n // just left.\n filterVisibility.rereadShown(filtersKey);\n // The panel's open state is the scope's like the size is, and its cards\n // are the scope's figures: they go now, and the bump below refetches.\n summary.resetScope(props.persistenceKey);\n setRefreshKey((k) => k + 1);\n }\n\n // -- Render ---------------------------------------------------------------\n\n // The reader's order, not the declaration's.\n const cols = orderedKeys.map((key) => [key, props.columns[key]!]) as Array<\n [string, ColumnDef<T>]\n >;\n const visibleCols = cols.filter(([key]) => visibleColumns.has(key));\n const hasCheckbox = Boolean(props.bulkActions?.length);\n const hasRowActions = Boolean(props.rowActions);\n\n const rowCtx: RowActionContext<T> = useMemo(\n () => ({ refresh, reload, clearSelection, optimistic: overlay.optimistic }),\n [refresh, reload, clearSelection, overlay.optimistic],\n );\n const bulkCtx: BulkActionContext<T> = useMemo(\n () => ({ refresh, reload, clearSelection, optimistic: overlay.optimistic }),\n [refresh, reload, clearSelection, overlay.optimistic],\n );\n\n /**\n * How many filters currently narrow the list — a count rather than the\n * boolean this used to be, because on a phone the bar is behind a button\n * and the trigger's badge is the only thing that says the table is\n * filtered at all.\n */\n const activeFilterCount = useMemo(() => {\n if (!props.filters || !form) return 0;\n return Object.keys(cleanFilterValues(form.currentValues ?? {})).length;\n }, [props.filters, form, refreshKey]);\n const hasActiveFilters = activeFilterCount > 0;\n\n // What every cell is told beside its row: the search the rows on screen\n // answer, from the first `preset: \"search\"` field holding one.\n const searchKey = Object.entries(props.filters?.fields ?? {}).find(\n ([, field]) => field.preset === \"search\",\n )?.[0];\n const rowSearch = searchKey ? rowFilters?.[searchKey] : undefined;\n const cellContext: DataTableCellContext = {\n search:\n typeof rowSearch === \"string\" && rowSearch.trim() !== \"\"\n ? rowSearch.trim()\n : undefined,\n };\n /**\n * Whether Reset filters would change anything: a value set, or a bar that\n * is not the one the table declares. Not the count alone, or a reader who\n * removed a default filter would have no way to bring it back.\n */\n const canResetFilters =\n hasActiveFilters || filterVisibility.differsFromDeclaration;\n\n // The empty state is showing, as opposed to the skeleton that also renders\n // on `data.length === 0`. Read by the `<Table>` height as well as the body,\n // so the two cannot disagree.\n const isEmptyState = !loading && data.length === 0;\n\n // A node that draws nothing is no help and no content: the `?` and the\n // band would open on an empty card. Decided here, once, and handed down\n // as `undefined` when it is empty.\n const hasHelp =\n props.help != null && props.help !== false && props.help !== \"\";\n const showToolbar =\n Boolean(props.filters) ||\n Boolean(props.leading) ||\n Boolean(props.toolbar) ||\n Boolean(props.actions?.length) ||\n hasHelp ||\n !props.hideColumnPicker ||\n !props.hideActionsMenu;\n // Drawn while a first fetch is out (its placeholders), and after that only\n // with something in it: a summary with no card and no content is no band.\n // A function is called on every render, which only builds its element: the\n // panel mounts it while open, and the counter is what tells it to reload.\n const rawSummaryContent = props.summary?.content;\n const summaryContent =\n typeof rawSummaryContent === \"function\"\n ? rawSummaryContent({ refreshKey })\n : rawSummaryContent;\n const hasSummaryContent =\n summaryContent != null && summaryContent !== false && summaryContent !== \"\";\n const showSummary =\n Boolean(props.summary) &&\n (summary.cards === undefined ||\n summary.cards.length > 0 ||\n hasSummaryContent);\n const cellPadding = DATA_TABLE_CELL_PADDING[props.cellPadding ?? \"normal\"];\n const squareRight = props.squareRight\n ? DATA_TABLE_SQUARE_RIGHT[`${props.squareRight}`]\n : undefined;\n // `flat` drops the outer frame and keeps the lines between the bands: the\n // toolbar keeps its bottom border, the footer its top one, and the rows\n // lose the sides. Applied after `squareRight`, which has nothing left to\n // square once the corners are gone.\n const flatTop = props.flat && \"rounded-none border-x-0 border-t-0\";\n const flatRows =\n props.flat && \"rounded-none border-x-0 border-t-0 border-b-0\";\n const flatBottom = props.flat && \"rounded-none border-x-0 border-b-0\";\n // The footer holds two controls, the size picker and the page links, and\n // the count beside them. A table that hid the picker (`pageSizes={[]}`)\n // and fits on one page has neither, and \"Page 1 of 1\" alone is a bar\n // saying nothing, so it goes. The links' condition is the footer's own.\n // `pagination={false}` holds for static rows only: a fetched table is\n // paged by the server, and hiding its pager would hide rows.\n const unpaged = props.pagination === false && Boolean(props.data);\n const showFooter =\n !unpaged &&\n ((props.pageSizes ?? PAGE_SIZES).length > 0 ||\n Boolean(meta?.totalPages && meta.totalPages > 1));\n const showTabs = Boolean(props.tabs?.length);\n // The classes of the band that joins under the tabs: flattened top, no top\n // border, `-mt-2` against the wrapper's gap, as below the summary.\n const underTabs = showTabs && \"-mt-2 rounded-t-none border-t-0\";\n const showColumnPicker = !props.hideColumnPicker && allColumnKeys.length > 0;\n const showActionsMenu = !props.hideActionsMenu;\n\n return (\n <ClientOnly>\n <div className={cn(\"flex flex-col gap-2\", props.className)}>\n {props.header && (\n <div className=\"flex items-center gap-2\">\n <div className=\"min-w-0 flex-1\">{props.header}</div>\n </div>\n )}\n\n {/*\n The summary opens the frame when it is there, so it takes the top\n corners `squareRight` squares, and whatever follows it (the filter\n bar, or the rows when there is none) joins under it the way the rows\n join the filter bar: flattened top, no top border, `-mt-2` against\n the wrapper's gap. The panel's own bottom border is the line\n between them.\n */}\n {showTabs && (\n <DataTableTabs\n tabs={props.tabs!}\n className={cn(squareRight?.top, flatTop, props.chromeClassName)}\n />\n )}\n\n {showSummary && (\n <DataTableSummaryPanel\n title={\n props.summary?.title ??\n tr(\"dataTable.summary\", { default: \"Summary\" })\n }\n open={summary.open}\n onOpenChange={summary.setOpen}\n cards={summary.cards}\n loading={summary.loading}\n content={hasSummaryContent ? summaryContent : undefined}\n className={cn(\n showTabs ? underTabs : squareRight?.top,\n flatTop,\n props.chromeClassName,\n )}\n />\n )}\n\n {showToolbar && (\n <DataTableToolbar<T>\n columns={props.columns}\n filters={untyped.filters}\n form={form}\n filterDefinition={filterDefinition}\n shownFilters={filterVisibility.shown}\n onShownFiltersChange={filterVisibility.setShown}\n canResetFilters={canResetFilters}\n leading={props.leading}\n toolbar={props.toolbar}\n actions={props.actions}\n help={hasHelp ? props.help : undefined}\n isMobile={isMobile}\n showColumnPicker={showColumnPicker}\n showActionsMenu={showActionsMenu}\n activeFilterCount={activeFilterCount}\n canShare={canShare}\n resetFilters={resetFilters}\n shareFilters={shareFilters}\n orderedKeys={orderedKeys}\n visibleColumns={visibleColumns}\n toggleColumn={toggleColumn}\n reorderColumn={reorderColumn}\n isRefreshing={isRefreshing}\n handleRefreshClick={handleRefreshClick}\n className={cn(\n showSummary || showTabs\n ? \"-mt-2 rounded-t-none border-t-0\"\n : squareRight?.top,\n flatTop,\n props.chromeClassName,\n )}\n />\n )}\n\n {hasCheckbox && selection.size > 0 && visibleBulkActions.length > 0 && (\n <DataTableBulkBar<T>\n selection={selection}\n selectedItems={selectedItems}\n visibleBulkActions={visibleBulkActions}\n bulkCtx={bulkCtx}\n clearSelection={clearSelection}\n />\n )}\n\n {/*\n The toolbar, the rows and the footer are one panel: each facing edge\n is flattened and its border dropped so no double line appears, and\n `-mt-2` cancels the wrapper's `gap-2`. The footer half follows\n `showFooter`, which is true for every table that keeps its size\n picker: gating the footer on `meta` alone would pop the bar in and\n flip this bottom border on every load, since `meta` starts null and\n only fills after the fetch. Only a table that hid the picker can\n lose it, and then the rows close the panel themselves.\n */}\n <div\n className={cn(\n \"flex min-h-0 flex-1 flex-col overflow-auto rounded-md border\",\n (showToolbar || showSummary || showTabs) &&\n \"-mt-2 rounded-t-none border-t-0\",\n showFooter ? \"rounded-b-none border-b-0\" : squareRight?.bottom,\n flatRows,\n // With no toolbar and no summary the rows open the table, so\n // their top-right corner is the one `squareRight` squares.\n !showToolbar && !showSummary && !showTabs && squareRight?.top,\n // `<Table>` wraps the table in a container div whose classes it\n // hardcodes, and only this table needs that container to grow,\n // so the one class it needs is set from out here instead.\n //\n // `grow`, NOT `flex-1`: `flex-1` sets the basis to 0, and in the\n // ordinary case this wrapper has no height of its own, so a 0\n // basis with nothing to grow into collapses the table to nothing.\n // `grow` keeps the content basis and only spends space that is\n // actually free, which is the full-height case.\n \"[&>[data-slot=table-container]]:grow\",\n )}\n >\n {/* `h-full` ONLY while the empty state is what is in the body.\n It is what lets that one row take the height the scroller grew\n into, so `align-middle` can centre the state in it.\n\n ⚠️ Never unconditionally. A CSS table given a height larger\n than its content does not leave the surplus at the bottom, it\n DISTRIBUTES IT ACROSS THE ROWS - so an unconditional `h-full`\n silently turns a short table into a tall one: Lore's Apps page,\n two rows in a full-height pane, rendered them 239px each. No\n unit test sees it (jsdom computes no layout) and it is invisible\n on a table long enough to fill its own container, which is why\n it reached e2e rather than review. */}\n <Table className={cn(isEmptyState && \"h-full\")}>\n {/* `bg-muted`, fully opaque, NOT the base header's `bg-muted/50`:\n this header is sticky, so anything translucent lets the rows\n scroll visibly through the column labels. Same tint, no\n transparency.\n\n Two inset lines, not one. The bottom is the divider against the\n first row; the top is the `--bevel` highlight, which is what\n gives the band its thickness. Inset shadows rather than borders\n because a border on a sticky `<thead>` is dropped by the\n collapsed table border model, and because the two lines have to\n sit INSIDE the header's own height: it is pinned at `top-0`\n against a scrolling body, so anything painted outside it is\n painted over. */}\n <TableHeader\n className={cn(\n // ⚠️ `[&_tr]:border-b-0` or the bottom rule is drawn TWICE: `TableHeader`\n // gives its rows a `border-b`, and the inset shadow above draws\n // the same line, so the band closed with 2px where it opens with\n // 1px. The inset one wins because it is what survives the sticky\n // header being painted over.\n \"bg-muted sticky top-0 z-10 shadow-[inset_0_1px_0_0_var(--bevel),inset_0_-1px_0_0_var(--border)] [&_tr]:border-b-0\",\n props.chromeClassName,\n )}\n >\n <DataTableHeaderRow<T>\n headClassName={cellPadding.head}\n visibleCols={visibleCols}\n hasCheckbox={hasCheckbox}\n hasRowActions={hasRowActions}\n allSelected={allSelected}\n someSelected={someSelected}\n toggleAll={toggleAll}\n sort={sort}\n toggleSort={toggleSort}\n setSortTo={setSortTo}\n moveColumn={moveColumn}\n toggleColumn={toggleColumn}\n headerFilter={headerFilter}\n />\n </TableHeader>\n <DataTableBody<T>\n cellClassName={cellPadding.cell}\n data={data}\n cellContext={cellContext}\n rowKeys={rowKeys}\n leaving={overlay.leaving}\n flash={overlay.flash}\n loading={loading}\n visibleCols={visibleCols}\n hasCheckbox={hasCheckbox}\n hasRowActions={hasRowActions}\n hasActiveFilters={hasActiveFilters}\n selection={selection}\n toggleRow={toggleRow}\n rowCtx={rowCtx}\n rowActions={props.rowActions}\n rowActionsDisplay={props.rowActionsDisplay}\n striped={props.striped}\n onRowClick={props.onRowClick}\n onRowHover={props.onRowHover}\n empty={props.empty}\n emptyMessage={props.emptyMessage}\n emptyState={props.emptyState}\n noMatchState={props.noMatchState}\n />\n </Table>\n </div>\n\n {/* A move is otherwise silent: nothing about a reordered table is\n spoken, and the visual change is the only feedback. Outside the\n table so it is not read as a cell. */}\n <span aria-live=\"polite\" className=\"sr-only\">\n {orderAnnouncement}\n </span>\n\n {showFooter && (\n <DataTableFooter\n pageSizes={props.pageSizes}\n sizeForm={sizeForm}\n meta={meta}\n isMobile={isMobile}\n setPage={setPage}\n className={cn(\n squareRight?.bottom,\n flatBottom,\n props.chromeClassName,\n )}\n />\n )}\n </div>\n </ClientOnly>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,MAAa,aAIX,UACG;;;;;;CAMH,MAAM,UAAU;;;;;;;;;;;;;;CAehB,MAAM,aACJ,MAAM,SAAS,YAAY,QAAQ,KAAA,IAAY,MAAM;CACvD,MAAM,aACJ,MAAM,SAAS,YAAY,QAAQ,KAAA,IAAY,MAAM;CACvD,MAAM,UACJ,MAAM,SAAS,SAAS,QAAQ,KAAA,IAAY,MAAM;CAKpD,MAAM,UACJ,MAAM,WAAW,WAAW,IAAI,KAAA,IAAY,MAAM;CAKpD,MAAM,CAAC,MAAM,WAAW,eACtB,cAAc,SAAS,MAAM,WAAW,CAC1C;CACA,MAAM,SAAS,UAAU;CACzB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,QAAQ,SAAS;;;;;;;;;;;CAWvB,MAAM,WAAW,YAAY;CAE7B,MAAM,EAAE,MAAM,YAAY,qBAAqB,uBAAuB;EACpE,OAAO;EACP;EACA;CACF,CAAC;CAED,MAAM,mBAAmB,6BAA6B;EACpD,YAAY;EACZ;CACF,CAA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eAAe,YAAY;MACrB;MACO;MACJ;MACT,SAAS,QAAQ;MACjB,OAAO,QAAQ;MACN;MACI;MACA;MACE;MACG;MACP;MACA;MACH;MACR,YAAY,MAAM;MAClB,mBAAmB,MAAM;MACzB,SAAS,MAAM;MACf,YAAY,MAAM;MAClB,YAAY,MAAM;MAClB,OAAO,MAAM;MACb,cAAc,MAAM;MACpB,YAAY,MAAM;MAClB,cAAc,MAAM;KACrB,CAAA,CACI;;GACJ,CAAA;GAKL,oBAAC,QAAD;IAAM,aAAU;IAAS,WAAU;IAChC,UAAA;GACG,CAAA;GAEL,cACC,oBAAC,iBAAD;IACE,WAAW,MAAM;IACP;IACJ;IACI;IACD;IACT,WAAW,GACT,aAAa,QACb,YACA,MAAM,eACR;GACD,CAAA;EAEA;CACK,CAAA,EAAA,CAAA;AAEhB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTableColumnPicker.d.ts","sourceRoot":"","sources":["../../src/table/DataTableColumnPicker.tsx"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,MAAM,WAAW,0BAA0B,CAAC,CAAC;IAC3C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;CAClD;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,GAAI,CAAC,SAC9B,0BAA0B,CAAC,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"DataTableColumnPicker.d.ts","sourceRoot":"","sources":["../../src/table/DataTableColumnPicker.tsx"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,MAAM,WAAW,0BAA0B,CAAC,CAAC;IAC3C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;CAClD;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,GAAI,CAAC,SAC9B,0BAA0B,CAAC,CAAC,CAAC,gCAiHrC,CAAC"}
|
|
@@ -59,6 +59,7 @@ const DataTableColumnPicker = (props) => {
|
|
|
59
59
|
}),
|
|
60
60
|
/* @__PURE__ */ jsx(DropdownMenuCheckboxItem, {
|
|
61
61
|
checked: props.visible.has(key),
|
|
62
|
+
disabled: props.visible.has(key) && props.visible.size === 1,
|
|
62
63
|
closeOnClick: false,
|
|
63
64
|
onCheckedChange: () => props.onToggle(key),
|
|
64
65
|
className: "flex-1",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTableColumnPicker.js","names":[],"sources":["../../src/table/DataTableColumnPicker.tsx"],"sourcesContent":["import { useI18n } from \"alepha/react/i18n\";\nimport { ChevronDown, ChevronUp, Columns3, GripVertical } from \"lucide-react\";\nimport { useState } from \"react\";\n\nimport { Button } from \"../core/Button.tsx\";\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from \"../core/DropdownMenu.tsx\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"../core/Tooltip.tsx\";\nimport { cn } from \"../core/utils.ts\";\nimport type { ColumnDef } from \"./dataTableTypes.ts\";\n\nexport interface DataTableColumnPickerProps<T> {\n columns: Record<string, ColumnDef<T>>;\n order: string[];\n visible: Set<string>;\n onToggle: (key: string) => void;\n onReorder: (key: string, target: string) => void;\n}\n\n/**\n * The single home for column state: what is shown, and in what order.\n *\n * Both live here rather than order being reachable only from the header's\n * context menu, and that is the shape decision. Right-click advertises\n * nothing and does not exist on touch, so a feature reachable only that way\n * is one most people never find. The menu is a fast path into this.\n *\n * Reordering is native HTML5 drag, the way Lore's folio tree does it: this\n * package has no drag-and-drop dependency and a column list is not worth\n * adding one. The arrows beside each row are not a fallback for a broken\n * drag - they are the keyboard and touch path, where drag does not exist.\n */\nexport const DataTableColumnPicker = <T,>(\n props: DataTableColumnPickerProps<T>,\n) => {\n const { tr } = useI18n();\n const [dragging, setDragging] = useState<string | null>(null);\n // The reader's order, so the list reads like the table it controls.\n const entries = props.order.map(\n (key) => [key, props.columns[key]!] as [string, ColumnDef<T>],\n );\n const label = tr(\"dataTable.toggleColumns\", {\n default: \"Toggle columns\",\n });\n return (\n <DropdownMenu>\n {/*\n * The trigger is composed rather than plain: it has to be the dropdown\n * trigger AND the tooltip trigger at once, or this button is the only\n * icon-only control in the toolbar with no tooltip (reset-filters and\n * refresh sit right next to it and both have one).\n *\n * `TooltipTrigger` wraps the rendered element rather than the other way\n * round, matching how `sidebar.tsx` composes the same two primitives.\n * `TooltipProvider` is supplied by the toolbar that renders this.\n */}\n <Tooltip>\n <DropdownMenuTrigger\n render={\n <TooltipTrigger\n render={\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"minimal\"\n className=\"h-9 w-9 p-0\"\n aria-label={label}\n />\n }\n />\n }\n >\n <Columns3 className=\"size-4\" />\n </DropdownMenuTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuGroup>\n <DropdownMenuLabel>\n {tr(\"dataTable.columns\", { default: \"Columns\" })}\n </DropdownMenuLabel>\n <DropdownMenuSeparator />\n {entries.map(([key, def], index) => (\n <div\n key={key}\n draggable\n onDragStart={() => setDragging(key)}\n onDragEnd={() => setDragging(null)}\n onDragOver={(event) => {\n // Required, or the drop never fires.\n event.preventDefault();\n }}\n onDrop={(event) => {\n event.preventDefault();\n if (dragging && dragging !== key)\n props.onReorder(dragging, key);\n setDragging(null);\n }}\n className={cn(\n \"flex items-center gap-1 pr-1\",\n dragging === key && \"opacity-45\",\n )}\n >\n <GripVertical\n className=\"text-muted-foreground/60 size-3.5 shrink-0 cursor-grab\"\n aria-hidden\n />\n <DropdownMenuCheckboxItem\n checked={props.visible.has(key)}\n closeOnClick={false}\n onCheckedChange={() => props.onToggle(key)}\n className=\"flex-1\"\n >\n {def.label}\n </DropdownMenuCheckboxItem>\n {/* Keyboard and touch reach the order here. A drag handle alone\n would put reordering out of reach for both. */}\n <button\n type=\"button\"\n disabled={index === 0}\n aria-label={tr(\"dataTable.moveUp\", { default: \"Move up\" })}\n onClick={() => props.onReorder(key, entries[index - 1]![0])}\n className=\"text-muted-foreground/60 hover:text-foreground rounded p-0.5 disabled:opacity-30\"\n >\n <ChevronUp className=\"size-3.5\" />\n </button>\n <button\n type=\"button\"\n disabled={index === entries.length - 1}\n aria-label={tr(\"dataTable.moveDown\", {\n default: \"Move down\",\n })}\n onClick={() => props.onReorder(entries[index + 1]![0], key)}\n className=\"text-muted-foreground/60 hover:text-foreground rounded p-0.5 disabled:opacity-30\"\n >\n <ChevronDown className=\"size-3.5\" />\n </button>\n </div>\n ))}\n </DropdownMenuGroup>\n </DropdownMenuContent>\n </DropdownMenu>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,yBACX,UACG;CACH,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,CAAC,UAAU,eAAe,SAAwB,IAAI;CAE5D,MAAM,UAAU,MAAM,MAAM,KACzB,QAAQ,CAAC,KAAK,MAAM,QAAQ,IAAK,CACpC;CACA,MAAM,QAAQ,GAAG,2BAA2B,EAC1C,SAAS,iBACX,CAAC;CACD,OACE,qBAAC,cAAD,EAAA,UAAA,CAWE,qBAAC,SAAD,EAAA,UAAA,CACE,oBAAC,qBAAD;EACE,QACE,oBAAC,gBAAD,EACE,QACE,oBAAC,QAAD;GACE,MAAK;GACL,MAAK;GACL,SAAQ;GACR,WAAU;GACV,cAAY;EACb,CAAA,EAEJ,CAAA;EAGH,UAAA,oBAAC,UAAD,EAAU,WAAU,SAAU,CAAA;CACX,CAAA,GACrB,oBAAC,gBAAD,EAAA,UAAiB,MAAsB,CAAA,CAChC,EAAA,CAAA,GACT,oBAAC,qBAAD;EAAqB,OAAM;EACzB,UAAA,qBAAC,mBAAD,EAAA,UAAA;GACE,oBAAC,mBAAD,EAAA,UACG,GAAG,qBAAqB,EAAE,SAAS,UAAU,CAAC,EAC9B,CAAA;GACnB,oBAAC,uBAAD,CAAwB,CAAA;GACvB,QAAQ,KAAK,CAAC,KAAK,MAAM,UACxB,qBAAC,OAAD;IAEE,WAAA;IACA,mBAAmB,YAAY,GAAG;IAClC,iBAAiB,YAAY,IAAI;IACjC,aAAa,UAAU;KAErB,MAAM,eAAe;IACvB;IACA,SAAS,UAAU;KACjB,MAAM,eAAe;KACrB,IAAI,YAAY,aAAa,KAC3B,MAAM,UAAU,UAAU,GAAG;KAC/B,YAAY,IAAI;IAClB;IACA,WAAW,GACT,gCACA,aAAa,OAAO,YACtB;IAlBF,UAAA;KAoBE,oBAAC,cAAD;MACE,WAAU;MACV,eAAA;KACD,CAAA;KACD,oBAAC,0BAAD;MACE,SAAS,MAAM,QAAQ,IAAI,GAAG;
|
|
1
|
+
{"version":3,"file":"DataTableColumnPicker.js","names":[],"sources":["../../src/table/DataTableColumnPicker.tsx"],"sourcesContent":["import { useI18n } from \"alepha/react/i18n\";\nimport { ChevronDown, ChevronUp, Columns3, GripVertical } from \"lucide-react\";\nimport { useState } from \"react\";\n\nimport { Button } from \"../core/Button.tsx\";\nimport {\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from \"../core/DropdownMenu.tsx\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"../core/Tooltip.tsx\";\nimport { cn } from \"../core/utils.ts\";\nimport type { ColumnDef } from \"./dataTableTypes.ts\";\n\nexport interface DataTableColumnPickerProps<T> {\n columns: Record<string, ColumnDef<T>>;\n order: string[];\n visible: Set<string>;\n onToggle: (key: string) => void;\n onReorder: (key: string, target: string) => void;\n}\n\n/**\n * The single home for column state: what is shown, and in what order.\n *\n * Both live here rather than order being reachable only from the header's\n * context menu, and that is the shape decision. Right-click advertises\n * nothing and does not exist on touch, so a feature reachable only that way\n * is one most people never find. The menu is a fast path into this.\n *\n * Reordering is native HTML5 drag, the way Lore's folio tree does it: this\n * package has no drag-and-drop dependency and a column list is not worth\n * adding one. The arrows beside each row are not a fallback for a broken\n * drag - they are the keyboard and touch path, where drag does not exist.\n */\nexport const DataTableColumnPicker = <T,>(\n props: DataTableColumnPickerProps<T>,\n) => {\n const { tr } = useI18n();\n const [dragging, setDragging] = useState<string | null>(null);\n // The reader's order, so the list reads like the table it controls.\n const entries = props.order.map(\n (key) => [key, props.columns[key]!] as [string, ColumnDef<T>],\n );\n const label = tr(\"dataTable.toggleColumns\", {\n default: \"Toggle columns\",\n });\n return (\n <DropdownMenu>\n {/*\n * The trigger is composed rather than plain: it has to be the dropdown\n * trigger AND the tooltip trigger at once, or this button is the only\n * icon-only control in the toolbar with no tooltip (reset-filters and\n * refresh sit right next to it and both have one).\n *\n * `TooltipTrigger` wraps the rendered element rather than the other way\n * round, matching how `sidebar.tsx` composes the same two primitives.\n * `TooltipProvider` is supplied by the toolbar that renders this.\n */}\n <Tooltip>\n <DropdownMenuTrigger\n render={\n <TooltipTrigger\n render={\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"minimal\"\n className=\"h-9 w-9 p-0\"\n aria-label={label}\n />\n }\n />\n }\n >\n <Columns3 className=\"size-4\" />\n </DropdownMenuTrigger>\n <TooltipContent>{label}</TooltipContent>\n </Tooltip>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuGroup>\n <DropdownMenuLabel>\n {tr(\"dataTable.columns\", { default: \"Columns\" })}\n </DropdownMenuLabel>\n <DropdownMenuSeparator />\n {entries.map(([key, def], index) => (\n <div\n key={key}\n draggable\n onDragStart={() => setDragging(key)}\n onDragEnd={() => setDragging(null)}\n onDragOver={(event) => {\n // Required, or the drop never fires.\n event.preventDefault();\n }}\n onDrop={(event) => {\n event.preventDefault();\n if (dragging && dragging !== key)\n props.onReorder(dragging, key);\n setDragging(null);\n }}\n className={cn(\n \"flex items-center gap-1 pr-1\",\n dragging === key && \"opacity-45\",\n )}\n >\n <GripVertical\n className=\"text-muted-foreground/60 size-3.5 shrink-0 cursor-grab\"\n aria-hidden\n />\n <DropdownMenuCheckboxItem\n checked={props.visible.has(key)}\n // The last visible column stays: a table of zero columns is\n // rows of empty cells, never what the reader meant.\n disabled={props.visible.has(key) && props.visible.size === 1}\n closeOnClick={false}\n onCheckedChange={() => props.onToggle(key)}\n className=\"flex-1\"\n >\n {def.label}\n </DropdownMenuCheckboxItem>\n {/* Keyboard and touch reach the order here. A drag handle alone\n would put reordering out of reach for both. */}\n <button\n type=\"button\"\n disabled={index === 0}\n aria-label={tr(\"dataTable.moveUp\", { default: \"Move up\" })}\n onClick={() => props.onReorder(key, entries[index - 1]![0])}\n className=\"text-muted-foreground/60 hover:text-foreground rounded p-0.5 disabled:opacity-30\"\n >\n <ChevronUp className=\"size-3.5\" />\n </button>\n <button\n type=\"button\"\n disabled={index === entries.length - 1}\n aria-label={tr(\"dataTable.moveDown\", {\n default: \"Move down\",\n })}\n onClick={() => props.onReorder(entries[index + 1]![0], key)}\n className=\"text-muted-foreground/60 hover:text-foreground rounded p-0.5 disabled:opacity-30\"\n >\n <ChevronDown className=\"size-3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AAU;MACV,eAAA;KACD,CAAA;KACD,oBAAC,0BAAD;MACE,SAAS,MAAM,QAAQ,IAAI,GAAG;MAG9B,UAAU,MAAM,QAAQ,IAAI,GAAG,KAAK,MAAM,QAAQ,SAAS;MAC3D,cAAc;MACd,uBAAuB,MAAM,SAAS,GAAG;MACzC,WAAU;MAET,UAAA,IAAI;KACmB,CAAA;KAG1B,oBAAC,UAAD;MACE,MAAK;MACL,UAAU,UAAU;MACpB,cAAY,GAAG,oBAAoB,EAAE,SAAS,UAAU,CAAC;MACzD,eAAe,MAAM,UAAU,KAAK,QAAQ,QAAQ,EAAE,CAAE,EAAE;MAC1D,WAAU;MAEV,UAAA,oBAAC,WAAD,EAAW,WAAU,WAAY,CAAA;KAC3B,CAAA;KACR,oBAAC,UAAD;MACE,MAAK;MACL,UAAU,UAAU,QAAQ,SAAS;MACrC,cAAY,GAAG,sBAAsB,EACnC,SAAS,YACX,CAAC;MACD,eAAe,MAAM,UAAU,QAAQ,QAAQ,EAAE,CAAE,IAAI,GAAG;MAC1D,WAAU;MAEV,UAAA,oBAAC,aAAD,EAAa,WAAU,WAAY,CAAA;KAC7B,CAAA;IACL;GAxDE,GAAA,GAwDF,CACN;EACgB,EAAA,CAAA;CACA,CAAA,CACT,EAAA,CAAA;AAElB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { ZObject, ZType } from "alepha";
|
|
2
2
|
import type { FormModel } from "alepha/react/form";
|
|
3
3
|
import type { DataTableFilterFieldOptions, DataTableFilterPreset } from "./dataTableTypes.ts";
|
|
4
4
|
export interface DataTableFilterBarProps {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTableFilterBar.d.ts","sourceRoot":"","sources":["../../src/table/DataTableFilterBar.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"DataTableFilterBar.d.ts","sourceRoot":"","sources":["../../src/table/DataTableFilterBar.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAQnD,OAAO,KAAK,EACV,2BAA2B,EAC3B,qBAAqB,EACtB,MAAM,qBAAqB,CAAC;AAG7B,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,IAAI,EAAE,SAAS,CAAC,OAAO,CAAC,CAAC;IAEzB;;;OAGG;IACH,MAAM,EAAE,uBAAuB,EAAE,CAAC;IAElC;;;;;OAKG;IACH,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAEzB;;;;OAIG;IACH,aAAa,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC;IAEvD;;;;OAIG;IACH,OAAO,CAAC,EAAE,KAAK,GAAG,QAAQ,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,eAAO,MAAM,kBAAkB,UAAW,uBAAuB,gCA0NhE,CAAC;AAEF;;;;GAIG;AACH,MAAM,WAAW,uBAAwB,SAAQ,2BAA2B;IAC1E;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,KAAK,CAAC;IACf,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC"}
|
|
@@ -2,13 +2,10 @@ import { FilterSlot } from "../core/FilterSlot.js";
|
|
|
2
2
|
import { Control } from "../form/Control.js";
|
|
3
3
|
import { DataTableFilterAdd } from "./DataTableFilterAdd.js";
|
|
4
4
|
import { DataTableFilterControl } from "./DataTableFilterControl.js";
|
|
5
|
-
import {
|
|
6
|
-
import { z } from "alepha";
|
|
5
|
+
import { useDataTableFilterModel } from "./useDataTableFilterModel.js";
|
|
7
6
|
import { useI18n } from "alepha/react/i18n";
|
|
8
|
-
import { Calendar, List, Search, Type } from "lucide-react";
|
|
9
7
|
import { useEffect, useLayoutEffect, useRef } from "react";
|
|
10
8
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
11
|
-
import { useFormValues } from "alepha/react/form";
|
|
12
9
|
// src/table/DataTableFilterBar.tsx
|
|
13
10
|
/**
|
|
14
11
|
* The filter bar `DataTable` draws from `filters.fields`: the locked filters
|
|
@@ -44,100 +41,13 @@ import { useFormValues } from "alepha/react/form";
|
|
|
44
41
|
*/
|
|
45
42
|
const DataTableFilterBar = (props) => {
|
|
46
43
|
const { tr } = useI18n();
|
|
47
|
-
const
|
|
44
|
+
const model = useDataTableFilterModel(props.form);
|
|
45
|
+
const { values, inputs, isSet, holds, isLocked, operatorKeyOf, operatorOf, kindOf, placeholderOf, labelOf, iconOf, clearField } = model;
|
|
48
46
|
const dialog = props.variant === "dialog";
|
|
49
|
-
const modeOf = (field) => field.mode ?? (field.preset === "search" ? "locked" : "optional");
|
|
50
47
|
const shown = props.shown;
|
|
51
48
|
const root = useRef(null);
|
|
52
49
|
const pendingOpen = useRef(void 0);
|
|
53
50
|
const heldValue = useRef({});
|
|
54
|
-
const inputs = props.form.input;
|
|
55
|
-
const isSet = (key) => {
|
|
56
|
-
const value = values[key];
|
|
57
|
-
return Array.isArray(value) ? value.length > 0 : Boolean(value);
|
|
58
|
-
};
|
|
59
|
-
const operatorKeyOf = (field) => field.operatorKey ?? `${field.key}Op`;
|
|
60
|
-
const holds = (field) => isSet(field.key) || values[operatorKeyOf(field)] !== void 0;
|
|
61
|
-
const isLocked = (field) => modeOf(field) === "locked";
|
|
62
|
-
const operatorsOf = (field) => {
|
|
63
|
-
if (!field.operators || typeof field.operators !== "string") return field.operators;
|
|
64
|
-
const not = tr("dataTable.operator.prefixNot", { default: "not" });
|
|
65
|
-
const labels = {
|
|
66
|
-
is: { label: tr("dataTable.operator.is", { default: "is" }) },
|
|
67
|
-
not: {
|
|
68
|
-
label: tr("dataTable.operator.isNot", { default: "is not" }),
|
|
69
|
-
prefix: not
|
|
70
|
-
},
|
|
71
|
-
any: { label: tr("dataTable.operator.anyOf", { default: "any of" }) },
|
|
72
|
-
all: {
|
|
73
|
-
label: tr("dataTable.operator.allOf", { default: "all of" }),
|
|
74
|
-
prefix: tr("dataTable.operator.prefixAll", { default: "all" })
|
|
75
|
-
},
|
|
76
|
-
none: {
|
|
77
|
-
label: tr("dataTable.operator.noneOf", { default: "none of" }),
|
|
78
|
-
prefix: not
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
return DATA_TABLE_FILTER_OPERATORS[field.operators].map((value) => ({
|
|
82
|
-
value,
|
|
83
|
-
label: labels[value]?.label ?? value,
|
|
84
|
-
prefix: labels[value]?.prefix
|
|
85
|
-
}));
|
|
86
|
-
};
|
|
87
|
-
const operatorOf = (field) => {
|
|
88
|
-
const operators = operatorsOf(field);
|
|
89
|
-
return operators?.find((operator) => operator.value === values[operatorKeyOf(field)]) ?? operators?.[0];
|
|
90
|
-
};
|
|
91
|
-
/**
|
|
92
|
-
* The schema a field is read with, stripped of `.optional()`: its own, or
|
|
93
|
-
* `z.string()` for the search preset.
|
|
94
|
-
*/
|
|
95
|
-
const schemaOf = (field) => field.schema ? z.schema.unwrap(field.schema) : field.preset === "search" ? z.string() : void 0;
|
|
96
|
-
/**
|
|
97
|
-
* The values an enum schema, or an array of one, allows. Empty for any
|
|
98
|
-
* other schema.
|
|
99
|
-
*/
|
|
100
|
-
const enumValuesOf = (field) => {
|
|
101
|
-
const schema = schemaOf(field);
|
|
102
|
-
if (!schema) return [];
|
|
103
|
-
if (z.schema.isEnum(schema)) return z.schema.enumOptions(schema);
|
|
104
|
-
if (z.schema.isArray(schema)) {
|
|
105
|
-
const element = z.schema.unwrap(z.schema.element(schema));
|
|
106
|
-
if (z.schema.isEnum(element)) return z.schema.enumOptions(element);
|
|
107
|
-
}
|
|
108
|
-
return [];
|
|
109
|
-
};
|
|
110
|
-
const itemsOf = (field) => {
|
|
111
|
-
if (typeof field.items === "function") return field.items(values);
|
|
112
|
-
if (field.items) return field.items;
|
|
113
|
-
const options = enumValuesOf(field);
|
|
114
|
-
if (options.length === 0) return void 0;
|
|
115
|
-
const optionLabel = field.optionLabel;
|
|
116
|
-
return optionLabel ? options.map((value) => ({
|
|
117
|
-
value,
|
|
118
|
-
label: optionLabel(value)
|
|
119
|
-
})) : options;
|
|
120
|
-
};
|
|
121
|
-
const kindOf = (field) => {
|
|
122
|
-
const schema = schemaOf(field);
|
|
123
|
-
if (schema && z.schema.isDateRange(schema)) return "date";
|
|
124
|
-
if (field.items || schema && (z.schema.isEnum(schema) || z.schema.isArray(schema))) return "list";
|
|
125
|
-
return "text";
|
|
126
|
-
};
|
|
127
|
-
const placeholderOf = (field) => field.placeholder ?? field.control?.placeholder ?? (field.preset === "search" ? tr("dataTable.search", { default: "Search" }) : void 0);
|
|
128
|
-
const labelOf = (field) => field.label ?? placeholderOf(field) ?? field.key;
|
|
129
|
-
const iconOf = (field) => {
|
|
130
|
-
if (field.icon) return field.icon;
|
|
131
|
-
if (field.preset === "search") return Search;
|
|
132
|
-
const kind = kindOf(field);
|
|
133
|
-
if (kind === "date") return Calendar;
|
|
134
|
-
if (kind === "list") return List;
|
|
135
|
-
return Type;
|
|
136
|
-
};
|
|
137
|
-
const clearField = (field) => {
|
|
138
|
-
inputs[field.key]?.set(void 0);
|
|
139
|
-
if (field.operators) inputs[operatorKeyOf(field)]?.set(void 0);
|
|
140
|
-
};
|
|
141
51
|
useEffect(() => {
|
|
142
52
|
const key = pendingOpen.current;
|
|
143
53
|
if (!key) return;
|
|
@@ -177,7 +87,6 @@ const DataTableFilterBar = (props) => {
|
|
|
177
87
|
className: "contents",
|
|
178
88
|
children: [ordered.filter((field) => drawn(field)).map((field) => {
|
|
179
89
|
const removable = !dialog && !isLocked(field);
|
|
180
|
-
const operators = operatorsOf(field);
|
|
181
90
|
const operator = operatorOf(field);
|
|
182
91
|
const label = labelOf(field);
|
|
183
92
|
return /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx("div", {
|
|
@@ -191,13 +100,7 @@ const DataTableFilterBar = (props) => {
|
|
|
191
100
|
props.onShownChange(shown.filter((key) => key !== field.key), true);
|
|
192
101
|
} : void 0,
|
|
193
102
|
children: /* @__PURE__ */ jsx(Control, {
|
|
194
|
-
...field
|
|
195
|
-
input: inputs[field.key],
|
|
196
|
-
label: "",
|
|
197
|
-
icon: iconOf(field),
|
|
198
|
-
clearable: true,
|
|
199
|
-
placeholder: placeholderOf(field),
|
|
200
|
-
items: itemsOf(field),
|
|
103
|
+
...model.controlPropsOf(field),
|
|
201
104
|
inputProps: {
|
|
202
105
|
"aria-label": label,
|
|
203
106
|
...kindOf(field) === "text" ? { size: Math.max(20, placeholderOf(field)?.length ?? 0) } : {},
|
|
@@ -206,13 +109,7 @@ const DataTableFilterBar = (props) => {
|
|
|
206
109
|
triggerPrefix: [tr("dataTable.filterName", {
|
|
207
110
|
default: `${label}:`,
|
|
208
111
|
args: [label]
|
|
209
|
-
}), operator?.prefix].filter(Boolean).join(" ")
|
|
210
|
-
popupClassName: "w-max min-w-48",
|
|
211
|
-
popupHeader: operators && /* @__PURE__ */ jsx(DataTableFilterOperator, {
|
|
212
|
-
options: operators,
|
|
213
|
-
value: operator?.value,
|
|
214
|
-
onChange: (value) => inputs[operatorKeyOf(field)]?.set(value)
|
|
215
|
-
})
|
|
112
|
+
}), operator?.prefix].filter(Boolean).join(" ")
|
|
216
113
|
})
|
|
217
114
|
})
|
|
218
115
|
}) }, field.key);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataTableFilterBar.js","names":[],"sources":["../../src/table/DataTableFilterBar.tsx"],"sourcesContent":["import { type ZObject, type ZType, z } from \"alepha\";\nimport type { FormModel } from \"alepha/react/form\";\nimport { useFormValues } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { Calendar, List, Search, Type } from \"lucide-react\";\nimport { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { FilterSlot } from \"../core/FilterSlot.tsx\";\nimport { Control } from \"../form/Control.tsx\";\nimport type { SelectOption } from \"../form/ControlSelect.tsx\";\nimport type { DataTableFilterAddType } from \"./DataTableFilterAdd.tsx\";\nimport { DataTableFilterAdd } from \"./DataTableFilterAdd.tsx\";\nimport { DataTableFilterControl } from \"./DataTableFilterControl.tsx\";\nimport type { DataTableFilterOperatorOption } from \"./DataTableFilterOperator.tsx\";\nimport {\n DATA_TABLE_FILTER_OPERATORS,\n DataTableFilterOperator,\n} from \"./DataTableFilterOperator.tsx\";\nimport type {\n DataTableFilterFieldOptions,\n DataTableFilterMode,\n DataTableFilterPreset,\n} from \"./dataTableTypes.ts\";\n\nexport interface DataTableFilterBarProps {\n /**\n * The table's filter form. Every `key` below names one of its fields, and\n * so does every operator key.\n */\n form: FormModel<ZObject>;\n\n /**\n * Every filter, in declaration order: the order the bar draws them in and\n * the add menu lists them in.\n */\n fields: DataTableFilterBarField[];\n\n /**\n * Which filters are on the bar. The table's state, not the bar's, because\n * three things write it: this bar, Reset filters and persistence.\n *\n * A locked field is drawn whether or not it is in here.\n */\n shown: readonly string[];\n\n /**\n * The shown filters changed. `act` is true for the reader's own add or\n * remove, and false when a filter joined the bar because it holds a value:\n * that is not the reader choosing anything, and must not be stored.\n */\n onShownChange: (shown: string[], act: boolean) => void;\n\n /**\n * `\"dialog\"` draws every filter, each like a locked field, and no add menu:\n * the phone dialog is already the on-demand step, and a menu per filter\n * behind that button would be a second one.\n */\n variant?: \"bar\" | \"dialog\";\n}\n\n/**\n * The filter bar `DataTable` draws from `filters.fields`: the locked filters\n * (the search box), then the filters the reader put on the bar, then the menu\n * that adds one.\n *\n * **Which filters start on the bar is the field's `mode`.** An `optional`\n * field, the default, is off it until the reader adds it; a `default` field\n * is on it from the start and removable; a `locked` field is always there and\n * never removable. Showing every filter a table supports spends the width of\n * the bar on questions nobody has asked; four boxes reading \"Any status\",\n * \"Any team\", \"Any role\" say only that those columns exist.\n *\n * ⚠️ **A filter holding a value, or a non-default operator, is always on the\n * bar**, whatever its mode and however it got the value: restored from\n * persistence, read from a shared link, carried across a remount. Keyed on\n * the shown state alone, the bar came back empty while the table stayed\n * filtered, and \"Add filters\" handed back a filter that was already set. The\n * same holds for `hidden`: an empty hidden field is off the bar and out of the\n * menu, and a hidden field narrowing the list is still drawn, or the list\n * would be narrowed with nothing on screen saying why.\n *\n * **Operators** are optional per field, and each is a field of its own in the\n * filters schema, `<key>Op` unless `operatorKey` says otherwise. The backend\n * must declare the same key and values; a default operator sends no key at\n * all. See `DataTableFilterOperator` for why it is one switch rather than an\n * EQUAL toggle beside an OR/AND one.\n *\n * Internal to the table: a table given `fields` and no `filters.render`\n * mounts it, in the toolbar and in the phone dialog.\n *\n * Built and settled on the `apps/ui` showcase (`/blocks/data-table/basic`) in #Q2308.\n */\nexport const DataTableFilterBar = (props: DataTableFilterBarProps) => {\n const { tr } = useI18n();\n const values = useFormValues(props.form) as Record<string, unknown>;\n const dialog = props.variant === \"dialog\";\n const modeOf = (field: DataTableFilterBarField): DataTableFilterMode =>\n field.mode ?? (field.preset === \"search\" ? \"locked\" : \"optional\");\n const shown = props.shown;\n const root = useRef<HTMLDivElement>(null);\n // The filter to open once React has put it on screen. A REF, not state: the\n // effect below both reads and clears it, and clearing it with `setState`\n // inside an effect is a cascading render. Nothing renders from it.\n const pendingOpen = useRef<string | undefined>(undefined);\n // Which filters held a value at the last commit - see the operator effect.\n const heldValue = useRef<Record<string, boolean>>({});\n\n const inputs = props.form.input as unknown as Record<\n string,\n { set: (value: unknown) => void } | undefined\n >;\n\n const isSet = (key: string): boolean => {\n const value = values[key];\n return Array.isArray(value) ? value.length > 0 : Boolean(value);\n };\n\n const operatorKeyOf = (field: DataTableFilterBarField) =>\n field.operatorKey ?? `${field.key}Op`;\n\n // Narrowing the list, by a value or by an operator standing on its own.\n const holds = (field: DataTableFilterBarField): boolean =>\n isSet(field.key) || values[operatorKeyOf(field)] !== undefined;\n\n const isLocked = (field: DataTableFilterBarField) =>\n modeOf(field) === \"locked\";\n\n const operatorsOf = (\n field: DataTableFilterBarField,\n ): DataTableFilterOperatorOption[] | undefined => {\n if (!field.operators || typeof field.operators !== \"string\") {\n return field.operators as DataTableFilterOperatorOption[] | undefined;\n }\n // The values come from the one table the filter schema is built from; only\n // the words are this bar's. A value is labelled the same in every preset\n // it appears in, so one entry per value covers all three.\n const not = tr(\"dataTable.operator.prefixNot\", { default: \"not\" });\n const labels: Record<\n string,\n Omit<DataTableFilterOperatorOption, \"value\">\n > = {\n is: { label: tr(\"dataTable.operator.is\", { default: \"is\" }) },\n not: {\n label: tr(\"dataTable.operator.isNot\", { default: \"is not\" }),\n prefix: not,\n },\n any: { label: tr(\"dataTable.operator.anyOf\", { default: \"any of\" }) },\n all: {\n label: tr(\"dataTable.operator.allOf\", { default: \"all of\" }),\n prefix: tr(\"dataTable.operator.prefixAll\", { default: \"all\" }),\n },\n none: {\n label: tr(\"dataTable.operator.noneOf\", { default: \"none of\" }),\n prefix: not,\n },\n };\n return DATA_TABLE_FILTER_OPERATORS[field.operators].map((value) => ({\n value,\n label: labels[value]?.label ?? value,\n prefix: labels[value]?.prefix,\n }));\n };\n\n const operatorOf = (field: DataTableFilterBarField) => {\n const operators = operatorsOf(field);\n return (\n operators?.find(\n (operator) => operator.value === values[operatorKeyOf(field)],\n ) ?? operators?.[0]\n );\n };\n\n /**\n * The schema a field is read with, stripped of `.optional()`: its own, or\n * `z.string()` for the search preset.\n */\n const schemaOf = (field: DataTableFilterBarField): ZType | undefined =>\n field.schema\n ? z.schema.unwrap(field.schema)\n : field.preset === \"search\"\n ? z.string()\n : undefined;\n\n /**\n * The values an enum schema, or an array of one, allows. Empty for any\n * other schema.\n */\n const enumValuesOf = (field: DataTableFilterBarField): string[] => {\n const schema = schemaOf(field);\n if (!schema) return [];\n if (z.schema.isEnum(schema)) return z.schema.enumOptions(schema);\n if (z.schema.isArray(schema)) {\n const element = z.schema.unwrap(z.schema.element(schema));\n if (z.schema.isEnum(element)) return z.schema.enumOptions(element);\n }\n return [];\n };\n\n // Live data first, then the enum the schema declares. A bare string falls\n // back to the select's own label for it.\n const itemsOf = (\n field: DataTableFilterBarField,\n ): SelectOption[] | undefined => {\n if (typeof field.items === \"function\") return field.items(values);\n if (field.items) return field.items;\n const options = enumValuesOf(field);\n if (options.length === 0) return undefined;\n const optionLabel = field.optionLabel;\n return optionLabel\n ? options.map((value) => ({ value, label: optionLabel(value) }))\n : options;\n };\n\n // Classified in `Control`'s own order, so the menu names the control the\n // filter will actually draw.\n const kindOf = (field: DataTableFilterBarField): DataTableFilterAddType => {\n const schema = schemaOf(field);\n // Before the list test, as `Control` orders it: a range IS an array, and\n // tested as one it would be offered as a list and drawn as a calendar.\n if (schema && z.schema.isDateRange(schema)) return \"date\";\n if (\n field.items ||\n (schema && (z.schema.isEnum(schema) || z.schema.isArray(schema)))\n ) {\n return \"list\";\n }\n return \"text\";\n };\n\n const placeholderOf = (field: DataTableFilterBarField) =>\n field.placeholder ??\n field.control?.placeholder ??\n (field.preset === \"search\"\n ? tr(\"dataTable.search\", { default: \"Search\" })\n : undefined);\n\n const labelOf = (field: DataTableFilterBarField) =>\n field.label ?? placeholderOf(field) ?? field.key;\n\n // Every filter has an icon, as every `Control` does: the caller's, the\n // search glyph for the search preset, else its kind's (the same glyphs the\n // controls fall back to). Without the last step a filter the caller gave no\n // icon was the one bare row of the add menu (\"When\", beside \"Resource\" and\n // \"What\").\n const iconOf = (field: DataTableFilterBarField) => {\n if (field.icon) return field.icon;\n if (field.preset === \"search\") return Search;\n const kind = kindOf(field);\n if (kind === \"date\") return Calendar;\n if (kind === \"list\") return List;\n return Type;\n };\n\n // A filter goes back to its default operator as its value goes: an\n // operator standing with nothing to qualify still counts as a filter in the\n // table's reset button and badge, while narrowing nothing.\n const clearField = (field: DataTableFilterBarField) => {\n inputs[field.key]?.set(undefined);\n if (field.operators) inputs[operatorKeyOf(field)]?.set(undefined);\n };\n\n useEffect(() => {\n const key = pendingOpen.current;\n if (!key) return;\n pendingOpen.current = undefined;\n // ⚠️ Opening the new filter has to happen from OUT HERE, after the render\n // that mounts it: inside the menu's click handler the control does not\n // exist yet. Driven through the DOM because `Control` exposes no\n // imperative \"open\" - a combobox owns that state, and a date range's\n // popover owns its own. A text filter has no list, so it is focused\n // instead. Scoped to this bar, so two tables on one page cannot open each\n // other's filters.\n const slot = root.current?.querySelector(`[data-filter=\"${key}\"]`);\n const trigger = slot?.querySelector<HTMLElement>(\n '[data-slot=\"combobox-trigger\"], [data-slot=\"date-trigger\"]',\n );\n if (trigger) {\n trigger.click();\n return;\n }\n slot?.querySelector<HTMLInputElement>('[data-slot=\"input\"]')?.focus();\n }, [shown]);\n\n useEffect(() => {\n // The other way a value empties: unticked inside the list, or cleared by\n // a locked field's own cross, rather than cleared by the button. Only on\n // the transition from set to empty, so a reader who picks \"is not\" BEFORE\n // picking a value keeps it, and a persisted operator survives the mount\n // it is restored on.\n for (const field of props.fields) {\n const set = isSet(field.key);\n const operatorKey = operatorKeyOf(field);\n if (\n field.operators &&\n heldValue.current[field.key] &&\n !set &&\n values[operatorKey] !== undefined\n ) {\n inputs[operatorKey]?.set(undefined);\n }\n heldValue.current[field.key] = set;\n }\n }, [values]);\n\n // A field holding a value or an operator joins `shown` the moment it is\n // seen - see the docblock. Folded INTO `shown` rather than drawn as\n // `shown ∪ set`, because a filter visible only for holding a value would\n // unmount the instant the reader emptied it, list open and cursor on it.\n // Locked fields are drawn regardless and never join it, and the dialog\n // draws every field.\n const unshown = dialog\n ? []\n : props.fields\n .filter(\n (field) =>\n !isLocked(field) && holds(field) && !shown.includes(field.key),\n )\n .map((field) => field.key);\n\n // The table's state cannot be set from this component's render, so it is\n // set in a LAYOUT effect: React flushes that update synchronously, before\n // the browser paints, so no frame shows the bar without the filter. The\n // guard stops it looping - it only fires while something is missing, and\n // the update adds exactly that.\n useLayoutEffect(() => {\n if (unshown.length > 0) {\n props.onShownChange([...shown, ...unshown], false);\n }\n });\n\n const drawn = (field: DataTableFilterBarField): boolean => {\n if (field.hidden && !holds(field)) return false;\n if (dialog || isLocked(field)) return true;\n return shown.includes(field.key);\n };\n\n // Locked first, in declaration order, then the shown ones in the order they\n // joined the bar: an added filter goes to the END, beside the \"+\" that\n // brought it, not back to its declared slot. Added D, C, B, A reads\n // D C B A. The dialog keeps the declaration as it is: nothing there is\n // added or removed.\n const rank = (field: DataTableFilterBarField) => {\n const index = shown.indexOf(field.key);\n return index === -1 ? Number.MAX_SAFE_INTEGER : index;\n };\n const ordered = dialog\n ? props.fields\n : [\n ...props.fields.filter((field) => isLocked(field)),\n ...props.fields\n .filter((field) => !isLocked(field))\n .sort((a, b) => rank(a) - rank(b)),\n ];\n\n return (\n // `contents`, so the slots are items of the table's own wrapping row (and\n // of the phone dialog's grid) exactly as a caller's bare fragment is.\n <div ref={root} className=\"contents\">\n {ordered\n .filter((field) => drawn(field))\n .map((field) => {\n // In the dialog every filter is drawn like a locked one: no\n // clear-and-remove button, the control's own cross resets it.\n const removable = !dialog && !isLocked(field);\n const operators = operatorsOf(field);\n const operator = operatorOf(field);\n const label = labelOf(field);\n return (\n <FilterSlot key={field.key}>\n <div data-filter={field.key}>\n <DataTableFilterControl\n label={label}\n active={isSet(field.key)}\n // A cross empties a filter holding a value; a funnel-x\n // removes an empty one. `active` picks between the two.\n // A locked filter is given neither, so it keeps the cross\n // inside its own field.\n onClear={removable ? () => clearField(field) : undefined}\n onRemove={\n removable\n ? () => {\n clearField(field);\n props.onShownChange(\n shown.filter((key) => key !== field.key),\n true,\n );\n }\n : undefined\n }\n >\n <Control\n {...field.control}\n input={inputs[field.key] as never}\n label=\"\"\n icon={iconOf(field)}\n clearable\n placeholder={placeholderOf(field)}\n items={itemsOf(field)}\n // The filter's name, as the control's accessible name:\n // an empty select says only its placeholder, and a set\n // one only its value. A name the caller gave wins.\n inputProps={{\n \"aria-label\": label,\n // A text filter is as wide as its placeholder. The slot\n // grows from its content, and an input's content width\n // is its `size` in characters (20 by default), so a\n // long placeholder was cut at the slot's minimum.\n ...(kindOf(field) === \"text\"\n ? {\n size: Math.max(\n 20,\n placeholderOf(field)?.length ?? 0,\n ),\n }\n : {}),\n ...field.control?.inputProps,\n }}\n // The filter's name, and a non-default operator, muted in\n // front of the value: \"Status: not Active\". An empty\n // select draws no prefix; its placeholder names it. The\n // colon is a catalog entry because French spaces it.\n triggerPrefix={[\n tr(\"dataTable.filterName\", {\n default: `${label}:`,\n args: [label],\n }),\n operator?.prefix,\n ]\n .filter(Boolean)\n .join(\" \")}\n // Sized from its content, not the trigger: the trigger\n // grows as the reader picks, and a popup tied to it would\n // widen under the cursor.\n popupClassName=\"w-max min-w-48\"\n popupHeader={\n operators && (\n <DataTableFilterOperator\n options={operators}\n value={operator?.value}\n onChange={(value) =>\n inputs[operatorKeyOf(field)]?.set(value)\n }\n />\n )\n }\n />\n </DataTableFilterControl>\n </div>\n </FilterSlot>\n );\n })}\n\n {!dialog && (\n <DataTableFilterAdd\n labeled={!ordered.some((field) => drawn(field))}\n items={props.fields\n .filter(\n (field) =>\n !isLocked(field) && !field.hidden && !shown.includes(field.key),\n )\n .map((field) => ({\n key: field.key,\n label: labelOf(field),\n icon: iconOf(field),\n type: kindOf(field),\n }))}\n onAdd={(key) => {\n pendingOpen.current = key;\n props.onShownChange([...shown, key], true);\n }}\n />\n )}\n </div>\n );\n};\n\n/**\n * One filter of the bar: a field of `filters.fields` with its key, as the\n * table hands it over. `schema` is the one the table read at mount, and gives\n * the options of an enum and the kind the add menu names.\n */\nexport interface DataTableFilterBarField extends DataTableFilterFieldOptions {\n /**\n * The form field this filter writes.\n */\n key: string;\n schema?: ZType;\n preset?: DataTableFilterPreset;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,MAAa,sBAAsB,UAAmC;CACpE,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,SAAS,cAAc,MAAM,IAAI;CACvC,MAAM,SAAS,MAAM,YAAY;CACjC,MAAM,UAAU,UACd,MAAM,SAAS,MAAM,WAAW,W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ACV,OAAO,OAAO,MAAM;MACpB,OAAM;MACN,MAAM,OAAO,KAAK;MAClB,WAAA;MACA,aAAa,cAAc,KAAK;MAChC,OAAO,QAAQ,KAAK;MAIpB,YAAY;OACV,cAAc;OAKd,GAAI,OAAO,KAAK,MAAM,SAClB,EACE,MAAM,KAAK,IACT,IACA,cAAc,KAAK,CAAC,EAAE,UAAU,CAClC,EACF,IACA,CAAC;OACL,GAAG,MAAM,SAAS;MACpB;MAKA,eAAe,CACb,GAAG,wBAAwB;OACzB,SAAS,GAAG,MAAM;OAClB,MAAM,CAAC,KAAK;MACd,CAAC,GACD,UAAU,MACZ,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;MAIX,gBAAe;MACf,aACE,aACE,oBAAC,yBAAD;OACE,SAAS;OACT,OAAO,UAAU;OACjB,WAAW,UACT,OAAO,cAAc,KAAK,EAAE,EAAE,IAAI,KAAK;MAE1C,CAAA;KAGN,CAAA;IACqB,CAAA;GACrB,CAAA,EACK,GAhFK,MAAM,GAgFX;EAEhB,CAAC,GAEF,CAAC,UACA,oBAAC,oBAAD;GACE,SAAS,CAAC,QAAQ,MAAM,UAAU,MAAM,KAAK,CAAC;GAC9C,OAAO,MAAM,OACV,QACE,UACC,CAAC,SAAS,KAAK,KAAK,CAAC,MAAM,UAAU,CAAC,MAAM,SAAS,MAAM,GAAG,CAClE,CAAC,CACA,KAAK,WAAW;IACf,KAAK,MAAM;IACX,OAAO,QAAQ,KAAK;IACpB,MAAM,OAAO,KAAK;IAClB,MAAM,OAAO,KAAK;GACpB,EAAE;GACJ,QAAQ,QAAQ;IACd,YAAY,UAAU;IACtB,MAAM,cAAc,CAAC,GAAG,OAAO,GAAG,GAAG,IAAI;GAC3C;EACD,CAAA,CAEA;;AAET"}
|
|
1
|
+
{"version":3,"file":"DataTableFilterBar.js","names":[],"sources":["../../src/table/DataTableFilterBar.tsx"],"sourcesContent":["import type { ZObject, ZType } from \"alepha\";\nimport type { FormModel } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { FilterSlot } from \"../core/FilterSlot.tsx\";\nimport { Control } from \"../form/Control.tsx\";\nimport { DataTableFilterAdd } from \"./DataTableFilterAdd.tsx\";\nimport { DataTableFilterControl } from \"./DataTableFilterControl.tsx\";\nimport type {\n DataTableFilterFieldOptions,\n DataTableFilterPreset,\n} from \"./dataTableTypes.ts\";\nimport { useDataTableFilterModel } from \"./useDataTableFilterModel.tsx\";\n\nexport interface DataTableFilterBarProps {\n /**\n * The table's filter form. Every `key` below names one of its fields, and\n * so does every operator key.\n */\n form: FormModel<ZObject>;\n\n /**\n * Every filter, in declaration order: the order the bar draws them in and\n * the add menu lists them in.\n */\n fields: DataTableFilterBarField[];\n\n /**\n * Which filters are on the bar. The table's state, not the bar's, because\n * three things write it: this bar, Reset filters and persistence.\n *\n * A locked field is drawn whether or not it is in here.\n */\n shown: readonly string[];\n\n /**\n * The shown filters changed. `act` is true for the reader's own add or\n * remove, and false when a filter joined the bar because it holds a value:\n * that is not the reader choosing anything, and must not be stored.\n */\n onShownChange: (shown: string[], act: boolean) => void;\n\n /**\n * `\"dialog\"` draws every filter, each like a locked field, and no add menu:\n * the phone dialog is already the on-demand step, and a menu per filter\n * behind that button would be a second one.\n */\n variant?: \"bar\" | \"dialog\";\n}\n\n/**\n * The filter bar `DataTable` draws from `filters.fields`: the locked filters\n * (the search box), then the filters the reader put on the bar, then the menu\n * that adds one.\n *\n * **Which filters start on the bar is the field's `mode`.** An `optional`\n * field, the default, is off it until the reader adds it; a `default` field\n * is on it from the start and removable; a `locked` field is always there and\n * never removable. Showing every filter a table supports spends the width of\n * the bar on questions nobody has asked; four boxes reading \"Any status\",\n * \"Any team\", \"Any role\" say only that those columns exist.\n *\n * ⚠️ **A filter holding a value, or a non-default operator, is always on the\n * bar**, whatever its mode and however it got the value: restored from\n * persistence, read from a shared link, carried across a remount. Keyed on\n * the shown state alone, the bar came back empty while the table stayed\n * filtered, and \"Add filters\" handed back a filter that was already set. The\n * same holds for `hidden`: an empty hidden field is off the bar and out of the\n * menu, and a hidden field narrowing the list is still drawn, or the list\n * would be narrowed with nothing on screen saying why.\n *\n * **Operators** are optional per field, and each is a field of its own in the\n * filters schema, `<key>Op` unless `operatorKey` says otherwise. The backend\n * must declare the same key and values; a default operator sends no key at\n * all. See `DataTableFilterOperator` for why it is one switch rather than an\n * EQUAL toggle beside an OR/AND one.\n *\n * Internal to the table: a table given `fields` and no `filters.render`\n * mounts it, in the toolbar and in the phone dialog.\n *\n * Built and settled on the `apps/ui` showcase (`/blocks/data-table/basic`) in #Q2308.\n */\nexport const DataTableFilterBar = (props: DataTableFilterBarProps) => {\n const { tr } = useI18n();\n const model = useDataTableFilterModel(props.form);\n const {\n values,\n inputs,\n isSet,\n holds,\n isLocked,\n operatorKeyOf,\n operatorOf,\n kindOf,\n placeholderOf,\n labelOf,\n iconOf,\n clearField,\n } = model;\n const dialog = props.variant === \"dialog\";\n const shown = props.shown;\n const root = useRef<HTMLDivElement>(null);\n // The filter to open once React has put it on screen. A REF, not state: the\n // effect below both reads and clears it, and clearing it with `setState`\n // inside an effect is a cascading render. Nothing renders from it.\n const pendingOpen = useRef<string | undefined>(undefined);\n // Which filters held a value at the last commit - see the operator effect.\n const heldValue = useRef<Record<string, boolean>>({});\n\n useEffect(() => {\n const key = pendingOpen.current;\n if (!key) return;\n pendingOpen.current = undefined;\n // ⚠️ Opening the new filter has to happen from OUT HERE, after the render\n // that mounts it: inside the menu's click handler the control does not\n // exist yet. Driven through the DOM because `Control` exposes no\n // imperative \"open\" - a combobox owns that state, and a date range's\n // popover owns its own. A text filter has no list, so it is focused\n // instead. Scoped to this bar, so two tables on one page cannot open each\n // other's filters.\n const slot = root.current?.querySelector(`[data-filter=\"${key}\"]`);\n const trigger = slot?.querySelector<HTMLElement>(\n '[data-slot=\"combobox-trigger\"], [data-slot=\"date-trigger\"]',\n );\n if (trigger) {\n trigger.click();\n return;\n }\n slot?.querySelector<HTMLInputElement>('[data-slot=\"input\"]')?.focus();\n }, [shown]);\n\n useEffect(() => {\n // The other way a value empties: unticked inside the list, or cleared by\n // a locked field's own cross, rather than cleared by the button. Only on\n // the transition from set to empty, so a reader who picks \"is not\" BEFORE\n // picking a value keeps it, and a persisted operator survives the mount\n // it is restored on.\n for (const field of props.fields) {\n const set = isSet(field.key);\n const operatorKey = operatorKeyOf(field);\n if (\n field.operators &&\n heldValue.current[field.key] &&\n !set &&\n values[operatorKey] !== undefined\n ) {\n inputs[operatorKey]?.set(undefined);\n }\n heldValue.current[field.key] = set;\n }\n }, [values]);\n\n // A field holding a value or an operator joins `shown` the moment it is\n // seen - see the docblock. Folded INTO `shown` rather than drawn as\n // `shown ∪ set`, because a filter visible only for holding a value would\n // unmount the instant the reader emptied it, list open and cursor on it.\n // Locked fields are drawn regardless and never join it, and the dialog\n // draws every field.\n const unshown = dialog\n ? []\n : props.fields\n .filter(\n (field) =>\n !isLocked(field) && holds(field) && !shown.includes(field.key),\n )\n .map((field) => field.key);\n\n // The table's state cannot be set from this component's render, so it is\n // set in a LAYOUT effect: React flushes that update synchronously, before\n // the browser paints, so no frame shows the bar without the filter. The\n // guard stops it looping - it only fires while something is missing, and\n // the update adds exactly that.\n useLayoutEffect(() => {\n if (unshown.length > 0) {\n props.onShownChange([...shown, ...unshown], false);\n }\n });\n\n const drawn = (field: DataTableFilterBarField): boolean => {\n if (field.hidden && !holds(field)) return false;\n if (dialog || isLocked(field)) return true;\n return shown.includes(field.key);\n };\n\n // Locked first, in declaration order, then the shown ones in the order they\n // joined the bar: an added filter goes to the END, beside the \"+\" that\n // brought it, not back to its declared slot. Added D, C, B, A reads\n // D C B A. The dialog keeps the declaration as it is: nothing there is\n // added or removed.\n const rank = (field: DataTableFilterBarField) => {\n const index = shown.indexOf(field.key);\n return index === -1 ? Number.MAX_SAFE_INTEGER : index;\n };\n const ordered = dialog\n ? props.fields\n : [\n ...props.fields.filter((field) => isLocked(field)),\n ...props.fields\n .filter((field) => !isLocked(field))\n .sort((a, b) => rank(a) - rank(b)),\n ];\n\n return (\n // `contents`, so the slots are items of the table's own wrapping row (and\n // of the phone dialog's grid) exactly as a caller's bare fragment is.\n <div ref={root} className=\"contents\">\n {ordered\n .filter((field) => drawn(field))\n .map((field) => {\n // In the dialog every filter is drawn like a locked one: no\n // clear-and-remove button, the control's own cross resets it.\n const removable = !dialog && !isLocked(field);\n const operator = operatorOf(field);\n const label = labelOf(field);\n return (\n <FilterSlot key={field.key}>\n <div data-filter={field.key}>\n <DataTableFilterControl\n label={label}\n active={isSet(field.key)}\n // A cross empties a filter holding a value; a funnel-x\n // removes an empty one. `active` picks between the two.\n // A locked filter is given neither, so it keeps the cross\n // inside its own field.\n onClear={removable ? () => clearField(field) : undefined}\n onRemove={\n removable\n ? () => {\n clearField(field);\n props.onShownChange(\n shown.filter((key) => key !== field.key),\n true,\n );\n }\n : undefined\n }\n >\n <Control\n {...model.controlPropsOf(field)}\n // The filter's name, as the control's accessible name:\n // an empty select says only its placeholder, and a set\n // one only its value. A name the caller gave wins.\n inputProps={{\n \"aria-label\": label,\n // A text filter is as wide as its placeholder. The slot\n // grows from its content, and an input's content width\n // is its `size` in characters (20 by default), so a\n // long placeholder was cut at the slot's minimum.\n ...(kindOf(field) === \"text\"\n ? {\n size: Math.max(\n 20,\n placeholderOf(field)?.length ?? 0,\n ),\n }\n : {}),\n ...field.control?.inputProps,\n }}\n // The filter's name, and a non-default operator, muted in\n // front of the value: \"Status: not Active\". An empty\n // select draws no prefix; its placeholder names it. The\n // colon is a catalog entry because French spaces it.\n triggerPrefix={[\n tr(\"dataTable.filterName\", {\n default: `${label}:`,\n args: [label],\n }),\n operator?.prefix,\n ]\n .filter(Boolean)\n .join(\" \")}\n />\n </DataTableFilterControl>\n </div>\n </FilterSlot>\n );\n })}\n\n {!dialog && (\n <DataTableFilterAdd\n labeled={!ordered.some((field) => drawn(field))}\n items={props.fields\n .filter(\n (field) =>\n !isLocked(field) && !field.hidden && !shown.includes(field.key),\n )\n .map((field) => ({\n key: field.key,\n label: labelOf(field),\n icon: iconOf(field),\n type: kindOf(field),\n }))}\n onAdd={(key) => {\n pendingOpen.current = key;\n props.onShownChange([...shown, key], true);\n }}\n />\n )}\n </div>\n );\n};\n\n/**\n * One filter of the bar: a field of `filters.fields` with its key, as the\n * table hands it over. `schema` is the one the table read at mount, and gives\n * the options of an enum and the kind the add menu names.\n */\nexport interface DataTableFilterBarField extends DataTableFilterFieldOptions {\n /**\n * The form field this filter writes.\n */\n key: string;\n schema?: ZType;\n preset?: DataTableFilterPreset;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,MAAa,sBAAsB,UAAmC;CACpE,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,QAAQ,wBAAwB,MAAM,IAAI;CAChD,MAAM,EACJ,QACA,QACA,OACA,OACA,UACA,eACA,YACA,QACA,eACA,SACA,QACA,eACE;CACJ,MAAM,SAAS,MAAM,YAAY;CACjC,MAAM,QAAQ,MAAM;CACpB,MAAM,OAAO,OAAuB,IAAI;CAIxC,MAAM,cAAc,OAA2B,KAAA,CAAS;CAExD,MAAM,YAAY,OAAgC,CAAC,CAAC;CAEpD,gBAAgB;EACd,MAAM,MAAM,YAAY;EACxB,IAAI,CAAC,KAAK;EACV,YAAY,UAAU,KAAA;EAQtB,MAAM,OAAO,KAAK,SAAS,cAAc,iBAAiB,IAAI,GAAG;EACjE,MAAM,UAAU,MAAM,cACpB,gEACF;EACA,IAAI,SAAS;GACX,QAAQ,MAAM;GACd;EACF;EACA,MAAM,cAAgC,uBAAqB,CAAC,EAAE,MAAM;CACtE,GAAG,CAAC,KAAK,CAAC;CAEV,gBAAgB;EAMd,KAAK,MAAM,SAAS,MAAM,QAAQ;GAChC,MAAM,MAAM,MAAM,MAAM,GAAG;GAC3B,MAAM,cAAc,cAAc,KAAK;GACvC,IACE,MAAM,aACN,UAAU,QAAQ,MAA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