@tanstack/preact-table 0.0.1 → 9.0.0-alpha.14
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/LICENSE +21 -0
- package/dist/esm/FlexRender.d.ts +46 -0
- package/dist/esm/FlexRender.js +41 -0
- package/dist/esm/FlexRender.js.map +1 -0
- package/dist/esm/Subscribe.d.ts +44 -0
- package/dist/esm/Subscribe.js +9 -0
- package/dist/esm/Subscribe.js.map +1 -0
- package/dist/esm/createTableHook.d.ts +349 -0
- package/dist/esm/createTableHook.js +133 -0
- package/dist/esm/createTableHook.js.map +1 -0
- package/dist/esm/index.d.ts +5 -0
- package/dist/esm/index.js +13 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/useTable.d.ts +52 -0
- package/dist/esm/useTable.js +46 -0
- package/dist/esm/useTable.js.map +1 -0
- package/package.json +61 -7
- package/src/FlexRender.tsx +119 -0
- package/src/Subscribe.ts +67 -0
- package/src/createTableHook.tsx +1120 -0
- package/src/index.ts +6 -0
- package/src/useTable.ts +132 -0
- package/README.md +0 -45
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createTableHook.js","sources":["../../src/createTableHook.tsx"],"sourcesContent":["'use client'\nimport { createContext } from 'preact'\nimport { useContext, useMemo } from 'preact/hooks'\nimport { createColumnHelper as coreCreateColumnHelper } from '@tanstack/table-core'\nimport { useTable } from './useTable'\nimport { FlexRender } from './FlexRender'\nimport type {\n AccessorFn,\n AccessorFnColumnDef,\n AccessorKeyColumnDef,\n Cell,\n CellContext,\n CellData,\n Column,\n ColumnDef,\n DeepKeys,\n DeepValue,\n DisplayColumnDef,\n GroupColumnDef,\n Header,\n IdentifiedColumnDef,\n NoInfer,\n Row,\n RowData,\n Table,\n TableFeatures,\n TableOptions,\n TableState,\n} from '@tanstack/table-core'\nimport type { ComponentChildren, ComponentType } from 'preact'\nimport type { PreactTable } from './useTable'\n\n// =============================================================================\n// Enhanced Context Types with Pre-bound Components\n// =============================================================================\n\n/**\n * Enhanced CellContext with pre-bound cell components.\n * The `cell` property includes the registered cellComponents.\n */\nexport type AppCellContext<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TValue extends CellData,\n TCellComponents extends Record<string, ComponentType<any>>,\n> = {\n cell: Cell<TFeatures, TData, TValue> &\n TCellComponents & { FlexRender: () => ComponentChildren }\n column: Column<TFeatures, TData, TValue>\n getValue: CellContext<TFeatures, TData, TValue>['getValue']\n renderValue: CellContext<TFeatures, TData, TValue>['renderValue']\n row: Row<TFeatures, TData>\n table: Table<TFeatures, TData>\n}\n\n/**\n * Enhanced HeaderContext with pre-bound header components.\n * The `header` property includes the registered headerComponents.\n */\nexport type AppHeaderContext<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TValue extends CellData,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> = {\n column: Column<TFeatures, TData, TValue>\n header: Header<TFeatures, TData, TValue> &\n THeaderComponents & { FlexRender: () => ComponentChildren }\n table: Table<TFeatures, TData>\n}\n\n// =============================================================================\n// Enhanced Column Definition Types\n// =============================================================================\n\n/**\n * Template type for column definitions that can be a string or a function.\n */\ntype AppColumnDefTemplate<TProps extends object> =\n | string\n | ((props: TProps) => any)\n\n/**\n * Enhanced column definition base with pre-bound components in cell/header/footer contexts.\n */\ntype AppColumnDefBase<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TValue extends CellData,\n TCellComponents extends Record<string, ComponentType<any>>,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> = Omit<\n IdentifiedColumnDef<TFeatures, TData, TValue>,\n 'cell' | 'header' | 'footer'\n> & {\n cell?: AppColumnDefTemplate<\n AppCellContext<TFeatures, TData, TValue, TCellComponents>\n >\n header?: AppColumnDefTemplate<\n AppHeaderContext<TFeatures, TData, TValue, THeaderComponents>\n >\n footer?: AppColumnDefTemplate<\n AppHeaderContext<TFeatures, TData, TValue, THeaderComponents>\n >\n}\n\n/**\n * Enhanced display column definition with pre-bound components.\n */\ntype AppDisplayColumnDef<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TCellComponents extends Record<string, ComponentType<any>>,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> = Omit<\n DisplayColumnDef<TFeatures, TData, unknown>,\n 'cell' | 'header' | 'footer'\n> & {\n cell?: AppColumnDefTemplate<\n AppCellContext<TFeatures, TData, unknown, TCellComponents>\n >\n header?: AppColumnDefTemplate<\n AppHeaderContext<TFeatures, TData, unknown, THeaderComponents>\n >\n footer?: AppColumnDefTemplate<\n AppHeaderContext<TFeatures, TData, unknown, THeaderComponents>\n >\n}\n\n/**\n * Enhanced group column definition with pre-bound components.\n */\ntype AppGroupColumnDef<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TCellComponents extends Record<string, ComponentType<any>>,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> = Omit<\n GroupColumnDef<TFeatures, TData, unknown>,\n 'cell' | 'header' | 'footer' | 'columns'\n> & {\n cell?: AppColumnDefTemplate<\n AppCellContext<TFeatures, TData, unknown, TCellComponents>\n >\n header?: AppColumnDefTemplate<\n AppHeaderContext<TFeatures, TData, unknown, THeaderComponents>\n >\n footer?: AppColumnDefTemplate<\n AppHeaderContext<TFeatures, TData, unknown, THeaderComponents>\n >\n columns?: Array<ColumnDef<TFeatures, TData, unknown>>\n}\n\n// =============================================================================\n// Enhanced Column Helper Type\n// =============================================================================\n\n/**\n * Enhanced column helper with pre-bound components in cell/header/footer contexts.\n * This enables TypeScript to know about the registered components when defining columns.\n */\nexport type AppColumnHelper<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TCellComponents extends Record<string, ComponentType<any>>,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> = {\n /**\n * Creates a data column definition with an accessor key or function.\n * The cell, header, and footer contexts include pre-bound components.\n */\n accessor: <\n TAccessor extends AccessorFn<TData> | DeepKeys<TData>,\n TValue extends TAccessor extends AccessorFn<TData, infer TReturn>\n ? TReturn\n : TAccessor extends DeepKeys<TData>\n ? DeepValue<TData, TAccessor>\n : never,\n >(\n accessor: TAccessor,\n column: TAccessor extends AccessorFn<TData>\n ? AppColumnDefBase<\n TFeatures,\n TData,\n TValue,\n TCellComponents,\n THeaderComponents\n > & { id: string }\n : AppColumnDefBase<\n TFeatures,\n TData,\n TValue,\n TCellComponents,\n THeaderComponents\n >,\n ) => TAccessor extends AccessorFn<TData>\n ? AccessorFnColumnDef<TFeatures, TData, TValue>\n : AccessorKeyColumnDef<TFeatures, TData, TValue>\n\n /**\n * Wraps an array of column definitions to preserve each column's individual TValue type.\n */\n columns: <TColumns extends ReadonlyArray<ColumnDef<TFeatures, TData, any>>>(\n columns: [...TColumns],\n ) => Array<ColumnDef<TFeatures, TData, any>> & [...TColumns]\n\n /**\n * Creates a display column definition for non-data columns.\n * The cell, header, and footer contexts include pre-bound components.\n */\n display: (\n column: AppDisplayColumnDef<\n TFeatures,\n TData,\n TCellComponents,\n THeaderComponents\n >,\n ) => DisplayColumnDef<TFeatures, TData, unknown>\n\n /**\n * Creates a group column definition with nested child columns.\n * The cell, header, and footer contexts include pre-bound components.\n */\n group: (\n column: AppGroupColumnDef<\n TFeatures,\n TData,\n TCellComponents,\n THeaderComponents\n >,\n ) => GroupColumnDef<TFeatures, TData, unknown>\n}\n\n// =============================================================================\n// CreateTableHook Options and Props\n// =============================================================================\n\n/**\n * Options for creating a table hook with pre-bound components and default table options.\n * Extends all TableOptions except 'columns' | 'data' | 'store' | 'state' | 'initialState'.\n */\nexport type CreateTableHookOptions<\n TFeatures extends TableFeatures,\n TTableComponents extends Record<string, ComponentType<any>>,\n TCellComponents extends Record<string, ComponentType<any>>,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> = Omit<\n TableOptions<TFeatures, any>,\n 'columns' | 'data' | 'store' | 'state' | 'initialState'\n> & {\n /**\n * Table-level components that need access to the table instance.\n * These are available directly on the table object returned by useAppTable.\n * Use `useTableContext()` inside these components.\n * @example { PaginationControls, GlobalFilter, RowCount }\n */\n tableComponents?: TTableComponents\n /**\n * Cell-level components that need access to the cell instance.\n * These are available on the cell object passed to AppCell's children.\n * Use `useCellContext()` inside these components.\n * @example { TextCell, NumberCell, DateCell, CurrencyCell }\n */\n cellComponents?: TCellComponents\n /**\n * Header-level components that need access to the header instance.\n * These are available on the header object passed to AppHeader/AppFooter's children.\n * Use `useHeaderContext()` inside these components.\n * @example { SortIndicator, ColumnFilter, ResizeHandle }\n */\n headerComponents?: THeaderComponents\n}\n\n/**\n * Props for AppTable component - without selector\n */\nexport interface AppTablePropsWithoutSelector {\n children: ComponentChildren\n selector?: never\n}\n\n/**\n * Props for AppTable component - with selector\n */\nexport interface AppTablePropsWithSelector<\n TFeatures extends TableFeatures,\n TSelected,\n> {\n children: (state: TSelected) => ComponentChildren\n selector: (state: TableState<TFeatures>) => TSelected\n}\n\n/**\n * Props for AppCell component - without selector\n */\nexport interface AppCellPropsWithoutSelector<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TValue extends CellData,\n TCellComponents extends Record<string, ComponentType<any>>,\n> {\n cell: Cell<TFeatures, TData, TValue>\n children: (\n cell: Cell<TFeatures, TData, TValue> &\n TCellComponents & { FlexRender: () => ComponentChildren },\n ) => ComponentChildren\n selector?: never\n}\n\n/**\n * Props for AppCell component - with selector\n */\nexport interface AppCellPropsWithSelector<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TValue extends CellData,\n TCellComponents extends Record<string, ComponentType<any>>,\n TSelected,\n> {\n cell: Cell<TFeatures, TData, TValue>\n children: (\n cell: Cell<TFeatures, TData, TValue> &\n TCellComponents & { FlexRender: () => ComponentChildren },\n state: TSelected,\n ) => ComponentChildren\n selector: (state: TableState<TFeatures>) => TSelected\n}\n\n/**\n * Props for AppHeader/AppFooter component - without selector\n */\nexport interface AppHeaderPropsWithoutSelector<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TValue extends CellData,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> {\n header: Header<TFeatures, TData, TValue>\n children: (\n header: Header<TFeatures, TData, TValue> &\n THeaderComponents & { FlexRender: () => ComponentChildren },\n ) => ComponentChildren\n selector?: never\n}\n\n/**\n * Props for AppHeader/AppFooter component - with selector\n */\nexport interface AppHeaderPropsWithSelector<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TValue extends CellData,\n THeaderComponents extends Record<string, ComponentType<any>>,\n TSelected,\n> {\n header: Header<TFeatures, TData, TValue>\n children: (\n header: Header<TFeatures, TData, TValue> &\n THeaderComponents & { FlexRender: () => ComponentChildren },\n state: TSelected,\n ) => ComponentChildren\n selector: (state: TableState<TFeatures>) => TSelected\n}\n\n/**\n * Component type for AppCell - wraps a cell and provides cell context with optional Subscribe\n */\nexport interface AppCellComponent<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TCellComponents extends Record<string, ComponentType<any>>,\n> {\n <TValue extends CellData = CellData>(\n props: AppCellPropsWithoutSelector<\n TFeatures,\n TData,\n TValue,\n TCellComponents\n >,\n ): ComponentChildren\n <TValue extends CellData = CellData, TSelected = unknown>(\n props: AppCellPropsWithSelector<\n TFeatures,\n TData,\n TValue,\n TCellComponents,\n TSelected\n >,\n ): ComponentChildren\n}\n\n/**\n * Component type for AppHeader/AppFooter - wraps a header and provides header context with optional Subscribe\n */\nexport interface AppHeaderComponent<\n TFeatures extends TableFeatures,\n TData extends RowData,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> {\n <TValue extends CellData = CellData>(\n props: AppHeaderPropsWithoutSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents\n >,\n ): ComponentChildren\n <TValue extends CellData = CellData, TSelected = unknown>(\n props: AppHeaderPropsWithSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents,\n TSelected\n >,\n ): ComponentChildren\n}\n\n/**\n * Component type for AppTable - root wrapper with optional Subscribe\n */\nexport interface AppTableComponent<TFeatures extends TableFeatures> {\n (props: AppTablePropsWithoutSelector): ComponentChildren\n <TSelected>(\n props: AppTablePropsWithSelector<TFeatures, TSelected>,\n ): ComponentChildren\n}\n\n/**\n * Extended table API returned by useAppTable with all App wrapper components\n */\nexport type AppPreactTable<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TSelected,\n TTableComponents extends Record<string, ComponentType<any>>,\n TCellComponents extends Record<string, ComponentType<any>>,\n THeaderComponents extends Record<string, ComponentType<any>>,\n> = PreactTable<TFeatures, TData, TSelected> &\n NoInfer<TTableComponents> & {\n /**\n * Root wrapper component that provides table context with optional Subscribe.\n * @example\n * ```tsx\n * // Without selector - children is ComponentChildren\n * <table.AppTable>\n * <table>...</table>\n * </table.AppTable>\n *\n * // With selector - children receives selected state\n * <table.AppTable selector={(s) => s.pagination}>\n * {(pagination) => <div>Page {pagination.pageIndex}</div>}\n * </table.AppTable>\n * ```\n */\n AppTable: AppTableComponent<TFeatures>\n /**\n * Wraps a cell and provides cell context with pre-bound cellComponents.\n * Optionally accepts a selector for Subscribe functionality.\n * @example\n * ```tsx\n * // Without selector\n * <table.AppCell cell={cell}>\n * {(c) => <td><c.TextCell /></td>}\n * </table.AppCell>\n *\n * // With selector - children receives cell and selected state\n * <table.AppCell cell={cell} selector={(s) => s.columnFilters}>\n * {(c, filters) => <td>{filters.length}</td>}\n * </table.AppCell>\n * ```\n */\n AppCell: AppCellComponent<TFeatures, TData, NoInfer<TCellComponents>>\n /**\n * Wraps a header and provides header context with pre-bound headerComponents.\n * Optionally accepts a selector for Subscribe functionality.\n * @example\n * ```tsx\n * // Without selector\n * <table.AppHeader header={header}>\n * {(h) => <th><h.SortIndicator /></th>}\n * </table.AppHeader>\n *\n * // With selector\n * <table.AppHeader header={header} selector={(s) => s.sorting}>\n * {(h, sorting) => <th>{sorting.length} sorted</th>}\n * </table.AppHeader>\n * ```\n */\n AppHeader: AppHeaderComponent<TFeatures, TData, NoInfer<THeaderComponents>>\n /**\n * Wraps a footer and provides header context with pre-bound headerComponents.\n * Optionally accepts a selector for Subscribe functionality.\n * @example\n * ```tsx\n * <table.AppFooter header={footer}>\n * {(f) => <td><table.FlexRender footer={footer} /></td>}\n * </table.AppFooter>\n * ```\n */\n AppFooter: AppHeaderComponent<TFeatures, TData, NoInfer<THeaderComponents>>\n }\n\n/**\n * Creates a custom table hook with pre-bound components for composition.\n *\n * This is the table equivalent of TanStack Form's `createFormHook`. It allows you to:\n * - Define features, row models, and default options once, shared across all tables\n * - Register reusable table, cell, and header components\n * - Access table/cell/header instances via context in those components\n * - Get a `useAppTable` hook that returns an extended table with App wrapper components\n * - Get a `createAppColumnHelper` function pre-bound to your features\n *\n * @example\n * ```tsx\n * // hooks/table.ts\n * export const {\n * useAppTable,\n * createAppColumnHelper,\n * useTableContext,\n * useCellContext,\n * useHeaderContext,\n * } = createTableHook({\n * _features: tableFeatures({\n * rowPaginationFeature,\n * rowSortingFeature,\n * columnFilteringFeature,\n * }),\n * _rowModels: {\n * paginatedRowModel: createPaginatedRowModel(),\n * sortedRowModel: createSortedRowModel(sortFns),\n * filteredRowModel: createFilteredRowModel(filterFns),\n * },\n * tableComponents: { PaginationControls, RowCount },\n * cellComponents: { TextCell, NumberCell },\n * headerComponents: { SortIndicator, ColumnFilter },\n * })\n *\n * // Create column helper with TFeatures already bound\n * const columnHelper = createAppColumnHelper<Person>()\n *\n * // components/table-components.tsx\n * function PaginationControls() {\n * const table = useTableContext() // TFeatures already known!\n * return <table.Subscribe selector={(s) => s.pagination}>...</table.Subscribe>\n * }\n *\n * // features/users.tsx\n * function UsersTable({ data }: { data: Person[] }) {\n * const table = useAppTable({\n * columns,\n * data, // TData inferred from Person[]\n * })\n *\n * return (\n * <table.AppTable>\n * <table>\n * <thead>\n * {table.getHeaderGroups().map(headerGroup => (\n * <tr key={headerGroup.id}>\n * {headerGroup.headers.map(h => (\n * <table.AppHeader header={h} key={h.id}>\n * {(header) => (\n * <th>\n * <table.FlexRender header={h} />\n * <header.SortIndicator />\n * </th>\n * )}\n * </table.AppHeader>\n * ))}\n * </tr>\n * ))}\n * </thead>\n * <tbody>\n * {table.getRowModel().rows.map(row => (\n * <tr key={row.id}>\n * {row.getAllCells().map(c => (\n * <table.AppCell cell={c} key={c.id}>\n * {(cell) => <td><cell.TextCell /></td>}\n * </table.AppCell>\n * ))}\n * </tr>\n * ))}\n * </tbody>\n * </table>\n * <table.PaginationControls />\n * </table.AppTable>\n * )\n * }\n * ```\n */\nexport function createTableHook<\n TFeatures extends TableFeatures,\n const TTableComponents extends Record<string, ComponentType<any>>,\n const TCellComponents extends Record<string, ComponentType<any>>,\n const THeaderComponents extends Record<string, ComponentType<any>>,\n>({\n tableComponents,\n cellComponents,\n headerComponents,\n ...defaultTableOptions\n}: CreateTableHookOptions<\n TFeatures,\n TTableComponents,\n TCellComponents,\n THeaderComponents\n>) {\n // Create contexts internally with TFeatures baked in\n const TableContext = createContext<PreactTable<TFeatures, any, any>>(\n null as never,\n )\n const CellContext = createContext<Cell<TFeatures, any, any>>(null as never)\n const HeaderContext = createContext<Header<TFeatures, any, any>>(\n null as never,\n )\n\n /**\n * Create a column helper pre-bound to the features and components configured in this table hook.\n * The cell, header, and footer contexts include pre-bound components (e.g., `cell.TextCell`).\n * @example\n * ```tsx\n * const columnHelper = createAppColumnHelper<Person>()\n *\n * const columns = [\n * columnHelper.accessor('firstName', {\n * header: 'First Name',\n * cell: ({ cell }) => <cell.TextCell />, // cell has pre-bound components!\n * }),\n * columnHelper.accessor('age', {\n * header: 'Age',\n * cell: ({ cell }) => <cell.NumberCell />,\n * }),\n * ]\n * ```\n */\n function createAppColumnHelper<TData extends RowData>(): AppColumnHelper<\n TFeatures,\n TData,\n TCellComponents,\n THeaderComponents\n > {\n // The runtime implementation is the same - components are attached at render time\n // This cast provides the enhanced types for column definitions\n return coreCreateColumnHelper<TFeatures, TData>() as AppColumnHelper<\n TFeatures,\n TData,\n TCellComponents,\n THeaderComponents\n >\n }\n\n /**\n * Access the table instance from within an `AppTable` wrapper.\n * Use this in custom `tableComponents` passed to `createTableHook`.\n * TFeatures is already known from the createTableHook call.\n *\n * @example\n * ```tsx\n * function PaginationControls() {\n * const table = useTableContext()\n * return (\n * <table.Subscribe selector={(s) => s.pagination}>\n * {(pagination) => (\n * <div>\n * <button onClick={() => table.previousPage()}>Prev</button>\n * <span>Page {pagination.pageIndex + 1}</span>\n * <button onClick={() => table.nextPage()}>Next</button>\n * </div>\n * )}\n * </table.Subscribe>\n * )\n * }\n * ```\n */\n function useTableContext<TData extends RowData = RowData>(): PreactTable<\n TFeatures,\n TData\n > {\n const table = useContext(TableContext)\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!table) {\n throw new Error(\n '`useTableContext` must be used within an `AppTable` component. ' +\n 'Make sure your component is wrapped with `<table.AppTable>...</table.AppTable>`.',\n )\n }\n\n return table as PreactTable<TFeatures, TData>\n }\n\n /**\n * Access the cell instance from within an `AppCell` wrapper.\n * Use this in custom `cellComponents` passed to `createTableHook`.\n * TFeatures is already known from the createTableHook call.\n *\n * @example\n * ```tsx\n * function TextCell() {\n * const cell = useCellContext<string>()\n * return <span>{cell.getValue()}</span>\n * }\n *\n * function NumberCell({ format }: { format?: Intl.NumberFormatOptions }) {\n * const cell = useCellContext<number>()\n * return <span>{cell.getValue().toLocaleString(undefined, format)}</span>\n * }\n * ```\n */\n function useCellContext<TValue extends CellData = CellData>() {\n const cell = useContext(CellContext)\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!cell) {\n throw new Error(\n '`useCellContext` must be used within an `AppCell` component. ' +\n 'Make sure your component is wrapped with `<table.AppCell cell={cell}>...</table.AppCell>`.',\n )\n }\n\n return cell as Cell<TFeatures, any, TValue>\n }\n\n /**\n * Access the header instance from within an `AppHeader` or `AppFooter` wrapper.\n * Use this in custom `headerComponents` passed to `createTableHook`.\n * TFeatures is already known from the createTableHook call.\n *\n * @example\n * ```tsx\n * function SortIndicator() {\n * const header = useHeaderContext()\n * const sorted = header.column.getIsSorted()\n * return sorted === 'asc' ? '🔼' : sorted === 'desc' ? '🔽' : null\n * }\n *\n * function ColumnFilter() {\n * const header = useHeaderContext()\n * if (!header.column.getCanFilter()) return null\n * return (\n * <input\n * value={(header.column.getFilterValue() ?? '') as string}\n * onChange={(e) => header.column.setFilterValue(e.target.value)}\n * placeholder=\"Filter...\"\n * />\n * )\n * }\n * ```\n */\n function useHeaderContext<TValue extends CellData = CellData>() {\n const header = useContext(HeaderContext)\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!header) {\n throw new Error(\n '`useHeaderContext` must be used within an `AppHeader` or `AppFooter` component.',\n )\n }\n\n return header as Header<TFeatures, any, TValue>\n }\n\n /**\n * Context-aware FlexRender component for cells.\n * Uses the cell from context, so no need to pass cell prop.\n */\n function CellFlexRender() {\n const cell = useCellContext()\n return <FlexRender cell={cell} />\n }\n\n /**\n * Context-aware FlexRender component for headers.\n * Uses the header from context, so no need to pass header prop.\n */\n function HeaderFlexRender() {\n const header = useHeaderContext()\n return <FlexRender header={header} />\n }\n\n /**\n * Context-aware FlexRender component for footers.\n * Uses the header from context, so no need to pass footer prop.\n */\n function FooterFlexRender() {\n const header = useHeaderContext()\n return <FlexRender footer={header} />\n }\n\n /**\n * Enhanced useTable hook that returns a table with App wrapper components\n * and pre-bound tableComponents attached directly to the table object.\n *\n * Default options from createTableHook are automatically merged with\n * the options passed here. Options passed here take precedence.\n *\n * TFeatures is already known from the createTableHook call; TData is inferred from the data prop.\n */\n function useAppTable<TData extends RowData, TSelected = {}>(\n tableOptions: Omit<\n TableOptions<TFeatures, TData>,\n '_features' | '_rowModels'\n >,\n selector?: (state: TableState<TFeatures>) => TSelected,\n ): AppPreactTable<\n TFeatures,\n TData,\n TSelected,\n TTableComponents,\n TCellComponents,\n THeaderComponents\n > {\n // Merge default options with provided options (provided takes precedence)\n const table = useTable<TFeatures, TData, TSelected>(\n { ...defaultTableOptions, ...tableOptions } as TableOptions<\n TFeatures,\n TData\n >,\n selector,\n )\n\n // AppTable - Root wrapper that provides table context with optional Subscribe\n const AppTable = useMemo(() => {\n function AppTableImpl(\n props: AppTablePropsWithoutSelector,\n ): ComponentChildren\n function AppTableImpl<TAppTableSelected>(\n props: AppTablePropsWithSelector<TFeatures, TAppTableSelected>,\n ): ComponentChildren\n function AppTableImpl<TAppTableSelected>(\n props:\n | AppTablePropsWithoutSelector\n | AppTablePropsWithSelector<TFeatures, TAppTableSelected>,\n ): ComponentChildren {\n const { children, selector: appTableSelector } = props as any\n\n return (\n <TableContext.Provider value={table}>\n {appTableSelector ? (\n <table.Subscribe selector={appTableSelector}>\n {(state: TAppTableSelected) =>\n (children as (state: TAppTableSelected) => ComponentChildren)(\n state,\n )\n }\n </table.Subscribe>\n ) : (\n children\n )}\n </TableContext.Provider>\n )\n }\n return AppTableImpl as AppTableComponent<TFeatures>\n }, [table])\n\n // AppCell - Wraps cell with context, pre-bound cellComponents, and optional Subscribe\n const AppCell = useMemo(() => {\n function AppCellImpl<TValue extends CellData = CellData>(\n props: AppCellPropsWithoutSelector<\n TFeatures,\n TData,\n TValue,\n TCellComponents\n >,\n ): ComponentChildren\n function AppCellImpl<\n TValue extends CellData = CellData,\n TAppCellSelected = unknown,\n >(\n props: AppCellPropsWithSelector<\n TFeatures,\n TData,\n TValue,\n TCellComponents,\n TAppCellSelected\n >,\n ): ComponentChildren\n function AppCellImpl<\n TValue extends CellData = CellData,\n TAppCellSelected = unknown,\n >(\n props:\n | AppCellPropsWithoutSelector<\n TFeatures,\n TData,\n TValue,\n TCellComponents\n >\n | AppCellPropsWithSelector<\n TFeatures,\n TData,\n TValue,\n TCellComponents,\n TAppCellSelected\n >,\n ): ComponentChildren {\n const { cell, children, selector: appCellSelector } = props as any\n const extendedCell = Object.assign(cell, {\n FlexRender: CellFlexRender,\n ...cellComponents,\n })\n\n return (\n <CellContext.Provider value={cell}>\n {appCellSelector ? (\n <table.Subscribe selector={appCellSelector}>\n {(state: TAppCellSelected) =>\n (\n children as (\n cell: Cell<TFeatures, TData, TValue> &\n TCellComponents & {\n FlexRender: () => ComponentChildren\n },\n state: TAppCellSelected,\n ) => ComponentChildren\n )(extendedCell, state)\n }\n </table.Subscribe>\n ) : (\n (\n children as (\n cell: Cell<TFeatures, TData, TValue> &\n TCellComponents & { FlexRender: () => ComponentChildren },\n ) => ComponentChildren\n )(extendedCell)\n )}\n </CellContext.Provider>\n )\n }\n return AppCellImpl as AppCellComponent<TFeatures, TData, TCellComponents>\n }, [table])\n\n // AppHeader - Wraps header with context, pre-bound headerComponents, and optional Subscribe\n const AppHeader = useMemo(() => {\n function AppHeaderImpl<TValue extends CellData = CellData>(\n props: AppHeaderPropsWithoutSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents\n >,\n ): ComponentChildren\n function AppHeaderImpl<\n TValue extends CellData = CellData,\n TAppHeaderSelected = unknown,\n >(\n props: AppHeaderPropsWithSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents,\n TAppHeaderSelected\n >,\n ): ComponentChildren\n function AppHeaderImpl<\n TValue extends CellData = CellData,\n TAppHeaderSelected = unknown,\n >(\n props:\n | AppHeaderPropsWithoutSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents\n >\n | AppHeaderPropsWithSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents,\n TAppHeaderSelected\n >,\n ): ComponentChildren {\n const { header, children, selector: appHeaderSelector } = props as any\n const extendedHeader = Object.assign(header, {\n FlexRender: HeaderFlexRender,\n ...headerComponents,\n })\n\n return (\n <HeaderContext.Provider value={header}>\n {appHeaderSelector ? (\n <table.Subscribe selector={appHeaderSelector}>\n {(state: TAppHeaderSelected) =>\n (\n children as (\n header: Header<TFeatures, TData, TValue> &\n THeaderComponents,\n state: TAppHeaderSelected,\n ) => ComponentChildren\n )(extendedHeader, state)\n }\n </table.Subscribe>\n ) : (\n (\n children as (\n header: Header<TFeatures, TData, TValue> &\n THeaderComponents & { FlexRender: () => ComponentChildren },\n ) => ComponentChildren\n )(extendedHeader)\n )}\n </HeaderContext.Provider>\n )\n }\n return AppHeaderImpl as AppHeaderComponent<\n TFeatures,\n TData,\n THeaderComponents\n >\n }, [table])\n\n // AppFooter - Same as AppHeader (footers use Header type)\n const AppFooter = useMemo(() => {\n function AppFooterImpl<TValue extends CellData = CellData>(\n props: AppHeaderPropsWithoutSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents\n >,\n ): ComponentChildren\n function AppFooterImpl<\n TValue extends CellData = CellData,\n TAppFooterSelected = unknown,\n >(\n props: AppHeaderPropsWithSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents,\n TAppFooterSelected\n >,\n ): ComponentChildren\n function AppFooterImpl<\n TValue extends CellData = CellData,\n TAppFooterSelected = unknown,\n >(\n props:\n | AppHeaderPropsWithoutSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents\n >\n | AppHeaderPropsWithSelector<\n TFeatures,\n TData,\n TValue,\n THeaderComponents,\n TAppFooterSelected\n >,\n ): ComponentChildren {\n const { header, children, selector: appFooterSelector } = props as any\n const extendedHeader = Object.assign(header, {\n FlexRender: FooterFlexRender,\n ...headerComponents,\n })\n\n return (\n <HeaderContext.Provider value={header}>\n {appFooterSelector ? (\n <table.Subscribe selector={appFooterSelector}>\n {(state: TAppFooterSelected) =>\n (\n children as (\n header: Header<TFeatures, TData, TValue> &\n THeaderComponents,\n state: TAppFooterSelected,\n ) => ComponentChildren\n )(extendedHeader, state)\n }\n </table.Subscribe>\n ) : (\n (\n children as (\n header: Header<TFeatures, TData, TValue> &\n THeaderComponents & { FlexRender: () => ComponentChildren },\n ) => ComponentChildren\n )(extendedHeader)\n )}\n </HeaderContext.Provider>\n )\n }\n return AppFooterImpl as AppHeaderComponent<\n TFeatures,\n TData,\n THeaderComponents\n >\n }, [table])\n\n // Combine everything into the extended table API\n const extendedTable = useMemo(() => {\n return Object.assign(table, {\n AppTable,\n AppCell,\n AppHeader,\n AppFooter,\n ...tableComponents,\n }) as AppPreactTable<\n TFeatures,\n TData,\n TSelected,\n TTableComponents,\n TCellComponents,\n THeaderComponents\n >\n }, [table, AppTable, AppCell, AppHeader, AppFooter])\n\n return extendedTable\n }\n\n return {\n appFeatures: defaultTableOptions._features as TFeatures,\n createAppColumnHelper,\n useAppTable,\n useTableContext,\n useCellContext,\n useHeaderContext,\n }\n}\n"],"names":[],"mappings":";;;;;;;AA+kBO;AAKL;AACA;AACA;AACA;AAEF;AAOE;AAAqB;AACnB;AAEF;AACA;AAAsB;AACpB;AAsBF;AAQE;AAAO;AA+BT;AAIE;AAGA;AACE;AAAU;AACR;AAAA;AAKJ;AAAO;AAqBT;AACE;AAGA;AACE;AAAU;AACR;AAAA;AAKJ;AAAO;AA6BT;AACE;AAGA;AACE;AAAU;AACR;AAAA;AAIJ;AAAO;AAOT;AACE;AACA;AAA+B;AAOjC;AACE;AACA;AAAmC;AAOrC;AACE;AACA;AAAmC;AAYrC;AAeE;AAAc;AACiB;AAI7B;AAIF;AAOE;AAKE;AAEA;AAKW;AACC;AAOV;AAGJ;AAAO;AAIT;AAqBE;AAmBE;AACA;AAAyC;AAC3B;AACT;AAGL;AAwBE;AAGJ;AAAO;AAIT;AAqBE;AAmBE;AACA;AAA6C;AAC/B;AACT;AAGL;AAsBE;AAGJ;AAAO;AAQT;AAqBE;AAmBE;AACA;AAA6C;AAC/B;AACT;AAGL;AAsBE;AAGJ;AAAO;AAQT;AACE;AAA4B;AAC1B;AACA;AACA;AACA;AACG;AACJ;AAUH;AAAO;AAGT;AAAO;AAC4B;AACjC;AACA;AACA;AACA;AACA;AAEJ;;;;"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export * from "@tanstack/table-core";
|
|
2
|
+
import { FlexRender, flexRender } from "./FlexRender.js";
|
|
3
|
+
import { Subscribe } from "./Subscribe.js";
|
|
4
|
+
import { createTableHook } from "./createTableHook.js";
|
|
5
|
+
import { useTable } from "./useTable.js";
|
|
6
|
+
export {
|
|
7
|
+
FlexRender,
|
|
8
|
+
Subscribe,
|
|
9
|
+
createTableHook,
|
|
10
|
+
flexRender,
|
|
11
|
+
useTable
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { CellData, NoInfer, RowData, Table, TableFeatures, TableOptions, TableState } from '@tanstack/table-core';
|
|
2
|
+
import { ComponentChildren } from 'preact';
|
|
3
|
+
import { FlexRenderProps } from './FlexRender.js';
|
|
4
|
+
export type PreactTable<TFeatures extends TableFeatures, TData extends RowData, TSelected = {}> = Table<TFeatures, TData> & {
|
|
5
|
+
/**
|
|
6
|
+
* A Preact HOC (Higher Order Component) that allows you to subscribe to the table state.
|
|
7
|
+
*
|
|
8
|
+
* This is useful for opting into state re-renders for specific parts of the table state.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* <table.Subscribe selector={(state) => ({ rowSelection: state.rowSelection })}>
|
|
12
|
+
* {({ rowSelection }) => ( // important to include `{() => {()}}` syntax
|
|
13
|
+
* <tr key={row.id}>
|
|
14
|
+
* // render the row
|
|
15
|
+
* </tr>
|
|
16
|
+
* )}
|
|
17
|
+
* </table.Subscribe>
|
|
18
|
+
*/
|
|
19
|
+
Subscribe: <TSelected>(props: {
|
|
20
|
+
selector: (state: NoInfer<TableState<TFeatures>>) => TSelected;
|
|
21
|
+
children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
|
|
22
|
+
}) => ComponentChildren;
|
|
23
|
+
/**
|
|
24
|
+
* A Preact component that renders headers, cells, or footers with custom markup.
|
|
25
|
+
* Use this utility component instead of manually calling flexRender.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```tsx
|
|
29
|
+
* <table.FlexRender cell={cell} />
|
|
30
|
+
* <table.FlexRender header={header} />
|
|
31
|
+
* <table.FlexRender footer={footer} />
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* This replaces calling `flexRender` directly like this:
|
|
35
|
+
* ```tsx
|
|
36
|
+
* flexRender(cell.column.columnDef.cell, cell.getContext())
|
|
37
|
+
* flexRender(header.column.columnDef.header, header.getContext())
|
|
38
|
+
* flexRender(footer.column.columnDef.footer, footer.getContext())
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
FlexRender: <TValue extends CellData = CellData>(props: FlexRenderProps<TFeatures, TData, TValue>) => ComponentChildren;
|
|
42
|
+
/**
|
|
43
|
+
* The selected state of the table. This state may not match the structure of `table.store.state` because it is selected by the `selector` function that you pass as the 2nd argument to `useTable`.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* const table = useTable(options, (state) => ({ globalFilter: state.globalFilter })) // only globalFilter is part of the selected state
|
|
47
|
+
*
|
|
48
|
+
* console.log(table.state.globalFilter)
|
|
49
|
+
*/
|
|
50
|
+
readonly state: Readonly<TSelected>;
|
|
51
|
+
};
|
|
52
|
+
export declare function useTable<TFeatures extends TableFeatures, TData extends RowData, TSelected = {}>(tableOptions: TableOptions<TFeatures, TData>, selector?: (state: TableState<TFeatures>) => TSelected): PreactTable<TFeatures, TData, TSelected>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { useState, useLayoutEffect, useEffect, useMemo } from "preact/hooks";
|
|
2
|
+
import { constructTable } from "@tanstack/table-core";
|
|
3
|
+
import { useStore } from "@tanstack/preact-store";
|
|
4
|
+
import { FlexRender } from "./FlexRender.js";
|
|
5
|
+
import { Subscribe } from "./Subscribe.js";
|
|
6
|
+
const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
|
|
7
|
+
function useTable(tableOptions, selector = () => ({})) {
|
|
8
|
+
const [table] = useState(() => {
|
|
9
|
+
const tableInstance = constructTable(tableOptions);
|
|
10
|
+
tableInstance.Subscribe = function SubscribeBound(props) {
|
|
11
|
+
return Subscribe({ ...props, table: tableInstance });
|
|
12
|
+
};
|
|
13
|
+
tableInstance.FlexRender = FlexRender;
|
|
14
|
+
return tableInstance;
|
|
15
|
+
});
|
|
16
|
+
table.setOptions((prev) => ({
|
|
17
|
+
...prev,
|
|
18
|
+
...tableOptions
|
|
19
|
+
}));
|
|
20
|
+
useIsomorphicLayoutEffect(() => {
|
|
21
|
+
queueMicrotask(() => {
|
|
22
|
+
table.baseStore.setState((prev) => ({
|
|
23
|
+
...prev
|
|
24
|
+
}));
|
|
25
|
+
});
|
|
26
|
+
}, [
|
|
27
|
+
table.options.columns,
|
|
28
|
+
// re-render when columns change
|
|
29
|
+
table.options.data,
|
|
30
|
+
// re-render when data changes
|
|
31
|
+
table.options.state
|
|
32
|
+
// sync preact state to the table store
|
|
33
|
+
]);
|
|
34
|
+
const state = useStore(table.store, selector);
|
|
35
|
+
return useMemo(
|
|
36
|
+
() => ({
|
|
37
|
+
...table,
|
|
38
|
+
state
|
|
39
|
+
}),
|
|
40
|
+
[state, table]
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
export {
|
|
44
|
+
useTable
|
|
45
|
+
};
|
|
46
|
+
//# sourceMappingURL=useTable.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useTable.js","sources":["../../src/useTable.ts"],"sourcesContent":["import { useEffect, useLayoutEffect, useMemo, useState } from 'preact/hooks'\nimport { constructTable } from '@tanstack/table-core'\nimport { useStore } from '@tanstack/preact-store'\nimport { FlexRender } from './FlexRender'\nimport { Subscribe } from './Subscribe'\nimport type {\n CellData,\n NoInfer,\n RowData,\n Table,\n TableFeatures,\n TableOptions,\n TableState,\n} from '@tanstack/table-core'\nimport type { ComponentChildren } from 'preact'\nimport type { FlexRenderProps } from './FlexRender'\nimport type { SubscribeProps } from './Subscribe'\n\nconst useIsomorphicLayoutEffect =\n typeof window !== 'undefined' ? useLayoutEffect : useEffect\n\nexport type PreactTable<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TSelected = {},\n> = Table<TFeatures, TData> & {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the table state.\n *\n * This is useful for opting into state re-renders for specific parts of the table state.\n *\n * @example\n * <table.Subscribe selector={(state) => ({ rowSelection: state.rowSelection })}>\n * {({ rowSelection }) => ( // important to include `{() => {()}}` syntax\n * <tr key={row.id}>\n * // render the row\n * </tr>\n * )}\n * </table.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: NoInfer<TableState<TFeatures>>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * A Preact component that renders headers, cells, or footers with custom markup.\n * Use this utility component instead of manually calling flexRender.\n *\n * @example\n * ```tsx\n * <table.FlexRender cell={cell} />\n * <table.FlexRender header={header} />\n * <table.FlexRender footer={footer} />\n * ```\n *\n * This replaces calling `flexRender` directly like this:\n * ```tsx\n * flexRender(cell.column.columnDef.cell, cell.getContext())\n * flexRender(header.column.columnDef.header, header.getContext())\n * flexRender(footer.column.columnDef.footer, footer.getContext())\n * ```\n */\n FlexRender: <TValue extends CellData = CellData>(\n props: FlexRenderProps<TFeatures, TData, TValue>,\n ) => ComponentChildren\n /**\n * The selected state of the table. This state may not match the structure of `table.store.state` because it is selected by the `selector` function that you pass as the 2nd argument to `useTable`.\n *\n * @example\n * const table = useTable(options, (state) => ({ globalFilter: state.globalFilter })) // only globalFilter is part of the selected state\n *\n * console.log(table.state.globalFilter)\n */\n readonly state: Readonly<TSelected>\n}\n\nexport function useTable<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TSelected = {},\n>(\n tableOptions: TableOptions<TFeatures, TData>,\n selector: (state: TableState<TFeatures>) => TSelected = () =>\n ({}) as TSelected,\n): PreactTable<TFeatures, TData, TSelected> {\n const [table] = useState(() => {\n const tableInstance = constructTable(tableOptions) as PreactTable<\n TFeatures,\n TData,\n TSelected\n >\n\n tableInstance.Subscribe = function SubscribeBound<TSelected>(\n props: Omit<SubscribeProps<TFeatures, TData, TSelected>, 'table'>,\n ) {\n return Subscribe({ ...props, table: tableInstance })\n }\n\n tableInstance.FlexRender = FlexRender\n\n return tableInstance\n })\n\n // sync table options on every render\n table.setOptions((prev) => ({\n ...prev,\n ...tableOptions,\n }))\n\n useIsomorphicLayoutEffect(() => {\n // prevent race condition between table.setOptions and table.baseStore.setState\n queueMicrotask(() => {\n table.baseStore.setState((prev) => ({\n ...prev,\n }))\n })\n }, [\n table.options.columns, // re-render when columns change\n table.options.data, // re-render when data changes\n table.options.state, // sync preact state to the table store\n ])\n\n const state = useStore(table.store, selector)\n\n return useMemo(\n () => ({\n ...table,\n state,\n }),\n [state, table],\n )\n}\n"],"names":[],"mappings":";;;;;AAkBA,MAAM,4BACJ,OAAO,WAAW,cAAc,kBAAkB;AAyD7C,SAAS,SAKd,cACA,WAAwD,OACrD,CAAA,IACuC;AAC1C,QAAM,CAAC,KAAK,IAAI,SAAS,MAAM;AAC7B,UAAM,gBAAgB,eAAe,YAAY;AAMjD,kBAAc,YAAY,SAAS,eACjC,OACA;AACA,aAAO,UAAU,EAAE,GAAG,OAAO,OAAO,eAAe;AAAA,IACrD;AAEA,kBAAc,aAAa;AAE3B,WAAO;AAAA,EACT,CAAC;AAGD,QAAM,WAAW,CAAC,UAAU;AAAA,IAC1B,GAAG;AAAA,IACH,GAAG;AAAA,EAAA,EACH;AAEF,4BAA0B,MAAM;AAE9B,mBAAe,MAAM;AACnB,YAAM,UAAU,SAAS,CAAC,UAAU;AAAA,QAClC,GAAG;AAAA,MAAA,EACH;AAAA,IACJ,CAAC;AAAA,EACH,GAAG;AAAA,IACD,MAAM,QAAQ;AAAA;AAAA,IACd,MAAM,QAAQ;AAAA;AAAA,IACd,MAAM,QAAQ;AAAA;AAAA,EAAA,CACf;AAED,QAAM,QAAQ,SAAS,MAAM,OAAO,QAAQ;AAE5C,SAAO;AAAA,IACL,OAAO;AAAA,MACL,GAAG;AAAA,MACH;AAAA,IAAA;AAAA,IAEF,CAAC,OAAO,KAAK;AAAA,EAAA;AAEjB;"}
|
package/package.json
CHANGED
|
@@ -1,10 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/preact-table",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "9.0.0-alpha.14",
|
|
4
|
+
"description": "Headless UI for building powerful tables & datagrids for Preact.",
|
|
5
|
+
"author": "Tanner Linsley",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/TanStack/table.git",
|
|
10
|
+
"directory": "packages/preact-table"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://tanstack.com/table",
|
|
13
|
+
"funding": {
|
|
14
|
+
"type": "github",
|
|
15
|
+
"url": "https://github.com/sponsors/tannerlinsley"
|
|
16
|
+
},
|
|
5
17
|
"keywords": [
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
|
|
18
|
+
"preact",
|
|
19
|
+
"table",
|
|
20
|
+
"preact-table",
|
|
21
|
+
"datagrid"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"types": "dist/esm/index.d.ts",
|
|
25
|
+
"main": "dist/esm/index.js",
|
|
26
|
+
"module": "dist/esm/index.js",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"import": {
|
|
30
|
+
"types": "./dist/esm/index.d.ts",
|
|
31
|
+
"default": "./dist/esm/index.js"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"sideEffects": false,
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=16"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"dist",
|
|
42
|
+
"src"
|
|
43
|
+
],
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"@tanstack/preact-store": "^0.11.1",
|
|
46
|
+
"@tanstack/table-core": "9.0.0-alpha.13"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@preact/preset-vite": "^2.10.3",
|
|
50
|
+
"preact": "^10.28.2"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"preact": ">=10"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"clean": "rimraf ./build && rimraf ./dist",
|
|
57
|
+
"test:eslint": "eslint ./src",
|
|
58
|
+
"test:lib": "vitest --passWithNoTests",
|
|
59
|
+
"test:lib:dev": "pnpm test:lib --watch",
|
|
60
|
+
"test:types": "tsc",
|
|
61
|
+
"test:build": "publint --strict",
|
|
62
|
+
"build": "vite build"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Cell,
|
|
3
|
+
CellData,
|
|
4
|
+
Header,
|
|
5
|
+
RowData,
|
|
6
|
+
TableFeatures,
|
|
7
|
+
} from '@tanstack/table-core'
|
|
8
|
+
import type { ComponentChild, ComponentType } from 'preact'
|
|
9
|
+
|
|
10
|
+
export type Renderable<TProps> = ComponentChild | ComponentType<TProps>
|
|
11
|
+
|
|
12
|
+
function isPreactComponent<TProps>(
|
|
13
|
+
component: unknown,
|
|
14
|
+
): component is ComponentType<TProps> {
|
|
15
|
+
return (
|
|
16
|
+
isClassComponent(component) ||
|
|
17
|
+
typeof component === 'function' ||
|
|
18
|
+
isExoticComponent(component)
|
|
19
|
+
)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function isClassComponent(component: any) {
|
|
23
|
+
return (
|
|
24
|
+
typeof component === 'function' &&
|
|
25
|
+
(() => {
|
|
26
|
+
const proto = Object.getPrototypeOf(component)
|
|
27
|
+
return proto.prototype && proto.prototype.isPreactComponent
|
|
28
|
+
})()
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isExoticComponent(component: any) {
|
|
33
|
+
return (
|
|
34
|
+
typeof component === 'object' &&
|
|
35
|
+
typeof component.$$typeof === 'symbol' &&
|
|
36
|
+
['preact.memo', 'preact.forward_ref'].includes(
|
|
37
|
+
component.$$typeof.description,
|
|
38
|
+
)
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.
|
|
44
|
+
* @example flexRender(cell.column.columnDef.cell, cell.getContext())
|
|
45
|
+
*/
|
|
46
|
+
export function flexRender<TProps extends object>(
|
|
47
|
+
Comp: Renderable<TProps> | null,
|
|
48
|
+
props: TProps,
|
|
49
|
+
): ComponentChild | Element | null {
|
|
50
|
+
return !Comp ? null : isPreactComponent<TProps>(Comp) ? (
|
|
51
|
+
<Comp {...props} />
|
|
52
|
+
) : (
|
|
53
|
+
Comp
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Simplified component wrapper of `flexRender`. Use this utility component to render headers, cells, or footers with custom markup.
|
|
59
|
+
* Only one prop (`cell`, `header`, or `footer`) may be passed.
|
|
60
|
+
* @example <FlexRender cell={cell} />
|
|
61
|
+
* @example <FlexRender header={header} />
|
|
62
|
+
* @example <FlexRender footer={footer} />
|
|
63
|
+
*/
|
|
64
|
+
export type FlexRenderProps<
|
|
65
|
+
TFeatures extends TableFeatures,
|
|
66
|
+
TData extends RowData,
|
|
67
|
+
TValue extends CellData = CellData,
|
|
68
|
+
> =
|
|
69
|
+
| { cell: Cell<TFeatures, TData, TValue>; header?: never; footer?: never }
|
|
70
|
+
| {
|
|
71
|
+
header: Header<TFeatures, TData, TValue>
|
|
72
|
+
cell?: never
|
|
73
|
+
footer?: never
|
|
74
|
+
}
|
|
75
|
+
| {
|
|
76
|
+
footer: Header<TFeatures, TData, TValue>
|
|
77
|
+
cell?: never
|
|
78
|
+
header?: never
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Simplified component wrapper of `flexRender`. Use this utility component to render headers, cells, or footers with custom markup.
|
|
83
|
+
* Only one prop (`cell`, `header`, or `footer`) may be passed.
|
|
84
|
+
* @example
|
|
85
|
+
* ```tsx
|
|
86
|
+
* <FlexRender cell={cell} />
|
|
87
|
+
* <FlexRender header={header} />
|
|
88
|
+
* <FlexRender footer={footer} />
|
|
89
|
+
* ```
|
|
90
|
+
*
|
|
91
|
+
* This replaces calling `flexRender` directly like this:
|
|
92
|
+
* ```tsx
|
|
93
|
+
* flexRender(cell.column.columnDef.cell, cell.getContext())
|
|
94
|
+
* flexRender(header.column.columnDef.header, header.getContext())
|
|
95
|
+
* flexRender(footer.column.columnDef.footer, footer.getContext())
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
export function FlexRender<
|
|
99
|
+
TFeatures extends TableFeatures,
|
|
100
|
+
TData extends RowData,
|
|
101
|
+
TValue extends CellData = CellData,
|
|
102
|
+
>(props: FlexRenderProps<TFeatures, TData, TValue>) {
|
|
103
|
+
if ('cell' in props && props.cell) {
|
|
104
|
+
return flexRender(props.cell.column.columnDef.cell, props.cell.getContext())
|
|
105
|
+
}
|
|
106
|
+
if ('header' in props && props.header) {
|
|
107
|
+
return flexRender(
|
|
108
|
+
props.header.column.columnDef.header,
|
|
109
|
+
props.header.getContext(),
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
if ('footer' in props && props.footer) {
|
|
113
|
+
return flexRender(
|
|
114
|
+
props.footer.column.columnDef.footer,
|
|
115
|
+
props.footer.getContext(),
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
return null
|
|
119
|
+
}
|
package/src/Subscribe.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { useStore } from '@tanstack/preact-store'
|
|
2
|
+
import type {
|
|
3
|
+
NoInfer,
|
|
4
|
+
RowData,
|
|
5
|
+
Table,
|
|
6
|
+
TableFeatures,
|
|
7
|
+
TableState,
|
|
8
|
+
} from '@tanstack/table-core'
|
|
9
|
+
import type { ComponentChildren } from 'preact'
|
|
10
|
+
|
|
11
|
+
export type SubscribeProps<
|
|
12
|
+
TFeatures extends TableFeatures,
|
|
13
|
+
TData extends RowData,
|
|
14
|
+
TSelected = {},
|
|
15
|
+
> = {
|
|
16
|
+
/**
|
|
17
|
+
* The table instance to subscribe to. Required when using as a standalone component.
|
|
18
|
+
* Not needed when using as `table.Subscribe`.
|
|
19
|
+
*/
|
|
20
|
+
table: Table<TFeatures, TData>
|
|
21
|
+
/**
|
|
22
|
+
* A selector function that selects the part of the table state to subscribe to.
|
|
23
|
+
* This allows for fine-grained reactivity by only re-rendering when the selected state changes.
|
|
24
|
+
*/
|
|
25
|
+
selector: (state: NoInfer<TableState<TFeatures>>) => TSelected
|
|
26
|
+
/**
|
|
27
|
+
* The children to render. Can be a function that receives the selected state, or a Preact node.
|
|
28
|
+
*/
|
|
29
|
+
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A Preact component that allows you to subscribe to the table state.
|
|
34
|
+
*
|
|
35
|
+
* This is useful for opting into state re-renders for specific parts of the table state.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```tsx
|
|
39
|
+
* // As a standalone component
|
|
40
|
+
* <Subscribe table={table} selector={(state) => ({ rowSelection: state.rowSelection })}>
|
|
41
|
+
* {({ rowSelection }) => (
|
|
42
|
+
* <div>Selected rows: {Object.keys(rowSelection).length}</div>
|
|
43
|
+
* )}
|
|
44
|
+
* </Subscribe>
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```tsx
|
|
49
|
+
* // As table.Subscribe (table instance method)
|
|
50
|
+
* <table.Subscribe selector={(state) => ({ rowSelection: state.rowSelection })}>
|
|
51
|
+
* {({ rowSelection }) => (
|
|
52
|
+
* <div>Selected rows: {Object.keys(rowSelection).length}</div>
|
|
53
|
+
* )}
|
|
54
|
+
* </table.Subscribe>
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export function Subscribe<
|
|
58
|
+
TFeatures extends TableFeatures,
|
|
59
|
+
TData extends RowData,
|
|
60
|
+
TSelected = {},
|
|
61
|
+
>(props: SubscribeProps<TFeatures, TData, TSelected>): ComponentChildren {
|
|
62
|
+
const selected = useStore(props.table.store, props.selector)
|
|
63
|
+
|
|
64
|
+
return typeof props.children === 'function'
|
|
65
|
+
? props.children(selected)
|
|
66
|
+
: props.children
|
|
67
|
+
}
|