@wordrhyme/auto-crud 1.23.3 → 1.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -15,12 +15,12 @@ let clsx = require("clsx");
15
15
  clsx = require_position.__toESM(clsx);
16
16
  let tailwind_merge = require("tailwind-merge");
17
17
  tailwind_merge = require_position.__toESM(tailwind_merge);
18
+ let __tanstack_react_table = require("@tanstack/react-table");
19
+ __tanstack_react_table = require_position.__toESM(__tanstack_react_table);
18
20
  let __wordrhyme_shadcn_ui = require("@wordrhyme/shadcn-ui");
19
21
  __wordrhyme_shadcn_ui = require_position.__toESM(__wordrhyme_shadcn_ui);
20
22
  let nanoid = require("nanoid");
21
23
  nanoid = require_position.__toESM(nanoid);
22
- let __tanstack_react_table = require("@tanstack/react-table");
23
- __tanstack_react_table = require_position.__toESM(__tanstack_react_table);
24
24
  let __wordrhyme_ui = require("@wordrhyme/ui");
25
25
  __wordrhyme_ui = require_position.__toESM(__wordrhyme_ui);
26
26
  let __wordrhyme_formily_shadcn = require("@wordrhyme/formily-shadcn");
@@ -252,6 +252,34 @@ const dataTableConfig = {
252
252
 
253
253
  //#endregion
254
254
  //#region src/lib/data-table.ts
255
+ function readRowId(row, idKey) {
256
+ const value = row[idKey];
257
+ return value === null || value === void 0 ? void 0 : String(value);
258
+ }
259
+ function getSelectedTableRows(table) {
260
+ return table.options.meta?.selectedRows ?? table.getFilteredSelectedRowModel().rows;
261
+ }
262
+ function createRowSelectionScope() {
263
+ const listeners$1 = /* @__PURE__ */ new Set();
264
+ return {
265
+ onDelete(listener) {
266
+ listeners$1.add(listener);
267
+ return () => {
268
+ listeners$1.delete(listener);
269
+ };
270
+ },
271
+ notifyDeleted(row) {
272
+ listeners$1.forEach((listener) => listener(row));
273
+ }
274
+ };
275
+ }
276
+ /** Infer a total only when the loaded page accounts for the whole result. */
277
+ function getSelectionTotal(table, loadedPageIndex = table.getState().pagination.pageIndex) {
278
+ if (table.options.rowCount !== void 0 || !table.options.manualPagination) return table.getRowCount();
279
+ const pages = table.getPageCount();
280
+ if (pages === 0) return 0;
281
+ if (pages === 1 && loadedPageIndex === 0) return table.getFilteredRowModel().rows.length;
282
+ }
255
283
  function getColumnPinningStyle({ column, withBorder = false }) {
256
284
  const isPinned = column.getIsPinned();
257
285
  const isLastLeftPinnedColumn = isPinned === "left" && column.getIsLastColumn("left");
@@ -2587,7 +2615,7 @@ const enUSPagination = {
2587
2615
  selected: (count, total) => `${count} of ${total} row(s) selected.`,
2588
2616
  total: (count) => `Total: ${count}`,
2589
2617
  rowsPerPage: "Rows per page",
2590
- page: (page, total) => `Page ${page} of ${total}`,
2618
+ page: (page, total, pageText) => `Page ${pageText ?? page} of ${total}`,
2591
2619
  pageJump: "Go to page",
2592
2620
  firstPage: "Go to first page",
2593
2621
  previousPage: "Go to previous page",
@@ -2665,7 +2693,7 @@ const zhCN = {
2665
2693
  selected: (count, total) => `已选择 ${total} 条中的 ${count} 条`,
2666
2694
  total: (count) => `共 ${count} 条`,
2667
2695
  rowsPerPage: "每页条数",
2668
- page: (page, total) => `第 ${page} / ${total} 页`,
2696
+ page: (page, total, pageText) => `第 ${pageText ?? page} / ${total} 页`,
2669
2697
  pageJump: "跳转到页",
2670
2698
  firstPage: "首页",
2671
2699
  previousPage: "上一页",
@@ -2852,7 +2880,7 @@ const jaJP = {
2852
2880
  selected: (count, total) => `${total} 件中 ${count} 件を選択`,
2853
2881
  total: (count) => `合計: ${count}`,
2854
2882
  rowsPerPage: "ページあたりの行数",
2855
- page: (page, total) => `${page} / ${total} ページ`,
2883
+ page: (page, total, pageText) => `${pageText ?? page} / ${total} ページ`,
2856
2884
  pageJump: "ページへ移動",
2857
2885
  firstPage: "最初のページ",
2858
2886
  previousPage: "前のページ",
@@ -2966,7 +2994,7 @@ const koKR = {
2966
2994
  selected: (count, total) => `${total}개 중 ${count}개 선택됨`,
2967
2995
  total: (count) => `전체: ${count}`,
2968
2996
  rowsPerPage: "페이지당 행 수",
2969
- page: (page, total) => `${page} / ${total} 페이지`,
2997
+ page: (page, total, pageText) => `${pageText ?? page} / ${total} 페이지`,
2970
2998
  pageJump: "페이지로 이동",
2971
2999
  firstPage: "첫 페이지",
2972
3000
  previousPage: "이전 페이지",
@@ -3080,7 +3108,7 @@ const frFR = {
3080
3108
  selected: (count, total) => `${count} ligne(s) sélectionnée(s) sur ${total}.`,
3081
3109
  total: (count) => `Total : ${count}`,
3082
3110
  rowsPerPage: "Lignes par page",
3083
- page: (page, total) => `Page ${page} sur ${total}`,
3111
+ page: (page, total, pageText) => `Page ${pageText ?? page} sur ${total}`,
3084
3112
  pageJump: "Aller à la page",
3085
3113
  firstPage: "Première page",
3086
3114
  previousPage: "Page précédente",
@@ -3194,7 +3222,7 @@ const deDE = {
3194
3222
  selected: (count, total) => `${count} von ${total} Zeile(n) ausgewählt.`,
3195
3223
  total: (count) => `Gesamt: ${count}`,
3196
3224
  rowsPerPage: "Zeilen pro Seite",
3197
- page: (page, total) => `Seite ${page} von ${total}`,
3225
+ page: (page, total, pageText) => `Seite ${pageText ?? page} von ${total}`,
3198
3226
  pageJump: "Zur Seite springen",
3199
3227
  firstPage: "Erste Seite",
3200
3228
  previousPage: "Vorherige Seite",
@@ -3308,7 +3336,7 @@ const esES = {
3308
3336
  selected: (count, total) => `${count} de ${total} fila(s) seleccionada(s).`,
3309
3337
  total: (count) => `Total: ${count}`,
3310
3338
  rowsPerPage: "Filas por página",
3311
- page: (page, total) => `Página ${page} de ${total}`,
3339
+ page: (page, total, pageText) => `Página ${pageText ?? page} de ${total}`,
3312
3340
  pageJump: "Ir a la página",
3313
3341
  firstPage: "Primera página",
3314
3342
  previousPage: "Página anterior",
@@ -3441,11 +3469,16 @@ function DataTablePagination({ table, pageSizeOptions = [
3441
3469
  const hideExtras = responsive && !hasSpace;
3442
3470
  const hiddenClass = hideExtras ? "absolute invisible pointer-events-none left-0 top-0" : void 0;
3443
3471
  const { pageIndex, pageSize } = table.getState().pagination;
3472
+ const currentPage = pageIndex + 1;
3444
3473
  const pageCount = table.getPageCount();
3445
3474
  const knownPageCount = pageCount >= 0;
3475
+ const pageSlot = "{currentPage}";
3476
+ const [beforeInput, afterInput] = showPageJump && knownPageCount ? locale.page(currentPage, pageCount, pageSlot).split(pageSlot) : [];
3446
3477
  const canJump = Number.isFinite(pageCount) && pageCount > 0;
3447
3478
  const canGoNext = table.getCanNextPage() && (knownPageCount || table.options.data.length >= pageSize);
3448
3479
  const total = table.options.rowCount ?? (table.options.manualPagination ? void 0 : table.getRowCount());
3480
+ const selectedCount = getSelectedTableRows(table).length;
3481
+ const selectionTotal = table.options.meta?.selectedRows !== void 0 ? getSelectionTotal(table) : table.getFilteredRowModel().rows.length;
3449
3482
  (0, react.useEffect)(() => {
3450
3483
  if (!responsive || !container.current || !summary.current || !controls.current || !navigation.current) return;
3451
3484
  if (typeof ResizeObserver === "undefined") return;
@@ -3459,7 +3492,8 @@ function DataTablePagination({ table, pageSizeOptions = [
3459
3492
  const children = Array.from(node.children);
3460
3493
  return children.reduce((sum, child) => {
3461
3494
  const style = getComputedStyle(child);
3462
- return sum + (child === nav || child === jump ? width(child) : child.getBoundingClientRect().width) + (parseFloat(style.marginLeft) || 0) + (parseFloat(style.marginRight) || 0);
3495
+ const measured = jump?.parentElement === child ? jump : child;
3496
+ return sum + (child === nav ? width(nav) : measured.getBoundingClientRect().width) + (parseFloat(style.marginLeft) || 0) + (parseFloat(style.marginRight) || 0);
3463
3497
  }, 0) + Math.max(0, children.length - 1) * gap(node);
3464
3498
  };
3465
3499
  const measure = () => {
@@ -3477,7 +3511,7 @@ function DataTablePagination({ table, pageSizeOptions = [
3477
3511
  ...info.children,
3478
3512
  ...group.children,
3479
3513
  ...nav.children,
3480
- ...jump?.children ?? []
3514
+ ...jump ? [jump] : []
3481
3515
  ]) observer.observe(node);
3482
3516
  measure();
3483
3517
  return () => observer.disconnect();
@@ -3494,9 +3528,13 @@ function DataTablePagination({ table, pageSizeOptions = [
3494
3528
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3495
3529
  ref: summary,
3496
3530
  className: "flex flex-1 items-center gap-6 whitespace-nowrap text-muted-foreground text-sm",
3497
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: locale.selected(table.getFilteredSelectedRowModel().rows.length, table.getFilteredRowModel().rows.length) }), total !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: locale.total(total) })]
3531
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: selectionTotal === void 0 || selectedCount > selectionTotal ? (locale.selectedCount ?? enUSActionBar.selected)(selectedCount) : locale.selected(selectedCount, selectionTotal) }), total !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: locale.total(total) })]
3498
3532
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3499
3533
  ref: controls,
3534
+ onPointerDownCapture: (event) => {
3535
+ const input = event.currentTarget.ownerDocument.activeElement;
3536
+ if (input instanceof HTMLInputElement && pageJump.current?.contains(input) && event.target instanceof Element && event.target.closest("button")) input.value = String(currentPage);
3537
+ },
3500
3538
  className: cn("flex items-center gap-4 sm:gap-6 lg:gap-8", responsive ? "flex-row flex-wrap justify-center whitespace-nowrap [&>*]:shrink-0" : "flex-col-reverse sm:flex-row"),
3501
3539
  children: [
3502
3540
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
@@ -3521,44 +3559,41 @@ function DataTablePagination({ table, pageSizeOptions = [
3521
3559
  })]
3522
3560
  })]
3523
3561
  }),
3524
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3562
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3525
3563
  className: "flex items-center justify-center font-medium text-sm",
3526
- children: knownPageCount ? locale.page(pageIndex + 1, pageCount) : pageIndex + 1
3527
- }),
3528
- showPageJump && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3529
- ref: pageJump,
3530
- className: hideExtras ? "pointer-events-none absolute inset-x-0 top-0 invisible overflow-hidden" : void 0,
3531
- "aria-hidden": hideExtras || void 0,
3532
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
3533
- className: "flex w-max items-center gap-2",
3534
- onSubmit: (event) => {
3535
- event.preventDefault();
3536
- const page = Number(new FormData(event.currentTarget).get("page"));
3537
- if (canJump && Number.isInteger(page) && page >= 1 && page <= pageCount) table.setPageIndex(page - 1);
3538
- },
3539
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
3540
- className: "flex items-center gap-2 whitespace-nowrap text-sm",
3541
- children: [jumpLabel, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn.Input, {
3542
- name: "page",
3543
- type: "number",
3544
- min: 1,
3545
- max: canJump ? pageCount : void 0,
3546
- step: 1,
3547
- required: true,
3548
- defaultValue: pageIndex + 1,
3549
- disabled: !canJump,
3550
- className: "h-8 w-20"
3551
- }, `${pageIndex}-${pageCount}`)]
3552
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn.Button, {
3553
- type: "submit",
3554
- variant: "outline",
3555
- size: "icon",
3556
- className: "size-8",
3557
- disabled: !canJump,
3558
- "aria-label": jumpLabel,
3559
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ChevronRight, {})
3560
- })]
3561
- })
3564
+ children: [(!showPageJump || hideExtras) && (knownPageCount ? locale.page(currentPage, pageCount) : currentPage), showPageJump && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3565
+ ref: pageJump,
3566
+ className: cn("flex w-max items-center gap-1 whitespace-nowrap", hiddenClass),
3567
+ "aria-hidden": hideExtras || void 0,
3568
+ children: [
3569
+ beforeInput,
3570
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn.Input, {
3571
+ "aria-label": jumpLabel,
3572
+ type: "text",
3573
+ inputMode: "numeric",
3574
+ enterKeyHint: "go",
3575
+ defaultValue: currentPage,
3576
+ disabled: !canJump || hideExtras,
3577
+ className: "h-8 min-w-10 px-1 text-center tabular-nums",
3578
+ style: { width: `calc(${String(pageCount).length}ch + 1rem)` },
3579
+ onFocus: (event) => event.currentTarget.select(),
3580
+ onKeyDown: (event) => {
3581
+ if (event.key !== "Enter" && event.key !== "Escape") return;
3582
+ event.preventDefault();
3583
+ if (event.key === "Escape") event.currentTarget.value = String(currentPage);
3584
+ event.currentTarget.blur();
3585
+ },
3586
+ onBlur: (event) => {
3587
+ const input = event.currentTarget;
3588
+ const value = input.value;
3589
+ const page = Number(value);
3590
+ input.value = String(currentPage);
3591
+ if (/^\d+$/.test(value) && page >= 1 && page <= pageCount && page !== currentPage) table.setPageIndex(page - 1);
3592
+ }
3593
+ }, `${pageIndex}-${pageCount}`),
3594
+ afterInput
3595
+ ]
3596
+ })]
3562
3597
  }),
