@wordrhyme/auto-crud 1.5.7 → 1.6.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/index.js CHANGED
@@ -383,13 +383,15 @@ function hasValidCanonicalDateTimePrefix(value) {
383
383
  const match = canonicalDateTimePrefixPattern.exec(value);
384
384
  return !match || isValidCalendarDate(match[1], match[2], match[3]);
385
385
  }
386
+ function getDateLocaleOptions() {
387
+ return hostDateFormatters[hostDateFormatters.length - 1]?.options;
388
+ }
386
389
  /**
387
- * Register the host's process-wide date presentation policy without coupling
388
- * AutoCrud to locale or timezone selection. The returned cleanup removes only
389
- * this registration, so overlapping registrations may be disposed out of order.
390
+ * Register the host's date formatter and optional calendar locale policy.
391
+ * Cleanup removes only this registration, including out-of-order cleanup.
390
392
  * Passing undefined clears every registration.
391
393
  */
392
- function setDateFormatter(formatter) {
394
+ function setDateFormatter(formatter, options) {
393
395
  if (formatter === void 0) {
394
396
  const hadFormatter = hostDateFormatters.length > 0;
395
397
  hostDateFormatters = [];
@@ -398,15 +400,16 @@ function setDateFormatter(formatter) {
398
400
  }
399
401
  const registration = {
400
402
  formatter,
403
+ ...options ? { options } : {},
401
404
  token: Symbol("date-formatter")
402
405
  };
403
406
  hostDateFormatters.push(registration);
404
407
  notifyDateFormatterChange();
405
408
  return () => {
406
- const currentFormatter = getHostDateFormatter();
409
+ const currentRegistration = hostDateFormatters[hostDateFormatters.length - 1];
407
410
  const previousLength = hostDateFormatters.length;
408
411
  hostDateFormatters = hostDateFormatters.filter(({ token }) => token !== registration.token);
409
- if (hostDateFormatters.length !== previousLength && getHostDateFormatter() !== currentFormatter) notifyDateFormatterChange();
412
+ if (hostDateFormatters.length !== previousLength && hostDateFormatters[hostDateFormatters.length - 1] !== currentRegistration) notifyDateFormatterChange();
410
413
  };
411
414
  }
412
415
  function formatDate(date, opts = {}, preset) {
@@ -1006,6 +1009,71 @@ function useDebouncedCallback(callback, delay) {
1006
1009
  }, [handleCallback, delay]);
1007
1010
  }
1008
1011
 
1012
+ //#endregion
1013
+ //#region src/lib/calendar-date.ts
1014
+ /** Calendar days are wall dates, never instants in the host's time zone. */
1015
+ function serializeCalendarDate(date) {
1016
+ return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
1017
+ }
1018
+ function parseCalendarDate(value) {
1019
+ if (value === void 0 || value === "") return void 0;
1020
+ if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
1021
+ const date$1 = /* @__PURE__ */ new Date(`${value}T00:00:00`);
1022
+ return !Number.isNaN(date$1.getTime()) && serializeCalendarDate(date$1) === value ? date$1 : void 0;
1023
+ }
1024
+ const date = new Date(Number(value));
1025
+ return Number.isNaN(date.getTime()) ? void 0 : date;
1026
+ }
1027
+ function calendarPresentation() {
1028
+ const localeOptions = getDateLocaleOptions();
1029
+ const locale = localeOptions?.locale ?? "en-US";
1030
+ const chinese = locale.toLowerCase().startsWith("zh");
1031
+ const localeInfo = new Intl.Locale(locale);
1032
+ const firstDay = localeInfo.getWeekInfo?.().firstDay ?? localeInfo.weekInfo?.firstDay ?? (chinese ? 1 : 7);
1033
+ const format = (date, options) => new Intl.DateTimeFormat(locale, {
1034
+ ...options,
1035
+ timeZone: "UTC"
1036
+ }).format(/* @__PURE__ */ new Date(`${serializeCalendarDate(date)}T00:00:00Z`));
1037
+ return {
1038
+ locale,
1039
+ weekStartsOn: firstDay % 7,
1040
+ formatDate: (date) => {
1041
+ if (!localeOptions) return formatDate(date);
1042
+ return date ? format(date, {
1043
+ year: "numeric",
1044
+ month: "long",
1045
+ day: "numeric"
1046
+ }) : "";
1047
+ },
1048
+ clearLabel: (title) => chinese ? `清除${title ?? ""}筛选` : `Clear ${title ?? ""} filter`,
1049
+ formatters: {
1050
+ formatCaption: (date) => format(date, {
1051
+ year: "numeric",
1052
+ month: "long"
1053
+ }),
1054
+ formatMonthDropdown: (date) => format(date, { month: "long" }),
1055
+ formatWeekdayName: (date) => format(date, { weekday: "short" })
1056
+ },
1057
+ labels: {
1058
+ labelNext: () => chinese ? "下个月" : "Go to the Next Month",
1059
+ labelPrevious: () => chinese ? "上个月" : "Go to the Previous Month",
1060
+ labelMonthDropdown: () => chinese ? "选择月份" : "Choose the Month",
1061
+ labelYearDropdown: () => chinese ? "选择年份" : "Choose the Year",
1062
+ labelGrid: (date) => format(date, {
1063
+ year: "numeric",
1064
+ month: "long"
1065
+ }),
1066
+ labelWeekday: (date) => format(date, { weekday: "long" }),
1067
+ labelDayButton: (date) => format(date, {
1068
+ year: "numeric",
1069
+ month: "long",
1070
+ day: "numeric",
1071
+ weekday: "long"
1072
+ })
1073
+ }
1074
+ };
1075
+ }
1076
+
1009
1077
  //#endregion
1010
1078
  //#region src/components/data-table/data-table-filter-list.tsx
1011
1079
  const DEBOUNCE_MS$2 = 300;
@@ -1177,6 +1245,7 @@ function DataTableFilterList({ table, debounceMs = DEBOUNCE_MS$2, throttleMs = T
1177
1245
  });
1178
1246
  }
