@coldsmirk/ledger-mantine 0.11.1 → 0.12.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.cjs CHANGED
@@ -1773,6 +1773,125 @@ function DataTablePagination(props) {
1773
1773
  });
1774
1774
  }
1775
1775
  //#endregion
1776
+ //#region src/scroll-snapshot.ts
1777
+ /**
1778
+ * Opaque scroll-restoration snapshots (`docs/virtualization.md#restoring-scroll-position`).
1779
+ *
1780
+ * A snapshot captures plain, JSON-serializable scroll geometry — the viewport's offsets, its last
1781
+ * known dimensions, and TanStack Virtual's measured row heights (`takeSnapshot()`) — tagged with a
1782
+ * shape version so storage/history payloads from another version of ledger fail validation instead
1783
+ * of restoring corrupt numbers.
1784
+ */
1785
+ const SCROLL_SNAPSHOT_VERSION = 1;
1786
+ function isRecord$1(value) {
1787
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1788
+ }
1789
+ function isFiniteNumber$1(value) {
1790
+ return typeof value === "number" && Number.isFinite(value);
1791
+ }
1792
+ function isNonNegativeFinite(value) {
1793
+ return isFiniteNumber$1(value) && value >= 0;
1794
+ }
1795
+ function isNonNegativeInteger(value) {
1796
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1797
+ }
1798
+ function isViewportRect(value) {
1799
+ if (!isRecord$1(value)) return false;
1800
+ return isNonNegativeFinite(value.width) && isNonNegativeFinite(value.height);
1801
+ }
1802
+ function isSerializedVirtualItem(value) {
1803
+ if (!isRecord$1(value)) return false;
1804
+ const validKey = typeof value.key === "string" || isFiniteNumber$1(value.key);
1805
+ return isNonNegativeInteger(value.index) && validKey && isFiniteNumber$1(value.start) && isNonNegativeFinite(value.size) && isFiniteNumber$1(value.end) && isNonNegativeInteger(value.lane);
1806
+ }
1807
+ /**
1808
+ * Validates an unknown value — such as one read back from `sessionStorage` or router history
1809
+ * state — as a {@link DataTableScrollSnapshot} written by this version of ledger.
1810
+ */
1811
+ function isDataTableScrollSnapshot(value) {
1812
+ if (!isRecord$1(value) || value.version !== SCROLL_SNAPSHOT_VERSION) return false;
1813
+ if (!isNonNegativeFinite(value.scrollTop) || !isFiniteNumber$1(value.scrollLeft)) return false;
1814
+ if (value.viewport !== null && !isViewportRect(value.viewport)) return false;
1815
+ return value.measurements === null || Array.isArray(value.measurements) && value.measurements.every(isSerializedVirtualItem);
1816
+ }
1817
+ /**
1818
+ * Validates and unwraps a snapshot at the component boundary. Invalid or mismatched-version
1819
+ * payloads degrade to `null` instead of throwing.
1820
+ */
1821
+ function readScrollSnapshot(value) {
1822
+ if (!isDataTableScrollSnapshot(value)) return null;
1823
+ return value;
1824
+ }
1825
+ function readViewportRect(viewport, virtualizer) {
1826
+ const virtualRect = virtualizer?.scrollRect;
1827
+ if (virtualRect && virtualRect.width > 0 && virtualRect.height > 0) return {
1828
+ width: Math.round(virtualRect.width),
1829
+ height: Math.round(virtualRect.height)
1830
+ };
1831
+ const width = Math.round(viewport.offsetWidth);
1832
+ const height = Math.round(viewport.offsetHeight);
1833
+ if (width > 0 && height > 0) return {
1834
+ width,
1835
+ height
1836
+ };
1837
+ return null;
1838
+ }
1839
+ function serializeVirtualMeasurements(virtualizer) {
1840
+ const items = [];
1841
+ for (const item of virtualizer.takeSnapshot()) {
1842
+ if (typeof item.key !== "string" && !(typeof item.key === "number" && Number.isFinite(item.key))) continue;
1843
+ items.push({
1844
+ index: item.index,
1845
+ key: item.key,
1846
+ start: item.start,
1847
+ size: item.size,
1848
+ end: item.end,
1849
+ lane: item.lane
1850
+ });
1851
+ }
1852
+ return items;
1853
+ }
1854
+ /**
1855
+ * Captures the viewport's current scroll offsets, dimensions, and measured virtualizer row heights
1856
+ * as an opaque plain-data snapshot. Returns `null` while the viewport is not mounted.
1857
+ */
1858
+ function captureScrollSnapshot(viewport, virtualizer) {
1859
+ if (!viewport) return null;
1860
+ const rawTop = Number.isFinite(viewport.scrollTop) ? viewport.scrollTop : 0;
1861
+ const scrollTop = Math.max(0, rawTop);
1862
+ const scrollLeft = Number.isFinite(viewport.scrollLeft) ? viewport.scrollLeft : 0;
1863
+ return {
1864
+ version: SCROLL_SNAPSHOT_VERSION,
1865
+ scrollTop,
1866
+ scrollLeft,
1867
+ viewport: readViewportRect(viewport, virtualizer),
1868
+ measurements: virtualizer === null ? null : serializeVirtualMeasurements(virtualizer)
1869
+ };
1870
+ }
1871
+ /**
1872
+ * Resolves a validated snapshot into the mount-only options TanStack Virtual expects, clamped to
1873
+ * the rows the table mounts with so a snapshot taken on a longer table lands at the end instead of
1874
+ * past it. Returns `null` when there is no snapshot or no rows to restore into.
1875
+ */
1876
+ function resolveInitialVirtualRestore(snapshot, rowKeys, estimateHeight) {
1877
+ if (snapshot === null || rowKeys.length === 0) return null;
1878
+ const measurements = [];
1879
+ const sizeByKey = /* @__PURE__ */ new Map();
1880
+ if (snapshot.measurements !== null) for (const item of snapshot.measurements) {
1881
+ sizeByKey.set(item.key, item.size);
1882
+ measurements.push({ ...item });
1883
+ }
1884
+ let totalHeight = 0;
1885
+ for (const key of rowKeys) totalHeight += sizeByKey.get(key) ?? estimateHeight;
1886
+ const viewportHeight = snapshot.viewport?.height ?? 0;
1887
+ const maxOffset = viewportHeight > 0 ? Math.max(0, totalHeight - viewportHeight) : totalHeight;
1888
+ return {
1889
+ offset: Math.min(snapshot.scrollTop, maxOffset),
1890
+ measurements,
1891
+ rect: snapshot.viewport ? { ...snapshot.viewport } : void 0
1892
+ };
1893
+ }
1894
+ //#endregion
1776
1895
  //#region src/search.tsx
