File size: 2,390 Bytes
5144199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use client';

import { FlexRender } from "./FlexRender.js";
import { Subscribe } from "./Subscribe.js";
import { reactReactivity } from "./reactivity.js";
import { constructTable } from "@tanstack/table-core";
import { useEffect, useLayoutEffect, useMemo, useState } from "react";
import { shallow, useSelector } from "@tanstack/react-store";
import { createRenderPhaseSource } from "@tanstack/table-core/reactivity";
import { table_publishExternalState, table_setOptions } from "@tanstack/table-core/static-functions";

//#region src/useTable.ts
const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
/**
* Creates a React table instance backed by TanStack Store atoms.
*
* The optional selector projects from `table.store`; the selected value is
* exposed on `table.state` and compared shallowly for React re-renders. Omit
* the selector to subscribe to every registered table state slice, or pass a
* narrower selector and use `table.Subscribe` lower in the tree for targeted
* subscriptions.
*
* @example
* ```tsx
* const table = useTable(
*   {
*     features,
*     columns,
*     data,
*   },
*   (state) => ({ pagination: state.pagination }),
* )
*
* table.state.pagination
* ```
*/
function useTable(tableOptions, selector) {
	const [{ table, rootSource }] = useState(() => {
		const tableInstance = constructTable({
			...tableOptions,
			features: {
				coreReactivityFeature: reactReactivity(),
				...tableOptions.features
			}
		});
		tableInstance.Subscribe = ((props) => {
			return Subscribe({
				...props,
				source: props.source ?? tableInstance.store
			});
		});
		tableInstance.FlexRender = FlexRender;
		return {
			table: tableInstance,
			rootSource: createRenderPhaseSource(tableInstance.store, shallow)
		};
	});
	const coreTable = table;
	table_setOptions(coreTable, (prev) => ({
		...prev,
		...tableOptions
	}), { syncExternalState: false });
	const controlledState = coreTable.options.state;
	const renderSnapshot = rootSource.get();
	const state = useSelector(rootSource, selector, { compare: shallow });
	useIsomorphicLayoutEffect(() => {
		rootSource.markCommitted(renderSnapshot);
		table_publishExternalState(coreTable, controlledState ?? null, shallow);
	});
	return useMemo(() => ({
		...table,
		options: tableOptions,
		state
	}), [
		table,
		tableOptions,
		state
	]);
}

//#endregion
export { useTable };