3563
3598
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3564
3599
  ref: navigation,
@@ -3811,7 +3846,7 @@ function DataTable({ table, actionBar, pagination, expandedRow, rowFooter, child
3811
3846
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(DataTablePagination, {
3812
3847
  table,
3813
3848
  ...pagination
3814
- }), actionBar && table.getFilteredSelectedRowModel().rows.length > 0 && actionBar]
3849
+ }), actionBar && getSelectedTableRows(table).length > 0 && actionBar]
3815
3850
  })
3816
3851
  ]
3817
3852
  });
@@ -5993,12 +6028,14 @@ function createSelectColumn() {
5993
6028
  id: "select",
5994
6029
  header: ({ table }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn.Checkbox, {
5995
6030
  "aria-label": "Select all",
6031
+ disabled: !table.getPaginationRowModel().flatRows.some((row) => row.getCanSelect()),
5996
6032
  className: "translate-y-0.5",
5997
6033
  checked: table.getIsAllPageRowsSelected() || table.getIsSomePageRowsSelected() && "indeterminate",
5998
6034
  onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
5999
6035
  }),
6000
6036
  cell: ({ row }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn.Checkbox, {
6001
6037
  "aria-label": "Select row",
6038
+ disabled: !row.getCanSelect(),
6002
6039
  className: "translate-y-0.5",
6003
6040
  checked: row.getIsSelected(),
6004
6041
  onCheckedChange: (value) => row.toggleSelected(!!value)
@@ -7340,7 +7377,7 @@ function getExportColumnIds(table) {
7340
7377
  function exportTableToCSV(table, opts = {}) {
7341
7378
  const { filename = "table", excludeColumns = [], onlySelected = false } = opts;
7342
7379
  const headers = getExportColumnIds(table).filter((id) => !excludeColumns.includes(id));
7343
- downloadCSV([headers.join(","), ...(onlySelected ? table.getFilteredSelectedRowModel().rows : table.getRowModel().rows).map((row) => headers.map((header) => {
7380
+ downloadCSV([headers.join(","), ...(onlySelected ? getSelectedTableRows(table) : table.getRowModel().rows).map((row) => headers.map((header) => {
7344
7381
  const cellValue = row.getValue(header);
7345
7382
  return typeof cellValue === "string" ? `"${cellValue.replace(/"/g, "\"\"")}"` : cellValue;
7346
7383
  }).join(","))].join("\n"), filename);
@@ -7389,14 +7426,14 @@ function AutoTableActionBar({ table, locale: localeProp, onDeleteSelected, onUpd
7389
7426
  ...enUSActionBar,
7390
7427
  ...localeProp
7391
7428
  }), [localeProp]);
7392
- const rows = table.getFilteredSelectedRowModel().rows;
7429
+ const rows = getSelectedTableRows(table);
7393
7430
  const selectedRows = react.useMemo(() => rows.map((row) => row.original), [rows]);
7394
7431
  const [deleteDialogOpen, setDeleteDialogOpen] = react.useState(false);
7395
7432
  react.useEffect(() => {
7396
7433
  if (selectedRows.length === 0) setDeleteDialogOpen(false);
7397
7434
  }, [selectedRows.length]);
7398
7435
  const clearSelection = react.useCallback(() => {
7399
- table.toggleAllRowsSelected(false);
7436
+ table.resetRowSelection(true);
7400
7437
  }, [table]);
7401
7438
  const actionContext = react.useMemo(() => ({
7402
7439
  rows: selectedRows,
@@ -7578,20 +7615,27 @@ function AutoTableActionBar({ table, locale: localeProp, onDeleteSelected, onUpd
7578
7615
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(__wordrhyme_shadcn_ui.ActionBar, {
7579
7616
  open: rows.length > 0,
7580
7617
  onOpenChange,
7618
+ className: "w-max max-w-[calc(100%-2rem)]",
7581
7619
  children: [
7582
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(__wordrhyme_shadcn_ui.ActionBarSelection, { children: [
7583
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
7584
- className: "font-medium",
7585
- children: locale.selected(rows.length)
7586
- }),
7587
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn_ui.ActionBarSeparator, {}),
7588
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn_ui.ActionBarClose, {
7589
- "aria-label": locale.clearSelection,
7590
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.X, {})
7591
- })
7592
- ] }),
7593
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn_ui.ActionBarSeparator, {}),
7594
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn_ui.ActionBarGroup, { children: renderedActions })
7620
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(__wordrhyme_shadcn_ui.ActionBarSelection, {
7621
+ className: "shrink-0 whitespace-nowrap",
7622
+ children: [
7623
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
7624
+ className: "font-medium",
7625
+ children: locale.selected(rows.length)
7626
+ }),
7627
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn_ui.ActionBarSeparator, {}),
7628
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn_ui.ActionBarClose, {
7629
+ "aria-label": locale.clearSelection,
7630
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.X, {})
7631
+ })
7632
+ ]
7633
+ }),
7634
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn_ui.ActionBarSeparator, { className: "shrink-0" }),
7635
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(__wordrhyme_shadcn_ui.ActionBarGroup, {
7636
+ className: "-m-1 min-w-0 overflow-x-auto p-1 [&>*]:shrink-0",
7637
+ children: renderedActions
7638
+ })
7595
7639
  ]
7596
7640
  });
7597
7641
  }