1777
1896
  /**
1778
1897
  * `DataTable.Search` — the global-filter input, debounced. A standalone compound: takes the
@@ -2919,7 +3038,7 @@ function LoadMoreErrorRow({ colSpan, message, ariaRowIndex, onRetry }) {
2919
3038
  })
2920
3039
  });
2921
3040
  }
2922
- function TableBody({ table, virtualization, columnWindow, filler, viewportRef, loading, loadingMore, loadMoreError, onLoadMoreRetry, reorderSourceId, reorderTarget, skeletonRowCount, onVirtualizerChange }) {
3041
+ function TableBody({ table, virtualization, initialScroll, columnWindow, filler, viewportRef, loading, loadingMore, loadMoreError, onLoadMoreRetry, reorderSourceId, reorderTarget, skeletonRowCount, onVirtualizerChange }) {
2923
3042
  const { getStyles, withColumnHeaders } = useDataTableContext();
2924
3043
  const ledger = table.options.meta?.ledger;
2925
3044
  const withDetailPanels = Boolean(ledger?.renderDetailPanel);
@@ -2947,18 +3066,24 @@ function TableBody({ table, virtualization, columnWindow, filler, viewportRef, l
2947
3066
  const getItemKey = (0, react.useCallback)((index) => centerDisplayRows[index]?.key ?? index, [centerDisplayRows]);
2948
3067
  const estimateHeight = virtualization?.estimateHeight ?? DEFAULT_ESTIMATED_ROW_HEIGHT;
2949
3068
  const estimateSize = (0, react.useCallback)(() => estimateHeight, [estimateHeight]);
3069
+ const [initialRestore] = (0, react.useState)(() => virtualization === null ? null : resolveInitialVirtualRestore(initialScroll, centerDisplayRows.map((row) => row.key), estimateHeight));
2950
3070
  const virtualizer = (0, _tanstack_react_virtual.useVirtualizer)({
2951
3071
  count: centerDisplayRows.length,
2952
3072
  enabled: virtualization !== null,
2953
3073
  estimateSize,
2954
3074
  getItemKey,
2955
3075
  getScrollElement: () => viewportRef.current,
3076
+ ...initialRestore !== null && {
3077
+ initialMeasurementsCache: initialRestore.measurements,
3078
+ initialOffset: initialRestore.offset,
3079
+ ...initialRestore.rect !== void 0 && { initialRect: initialRestore.rect }
3080
+ },
2956
3081
  measureElement: measureRow,
2957
3082
  overscan: virtualization?.overscan ?? DEFAULT_OVERSCAN,
2958
3083
  useFlushSync: false
2959
3084
  });
2960
3085
  const virtualEnabled = virtualization !== null;
2961
- (0, react.useEffect)(() => {
3086
+ (0, react.useLayoutEffect)(() => {
2962
3087
  onVirtualizerChange(virtualEnabled ? virtualizer : null);
2963
3088
  return () => onVirtualizerChange(null);
2964
3089
  }, [
@@ -7193,7 +7318,7 @@ function DataTableFromOptions({ props }) {
7193
7318
  });
7194
7319
  }
7195
7320
  function DataTableCore({ presentation, stylesProps, table }) {
7196
- const { striped, stripedColor: _stripedColor, highlightOnHover, highlightOnHoverColor: _highlightOnHoverColor, withTableBorder, withColumnBorders, withRowBorders, withBottomBorder, borderColor: _borderColor, radius: _radius, size: sizeProp, verticalSpacing, horizontalSpacing, tabularNums, tableMinWidth, columnMinSizeFromHeader, virtualizedRows, virtualizedColumns, onEndReached, endReachedOffset, loadingMore, loadMoreError, loading, emptyState, error, onRetry, withColumnHeaders, withPaginationBar, pageSizeOptions, onRowClick, onRowActivate, onRowDoubleClick, onRowContextMenu, rowProps, headerRowProps, footerRowProps, viewportProps, labels: labelsProp, icons: iconsProp, handleRef, ref: rootRef, classNames, styles, unstyled, vars, className, style, attributes, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "aria-describedby": ariaDescribedBy, ...others } = presentation;
7321
+ const { striped, stripedColor: _stripedColor, highlightOnHover, highlightOnHoverColor: _highlightOnHoverColor, withTableBorder, withColumnBorders, withRowBorders, withBottomBorder, borderColor: _borderColor, radius: _radius, size: sizeProp, verticalSpacing, horizontalSpacing, tabularNums, tableMinWidth, columnMinSizeFromHeader, virtualizedRows, virtualizedColumns, initialScroll, onEndReached, endReachedOffset, loadingMore, loadMoreError, loading, emptyState, error, onRetry, withColumnHeaders, withPaginationBar, pageSizeOptions, onRowClick, onRowActivate, onRowDoubleClick, onRowContextMenu, rowProps, headerRowProps, footerRowProps, viewportProps, labels: labelsProp, icons: iconsProp, handleRef, ref: rootRef, classNames, styles, unstyled, vars, className, style, attributes, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "aria-describedby": ariaDescribedBy, ...others } = presentation;
7197
7322
  const getStyles = (0, _mantine_core.useStyles)({
7198
7323
  name: "DataTable",
7199
7324
  classes,
@@ -7266,6 +7391,7 @@ function DataTableCore({ presentation, stylesProps, table }) {
7266
7391
  tableMinWidth,
7267
7392
  viewport
7268
7393
  });
7394
+ const [initialScrollData] = (0, react.useState)(() => readScrollSnapshot(initialScroll));
7269
7395
  const virtualization = virtualizedRows ? {
7270
7396
  estimateHeight: typeof virtualizedRows === "object" && virtualizedRows.estimateHeight !== void 0 ? virtualizedRows.estimateHeight : scale.rowHeight,
7271
7397
  overscan: typeof virtualizedRows === "object" && virtualizedRows.overscan !== void 0 ? virtualizedRows.overscan : 8
@@ -7488,6 +7614,19 @@ function DataTableCore({ presentation, stylesProps, table }) {
7488
7614
  if (!element) return;
7489
7615
  for (const mirror of [headerViewportRef.current, footerViewportRef.current]) if (mirror && mirror.scrollLeft !== element.scrollLeft) mirror.scrollLeft = element.scrollLeft;
7490
7616
  });
7617
+ const initialScrollApplied = (0, react.useRef)(false);
7618
+ (0, react.useLayoutEffect)(() => {
7619
+ if (initialScrollApplied.current || initialScrollData === null) return;
7620
+ const element = viewportRef.current;
7621
+ if (!element) return;
7622
+ initialScrollApplied.current = true;
7623
+ if (!virtualEnabled && initialScrollData.scrollTop > 0 && rowsLength > 0) element.scrollTop = initialScrollData.scrollTop;
7624
+ if (initialScrollData.scrollLeft !== 0) {
7625
+ element.scrollLeft = initialScrollData.scrollLeft;
7626
+ mirrorBodyScrollLeft();
7627
+ updateScrollEdges();
7628
+ }
7629
+ }, []);
7491
7630
  (0, react.useEffect)(() => {
7492
7631
  updateScrollEdges();
7493
7632
  mirrorBodyScrollLeft();
@@ -7583,6 +7722,7 @@ function DataTableCore({ presentation, stylesProps, table }) {
7583
7722
  left: rtl ? -target : target
7584
7723
  });
7585
7724
  });
7725
+ const getScrollSnapshot = (0, react.useCallback)(() => captureScrollSnapshot(viewportRef.current, virtualizerRef.current), []);
7586
7726
  (0, react.useImperativeHandle)(handleRef, () => {
7587
7727
  return {
7588
7728
  table,
@@ -7592,6 +7732,7 @@ function DataTableCore({ presentation, stylesProps, table }) {
7592
7732
  scrollToRow: scrollRowIntoView,
7593
7733
  scrollToIndex: scrollIndexIntoView,
7594
7734
  scrollToColumn: scrollColumnIntoView,
7735
+ getScrollSnapshot,
7595
7736
  startEditing: (rowId, columnId) => {
7596
7737
  const editing = table.options.meta?.ledger?.editing;
7597
7738
  if (!editing) return;
@@ -7612,7 +7753,8 @@ function DataTableCore({ presentation, stylesProps, table }) {
7612
7753
  table,
7613
7754
  scrollRowIntoView,
7614
7755
  scrollIndexIntoView,
7615
- scrollColumnIntoView
7756
+ scrollColumnIntoView,
7757
+ getScrollSnapshot
7616
7758
  ]);
7617
7759
  const activeRowAnnouncer = (0, react.useRef)(null);
7618
7760
  const rowNavigationHintId = `${instanceId}-row-navigation`;
@@ -7881,6 +8023,7 @@ function DataTableCore({ presentation, stylesProps, table }) {
7881
8023
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("colgroup", { children: colElements }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TableBody, {
7882
8024
  columnWindow,
7883
8025
  filler,
8026
+ initialScroll: initialScrollData,
7884
8027
  loading: loading === true,
7885
8028
  loadingMore: loadingMore === true,
7886
8029
  loadMoreError: loadMoreError ?? false,
@@ -8086,6 +8229,7 @@ Object.defineProperty(exports, "flexRender", {
8086
8229
  return _tanstack_react_table.flexRender;
8087
8230
  }
8088
8231
  });
8232
+ exports.isDataTableScrollSnapshot = isDataTableScrollSnapshot;
8089
8233
  exports.numberEditor = numberEditor;
8090
8234
  exports.selectEditor = selectEditor;
8091
8235
  exports.textEditor = textEditor;