1179
1247
  function DataTableFilterItem$1({ filter, index: index$1, filterItemId, joinOperator, setJoinOperator, columns, onFilterUpdate, onFilterRemove }) {
1248
+ useDateFormatterVersion();
1180
1249
  const [showFieldSelector, setShowFieldSelector] = React.useState(false);
1181
1250
  const [showOperatorSelector, setShowOperatorSelector] = React.useState(false);
1182
1251
  const [showValueSelector, setShowValueSelector] = React.useState(false);
@@ -1465,10 +1534,10 @@ function onFilterInputRender$1({ filter, inputId, column, columnMeta, onFilterUp
1465
1534
  case "dateRange": {
1466
1535
  const inputListboxId = `${inputId}-listbox`;
1467
1536
  const dateValue = Array.isArray(filter.value) ? filter.value.filter(Boolean) : [filter.value, filter.value].filter(Boolean);
1468
- const startDate = dateValue[0] ? new Date(Number(dateValue[0])) : void 0;
1469
- const endDate = dateValue[1] ? new Date(Number(dateValue[1])) : void 0;
1537
+ const startDate = dateValue[0] ? parseCalendarDate(dateValue[0]) : void 0;
1538
+ const endDate = dateValue[1] ? parseCalendarDate(dateValue[1]) : void 0;
1470
1539
  const isSameDate = startDate && endDate && startDate.toDateString() === endDate.toDateString();
1471
- const displayValue = filter.operator === "isBetween" && dateValue.length === 2 && !isSameDate ? `${formatDate(startDate, { month: "short" })} - ${formatDate(endDate, { month: "short" })}` : startDate ? formatDate(startDate, { month: "short" }) : "Pick a date";
1540
+ const displayValue = filter.operator === "isBetween" && dateValue.length === 2 && !isSameDate ? `${calendarPresentation().formatDate(startDate)} - ${calendarPresentation().formatDate(endDate)}` : startDate ? calendarPresentation().formatDate(startDate) : "Pick a date";
1472
1541
  return /* @__PURE__ */ jsxs(Popover, {
1473
1542
  open: showValueSelector,
1474
1543
  onOpenChange: setShowValueSelector,
@@ -1491,28 +1560,36 @@ function onFilterInputRender$1({ filter, inputId, column, columnMeta, onFilterUp
1491
1560
  align: "start",
1492
1561
  className: "w-auto p-0",
1493
1562
  children: filter.operator === "isBetween" ? /* @__PURE__ */ jsx(Calendar, {
1563
+ lang: calendarPresentation().locale,
1564
+ weekStartsOn: calendarPresentation().weekStartsOn,
1565
+ formatters: calendarPresentation().formatters,
1566
+ labels: calendarPresentation().labels,
1494
1567
  "aria-label": `Select ${columnMeta?.label} date range`,
1495
1568
  autoFocus: true,
1496
1569
  captionLayout: "dropdown",
1497
1570
  mode: "range",
1498
1571
  selected: dateValue.length === 2 ? {
1499
- from: new Date(Number(dateValue[0])),
1500
- to: new Date(Number(dateValue[1]))
1572
+ from: parseCalendarDate(dateValue[0]),
1573
+ to: parseCalendarDate(dateValue[1])
1501
1574
  } : {
1502
1575
  from: /* @__PURE__ */ new Date(),
1503
1576
  to: /* @__PURE__ */ new Date()
1504
1577
  },
1505
1578
  onSelect: (date) => {
1506
- onFilterUpdate(filter.filterId, { value: date ? [(date.from?.getTime() ?? "").toString(), (date.to?.getTime() ?? "").toString()] : [] });
1579
+ onFilterUpdate(filter.filterId, { value: date ? [date.from ? serializeCalendarDate(date.from) : "", date.to ? serializeCalendarDate(date.to) : ""] : [] });
1507
1580
  }
1508
1581
  }) : /* @__PURE__ */ jsx(Calendar, {
1582
+ lang: calendarPresentation().locale,
1583
+ weekStartsOn: calendarPresentation().weekStartsOn,
1584
+ formatters: calendarPresentation().formatters,
1585
+ labels: calendarPresentation().labels,
1509
1586
  "aria-label": `Select ${columnMeta?.label} date`,
1510
1587
  autoFocus: true,
1511
1588
  captionLayout: "dropdown",
1512
1589
  mode: "single",
1513
- selected: dateValue[0] ? new Date(Number(dateValue[0])) : void 0,
1590
+ selected: dateValue[0] ? parseCalendarDate(dateValue[0]) : void 0,
1514
1591
  onSelect: (date) => {
1515
- onFilterUpdate(filter.filterId, { value: (date?.getTime() ?? "").toString() });
1592
+ onFilterUpdate(filter.filterId, { value: date ? serializeCalendarDate(date) : "" });
1516
1593
  setShowValueSelector(false);
1517
1594
  }
1518
1595
  })
@@ -1724,6 +1801,7 @@ function DataTableFilterMenu({ table, debounceMs = DEBOUNCE_MS$1, throttleMs = T
1724
1801
  }
1725
1802
  function DataTableFilterItem({ filter, filterItemId, columns, onFilterUpdate, onFilterRemove }) {
1726
1803
  {
1804
+ useDateFormatterVersion();
1727
1805
  const [showFieldSelector, setShowFieldSelector] = React.useState(false);
1728
1806
  const [showOperatorSelector, setShowOperatorSelector] = React.useState(false);
1729
1807
  const [showValueSelector, setShowValueSelector] = React.useState(false);
@@ -1834,6 +1912,7 @@ function DataTableFilterItem({ filter, filterItemId, columns, onFilterUpdate, on
1834
1912
  }
1835
1913
  }
1836
1914
  function FilterValueSelector({ column, value, onSelect }) {
1915
+ useDateFormatterVersion();
1837
1916
  switch (column.columnDef.meta?.variant ?? "text") {
1838
1917
  case "boolean": return /* @__PURE__ */ jsxs(CommandGroup, { children: [/* @__PURE__ */ jsx(CommandItem, {
1839
1918
  value: "true",
@@ -1862,11 +1941,15 @@ function FilterValueSelector({ column, value, onSelect }) {
1862
1941
  }, option.value)) });
1863
1942
  case "date":
1864
1943
  case "dateRange": return /* @__PURE__ */ jsx(Calendar, {
1944
+ lang: calendarPresentation().locale,
1945
+ weekStartsOn: calendarPresentation().weekStartsOn,
1946
+ formatters: calendarPresentation().formatters,
1947
+ labels: calendarPresentation().labels,
1865
1948
  autoFocus: true,
1866
1949
  captionLayout: "dropdown",
1867
1950
  mode: "single",
1868
- selected: value ? new Date(value) : void 0,
1869
- onSelect: (date) => onSelect(date?.getTime().toString() ?? "")
1951
+ selected: parseCalendarDate(value),
1952
+ onSelect: (date) => onSelect(date ? serializeCalendarDate(date) : "")
1870
1953
  });
1871
1954
  default: {
1872
1955
  const isEmpty = !value.trim();
@@ -2020,10 +2103,10 @@ function onFilterInputRender({ filter, column, inputId, onFilterUpdate, showValu
2020
2103
  case "dateRange": {
2021
2104
  const inputListboxId = `${inputId}-listbox`;
2022
2105
  const dateValue = Array.isArray(filter.value) ? filter.value.filter(Boolean) : [filter.value, filter.value].filter(Boolean);
2023
- const startDate = dateValue[0] ? new Date(Number(dateValue[0])) : void 0;
2024
- const endDate = dateValue[1] ? new Date(Number(dateValue[1])) : void 0;
2106
+ const startDate = dateValue[0] ? parseCalendarDate(dateValue[0]) : void 0;
2107
+ const endDate = dateValue[1] ? parseCalendarDate(dateValue[1]) : void 0;
2025
2108
  const isSameDate = startDate && endDate && startDate.toDateString() === endDate.toDateString();
2026
- const displayValue = filter.operator === "isBetween" && dateValue.length === 2 && !isSameDate ? `${formatDate(startDate, { month: "short" })} - ${formatDate(endDate, { month: "short" })}` : startDate ? formatDate(startDate, { month: "short" }) : "Pick date...";
2109
+ const displayValue = filter.operator === "isBetween" && dateValue.length === 2 && !isSameDate ? `${calendarPresentation().formatDate(startDate)} - ${calendarPresentation().formatDate(endDate)}` : startDate ? calendarPresentation().formatDate(startDate) : "Pick date...";
2027
2110
  return /* @__PURE__ */ jsxs(Popover, {
2028
2111
  open: showValueSelector,
2029
2112
  onOpenChange: setShowValueSelector,
@@ -2045,26 +2128,34 @@ function onFilterInputRender({ filter, column, inputId, onFilterUpdate, showValu
2045
2128
  align: "start",
2046
2129
  className: "w-auto p-0",
2047
2130
  children: filter.operator === "isBetween" ? /* @__PURE__ */ jsx(Calendar, {
2131
+ lang: calendarPresentation().locale,
2132
+ weekStartsOn: calendarPresentation().weekStartsOn,
2133
+ formatters: calendarPresentation().formatters,
2134
+ labels: calendarPresentation().labels,
2048
2135
  autoFocus: true,
2049
2136
  captionLayout: "dropdown",
2050
2137
  mode: "range",
2051
2138
  selected: dateValue.length === 2 ? {
2052
- from: new Date(Number(dateValue[0])),
2053
- to: new Date(Number(dateValue[1]))
2139
+ from: parseCalendarDate(dateValue[0]),
2140
+ to: parseCalendarDate(dateValue[1])
2054
2141
  } : {
2055
2142
  from: /* @__PURE__ */ new Date(),
2056
2143
  to: /* @__PURE__ */ new Date()
2057
2144
  },
2058
2145
  onSelect: (date) => {
2059
- onFilterUpdate(filter.filterId, { value: date ? [(date.from?.getTime() ?? "").toString(), (date.to?.getTime() ?? "").toString()] : [] });
2146
+ onFilterUpdate(filter.filterId, { value: date ? [date.from ? serializeCalendarDate(date.from) : "", date.to ? serializeCalendarDate(date.to) : ""] : [] });
2060
2147
  }
2061
2148
  }) : /* @__PURE__ */ jsx(Calendar, {
2149
+ lang: calendarPresentation().locale,
2150
+ weekStartsOn: calendarPresentation().weekStartsOn,
2151
+ formatters: calendarPresentation().formatters,
2152
+ labels: calendarPresentation().labels,
2062
2153
  autoFocus: true,
2063
2154
  captionLayout: "dropdown",
2064
2155
  mode: "single",
2065
- selected: dateValue[0] ? new Date(Number(dateValue[0])) : void 0,
2156
+ selected: dateValue[0] ? parseCalendarDate(dateValue[0]) : void 0,
2066
2157
  onSelect: (date) => {
2067
- onFilterUpdate(filter.filterId, { value: (date?.getTime() ?? "").toString() });
2158
+ onFilterUpdate(filter.filterId, { value: date ? serializeCalendarDate(date) : "" });
2068
2159
  }
2069
2160
  })
2070
2161
  })]
@@ -2813,11 +2904,17 @@ function SimpleSliderFilter({ title, range, unit, value, onChange }) {
2813
2904
  })] });
2814
2905
  }
2815
2906
  function SimpleDateFilter({ title, multiple, value, onChange }) {
2907
+ const [open, setOpen] = React.useState(false);
2908
+ const commit = (next) => {
2909
+ setOpen(false);
2910
+ onChange(next);
2911
+ };
2912
+ const formatterVersion = useDateFormatterVersion();
2913
+ const presentation = React.useMemo(() => calendarPresentation(), [formatterVersion]);
2914
+ const { formatDate: formatDate$1 } = presentation;
2816
2915
  const timestamps = Array.isArray(value) ? value : value ? [value] : [];
2817
- const fromTimestamp = timestamps[0] ? Number(timestamps[0]) : void 0;
2818
- const toTimestamp = timestamps[1] ? Number(timestamps[1]) : void 0;
2819
- const fromDate = fromTimestamp ? new Date(fromTimestamp) : void 0;
2820
- const toDate = toTimestamp ? new Date(toTimestamp) : void 0;
2916
+ const fromDate = parseCalendarDate(timestamps[0]);
2917
+ const toDate = parseCalendarDate(timestamps[1]);
2821
2918
  const [localRange, setLocalRange] = React.useState({
2822
2919
  from: void 0,
2823
2920
  to: void 0
@@ -2836,100 +2933,114 @@ function SimpleDateFilter({ title, multiple, value, onChange }) {
2836
2933
  const hasValue = multiple ? fromDate || toDate : fromDate;
2837
2934
  const onReset = (e) => {
2838
2935
  e.stopPropagation();
2839
- onChange(void 0);
2936
+ commit(void 0);
2840
2937
  };
2841
- const label = multiple ? fromDate && toDate ? `${formatDate(fromDate)} - ${formatDate(toDate)}` : fromDate ? formatDate(fromDate) : void 0 : fromDate ? formatDate(fromDate) : void 0;
2842
- return /* @__PURE__ */ jsxs(Popover, { children: [/* @__PURE__ */ jsx(PopoverTrigger, {
2843
- asChild: true,
2844
- children: /* @__PURE__ */ jsxs(Button, {
2845
- variant: "outline",
2846
- size: "sm",
2847
- className: "border-dashed font-normal",
2848
- children: [
2849
- hasValue ? /* @__PURE__ */ jsx("div", {
2850
- role: "button",
2851
- tabIndex: 0,
2852
- className: "rounded-sm opacity-70 hover:opacity-100",
2853
- onClick: onReset,
2854
- onKeyDown: (e) => {
2855
- if (e.key === "Enter" || e.key === " ") {
2856
- e.preventDefault();
2857
- onReset(e);
2938
+ const label = multiple ? fromDate && toDate ? `${formatDate$1(fromDate)} - ${formatDate$1(toDate)}` : fromDate ? formatDate$1(fromDate) : void 0 : fromDate ? formatDate$1(fromDate) : void 0;
2939
+ return /* @__PURE__ */ jsxs(Popover, {
2940
+ open,
2941
+ onOpenChange: setOpen,
2942
+ children: [/* @__PURE__ */ jsx(PopoverTrigger, {
2943
+ asChild: true,
2944
+ children: /* @__PURE__ */ jsxs(Button, {
2945
+ variant: "outline",
2946
+ size: "sm",
2947
+ className: "border-dashed font-normal",
2948
+ children: [
2949
+ hasValue ? /* @__PURE__ */ jsx("div", {
2950
+ role: "button",
2951
+ tabIndex: 0,
2952
+ className: "rounded-sm opacity-70 hover:opacity-100",
2953
+ onClick: onReset,
2954
+ onKeyDown: (e) => {
2955
+ if (e.key === "Enter" || e.key === " ") {
2956
+ e.preventDefault();
2957
+ onReset(e);
2958
+ }
2959
+ },
2960
+ children: /* @__PURE__ */ jsx(XCircle, {})
2961
+ }) : /* @__PURE__ */ jsx(CalendarIcon, {}),
2962
+ /* @__PURE__ */ jsx("span", { children: title }),
2963
+ label && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Separator, {
2964
+ orientation: "vertical",
2965
+ className: "mx-0.5 h-4"
2966
+ }), /* @__PURE__ */ jsx("span", { children: label })] })
2967
+ ]
2968
+ })
2969
+ }), /* @__PURE__ */ jsx(PopoverContent, {
2970
+ className: "w-auto p-0",
2971
+ align: "start",
2972
+ children: multiple ? /* @__PURE__ */ jsx(Calendar, {
2973
+ lang: presentation.locale,
2974
+ weekStartsOn: presentation.weekStartsOn,
2975
+ formatters: presentation.formatters,
2976
+ labels: presentation.labels,
2977
+ defaultMonth: fromDate,
2978
+ autoFocus: true,
2979
+ captionLayout: "dropdown",
2980
+ mode: "range",
2981
+ selected: localRange,
2982
+ onSelect: (range) => {
2983
+ if (!range?.from && !range?.to) {
2984
+ commit(void 0);
2985
+ setLocalRange({
2986
+ from: void 0,
2987
+ to: void 0
2988
+ });
2989
+ return;
2990
+ }
2991
+ const hadFrom = Boolean(localRange.from);
2992
+ const hadTo = Boolean(localRange.to);
2993
+ const from = range.from?.getTime();
2994
+ const to = range.to?.getTime();
2995
+ if (from != null && to != null && from === to) {
2996
+ if (!hadFrom || hadTo) {
2997
+ setLocalRange({
2998
+ from: range.from,
2999
+ to: void 0
3000
+ });
3001
+ return;
2858
3002
  }
2859
- },
2860
- children: /* @__PURE__ */ jsx(XCircle, {})
2861
- }) : /* @__PURE__ */ jsx(CalendarIcon, {}),
2862
- /* @__PURE__ */ jsx("span", { children: title }),
2863
- label && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Separator, {
2864
- orientation: "vertical",
2865
- className: "mx-0.5 h-4"
2866
- }), /* @__PURE__ */ jsx("span", { children: label })] })
2867
- ]
2868
- })
2869
- }), /* @__PURE__ */ jsx(PopoverContent, {
2870
- className: "w-auto p-0",
2871
- align: "start",
2872
- children: multiple ? /* @__PURE__ */ jsx(Calendar, {
2873
- autoFocus: true,
2874
- captionLayout: "dropdown",
2875
- mode: "range",
2876
- selected: localRange,
2877
- onSelect: (range) => {
2878
- if (!range?.from && !range?.to) {
2879
- onChange(void 0);
2880
- setLocalRange({
2881
- from: void 0,
2882
- to: void 0
2883
- });
2884
- return;
2885
- }
2886
- const hadFrom = Boolean(localRange.from);
2887
- const hadTo = Boolean(localRange.to);
2888
- const from = range.from?.getTime();
2889
- const to = range.to?.getTime();
2890
- if (from != null && to != null && from === to) {
2891
- if (!hadFrom || hadTo) {
3003
+ if (hadFrom && !hadTo && localRange.from) {
3004
+ const prevFrom = localRange.from;
3005
+ const newDate = range.from;
3006
+ const [finalFrom, finalTo] = prevFrom <= newDate ? [prevFrom, newDate] : [newDate, prevFrom];
3007
+ setLocalRange({
3008
+ from: finalFrom,
3009
+ to: finalTo
3010
+ });
3011
+ commit([serializeCalendarDate(finalFrom), serializeCalendarDate(finalTo)]);
3012
+ return;
3013
+ }
3014
+ }
3015
+ if (from != null && to != null && from !== to) {
2892
3016
  setLocalRange({
2893
3017
  from: range.from,
2894
- to: void 0
3018
+ to: range.to
2895
3019
  });
3020
+ commit([serializeCalendarDate(range.from), serializeCalendarDate(range.to)]);
2896
3021
  return;
2897
3022
  }
2898
- if (hadFrom && !hadTo && localRange.from) {
2899
- const prevFrom = localRange.from;
2900
- const newDate = range.from;
2901
- const [finalFrom, finalTo] = prevFrom <= newDate ? [prevFrom, newDate] : [newDate, prevFrom];
3023
+ if (range.from && !range.to) {
2902
3024
  setLocalRange({
2903
- from: finalFrom,
2904
- to: finalTo
3025
+ from: range.from,
3026
+ to: void 0
2905
3027
  });
2906
- onChange([finalFrom.getTime().toString(), finalTo.getTime().toString()]);
2907
3028
  return;
2908
3029
  }
2909
3030
  }
2910
- if (from != null && to != null && from !== to) {
2911
- setLocalRange({
2912
- from: range.from,
2913
- to: range.to
2914
- });
2915
- onChange([range.from.getTime().toString(), range.to.getTime().toString()]);
2916
- return;
2917
- }
2918
- if (range.from && !range.to) {
2919
- setLocalRange({
2920
- from: range.from,
2921
- to: void 0
2922
- });
2923
- return;
2924
- }
2925
- }
2926
- }) : /* @__PURE__ */ jsx(Calendar, {
2927
- captionLayout: "dropdown",
2928
- mode: "single",
2929
- selected: fromDate,
2930
- onSelect: (date) => onChange(date ? date.getTime().toString() : void 0)
2931
- })
2932
- })] });
3031
+ }) : /* @__PURE__ */ jsx(Calendar, {
3032
+ lang: presentation.locale,
3033
+ weekStartsOn: presentation.weekStartsOn,
3034
+ formatters: presentation.formatters,
3035
+ labels: presentation.labels,
3036
+ defaultMonth: fromDate,
3037
+ captionLayout: "dropdown",
3038
+ mode: "single",
3039
+ selected: fromDate,
3040
+ onSelect: (date) => commit(date ? serializeCalendarDate(date) : void 0)
3041
+ })
3042
+ })]
3043
+ });
2933
3044
  }
2934
3045
 
2935
3046
  //#endregion
@@ -3937,7 +4048,8 @@ function useDataTable(props) {
3937
4048
  if (enableAdvancedFilter) return [];
3938
4049
  return Object.entries(filterValues).reduce((filters, [key, value]) => {
3939
4050
  if (value !== null) {
3940
- const processedValue = Array.isArray(value) ? value : typeof value === "string" && /[^a-zA-Z0-9]/.test(value) ? value.split(/[^a-zA-Z0-9]+/).filter(Boolean) : [value];
4051
+ const variant = filterableColumns.find((column) => column.id === key)?.meta?.variant;
4052
+ const processedValue = Array.isArray(value) ? value : typeof value === "string" && (variant === "date" || variant === "dateRange") ? value.split(",").filter(Boolean) : typeof value === "string" && /[^a-zA-Z0-9]/.test(value) ? value.split(/[^a-zA-Z0-9]+/).filter(Boolean) : [value];
3941
4053
  filters.push({
3942
4054
  id: key,
3943
4055
  value: processedValue
@@ -3945,7 +4057,11 @@ function useDataTable(props) {
3945
4057
  }
3946
4058
  return filters;
3947
4059
  }, []);
3948
- }, [filterValues, enableAdvancedFilter]);
4060
+ }, [
4061
+ filterValues,
4062
+ enableAdvancedFilter,
4063
+ filterableColumns
4064
+ ]);
3949
4065
  const [columnFilters, setColumnFilters] = React.useState(initialColumnFilters);
3950
4066
  const onColumnFiltersChange = React.useCallback((updaterOrValue) => {
3951
4067
  if (enableAdvancedFilter) return;
@@ -6099,13 +6215,6 @@ function mergeFieldOptions(current, incoming) {
6099
6215
  if ((!current || current.length === 0) && (!incoming || incoming.length === 0)) return;
6100
6216
  return mergeFilterOptions(current, incoming ?? []);
6101
6217
  }
6102
- function mergeOptionsByField(left, right) {
6103
- const keys = new Set([...Object.keys(left ?? {}), ...Object.keys(right ?? {})]);
6104
- return Object.fromEntries(Array.from(keys).flatMap((key) => {
6105
- const options = mergeFieldOptions(left?.[key], right?.[key]);
6106
- return options ? [[key, options]] : [];
6107
- }));
6108
- }
6109
6218
  function shouldResolveOptions(field, config, hiddenColumns) {
6110
6219
  if (!config) return false;
6111
6220
  if (hiddenColumns.has(field)) return false;
@@ -6642,7 +6751,7 @@ function buildBatchUpdateFields(schema, batchFields, fields) {
6642
6751
  /**
6643
6752
  * 渲染字段值
6644
6753
  */
6645
- function renderFieldValue(value, type, booleanLocale, options, display = "auto") {
6754
+ function renderFieldValue(value, type, booleanLocale, options, display = "auto", maxItems = 5) {
6646
6755
  if (value === null || value === void 0) return /* @__PURE__ */ jsx("span", {
6647
6756
  className: "text-muted-foreground",
6648
6757
  children: "-"
@@ -6657,12 +6766,12 @@ function renderFieldValue(value, type, booleanLocale, options, display = "auto")
6657
6766
  if (display === "badge" && (!options || options.length === 0)) {
6658
6767
  if (Array.isArray(value)) return /* @__PURE__ */ jsxs("div", {
6659
6768
  className: "flex gap-1 flex-wrap",
6660
- children: [value.slice(0, 5).map((item, index$1) => /* @__PURE__ */ jsx(Badge, {
6769
+ children: [value.slice(0, maxItems).map((item, index$1) => /* @__PURE__ */ jsx(Badge, {
6661
6770
  variant: "secondary",
6662
6771
  children: String(item)
6663
- }, index$1)), value.length > 5 && /* @__PURE__ */ jsxs(Badge, {
6772
+ }, index$1)), value.length > maxItems && /* @__PURE__ */ jsxs(Badge, {
6664
6773
  variant: "outline",
6665
- children: ["+", value.length - 5]
6774
+ children: ["+", value.length - maxItems]
6666
6775
  })]
6667
6776
  });
6668
6777
  return /* @__PURE__ */ jsx(Badge, {
@@ -6674,12 +6783,12 @@ function renderFieldValue(value, type, booleanLocale, options, display = "auto")
6674
6783
  if ((display === "badge" || display === "auto") && options && options.length > 0) {
6675
6784
  if (Array.isArray(value)) return /* @__PURE__ */ jsxs("div", {
6676
6785
  className: "flex gap-1 flex-wrap",
6677
- children: [value.slice(0, 5).map((v, i) => /* @__PURE__ */ jsx(Badge, {
6786
+ children: [value.slice(0, maxItems).map((v, i) => /* @__PURE__ */ jsx(Badge, {
6678
6787
  variant: "secondary",
6679
6788
  children: getOptionLabel(v, options)
6680
- }, i)), value.length > 5 && /* @__PURE__ */ jsxs(Badge, {
6789
+ }, i)), value.length > maxItems && /* @__PURE__ */ jsxs(Badge, {
6681
6790
  variant: "outline",
6682
- children: ["+", value.length - 5]
6791
+ children: ["+", value.length - maxItems]
6683
6792
  })]
6684
6793
  });
6685
6794
  return /* @__PURE__ */ jsx(Badge, {
@@ -6698,48 +6807,81 @@ function renderFieldValue(value, type, booleanLocale, options, display = "auto")
6698
6807
  });
6699
6808
  case "array": return Array.isArray(value) ? /* @__PURE__ */ jsxs("div", {
6700
6809
  className: "flex gap-1 flex-wrap",
6701
- children: [value.slice(0, 5).map((v, i) => /* @__PURE__ */ jsx(Badge, {
6810
+ children: [value.slice(0, maxItems).map((v, i) => /* @__PURE__ */ jsx(Badge, {
6702
6811
  variant: "secondary",
6703
6812
  children: String(v)
6704
- }, i)), value.length > 5 && /* @__PURE__ */ jsxs(Badge, {
6813
+ }, i)), value.length > maxItems && /* @__PURE__ */ jsxs(Badge, {
6705
6814
  variant: "outline",
6706
- children: ["+", value.length - 5]
6815
+ children: ["+", value.length - maxItems]
6707
6816
  })]
6708
6817
  }) : null;
6709
6818
  default: return String(value);
6710
6819
  }
6711
6820
  }
6712
- /**
6713
- * ViewModal 组件 - 详情查看弹窗
6714
- */
6715
- function ViewModal({ open, onOpenChange, variant, data, schema, fields: fieldConfig, dynamicOptions, denyFields, locale }) {
6716
- if (!data) return null;
6717
- const shape = schema.shape;
6718
- const denySet = new Set(denyFields ?? []);
6821
+ function ViewModal(props) {
6822
+ if (!props.open || !props.data) return null;
6823
+ return /* @__PURE__ */ jsx(ViewModalContent, { ...props });
6824
+ }
6825
+ function ViewModalContent({ open, onOpenChange, variant, data, schema, fields: fieldConfig, dynamicOptions, denyFields, locale, tableOverrides, view }) {
6826
+ const excluded = React.useMemo(() => {
6827
+ const denied = new Set(denyFields ?? []);
6828
+ return Object.keys(schema.shape).filter((key) => {
6829
+ const config = fieldConfig?.[key];
6830
+ return denied.has(key) || config?.hidden || view?.overrides?.[key]?.hidden || isDefaultHiddenAuditField(key) && !isFieldTableExplicitlyVisible(config) && view?.overrides?.[key]?.hidden !== false;
6831
+ });
6832
+ }, [
6833
+ schema,
6834
+ fieldConfig,
6835
+ denyFields,
6836
+ view?.overrides
6837
+ ]);
6838
+ const rows = React.useMemo(() => data ? [data] : [], [data]);
6839
+ const resolvedOptions = useDynamicResolveOptions(fieldConfig, rows, excluded);
6719
6840
  const content = /* @__PURE__ */ jsx("dl", {
6720
6841
  className: "grid gap-4 py-4",
6721
- children: Object.entries(shape).filter(([key]) => {
6722
- if (denySet.has(key)) return false;
6723
- const config = fieldConfig?.[key];
6724
- if (config?.hidden) return false;
6725
- if (isDefaultHiddenAuditField(key) && !isFieldTableExplicitlyVisible(config)) return false;
6726
- return true;
6727
- }).map(([key, fieldSchema]) => {
6728
- const parsed = parseZodField(fieldSchema);
6729
- const label = fieldConfig?.[key]?.label ?? humanize(key);
6730
- const value = data[key];
6731
- const options = normalizeFieldOptions(fieldConfig?.[key]?.enum) ?? normalizeFieldOptions(dynamicOptions?.[key]);
6732
- return /* @__PURE__ */ jsxs("div", {
6733
- className: "grid grid-cols-3 items-start gap-4",
6734
- children: [/* @__PURE__ */ jsx("dt", {
6735
- className: "text-sm font-medium text-muted-foreground",
6736
- children: label
6737
- }), /* @__PURE__ */ jsx("dd", {
6738
- className: "col-span-2 text-sm",
6739
- children: renderFieldValue(value, parsed.type, locale.boolean, options)
6740
- })]
6741
- }, key);
6742
- })
6842
+ children: useReactTable({
6843
+ data: rows,
6844
+ columns: React.useMemo(() => {
6845
+ const overrides = {};
6846
+ for (const [key, fieldSchema] of Object.entries(schema.shape).filter(([fieldKey]) => !excluded.includes(fieldKey))) {
6847
+ const config = fieldConfig?.[key] ?? {};
6848
+ const tableConfig = getTableConfig(config);
6849
+ const listOverride = tableOverrides?.[key];
6850
+ const options = getTableOptions(config) ?? resolvedOptions.optionsByField[key] ?? (tableConfig?.dataSource !== void 0 ? void 0 : dynamicOptions?.[key]);
6851
+ overrides[key] = {
6852
+ label: tableConfig?.label ?? config.label ?? listOverride?.label ?? humanize(key),
6853
+ index: tableConfig?.index ?? listOverride?.index,
6854
+ cell: ({ getValue }) => renderFieldValue(getValue(), parseZodField(fieldSchema).type, locale.boolean, options, tableConfig?.display ?? "auto", Infinity),
6855
+ ...view?.presentation === "table" ? listOverride : void 0,
6856
+ hidden: false,
6857
+ ...view?.overrides?.[key]
6858
+ };
6859
+ }
6860
+ return createTableSchema(schema, {
6861
+ overrides,
6862
+ exclude: excluded
6863
+ });
6864
+ }, [
6865
+ schema,
6866
+ excluded,
6867
+ fieldConfig,
6868
+ tableOverrides,
6869
+ view,
6870
+ resolvedOptions.optionsByField,
6871
+ dynamicOptions,
6872
+ locale.boolean
6873
+ ]),
6874
+ getCoreRowModel: getCoreRowModel()
6875
+ }).getRowModel().rows[0]?.getAllCells().map((cell) => /* @__PURE__ */ jsxs("div", {
6876
+ className: "grid grid-cols-3 items-start gap-4",
6877
+ children: [/* @__PURE__ */ jsx("dt", {
6878
+ className: "text-sm font-medium text-muted-foreground",
6879
+ children: cell.column.columnDef.meta?.label ?? humanize(cell.column.id)
6880
+ }), /* @__PURE__ */ jsx("dd", {
6881
+ className: "col-span-2 min-w-0 whitespace-pre-wrap break-words text-sm",
6882
+ children: flexRender(cell.column.columnDef.cell, cell.getContext())
6883
+ })]
6884
+ }, cell.id))
6743
6885
  });
6744
6886
  if (variant === "sheet") return /* @__PURE__ */ jsx(Sheet, {
6745
6887
  open,
@@ -6860,7 +7002,7 @@ function resolveActions(actionsOrFn, defaults, rowActionsLocale, context) {
6860
7002
  *
6861
7003
  * 高级 CRUD 表格组件,封装了完整的增删改查流程
6862
7004
  */
6863
- function AutoCrudTable({ id, title, description, schema, resource, fields, table: tableConfig, form: formConfig, permissions, actions: actionItems, toolbar, toolbarActions, locale: localeProp, onCreate }) {
7005
+ function AutoCrudTable({ id, title, description, schema, resource, fields, table: tableConfig, form: formConfig, view: viewConfig, permissions, actions: actionItems, toolbar, toolbarActions, locale: localeProp, onCreate }) {
6864
7006
  const locale = resolveLocale(localeProp);
6865
7007
  const resolvedSchema = resource.schema ?? schema;
6866
7008
  const resolvedFields = React.useMemo(() => applyResourceTablePresentation(mergeFields(resource.fields, fields), resource.fields) ?? {}, [fields, resource.fields]);
@@ -6886,18 +7028,6 @@ function AutoCrudTable({ id, title, description, schema, resource, fields, table
6886
7028
  tableConfig?.overrides
6887
7029
  ]);
6888
7030
  const dynamicResolveOptions = useDynamicResolveOptions(resolvedFields, resource.tableData.data, hiddenColumns);
6889
- const sharedResolveOptions = useDynamicResolveOptions(React.useMemo(() => Object.fromEntries(Object.entries(resolvedFields).flatMap(([field, config]) => {
6890
- const table = getTableConfig(config);
6891
- if (table?.options === void 0 && table?.dataSource === void 0) return [];
6892
- const { table: _table,...sharedConfig } = config;
6893
- return [[field, sharedConfig]];
6894
- })), [resolvedFields]), resource.tableData.data, hiddenColumns);
6895
- const viewDynamicOptionsByField = React.useMemo(() => mergeOptionsByField(mergeOptionsByField(dynamicFilterOptions.labelOptionsByField, sharedResolveOptions.optionsByField), Object.fromEntries(Object.entries(dynamicResolveOptions.optionsByField).filter(([field]) => !getTableConfig(resolvedFields[field] ?? {})?.dataSource))), [
6896
- dynamicFilterOptions.labelOptionsByField,
6897
- dynamicResolveOptions.optionsByField,
6898
- sharedResolveOptions.optionsByField,
6899
- resolvedFields
6900
- ]);
6901
7031
  const resourceIdKey = resource.idKey ?? "id";
6902
7032
  const actionRegistryVersion = useCrudActionsVersion();
6903
7033
  const unifiedActions = React.useMemo(() => {
@@ -7229,9 +7359,11 @@ function AutoCrudTable({ id, title, description, schema, resource, fields, table
7229
7359
  data: resource.modal.selected,
7230
7360
  schema: resolvedSchema,
7231
7361
  fields: resolvedFields,
7232
- dynamicOptions: viewDynamicOptionsByField,
7362
+ dynamicOptions: dynamicFilterOptions.labelOptionsByField,
7233
7363
  denyFields,
7234
- locale
7364
+ locale,
7365
+ tableOverrides,
7366
+ view: viewConfig
7235
7367
  }),
7236
7368
  /* @__PURE__ */ jsx(AlertDialog, {
7237
7369
  open: resource.modal.deleteOpen,
@@ -7428,10 +7560,7 @@ function getIsDateRange(value) {
7428
7560
  return value && typeof value === "object" && !Array.isArray(value);
7429
7561
  }
7430
7562
  function parseAsDate(timestamp) {
7431
- if (!timestamp) return void 0;
7432
- const numericTimestamp = typeof timestamp === "string" ? Number(timestamp) : timestamp;
7433
- const date = new Date(numericTimestamp);
7434
- return !Number.isNaN(date.getTime()) ? date : void 0;
7563
+ return parseCalendarDate(timestamp);
7435
7564
  }
7436
7565
  function parseColumnFilterValue(value) {
7437
7566
  if (value === null || value === void 0) return [];
@@ -7442,6 +7571,9 @@ function parseColumnFilterValue(value) {
7442
7571
  return [];
7443
7572
  }
7444
7573
  function DataTableDateFilter({ column, title, multiple }) {
7574
+ const formatterVersion = useDateFormatterVersion();
7575
+ const presentation = React.useMemo(() => calendarPresentation(), [formatterVersion]);
7576
+ const { formatDate: formatDate$1 } = presentation;
7445
7577
  const columnFilterValue = column.getFilterValue();
7446
7578
  const selectedDates = React.useMemo(() => {
7447
7579
  if (!columnFilterValue) return multiple ? {
@@ -7515,12 +7647,12 @@ function DataTableDateFilter({ column, title, multiple }) {
7515
7647
  from: nextFrom,
7516
7648
  to: nextTo
7517
7649
  });
7518
- if (nextTo) column.setFilterValue([nextFrom.getTime(), nextTo.getTime()]);
7650
+ if (nextTo) column.setFilterValue([serializeCalendarDate(nextFrom), serializeCalendarDate(nextTo)]);
7519
7651
  return;
7520
7652
  }
7521
7653
  setLocalRange(date);
7522
- if (from && to) column.setFilterValue([from, to]);
7523
- } else if (!multiple && "getTime" in date) column.setFilterValue(date.getTime());
7654
+ if (from && to) column.setFilterValue([serializeCalendarDate(new Date(from)), serializeCalendarDate(new Date(to))]);
7655
+ } else if (!multiple && "getTime" in date) column.setFilterValue(serializeCalendarDate(date));
7524
7656
  }, [
7525
7657
  column,
7526
7658
  multiple,
@@ -7540,9 +7672,9 @@ function DataTableDateFilter({ column, title, multiple }) {
7540
7672
  }, [multiple, selectedDates]);
7541
7673
  const formatDateRange = React.useCallback((range) => {
7542
7674
  if (!range.from && !range.to) return "";
7543
- if (range.from && range.to) return `${formatDate(range.from)} - ${formatDate(range.to)}`;
7544
- return formatDate(range.from ?? range.to);
7545
- }, []);
7675
+ if (range.from && range.to) return `${formatDate$1(range.from)} - ${formatDate$1(range.to)}`;
7676
+ return formatDate$1(range.from ?? range.to);
7677
+ }, [formatDate$1]);
7546
7678
  const label = React.useMemo(() => {
7547
7679
  if (multiple) {
7548
7680
  if (!getIsDateRange(selectedDates)) return null;
@@ -7558,7 +7690,7 @@ function DataTableDateFilter({ column, title, multiple }) {
7558
7690
  }
7559
7691
  if (getIsDateRange(selectedDates)) return null;
7560
7692
  const hasSelectedDate = selectedDates.length > 0;
7561
- const dateText = hasSelectedDate ? formatDate(selectedDates[0]) : "Select date";
7693
+ const dateText = hasSelectedDate ? formatDate$1(selectedDates[0]) : "Select date";
7562
7694
  return /* @__PURE__ */ jsxs("span", {
7563
7695
  className: "flex items-center gap-2",
7564
7696
  children: [/* @__PURE__ */ jsx("span", { children: title }), hasSelectedDate && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Separator, {
@@ -7570,7 +7702,8 @@ function DataTableDateFilter({ column, title, multiple }) {
7570
7702
  selectedDates,
7571
7703
  multiple,
7572
7704
  formatDateRange,
7573
- title
7705
+ title,
7706
+ formatDate$1
7574
7707
  ]);
7575
7708
  return /* @__PURE__ */ jsxs(Popover, { children: [/* @__PURE__ */ jsx(PopoverTrigger, {
7576
7709
  asChild: true,
@@ -7580,7 +7713,7 @@ function DataTableDateFilter({ column, title, multiple }) {
7580
7713
  className: "border-dashed font-normal",
7581
7714
  children: [hasValue ? /* @__PURE__ */ jsx("div", {
7582
7715
  role: "button",
7583
- "aria-label": `Clear ${title} filter`,
7716
+ "aria-label": presentation.clearLabel(title),
7584
7717
  tabIndex: 0,
7585
7718
  onClick: onReset,
7586
7719
  className: "rounded-sm opacity-70 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
@@ -7591,14 +7724,24 @@ function DataTableDateFilter({ column, title, multiple }) {
7591
7724
  className: "w-auto p-0",
7592
7725
  align: "start",
7593
7726
  children: multiple ? /* @__PURE__ */ jsx(Calendar, {
7727
+ lang: presentation.locale,
7728
+ weekStartsOn: presentation.weekStartsOn,
7729
+ formatters: presentation.formatters,
7730
+ labels: presentation.labels,
7594
7731
  autoFocus: true,
7595
7732
  captionLayout: "dropdown",
7596
7733
  mode: "range",
7734
+ defaultMonth: localRange.from,
7597
7735
  selected: localRange,
7598
7736
  onSelect
7599
7737
  }) : /* @__PURE__ */ jsx(Calendar, {
7738
+ lang: presentation.locale,
7739
+ weekStartsOn: presentation.weekStartsOn,
7740
+ formatters: presentation.formatters,
7741
+ labels: presentation.labels,
7600
7742
  captionLayout: "dropdown",
7601
7743
  mode: "single",
7744
+ defaultMonth: !getIsDateRange(selectedDates) ? selectedDates[0] : void 0,
7602
7745
  selected: !getIsDateRange(selectedDates) ? selectedDates[0] : void 0,
7603
7746
  onSelect
7604
7747
  })