@@ -7803,7 +7847,7 @@ const filterModeConfig = {
7803
7847
  tooltip: "Linear-style command filters"
7804
7848
  }
7805
7849
  };
7806
- function AutoTable({ resourceId, views, schema, data, getRowId, expandedRow, rowFooter, defaultExpanded = false, pageCount = 1, pagination, total, overrides, classNames, enableRowSelection = true, queryKeys, initialColumnVisibility, exclude, filterOnly, actions, pinnedColumns, filterMode, search = false, batchSearch, filterState, toolbarExtra, locale = enUSTableControls, onDeleteSelected, onUpdateSelected, batchUpdateFields, actionBarExtra, actionBarLocale, actionBarActions, deleteConfirmation, initialSorting, enableExport = true, showDefaultExport = true, onSelectedCountChange, onSelectedRowsChange, getSelectedRows, exportTableRef }) {
7850
+ function AutoTable({ resourceId, views, schema, data, getRowId, idKey = "id", selectionScope, pagePending = false, expandedRow, rowFooter, defaultExpanded = false, pageCount = 1, pagination, total, overrides, classNames, enableRowSelection = true, queryKeys, initialColumnVisibility, exclude, filterOnly, actions, pinnedColumns, filterMode, search = false, batchSearch, filterState, toolbarExtra, locale = enUSTableControls, onDeleteSelected, onUpdateSelected, batchUpdateFields, actionBarExtra, actionBarLocale, actionBarActions, deleteConfirmation, initialSorting, enableExport = true, showDefaultExport = true, onSelectedCountChange, onSelectedRowsChange, getSelectedRows, exportTableRef }) {
7807
7851
  const inheritedResourceId = (0, react.useContext)(CrudResourceContext);
7808
7852
  const activeResourceId = resourceId ?? inheritedResourceId;
7809
7853
  const viewsEnabled = views ?? false;
@@ -7924,12 +7968,28 @@ function AutoTable({ resourceId, views, schema, data, getRowId, expandedRow, row
7924
7968
  actions
7925
7969
  ]);
7926
7970
  const expandedRowModel = (0, react.useMemo)(() => (0, __tanstack_react_table.getExpandedRowModel)(), []);
7971
+ const resolveRowId = (0, react.useMemo)(() => {
7972
+ if (getRowId) return getRowId;
7973
+ const anonymousRows = /* @__PURE__ */ new WeakMap();
7974
+ let nextId = 0;
7975
+ return (record) => {
7976
+ const key = readRowId(record, idKey);
7977
+ if (key !== void 0) return `key:${key}`;
7978
+ let id = anonymousRows.get(record);
7979
+ if (id === void 0) {
7980
+ id = `local:${nextId++}`;
7981
+ anonymousRows.set(record, id);
7982
+ }
7983
+ return id;
7984
+ };
7985
+ }, [getRowId, idKey]);
7986
+ const keyedData = (0, react.useMemo)(() => data.slice(), [data, idKey]);
7927
7987
  const { table, shallow, debounceMs, throttleMs } = useDataTable({
7928
- data,
7988
+ data: keyedData,
7929
7989
  columns,
7930
7990
  queryKeys,
7931
- enableRowSelection,
7932
- getRowId,
7991
+ enableRowSelection: enableRowSelection && !pagePending,
7992
+ getRowId: resolveRowId,
7933
7993
  getRowCanExpand: () => enableExpansion,
7934
7994
  getExpandedRowModel: enableExpansion ? expandedRowModel : void 0,
7935
7995
  autoResetExpanded: defaultExpanded ? false : void 0,
@@ -7961,14 +8021,95 @@ function AutoTable({ resourceId, views, schema, data, getRowId, expandedRow, row
7961
8021
  exportTableRef.current = null;
7962
8022
  };
7963
8023
  }, [table, exportTableRef]);
7964
- const rowSelection = table.getState().rowSelection;
7965
- const columnFilters = table.getState().columnFilters;
7966
- const selectedRows = (0, react.useMemo)(() => table.getFilteredSelectedRowModel().rows.map((row) => row.original), [
8024
+ const [filters] = useReadableFilters(columns, { state: filterState });
8025
+ const [query] = useQueryState("search", parseAsString.withDefault(""));
8026
+ const [join] = useQueryState(queryKeys?.joinOperator ?? "joinOperator", parseAsString.withDefault("and"));
8027
+ const resultSet = (0, react.useMemo)(() => selectionScope ?? JSON.stringify([
8028
+ query.trim(),
8029
+ join,
8030
+ filterSignature(filters),
8031
+ batchSearch?.filter
8032
+ ]), [
8033
+ selectionScope,
8034
+ query,
8035
+ join,
8036
+ filters,
8037
+ batchSearch?.filter
8038
+ ]);
8039
+ const scope = (0, react.useMemo)(() => ({
8040
+ activeResourceId,
8041
+ idKey,
8042
+ enableRowSelection,
8043
+ resultSet
8044
+ }), [
8045
+ activeResourceId,
8046
+ idKey,
8047
+ enableRowSelection,
8048
+ resultSet
8049
+ ]);
8050
+ const [previousScope, setPreviousScope] = (0, react.useState)(scope);
8051
+ if (previousScope !== scope) {
8052
+ setPreviousScope(scope);
8053
+ table.resetRowSelection(true);
8054
+ }
8055
+ const { rowSelection, pagination: { pageIndex } } = table.getState();
8056
+ const pageSelection = table.getFilteredSelectedRowModel().rows;
8057
+ const retained = (0, react.useRef)([]);
8058
+ const loadedPage = (0, react.useRef)(null);
8059
+ const loadedIndex = loadedPage.current?.data === data ? loadedPage.current.index : pageIndex;
8060
+ const allRowsLoaded = !pagePending && getSelectionTotal(table, loadedIndex) === data.length;
8061
+ const selectedTableRows = (0, react.useMemo)(() => {
8062
+ if (pagePending) return retained.current.filter((row) => rowSelection[row.id]);
8063
+ if (allRowsLoaded || pageSelection.length === Object.keys(rowSelection).length) return pageSelection;
8064
+ const rows = /* @__PURE__ */ new Map();
8065
+ for (const row of retained.current) if (rowSelection[row.id] && (getRowId || row.original[idKey] != null)) rows.set(row.id, row);
8066
+ for (const row of pageSelection) rows.set(row.id, row);
8067
+ return Array.from(rows.values());
8068
+ }, [
8069
+ allRowsLoaded,
8070
+ pagePending,
8071
+ pageSelection,
8072
+ rowSelection,
8073
+ getRowId,
8074
+ idKey
8075
+ ]);
8076
+ table.setOptions((options) => ({
8077
+ ...options,
8078
+ meta: {
8079
+ ...options.meta,
8080
+ selectedRows: selectedTableRows
8081
+ }
8082
+ }));
8083
+ (0, react.useLayoutEffect)(() => {
8084
+ loadedPage.current = pagePending ? null : {
8085
+ data,
8086
+ index: loadedIndex
8087
+ };
8088
+ retained.current = selectedTableRows;
8089
+ if (!pagePending && Object.keys(rowSelection).length > selectedTableRows.length) table.setRowSelection(Object.fromEntries(selectedTableRows.map((row) => [row.id, true])));
8090
+ }, [
7967
8091
  table,
7968
8092
  rowSelection,
7969
- columnFilters,
7970
- data
8093
+ selectedTableRows,
8094
+ pagePending,
8095
+ data,
8096
+ loadedIndex
8097
+ ]);
8098
+ (0, react.useLayoutEffect)(() => selectionScope?.onDelete((deleted) => {
8099
+ const id = readRowId(deleted, idKey);
8100
+ const rows = retained.current.filter((row) => row.original === deleted || id !== void 0 && readRowId(row.original, idKey) === id);
8101
+ if (!rows.length) return;
8102
+ table.setRowSelection((current) => {
8103
+ const next = { ...current };
8104
+ for (const row of rows) delete next[row.id];
8105
+ return next;
8106
+ });
8107
+ }), [
8108
+ selectionScope,
8109
+ table,
8110
+ idKey
7971
8111
  ]);
8112
+ const selectedRows = (0, react.useMemo)(() => selectedTableRows.map((row) => row.original), [selectedTableRows]);
7972
8113
  const getSelectedRowsFn = (0, react.useCallback)(() => selectedRows, [selectedRows]);
7973
8114
  (0, react.useEffect)(() => {
7974
8115
  if (getSelectedRows) getSelectedRows.current = getSelectedRowsFn;
@@ -8085,20 +8226,28 @@ function AutoTable({ resourceId, views, schema, data, getRowId, expandedRow, row
8085
8226
  });
8086
8227
  const state = table.getState();
8087
8228
  const tableContent = (0, react.useMemo)(() => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DataTable, {
8088
- pagination,
8229
+ pagination: {
8230
+ ...pagination,
8231
+ locale: {
8232
+ selectedCount: actionBarLocale?.selected,
8233
+ ...pagination?.locale
8234
+ }
8235
+ },
8089
8236
  table,
8090
8237
  classNames,
8091
8238
  expandedRow,
8092
8239
  rowFooter
8093
8240
  }), [
8094
8241
  table,
8095
- data,
8242
+ keyedData,
8243
+ pagePending,
8096
8244
  columns,
8097
8245
  getRowId,
8098
8246
  pageCount,
8099
8247
  total,
8100
8248
  stableInitialState,
8101
8249
  pagination,
8250
+ actionBarLocale?.selected,
8102
8251
  classNames,
8103
8252
  expandedRow,
8104
8253
  rowFooter,
@@ -9665,10 +9814,6 @@ function resolveOwnerBatchActions(actions) {
9665
9814
  function isUnifiedActionsConfig(actions) {
9666
9815
  return typeof actions === "object" && actions !== null && !Array.isArray(actions);
9667
9816
  }
9668
- function readRowId(row, idKey) {
9669
- const value = row[idKey];
9670
- return value === null || value === void 0 ? void 0 : String(value);
9671
- }
9672
9817
  function readRowIds(rows, idKey) {
9673
9818
  return rows.flatMap((row) => {
9674
9819
  const value = readRowId(row, idKey);
@@ -9819,6 +9964,7 @@ function useDynamicFilterOptions(fields) {
9819
9964
  const searchValuesRef = react.useRef({});
9820
9965
  const sourceEntriesByFieldRef = react.useRef({});
9821
9966
  const timersRef = react.useRef({});
9967
+ const loadedSourcesRef = react.useRef(/* @__PURE__ */ new Map());
9822
9968
  const sourceEntries = react.useMemo(() => {
9823
9969
  if (!fields) return [];
9824
9970
  return Object.entries(fields).flatMap(([field, config]) => {
@@ -9940,9 +10086,10 @@ function useDynamicFilterOptions(fields) {
9940
10086
  setFieldHasMore(field, hasMore);
9941
10087
  setFieldLoading(field, false);
9942
10088
  }, (error) => {
9943
- if (controller?.signal.aborted) return;
10089
+ if (requestVersionsRef.current[field] !== requestVersion || controller?.signal.aborted) return;
9944
10090
  console.warn(`[AutoCrud] Failed to load filter data source "${source.key}".`, error);
9945
10091
  if (!append) {
10092
+ loadedSourcesRef.current.delete(field);
9946
10093
  setFieldOptions(field, []);
9947
10094
  setFieldHasMore(field, false);
9948
10095
  pageByFieldRef.current = {
@@ -9973,6 +10120,7 @@ function useDynamicFilterOptions(fields) {
9973
10120
  }, []);
9974
10121
  react.useEffect(() => {
9975
10122
  if (sourceEntries.length === 0) {
10123
+ loadedSourcesRef.current.clear();
9976
10124
  hasMoreByFieldRef.current = {};
9977
10125
  loadingByFieldRef.current = {};
9978
10126
  optionsByFieldRef.current = {};
@@ -9988,7 +10136,19 @@ function useDynamicFilterOptions(fields) {
9988
10136
  removeInactiveFieldState(setLoadingByField, loadingByFieldRef, activeFields);
9989
10137
  removeInactiveFieldState(setOptionsByField, optionsByFieldRef, activeFields);
9990
10138
  for (const field of Object.keys(controllersRef.current)) if (!activeFields.has(field)) clearFieldRequest(field);
9991
- for (const { field } of sourceEntries) loadFieldOptions(field);
10139
+ for (const field of loadedSourcesRef.current.keys()) if (!activeFields.has(field)) loadedSourcesRef.current.delete(field);
10140
+ for (const { field, source } of sourceEntries) {
10141
+ const entry = dataSources.get(source.key);
10142
+ const search = entry?.search ? searchValues[field] ?? "" : void 0;
10143
+ const previous = loadedSourcesRef.current.get(field);
10144
+ if (previous?.key === source.key && previous.entry === entry && previous.search === search) continue;
10145
+ loadedSourcesRef.current.set(field, {
10146
+ key: source.key,
10147
+ entry,
10148
+ search
10149
+ });
10150
+ loadFieldOptions(field);
10151
+ }
9992
10152
  }, [
9993
10153
  clearFieldRequest,
9994
10154
  loadFieldOptions,
@@ -9999,6 +10159,7 @@ function useDynamicFilterOptions(fields) {
9999
10159
  ]);
10000
10160
  react.useEffect(() => () => {
10001
10161
  for (const field of Object.keys(controllersRef.current)) clearFieldRequest(field);
10162
+ loadedSourcesRef.current.clear();
10002
10163
  }, [clearFieldRequest]);
10003
10164
  return react.useMemo(() => ({
10004
10165
  hasMoreByField,
@@ -10065,7 +10226,7 @@ function useDynamicResolveOptions(fields, rows, hiddenColumns) {
10065
10226
  const requestVersion = requestVersionRef.current + 1;
10066
10227
  requestVersionRef.current = requestVersion;
10067
10228
  if (sourceEntries.length === 0) {
10068
- setOptionsByField({});
10229
+ setOptionsByField((current) => Object.keys(current).length === 0 ? current : {});
10069
10230
  return;
10070
10231
  }
10071
10232
  let cancelled = false;
@@ -10094,7 +10255,7 @@ function useDynamicResolveOptions(fields, rows, hiddenColumns) {
10094
10255
  if (cached.length > 0) next[entry.field] = cached;
10095
10256
  }
10096
10257
  for (const [field, options] of Object.entries(current)) if (activeFields.has(field) && !next[field]) next[field] = options;
10097
- return next;
10258
+ return Object.keys(next).length === 0 && Object.keys(current).length === 0 ? current : next;
10098
10259
  });
10099
10260
  for (const sourceEntry of sourceEntries) {
10100
10261
  const entry = dataSources.get(sourceEntry.source.key);
@@ -10861,7 +11022,7 @@ function AutoCrudTable({ id, title, description, schema, resource, fields, table
10861
11022
  ...action$1,
10862
11023
  onClick: (_rows, { table }) => {
10863
11024
  const headers = getExportColumnIds(table).filter((key) => key !== "select" && key !== "actions" && !denyFields?.includes(key));
10864
- exportAllToCSV(table.getFilteredSelectedRowModel().rows.map((row) => formatExportRow(row.original, resolvedFields, Object.fromEntries(headers.map((key) => [key, row.getValue(key)])))), {
11025
+ exportAllToCSV(getSelectedTableRows(table).map((row) => formatExportRow(row.original, resolvedFields, Object.fromEntries(headers.map((key) => [key, row.getValue(key)])))), {
10865
11026
  filename: "table",
10866
11027
  headers
10867
11028
  });
@@ -11173,6 +11334,9 @@ function AutoCrudTable({ id, title, description, schema, resource, fields, table
11173
11334
  enableRowSelection: tableConfig?.enableRowSelection,
11174
11335
  initialColumnVisibility: tableConfig?.initialColumnVisibility,
11175
11336
  getRowId: tableConfig?.getRowId,
11337
+ idKey: resourceIdKey,
11338
+ selectionScope: resource.tableData.selectionScope,
11339
+ pagePending: resource.tableData.isLoading || resource.tableData.isPlaceholderData || Boolean(resource.tableData.error) && resource.tableData.data.length === 0,
11176
11340
  expandedRow: tableConfig?.expandedRow,
11177
11341
  rowFooter: tableConfig?.rowFooter,
11178
11342
  defaultExpanded: tableConfig?.defaultExpanded,
@@ -12117,25 +12281,49 @@ function useAutoCrudResource({ router, queryKeys, schema, query: queryTransform,
12117
12281
  const [filtersReady, setFiltersReady] = (0, react.useState)(!metadataPending);
12118
12282
  (0, react.useEffect)(() => setFiltersReady(!metadataPending), [metadataPending]);
12119
12283
  const listReady = !metadataPending && filtersReady;
12284
+ const firstPageParams = (0, react.useMemo)(() => ({
12285
+ page: 1,
12286
+ perPage: 10,
12287
+ sort: defaultSorting,
12288
+ filters,
12289
+ joinOperator,
12290
+ ...search.trim() ? { search: search.trim() } : {}
12291
+ }), [
12292
+ defaultSorting,
12293
+ filters,
12294
+ joinOperator,
12295
+ search
12296
+ ]);
12297
+ const firstPageInput = (0, react.useMemo)(() => queryTransform ? queryTransform({ ...firstPageParams }) : firstPageParams, [queryTransform, firstPageParams]);
12120
12298
  const queryInput = (0, react.useMemo)(() => {
12299
+ if (page === firstPageParams.page && perPage === firstPageParams.perPage && sort === firstPageParams.sort) return firstPageInput;
12121
12300
  const autoParams = {
12301
+ ...firstPageParams,
12122
12302
  page,
12123
12303
  perPage,
12124
- sort,
12125
- filters,
12126
- joinOperator,
12127
- ...search.trim() ? { search: search.trim() } : {}
12304
+ sort
12128
12305
  };
12129
12306
  return queryTransform ? queryTransform(autoParams) : autoParams;
12130
12307
  }, [
12131
12308
  page,
12132
12309
  perPage,
12133
12310
  sort,
12134
- filters,
12135
- joinOperator,
12136
- search,
12311
+ firstPageParams,
12312
+ firstPageInput,
12137
12313
  queryTransform
12138
12314
  ]);
12315
+ const previousCriteria = (0, react.useRef)(void 0);
12316
+ const selectionCriteria = (0, react.useMemo)(() => {
12317
+ const criteria = firstPageInput?.filters === filters ? {
12318
+ ...firstPageInput,
12319
+ filters: filterSignature(filters)
12320
+ } : firstPageInput;
12321
+ return (0, __tanstack_react_query.replaceEqualDeep)(previousCriteria.current, criteria);
12322
+ }, [firstPageInput, filters]);
12323
+ (0, react.useEffect)(() => {
12324
+ previousCriteria.current = selectionCriteria;
12325
+ }, [selectionCriteria]);
12326
+ const selectionScope = (0, react.useMemo)(() => createRowSelectionScope(), [router.list, selectionCriteria]);
12139
12327
  const hasReadyListData = (0, react.useRef)(false);
12140
12328
  const listQuery = router.list.useQuery(queryInput, {
12141
12329
  ...queryContext !== void 0 ? { trpc: { context: queryContext } } : {},
@@ -12318,6 +12506,7 @@ function useAutoCrudResource({ router, queryKeys, schema, query: queryTransform,
12318
12506
  return;
12319
12507
  }
12320
12508
  toast$1.success("删除成功");
12509
+ selectionScope.notifyDeleted(modal.selected);
12321
12510
  dispatch({
12322
12511
  type: "DELETE_SUCCEEDED",
12323
12512
  payload: modal.selected
@@ -12329,7 +12518,8 @@ function useAutoCrudResource({ router, queryKeys, schema, query: queryTransform,
12329
12518
  idKey,
12330
12519
  deleteMutation,
12331
12520
  refreshResource,
12332
- toast$1
12521
+ toast$1,
12522
+ selectionScope
12333
12523
  ]);
12334
12524
  const deleteMany = (0, react.useCallback)((rows) => {
12335
12525
  const currentHooks = hooksRef.current;
@@ -12432,6 +12622,8 @@ function useAutoCrudResource({ router, queryKeys, schema, query: queryTransform,
12432
12622
  filterState,
12433
12623
  tableData: {
12434
12624
  data: tableRows,
12625
+ selectionScope,
12626
+ isPlaceholderData: Boolean(listQuery.isPlaceholderData),
12435
12627
  countSource: {
12436
12628
  navigationKey: listData && !listQuery.isPlaceholderData ? navigationKey : null,
12437
12629
  refreshVersion,