feat: robust metric extraction with confidence score and proof snippets

- fixed Year-Prefix Bug in MetricParser
- added metric_confidence and metric_proof_text to database
- added Entity-Check and Annual-Priority to LLM prompt
- improved UI: added confidence traffic light and mouse-over proof tooltip
- restored missing API endpoints (create, bulk, wiki-override)
This commit is contained in:
2026-01-23 21:16:07 +00:00
parent c5652fc9b5
commit e43e129771
7006 changed files with 1367435 additions and 201 deletions

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Tanner Linsley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,9 @@
import * as React from 'react';
export * from '@tanstack/table-core';
import { TableOptions, RowData } from '@tanstack/table-core';
export type Renderable<TProps> = React.ReactNode | React.ComponentType<TProps>;
/**
* If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.
*/
export declare function flexRender<TProps extends object>(Comp: Renderable<TProps>, props: TProps): React.ReactNode | React.JSX.Element;
export declare function useReactTable<TData extends RowData>(options: TableOptions<TData>): import("@tanstack/table-core").Table<TData>;

View File

@@ -0,0 +1,74 @@
/**
* react-table
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
import * as React from 'react';
import { createTable } from '@tanstack/table-core';
export * from '@tanstack/table-core';
//
/**
* If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.
*/
function flexRender(Comp, props) {
return !Comp ? null : isReactComponent(Comp) ? /*#__PURE__*/React.createElement(Comp, props) : Comp;
}
function isReactComponent(component) {
return isClassComponent(component) || typeof component === 'function' || isExoticComponent(component);
}
function isClassComponent(component) {
return typeof component === 'function' && (() => {
const proto = Object.getPrototypeOf(component);
return proto.prototype && proto.prototype.isReactComponent;
})();
}
function isExoticComponent(component) {
return typeof component === 'object' && typeof component.$$typeof === 'symbol' && ['react.memo', 'react.forward_ref'].includes(component.$$typeof.description);
}
function useReactTable(options) {
// Compose in the generic options to the user options
const resolvedOptions = {
state: {},
// Dummy state
onStateChange: () => {},
// noop
renderFallbackValue: null,
...options
};
// Create a new table and store it in state
const [tableRef] = React.useState(() => ({
current: createTable(resolvedOptions)
}));
// By default, manage table state here using the table's initial state
const [state, setState] = React.useState(() => tableRef.current.initialState);
// Compose the default state above with any user state. This will allow the user
// to only control a subset of the state if desired.
tableRef.current.setOptions(prev => ({
...prev,
...options,
state: {
...state,
...options.state
},
// Similarly, we'll maintain both our internal state and any user-provided
// state.
onStateChange: updater => {
setState(updater);
options.onStateChange == null || options.onStateChange(updater);
}
}));
return tableRef.current;
}
export { flexRender, useReactTable };
//# sourceMappingURL=index.esm.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.esm.js","sources":["../../src/index.tsx"],"sourcesContent":["import * as React from 'react'\nexport * from '@tanstack/table-core'\n\nimport {\n TableOptions,\n TableOptionsResolved,\n RowData,\n createTable,\n} from '@tanstack/table-core'\n\nexport type Renderable<TProps> = React.ReactNode | React.ComponentType<TProps>\n\n//\n\n/**\n * If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.\n */\nexport function flexRender<TProps extends object>(\n Comp: Renderable<TProps>,\n props: TProps\n): React.ReactNode | React.JSX.Element {\n return !Comp ? null : isReactComponent<TProps>(Comp) ? (\n <Comp {...props} />\n ) : (\n Comp\n )\n}\n\nfunction isReactComponent<TProps>(\n component: unknown\n): component is React.ComponentType<TProps> {\n return (\n isClassComponent(component) ||\n typeof component === 'function' ||\n isExoticComponent(component)\n )\n}\n\nfunction isClassComponent(component: any) {\n return (\n typeof component === 'function' &&\n (() => {\n const proto = Object.getPrototypeOf(component)\n return proto.prototype && proto.prototype.isReactComponent\n })()\n )\n}\n\nfunction isExoticComponent(component: any) {\n return (\n typeof component === 'object' &&\n typeof component.$$typeof === 'symbol' &&\n ['react.memo', 'react.forward_ref'].includes(component.$$typeof.description)\n )\n}\n\nexport function useReactTable<TData extends RowData>(\n options: TableOptions<TData>\n) {\n // Compose in the generic options to the user options\n const resolvedOptions: TableOptionsResolved<TData> = {\n state: {}, // Dummy state\n onStateChange: () => {}, // noop\n renderFallbackValue: null,\n ...options,\n }\n\n // Create a new table and store it in state\n const [tableRef] = React.useState(() => ({\n current: createTable<TData>(resolvedOptions),\n }))\n\n // By default, manage table state here using the table's initial state\n const [state, setState] = React.useState(() => tableRef.current.initialState)\n\n // Compose the default state above with any user state. This will allow the user\n // to only control a subset of the state if desired.\n tableRef.current.setOptions(prev => ({\n ...prev,\n ...options,\n state: {\n ...state,\n ...options.state,\n },\n // Similarly, we'll maintain both our internal state and any user-provided\n // state.\n onStateChange: updater => {\n setState(updater)\n options.onStateChange?.(updater)\n },\n }))\n\n return tableRef.current\n}\n"],"names":["flexRender","Comp","props","isReactComponent","React","createElement","component","isClassComponent","isExoticComponent","proto","Object","getPrototypeOf","prototype","$$typeof","includes","description","useReactTable","options","resolvedOptions","state","onStateChange","renderFallbackValue","tableRef","useState","current","createTable","setState","initialState","setOptions","prev","updater"],"mappings":";;;;;;;;;;;;;;AAYA;;AAEA;AACA;AACA;AACO,SAASA,UAAUA,CACxBC,IAAwB,EACxBC,KAAa,EACwB;AACrC,EAAA,OAAO,CAACD,IAAI,GAAG,IAAI,GAAGE,gBAAgB,CAASF,IAAI,CAAC,gBAClDG,KAAA,CAAAC,aAAA,CAACJ,IAAI,EAAKC,KAAQ,CAAC,GAEnBD,IACD,CAAA;AACH,CAAA;AAEA,SAASE,gBAAgBA,CACvBG,SAAkB,EACwB;AAC1C,EAAA,OACEC,gBAAgB,CAACD,SAAS,CAAC,IAC3B,OAAOA,SAAS,KAAK,UAAU,IAC/BE,iBAAiB,CAACF,SAAS,CAAC,CAAA;AAEhC,CAAA;AAEA,SAASC,gBAAgBA,CAACD,SAAc,EAAE;AACxC,EAAA,OACE,OAAOA,SAAS,KAAK,UAAU,IAC/B,CAAC,MAAM;AACL,IAAA,MAAMG,KAAK,GAAGC,MAAM,CAACC,cAAc,CAACL,SAAS,CAAC,CAAA;IAC9C,OAAOG,KAAK,CAACG,SAAS,IAAIH,KAAK,CAACG,SAAS,CAACT,gBAAgB,CAAA;AAC5D,GAAC,GAAG,CAAA;AAER,CAAA;AAEA,SAASK,iBAAiBA,CAACF,SAAc,EAAE;EACzC,OACE,OAAOA,SAAS,KAAK,QAAQ,IAC7B,OAAOA,SAAS,CAACO,QAAQ,KAAK,QAAQ,IACtC,CAAC,YAAY,EAAE,mBAAmB,CAAC,CAACC,QAAQ,CAACR,SAAS,CAACO,QAAQ,CAACE,WAAW,CAAC,CAAA;AAEhF,CAAA;AAEO,SAASC,aAAaA,CAC3BC,OAA4B,EAC5B;AACA;AACA,EAAA,MAAMC,eAA4C,GAAG;IACnDC,KAAK,EAAE,EAAE;AAAE;AACXC,IAAAA,aAAa,EAAEA,MAAM,EAAE;AAAE;AACzBC,IAAAA,mBAAmB,EAAE,IAAI;IACzB,GAAGJ,OAAAA;GACJ,CAAA;;AAED;EACA,MAAM,CAACK,QAAQ,CAAC,GAAGlB,KAAK,CAACmB,QAAQ,CAAC,OAAO;IACvCC,OAAO,EAAEC,WAAW,CAAQP,eAAe,CAAA;AAC7C,GAAC,CAAC,CAAC,CAAA;;AAEH;AACA,EAAA,MAAM,CAACC,KAAK,EAAEO,QAAQ,CAAC,GAAGtB,KAAK,CAACmB,QAAQ,CAAC,MAAMD,QAAQ,CAACE,OAAO,CAACG,YAAY,CAAC,CAAA;;AAE7E;AACA;AACAL,EAAAA,QAAQ,CAACE,OAAO,CAACI,UAAU,CAACC,IAAI,KAAK;AACnC,IAAA,GAAGA,IAAI;AACP,IAAA,GAAGZ,OAAO;AACVE,IAAAA,KAAK,EAAE;AACL,MAAA,GAAGA,KAAK;AACR,MAAA,GAAGF,OAAO,CAACE,KAAAA;KACZ;AACD;AACA;IACAC,aAAa,EAAEU,OAAO,IAAI;MACxBJ,QAAQ,CAACI,OAAO,CAAC,CAAA;MACjBb,OAAO,CAACG,aAAa,IAArBH,IAAAA,IAAAA,OAAO,CAACG,aAAa,CAAGU,OAAO,CAAC,CAAA;AAClC,KAAA;AACF,GAAC,CAAC,CAAC,CAAA;EAEH,OAAOR,QAAQ,CAACE,OAAO,CAAA;AACzB;;;;"}

View File

@@ -0,0 +1,101 @@
/**
* react-table
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var React = require('react');
var tableCore = require('@tanstack/table-core');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
//
/**
* If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.
*/
function flexRender(Comp, props) {
return !Comp ? null : isReactComponent(Comp) ? /*#__PURE__*/React__namespace.createElement(Comp, props) : Comp;
}
function isReactComponent(component) {
return isClassComponent(component) || typeof component === 'function' || isExoticComponent(component);
}
function isClassComponent(component) {
return typeof component === 'function' && (() => {
const proto = Object.getPrototypeOf(component);
return proto.prototype && proto.prototype.isReactComponent;
})();
}
function isExoticComponent(component) {
return typeof component === 'object' && typeof component.$$typeof === 'symbol' && ['react.memo', 'react.forward_ref'].includes(component.$$typeof.description);
}
function useReactTable(options) {
// Compose in the generic options to the user options
const resolvedOptions = {
state: {},
// Dummy state
onStateChange: () => {},
// noop
renderFallbackValue: null,
...options
};
// Create a new table and store it in state
const [tableRef] = React__namespace.useState(() => ({
current: tableCore.createTable(resolvedOptions)
}));
// By default, manage table state here using the table's initial state
const [state, setState] = React__namespace.useState(() => tableRef.current.initialState);
// Compose the default state above with any user state. This will allow the user
// to only control a subset of the state if desired.
tableRef.current.setOptions(prev => ({
...prev,
...options,
state: {
...state,
...options.state
},
// Similarly, we'll maintain both our internal state and any user-provided
// state.
onStateChange: updater => {
setState(updater);
options.onStateChange == null || options.onStateChange(updater);
}
}));
return tableRef.current;
}
exports.flexRender = flexRender;
exports.useReactTable = useReactTable;
Object.keys(tableCore).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return tableCore[k]; }
});
});
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../src/index.tsx"],"sourcesContent":["import * as React from 'react'\nexport * from '@tanstack/table-core'\n\nimport {\n TableOptions,\n TableOptionsResolved,\n RowData,\n createTable,\n} from '@tanstack/table-core'\n\nexport type Renderable<TProps> = React.ReactNode | React.ComponentType<TProps>\n\n//\n\n/**\n * If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.\n */\nexport function flexRender<TProps extends object>(\n Comp: Renderable<TProps>,\n props: TProps\n): React.ReactNode | React.JSX.Element {\n return !Comp ? null : isReactComponent<TProps>(Comp) ? (\n <Comp {...props} />\n ) : (\n Comp\n )\n}\n\nfunction isReactComponent<TProps>(\n component: unknown\n): component is React.ComponentType<TProps> {\n return (\n isClassComponent(component) ||\n typeof component === 'function' ||\n isExoticComponent(component)\n )\n}\n\nfunction isClassComponent(component: any) {\n return (\n typeof component === 'function' &&\n (() => {\n const proto = Object.getPrototypeOf(component)\n return proto.prototype && proto.prototype.isReactComponent\n })()\n )\n}\n\nfunction isExoticComponent(component: any) {\n return (\n typeof component === 'object' &&\n typeof component.$$typeof === 'symbol' &&\n ['react.memo', 'react.forward_ref'].includes(component.$$typeof.description)\n )\n}\n\nexport function useReactTable<TData extends RowData>(\n options: TableOptions<TData>\n) {\n // Compose in the generic options to the user options\n const resolvedOptions: TableOptionsResolved<TData> = {\n state: {}, // Dummy state\n onStateChange: () => {}, // noop\n renderFallbackValue: null,\n ...options,\n }\n\n // Create a new table and store it in state\n const [tableRef] = React.useState(() => ({\n current: createTable<TData>(resolvedOptions),\n }))\n\n // By default, manage table state here using the table's initial state\n const [state, setState] = React.useState(() => tableRef.current.initialState)\n\n // Compose the default state above with any user state. This will allow the user\n // to only control a subset of the state if desired.\n tableRef.current.setOptions(prev => ({\n ...prev,\n ...options,\n state: {\n ...state,\n ...options.state,\n },\n // Similarly, we'll maintain both our internal state and any user-provided\n // state.\n onStateChange: updater => {\n setState(updater)\n options.onStateChange?.(updater)\n },\n }))\n\n return tableRef.current\n}\n"],"names":["flexRender","Comp","props","isReactComponent","React","createElement","component","isClassComponent","isExoticComponent","proto","Object","getPrototypeOf","prototype","$$typeof","includes","description","useReactTable","options","resolvedOptions","state","onStateChange","renderFallbackValue","tableRef","useState","current","createTable","setState","initialState","setOptions","prev","updater"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA;;AAEA;AACA;AACA;AACO,SAASA,UAAUA,CACxBC,IAAwB,EACxBC,KAAa,EACwB;AACrC,EAAA,OAAO,CAACD,IAAI,GAAG,IAAI,GAAGE,gBAAgB,CAASF,IAAI,CAAC,gBAClDG,gBAAA,CAAAC,aAAA,CAACJ,IAAI,EAAKC,KAAQ,CAAC,GAEnBD,IACD,CAAA;AACH,CAAA;AAEA,SAASE,gBAAgBA,CACvBG,SAAkB,EACwB;AAC1C,EAAA,OACEC,gBAAgB,CAACD,SAAS,CAAC,IAC3B,OAAOA,SAAS,KAAK,UAAU,IAC/BE,iBAAiB,CAACF,SAAS,CAAC,CAAA;AAEhC,CAAA;AAEA,SAASC,gBAAgBA,CAACD,SAAc,EAAE;AACxC,EAAA,OACE,OAAOA,SAAS,KAAK,UAAU,IAC/B,CAAC,MAAM;AACL,IAAA,MAAMG,KAAK,GAAGC,MAAM,CAACC,cAAc,CAACL,SAAS,CAAC,CAAA;IAC9C,OAAOG,KAAK,CAACG,SAAS,IAAIH,KAAK,CAACG,SAAS,CAACT,gBAAgB,CAAA;AAC5D,GAAC,GAAG,CAAA;AAER,CAAA;AAEA,SAASK,iBAAiBA,CAACF,SAAc,EAAE;EACzC,OACE,OAAOA,SAAS,KAAK,QAAQ,IAC7B,OAAOA,SAAS,CAACO,QAAQ,KAAK,QAAQ,IACtC,CAAC,YAAY,EAAE,mBAAmB,CAAC,CAACC,QAAQ,CAACR,SAAS,CAACO,QAAQ,CAACE,WAAW,CAAC,CAAA;AAEhF,CAAA;AAEO,SAASC,aAAaA,CAC3BC,OAA4B,EAC5B;AACA;AACA,EAAA,MAAMC,eAA4C,GAAG;IACnDC,KAAK,EAAE,EAAE;AAAE;AACXC,IAAAA,aAAa,EAAEA,MAAM,EAAE;AAAE;AACzBC,IAAAA,mBAAmB,EAAE,IAAI;IACzB,GAAGJ,OAAAA;GACJ,CAAA;;AAED;EACA,MAAM,CAACK,QAAQ,CAAC,GAAGlB,gBAAK,CAACmB,QAAQ,CAAC,OAAO;IACvCC,OAAO,EAAEC,qBAAW,CAAQP,eAAe,CAAA;AAC7C,GAAC,CAAC,CAAC,CAAA;;AAEH;AACA,EAAA,MAAM,CAACC,KAAK,EAAEO,QAAQ,CAAC,GAAGtB,gBAAK,CAACmB,QAAQ,CAAC,MAAMD,QAAQ,CAACE,OAAO,CAACG,YAAY,CAAC,CAAA;;AAE7E;AACA;AACAL,EAAAA,QAAQ,CAACE,OAAO,CAACI,UAAU,CAACC,IAAI,KAAK;AACnC,IAAA,GAAGA,IAAI;AACP,IAAA,GAAGZ,OAAO;AACVE,IAAAA,KAAK,EAAE;AACL,MAAA,GAAGA,KAAK;AACR,MAAA,GAAGF,OAAO,CAACE,KAAAA;KACZ;AACD;AACA;IACAC,aAAa,EAAEU,OAAO,IAAI;MACxBJ,QAAQ,CAACI,OAAO,CAAC,CAAA;MACjBb,OAAO,CAACG,aAAa,IAArBH,IAAAA,IAAAA,OAAO,CAACG,aAAa,CAAGU,OAAO,CAAC,CAAA;AAClC,KAAA;AACF,GAAC,CAAC,CAAC,CAAA;EAEH,OAAOR,QAAQ,CAACE,OAAO,CAAA;AACzB;;;;;;;;;;;"}

View File

@@ -0,0 +1,74 @@
/**
* react-table
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
import * as React from 'react';
import { createTable } from '@tanstack/table-core';
export * from '@tanstack/table-core';
//
/**
* If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.
*/
function flexRender(Comp, props) {
return !Comp ? null : isReactComponent(Comp) ? /*#__PURE__*/React.createElement(Comp, props) : Comp;
}
function isReactComponent(component) {
return isClassComponent(component) || typeof component === 'function' || isExoticComponent(component);
}
function isClassComponent(component) {
return typeof component === 'function' && (() => {
const proto = Object.getPrototypeOf(component);
return proto.prototype && proto.prototype.isReactComponent;
})();
}
function isExoticComponent(component) {
return typeof component === 'object' && typeof component.$$typeof === 'symbol' && ['react.memo', 'react.forward_ref'].includes(component.$$typeof.description);
}
function useReactTable(options) {
// Compose in the generic options to the user options
const resolvedOptions = {
state: {},
// Dummy state
onStateChange: () => {},
// noop
renderFallbackValue: null,
...options
};
// Create a new table and store it in state
const [tableRef] = React.useState(() => ({
current: createTable(resolvedOptions)
}));
// By default, manage table state here using the table's initial state
const [state, setState] = React.useState(() => tableRef.current.initialState);
// Compose the default state above with any user state. This will allow the user
// to only control a subset of the state if desired.
tableRef.current.setOptions(prev => ({
...prev,
...options,
state: {
...state,
...options.state
},
// Similarly, we'll maintain both our internal state and any user-provided
// state.
onStateChange: updater => {
setState(updater);
options.onStateChange == null || options.onStateChange(updater);
}
}));
return tableRef.current;
}
export { flexRender, useReactTable };
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../src/index.tsx"],"sourcesContent":["import * as React from 'react'\nexport * from '@tanstack/table-core'\n\nimport {\n TableOptions,\n TableOptionsResolved,\n RowData,\n createTable,\n} from '@tanstack/table-core'\n\nexport type Renderable<TProps> = React.ReactNode | React.ComponentType<TProps>\n\n//\n\n/**\n * If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.\n */\nexport function flexRender<TProps extends object>(\n Comp: Renderable<TProps>,\n props: TProps\n): React.ReactNode | React.JSX.Element {\n return !Comp ? null : isReactComponent<TProps>(Comp) ? (\n <Comp {...props} />\n ) : (\n Comp\n )\n}\n\nfunction isReactComponent<TProps>(\n component: unknown\n): component is React.ComponentType<TProps> {\n return (\n isClassComponent(component) ||\n typeof component === 'function' ||\n isExoticComponent(component)\n )\n}\n\nfunction isClassComponent(component: any) {\n return (\n typeof component === 'function' &&\n (() => {\n const proto = Object.getPrototypeOf(component)\n return proto.prototype && proto.prototype.isReactComponent\n })()\n )\n}\n\nfunction isExoticComponent(component: any) {\n return (\n typeof component === 'object' &&\n typeof component.$$typeof === 'symbol' &&\n ['react.memo', 'react.forward_ref'].includes(component.$$typeof.description)\n )\n}\n\nexport function useReactTable<TData extends RowData>(\n options: TableOptions<TData>\n) {\n // Compose in the generic options to the user options\n const resolvedOptions: TableOptionsResolved<TData> = {\n state: {}, // Dummy state\n onStateChange: () => {}, // noop\n renderFallbackValue: null,\n ...options,\n }\n\n // Create a new table and store it in state\n const [tableRef] = React.useState(() => ({\n current: createTable<TData>(resolvedOptions),\n }))\n\n // By default, manage table state here using the table's initial state\n const [state, setState] = React.useState(() => tableRef.current.initialState)\n\n // Compose the default state above with any user state. This will allow the user\n // to only control a subset of the state if desired.\n tableRef.current.setOptions(prev => ({\n ...prev,\n ...options,\n state: {\n ...state,\n ...options.state,\n },\n // Similarly, we'll maintain both our internal state and any user-provided\n // state.\n onStateChange: updater => {\n setState(updater)\n options.onStateChange?.(updater)\n },\n }))\n\n return tableRef.current\n}\n"],"names":["flexRender","Comp","props","isReactComponent","React","createElement","component","isClassComponent","isExoticComponent","proto","Object","getPrototypeOf","prototype","$$typeof","includes","description","useReactTable","options","resolvedOptions","state","onStateChange","renderFallbackValue","tableRef","useState","current","createTable","setState","initialState","setOptions","prev","updater"],"mappings":";;;;;;;;;;;;;;AAYA;;AAEA;AACA;AACA;AACO,SAASA,UAAUA,CACxBC,IAAwB,EACxBC,KAAa,EACwB;AACrC,EAAA,OAAO,CAACD,IAAI,GAAG,IAAI,GAAGE,gBAAgB,CAASF,IAAI,CAAC,gBAClDG,KAAA,CAAAC,aAAA,CAACJ,IAAI,EAAKC,KAAQ,CAAC,GAEnBD,IACD,CAAA;AACH,CAAA;AAEA,SAASE,gBAAgBA,CACvBG,SAAkB,EACwB;AAC1C,EAAA,OACEC,gBAAgB,CAACD,SAAS,CAAC,IAC3B,OAAOA,SAAS,KAAK,UAAU,IAC/BE,iBAAiB,CAACF,SAAS,CAAC,CAAA;AAEhC,CAAA;AAEA,SAASC,gBAAgBA,CAACD,SAAc,EAAE;AACxC,EAAA,OACE,OAAOA,SAAS,KAAK,UAAU,IAC/B,CAAC,MAAM;AACL,IAAA,MAAMG,KAAK,GAAGC,MAAM,CAACC,cAAc,CAACL,SAAS,CAAC,CAAA;IAC9C,OAAOG,KAAK,CAACG,SAAS,IAAIH,KAAK,CAACG,SAAS,CAACT,gBAAgB,CAAA;AAC5D,GAAC,GAAG,CAAA;AAER,CAAA;AAEA,SAASK,iBAAiBA,CAACF,SAAc,EAAE;EACzC,OACE,OAAOA,SAAS,KAAK,QAAQ,IAC7B,OAAOA,SAAS,CAACO,QAAQ,KAAK,QAAQ,IACtC,CAAC,YAAY,EAAE,mBAAmB,CAAC,CAACC,QAAQ,CAACR,SAAS,CAACO,QAAQ,CAACE,WAAW,CAAC,CAAA;AAEhF,CAAA;AAEO,SAASC,aAAaA,CAC3BC,OAA4B,EAC5B;AACA;AACA,EAAA,MAAMC,eAA4C,GAAG;IACnDC,KAAK,EAAE,EAAE;AAAE;AACXC,IAAAA,aAAa,EAAEA,MAAM,EAAE;AAAE;AACzBC,IAAAA,mBAAmB,EAAE,IAAI;IACzB,GAAGJ,OAAAA;GACJ,CAAA;;AAED;EACA,MAAM,CAACK,QAAQ,CAAC,GAAGlB,KAAK,CAACmB,QAAQ,CAAC,OAAO;IACvCC,OAAO,EAAEC,WAAW,CAAQP,eAAe,CAAA;AAC7C,GAAC,CAAC,CAAC,CAAA;;AAEH;AACA,EAAA,MAAM,CAACC,KAAK,EAAEO,QAAQ,CAAC,GAAGtB,KAAK,CAACmB,QAAQ,CAAC,MAAMD,QAAQ,CAACE,OAAO,CAACG,YAAY,CAAC,CAAA;;AAE7E;AACA;AACAL,EAAAA,QAAQ,CAACE,OAAO,CAACI,UAAU,CAACC,IAAI,KAAK;AACnC,IAAA,GAAGA,IAAI;AACP,IAAA,GAAGZ,OAAO;AACVE,IAAAA,KAAK,EAAE;AACL,MAAA,GAAGA,KAAK;AACR,MAAA,GAAGF,OAAO,CAACE,KAAAA;KACZ;AACD;AACA;IACAC,aAAa,EAAEU,OAAO,IAAI;MACxBJ,QAAQ,CAACI,OAAO,CAAC,CAAA;MACjBb,OAAO,CAACG,aAAa,IAArBH,IAAAA,IAAAA,OAAO,CAACG,aAAa,CAAGU,OAAO,CAAC,CAAA;AAClC,KAAA;AACF,GAAC,CAAC,CAAC,CAAA;EAEH,OAAOR,QAAQ,CAACE,OAAO,CAAA;AACzB;;;;"}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,56 @@
{
"name": "@tanstack/react-table",
"version": "8.21.3",
"description": "Headless UI for building powerful tables & datagrids for React.",
"author": "Tanner Linsley",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/TanStack/table.git",
"directory": "packages/react-table"
},
"homepage": "https://tanstack.com/table",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"keywords": [
"react",
"table",
"react-table",
"datagrid"
],
"type": "commonjs",
"module": "build/lib/index.esm.js",
"main": "build/lib/index.js",
"types": "build/lib/index.d.ts",
"exports": {
".": {
"types": "./build/lib/index.d.ts",
"import": "./build/lib/index.mjs",
"default": "./build/lib/index.js"
},
"./package.json": "./package.json"
},
"sideEffects": false,
"engines": {
"node": ">=12"
},
"files": [
"build/lib/*",
"build/umd/*",
"src"
],
"dependencies": {
"@tanstack/table-core": "8.21.3"
},
"devDependencies": {
"@types/react": "^18.3.3",
"react": "^18.3.1"
},
"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
},
"scripts": {}
}

View File

@@ -0,0 +1,94 @@
import * as React from 'react'
export * from '@tanstack/table-core'
import {
TableOptions,
TableOptionsResolved,
RowData,
createTable,
} from '@tanstack/table-core'
export type Renderable<TProps> = React.ReactNode | React.ComponentType<TProps>
//
/**
* If rendering headers, cells, or footers with custom markup, use flexRender instead of `cell.getValue()` or `cell.renderValue()`.
*/
export function flexRender<TProps extends object>(
Comp: Renderable<TProps>,
props: TProps
): React.ReactNode | React.JSX.Element {
return !Comp ? null : isReactComponent<TProps>(Comp) ? (
<Comp {...props} />
) : (
Comp
)
}
function isReactComponent<TProps>(
component: unknown
): component is React.ComponentType<TProps> {
return (
isClassComponent(component) ||
typeof component === 'function' ||
isExoticComponent(component)
)
}
function isClassComponent(component: any) {
return (
typeof component === 'function' &&
(() => {
const proto = Object.getPrototypeOf(component)
return proto.prototype && proto.prototype.isReactComponent
})()
)
}
function isExoticComponent(component: any) {
return (
typeof component === 'object' &&
typeof component.$$typeof === 'symbol' &&
['react.memo', 'react.forward_ref'].includes(component.$$typeof.description)
)
}
export function useReactTable<TData extends RowData>(
options: TableOptions<TData>
) {
// Compose in the generic options to the user options
const resolvedOptions: TableOptionsResolved<TData> = {
state: {}, // Dummy state
onStateChange: () => {}, // noop
renderFallbackValue: null,
...options,
}
// Create a new table and store it in state
const [tableRef] = React.useState(() => ({
current: createTable<TData>(resolvedOptions),
}))
// By default, manage table state here using the table's initial state
const [state, setState] = React.useState(() => tableRef.current.initialState)
// Compose the default state above with any user state. This will allow the user
// to only control a subset of the state if desired.
tableRef.current.setOptions(prev => ({
...prev,
...options,
state: {
...state,
...options.state,
},
// Similarly, we'll maintain both our internal state and any user-provided
// state.
onStateChange: updater => {
setState(updater)
options.onStateChange?.(updater)
},
}))
return tableRef.current
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Tanner Linsley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,13 @@
import { AggregationFn } from './features/ColumnGrouping';
export declare const aggregationFns: {
sum: AggregationFn<any>;
min: AggregationFn<any>;
max: AggregationFn<any>;
extent: AggregationFn<any>;
mean: AggregationFn<any>;
median: AggregationFn<any>;
unique: AggregationFn<any>;
uniqueCount: AggregationFn<any>;
count: AggregationFn<any>;
};
export type BuiltInAggregationFn = keyof typeof aggregationFns;

View File

@@ -0,0 +1,108 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('./utils.js');
const sum = (columnId, _leafRows, childRows) => {
// It's faster to just add the aggregations together instead of
// process leaf nodes individually
return childRows.reduce((sum, next) => {
const nextValue = next.getValue(columnId);
return sum + (typeof nextValue === 'number' ? nextValue : 0);
}, 0);
};
const min = (columnId, _leafRows, childRows) => {
let min;
childRows.forEach(row => {
const value = row.getValue(columnId);
if (value != null && (min > value || min === undefined && value >= value)) {
min = value;
}
});
return min;
};
const max = (columnId, _leafRows, childRows) => {
let max;
childRows.forEach(row => {
const value = row.getValue(columnId);
if (value != null && (max < value || max === undefined && value >= value)) {
max = value;
}
});
return max;
};
const extent = (columnId, _leafRows, childRows) => {
let min;
let max;
childRows.forEach(row => {
const value = row.getValue(columnId);
if (value != null) {
if (min === undefined) {
if (value >= value) min = max = value;
} else {
if (min > value) min = value;
if (max < value) max = value;
}
}
});
return [min, max];
};
const mean = (columnId, leafRows) => {
let count = 0;
let sum = 0;
leafRows.forEach(row => {
let value = row.getValue(columnId);
if (value != null && (value = +value) >= value) {
++count, sum += value;
}
});
if (count) return sum / count;
return;
};
const median = (columnId, leafRows) => {
if (!leafRows.length) {
return;
}
const values = leafRows.map(row => row.getValue(columnId));
if (!utils.isNumberArray(values)) {
return;
}
if (values.length === 1) {
return values[0];
}
const mid = Math.floor(values.length / 2);
const nums = values.sort((a, b) => a - b);
return values.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
const unique = (columnId, leafRows) => {
return Array.from(new Set(leafRows.map(d => d.getValue(columnId))).values());
};
const uniqueCount = (columnId, leafRows) => {
return new Set(leafRows.map(d => d.getValue(columnId))).size;
};
const count = (_columnId, leafRows) => {
return leafRows.length;
};
const aggregationFns = {
sum,
min,
max,
extent,
mean,
median,
unique,
uniqueCount,
count
};
exports.aggregationFns = aggregationFns;
//# sourceMappingURL=aggregationFns.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
import { AccessorFn, AccessorFnColumnDef, AccessorKeyColumnDef, DisplayColumnDef, GroupColumnDef, IdentifiedColumnDef, RowData } from './types';
import { DeepKeys, DeepValue } from './utils';
export type ColumnHelper<TData extends RowData> = {
accessor: <TAccessor extends AccessorFn<TData> | DeepKeys<TData>, TValue extends TAccessor extends AccessorFn<TData, infer TReturn> ? TReturn : TAccessor extends DeepKeys<TData> ? DeepValue<TData, TAccessor> : never>(accessor: TAccessor, column: TAccessor extends AccessorFn<TData> ? DisplayColumnDef<TData, TValue> : IdentifiedColumnDef<TData, TValue>) => TAccessor extends AccessorFn<TData> ? AccessorFnColumnDef<TData, TValue> : AccessorKeyColumnDef<TData, TValue>;
display: (column: DisplayColumnDef<TData>) => DisplayColumnDef<TData, unknown>;
group: (column: GroupColumnDef<TData>) => GroupColumnDef<TData, unknown>;
};
export declare function createColumnHelper<TData extends RowData>(): ColumnHelper<TData>;

View File

@@ -0,0 +1,71 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
// type Person = {
// firstName: string
// lastName: string
// age: number
// visits: number
// status: string
// progress: number
// createdAt: Date
// nested: {
// foo: [
// {
// bar: 'bar'
// }
// ]
// bar: { subBar: boolean }[]
// baz: {
// foo: 'foo'
// bar: {
// baz: 'baz'
// }
// }
// }
// }
// const test: DeepKeys<Person> = 'nested.foo.0.bar'
// const test2: DeepKeys<Person> = 'nested.bar'
// const helper = createColumnHelper<Person>()
// helper.accessor('nested.foo', {
// cell: info => info.getValue(),
// })
// helper.accessor('nested.foo.0.bar', {
// cell: info => info.getValue(),
// })
// helper.accessor('nested.bar', {
// cell: info => info.getValue(),
// })
function createColumnHelper() {
return {
accessor: (accessor, column) => {
return typeof accessor === 'function' ? {
...column,
accessorFn: accessor
} : {
...column,
accessorKey: accessor
};
},
display: column => column,
group: column => column
};
}
exports.createColumnHelper = createColumnHelper;
//# sourceMappingURL=columnHelper.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"columnHelper.js","sources":["../../src/columnHelper.ts"],"sourcesContent":["import {\n AccessorFn,\n AccessorFnColumnDef,\n AccessorKeyColumnDef,\n DisplayColumnDef,\n GroupColumnDef,\n IdentifiedColumnDef,\n RowData,\n} from './types'\nimport { DeepKeys, DeepValue } from './utils'\n\n// type Person = {\n// firstName: string\n// lastName: string\n// age: number\n// visits: number\n// status: string\n// progress: number\n// createdAt: Date\n// nested: {\n// foo: [\n// {\n// bar: 'bar'\n// }\n// ]\n// bar: { subBar: boolean }[]\n// baz: {\n// foo: 'foo'\n// bar: {\n// baz: 'baz'\n// }\n// }\n// }\n// }\n\n// const test: DeepKeys<Person> = 'nested.foo.0.bar'\n// const test2: DeepKeys<Person> = 'nested.bar'\n\n// const helper = createColumnHelper<Person>()\n\n// helper.accessor('nested.foo', {\n// cell: info => info.getValue(),\n// })\n\n// helper.accessor('nested.foo.0.bar', {\n// cell: info => info.getValue(),\n// })\n\n// helper.accessor('nested.bar', {\n// cell: info => info.getValue(),\n// })\n\nexport type ColumnHelper<TData extends RowData> = {\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 ? DisplayColumnDef<TData, TValue>\n : IdentifiedColumnDef<TData, TValue>\n ) => TAccessor extends AccessorFn<TData>\n ? AccessorFnColumnDef<TData, TValue>\n : AccessorKeyColumnDef<TData, TValue>\n display: (column: DisplayColumnDef<TData>) => DisplayColumnDef<TData, unknown>\n group: (column: GroupColumnDef<TData>) => GroupColumnDef<TData, unknown>\n}\n\nexport function createColumnHelper<\n TData extends RowData,\n>(): ColumnHelper<TData> {\n return {\n accessor: (accessor, column) => {\n return typeof accessor === 'function'\n ? ({\n ...column,\n accessorFn: accessor,\n } as any)\n : {\n ...column,\n accessorKey: accessor,\n }\n },\n display: column => column,\n group: column => column,\n }\n}\n"],"names":["createColumnHelper","accessor","column","accessorFn","accessorKey","display","group"],"mappings":";;;;;;;;;;;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAsBO,SAASA,kBAAkBA,GAET;EACvB,OAAO;AACLC,IAAAA,QAAQ,EAAEA,CAACA,QAAQ,EAAEC,MAAM,KAAK;AAC9B,MAAA,OAAO,OAAOD,QAAQ,KAAK,UAAU,GAChC;AACC,QAAA,GAAGC,MAAM;AACTC,QAAAA,UAAU,EAAEF,QAAAA;AACd,OAAC,GACD;AACE,QAAA,GAAGC,MAAM;AACTE,QAAAA,WAAW,EAAEH,QAAAA;OACd,CAAA;KACN;IACDI,OAAO,EAAEH,MAAM,IAAIA,MAAM;IACzBI,KAAK,EAAEJ,MAAM,IAAIA,MAAAA;GAClB,CAAA;AACH;;;;"}

View File

@@ -0,0 +1,49 @@
import { RowData, Cell, Column, Row, Table } from '../types';
import { Getter } from '../utils';
export interface CellContext<TData extends RowData, TValue> {
cell: Cell<TData, TValue>;
column: Column<TData, TValue>;
getValue: Getter<TValue>;
renderValue: Getter<TValue | null>;
row: Row<TData>;
table: Table<TData>;
}
export interface CoreCell<TData extends RowData, TValue> {
/**
* The associated Column object for the cell.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#column)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)
*/
column: Column<TData, TValue>;
/**
* Returns the rendering context (or props) for cell-based components like cells and aggregated cells. Use these props with your framework's `flexRender` utility to render these using the template of your choice:
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#getcontext)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)
*/
getContext: () => CellContext<TData, TValue>;
/**
* Returns the value for the cell, accessed via the associated column's accessor key or accessor function.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#getvalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)
*/
getValue: CellContext<TData, TValue>['getValue'];
/**
* The unique ID for the cell across the entire table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#id)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)
*/
id: string;
/**
* Renders the value for a cell the same as `getValue`, but will return the `renderFallbackValue` if no value is found.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#rendervalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)
*/
renderValue: CellContext<TData, TValue>['renderValue'];
/**
* The associated Row object for the cell.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#row)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)
*/
row: Row<TData>;
}
export declare function createCell<TData extends RowData, TValue>(table: Table<TData>, row: Row<TData>, column: Column<TData, TValue>, columnId: string): Cell<TData, TValue>;

View File

@@ -0,0 +1,42 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
function createCell(table, row, column, columnId) {
const getRenderValue = () => {
var _cell$getValue;
return (_cell$getValue = cell.getValue()) != null ? _cell$getValue : table.options.renderFallbackValue;
};
const cell = {
id: `${row.id}_${column.id}`,
row,
column,
getValue: () => row.getValue(columnId),
renderValue: getRenderValue,
getContext: utils.memo(() => [table, column, row, cell], (table, column, row, cell) => ({
table,
column,
row,
cell: cell,
getValue: cell.getValue,
renderValue: cell.renderValue
}), utils.getMemoOptions(table.options, 'debugCells', 'cell.getContext'))
};
table._features.forEach(feature => {
feature.createCell == null || feature.createCell(cell, column, row, table);
}, {});
return cell;
}
exports.createCell = createCell;
//# sourceMappingURL=cell.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cell.js","sources":["../../../src/core/cell.ts"],"sourcesContent":["import { RowData, Cell, Column, Row, Table } from '../types'\nimport { Getter, getMemoOptions, memo } from '../utils'\n\nexport interface CellContext<TData extends RowData, TValue> {\n cell: Cell<TData, TValue>\n column: Column<TData, TValue>\n getValue: Getter<TValue>\n renderValue: Getter<TValue | null>\n row: Row<TData>\n table: Table<TData>\n}\n\nexport interface CoreCell<TData extends RowData, TValue> {\n /**\n * The associated Column object for the cell.\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#column)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)\n */\n column: Column<TData, TValue>\n /**\n * Returns the rendering context (or props) for cell-based components like cells and aggregated cells. Use these props with your framework's `flexRender` utility to render these using the template of your choice:\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#getcontext)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)\n */\n getContext: () => CellContext<TData, TValue>\n /**\n * Returns the value for the cell, accessed via the associated column's accessor key or accessor function.\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#getvalue)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)\n */\n getValue: CellContext<TData, TValue>['getValue']\n /**\n * The unique ID for the cell across the entire table.\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#id)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)\n */\n id: string\n /**\n * Renders the value for a cell the same as `getValue`, but will return the `renderFallbackValue` if no value is found.\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#rendervalue)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)\n */\n renderValue: CellContext<TData, TValue>['renderValue']\n /**\n * The associated Row object for the cell.\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/core/cell#row)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/cells)\n */\n row: Row<TData>\n}\n\nexport function createCell<TData extends RowData, TValue>(\n table: Table<TData>,\n row: Row<TData>,\n column: Column<TData, TValue>,\n columnId: string\n): Cell<TData, TValue> {\n const getRenderValue = () =>\n cell.getValue() ?? table.options.renderFallbackValue\n\n const cell: CoreCell<TData, TValue> = {\n id: `${row.id}_${column.id}`,\n row,\n column,\n getValue: () => row.getValue(columnId),\n renderValue: getRenderValue,\n getContext: memo(\n () => [table, column, row, cell],\n (table, column, row, cell) => ({\n table,\n column,\n row,\n cell: cell as Cell<TData, TValue>,\n getValue: cell.getValue,\n renderValue: cell.renderValue,\n }),\n getMemoOptions(table.options, 'debugCells', 'cell.getContext')\n ),\n }\n\n table._features.forEach(feature => {\n feature.createCell?.(\n cell as Cell<TData, TValue>,\n column,\n row as Row<TData>,\n table\n )\n }, {})\n\n return cell as Cell<TData, TValue>\n}\n"],"names":["createCell","table","row","column","columnId","getRenderValue","_cell$getValue","cell","getValue","options","renderFallbackValue","id","renderValue","getContext","memo","getMemoOptions","_features","forEach","feature"],"mappings":";;;;;;;;;;;;;;AAmDO,SAASA,UAAUA,CACxBC,KAAmB,EACnBC,GAAe,EACfC,MAA6B,EAC7BC,QAAgB,EACK;EACrB,MAAMC,cAAc,GAAGA,MAAA;AAAA,IAAA,IAAAC,cAAA,CAAA;AAAA,IAAA,OAAA,CAAAA,cAAA,GACrBC,IAAI,CAACC,QAAQ,EAAE,KAAAF,IAAAA,GAAAA,cAAA,GAAIL,KAAK,CAACQ,OAAO,CAACC,mBAAmB,CAAA;AAAA,GAAA,CAAA;AAEtD,EAAA,MAAMH,IAA6B,GAAG;IACpCI,EAAE,EAAE,GAAGT,GAAG,CAACS,EAAE,CAAIR,CAAAA,EAAAA,MAAM,CAACQ,EAAE,CAAE,CAAA;IAC5BT,GAAG;IACHC,MAAM;IACNK,QAAQ,EAAEA,MAAMN,GAAG,CAACM,QAAQ,CAACJ,QAAQ,CAAC;AACtCQ,IAAAA,WAAW,EAAEP,cAAc;IAC3BQ,UAAU,EAAEC,UAAI,CACd,MAAM,CAACb,KAAK,EAAEE,MAAM,EAAED,GAAG,EAAEK,IAAI,CAAC,EAChC,CAACN,KAAK,EAAEE,MAAM,EAAED,GAAG,EAAEK,IAAI,MAAM;MAC7BN,KAAK;MACLE,MAAM;MACND,GAAG;AACHK,MAAAA,IAAI,EAAEA,IAA2B;MACjCC,QAAQ,EAAED,IAAI,CAACC,QAAQ;MACvBI,WAAW,EAAEL,IAAI,CAACK,WAAAA;KACnB,CAAC,EACFG,oBAAc,CAACd,KAAK,CAACQ,OAAO,EAAE,YAAY,EAAE,iBAAiB,CAC/D,CAAA;GACD,CAAA;AAEDR,EAAAA,KAAK,CAACe,SAAS,CAACC,OAAO,CAACC,OAAO,IAAI;AACjCA,IAAAA,OAAO,CAAClB,UAAU,IAAlBkB,IAAAA,IAAAA,OAAO,CAAClB,UAAU,CAChBO,IAAI,EACJJ,MAAM,EACND,GAAG,EACHD,KACF,CAAC,CAAA;GACF,EAAE,EAAE,CAAC,CAAA;AAEN,EAAA,OAAOM,IAAI,CAAA;AACb;;;;"}

View File

@@ -0,0 +1,55 @@
import { Column, Table, AccessorFn, ColumnDef, RowData } from '../types';
export interface CoreColumn<TData extends RowData, TValue> {
/**
* The resolved accessor function to use when extracting the value for the column from each row. Will only be defined if the column def has a valid accessor key or function defined.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/column#accessorfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-defs)
*/
accessorFn?: AccessorFn<TData, TValue>;
/**
* The original column def used to create the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/column#columndef)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-defs)
*/
columnDef: ColumnDef<TData, TValue>;
/**
* The child column (if the column is a group column). Will be an empty array if the column is not a group column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/column#columns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-defs)
*/
columns: Column<TData, TValue>[];
/**
* The depth of the column (if grouped) relative to the root column def array.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/column#depth)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-defs)
*/
depth: number;
/**
* Returns the flattened array of this column and all child/grand-child columns for this column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/column#getflatcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-defs)
*/
getFlatColumns: () => Column<TData, TValue>[];
/**
* Returns an array of all leaf-node columns for this column. If a column has no children, it is considered the only leaf-node column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/column#getleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-defs)
*/
getLeafColumns: () => Column<TData, TValue>[];
/**
* The resolved unique identifier for the column resolved in this priority:
- A manual `id` property from the column def
- The accessor key from the column def
- The header string from the column def
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/column#id)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-defs)
*/
id: string;
/**
* The parent column for this column. Will be undefined if this is a root column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/column#parent)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-defs)
*/
parent?: Column<TData, TValue>;
}
export declare function createColumn<TData extends RowData, TValue>(table: Table<TData>, columnDef: ColumnDef<TData, TValue>, depth: number, parent?: Column<TData, TValue>): Column<TData, TValue>;

View File

@@ -0,0 +1,80 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
function createColumn(table, columnDef, depth, parent) {
var _ref, _resolvedColumnDef$id;
const defaultColumn = table._getDefaultColumnDef();
const resolvedColumnDef = {
...defaultColumn,
...columnDef
};
const accessorKey = resolvedColumnDef.accessorKey;
let id = (_ref = (_resolvedColumnDef$id = resolvedColumnDef.id) != null ? _resolvedColumnDef$id : accessorKey ? typeof String.prototype.replaceAll === 'function' ? accessorKey.replaceAll('.', '_') : accessorKey.replace(/\./g, '_') : undefined) != null ? _ref : typeof resolvedColumnDef.header === 'string' ? resolvedColumnDef.header : undefined;
let accessorFn;
if (resolvedColumnDef.accessorFn) {
accessorFn = resolvedColumnDef.accessorFn;
} else if (accessorKey) {
// Support deep accessor keys
if (accessorKey.includes('.')) {
accessorFn = originalRow => {
let result = originalRow;
for (const key of accessorKey.split('.')) {
var _result;
result = (_result = result) == null ? void 0 : _result[key];
if (process.env.NODE_ENV !== 'production' && result === undefined) {
console.warn(`"${key}" in deeply nested key "${accessorKey}" returned undefined.`);
}
}
return result;
};
} else {
accessorFn = originalRow => originalRow[resolvedColumnDef.accessorKey];
}
}
if (!id) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(resolvedColumnDef.accessorFn ? `Columns require an id when using an accessorFn` : `Columns require an id when using a non-string header`);
}
throw new Error();
}
let column = {
id: `${String(id)}`,
accessorFn,
parent: parent,
depth,
columnDef: resolvedColumnDef,
columns: [],
getFlatColumns: utils.memo(() => [true], () => {
var _column$columns;
return [column, ...((_column$columns = column.columns) == null ? void 0 : _column$columns.flatMap(d => d.getFlatColumns()))];
}, utils.getMemoOptions(table.options, 'debugColumns', 'column.getFlatColumns')),
getLeafColumns: utils.memo(() => [table._getOrderColumnsFn()], orderColumns => {
var _column$columns2;
if ((_column$columns2 = column.columns) != null && _column$columns2.length) {
let leafColumns = column.columns.flatMap(column => column.getLeafColumns());
return orderColumns(leafColumns);
}
return [column];
}, utils.getMemoOptions(table.options, 'debugColumns', 'column.getLeafColumns'))
};
for (const feature of table._features) {
feature.createColumn == null || feature.createColumn(column, table);
}
// Yes, we have to convert table to unknown, because we know more than the compiler here.
return column;
}
exports.createColumn = createColumn;
//# sourceMappingURL=column.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,194 @@
import { RowData, Column, Header, HeaderGroup, Table, TableFeature } from '../types';
export interface CoreHeaderGroup<TData extends RowData> {
depth: number;
headers: Header<TData, unknown>[];
id: string;
}
export interface HeaderContext<TData, TValue> {
/**
* An instance of a column.
*/
column: Column<TData, TValue>;
/**
* An instance of a header.
*/
header: Header<TData, TValue>;
/**
* The table instance.
*/
table: Table<TData>;
}
export interface CoreHeader<TData extends RowData, TValue> {
/**
* The col-span for the header.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#colspan)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
colSpan: number;
/**
* The header's associated column object.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#column)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
column: Column<TData, TValue>;
/**
* The depth of the header, zero-indexed based.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#depth)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
depth: number;
/**
* Returns the rendering context (or props) for column-based components like headers, footers and filters.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#getcontext)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getContext: () => HeaderContext<TData, TValue>;
/**
* Returns the leaf headers hierarchically nested under this header.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#getleafheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getLeafHeaders: () => Header<TData, unknown>[];
/**
* The header's associated header group object.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#headergroup)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
headerGroup: HeaderGroup<TData>;
/**
* The unique identifier for the header.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#id)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
id: string;
/**
* The index for the header within the header group.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#index)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
index: number;
/**
* A boolean denoting if the header is a placeholder header.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#isplaceholder)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
isPlaceholder: boolean;
/**
* If the header is a placeholder header, this will be a unique header ID that does not conflict with any other headers across the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#placeholderid)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
placeholderId?: string;
/**
* The row-span for the header.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#rowspan)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
rowSpan: number;
/**
* The header's hierarchical sub/child headers. Will be empty if the header's associated column is a leaf-column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/header#subheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
subHeaders: Header<TData, TValue>[];
}
export interface HeadersInstance<TData extends RowData> {
/**
* Returns all header groups for the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getheadergroups)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getHeaderGroups: () => HeaderGroup<TData>[];
/**
* If pinning, returns the header groups for the left pinned columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getleftheadergroups)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getLeftHeaderGroups: () => HeaderGroup<TData>[];
/**
* If pinning, returns the header groups for columns that are not pinned.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getcenterheadergroups)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getCenterHeaderGroups: () => HeaderGroup<TData>[];
/**
* If pinning, returns the header groups for the right pinned columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getrightheadergroups)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getRightHeaderGroups: () => HeaderGroup<TData>[];
/**
* Returns the footer groups for the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getfootergroups)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getFooterGroups: () => HeaderGroup<TData>[];
/**
* If pinning, returns the footer groups for the left pinned columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getleftfootergroups)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getLeftFooterGroups: () => HeaderGroup<TData>[];
/**
* If pinning, returns the footer groups for columns that are not pinned.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getcenterfootergroups)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getCenterFooterGroups: () => HeaderGroup<TData>[];
/**
* If pinning, returns the footer groups for the right pinned columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getrightfootergroups)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getRightFooterGroups: () => HeaderGroup<TData>[];
/**
* Returns headers for all columns in the table, including parent headers.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getflatheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getFlatHeaders: () => Header<TData, unknown>[];
/**
* If pinning, returns headers for all left pinned columns in the table, including parent headers.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getleftflatheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getLeftFlatHeaders: () => Header<TData, unknown>[];
/**
* If pinning, returns headers for all columns that are not pinned, including parent headers.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getcenterflatheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getCenterFlatHeaders: () => Header<TData, unknown>[];
/**
* If pinning, returns headers for all right pinned columns in the table, including parent headers.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getrightflatheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getRightFlatHeaders: () => Header<TData, unknown>[];
/**
* Returns headers for all leaf columns in the table, (not including parent headers).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getleafheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getLeafHeaders: () => Header<TData, unknown>[];
/**
* If pinning, returns headers for all left pinned leaf columns in the table, (not including parent headers).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getleftleafheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getLeftLeafHeaders: () => Header<TData, unknown>[];
/**
* If pinning, returns headers for all columns that are not pinned, (not including parent headers).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getcenterleafheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getCenterLeafHeaders: () => Header<TData, unknown>[];
/**
* If pinning, returns headers for all right pinned leaf columns in the table, (not including parent headers).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/headers#getrightleafheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/headers)
*/
getRightLeafHeaders: () => Header<TData, unknown>[];
}
export declare const Headers: TableFeature;
export declare function buildHeaderGroups<TData extends RowData>(allColumns: Column<TData, unknown>[], columnsToGroup: Column<TData, unknown>[], table: Table<TData>, headerFamily?: 'center' | 'left' | 'right'): HeaderGroup<TData>[];

View File

@@ -0,0 +1,270 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
const debug = 'debugHeaders';
//
function createHeader(table, column, options) {
var _options$id;
const id = (_options$id = options.id) != null ? _options$id : column.id;
let header = {
id,
column,
index: options.index,
isPlaceholder: !!options.isPlaceholder,
placeholderId: options.placeholderId,
depth: options.depth,
subHeaders: [],
colSpan: 0,
rowSpan: 0,
headerGroup: null,
getLeafHeaders: () => {
const leafHeaders = [];
const recurseHeader = h => {
if (h.subHeaders && h.subHeaders.length) {
h.subHeaders.map(recurseHeader);
}
leafHeaders.push(h);
};
recurseHeader(header);
return leafHeaders;
},
getContext: () => ({
table,
header: header,
column
})
};
table._features.forEach(feature => {
feature.createHeader == null || feature.createHeader(header, table);
});
return header;
}
const Headers = {
createTable: table => {
// Header Groups
table.getHeaderGroups = utils.memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => {
var _left$map$filter, _right$map$filter;
const leftColumns = (_left$map$filter = left == null ? void 0 : left.map(columnId => leafColumns.find(d => d.id === columnId)).filter(Boolean)) != null ? _left$map$filter : [];
const rightColumns = (_right$map$filter = right == null ? void 0 : right.map(columnId => leafColumns.find(d => d.id === columnId)).filter(Boolean)) != null ? _right$map$filter : [];
const centerColumns = leafColumns.filter(column => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id)));
const headerGroups = buildHeaderGroups(allColumns, [...leftColumns, ...centerColumns, ...rightColumns], table);
return headerGroups;
}, utils.getMemoOptions(table.options, debug, 'getHeaderGroups'));
table.getCenterHeaderGroups = utils.memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => {
leafColumns = leafColumns.filter(column => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id)));
return buildHeaderGroups(allColumns, leafColumns, table, 'center');
}, utils.getMemoOptions(table.options, debug, 'getCenterHeaderGroups'));
table.getLeftHeaderGroups = utils.memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left], (allColumns, leafColumns, left) => {
var _left$map$filter2;
const orderedLeafColumns = (_left$map$filter2 = left == null ? void 0 : left.map(columnId => leafColumns.find(d => d.id === columnId)).filter(Boolean)) != null ? _left$map$filter2 : [];
return buildHeaderGroups(allColumns, orderedLeafColumns, table, 'left');
}, utils.getMemoOptions(table.options, debug, 'getLeftHeaderGroups'));
table.getRightHeaderGroups = utils.memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.right], (allColumns, leafColumns, right) => {
var _right$map$filter2;
const orderedLeafColumns = (_right$map$filter2 = right == null ? void 0 : right.map(columnId => leafColumns.find(d => d.id === columnId)).filter(Boolean)) != null ? _right$map$filter2 : [];
return buildHeaderGroups(allColumns, orderedLeafColumns, table, 'right');
}, utils.getMemoOptions(table.options, debug, 'getRightHeaderGroups'));
// Footer Groups
table.getFooterGroups = utils.memo(() => [table.getHeaderGroups()], headerGroups => {
return [...headerGroups].reverse();
}, utils.getMemoOptions(table.options, debug, 'getFooterGroups'));
table.getLeftFooterGroups = utils.memo(() => [table.getLeftHeaderGroups()], headerGroups => {
return [...headerGroups].reverse();
}, utils.getMemoOptions(table.options, debug, 'getLeftFooterGroups'));
table.getCenterFooterGroups = utils.memo(() => [table.getCenterHeaderGroups()], headerGroups => {
return [...headerGroups].reverse();
}, utils.getMemoOptions(table.options, debug, 'getCenterFooterGroups'));
table.getRightFooterGroups = utils.memo(() => [table.getRightHeaderGroups()], headerGroups => {
return [...headerGroups].reverse();
}, utils.getMemoOptions(table.options, debug, 'getRightFooterGroups'));
// Flat Headers
table.getFlatHeaders = utils.memo(() => [table.getHeaderGroups()], headerGroups => {
return headerGroups.map(headerGroup => {
return headerGroup.headers;
}).flat();
}, utils.getMemoOptions(table.options, debug, 'getFlatHeaders'));
table.getLeftFlatHeaders = utils.memo(() => [table.getLeftHeaderGroups()], left => {
return left.map(headerGroup => {
return headerGroup.headers;
}).flat();
}, utils.getMemoOptions(table.options, debug, 'getLeftFlatHeaders'));
table.getCenterFlatHeaders = utils.memo(() => [table.getCenterHeaderGroups()], left => {
return left.map(headerGroup => {
return headerGroup.headers;
}).flat();
}, utils.getMemoOptions(table.options, debug, 'getCenterFlatHeaders'));
table.getRightFlatHeaders = utils.memo(() => [table.getRightHeaderGroups()], left => {
return left.map(headerGroup => {
return headerGroup.headers;
}).flat();
}, utils.getMemoOptions(table.options, debug, 'getRightFlatHeaders'));
// Leaf Headers
table.getCenterLeafHeaders = utils.memo(() => [table.getCenterFlatHeaders()], flatHeaders => {
return flatHeaders.filter(header => {
var _header$subHeaders;
return !((_header$subHeaders = header.subHeaders) != null && _header$subHeaders.length);
});
}, utils.getMemoOptions(table.options, debug, 'getCenterLeafHeaders'));
table.getLeftLeafHeaders = utils.memo(() => [table.getLeftFlatHeaders()], flatHeaders => {
return flatHeaders.filter(header => {
var _header$subHeaders2;
return !((_header$subHeaders2 = header.subHeaders) != null && _header$subHeaders2.length);
});
}, utils.getMemoOptions(table.options, debug, 'getLeftLeafHeaders'));
table.getRightLeafHeaders = utils.memo(() => [table.getRightFlatHeaders()], flatHeaders => {
return flatHeaders.filter(header => {
var _header$subHeaders3;
return !((_header$subHeaders3 = header.subHeaders) != null && _header$subHeaders3.length);
});
}, utils.getMemoOptions(table.options, debug, 'getRightLeafHeaders'));
table.getLeafHeaders = utils.memo(() => [table.getLeftHeaderGroups(), table.getCenterHeaderGroups(), table.getRightHeaderGroups()], (left, center, right) => {
var _left$0$headers, _left$, _center$0$headers, _center$, _right$0$headers, _right$;
return [...((_left$0$headers = (_left$ = left[0]) == null ? void 0 : _left$.headers) != null ? _left$0$headers : []), ...((_center$0$headers = (_center$ = center[0]) == null ? void 0 : _center$.headers) != null ? _center$0$headers : []), ...((_right$0$headers = (_right$ = right[0]) == null ? void 0 : _right$.headers) != null ? _right$0$headers : [])].map(header => {
return header.getLeafHeaders();
}).flat();
}, utils.getMemoOptions(table.options, debug, 'getLeafHeaders'));
}
};
function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) {
var _headerGroups$0$heade, _headerGroups$;
// Find the max depth of the columns:
// build the leaf column row
// build each buffer row going up
// placeholder for non-existent level
// real column for existing level
let maxDepth = 0;
const findMaxDepth = function (columns, depth) {
if (depth === void 0) {
depth = 1;
}
maxDepth = Math.max(maxDepth, depth);
columns.filter(column => column.getIsVisible()).forEach(column => {
var _column$columns;
if ((_column$columns = column.columns) != null && _column$columns.length) {
findMaxDepth(column.columns, depth + 1);
}
}, 0);
};
findMaxDepth(allColumns);
let headerGroups = [];
const createHeaderGroup = (headersToGroup, depth) => {
// The header group we are creating
const headerGroup = {
depth,
id: [headerFamily, `${depth}`].filter(Boolean).join('_'),
headers: []
};
// The parent columns we're going to scan next
const pendingParentHeaders = [];
// Scan each column for parents
headersToGroup.forEach(headerToGroup => {
// What is the latest (last) parent column?
const latestPendingParentHeader = [...pendingParentHeaders].reverse()[0];
const isLeafHeader = headerToGroup.column.depth === headerGroup.depth;
let column;
let isPlaceholder = false;
if (isLeafHeader && headerToGroup.column.parent) {
// The parent header is new
column = headerToGroup.column.parent;
} else {
// The parent header is repeated
column = headerToGroup.column;
isPlaceholder = true;
}
if (latestPendingParentHeader && (latestPendingParentHeader == null ? void 0 : latestPendingParentHeader.column) === column) {
// This column is repeated. Add it as a sub header to the next batch
latestPendingParentHeader.subHeaders.push(headerToGroup);
} else {
// This is a new header. Let's create it
const header = createHeader(table, column, {
id: [headerFamily, depth, column.id, headerToGroup == null ? void 0 : headerToGroup.id].filter(Boolean).join('_'),
isPlaceholder,
placeholderId: isPlaceholder ? `${pendingParentHeaders.filter(d => d.column === column).length}` : undefined,
depth,
index: pendingParentHeaders.length
});
// Add the headerToGroup as a subHeader of the new header
header.subHeaders.push(headerToGroup);
// Add the new header to the pendingParentHeaders to get grouped
// in the next batch
pendingParentHeaders.push(header);
}
headerGroup.headers.push(headerToGroup);
headerToGroup.headerGroup = headerGroup;
});
headerGroups.push(headerGroup);
if (depth > 0) {
createHeaderGroup(pendingParentHeaders, depth - 1);
}
};
const bottomHeaders = columnsToGroup.map((column, index) => createHeader(table, column, {
depth: maxDepth,
index
}));
createHeaderGroup(bottomHeaders, maxDepth - 1);
headerGroups.reverse();
// headerGroups = headerGroups.filter(headerGroup => {
// return !headerGroup.headers.every(header => header.isPlaceholder)
// })
const recurseHeadersForSpans = headers => {
const filteredHeaders = headers.filter(header => header.column.getIsVisible());
return filteredHeaders.map(header => {
let colSpan = 0;
let rowSpan = 0;
let childRowSpans = [0];
if (header.subHeaders && header.subHeaders.length) {
childRowSpans = [];
recurseHeadersForSpans(header.subHeaders).forEach(_ref => {
let {
colSpan: childColSpan,
rowSpan: childRowSpan
} = _ref;
colSpan += childColSpan;
childRowSpans.push(childRowSpan);
});
} else {
colSpan = 1;
}
const minChildRowSpan = Math.min(...childRowSpans);
rowSpan = rowSpan + minChildRowSpan;
header.colSpan = colSpan;
header.rowSpan = rowSpan;
return {
colSpan,
rowSpan
};
});
};
recurseHeadersForSpans((_headerGroups$0$heade = (_headerGroups$ = headerGroups[0]) == null ? void 0 : _headerGroups$.headers) != null ? _headerGroups$0$heade : []);
return headerGroups;
}
exports.Headers = Headers;
exports.buildHeaderGroups = buildHeaderGroups;
//# sourceMappingURL=headers.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,91 @@
import { RowData, Cell, Row, Table } from '../types';
export interface CoreRow<TData extends RowData> {
_getAllCellsByColumnId: () => Record<string, Cell<TData, unknown>>;
_uniqueValuesCache: Record<string, unknown>;
_valuesCache: Record<string, unknown>;
/**
* The depth of the row (if nested or grouped) relative to the root row array.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#depth)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
depth: number;
/**
* Returns all of the cells for the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#getallcells)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
getAllCells: () => Cell<TData, unknown>[];
/**
* Returns the leaf rows for the row, not including any parent rows.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#getleafrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
getLeafRows: () => Row<TData>[];
/**
* Returns the parent row for the row, if it exists.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#getparentrow)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
getParentRow: () => Row<TData> | undefined;
/**
* Returns the parent rows for the row, all the way up to a root row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#getparentrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
getParentRows: () => Row<TData>[];
/**
* Returns a unique array of values from the row for a given columnId.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#getuniquevalues)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
getUniqueValues: <TValue>(columnId: string) => TValue[];
/**
* Returns the value from the row for a given columnId.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#getvalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
getValue: <TValue>(columnId: string) => TValue;
/**
* The resolved unique identifier for the row resolved via the `options.getRowId` option. Defaults to the row's index (or relative index if it is a subRow).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#id)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
id: string;
/**
* The index of the row within its parent array (or the root data array).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#index)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
index: number;
/**
* The original row object provided to the table. If the row is a grouped row, the original row object will be the first original in the group.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#original)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
original: TData;
/**
* An array of the original subRows as returned by the `options.getSubRows` option.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#originalsubrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
originalSubRows?: TData[];
/**
* If nested, this row's parent row id.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#parentid)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
parentId?: string;
/**
* Renders the value for the row in a given columnId the same as `getValue`, but will return the `renderFallbackValue` if no value is found.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#rendervalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
renderValue: <TValue>(columnId: string) => TValue;
/**
* An array of subRows for the row as returned and created by the `options.getSubRows` option.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/row#subrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/rows)
*/
subRows: Row<TData>[];
}
export declare const createRow: <TData extends unknown>(table: Table<TData>, id: string, original: TData, rowIndex: number, depth: number, subRows?: Row<TData>[], parentId?: string) => Row<TData>;

View File

@@ -0,0 +1,89 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
var cell = require('./cell.js');
const createRow = (table, id, original, rowIndex, depth, subRows, parentId) => {
let row = {
id,
index: rowIndex,
original,
depth,
parentId,
_valuesCache: {},
_uniqueValuesCache: {},
getValue: columnId => {
if (row._valuesCache.hasOwnProperty(columnId)) {
return row._valuesCache[columnId];
}
const column = table.getColumn(columnId);
if (!(column != null && column.accessorFn)) {
return undefined;
}
row._valuesCache[columnId] = column.accessorFn(row.original, rowIndex);
return row._valuesCache[columnId];
},
getUniqueValues: columnId => {
if (row._uniqueValuesCache.hasOwnProperty(columnId)) {
return row._uniqueValuesCache[columnId];
}
const column = table.getColumn(columnId);
if (!(column != null && column.accessorFn)) {
return undefined;
}
if (!column.columnDef.getUniqueValues) {
row._uniqueValuesCache[columnId] = [row.getValue(columnId)];
return row._uniqueValuesCache[columnId];
}
row._uniqueValuesCache[columnId] = column.columnDef.getUniqueValues(row.original, rowIndex);
return row._uniqueValuesCache[columnId];
},
renderValue: columnId => {
var _row$getValue;
return (_row$getValue = row.getValue(columnId)) != null ? _row$getValue : table.options.renderFallbackValue;
},
subRows: subRows != null ? subRows : [],
getLeafRows: () => utils.flattenBy(row.subRows, d => d.subRows),
getParentRow: () => row.parentId ? table.getRow(row.parentId, true) : undefined,
getParentRows: () => {
let parentRows = [];
let currentRow = row;
while (true) {
const parentRow = currentRow.getParentRow();
if (!parentRow) break;
parentRows.push(parentRow);
currentRow = parentRow;
}
return parentRows.reverse();
},
getAllCells: utils.memo(() => [table.getAllLeafColumns()], leafColumns => {
return leafColumns.map(column => {
return cell.createCell(table, row, column, column.id);
});
}, utils.getMemoOptions(table.options, 'debugRows', 'getAllCells')),
_getAllCellsByColumnId: utils.memo(() => [row.getAllCells()], allCells => {
return allCells.reduce((acc, cell) => {
acc[cell.column.id] = cell;
return acc;
}, {});
}, utils.getMemoOptions(table.options, 'debugRows', 'getAllCellsByColumnId'))
};
for (let i = 0; i < table._features.length; i++) {
const feature = table._features[i];
feature == null || feature.createRow == null || feature.createRow(row, table);
}
return row;
};
exports.createRow = createRow;
//# sourceMappingURL=row.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,220 @@
import { RequiredKeys } from '../utils';
import { Updater, TableOptionsResolved, TableState, Table, InitialTableState, Row, Column, RowModel, ColumnDef, TableOptions, RowData, TableMeta, TableFeature } from '../types';
export interface CoreTableState {
}
export interface CoreOptions<TData extends RowData> {
/**
* An array of extra features that you can add to the table instance.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#_features)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
_features?: TableFeature[];
/**
* Set this option to override any of the `autoReset...` feature options.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#autoresetall)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
autoResetAll?: boolean;
/**
* The array of column defs to use for the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#columns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
columns: ColumnDef<TData, any>[];
/**
* The data for the table to display. This array should match the type you provided to `table.setRowType<...>`. Columns can access this data via string/index or a functional accessor. When the `data` option changes reference, the table will reprocess the data.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#data)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
data: TData[];
/**
* Set this option to `true` to output all debugging information to the console.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#debugall)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
debugAll?: boolean;
/**
* Set this option to `true` to output cell debugging information to the console.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#debugcells]
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
debugCells?: boolean;
/**
* Set this option to `true` to output column debugging information to the console.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#debugcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
debugColumns?: boolean;
/**
* Set this option to `true` to output header debugging information to the console.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#debugheaders)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
debugHeaders?: boolean;
/**
* Set this option to `true` to output row debugging information to the console.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#debugrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
debugRows?: boolean;
/**
* Set this option to `true` to output table debugging information to the console.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#debugtable)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
debugTable?: boolean;
/**
* Default column options to use for all column defs supplied to the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#defaultcolumn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
defaultColumn?: Partial<ColumnDef<TData, unknown>>;
/**
* This required option is a factory for a function that computes and returns the core row model for the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getcorerowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getCoreRowModel: (table: Table<any>) => () => RowModel<any>;
/**
* This optional function is used to derive a unique ID for any given row. If not provided the rows index is used (nested rows join together with `.` using their grandparents' index eg. `index.index.index`). If you need to identify individual rows that are originating from any server-side operations, it's suggested you use this function to return an ID that makes sense regardless of network IO/ambiguity eg. a userId, taskId, database ID field, etc.
* @example getRowId: row => row.userId
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getrowid)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getRowId?: (originalRow: TData, index: number, parent?: Row<TData>) => string;
/**
* This optional function is used to access the sub rows for any given row. If you are using nested rows, you will need to use this function to return the sub rows object (or undefined) from the row.
* @example getSubRows: row => row.subRows
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getsubrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getSubRows?: (originalRow: TData, index: number) => undefined | TData[];
/**
* Use this option to optionally pass initial state to the table. This state will be used when resetting various table states either automatically by the table (eg. `options.autoResetPageIndex`) or via functions like `table.resetRowSelection()`. Most reset function allow you optionally pass a flag to reset to a blank/default state instead of the initial state.
*
* Table state will not be reset when this object changes, which also means that the initial state object does not need to be stable.
*
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#initialstate)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
initialState?: InitialTableState;
/**
* This option is used to optionally implement the merging of table options.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#mergeoptions)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
mergeOptions?: (defaultOptions: TableOptions<TData>, options: Partial<TableOptions<TData>>) => TableOptions<TData>;
/**
* You can pass any object to `options.meta` and access it anywhere the `table` is available via `table.options.meta`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#meta)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
meta?: TableMeta<TData>;
/**
* The `onStateChange` option can be used to optionally listen to state changes within the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#onstatechange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
onStateChange: (updater: Updater<TableState>) => void;
/**
* Value used when the desired value is not found in the data.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#renderfallbackvalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
renderFallbackValue: any;
/**
* The `state` option can be used to optionally _control_ part or all of the table state. The state you pass here will merge with and overwrite the internal automatically-managed state to produce the final state for the table. You can also listen to state changes via the `onStateChange` option.
* > Note: Any state passed in here will override both the internal state and any other `initialState` you provide.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#state)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
state: Partial<TableState>;
}
export interface CoreInstance<TData extends RowData> {
_features: readonly TableFeature[];
_getAllFlatColumnsById: () => Record<string, Column<TData, unknown>>;
_getColumnDefs: () => ColumnDef<TData, unknown>[];
_getCoreRowModel?: () => RowModel<TData>;
_getDefaultColumnDef: () => Partial<ColumnDef<TData, unknown>>;
_getRowId: (_: TData, index: number, parent?: Row<TData>) => string;
_queue: (cb: () => void) => void;
/**
* Returns all columns in the table in their normalized and nested hierarchy.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getallcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getAllColumns: () => Column<TData, unknown>[];
/**
* Returns all columns in the table flattened to a single level.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getallflatcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getAllFlatColumns: () => Column<TData, unknown>[];
/**
* Returns all leaf-node columns in the table flattened to a single level. This does not include parent columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getallleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getAllLeafColumns: () => Column<TData, unknown>[];
/**
* Returns a single column by its ID.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getcolumn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getColumn: (columnId: string) => Column<TData, unknown> | undefined;
/**
* Returns the core row model before any processing has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getcorerowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getCoreRowModel: () => RowModel<TData>;
/**
* Returns the row with the given ID.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getrow)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getRow: (id: string, searchAll?: boolean) => Row<TData>;
/**
* Returns the final model after all processing from other used features has been applied. This is the row model that is most commonly used for rendering.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getRowModel: () => RowModel<TData>;
/**
* Call this function to get the table's current state. It's recommended to use this function and its state, especially when managing the table state manually. It is the exact same state used internally by the table for every feature and function it provides.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#getstate)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
getState: () => TableState;
/**
* This is the resolved initial state of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#initialstate)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
initialState: TableState;
/**
* A read-only reference to the table's current options.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#options)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
options: RequiredKeys<TableOptionsResolved<TData>, 'state'>;
/**
* Call this function to reset the table state to the initial state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#reset)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
reset: () => void;
/**
* This function can be used to update the table options.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#setoptions)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
setOptions: (newOptions: Updater<TableOptionsResolved<TData>>) => void;
/**
* Call this function to update the table state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/core/table#setstate)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/tables)
*/
setState: (updater: Updater<TableState>) => void;
}
export declare function createTable<TData extends RowData>(options: TableOptionsResolved<TData>): Table<TData>;

View File

@@ -0,0 +1,212 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
var column = require('./column.js');
var headers = require('./headers.js');
var ColumnFaceting = require('../features/ColumnFaceting.js');
var ColumnFiltering = require('../features/ColumnFiltering.js');
var ColumnGrouping = require('../features/ColumnGrouping.js');
var ColumnOrdering = require('../features/ColumnOrdering.js');
var ColumnPinning = require('../features/ColumnPinning.js');
var ColumnSizing = require('../features/ColumnSizing.js');
var ColumnVisibility = require('../features/ColumnVisibility.js');
var GlobalFaceting = require('../features/GlobalFaceting.js');
var GlobalFiltering = require('../features/GlobalFiltering.js');
var RowExpanding = require('../features/RowExpanding.js');
var RowPagination = require('../features/RowPagination.js');
var RowPinning = require('../features/RowPinning.js');
var RowSelection = require('../features/RowSelection.js');
var RowSorting = require('../features/RowSorting.js');
const builtInFeatures = [headers.Headers, ColumnVisibility.ColumnVisibility, ColumnOrdering.ColumnOrdering, ColumnPinning.ColumnPinning, ColumnFaceting.ColumnFaceting, ColumnFiltering.ColumnFiltering, GlobalFaceting.GlobalFaceting,
//depends on ColumnFaceting
GlobalFiltering.GlobalFiltering,
//depends on ColumnFiltering
RowSorting.RowSorting, ColumnGrouping.ColumnGrouping,
//depends on RowSorting
RowExpanding.RowExpanding, RowPagination.RowPagination, RowPinning.RowPinning, RowSelection.RowSelection, ColumnSizing.ColumnSizing];
//
function createTable(options) {
var _options$_features, _options$initialState;
if (process.env.NODE_ENV !== 'production' && (options.debugAll || options.debugTable)) {
console.info('Creating Table Instance...');
}
const _features = [...builtInFeatures, ...((_options$_features = options._features) != null ? _options$_features : [])];
let table = {
_features
};
const defaultOptions = table._features.reduce((obj, feature) => {
return Object.assign(obj, feature.getDefaultOptions == null ? void 0 : feature.getDefaultOptions(table));
}, {});
const mergeOptions = options => {
if (table.options.mergeOptions) {
return table.options.mergeOptions(defaultOptions, options);
}
return {
...defaultOptions,
...options
};
};
const coreInitialState = {};
let initialState = {
...coreInitialState,
...((_options$initialState = options.initialState) != null ? _options$initialState : {})
};
table._features.forEach(feature => {
var _feature$getInitialSt;
initialState = (_feature$getInitialSt = feature.getInitialState == null ? void 0 : feature.getInitialState(initialState)) != null ? _feature$getInitialSt : initialState;
});
const queued = [];
let queuedTimeout = false;
const coreInstance = {
_features,
options: {
...defaultOptions,
...options
},
initialState,
_queue: cb => {
queued.push(cb);
if (!queuedTimeout) {
queuedTimeout = true;
// Schedule a microtask to run the queued callbacks after
// the current call stack (render, etc) has finished.
Promise.resolve().then(() => {
while (queued.length) {
queued.shift()();
}
queuedTimeout = false;
}).catch(error => setTimeout(() => {
throw error;
}));
}
},
reset: () => {
table.setState(table.initialState);
},
setOptions: updater => {
const newOptions = utils.functionalUpdate(updater, table.options);
table.options = mergeOptions(newOptions);
},
getState: () => {
return table.options.state;
},
setState: updater => {
table.options.onStateChange == null || table.options.onStateChange(updater);
},
_getRowId: (row, index, parent) => {
var _table$options$getRow;
return (_table$options$getRow = table.options.getRowId == null ? void 0 : table.options.getRowId(row, index, parent)) != null ? _table$options$getRow : `${parent ? [parent.id, index].join('.') : index}`;
},
getCoreRowModel: () => {
if (!table._getCoreRowModel) {
table._getCoreRowModel = table.options.getCoreRowModel(table);
}
return table._getCoreRowModel();
},
// The final calls start at the bottom of the model,
// expanded rows, which then work their way up
getRowModel: () => {
return table.getPaginationRowModel();
},
//in next version, we should just pass in the row model as the optional 2nd arg
getRow: (id, searchAll) => {
let row = (searchAll ? table.getPrePaginationRowModel() : table.getRowModel()).rowsById[id];
if (!row) {
row = table.getCoreRowModel().rowsById[id];
if (!row) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(`getRow could not find row with ID: ${id}`);
}
throw new Error();
}
}
return row;
},
_getDefaultColumnDef: utils.memo(() => [table.options.defaultColumn], defaultColumn => {
var _defaultColumn;
defaultColumn = (_defaultColumn = defaultColumn) != null ? _defaultColumn : {};
return {
header: props => {
const resolvedColumnDef = props.header.column.columnDef;
if (resolvedColumnDef.accessorKey) {
return resolvedColumnDef.accessorKey;
}
if (resolvedColumnDef.accessorFn) {
return resolvedColumnDef.id;
}
return null;
},
// footer: props => props.header.column.id,
cell: props => {
var _props$renderValue$to, _props$renderValue;
return (_props$renderValue$to = (_props$renderValue = props.renderValue()) == null || _props$renderValue.toString == null ? void 0 : _props$renderValue.toString()) != null ? _props$renderValue$to : null;
},
...table._features.reduce((obj, feature) => {
return Object.assign(obj, feature.getDefaultColumnDef == null ? void 0 : feature.getDefaultColumnDef());
}, {}),
...defaultColumn
};
}, utils.getMemoOptions(options, 'debugColumns', '_getDefaultColumnDef')),
_getColumnDefs: () => table.options.columns,
getAllColumns: utils.memo(() => [table._getColumnDefs()], columnDefs => {
const recurseColumns = function (columnDefs, parent, depth) {
if (depth === void 0) {
depth = 0;
}
return columnDefs.map(columnDef => {
const column$1 = column.createColumn(table, columnDef, depth, parent);
const groupingColumnDef = columnDef;
column$1.columns = groupingColumnDef.columns ? recurseColumns(groupingColumnDef.columns, column$1, depth + 1) : [];
return column$1;
});
};
return recurseColumns(columnDefs);
}, utils.getMemoOptions(options, 'debugColumns', 'getAllColumns')),
getAllFlatColumns: utils.memo(() => [table.getAllColumns()], allColumns => {
return allColumns.flatMap(column => {
return column.getFlatColumns();
});
}, utils.getMemoOptions(options, 'debugColumns', 'getAllFlatColumns')),
_getAllFlatColumnsById: utils.memo(() => [table.getAllFlatColumns()], flatColumns => {
return flatColumns.reduce((acc, column) => {
acc[column.id] = column;
return acc;
}, {});
}, utils.getMemoOptions(options, 'debugColumns', 'getAllFlatColumnsById')),
getAllLeafColumns: utils.memo(() => [table.getAllColumns(), table._getOrderColumnsFn()], (allColumns, orderColumns) => {
let leafColumns = allColumns.flatMap(column => column.getLeafColumns());
return orderColumns(leafColumns);
}, utils.getMemoOptions(options, 'debugColumns', 'getAllLeafColumns')),
getColumn: columnId => {
const column = table._getAllFlatColumnsById()[columnId];
if (process.env.NODE_ENV !== 'production' && !column) {
console.error(`[Table] Column with id '${columnId}' does not exist.`);
}
return column;
}
};
Object.assign(table, coreInstance);
for (let index = 0; index < table._features.length; index++) {
const feature = table._features[index];
feature == null || feature.createTable == null || feature.createTable(table);
}
return table;
}
exports.createTable = createTable;
//# sourceMappingURL=table.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,34 @@
import { RowModel } from '..';
import { RowData, Table, TableFeature } from '../types';
export interface FacetedColumn<TData extends RowData> {
_getFacetedMinMaxValues?: () => undefined | [number, number];
_getFacetedRowModel?: () => RowModel<TData>;
_getFacetedUniqueValues?: () => Map<any, number>;
/**
* A function that **computes and returns** a min/max tuple derived from `column.getFacetedRowModel`. Useful for displaying faceted result values.
* > ⚠️ Requires that you pass a valid `getFacetedMinMaxValues` function to `options.getFacetedMinMaxValues`. A default implementation is provided via the exported `getFacetedMinMaxValues` function.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-faceting#getfacetedminmaxvalues)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-faceting)
*/
getFacetedMinMaxValues: () => undefined | [number, number];
/**
* Returns the row model with all other column filters applied, excluding its own filter. Useful for displaying faceted result counts.
* > ⚠️ Requires that you pass a valid `getFacetedRowModel` function to `options.facetedRowModel`. A default implementation is provided via the exported `getFacetedRowModel` function.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-faceting#getfacetedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-faceting)
*/
getFacetedRowModel: () => RowModel<TData>;
/**
* A function that **computes and returns** a `Map` of unique values and their occurrences derived from `column.getFacetedRowModel`. Useful for displaying faceted result values.
* > ⚠️ Requires that you pass a valid `getFacetedUniqueValues` function to `options.getFacetedUniqueValues`. A default implementation is provided via the exported `getFacetedUniqueValues` function.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-faceting#getfaceteduniquevalues)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-faceting)
*/
getFacetedUniqueValues: () => Map<any, number>;
}
export interface FacetedOptions<TData extends RowData> {
getFacetedMinMaxValues?: (table: Table<TData>, columnId: string) => () => undefined | [number, number];
getFacetedRowModel?: (table: Table<TData>, columnId: string) => () => RowModel<TData>;
getFacetedUniqueValues?: (table: Table<TData>, columnId: string) => () => Map<any, number>;
}
export declare const ColumnFaceting: TableFeature;

View File

@@ -0,0 +1,42 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
//
const ColumnFaceting = {
createColumn: (column, table) => {
column._getFacetedRowModel = table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, column.id);
column.getFacetedRowModel = () => {
if (!column._getFacetedRowModel) {
return table.getPreFilteredRowModel();
}
return column._getFacetedRowModel();
};
column._getFacetedUniqueValues = table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, column.id);
column.getFacetedUniqueValues = () => {
if (!column._getFacetedUniqueValues) {
return new Map();
}
return column._getFacetedUniqueValues();
};
column._getFacetedMinMaxValues = table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, column.id);
column.getFacetedMinMaxValues = () => {
if (!column._getFacetedMinMaxValues) {
return undefined;
}
return column._getFacetedMinMaxValues();
};
}
};
exports.ColumnFaceting = ColumnFaceting;
//# sourceMappingURL=ColumnFaceting.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,194 @@
import { RowModel } from '..';
import { BuiltInFilterFn } from '../filterFns';
import { Column, FilterFns, FilterMeta, OnChangeFn, Row, RowData, Table, TableFeature, Updater } from '../types';
export interface ColumnFiltersTableState {
columnFilters: ColumnFiltersState;
}
export type ColumnFiltersState = ColumnFilter[];
export interface ColumnFilter {
id: string;
value: unknown;
}
export interface ResolvedColumnFilter<TData extends RowData> {
filterFn: FilterFn<TData>;
id: string;
resolvedValue: unknown;
}
export interface FilterFn<TData extends RowData> {
(row: Row<TData>, columnId: string, filterValue: any, addMeta: (meta: FilterMeta) => void): boolean;
autoRemove?: ColumnFilterAutoRemoveTestFn<TData>;
resolveFilterValue?: TransformFilterValueFn<TData>;
}
export type TransformFilterValueFn<TData extends RowData> = (value: any, column?: Column<TData, unknown>) => unknown;
export type ColumnFilterAutoRemoveTestFn<TData extends RowData> = (value: any, column?: Column<TData, unknown>) => boolean;
export type CustomFilterFns<TData extends RowData> = Record<string, FilterFn<TData>>;
export type FilterFnOption<TData extends RowData> = 'auto' | BuiltInFilterFn | keyof FilterFns | FilterFn<TData>;
export interface ColumnFiltersColumnDef<TData extends RowData> {
/**
* Enables/disables the **column** filter for this column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#enablecolumnfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
enableColumnFilter?: boolean;
/**
* The filter function to use with this column. Can be the name of a built-in filter function or a custom filter function.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#filterfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
filterFn?: FilterFnOption<TData>;
}
export interface ColumnFiltersColumn<TData extends RowData> {
/**
* Returns an automatically calculated filter function for the column based off of the columns first known value.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getautofilterfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getAutoFilterFn: () => FilterFn<TData> | undefined;
/**
* Returns whether or not the column can be **column** filtered.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getcanfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getCanFilter: () => boolean;
/**
* Returns the filter function (either user-defined or automatic, depending on configuration) for the columnId specified.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getfilterfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getFilterFn: () => FilterFn<TData> | undefined;
/**
* Returns the index (including `-1`) of the column filter in the table's `state.columnFilters` array.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getfilterindex)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getFilterIndex: () => number;
/**
* Returns the current filter value for the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getfiltervalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getFilterValue: () => unknown;
/**
* Returns whether or not the column is currently filtered.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getisfiltered)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getIsFiltered: () => boolean;
/**
* A function that sets the current filter value for the column. You can pass it a value or an updater function for immutability-safe operations on existing values.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#setfiltervalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
setFilterValue: (updater: Updater<any>) => void;
}
export interface ColumnFiltersRow<TData extends RowData> {
/**
* The column filters map for the row. This object tracks whether a row is passing/failing specific filters by their column ID.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#columnfilters)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
columnFilters: Record<string, boolean>;
/**
* The column filters meta map for the row. This object tracks any filter meta for a row as optionally provided during the filtering process.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#columnfiltersmeta)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
columnFiltersMeta: Record<string, FilterMeta>;
}
interface ColumnFiltersOptionsBase<TData extends RowData> {
/**
* Enables/disables **column** filtering for all columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#enablecolumnfilters)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
enableColumnFilters?: boolean;
/**
* Enables/disables all filtering for the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#enablefilters)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
enableFilters?: boolean;
/**
* By default, filtering is done from parent rows down (so if a parent row is filtered out, all of its children will be filtered out as well). Setting this option to `true` will cause filtering to be done from leaf rows up (which means parent rows will be included so long as one of their child or grand-child rows is also included).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#filterfromleafrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
filterFromLeafRows?: boolean;
/**
* If provided, this function is called **once** per table and should return a **new function** which will calculate and return the row model for the table when it's filtered.
* - For server-side filtering, this function is unnecessary and can be ignored since the server should already return the filtered row model.
* - For client-side filtering, this function is required. A default implementation is provided via any table adapter's `{ getFilteredRowModel }` export.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getfilteredrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getFilteredRowModel?: (table: Table<any>) => () => RowModel<any>;
/**
* Disables the `getFilteredRowModel` from being used to filter data. This may be useful if your table needs to dynamically support both client-side and server-side filtering.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#manualfiltering)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
manualFiltering?: boolean;
/**
* By default, filtering is done for all rows (max depth of 100), no matter if they are root level parent rows or the child leaf rows of a parent row. Setting this option to `0` will cause filtering to only be applied to the root level parent rows, with all sub-rows remaining unfiltered. Similarly, setting this option to `1` will cause filtering to only be applied to child leaf rows 1 level deep, and so on.
* This is useful for situations where you want a row's entire child hierarchy to be visible regardless of the applied filter.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#maxleafrowfilterdepth)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
maxLeafRowFilterDepth?: number;
/**
* If provided, this function will be called with an `updaterFn` when `state.columnFilters` changes. This overrides the default internal state management, so you will need to persist the state change either fully or partially outside of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#oncolumnfilterschange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
onColumnFiltersChange?: OnChangeFn<ColumnFiltersState>;
}
type ResolvedFilterFns = keyof FilterFns extends never ? {
filterFns?: Record<string, FilterFn<any>>;
} : {
filterFns: Record<keyof FilterFns, FilterFn<any>>;
};
export interface ColumnFiltersOptions<TData extends RowData> extends ColumnFiltersOptionsBase<TData>, ResolvedFilterFns {
}
export interface ColumnFiltersInstance<TData extends RowData> {
_getFilteredRowModel?: () => RowModel<TData>;
/**
* Returns the row model for the table after **column** filtering has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getfilteredrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getFilteredRowModel: () => RowModel<TData>;
/**
* Returns the row model for the table before any **column** filtering has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#getprefilteredrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
getPreFilteredRowModel: () => RowModel<TData>;
/**
* Resets the **columnFilters** state to `initialState.columnFilters`, or `true` can be passed to force a default blank state reset to `[]`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#resetcolumnfilters)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
resetColumnFilters: (defaultState?: boolean) => void;
/**
* Resets the **globalFilter** state to `initialState.globalFilter`, or `true` can be passed to force a default blank state reset to `undefined`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#resetglobalfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
resetGlobalFilter: (defaultState?: boolean) => void;
/**
* Sets or updates the `state.columnFilters` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#setcolumnfilters)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
setColumnFilters: (updater: Updater<ColumnFiltersState>) => void;
/**
* Sets or updates the `state.globalFilter` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-filtering#setglobalfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-filtering)
*/
setGlobalFilter: (updater: Updater<any>) => void;
}
export declare const ColumnFiltering: TableFeature;
export declare function shouldAutoRemoveFilter<TData extends RowData>(filterFn?: FilterFn<TData>, value?: any, column?: Column<TData, unknown>): boolean;
export {};

View File

@@ -0,0 +1,151 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var filterFns = require('../filterFns.js');
var utils = require('../utils.js');
//
const ColumnFiltering = {
getDefaultColumnDef: () => {
return {
filterFn: 'auto'
};
},
getInitialState: state => {
return {
columnFilters: [],
...state
};
},
getDefaultOptions: table => {
return {
onColumnFiltersChange: utils.makeStateUpdater('columnFilters', table),
filterFromLeafRows: false,
maxLeafRowFilterDepth: 100
};
},
createColumn: (column, table) => {
column.getAutoFilterFn = () => {
const firstRow = table.getCoreRowModel().flatRows[0];
const value = firstRow == null ? void 0 : firstRow.getValue(column.id);
if (typeof value === 'string') {
return filterFns.filterFns.includesString;
}
if (typeof value === 'number') {
return filterFns.filterFns.inNumberRange;
}
if (typeof value === 'boolean') {
return filterFns.filterFns.equals;
}
if (value !== null && typeof value === 'object') {
return filterFns.filterFns.equals;
}
if (Array.isArray(value)) {
return filterFns.filterFns.arrIncludes;
}
return filterFns.filterFns.weakEquals;
};
column.getFilterFn = () => {
var _table$options$filter, _table$options$filter2;
return utils.isFunction(column.columnDef.filterFn) ? column.columnDef.filterFn : column.columnDef.filterFn === 'auto' ? column.getAutoFilterFn() : // @ts-ignore
(_table$options$filter = (_table$options$filter2 = table.options.filterFns) == null ? void 0 : _table$options$filter2[column.columnDef.filterFn]) != null ? _table$options$filter : filterFns.filterFns[column.columnDef.filterFn];
};
column.getCanFilter = () => {
var _column$columnDef$ena, _table$options$enable, _table$options$enable2;
return ((_column$columnDef$ena = column.columnDef.enableColumnFilter) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableColumnFilters) != null ? _table$options$enable : true) && ((_table$options$enable2 = table.options.enableFilters) != null ? _table$options$enable2 : true) && !!column.accessorFn;
};
column.getIsFiltered = () => column.getFilterIndex() > -1;
column.getFilterValue = () => {
var _table$getState$colum;
return (_table$getState$colum = table.getState().columnFilters) == null || (_table$getState$colum = _table$getState$colum.find(d => d.id === column.id)) == null ? void 0 : _table$getState$colum.value;
};
column.getFilterIndex = () => {
var _table$getState$colum2, _table$getState$colum3;
return (_table$getState$colum2 = (_table$getState$colum3 = table.getState().columnFilters) == null ? void 0 : _table$getState$colum3.findIndex(d => d.id === column.id)) != null ? _table$getState$colum2 : -1;
};
column.setFilterValue = value => {
table.setColumnFilters(old => {
const filterFn = column.getFilterFn();
const previousFilter = old == null ? void 0 : old.find(d => d.id === column.id);
const newFilter = utils.functionalUpdate(value, previousFilter ? previousFilter.value : undefined);
//
if (shouldAutoRemoveFilter(filterFn, newFilter, column)) {
var _old$filter;
return (_old$filter = old == null ? void 0 : old.filter(d => d.id !== column.id)) != null ? _old$filter : [];
}
const newFilterObj = {
id: column.id,
value: newFilter
};
if (previousFilter) {
var _old$map;
return (_old$map = old == null ? void 0 : old.map(d => {
if (d.id === column.id) {
return newFilterObj;
}
return d;
})) != null ? _old$map : [];
}
if (old != null && old.length) {
return [...old, newFilterObj];
}
return [newFilterObj];
});
};
},
createRow: (row, _table) => {
row.columnFilters = {};
row.columnFiltersMeta = {};
},
createTable: table => {
table.setColumnFilters = updater => {
const leafColumns = table.getAllLeafColumns();
const updateFn = old => {
var _functionalUpdate;
return (_functionalUpdate = utils.functionalUpdate(updater, old)) == null ? void 0 : _functionalUpdate.filter(filter => {
const column = leafColumns.find(d => d.id === filter.id);
if (column) {
const filterFn = column.getFilterFn();
if (shouldAutoRemoveFilter(filterFn, filter.value, column)) {
return false;
}
}
return true;
});
};
table.options.onColumnFiltersChange == null || table.options.onColumnFiltersChange(updateFn);
};
table.resetColumnFilters = defaultState => {
var _table$initialState$c, _table$initialState;
table.setColumnFilters(defaultState ? [] : (_table$initialState$c = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.columnFilters) != null ? _table$initialState$c : []);
};
table.getPreFilteredRowModel = () => table.getCoreRowModel();
table.getFilteredRowModel = () => {
if (!table._getFilteredRowModel && table.options.getFilteredRowModel) {
table._getFilteredRowModel = table.options.getFilteredRowModel(table);
}
if (table.options.manualFiltering || !table._getFilteredRowModel) {
return table.getPreFilteredRowModel();
}
return table._getFilteredRowModel();
};
}
};
function shouldAutoRemoveFilter(filterFn, value, column) {
return (filterFn && filterFn.autoRemove ? filterFn.autoRemove(value, column) : false) || typeof value === 'undefined' || typeof value === 'string' && !value;
}
exports.ColumnFiltering = ColumnFiltering;
exports.shouldAutoRemoveFilter = shouldAutoRemoveFilter;
//# sourceMappingURL=ColumnFiltering.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,201 @@
import { RowModel } from '..';
import { BuiltInAggregationFn } from '../aggregationFns';
import { AggregationFns, Cell, Column, ColumnDefTemplate, OnChangeFn, Row, RowData, Table, TableFeature, Updater } from '../types';
export type GroupingState = string[];
export interface GroupingTableState {
grouping: GroupingState;
}
export type AggregationFn<TData extends RowData> = (columnId: string, leafRows: Row<TData>[], childRows: Row<TData>[]) => any;
export type CustomAggregationFns = Record<string, AggregationFn<any>>;
export type AggregationFnOption<TData extends RowData> = 'auto' | keyof AggregationFns | BuiltInAggregationFn | AggregationFn<TData>;
export interface GroupingColumnDef<TData extends RowData, TValue> {
/**
* The cell to display each row for the column if the cell is an aggregate. If a function is passed, it will be passed a props object with the context of the cell and should return the property type for your adapter (the exact type depends on the adapter being used).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#aggregatedcell)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
aggregatedCell?: ColumnDefTemplate<ReturnType<Cell<TData, TValue>['getContext']>>;
/**
* The resolved aggregation function for the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#aggregationfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
aggregationFn?: AggregationFnOption<TData>;
/**
* Enables/disables grouping for this column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#enablegrouping)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
enableGrouping?: boolean;
/**
* Specify a value to be used for grouping rows on this column. If this option is not specified, the value derived from `accessorKey` / `accessorFn` will be used instead.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getgroupingvalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getGroupingValue?: (row: TData) => any;
}
export interface GroupingColumn<TData extends RowData> {
/**
* Returns the aggregation function for the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getaggregationfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getAggregationFn: () => AggregationFn<TData> | undefined;
/**
* Returns the automatically inferred aggregation function for the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getautoaggregationfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getAutoAggregationFn: () => AggregationFn<TData> | undefined;
/**
* Returns whether or not the column can be grouped.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getcangroup)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getCanGroup: () => boolean;
/**
* Returns the index of the column in the grouping state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getgroupedindex)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getGroupedIndex: () => number;
/**
* Returns whether or not the column is currently grouped.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getisgrouped)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getIsGrouped: () => boolean;
/**
* Returns a function that toggles the grouping state of the column. This is useful for passing to the `onClick` prop of a button.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#gettogglegroupinghandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getToggleGroupingHandler: () => () => void;
/**
* Toggles the grouping state of the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#togglegrouping)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
toggleGrouping: () => void;
}
export interface GroupingRow {
_groupingValuesCache: Record<string, any>;
/**
* Returns the grouping value for any row and column (including leaf rows).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getgroupingvalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getGroupingValue: (columnId: string) => unknown;
/**
* Returns whether or not the row is currently grouped.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getisgrouped)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getIsGrouped: () => boolean;
/**
* If this row is grouped, this is the id of the column that this row is grouped by.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#groupingcolumnid)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
groupingColumnId?: string;
/**
* If this row is grouped, this is the unique/shared value for the `groupingColumnId` for all of the rows in this group.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#groupingvalue)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
groupingValue?: unknown;
}
export interface GroupingCell {
/**
* Returns whether or not the cell is currently aggregated.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getisaggregated)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getIsAggregated: () => boolean;
/**
* Returns whether or not the cell is currently grouped.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getisgrouped)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getIsGrouped: () => boolean;
/**
* Returns whether or not the cell is currently a placeholder cell.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getisplaceholder)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getIsPlaceholder: () => boolean;
}
export interface ColumnDefaultOptions {
enableGrouping: boolean;
onGroupingChange: OnChangeFn<GroupingState>;
}
interface GroupingOptionsBase {
/**
* Enables/disables grouping for the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#enablegrouping)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
enableGrouping?: boolean;
/**
* Returns the row model after grouping has taken place, but no further.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getgroupedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getGroupedRowModel?: (table: Table<any>) => () => RowModel<any>;
/**
* Grouping columns are automatically reordered by default to the start of the columns list. If you would rather remove them or leave them as-is, set the appropriate mode here.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#groupedcolumnmode)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
groupedColumnMode?: false | 'reorder' | 'remove';
/**
* Enables manual grouping. If this option is set to `true`, the table will not automatically group rows using `getGroupedRowModel()` and instead will expect you to manually group the rows before passing them to the table. This is useful if you are doing server-side grouping and aggregation.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#manualgrouping)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
manualGrouping?: boolean;
/**
* If this function is provided, it will be called when the grouping state changes and you will be expected to manage the state yourself. You can pass the managed state back to the table via the `tableOptions.state.grouping` option.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#ongroupingchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
onGroupingChange?: OnChangeFn<GroupingState>;
}
type ResolvedAggregationFns = keyof AggregationFns extends never ? {
aggregationFns?: Record<string, AggregationFn<any>>;
} : {
aggregationFns: Record<keyof AggregationFns, AggregationFn<any>>;
};
export interface GroupingOptions extends GroupingOptionsBase, ResolvedAggregationFns {
}
export type GroupingColumnMode = false | 'reorder' | 'remove';
export interface GroupingInstance<TData extends RowData> {
_getGroupedRowModel?: () => RowModel<TData>;
/**
* Returns the row model for the table after grouping has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getgroupedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getGroupedRowModel: () => RowModel<TData>;
/**
* Returns the row model for the table before any grouping has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#getpregroupedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
getPreGroupedRowModel: () => RowModel<TData>;
/**
* Resets the **grouping** state to `initialState.grouping`, or `true` can be passed to force a default blank state reset to `[]`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#resetgrouping)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
resetGrouping: (defaultState?: boolean) => void;
/**
* Updates the grouping state of the table via an update function or value.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/grouping#setgrouping)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/grouping)
*/
setGrouping: (updater: Updater<GroupingState>) => void;
}
export declare const ColumnGrouping: TableFeature;
export declare function orderColumns<TData extends RowData>(leafColumns: Column<TData, unknown>[], grouping: string[], groupedColumnMode?: GroupingColumnMode): Column<TData, unknown>[];
export {};

View File

@@ -0,0 +1,142 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var aggregationFns = require('../aggregationFns.js');
var utils = require('../utils.js');
//
const ColumnGrouping = {
getDefaultColumnDef: () => {
return {
aggregatedCell: props => {
var _toString, _props$getValue;
return (_toString = (_props$getValue = props.getValue()) == null || _props$getValue.toString == null ? void 0 : _props$getValue.toString()) != null ? _toString : null;
},
aggregationFn: 'auto'
};
},
getInitialState: state => {
return {
grouping: [],
...state
};
},
getDefaultOptions: table => {
return {
onGroupingChange: utils.makeStateUpdater('grouping', table),
groupedColumnMode: 'reorder'
};
},
createColumn: (column, table) => {
column.toggleGrouping = () => {
table.setGrouping(old => {
// Find any existing grouping for this column
if (old != null && old.includes(column.id)) {
return old.filter(d => d !== column.id);
}
return [...(old != null ? old : []), column.id];
});
};
column.getCanGroup = () => {
var _column$columnDef$ena, _table$options$enable;
return ((_column$columnDef$ena = column.columnDef.enableGrouping) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableGrouping) != null ? _table$options$enable : true) && (!!column.accessorFn || !!column.columnDef.getGroupingValue);
};
column.getIsGrouped = () => {
var _table$getState$group;
return (_table$getState$group = table.getState().grouping) == null ? void 0 : _table$getState$group.includes(column.id);
};
column.getGroupedIndex = () => {
var _table$getState$group2;
return (_table$getState$group2 = table.getState().grouping) == null ? void 0 : _table$getState$group2.indexOf(column.id);
};
column.getToggleGroupingHandler = () => {
const canGroup = column.getCanGroup();
return () => {
if (!canGroup) return;
column.toggleGrouping();
};
};
column.getAutoAggregationFn = () => {
const firstRow = table.getCoreRowModel().flatRows[0];
const value = firstRow == null ? void 0 : firstRow.getValue(column.id);
if (typeof value === 'number') {
return aggregationFns.aggregationFns.sum;
}
if (Object.prototype.toString.call(value) === '[object Date]') {
return aggregationFns.aggregationFns.extent;
}
};
column.getAggregationFn = () => {
var _table$options$aggreg, _table$options$aggreg2;
if (!column) {
throw new Error();
}
return utils.isFunction(column.columnDef.aggregationFn) ? column.columnDef.aggregationFn : column.columnDef.aggregationFn === 'auto' ? column.getAutoAggregationFn() : (_table$options$aggreg = (_table$options$aggreg2 = table.options.aggregationFns) == null ? void 0 : _table$options$aggreg2[column.columnDef.aggregationFn]) != null ? _table$options$aggreg : aggregationFns.aggregationFns[column.columnDef.aggregationFn];
};
},
createTable: table => {
table.setGrouping = updater => table.options.onGroupingChange == null ? void 0 : table.options.onGroupingChange(updater);
table.resetGrouping = defaultState => {
var _table$initialState$g, _table$initialState;
table.setGrouping(defaultState ? [] : (_table$initialState$g = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.grouping) != null ? _table$initialState$g : []);
};
table.getPreGroupedRowModel = () => table.getFilteredRowModel();
table.getGroupedRowModel = () => {
if (!table._getGroupedRowModel && table.options.getGroupedRowModel) {
table._getGroupedRowModel = table.options.getGroupedRowModel(table);
}
if (table.options.manualGrouping || !table._getGroupedRowModel) {
return table.getPreGroupedRowModel();
}
return table._getGroupedRowModel();
};
},
createRow: (row, table) => {
row.getIsGrouped = () => !!row.groupingColumnId;
row.getGroupingValue = columnId => {
if (row._groupingValuesCache.hasOwnProperty(columnId)) {
return row._groupingValuesCache[columnId];
}
const column = table.getColumn(columnId);
if (!(column != null && column.columnDef.getGroupingValue)) {
return row.getValue(columnId);
}
row._groupingValuesCache[columnId] = column.columnDef.getGroupingValue(row.original);
return row._groupingValuesCache[columnId];
};
row._groupingValuesCache = {};
},
createCell: (cell, column, row, table) => {
cell.getIsGrouped = () => column.getIsGrouped() && column.id === row.groupingColumnId;
cell.getIsPlaceholder = () => !cell.getIsGrouped() && column.getIsGrouped();
cell.getIsAggregated = () => {
var _row$subRows;
return !cell.getIsGrouped() && !cell.getIsPlaceholder() && !!((_row$subRows = row.subRows) != null && _row$subRows.length);
};
}
};
function orderColumns(leafColumns, grouping, groupedColumnMode) {
if (!(grouping != null && grouping.length) || !groupedColumnMode) {
return leafColumns;
}
const nonGroupingColumns = leafColumns.filter(col => !grouping.includes(col.id));
if (groupedColumnMode === 'remove') {
return nonGroupingColumns;
}
const groupingColumns = grouping.map(g => leafColumns.find(col => col.id === g)).filter(Boolean);
return [...groupingColumns, ...nonGroupingColumns];
}
exports.ColumnGrouping = ColumnGrouping;
exports.orderColumns = orderColumns;
//# sourceMappingURL=ColumnGrouping.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,53 @@
import { Column, OnChangeFn, RowData, TableFeature, Updater } from '../types';
import { ColumnPinningPosition } from '..';
export interface ColumnOrderTableState {
columnOrder: ColumnOrderState;
}
export type ColumnOrderState = string[];
export interface ColumnOrderOptions {
/**
* If provided, this function will be called with an `updaterFn` when `state.columnOrder` changes. This overrides the default internal state management, so you will need to persist the state change either fully or partially outside of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-ordering#oncolumnorderchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-ordering)
*/
onColumnOrderChange?: OnChangeFn<ColumnOrderState>;
}
export interface ColumnOrderColumn {
/**
* Returns the index of the column in the order of the visible columns. Optionally pass a `position` parameter to get the index of the column in a sub-section of the table
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-ordering#getindex)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-ordering)
*/
getIndex: (position?: ColumnPinningPosition | 'center') => number;
/**
* Returns `true` if the column is the first column in the order of the visible columns. Optionally pass a `position` parameter to check if the column is the first in a sub-section of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-ordering#getisfirstcolumn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-ordering)
*/
getIsFirstColumn: (position?: ColumnPinningPosition | 'center') => boolean;
/**
* Returns `true` if the column is the last column in the order of the visible columns. Optionally pass a `position` parameter to check if the column is the last in a sub-section of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-ordering#getislastcolumn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-ordering)
*/
getIsLastColumn: (position?: ColumnPinningPosition | 'center') => boolean;
}
export interface ColumnOrderDefaultOptions {
onColumnOrderChange: OnChangeFn<ColumnOrderState>;
}
export interface ColumnOrderInstance<TData extends RowData> {
_getOrderColumnsFn: () => (columns: Column<TData, unknown>[]) => Column<TData, unknown>[];
/**
* Resets the **columnOrder** state to `initialState.columnOrder`, or `true` can be passed to force a default blank state reset to `[]`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-ordering#resetcolumnorder)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-ordering)
*/
resetColumnOrder: (defaultState?: boolean) => void;
/**
* Sets or updates the `state.columnOrder` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-ordering#setcolumnorder)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-ordering)
*/
setColumnOrder: (updater: Updater<ColumnOrderState>) => void;
}
export declare const ColumnOrdering: TableFeature;

View File

@@ -0,0 +1,84 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
var ColumnGrouping = require('./ColumnGrouping.js');
var ColumnVisibility = require('./ColumnVisibility.js');
//
const ColumnOrdering = {
getInitialState: state => {
return {
columnOrder: [],
...state
};
},
getDefaultOptions: table => {
return {
onColumnOrderChange: utils.makeStateUpdater('columnOrder', table)
};
},
createColumn: (column, table) => {
column.getIndex = utils.memo(position => [ColumnVisibility._getVisibleLeafColumns(table, position)], columns => columns.findIndex(d => d.id === column.id), utils.getMemoOptions(table.options, 'debugColumns', 'getIndex'));
column.getIsFirstColumn = position => {
var _columns$;
const columns = ColumnVisibility._getVisibleLeafColumns(table, position);
return ((_columns$ = columns[0]) == null ? void 0 : _columns$.id) === column.id;
};
column.getIsLastColumn = position => {
var _columns;
const columns = ColumnVisibility._getVisibleLeafColumns(table, position);
return ((_columns = columns[columns.length - 1]) == null ? void 0 : _columns.id) === column.id;
};
},
createTable: table => {
table.setColumnOrder = updater => table.options.onColumnOrderChange == null ? void 0 : table.options.onColumnOrderChange(updater);
table.resetColumnOrder = defaultState => {
var _table$initialState$c;
table.setColumnOrder(defaultState ? [] : (_table$initialState$c = table.initialState.columnOrder) != null ? _table$initialState$c : []);
};
table._getOrderColumnsFn = utils.memo(() => [table.getState().columnOrder, table.getState().grouping, table.options.groupedColumnMode], (columnOrder, grouping, groupedColumnMode) => columns => {
// Sort grouped columns to the start of the column list
// before the headers are built
let orderedColumns = [];
// If there is no order, return the normal columns
if (!(columnOrder != null && columnOrder.length)) {
orderedColumns = columns;
} else {
const columnOrderCopy = [...columnOrder];
// If there is an order, make a copy of the columns
const columnsCopy = [...columns];
// And make a new ordered array of the columns
// Loop over the columns and place them in order into the new array
while (columnsCopy.length && columnOrderCopy.length) {
const targetColumnId = columnOrderCopy.shift();
const foundIndex = columnsCopy.findIndex(d => d.id === targetColumnId);
if (foundIndex > -1) {
orderedColumns.push(columnsCopy.splice(foundIndex, 1)[0]);
}
}
// If there are any columns left, add them to the end
orderedColumns = [...orderedColumns, ...columnsCopy];
}
return ColumnGrouping.orderColumns(orderedColumns, grouping, groupedColumnMode);
}, utils.getMemoOptions(table.options, 'debugTable', '_getOrderColumnsFn'));
}
};
exports.ColumnOrdering = ColumnOrdering;
//# sourceMappingURL=ColumnOrdering.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,126 @@
import { OnChangeFn, Updater, Column, Cell, RowData, TableFeature } from '../types';
export type ColumnPinningPosition = false | 'left' | 'right';
export interface ColumnPinningState {
left?: string[];
right?: string[];
}
export interface ColumnPinningTableState {
columnPinning: ColumnPinningState;
}
export interface ColumnPinningOptions {
/**
* Enables/disables column pinning for the table. Defaults to `true`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#enablecolumnpinning)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
enableColumnPinning?: boolean;
/**
* @deprecated Use `enableColumnPinning` or `enableRowPinning` instead.
* Enables/disables all pinning for the table. Defaults to `true`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#enablepinning)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
enablePinning?: boolean;
/**
* If provided, this function will be called with an `updaterFn` when `state.columnPinning` changes. This overrides the default internal state management, so you will also need to supply `state.columnPinning` from your own managed state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#oncolumnpinningchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/oncolumnpinningchange)
*/
onColumnPinningChange?: OnChangeFn<ColumnPinningState>;
}
export interface ColumnPinningDefaultOptions {
onColumnPinningChange: OnChangeFn<ColumnPinningState>;
}
export interface ColumnPinningColumnDef {
/**
* Enables/disables column pinning for this column. Defaults to `true`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#enablepinning-1)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
enablePinning?: boolean;
}
export interface ColumnPinningColumn {
/**
* Returns whether or not the column can be pinned.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getcanpin)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getCanPin: () => boolean;
/**
* Returns the pinned position of the column. (`'left'`, `'right'` or `false`)
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getispinned)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getIsPinned: () => ColumnPinningPosition;
/**
* Returns the numeric pinned index of the column within a pinned column group.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getpinnedindex)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getPinnedIndex: () => number;
/**
* Pins a column to the `'left'` or `'right'`, or unpins the column to the center if `false` is passed.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#pin)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
pin: (position: ColumnPinningPosition) => void;
}
export interface ColumnPinningRow<TData extends RowData> {
/**
* Returns all center pinned (unpinned) leaf cells in the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getcentervisiblecells)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getCenterVisibleCells: () => Cell<TData, unknown>[];
/**
* Returns all left pinned leaf cells in the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getleftvisiblecells)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getLeftVisibleCells: () => Cell<TData, unknown>[];
/**
* Returns all right pinned leaf cells in the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getrightvisiblecells)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getRightVisibleCells: () => Cell<TData, unknown>[];
}
export interface ColumnPinningInstance<TData extends RowData> {
/**
* Returns all center pinned (unpinned) leaf columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getcenterleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getCenterLeafColumns: () => Column<TData, unknown>[];
/**
* Returns whether or not any columns are pinned. Optionally specify to only check for pinned columns in either the `left` or `right` position.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getissomecolumnspinned)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getIsSomeColumnsPinned: (position?: ColumnPinningPosition) => boolean;
/**
* Returns all left pinned leaf columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getleftleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getLeftLeafColumns: () => Column<TData, unknown>[];
/**
* Returns all right pinned leaf columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#getrightleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
getRightLeafColumns: () => Column<TData, unknown>[];
/**
* Resets the **columnPinning** state to `initialState.columnPinning`, or `true` can be passed to force a default blank state reset to `{ left: [], right: [], }`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#resetcolumnpinning)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
resetColumnPinning: (defaultState?: boolean) => void;
/**
* Sets or updates the `state.columnPinning` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-pinning#setcolumnpinning)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-pinning)
*/
setColumnPinning: (updater: Updater<ColumnPinningState>) => void;
}
export declare const ColumnPinning: TableFeature;

View File

@@ -0,0 +1,130 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
//
const getDefaultColumnPinningState = () => ({
left: [],
right: []
});
const ColumnPinning = {
getInitialState: state => {
return {
columnPinning: getDefaultColumnPinningState(),
...state
};
},
getDefaultOptions: table => {
return {
onColumnPinningChange: utils.makeStateUpdater('columnPinning', table)
};
},
createColumn: (column, table) => {
column.pin = position => {
const columnIds = column.getLeafColumns().map(d => d.id).filter(Boolean);
table.setColumnPinning(old => {
var _old$left3, _old$right3;
if (position === 'right') {
var _old$left, _old$right;
return {
left: ((_old$left = old == null ? void 0 : old.left) != null ? _old$left : []).filter(d => !(columnIds != null && columnIds.includes(d))),
right: [...((_old$right = old == null ? void 0 : old.right) != null ? _old$right : []).filter(d => !(columnIds != null && columnIds.includes(d))), ...columnIds]
};
}
if (position === 'left') {
var _old$left2, _old$right2;
return {
left: [...((_old$left2 = old == null ? void 0 : old.left) != null ? _old$left2 : []).filter(d => !(columnIds != null && columnIds.includes(d))), ...columnIds],
right: ((_old$right2 = old == null ? void 0 : old.right) != null ? _old$right2 : []).filter(d => !(columnIds != null && columnIds.includes(d)))
};
}
return {
left: ((_old$left3 = old == null ? void 0 : old.left) != null ? _old$left3 : []).filter(d => !(columnIds != null && columnIds.includes(d))),
right: ((_old$right3 = old == null ? void 0 : old.right) != null ? _old$right3 : []).filter(d => !(columnIds != null && columnIds.includes(d)))
};
});
};
column.getCanPin = () => {
const leafColumns = column.getLeafColumns();
return leafColumns.some(d => {
var _d$columnDef$enablePi, _ref, _table$options$enable;
return ((_d$columnDef$enablePi = d.columnDef.enablePinning) != null ? _d$columnDef$enablePi : true) && ((_ref = (_table$options$enable = table.options.enableColumnPinning) != null ? _table$options$enable : table.options.enablePinning) != null ? _ref : true);
});
};
column.getIsPinned = () => {
const leafColumnIds = column.getLeafColumns().map(d => d.id);
const {
left,
right
} = table.getState().columnPinning;
const isLeft = leafColumnIds.some(d => left == null ? void 0 : left.includes(d));
const isRight = leafColumnIds.some(d => right == null ? void 0 : right.includes(d));
return isLeft ? 'left' : isRight ? 'right' : false;
};
column.getPinnedIndex = () => {
var _table$getState$colum, _table$getState$colum2;
const position = column.getIsPinned();
return position ? (_table$getState$colum = (_table$getState$colum2 = table.getState().columnPinning) == null || (_table$getState$colum2 = _table$getState$colum2[position]) == null ? void 0 : _table$getState$colum2.indexOf(column.id)) != null ? _table$getState$colum : -1 : 0;
};
},
createRow: (row, table) => {
row.getCenterVisibleCells = utils.memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allCells, left, right) => {
const leftAndRight = [...(left != null ? left : []), ...(right != null ? right : [])];
return allCells.filter(d => !leftAndRight.includes(d.column.id));
}, utils.getMemoOptions(table.options, 'debugRows', 'getCenterVisibleCells'));
row.getLeftVisibleCells = utils.memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left], (allCells, left) => {
const cells = (left != null ? left : []).map(columnId => allCells.find(cell => cell.column.id === columnId)).filter(Boolean).map(d => ({
...d,
position: 'left'
}));
return cells;
}, utils.getMemoOptions(table.options, 'debugRows', 'getLeftVisibleCells'));
row.getRightVisibleCells = utils.memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.right], (allCells, right) => {
const cells = (right != null ? right : []).map(columnId => allCells.find(cell => cell.column.id === columnId)).filter(Boolean).map(d => ({
...d,
position: 'right'
}));
return cells;
}, utils.getMemoOptions(table.options, 'debugRows', 'getRightVisibleCells'));
},
createTable: table => {
table.setColumnPinning = updater => table.options.onColumnPinningChange == null ? void 0 : table.options.onColumnPinningChange(updater);
table.resetColumnPinning = defaultState => {
var _table$initialState$c, _table$initialState;
return table.setColumnPinning(defaultState ? getDefaultColumnPinningState() : (_table$initialState$c = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.columnPinning) != null ? _table$initialState$c : getDefaultColumnPinningState());
};
table.getIsSomeColumnsPinned = position => {
var _pinningState$positio;
const pinningState = table.getState().columnPinning;
if (!position) {
var _pinningState$left, _pinningState$right;
return Boolean(((_pinningState$left = pinningState.left) == null ? void 0 : _pinningState$left.length) || ((_pinningState$right = pinningState.right) == null ? void 0 : _pinningState$right.length));
}
return Boolean((_pinningState$positio = pinningState[position]) == null ? void 0 : _pinningState$positio.length);
};
table.getLeftLeafColumns = utils.memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left], (allColumns, left) => {
return (left != null ? left : []).map(columnId => allColumns.find(column => column.id === columnId)).filter(Boolean);
}, utils.getMemoOptions(table.options, 'debugColumns', 'getLeftLeafColumns'));
table.getRightLeafColumns = utils.memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.right], (allColumns, right) => {
return (right != null ? right : []).map(columnId => allColumns.find(column => column.id === columnId)).filter(Boolean);
}, utils.getMemoOptions(table.options, 'debugColumns', 'getRightLeafColumns'));
table.getCenterLeafColumns = utils.memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, left, right) => {
const leftAndRight = [...(left != null ? left : []), ...(right != null ? right : [])];
return allColumns.filter(d => !leftAndRight.includes(d.id));
}, utils.getMemoOptions(table.options, 'debugColumns', 'getCenterLeafColumns'));
}
};
exports.ColumnPinning = ColumnPinning;
//# sourceMappingURL=ColumnPinning.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,193 @@
import { OnChangeFn, Updater, TableFeature } from '../types';
import { ColumnPinningPosition } from './ColumnPinning';
export interface ColumnSizingTableState {
columnSizing: ColumnSizingState;
columnSizingInfo: ColumnSizingInfoState;
}
export type ColumnSizingState = Record<string, number>;
export interface ColumnSizingInfoState {
columnSizingStart: [string, number][];
deltaOffset: null | number;
deltaPercentage: null | number;
isResizingColumn: false | string;
startOffset: null | number;
startSize: null | number;
}
export type ColumnResizeMode = 'onChange' | 'onEnd';
export type ColumnResizeDirection = 'ltr' | 'rtl';
export interface ColumnSizingOptions {
/**
* Determines when the columnSizing state is updated. `onChange` updates the state when the user is dragging the resize handle. `onEnd` updates the state when the user releases the resize handle.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#columnresizemode)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
columnResizeMode?: ColumnResizeMode;
/**
* Enables or disables column resizing for the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#enablecolumnresizing)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
enableColumnResizing?: boolean;
/**
* Enables or disables right-to-left support for resizing the column. defaults to 'ltr'.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#columnResizeDirection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
columnResizeDirection?: ColumnResizeDirection;
/**
* If provided, this function will be called with an `updaterFn` when `state.columnSizing` changes. This overrides the default internal state management, so you will also need to supply `state.columnSizing` from your own managed state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#oncolumnsizingchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
onColumnSizingChange?: OnChangeFn<ColumnSizingState>;
/**
* If provided, this function will be called with an `updaterFn` when `state.columnSizingInfo` changes. This overrides the default internal state management, so you will also need to supply `state.columnSizingInfo` from your own managed state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#oncolumnsizinginfochange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
onColumnSizingInfoChange?: OnChangeFn<ColumnSizingInfoState>;
}
export type ColumnSizingDefaultOptions = Pick<ColumnSizingOptions, 'columnResizeMode' | 'onColumnSizingChange' | 'onColumnSizingInfoChange' | 'columnResizeDirection'>;
export interface ColumnSizingInstance {
/**
* If pinning, returns the total size of the center portion of the table by calculating the sum of the sizes of all unpinned/center leaf-columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getcentertotalsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getCenterTotalSize: () => number;
/**
* Returns the total size of the left portion of the table by calculating the sum of the sizes of all left leaf-columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getlefttotalsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getLeftTotalSize: () => number;
/**
* Returns the total size of the right portion of the table by calculating the sum of the sizes of all right leaf-columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getrighttotalsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getRightTotalSize: () => number;
/**
* Returns the total size of the table by calculating the sum of the sizes of all leaf-columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#gettotalsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getTotalSize: () => number;
/**
* Resets column sizing to its initial state. If `defaultState` is `true`, the default state for the table will be used instead of the initialValue provided to the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#resetcolumnsizing)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
resetColumnSizing: (defaultState?: boolean) => void;
/**
* Resets column sizing info to its initial state. If `defaultState` is `true`, the default state for the table will be used instead of the initialValue provided to the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#resetheadersizeinfo)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
resetHeaderSizeInfo: (defaultState?: boolean) => void;
/**
* Sets the column sizing state using an updater function or a value. This will trigger the underlying `onColumnSizingChange` function if one is passed to the table options, otherwise the state will be managed automatically by the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#setcolumnsizing)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
setColumnSizing: (updater: Updater<ColumnSizingState>) => void;
/**
* Sets the column sizing info state using an updater function or a value. This will trigger the underlying `onColumnSizingInfoChange` function if one is passed to the table options, otherwise the state will be managed automatically by the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#setcolumnsizinginfo)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
setColumnSizingInfo: (updater: Updater<ColumnSizingInfoState>) => void;
}
export interface ColumnSizingColumnDef {
/**
* Enables or disables column resizing for the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#enableresizing)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
enableResizing?: boolean;
/**
* The maximum allowed size for the column
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#maxsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
maxSize?: number;
/**
* The minimum allowed size for the column
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#minsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
minSize?: number;
/**
* The desired size for the column
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#size)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
size?: number;
}
export interface ColumnSizingColumn {
/**
* Returns `true` if the column can be resized.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getcanresize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getCanResize: () => boolean;
/**
* Returns `true` if the column is currently being resized.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getisresizing)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getIsResizing: () => boolean;
/**
* Returns the current size of the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getSize: () => number;
/**
* Returns the offset measurement along the row-axis (usually the x-axis for standard tables) for the header. This is effectively a sum of the offset measurements of all preceding (left) headers in relation to the current column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getstart)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getStart: (position?: ColumnPinningPosition | 'center') => number;
/**
* Returns the offset measurement along the row-axis (usually the x-axis for standard tables) for the header. This is effectively a sum of the offset measurements of all succeeding (right) headers in relation to the current column.
*/
getAfter: (position?: ColumnPinningPosition | 'center') => number;
/**
* Resets the column to its initial size.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#resetsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
resetSize: () => void;
}
export interface ColumnSizingHeader {
/**
* Returns an event handler function that can be used to resize the header. It can be used as an:
* - `onMouseDown` handler
* - `onTouchStart` handler
*
* The dragging and release events are automatically handled for you.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getresizehandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getResizeHandler: (context?: Document) => (event: unknown) => void;
/**
* Returns the current size of the header.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getsize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getSize: () => number;
/**
* Returns the offset measurement along the row-axis (usually the x-axis for standard tables) for the header. This is effectively a sum of the offset measurements of all preceding headers.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-sizing#getstart)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-sizing)
*/
getStart: (position?: ColumnPinningPosition) => number;
}
export declare const defaultColumnSizing: {
size: number;
minSize: number;
maxSize: number;
};
export declare const ColumnSizing: TableFeature;
export declare function passiveEventSupported(): boolean;

View File

@@ -0,0 +1,271 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
var document = require('../utils/document.js');
var ColumnVisibility = require('./ColumnVisibility.js');
//
//
const defaultColumnSizing = {
size: 150,
minSize: 20,
maxSize: Number.MAX_SAFE_INTEGER
};
const getDefaultColumnSizingInfoState = () => ({
startOffset: null,
startSize: null,
deltaOffset: null,
deltaPercentage: null,
isResizingColumn: false,
columnSizingStart: []
});
const ColumnSizing = {
getDefaultColumnDef: () => {
return defaultColumnSizing;
},
getInitialState: state => {
return {
columnSizing: {},
columnSizingInfo: getDefaultColumnSizingInfoState(),
...state
};
},
getDefaultOptions: table => {
return {
columnResizeMode: 'onEnd',
columnResizeDirection: 'ltr',
onColumnSizingChange: utils.makeStateUpdater('columnSizing', table),
onColumnSizingInfoChange: utils.makeStateUpdater('columnSizingInfo', table)
};
},
createColumn: (column, table) => {
column.getSize = () => {
var _column$columnDef$min, _ref, _column$columnDef$max;
const columnSize = table.getState().columnSizing[column.id];
return Math.min(Math.max((_column$columnDef$min = column.columnDef.minSize) != null ? _column$columnDef$min : defaultColumnSizing.minSize, (_ref = columnSize != null ? columnSize : column.columnDef.size) != null ? _ref : defaultColumnSizing.size), (_column$columnDef$max = column.columnDef.maxSize) != null ? _column$columnDef$max : defaultColumnSizing.maxSize);
};
column.getStart = utils.memo(position => [position, ColumnVisibility._getVisibleLeafColumns(table, position), table.getState().columnSizing], (position, columns) => columns.slice(0, column.getIndex(position)).reduce((sum, column) => sum + column.getSize(), 0), utils.getMemoOptions(table.options, 'debugColumns', 'getStart'));
column.getAfter = utils.memo(position => [position, ColumnVisibility._getVisibleLeafColumns(table, position), table.getState().columnSizing], (position, columns) => columns.slice(column.getIndex(position) + 1).reduce((sum, column) => sum + column.getSize(), 0), utils.getMemoOptions(table.options, 'debugColumns', 'getAfter'));
column.resetSize = () => {
table.setColumnSizing(_ref2 => {
let {
[column.id]: _,
...rest
} = _ref2;
return rest;
});
};
column.getCanResize = () => {
var _column$columnDef$ena, _table$options$enable;
return ((_column$columnDef$ena = column.columnDef.enableResizing) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableColumnResizing) != null ? _table$options$enable : true);
};
column.getIsResizing = () => {
return table.getState().columnSizingInfo.isResizingColumn === column.id;
};
},
createHeader: (header, table) => {
header.getSize = () => {
let sum = 0;
const recurse = header => {
if (header.subHeaders.length) {
header.subHeaders.forEach(recurse);
} else {
var _header$column$getSiz;
sum += (_header$column$getSiz = header.column.getSize()) != null ? _header$column$getSiz : 0;
}
};
recurse(header);
return sum;
};
header.getStart = () => {
if (header.index > 0) {
const prevSiblingHeader = header.headerGroup.headers[header.index - 1];
return prevSiblingHeader.getStart() + prevSiblingHeader.getSize();
}
return 0;
};
header.getResizeHandler = _contextDocument => {
const column = table.getColumn(header.column.id);
const canResize = column == null ? void 0 : column.getCanResize();
return e => {
if (!column || !canResize) {
return;
}
e.persist == null || e.persist();
if (isTouchStartEvent(e)) {
// lets not respond to multiple touches (e.g. 2 or 3 fingers)
if (e.touches && e.touches.length > 1) {
return;
}
}
const startSize = header.getSize();
const columnSizingStart = header ? header.getLeafHeaders().map(d => [d.column.id, d.column.getSize()]) : [[column.id, column.getSize()]];
const clientX = isTouchStartEvent(e) ? Math.round(e.touches[0].clientX) : e.clientX;
const newColumnSizing = {};
const updateOffset = (eventType, clientXPos) => {
if (typeof clientXPos !== 'number') {
return;
}
table.setColumnSizingInfo(old => {
var _old$startOffset, _old$startSize;
const deltaDirection = table.options.columnResizeDirection === 'rtl' ? -1 : 1;
const deltaOffset = (clientXPos - ((_old$startOffset = old == null ? void 0 : old.startOffset) != null ? _old$startOffset : 0)) * deltaDirection;
const deltaPercentage = Math.max(deltaOffset / ((_old$startSize = old == null ? void 0 : old.startSize) != null ? _old$startSize : 0), -0.999999);
old.columnSizingStart.forEach(_ref3 => {
let [columnId, headerSize] = _ref3;
newColumnSizing[columnId] = Math.round(Math.max(headerSize + headerSize * deltaPercentage, 0) * 100) / 100;
});
return {
...old,
deltaOffset,
deltaPercentage
};
});
if (table.options.columnResizeMode === 'onChange' || eventType === 'end') {
table.setColumnSizing(old => ({
...old,
...newColumnSizing
}));
}
};
const onMove = clientXPos => updateOffset('move', clientXPos);
const onEnd = clientXPos => {
updateOffset('end', clientXPos);
table.setColumnSizingInfo(old => ({
...old,
isResizingColumn: false,
startOffset: null,
startSize: null,
deltaOffset: null,
deltaPercentage: null,
columnSizingStart: []
}));
};
const contextDocument = document.safelyAccessDocument(_contextDocument);
const mouseEvents = {
moveHandler: e => onMove(e.clientX),
upHandler: e => {
contextDocument == null || contextDocument.removeEventListener('mousemove', mouseEvents.moveHandler);
contextDocument == null || contextDocument.removeEventListener('mouseup', mouseEvents.upHandler);
onEnd(e.clientX);
}
};
const touchEvents = {
moveHandler: e => {
if (e.cancelable) {
e.preventDefault();
e.stopPropagation();
}
onMove(e.touches[0].clientX);
return false;
},
upHandler: e => {
var _e$touches$;
contextDocument == null || contextDocument.removeEventListener('touchmove', touchEvents.moveHandler);
contextDocument == null || contextDocument.removeEventListener('touchend', touchEvents.upHandler);
if (e.cancelable) {
e.preventDefault();
e.stopPropagation();
}
onEnd((_e$touches$ = e.touches[0]) == null ? void 0 : _e$touches$.clientX);
}
};
const passiveIfSupported = passiveEventSupported() ? {
passive: false
} : false;
if (isTouchStartEvent(e)) {
contextDocument == null || contextDocument.addEventListener('touchmove', touchEvents.moveHandler, passiveIfSupported);
contextDocument == null || contextDocument.addEventListener('touchend', touchEvents.upHandler, passiveIfSupported);
} else {
contextDocument == null || contextDocument.addEventListener('mousemove', mouseEvents.moveHandler, passiveIfSupported);
contextDocument == null || contextDocument.addEventListener('mouseup', mouseEvents.upHandler, passiveIfSupported);
}
table.setColumnSizingInfo(old => ({
...old,
startOffset: clientX,
startSize,
deltaOffset: 0,
deltaPercentage: 0,
columnSizingStart,
isResizingColumn: column.id
}));
};
};
},
createTable: table => {
table.setColumnSizing = updater => table.options.onColumnSizingChange == null ? void 0 : table.options.onColumnSizingChange(updater);
table.setColumnSizingInfo = updater => table.options.onColumnSizingInfoChange == null ? void 0 : table.options.onColumnSizingInfoChange(updater);
table.resetColumnSizing = defaultState => {
var _table$initialState$c;
table.setColumnSizing(defaultState ? {} : (_table$initialState$c = table.initialState.columnSizing) != null ? _table$initialState$c : {});
};
table.resetHeaderSizeInfo = defaultState => {
var _table$initialState$c2;
table.setColumnSizingInfo(defaultState ? getDefaultColumnSizingInfoState() : (_table$initialState$c2 = table.initialState.columnSizingInfo) != null ? _table$initialState$c2 : getDefaultColumnSizingInfoState());
};
table.getTotalSize = () => {
var _table$getHeaderGroup, _table$getHeaderGroup2;
return (_table$getHeaderGroup = (_table$getHeaderGroup2 = table.getHeaderGroups()[0]) == null ? void 0 : _table$getHeaderGroup2.headers.reduce((sum, header) => {
return sum + header.getSize();
}, 0)) != null ? _table$getHeaderGroup : 0;
};
table.getLeftTotalSize = () => {
var _table$getLeftHeaderG, _table$getLeftHeaderG2;
return (_table$getLeftHeaderG = (_table$getLeftHeaderG2 = table.getLeftHeaderGroups()[0]) == null ? void 0 : _table$getLeftHeaderG2.headers.reduce((sum, header) => {
return sum + header.getSize();
}, 0)) != null ? _table$getLeftHeaderG : 0;
};
table.getCenterTotalSize = () => {
var _table$getCenterHeade, _table$getCenterHeade2;
return (_table$getCenterHeade = (_table$getCenterHeade2 = table.getCenterHeaderGroups()[0]) == null ? void 0 : _table$getCenterHeade2.headers.reduce((sum, header) => {
return sum + header.getSize();
}, 0)) != null ? _table$getCenterHeade : 0;
};
table.getRightTotalSize = () => {
var _table$getRightHeader, _table$getRightHeader2;
return (_table$getRightHeader = (_table$getRightHeader2 = table.getRightHeaderGroups()[0]) == null ? void 0 : _table$getRightHeader2.headers.reduce((sum, header) => {
return sum + header.getSize();
}, 0)) != null ? _table$getRightHeader : 0;
};
}
};
let passiveSupported = null;
function passiveEventSupported() {
if (typeof passiveSupported === 'boolean') return passiveSupported;
let supported = false;
try {
const options = {
get passive() {
supported = true;
return false;
}
};
const noop = () => {};
window.addEventListener('test', noop, options);
window.removeEventListener('test', noop);
} catch (err) {
supported = false;
}
passiveSupported = supported;
return passiveSupported;
}
function isTouchStartEvent(e) {
return e.type === 'touchstart';
}
exports.ColumnSizing = ColumnSizing;
exports.defaultColumnSizing = defaultColumnSizing;
exports.passiveEventSupported = passiveEventSupported;
//# sourceMappingURL=ColumnSizing.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,129 @@
import { ColumnPinningPosition } from '..';
import { Cell, Column, OnChangeFn, Table, Updater, RowData, TableFeature } from '../types';
export type VisibilityState = Record<string, boolean>;
export interface VisibilityTableState {
columnVisibility: VisibilityState;
}
export interface VisibilityOptions {
/**
* Whether to enable column hiding. Defaults to `true`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#enablehiding)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
enableHiding?: boolean;
/**
* If provided, this function will be called with an `updaterFn` when `state.columnVisibility` changes. This overrides the default internal state management, so you will need to persist the state change either fully or partially outside of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#oncolumnvisibilitychange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
onColumnVisibilityChange?: OnChangeFn<VisibilityState>;
}
export type VisibilityDefaultOptions = Pick<VisibilityOptions, 'onColumnVisibilityChange'>;
export interface VisibilityInstance<TData extends RowData> {
/**
* If column pinning, returns a flat array of leaf-node columns that are visible in the unpinned/center portion of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getcentervisibleleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getCenterVisibleLeafColumns: () => Column<TData, unknown>[];
/**
* Returns whether all columns are visible
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getisallcolumnsvisible)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getIsAllColumnsVisible: () => boolean;
/**
* Returns whether any columns are visible
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getissomecolumnsvisible)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getIsSomeColumnsVisible: () => boolean;
/**
* If column pinning, returns a flat array of leaf-node columns that are visible in the left portion of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getleftvisibleleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getLeftVisibleLeafColumns: () => Column<TData, unknown>[];
/**
* If column pinning, returns a flat array of leaf-node columns that are visible in the right portion of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getrightvisibleleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getRightVisibleLeafColumns: () => Column<TData, unknown>[];
/**
* Returns a handler for toggling the visibility of all columns, meant to be bound to a `input[type=checkbox]` element.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#gettoggleallcolumnsvisibilityhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getToggleAllColumnsVisibilityHandler: () => (event: unknown) => void;
/**
* Returns a flat array of columns that are visible, including parent columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getvisibleflatcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getVisibleFlatColumns: () => Column<TData, unknown>[];
/**
* Returns a flat array of leaf-node columns that are visible.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getvisibleleafcolumns)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getVisibleLeafColumns: () => Column<TData, unknown>[];
/**
* Resets the column visibility state to the initial state. If `defaultState` is provided, the state will be reset to `{}`
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#resetcolumnvisibility)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
resetColumnVisibility: (defaultState?: boolean) => void;
/**
* Sets or updates the `state.columnVisibility` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#setcolumnvisibility)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
setColumnVisibility: (updater: Updater<VisibilityState>) => void;
/**
* Toggles the visibility of all columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#toggleallcolumnsvisible)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
toggleAllColumnsVisible: (value?: boolean) => void;
}
export interface VisibilityColumnDef {
enableHiding?: boolean;
}
export interface VisibilityRow<TData extends RowData> {
_getAllVisibleCells: () => Cell<TData, unknown>[];
/**
* Returns an array of cells that account for column visibility for the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getvisiblecells)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getVisibleCells: () => Cell<TData, unknown>[];
}
export interface VisibilityColumn {
/**
* Returns whether the column can be hidden
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getcanhide)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getCanHide: () => boolean;
/**
* Returns whether the column is visible
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#getisvisible)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getIsVisible: () => boolean;
/**
* Returns a function that can be used to toggle the column visibility. This function can be used to bind to an event handler to a checkbox.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#gettogglevisibilityhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
getToggleVisibilityHandler: () => (event: unknown) => void;
/**
* Toggles the visibility of the column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/column-visibility#togglevisibility)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/column-visibility)
*/
toggleVisibility: (value?: boolean) => void;
}
export declare const ColumnVisibility: TableFeature;
export declare function _getVisibleLeafColumns<TData extends RowData>(table: Table<TData>, position?: ColumnPinningPosition | 'center'): Column<TData, unknown>[];

View File

@@ -0,0 +1,99 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
//
const ColumnVisibility = {
getInitialState: state => {
return {
columnVisibility: {},
...state
};
},
getDefaultOptions: table => {
return {
onColumnVisibilityChange: utils.makeStateUpdater('columnVisibility', table)
};
},
createColumn: (column, table) => {
column.toggleVisibility = value => {
if (column.getCanHide()) {
table.setColumnVisibility(old => ({
...old,
[column.id]: value != null ? value : !column.getIsVisible()
}));
}
};
column.getIsVisible = () => {
var _ref, _table$getState$colum;
const childColumns = column.columns;
return (_ref = childColumns.length ? childColumns.some(c => c.getIsVisible()) : (_table$getState$colum = table.getState().columnVisibility) == null ? void 0 : _table$getState$colum[column.id]) != null ? _ref : true;
};
column.getCanHide = () => {
var _column$columnDef$ena, _table$options$enable;
return ((_column$columnDef$ena = column.columnDef.enableHiding) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableHiding) != null ? _table$options$enable : true);
};
column.getToggleVisibilityHandler = () => {
return e => {
column.toggleVisibility == null || column.toggleVisibility(e.target.checked);
};
};
},
createRow: (row, table) => {
row._getAllVisibleCells = utils.memo(() => [row.getAllCells(), table.getState().columnVisibility], cells => {
return cells.filter(cell => cell.column.getIsVisible());
}, utils.getMemoOptions(table.options, 'debugRows', '_getAllVisibleCells'));
row.getVisibleCells = utils.memo(() => [row.getLeftVisibleCells(), row.getCenterVisibleCells(), row.getRightVisibleCells()], (left, center, right) => [...left, ...center, ...right], utils.getMemoOptions(table.options, 'debugRows', 'getVisibleCells'));
},
createTable: table => {
const makeVisibleColumnsMethod = (key, getColumns) => {
return utils.memo(() => [getColumns(), getColumns().filter(d => d.getIsVisible()).map(d => d.id).join('_')], columns => {
return columns.filter(d => d.getIsVisible == null ? void 0 : d.getIsVisible());
}, utils.getMemoOptions(table.options, 'debugColumns', key));
};
table.getVisibleFlatColumns = makeVisibleColumnsMethod('getVisibleFlatColumns', () => table.getAllFlatColumns());
table.getVisibleLeafColumns = makeVisibleColumnsMethod('getVisibleLeafColumns', () => table.getAllLeafColumns());
table.getLeftVisibleLeafColumns = makeVisibleColumnsMethod('getLeftVisibleLeafColumns', () => table.getLeftLeafColumns());
table.getRightVisibleLeafColumns = makeVisibleColumnsMethod('getRightVisibleLeafColumns', () => table.getRightLeafColumns());
table.getCenterVisibleLeafColumns = makeVisibleColumnsMethod('getCenterVisibleLeafColumns', () => table.getCenterLeafColumns());
table.setColumnVisibility = updater => table.options.onColumnVisibilityChange == null ? void 0 : table.options.onColumnVisibilityChange(updater);
table.resetColumnVisibility = defaultState => {
var _table$initialState$c;
table.setColumnVisibility(defaultState ? {} : (_table$initialState$c = table.initialState.columnVisibility) != null ? _table$initialState$c : {});
};
table.toggleAllColumnsVisible = value => {
var _value;
value = (_value = value) != null ? _value : !table.getIsAllColumnsVisible();
table.setColumnVisibility(table.getAllLeafColumns().reduce((obj, column) => ({
...obj,
[column.id]: !value ? !(column.getCanHide != null && column.getCanHide()) : value
}), {}));
};
table.getIsAllColumnsVisible = () => !table.getAllLeafColumns().some(column => !(column.getIsVisible != null && column.getIsVisible()));
table.getIsSomeColumnsVisible = () => table.getAllLeafColumns().some(column => column.getIsVisible == null ? void 0 : column.getIsVisible());
table.getToggleAllColumnsVisibilityHandler = () => {
return e => {
var _target;
table.toggleAllColumnsVisible((_target = e.target) == null ? void 0 : _target.checked);
};
};
}
};
function _getVisibleLeafColumns(table, position) {
return !position ? table.getVisibleLeafColumns() : position === 'center' ? table.getCenterVisibleLeafColumns() : position === 'left' ? table.getLeftVisibleLeafColumns() : table.getRightVisibleLeafColumns();
}
exports.ColumnVisibility = ColumnVisibility;
exports._getVisibleLeafColumns = _getVisibleLeafColumns;
//# sourceMappingURL=ColumnVisibility.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
import { RowModel } from '..';
import { RowData, TableFeature } from '../types';
export interface GlobalFacetingInstance<TData extends RowData> {
_getGlobalFacetedMinMaxValues?: () => undefined | [number, number];
_getGlobalFacetedRowModel?: () => RowModel<TData>;
_getGlobalFacetedUniqueValues?: () => Map<any, number>;
/**
* Currently, this function returns the built-in `includesString` filter function. In future releases, it may return more dynamic filter functions based on the nature of the data provided.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-faceting#getglobalautofilterfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-faceting)
*/
getGlobalFacetedMinMaxValues: () => undefined | [number, number];
/**
* Returns the row model for the table after **global** filtering has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-faceting#getglobalfacetedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-faceting)
*/
getGlobalFacetedRowModel: () => RowModel<TData>;
/**
* Returns the faceted unique values for the global filter.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-faceting#getglobalfaceteduniquevalues)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-faceting)
*/
getGlobalFacetedUniqueValues: () => Map<any, number>;
}
export declare const GlobalFaceting: TableFeature;

View File

@@ -0,0 +1,42 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
//
const GlobalFaceting = {
createTable: table => {
table._getGlobalFacetedRowModel = table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, '__global__');
table.getGlobalFacetedRowModel = () => {
if (table.options.manualFiltering || !table._getGlobalFacetedRowModel) {
return table.getPreFilteredRowModel();
}
return table._getGlobalFacetedRowModel();
};
table._getGlobalFacetedUniqueValues = table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, '__global__');
table.getGlobalFacetedUniqueValues = () => {
if (!table._getGlobalFacetedUniqueValues) {
return new Map();
}
return table._getGlobalFacetedUniqueValues();
};
table._getGlobalFacetedMinMaxValues = table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, '__global__');
table.getGlobalFacetedMinMaxValues = () => {
if (!table._getGlobalFacetedMinMaxValues) {
return;
}
return table._getGlobalFacetedMinMaxValues();
};
}
};
exports.GlobalFaceting = GlobalFaceting;
//# sourceMappingURL=GlobalFaceting.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"GlobalFaceting.js","sources":["../../../src/features/GlobalFaceting.ts"],"sourcesContent":["import { RowModel } from '..'\nimport { Table, RowData, TableFeature } from '../types'\n\nexport interface GlobalFacetingInstance<TData extends RowData> {\n _getGlobalFacetedMinMaxValues?: () => undefined | [number, number]\n _getGlobalFacetedRowModel?: () => RowModel<TData>\n _getGlobalFacetedUniqueValues?: () => Map<any, number>\n /**\n * Currently, this function returns the built-in `includesString` filter function. In future releases, it may return more dynamic filter functions based on the nature of the data provided.\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-faceting#getglobalautofilterfn)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/global-faceting)\n */\n getGlobalFacetedMinMaxValues: () => undefined | [number, number]\n /**\n * Returns the row model for the table after **global** filtering has been applied.\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-faceting#getglobalfacetedrowmodel)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/global-faceting)\n */\n getGlobalFacetedRowModel: () => RowModel<TData>\n /**\n * Returns the faceted unique values for the global filter.\n * @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-faceting#getglobalfaceteduniquevalues)\n * @link [Guide](https://tanstack.com/table/v8/docs/guide/global-faceting)\n */\n getGlobalFacetedUniqueValues: () => Map<any, number>\n}\n\n//\n\nexport const GlobalFaceting: TableFeature = {\n createTable: <TData extends RowData>(table: Table<TData>): void => {\n table._getGlobalFacetedRowModel =\n table.options.getFacetedRowModel &&\n table.options.getFacetedRowModel(table, '__global__')\n\n table.getGlobalFacetedRowModel = () => {\n if (table.options.manualFiltering || !table._getGlobalFacetedRowModel) {\n return table.getPreFilteredRowModel()\n }\n\n return table._getGlobalFacetedRowModel()\n }\n\n table._getGlobalFacetedUniqueValues =\n table.options.getFacetedUniqueValues &&\n table.options.getFacetedUniqueValues(table, '__global__')\n table.getGlobalFacetedUniqueValues = () => {\n if (!table._getGlobalFacetedUniqueValues) {\n return new Map()\n }\n\n return table._getGlobalFacetedUniqueValues()\n }\n\n table._getGlobalFacetedMinMaxValues =\n table.options.getFacetedMinMaxValues &&\n table.options.getFacetedMinMaxValues(table, '__global__')\n table.getGlobalFacetedMinMaxValues = () => {\n if (!table._getGlobalFacetedMinMaxValues) {\n return\n }\n\n return table._getGlobalFacetedMinMaxValues()\n }\n },\n}\n"],"names":["GlobalFaceting","createTable","table","_getGlobalFacetedRowModel","options","getFacetedRowModel","getGlobalFacetedRowModel","manualFiltering","getPreFilteredRowModel","_getGlobalFacetedUniqueValues","getFacetedUniqueValues","getGlobalFacetedUniqueValues","Map","_getGlobalFacetedMinMaxValues","getFacetedMinMaxValues","getGlobalFacetedMinMaxValues"],"mappings":";;;;;;;;;;;;AA2BA;;AAEO,MAAMA,cAA4B,GAAG;EAC1CC,WAAW,EAA0BC,KAAmB,IAAW;AACjEA,IAAAA,KAAK,CAACC,yBAAyB,GAC7BD,KAAK,CAACE,OAAO,CAACC,kBAAkB,IAChCH,KAAK,CAACE,OAAO,CAACC,kBAAkB,CAACH,KAAK,EAAE,YAAY,CAAC,CAAA;IAEvDA,KAAK,CAACI,wBAAwB,GAAG,MAAM;MACrC,IAAIJ,KAAK,CAACE,OAAO,CAACG,eAAe,IAAI,CAACL,KAAK,CAACC,yBAAyB,EAAE;AACrE,QAAA,OAAOD,KAAK,CAACM,sBAAsB,EAAE,CAAA;AACvC,OAAA;AAEA,MAAA,OAAON,KAAK,CAACC,yBAAyB,EAAE,CAAA;KACzC,CAAA;AAEDD,IAAAA,KAAK,CAACO,6BAA6B,GACjCP,KAAK,CAACE,OAAO,CAACM,sBAAsB,IACpCR,KAAK,CAACE,OAAO,CAACM,sBAAsB,CAACR,KAAK,EAAE,YAAY,CAAC,CAAA;IAC3DA,KAAK,CAACS,4BAA4B,GAAG,MAAM;AACzC,MAAA,IAAI,CAACT,KAAK,CAACO,6BAA6B,EAAE;QACxC,OAAO,IAAIG,GAAG,EAAE,CAAA;AAClB,OAAA;AAEA,MAAA,OAAOV,KAAK,CAACO,6BAA6B,EAAE,CAAA;KAC7C,CAAA;AAEDP,IAAAA,KAAK,CAACW,6BAA6B,GACjCX,KAAK,CAACE,OAAO,CAACU,sBAAsB,IACpCZ,KAAK,CAACE,OAAO,CAACU,sBAAsB,CAACZ,KAAK,EAAE,YAAY,CAAC,CAAA;IAC3DA,KAAK,CAACa,4BAA4B,GAAG,MAAM;AACzC,MAAA,IAAI,CAACb,KAAK,CAACW,6BAA6B,EAAE;AACxC,QAAA,OAAA;AACF,OAAA;AAEA,MAAA,OAAOX,KAAK,CAACW,6BAA6B,EAAE,CAAA;KAC7C,CAAA;AACH,GAAA;AACF;;;;"}

View File

@@ -0,0 +1,79 @@
import { FilterFn, FilterFnOption } from '..';
import { Column, OnChangeFn, Updater, RowData, TableFeature } from '../types';
export interface GlobalFilterTableState {
globalFilter: any;
}
export interface GlobalFilterColumnDef {
/**
* Enables/disables the **global** filter for this column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#enableglobalfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
enableGlobalFilter?: boolean;
}
export interface GlobalFilterColumn {
/**
* Returns whether or not the column can be **globally** filtered. Set to `false` to disable a column from being scanned during global filtering.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#getcanglobalfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
getCanGlobalFilter: () => boolean;
}
export interface GlobalFilterOptions<TData extends RowData> {
/**
* Enables/disables **global** filtering for all columns.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#enableglobalfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
enableGlobalFilter?: boolean;
/**
* If provided, this function will be called with the column and should return `true` or `false` to indicate whether this column should be used for global filtering.
*
* This is useful if the column can contain data that is not `string` or `number` (i.e. `undefined`).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#getcolumncanglobalfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
getColumnCanGlobalFilter?: (column: Column<TData, unknown>) => boolean;
/**
* The filter function to use for global filtering.
* - A `string` referencing a built-in filter function
* - A `string` that references a custom filter functions provided via the `tableOptions.filterFns` option
* - A custom filter function
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#globalfilterfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
globalFilterFn?: FilterFnOption<TData>;
/**
* If provided, this function will be called with an `updaterFn` when `state.globalFilter` changes. This overrides the default internal state management, so you will need to persist the state change either fully or partially outside of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#onglobalfilterchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
onGlobalFilterChange?: OnChangeFn<any>;
}
export interface GlobalFilterInstance<TData extends RowData> {
/**
* Currently, this function returns the built-in `includesString` filter function. In future releases, it may return more dynamic filter functions based on the nature of the data provided.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#getglobalautofilterfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
getGlobalAutoFilterFn: () => FilterFn<TData> | undefined;
/**
* Returns the filter function (either user-defined or automatic, depending on configuration) for the global filter.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#getglobalfilterfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
getGlobalFilterFn: () => FilterFn<TData> | undefined;
/**
* Resets the **globalFilter** state to `initialState.globalFilter`, or `true` can be passed to force a default blank state reset to `undefined`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#resetglobalfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
resetGlobalFilter: (defaultState?: boolean) => void;
/**
* Sets or updates the `state.globalFilter` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/global-filtering#setglobalfilter)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/global-filtering)
*/
setGlobalFilter: (updater: Updater<any>) => void;
}
export declare const GlobalFiltering: TableFeature;

View File

@@ -0,0 +1,63 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var filterFns = require('../filterFns.js');
var utils = require('../utils.js');
//
const GlobalFiltering = {
getInitialState: state => {
return {
globalFilter: undefined,
...state
};
},
getDefaultOptions: table => {
return {
onGlobalFilterChange: utils.makeStateUpdater('globalFilter', table),
globalFilterFn: 'auto',
getColumnCanGlobalFilter: column => {
var _table$getCoreRowMode;
const value = (_table$getCoreRowMode = table.getCoreRowModel().flatRows[0]) == null || (_table$getCoreRowMode = _table$getCoreRowMode._getAllCellsByColumnId()[column.id]) == null ? void 0 : _table$getCoreRowMode.getValue();
return typeof value === 'string' || typeof value === 'number';
}
};
},
createColumn: (column, table) => {
column.getCanGlobalFilter = () => {
var _column$columnDef$ena, _table$options$enable, _table$options$enable2, _table$options$getCol;
return ((_column$columnDef$ena = column.columnDef.enableGlobalFilter) != null ? _column$columnDef$ena : true) && ((_table$options$enable = table.options.enableGlobalFilter) != null ? _table$options$enable : true) && ((_table$options$enable2 = table.options.enableFilters) != null ? _table$options$enable2 : true) && ((_table$options$getCol = table.options.getColumnCanGlobalFilter == null ? void 0 : table.options.getColumnCanGlobalFilter(column)) != null ? _table$options$getCol : true) && !!column.accessorFn;
};
},
createTable: table => {
table.getGlobalAutoFilterFn = () => {
return filterFns.filterFns.includesString;
};
table.getGlobalFilterFn = () => {
var _table$options$filter, _table$options$filter2;
const {
globalFilterFn: globalFilterFn
} = table.options;
return utils.isFunction(globalFilterFn) ? globalFilterFn : globalFilterFn === 'auto' ? table.getGlobalAutoFilterFn() : (_table$options$filter = (_table$options$filter2 = table.options.filterFns) == null ? void 0 : _table$options$filter2[globalFilterFn]) != null ? _table$options$filter : filterFns.filterFns[globalFilterFn];
};
table.setGlobalFilter = updater => {
table.options.onGlobalFilterChange == null || table.options.onGlobalFilterChange(updater);
};
table.resetGlobalFilter = defaultState => {
table.setGlobalFilter(defaultState ? undefined : table.initialState.globalFilter);
};
}
};
exports.GlobalFiltering = GlobalFiltering;
//# sourceMappingURL=GlobalFiltering.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,154 @@
import { RowModel } from '..';
import { OnChangeFn, Table, Row, Updater, RowData, TableFeature } from '../types';
export type ExpandedStateList = Record<string, boolean>;
export type ExpandedState = true | Record<string, boolean>;
export interface ExpandedTableState {
expanded: ExpandedState;
}
export interface ExpandedRow {
/**
* Returns whether the row can be expanded.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getcanexpand)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getCanExpand: () => boolean;
/**
* Returns whether all parent rows of the row are expanded.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getisallparentsexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getIsAllParentsExpanded: () => boolean;
/**
* Returns whether the row is expanded.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getisexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getIsExpanded: () => boolean;
/**
* Returns a function that can be used to toggle the expanded state of the row. This function can be used to bind to an event handler to a button.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#gettoggleexpandedhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getToggleExpandedHandler: () => () => void;
/**
* Toggles the expanded state (or sets it if `expanded` is provided) for the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#toggleexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
toggleExpanded: (expanded?: boolean) => void;
}
export interface ExpandedOptions<TData extends RowData> {
/**
* Enable this setting to automatically reset the expanded state of the table when expanding state changes.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#autoresetexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
autoResetExpanded?: boolean;
/**
* Enable/disable expanding for all rows.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#enableexpanding)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
enableExpanding?: boolean;
/**
* This function is responsible for returning the expanded row model. If this function is not provided, the table will not expand rows. You can use the default exported `getExpandedRowModel` function to get the expanded row model or implement your own.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getexpandedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getExpandedRowModel?: (table: Table<any>) => () => RowModel<any>;
/**
* If provided, allows you to override the default behavior of determining whether a row is currently expanded.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getisrowexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getIsRowExpanded?: (row: Row<TData>) => boolean;
/**
* If provided, allows you to override the default behavior of determining whether a row can be expanded.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getrowcanexpand)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getRowCanExpand?: (row: Row<TData>) => boolean;
/**
* Enables manual row expansion. If this is set to `true`, `getExpandedRowModel` will not be used to expand rows and you would be expected to perform the expansion in your own data model. This is useful if you are doing server-side expansion.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#manualexpanding)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
manualExpanding?: boolean;
/**
* This function is called when the `expanded` table state changes. If a function is provided, you will be responsible for managing this state on your own. To pass the managed state back to the table, use the `tableOptions.state.expanded` option.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#onexpandedchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
onExpandedChange?: OnChangeFn<ExpandedState>;
/**
* If `true` expanded rows will be paginated along with the rest of the table (which means expanded rows may span multiple pages). If `false` expanded rows will not be considered for pagination (which means expanded rows will always render on their parents page. This also means more rows will be rendered than the set page size)
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#paginateexpandedrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
paginateExpandedRows?: boolean;
}
export interface ExpandedInstance<TData extends RowData> {
_autoResetExpanded: () => void;
_getExpandedRowModel?: () => RowModel<TData>;
/**
* Returns whether there are any rows that can be expanded.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getcansomerowsexpand)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getCanSomeRowsExpand: () => boolean;
/**
* Returns the maximum depth of the expanded rows.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getexpandeddepth)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getExpandedDepth: () => number;
/**
* Returns the row model after expansion has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getexpandedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getExpandedRowModel: () => RowModel<TData>;
/**
* Returns whether all rows are currently expanded.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getisallrowsexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getIsAllRowsExpanded: () => boolean;
/**
* Returns whether there are any rows that are currently expanded.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getissomerowsexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getIsSomeRowsExpanded: () => boolean;
/**
* Returns the row model before expansion has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#getpreexpandedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getPreExpandedRowModel: () => RowModel<TData>;
/**
* Returns a handler that can be used to toggle the expanded state of all rows. This handler is meant to be used with an `input[type=checkbox]` element.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#gettoggleallrowsexpandedhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
getToggleAllRowsExpandedHandler: () => (event: unknown) => void;
/**
* Resets the expanded state of the table to the initial state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#resetexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
resetExpanded: (defaultState?: boolean) => void;
/**
* Updates the expanded state of the table via an update function or value.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#setexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
setExpanded: (updater: Updater<ExpandedState>) => void;
/**
* Toggles the expanded state for all rows.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/expanding#toggleallrowsexpanded)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/expanding)
*/
toggleAllRowsExpanded: (expanded?: boolean) => void;
}
export declare const RowExpanding: TableFeature;

View File

@@ -0,0 +1,173 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
//
const RowExpanding = {
getInitialState: state => {
return {
expanded: {},
...state
};
},
getDefaultOptions: table => {
return {
onExpandedChange: utils.makeStateUpdater('expanded', table),
paginateExpandedRows: true
};
},
createTable: table => {
let registered = false;
let queued = false;
table._autoResetExpanded = () => {
var _ref, _table$options$autoRe;
if (!registered) {
table._queue(() => {
registered = true;
});
return;
}
if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetExpanded) != null ? _ref : !table.options.manualExpanding) {
if (queued) return;
queued = true;
table._queue(() => {
table.resetExpanded();
queued = false;
});
}
};
table.setExpanded = updater => table.options.onExpandedChange == null ? void 0 : table.options.onExpandedChange(updater);
table.toggleAllRowsExpanded = expanded => {
if (expanded != null ? expanded : !table.getIsAllRowsExpanded()) {
table.setExpanded(true);
} else {
table.setExpanded({});
}
};
table.resetExpanded = defaultState => {
var _table$initialState$e, _table$initialState;
table.setExpanded(defaultState ? {} : (_table$initialState$e = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.expanded) != null ? _table$initialState$e : {});
};
table.getCanSomeRowsExpand = () => {
return table.getPrePaginationRowModel().flatRows.some(row => row.getCanExpand());
};
table.getToggleAllRowsExpandedHandler = () => {
return e => {
e.persist == null || e.persist();
table.toggleAllRowsExpanded();
};
};
table.getIsSomeRowsExpanded = () => {
const expanded = table.getState().expanded;
return expanded === true || Object.values(expanded).some(Boolean);
};
table.getIsAllRowsExpanded = () => {
const expanded = table.getState().expanded;
// If expanded is true, save some cycles and return true
if (typeof expanded === 'boolean') {
return expanded === true;
}
if (!Object.keys(expanded).length) {
return false;
}
// If any row is not expanded, return false
if (table.getRowModel().flatRows.some(row => !row.getIsExpanded())) {
return false;
}
// They must all be expanded :shrug:
return true;
};
table.getExpandedDepth = () => {
let maxDepth = 0;
const rowIds = table.getState().expanded === true ? Object.keys(table.getRowModel().rowsById) : Object.keys(table.getState().expanded);
rowIds.forEach(id => {
const splitId = id.split('.');
maxDepth = Math.max(maxDepth, splitId.length);
});
return maxDepth;
};
table.getPreExpandedRowModel = () => table.getSortedRowModel();
table.getExpandedRowModel = () => {
if (!table._getExpandedRowModel && table.options.getExpandedRowModel) {
table._getExpandedRowModel = table.options.getExpandedRowModel(table);
}
if (table.options.manualExpanding || !table._getExpandedRowModel) {
return table.getPreExpandedRowModel();
}
return table._getExpandedRowModel();
};
},
createRow: (row, table) => {
row.toggleExpanded = expanded => {
table.setExpanded(old => {
var _expanded;
const exists = old === true ? true : !!(old != null && old[row.id]);
let oldExpanded = {};
if (old === true) {
Object.keys(table.getRowModel().rowsById).forEach(rowId => {
oldExpanded[rowId] = true;
});
} else {
oldExpanded = old;
}
expanded = (_expanded = expanded) != null ? _expanded : !exists;
if (!exists && expanded) {
return {
...oldExpanded,
[row.id]: true
};
}
if (exists && !expanded) {
const {
[row.id]: _,
...rest
} = oldExpanded;
return rest;
}
return old;
});
};
row.getIsExpanded = () => {
var _table$options$getIsR;
const expanded = table.getState().expanded;
return !!((_table$options$getIsR = table.options.getIsRowExpanded == null ? void 0 : table.options.getIsRowExpanded(row)) != null ? _table$options$getIsR : expanded === true || (expanded == null ? void 0 : expanded[row.id]));
};
row.getCanExpand = () => {
var _table$options$getRow, _table$options$enable, _row$subRows;
return (_table$options$getRow = table.options.getRowCanExpand == null ? void 0 : table.options.getRowCanExpand(row)) != null ? _table$options$getRow : ((_table$options$enable = table.options.enableExpanding) != null ? _table$options$enable : true) && !!((_row$subRows = row.subRows) != null && _row$subRows.length);
};
row.getIsAllParentsExpanded = () => {
let isFullyExpanded = true;
let currentRow = row;
while (isFullyExpanded && currentRow.parentId) {
currentRow = table.getRow(currentRow.parentId, true);
isFullyExpanded = currentRow.getIsExpanded();
}
return isFullyExpanded;
};
row.getToggleExpandedHandler = () => {
const canExpand = row.getCanExpand();
return () => {
if (!canExpand) return;
row.toggleExpanded();
};
};
}
};
exports.RowExpanding = RowExpanding;
//# sourceMappingURL=RowExpanding.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,165 @@
import { OnChangeFn, Table, RowModel, Updater, RowData, TableFeature } from '../types';
export interface PaginationState {
pageIndex: number;
pageSize: number;
}
export interface PaginationTableState {
pagination: PaginationState;
}
export interface PaginationInitialTableState {
pagination?: Partial<PaginationState>;
}
export interface PaginationOptions {
/**
* If set to `true`, pagination will be reset to the first page when page-altering state changes eg. `data` is updated, filters change, grouping changes, etc.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#autoresetpageindex)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
autoResetPageIndex?: boolean;
/**
* Returns the row model after pagination has taken place, but no further.
*
* Pagination columns are automatically reordered by default to the start of the columns list. If you would rather remove them or leave them as-is, set the appropriate mode here.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#getpaginationrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
getPaginationRowModel?: (table: Table<any>) => () => RowModel<any>;
/**
* Enables manual pagination. If this option is set to `true`, the table will not automatically paginate rows using `getPaginationRowModel()` and instead will expect you to manually paginate the rows before passing them to the table. This is useful if you are doing server-side pagination and aggregation.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#manualpagination)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
manualPagination?: boolean;
/**
* If this function is provided, it will be called when the pagination state changes and you will be expected to manage the state yourself. You can pass the managed state back to the table via the `tableOptions.state.pagination` option.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#onpaginationchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
onPaginationChange?: OnChangeFn<PaginationState>;
/**
* When manually controlling pagination, you can supply a total `pageCount` value to the table if you know it (Or supply a `rowCount` and `pageCount` will be calculated). If you do not know how many pages there are, you can set this to `-1`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#pagecount)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
pageCount?: number;
/**
* When manually controlling pagination, you can supply a total `rowCount` value to the table if you know it. The `pageCount` can be calculated from this value and the `pageSize`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#rowcount)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
rowCount?: number;
}
export interface PaginationDefaultOptions {
onPaginationChange: OnChangeFn<PaginationState>;
}
export interface PaginationInstance<TData extends RowData> {
_autoResetPageIndex: () => void;
_getPaginationRowModel?: () => RowModel<TData>;
/**
* Returns whether the table can go to the next page.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#getcannextpage)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
getCanNextPage: () => boolean;
/**
* Returns whether the table can go to the previous page.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#getcanpreviouspage)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
getCanPreviousPage: () => boolean;
/**
* Returns the page count. If manually paginating or controlling the pagination state, this will come directly from the `options.pageCount` table option, otherwise it will be calculated from the table data using the total row count and current page size.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#getpagecount)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
getPageCount: () => number;
/**
* Returns the row count. If manually paginating or controlling the pagination state, this will come directly from the `options.rowCount` table option, otherwise it will be calculated from the table data.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#getrowcount)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
getRowCount: () => number;
/**
* Returns an array of page options (zero-index-based) for the current page size.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#getpageoptions)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
getPageOptions: () => number[];
/**
* Returns the row model for the table after pagination has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#getpaginationrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
getPaginationRowModel: () => RowModel<TData>;
/**
* Returns the row model for the table before any pagination has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#getprepaginationrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
getPrePaginationRowModel: () => RowModel<TData>;
/**
* Increments the page index by one, if possible.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#nextpage)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
nextPage: () => void;
/**
* Decrements the page index by one, if possible.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#previouspage)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
previousPage: () => void;
/**
* Sets the page index to `0`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#firstpage)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
firstPage: () => void;
/**
* Sets the page index to the last page.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#lastpage)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
lastPage: () => void;
/**
* Resets the page index to its initial state. If `defaultState` is `true`, the page index will be reset to `0` regardless of initial state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#resetpageindex)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
resetPageIndex: (defaultState?: boolean) => void;
/**
* Resets the page size to its initial state. If `defaultState` is `true`, the page size will be reset to `10` regardless of initial state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#resetpagesize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
resetPageSize: (defaultState?: boolean) => void;
/**
* Resets the **pagination** state to `initialState.pagination`, or `true` can be passed to force a default blank state reset to `[]`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#resetpagination)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
resetPagination: (defaultState?: boolean) => void;
/**
* @deprecated The page count no longer exists in the pagination state. Just pass as a table option instead.
*/
setPageCount: (updater: Updater<number>) => void;
/**
* Updates the page index using the provided function or value in the `state.pagination.pageIndex` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#setpageindex)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
setPageIndex: (updater: Updater<number>) => void;
/**
* Updates the page size using the provided function or value in the `state.pagination.pageSize` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#setpagesize)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
setPageSize: (updater: Updater<number>) => void;
/**
* Sets or updates the `state.pagination` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/pagination#setpagination)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/pagination)
*/
setPagination: (updater: Updater<PaginationState>) => void;
}
export declare const RowPagination: TableFeature;

View File

@@ -0,0 +1,169 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
//
const defaultPageIndex = 0;
const defaultPageSize = 10;
const getDefaultPaginationState = () => ({
pageIndex: defaultPageIndex,
pageSize: defaultPageSize
});
const RowPagination = {
getInitialState: state => {
return {
...state,
pagination: {
...getDefaultPaginationState(),
...(state == null ? void 0 : state.pagination)
}
};
},
getDefaultOptions: table => {
return {
onPaginationChange: utils.makeStateUpdater('pagination', table)
};
},
createTable: table => {
let registered = false;
let queued = false;
table._autoResetPageIndex = () => {
var _ref, _table$options$autoRe;
if (!registered) {
table._queue(() => {
registered = true;
});
return;
}
if ((_ref = (_table$options$autoRe = table.options.autoResetAll) != null ? _table$options$autoRe : table.options.autoResetPageIndex) != null ? _ref : !table.options.manualPagination) {
if (queued) return;
queued = true;
table._queue(() => {
table.resetPageIndex();
queued = false;
});
}
};
table.setPagination = updater => {
const safeUpdater = old => {
let newState = utils.functionalUpdate(updater, old);
return newState;
};
return table.options.onPaginationChange == null ? void 0 : table.options.onPaginationChange(safeUpdater);
};
table.resetPagination = defaultState => {
var _table$initialState$p;
table.setPagination(defaultState ? getDefaultPaginationState() : (_table$initialState$p = table.initialState.pagination) != null ? _table$initialState$p : getDefaultPaginationState());
};
table.setPageIndex = updater => {
table.setPagination(old => {
let pageIndex = utils.functionalUpdate(updater, old.pageIndex);
const maxPageIndex = typeof table.options.pageCount === 'undefined' || table.options.pageCount === -1 ? Number.MAX_SAFE_INTEGER : table.options.pageCount - 1;
pageIndex = Math.max(0, Math.min(pageIndex, maxPageIndex));
return {
...old,
pageIndex
};
});
};
table.resetPageIndex = defaultState => {
var _table$initialState$p2, _table$initialState;
table.setPageIndex(defaultState ? defaultPageIndex : (_table$initialState$p2 = (_table$initialState = table.initialState) == null || (_table$initialState = _table$initialState.pagination) == null ? void 0 : _table$initialState.pageIndex) != null ? _table$initialState$p2 : defaultPageIndex);
};
table.resetPageSize = defaultState => {
var _table$initialState$p3, _table$initialState2;
table.setPageSize(defaultState ? defaultPageSize : (_table$initialState$p3 = (_table$initialState2 = table.initialState) == null || (_table$initialState2 = _table$initialState2.pagination) == null ? void 0 : _table$initialState2.pageSize) != null ? _table$initialState$p3 : defaultPageSize);
};
table.setPageSize = updater => {
table.setPagination(old => {
const pageSize = Math.max(1, utils.functionalUpdate(updater, old.pageSize));
const topRowIndex = old.pageSize * old.pageIndex;
const pageIndex = Math.floor(topRowIndex / pageSize);
return {
...old,
pageIndex,
pageSize
};
});
};
//deprecated
table.setPageCount = updater => table.setPagination(old => {
var _table$options$pageCo;
let newPageCount = utils.functionalUpdate(updater, (_table$options$pageCo = table.options.pageCount) != null ? _table$options$pageCo : -1);
if (typeof newPageCount === 'number') {
newPageCount = Math.max(-1, newPageCount);
}
return {
...old,
pageCount: newPageCount
};
});
table.getPageOptions = utils.memo(() => [table.getPageCount()], pageCount => {
let pageOptions = [];
if (pageCount && pageCount > 0) {
pageOptions = [...new Array(pageCount)].fill(null).map((_, i) => i);
}
return pageOptions;
}, utils.getMemoOptions(table.options, 'debugTable', 'getPageOptions'));
table.getCanPreviousPage = () => table.getState().pagination.pageIndex > 0;
table.getCanNextPage = () => {
const {
pageIndex
} = table.getState().pagination;
const pageCount = table.getPageCount();
if (pageCount === -1) {
return true;
}
if (pageCount === 0) {
return false;
}
return pageIndex < pageCount - 1;
};
table.previousPage = () => {
return table.setPageIndex(old => old - 1);
};
table.nextPage = () => {
return table.setPageIndex(old => {
return old + 1;
});
};
table.firstPage = () => {
return table.setPageIndex(0);
};
table.lastPage = () => {
return table.setPageIndex(table.getPageCount() - 1);
};
table.getPrePaginationRowModel = () => table.getExpandedRowModel();
table.getPaginationRowModel = () => {
if (!table._getPaginationRowModel && table.options.getPaginationRowModel) {
table._getPaginationRowModel = table.options.getPaginationRowModel(table);
}
if (table.options.manualPagination || !table._getPaginationRowModel) {
return table.getPrePaginationRowModel();
}
return table._getPaginationRowModel();
};
table.getPageCount = () => {
var _table$options$pageCo2;
return (_table$options$pageCo2 = table.options.pageCount) != null ? _table$options$pageCo2 : Math.ceil(table.getRowCount() / table.getState().pagination.pageSize);
};
table.getRowCount = () => {
var _table$options$rowCou;
return (_table$options$rowCou = table.options.rowCount) != null ? _table$options$rowCou : table.getPrePaginationRowModel().rows.length;
};
}
};
exports.RowPagination = RowPagination;
//# sourceMappingURL=RowPagination.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,98 @@
import { OnChangeFn, Updater, Row, RowData, TableFeature } from '../types';
export type RowPinningPosition = false | 'top' | 'bottom';
export interface RowPinningState {
bottom?: string[];
top?: string[];
}
export interface RowPinningTableState {
rowPinning: RowPinningState;
}
export interface RowPinningOptions<TData extends RowData> {
/**
* Enables/disables row pinning for the table. Defaults to `true`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#enablerowpinning)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
enableRowPinning?: boolean | ((row: Row<TData>) => boolean);
/**
* When `false`, pinned rows will not be visible if they are filtered or paginated out of the table. When `true`, pinned rows will always be visible regardless of filtering or pagination. Defaults to `true`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#keeppinnedrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
keepPinnedRows?: boolean;
/**
* If provided, this function will be called with an `updaterFn` when `state.rowPinning` changes. This overrides the default internal state management, so you will also need to supply `state.rowPinning` from your own managed state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#onrowpinningchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/onrowpinningchange)
*/
onRowPinningChange?: OnChangeFn<RowPinningState>;
}
export interface RowPinningDefaultOptions {
onRowPinningChange: OnChangeFn<RowPinningState>;
}
export interface RowPinningRow {
/**
* Returns whether or not the row can be pinned.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#getcanpin-1)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
getCanPin: () => boolean;
/**
* Returns the pinned position of the row. (`'top'`, `'bottom'` or `false`)
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#getispinned-1)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
getIsPinned: () => RowPinningPosition;
/**
* Returns the numeric pinned index of the row within a pinned row group.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#getpinnedindex-1)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
getPinnedIndex: () => number;
/**
* Pins a row to the `'top'` or `'bottom'`, or unpins the row to the center if `false` is passed.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#pin-1)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
pin: (position: RowPinningPosition, includeLeafRows?: boolean, includeParentRows?: boolean) => void;
}
export interface RowPinningInstance<TData extends RowData> {
_getPinnedRows: (visiblePinnedRows: Array<Row<TData>>, pinnedRowIds: Array<string> | undefined, position: 'top' | 'bottom') => Row<TData>[];
/**
* Returns all bottom pinned rows.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#getbottomrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
getBottomRows: () => Row<TData>[];
/**
* Returns all rows that are not pinned to the top or bottom.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#getcenterrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
getCenterRows: () => Row<TData>[];
/**
* Returns whether or not any rows are pinned. Optionally specify to only check for pinned rows in either the `top` or `bottom` position.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#getissomerowspinned)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
getIsSomeRowsPinned: (position?: RowPinningPosition) => boolean;
/**
* Returns all top pinned rows.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#gettoprows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
getTopRows: () => Row<TData>[];
/**
* Resets the **rowPinning** state to `initialState.rowPinning`, or `true` can be passed to force a default blank state reset to `{ top: [], bottom: [], }`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#resetrowpinning)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
resetRowPinning: (defaultState?: boolean) => void;
/**
* Sets or updates the `state.rowPinning` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-pinning#setrowpinning)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-pinning)
*/
setRowPinning: (updater: Updater<RowPinningState>) => void;
}
export declare const RowPinning: TableFeature;

View File

@@ -0,0 +1,145 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
//
const getDefaultRowPinningState = () => ({
top: [],
bottom: []
});
const RowPinning = {
getInitialState: state => {
return {
rowPinning: getDefaultRowPinningState(),
...state
};
},
getDefaultOptions: table => {
return {
onRowPinningChange: utils.makeStateUpdater('rowPinning', table)
};
},
createRow: (row, table) => {
row.pin = (position, includeLeafRows, includeParentRows) => {
const leafRowIds = includeLeafRows ? row.getLeafRows().map(_ref => {
let {
id
} = _ref;
return id;
}) : [];
const parentRowIds = includeParentRows ? row.getParentRows().map(_ref2 => {
let {
id
} = _ref2;
return id;
}) : [];
const rowIds = new Set([...parentRowIds, row.id, ...leafRowIds]);
table.setRowPinning(old => {
var _old$top3, _old$bottom3;
if (position === 'bottom') {
var _old$top, _old$bottom;
return {
top: ((_old$top = old == null ? void 0 : old.top) != null ? _old$top : []).filter(d => !(rowIds != null && rowIds.has(d))),
bottom: [...((_old$bottom = old == null ? void 0 : old.bottom) != null ? _old$bottom : []).filter(d => !(rowIds != null && rowIds.has(d))), ...Array.from(rowIds)]
};
}
if (position === 'top') {
var _old$top2, _old$bottom2;
return {
top: [...((_old$top2 = old == null ? void 0 : old.top) != null ? _old$top2 : []).filter(d => !(rowIds != null && rowIds.has(d))), ...Array.from(rowIds)],
bottom: ((_old$bottom2 = old == null ? void 0 : old.bottom) != null ? _old$bottom2 : []).filter(d => !(rowIds != null && rowIds.has(d)))
};
}
return {
top: ((_old$top3 = old == null ? void 0 : old.top) != null ? _old$top3 : []).filter(d => !(rowIds != null && rowIds.has(d))),
bottom: ((_old$bottom3 = old == null ? void 0 : old.bottom) != null ? _old$bottom3 : []).filter(d => !(rowIds != null && rowIds.has(d)))
};
});
};
row.getCanPin = () => {
var _ref3;
const {
enableRowPinning,
enablePinning
} = table.options;
if (typeof enableRowPinning === 'function') {
return enableRowPinning(row);
}
return (_ref3 = enableRowPinning != null ? enableRowPinning : enablePinning) != null ? _ref3 : true;
};
row.getIsPinned = () => {
const rowIds = [row.id];
const {
top,
bottom
} = table.getState().rowPinning;
const isTop = rowIds.some(d => top == null ? void 0 : top.includes(d));
const isBottom = rowIds.some(d => bottom == null ? void 0 : bottom.includes(d));
return isTop ? 'top' : isBottom ? 'bottom' : false;
};
row.getPinnedIndex = () => {
var _ref4, _visiblePinnedRowIds$;
const position = row.getIsPinned();
if (!position) return -1;
const visiblePinnedRowIds = (_ref4 = position === 'top' ? table.getTopRows() : table.getBottomRows()) == null ? void 0 : _ref4.map(_ref5 => {
let {
id
} = _ref5;
return id;
});
return (_visiblePinnedRowIds$ = visiblePinnedRowIds == null ? void 0 : visiblePinnedRowIds.indexOf(row.id)) != null ? _visiblePinnedRowIds$ : -1;
};
},
createTable: table => {
table.setRowPinning = updater => table.options.onRowPinningChange == null ? void 0 : table.options.onRowPinningChange(updater);
table.resetRowPinning = defaultState => {
var _table$initialState$r, _table$initialState;
return table.setRowPinning(defaultState ? getDefaultRowPinningState() : (_table$initialState$r = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.rowPinning) != null ? _table$initialState$r : getDefaultRowPinningState());
};
table.getIsSomeRowsPinned = position => {
var _pinningState$positio;
const pinningState = table.getState().rowPinning;
if (!position) {
var _pinningState$top, _pinningState$bottom;
return Boolean(((_pinningState$top = pinningState.top) == null ? void 0 : _pinningState$top.length) || ((_pinningState$bottom = pinningState.bottom) == null ? void 0 : _pinningState$bottom.length));
}
return Boolean((_pinningState$positio = pinningState[position]) == null ? void 0 : _pinningState$positio.length);
};
table._getPinnedRows = (visibleRows, pinnedRowIds, position) => {
var _table$options$keepPi;
const rows = ((_table$options$keepPi = table.options.keepPinnedRows) != null ? _table$options$keepPi : true) ?
//get all rows that are pinned even if they would not be otherwise visible
//account for expanded parent rows, but not pagination or filtering
(pinnedRowIds != null ? pinnedRowIds : []).map(rowId => {
const row = table.getRow(rowId, true);
return row.getIsAllParentsExpanded() ? row : null;
}) :
//else get only visible rows that are pinned
(pinnedRowIds != null ? pinnedRowIds : []).map(rowId => visibleRows.find(row => row.id === rowId));
return rows.filter(Boolean).map(d => ({
...d,
position
}));
};
table.getTopRows = utils.memo(() => [table.getRowModel().rows, table.getState().rowPinning.top], (allRows, topPinnedRowIds) => table._getPinnedRows(allRows, topPinnedRowIds, 'top'), utils.getMemoOptions(table.options, 'debugRows', 'getTopRows'));
table.getBottomRows = utils.memo(() => [table.getRowModel().rows, table.getState().rowPinning.bottom], (allRows, bottomPinnedRowIds) => table._getPinnedRows(allRows, bottomPinnedRowIds, 'bottom'), utils.getMemoOptions(table.options, 'debugRows', 'getBottomRows'));
table.getCenterRows = utils.memo(() => [table.getRowModel().rows, table.getState().rowPinning.top, table.getState().rowPinning.bottom], (allRows, top, bottom) => {
const topAndBottom = new Set([...(top != null ? top : []), ...(bottom != null ? bottom : [])]);
return allRows.filter(d => !topAndBottom.has(d.id));
}, utils.getMemoOptions(table.options, 'debugRows', 'getCenterRows'));
}
};
exports.RowPinning = RowPinning;
//# sourceMappingURL=RowPinning.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,176 @@
import { OnChangeFn, Table, Row, RowModel, Updater, RowData, TableFeature } from '../types';
export type RowSelectionState = Record<string, boolean>;
export interface RowSelectionTableState {
rowSelection: RowSelectionState;
}
export interface RowSelectionOptions<TData extends RowData> {
/**
* - Enables/disables multiple row selection for all rows in the table OR
* - A function that given a row, returns whether to enable/disable multiple row selection for that row's children/grandchildren
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#enablemultirowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
enableMultiRowSelection?: boolean | ((row: Row<TData>) => boolean);
/**
* - Enables/disables row selection for all rows in the table OR
* - A function that given a row, returns whether to enable/disable row selection for that row
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#enablerowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
enableRowSelection?: boolean | ((row: Row<TData>) => boolean);
/**
* Enables/disables automatic sub-row selection when a parent row is selected, or a function that enables/disables automatic sub-row selection for each row.
* (Use in combination with expanding or grouping features)
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#enablesubrowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
enableSubRowSelection?: boolean | ((row: Row<TData>) => boolean);
/**
* If provided, this function will be called with an `updaterFn` when `state.rowSelection` changes. This overrides the default internal state management, so you will need to persist the state change either fully or partially outside of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#onrowselectionchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
onRowSelectionChange?: OnChangeFn<RowSelectionState>;
}
export interface RowSelectionRow {
/**
* Returns whether or not the row can multi-select.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getcanmultiselect)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getCanMultiSelect: () => boolean;
/**
* Returns whether or not the row can be selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getcanselect)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getCanSelect: () => boolean;
/**
* Returns whether or not the row can select sub rows automatically when the parent row is selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getcanselectsubrows)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getCanSelectSubRows: () => boolean;
/**
* Returns whether or not all of the row's sub rows are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getisallsubrowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsAllSubRowsSelected: () => boolean;
/**
* Returns whether or not the row is selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getisselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsSelected: () => boolean;
/**
* Returns whether or not some of the row's sub rows are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getissomeselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsSomeSelected: () => boolean;
/**
* Returns a handler that can be used to toggle the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#gettoggleselectedhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getToggleSelectedHandler: () => (event: unknown) => void;
/**
* Selects/deselects the row.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#toggleselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
toggleSelected: (value?: boolean, opts?: {
selectChildren?: boolean;
}) => void;
}
export interface RowSelectionInstance<TData extends RowData> {
/**
* Returns the row model of all rows that are selected after filtering has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getfilteredselectedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getFilteredSelectedRowModel: () => RowModel<TData>;
/**
* Returns the row model of all rows that are selected after grouping has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getgroupedselectedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getGroupedSelectedRowModel: () => RowModel<TData>;
/**
* Returns whether or not all rows on the current page are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getisallpagerowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsAllPageRowsSelected: () => boolean;
/**
* Returns whether or not all rows in the table are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getisallrowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsAllRowsSelected: () => boolean;
/**
* Returns whether or not any rows on the current page are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getissomepagerowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsSomePageRowsSelected: () => boolean;
/**
* Returns whether or not any rows in the table are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getissomerowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getIsSomeRowsSelected: () => boolean;
/**
* Returns the core row model of all rows before row selection has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getpreselectedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getPreSelectedRowModel: () => RowModel<TData>;
/**
* Returns the row model of all rows that are selected.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#getselectedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getSelectedRowModel: () => RowModel<TData>;
/**
* Returns a handler that can be used to toggle all rows on the current page.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#gettoggleallpagerowsselectedhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getToggleAllPageRowsSelectedHandler: () => (event: unknown) => void;
/**
* Returns a handler that can be used to toggle all rows in the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#gettoggleallrowsselectedhandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
getToggleAllRowsSelectedHandler: () => (event: unknown) => void;
/**
* Resets the **rowSelection** state to the `initialState.rowSelection`, or `true` can be passed to force a default blank state reset to `{}`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#resetrowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
resetRowSelection: (defaultState?: boolean) => void;
/**
* Sets or updates the `state.rowSelection` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#setrowselection)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
setRowSelection: (updater: Updater<RowSelectionState>) => void;
/**
* Selects/deselects all rows on the current page.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#toggleallpagerowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
toggleAllPageRowsSelected: (value?: boolean) => void;
/**
* Selects/deselects all rows in the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/row-selection#toggleallrowsselected)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/row-selection)
*/
toggleAllRowsSelected: (value?: boolean) => void;
}
export declare const RowSelection: TableFeature;
export declare function selectRowsFn<TData extends RowData>(table: Table<TData>, rowModel: RowModel<TData>): RowModel<TData>;
export declare function isRowSelected<TData extends RowData>(row: Row<TData>, selection: Record<string, boolean>): boolean;
export declare function isSubRowSelected<TData extends RowData>(row: Row<TData>, selection: Record<string, boolean>, table: Table<TData>): boolean | 'some' | 'all';

View File

@@ -0,0 +1,391 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var utils = require('../utils.js');
//
const RowSelection = {
getInitialState: state => {
return {
rowSelection: {},
...state
};
},
getDefaultOptions: table => {
return {
onRowSelectionChange: utils.makeStateUpdater('rowSelection', table),
enableRowSelection: true,
enableMultiRowSelection: true,
enableSubRowSelection: true
// enableGroupingRowSelection: false,
// isAdditiveSelectEvent: (e: unknown) => !!e.metaKey,
// isInclusiveSelectEvent: (e: unknown) => !!e.shiftKey,
};
},
createTable: table => {
table.setRowSelection = updater => table.options.onRowSelectionChange == null ? void 0 : table.options.onRowSelectionChange(updater);
table.resetRowSelection = defaultState => {
var _table$initialState$r;
return table.setRowSelection(defaultState ? {} : (_table$initialState$r = table.initialState.rowSelection) != null ? _table$initialState$r : {});
};
table.toggleAllRowsSelected = value => {
table.setRowSelection(old => {
value = typeof value !== 'undefined' ? value : !table.getIsAllRowsSelected();
const rowSelection = {
...old
};
const preGroupedFlatRows = table.getPreGroupedRowModel().flatRows;
// We don't use `mutateRowIsSelected` here for performance reasons.
// All of the rows are flat already, so it wouldn't be worth it
if (value) {
preGroupedFlatRows.forEach(row => {
if (!row.getCanSelect()) {
return;
}
rowSelection[row.id] = true;
});
} else {
preGroupedFlatRows.forEach(row => {
delete rowSelection[row.id];
});
}
return rowSelection;
});
};
table.toggleAllPageRowsSelected = value => table.setRowSelection(old => {
const resolvedValue = typeof value !== 'undefined' ? value : !table.getIsAllPageRowsSelected();
const rowSelection = {
...old
};
table.getRowModel().rows.forEach(row => {
mutateRowIsSelected(rowSelection, row.id, resolvedValue, true, table);
});
return rowSelection;
});
// addRowSelectionRange: rowId => {
// const {
// rows,
// rowsById,
// options: { selectGroupingRows, selectSubRows },
// } = table
// const findSelectedRow = (rows: Row[]) => {
// let found
// rows.find(d => {
// if (d.getIsSelected()) {
// found = d
// return true
// }
// const subFound = findSelectedRow(d.subRows || [])
// if (subFound) {
// found = subFound
// return true
// }
// return false
// })
// return found
// }
// const firstRow = findSelectedRow(rows) || rows[0]
// const lastRow = rowsById[rowId]
// let include = false
// const selectedRowIds = {}
// const addRow = (row: Row) => {
// mutateRowIsSelected(selectedRowIds, row.id, true, {
// rowsById,
// selectGroupingRows: selectGroupingRows!,
// selectSubRows: selectSubRows!,
// })
// }
// table.rows.forEach(row => {
// const isFirstRow = row.id === firstRow.id
// const isLastRow = row.id === lastRow.id
// if (isFirstRow || isLastRow) {
// if (!include) {
// include = true
// } else if (include) {
// addRow(row)
// include = false
// }
// }
// if (include) {
// addRow(row)
// }
// })
// table.setRowSelection(selectedRowIds)
// },
table.getPreSelectedRowModel = () => table.getCoreRowModel();
table.getSelectedRowModel = utils.memo(() => [table.getState().rowSelection, table.getCoreRowModel()], (rowSelection, rowModel) => {
if (!Object.keys(rowSelection).length) {
return {
rows: [],
flatRows: [],
rowsById: {}
};
}
return selectRowsFn(table, rowModel);
}, utils.getMemoOptions(table.options, 'debugTable', 'getSelectedRowModel'));
table.getFilteredSelectedRowModel = utils.memo(() => [table.getState().rowSelection, table.getFilteredRowModel()], (rowSelection, rowModel) => {
if (!Object.keys(rowSelection).length) {
return {
rows: [],
flatRows: [],
rowsById: {}
};
}
return selectRowsFn(table, rowModel);
}, utils.getMemoOptions(table.options, 'debugTable', 'getFilteredSelectedRowModel'));
table.getGroupedSelectedRowModel = utils.memo(() => [table.getState().rowSelection, table.getSortedRowModel()], (rowSelection, rowModel) => {
if (!Object.keys(rowSelection).length) {
return {
rows: [],
flatRows: [],
rowsById: {}
};
}
return selectRowsFn(table, rowModel);
}, utils.getMemoOptions(table.options, 'debugTable', 'getGroupedSelectedRowModel'));
///
// getGroupingRowCanSelect: rowId => {
// const row = table.getRow(rowId)
// if (!row) {
// throw new Error()
// }
// if (typeof table.options.enableGroupingRowSelection === 'function') {
// return table.options.enableGroupingRowSelection(row)
// }
// return table.options.enableGroupingRowSelection ?? false
// },
table.getIsAllRowsSelected = () => {
const preGroupedFlatRows = table.getFilteredRowModel().flatRows;
const {
rowSelection
} = table.getState();
let isAllRowsSelected = Boolean(preGroupedFlatRows.length && Object.keys(rowSelection).length);
if (isAllRowsSelected) {
if (preGroupedFlatRows.some(row => row.getCanSelect() && !rowSelection[row.id])) {
isAllRowsSelected = false;
}
}
return isAllRowsSelected;
};
table.getIsAllPageRowsSelected = () => {
const paginationFlatRows = table.getPaginationRowModel().flatRows.filter(row => row.getCanSelect());
const {
rowSelection
} = table.getState();
let isAllPageRowsSelected = !!paginationFlatRows.length;
if (isAllPageRowsSelected && paginationFlatRows.some(row => !rowSelection[row.id])) {
isAllPageRowsSelected = false;
}
return isAllPageRowsSelected;
};
table.getIsSomeRowsSelected = () => {
var _table$getState$rowSe;
const totalSelected = Object.keys((_table$getState$rowSe = table.getState().rowSelection) != null ? _table$getState$rowSe : {}).length;
return totalSelected > 0 && totalSelected < table.getFilteredRowModel().flatRows.length;
};
table.getIsSomePageRowsSelected = () => {
const paginationFlatRows = table.getPaginationRowModel().flatRows;
return table.getIsAllPageRowsSelected() ? false : paginationFlatRows.filter(row => row.getCanSelect()).some(d => d.getIsSelected() || d.getIsSomeSelected());
};
table.getToggleAllRowsSelectedHandler = () => {
return e => {
table.toggleAllRowsSelected(e.target.checked);
};
};
table.getToggleAllPageRowsSelectedHandler = () => {
return e => {
table.toggleAllPageRowsSelected(e.target.checked);
};
};
},
createRow: (row, table) => {
row.toggleSelected = (value, opts) => {
const isSelected = row.getIsSelected();
table.setRowSelection(old => {
var _opts$selectChildren;
value = typeof value !== 'undefined' ? value : !isSelected;
if (row.getCanSelect() && isSelected === value) {
return old;
}
const selectedRowIds = {
...old
};
mutateRowIsSelected(selectedRowIds, row.id, value, (_opts$selectChildren = opts == null ? void 0 : opts.selectChildren) != null ? _opts$selectChildren : true, table);
return selectedRowIds;
});
};
row.getIsSelected = () => {
const {
rowSelection
} = table.getState();
return isRowSelected(row, rowSelection);
};
row.getIsSomeSelected = () => {
const {
rowSelection
} = table.getState();
return isSubRowSelected(row, rowSelection) === 'some';
};
row.getIsAllSubRowsSelected = () => {
const {
rowSelection
} = table.getState();
return isSubRowSelected(row, rowSelection) === 'all';
};
row.getCanSelect = () => {
var _table$options$enable;
if (typeof table.options.enableRowSelection === 'function') {
return table.options.enableRowSelection(row);
}
return (_table$options$enable = table.options.enableRowSelection) != null ? _table$options$enable : true;
};
row.getCanSelectSubRows = () => {
var _table$options$enable2;
if (typeof table.options.enableSubRowSelection === 'function') {
return table.options.enableSubRowSelection(row);
}
return (_table$options$enable2 = table.options.enableSubRowSelection) != null ? _table$options$enable2 : true;
};
row.getCanMultiSelect = () => {
var _table$options$enable3;
if (typeof table.options.enableMultiRowSelection === 'function') {
return table.options.enableMultiRowSelection(row);
}
return (_table$options$enable3 = table.options.enableMultiRowSelection) != null ? _table$options$enable3 : true;
};
row.getToggleSelectedHandler = () => {
const canSelect = row.getCanSelect();
return e => {
var _target;
if (!canSelect) return;
row.toggleSelected((_target = e.target) == null ? void 0 : _target.checked);
};
};
}
};
const mutateRowIsSelected = (selectedRowIds, id, value, includeChildren, table) => {
var _row$subRows;
const row = table.getRow(id, true);
// const isGrouped = row.getIsGrouped()
// if ( // TODO: enforce grouping row selection rules
// !isGrouped ||
// (isGrouped && table.options.enableGroupingRowSelection)
// ) {
if (value) {
if (!row.getCanMultiSelect()) {
Object.keys(selectedRowIds).forEach(key => delete selectedRowIds[key]);
}
if (row.getCanSelect()) {
selectedRowIds[id] = true;
}
} else {
delete selectedRowIds[id];
}
// }
if (includeChildren && (_row$subRows = row.subRows) != null && _row$subRows.length && row.getCanSelectSubRows()) {
row.subRows.forEach(row => mutateRowIsSelected(selectedRowIds, row.id, value, includeChildren, table));
}
};
function selectRowsFn(table, rowModel) {
const rowSelection = table.getState().rowSelection;
const newSelectedFlatRows = [];
const newSelectedRowsById = {};
// Filters top level and nested rows
const recurseRows = function (rows, depth) {
return rows.map(row => {
var _row$subRows2;
const isSelected = isRowSelected(row, rowSelection);
if (isSelected) {
newSelectedFlatRows.push(row);
newSelectedRowsById[row.id] = row;
}
if ((_row$subRows2 = row.subRows) != null && _row$subRows2.length) {
row = {
...row,
subRows: recurseRows(row.subRows)
};
}
if (isSelected) {
return row;
}
}).filter(Boolean);
};
return {
rows: recurseRows(rowModel.rows),
flatRows: newSelectedFlatRows,
rowsById: newSelectedRowsById
};
}
function isRowSelected(row, selection) {
var _selection$row$id;
return (_selection$row$id = selection[row.id]) != null ? _selection$row$id : false;
}
function isSubRowSelected(row, selection, table) {
var _row$subRows3;
if (!((_row$subRows3 = row.subRows) != null && _row$subRows3.length)) return false;
let allChildrenSelected = true;
let someSelected = false;
row.subRows.forEach(subRow => {
// Bail out early if we know both of these
if (someSelected && !allChildrenSelected) {
return;
}
if (subRow.getCanSelect()) {
if (isRowSelected(subRow, selection)) {
someSelected = true;
} else {
allChildrenSelected = false;
}
}
// Check row selection of nested subrows
if (subRow.subRows && subRow.subRows.length) {
const subRowChildrenSelected = isSubRowSelected(subRow, selection);
if (subRowChildrenSelected === 'all') {
someSelected = true;
} else if (subRowChildrenSelected === 'some') {
someSelected = true;
allChildrenSelected = false;
} else {
allChildrenSelected = false;
}
}
});
return allChildrenSelected ? 'all' : someSelected ? 'some' : false;
}
exports.RowSelection = RowSelection;
exports.isRowSelected = isRowSelected;
exports.isSubRowSelected = isSubRowSelected;
exports.selectRowsFn = selectRowsFn;
//# sourceMappingURL=RowSelection.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,237 @@
import { RowModel } from '..';
import { BuiltInSortingFn } from '../sortingFns';
import { OnChangeFn, Table, Row, Updater, RowData, SortingFns, TableFeature } from '../types';
export type SortDirection = 'asc' | 'desc';
export interface ColumnSort {
desc: boolean;
id: string;
}
export type SortingState = ColumnSort[];
export interface SortingTableState {
sorting: SortingState;
}
export interface SortingFn<TData extends RowData> {
(rowA: Row<TData>, rowB: Row<TData>, columnId: string): number;
}
export type CustomSortingFns<TData extends RowData> = Record<string, SortingFn<TData>>;
export type SortingFnOption<TData extends RowData> = 'auto' | keyof SortingFns | BuiltInSortingFn | SortingFn<TData>;
export interface SortingColumnDef<TData extends RowData> {
/**
* Enables/Disables multi-sorting for this column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#enablemultisort)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
enableMultiSort?: boolean;
/**
* Enables/Disables sorting for this column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#enablesorting)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
enableSorting?: boolean;
/**
* Inverts the order of the sorting for this column. This is useful for values that have an inverted best/worst scale where lower numbers are better, eg. a ranking (1st, 2nd, 3rd) or golf-like scoring
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#invertsorting)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
invertSorting?: boolean;
/**
* Set to `true` for sorting toggles on this column to start in the descending direction.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#sortdescfirst)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
sortDescFirst?: boolean;
/**
* The sorting function to use with this column.
* - A `string` referencing a built-in sorting function
* - A custom sorting function
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#sortingfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
sortingFn?: SortingFnOption<TData>;
/**
* The priority of undefined values when sorting this column.
* - `false`
* - Undefined values will be considered tied and need to be sorted by the next column filter or original index (whichever applies)
* - `-1`
* - Undefined values will be sorted with higher priority (ascending) (if ascending, undefined will appear on the beginning of the list)
* - `1`
* - Undefined values will be sorted with lower priority (descending) (if ascending, undefined will appear on the end of the list)
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#sortundefined)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
sortUndefined?: false | -1 | 1 | 'first' | 'last';
}
export interface SortingColumn<TData extends RowData> {
/**
* Removes this column from the table's sorting state
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#clearsorting)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
clearSorting: () => void;
/**
* Returns a sort direction automatically inferred based on the columns values.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getautosortdir)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getAutoSortDir: () => SortDirection;
/**
* Returns a sorting function automatically inferred based on the columns values.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getautosortingfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getAutoSortingFn: () => SortingFn<TData>;
/**
* Returns whether this column can be multi-sorted.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getcanmultisort)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getCanMultiSort: () => boolean;
/**
* Returns whether this column can be sorted.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getcansort)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getCanSort: () => boolean;
/**
* Returns the first direction that should be used when sorting this column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getfirstsortdir)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getFirstSortDir: () => SortDirection;
/**
* Returns the current sort direction of this column.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getissorted)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getIsSorted: () => false | SortDirection;
/**
* Returns the next sorting order.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getnextsortingorder)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getNextSortingOrder: () => SortDirection | false;
/**
* Returns the index position of this column's sorting within the sorting state
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getsortindex)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getSortIndex: () => number;
/**
* Returns the resolved sorting function to be used for this column
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getsortingfn)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getSortingFn: () => SortingFn<TData>;
/**
* Returns a function that can be used to toggle this column's sorting state. This is useful for attaching a click handler to the column header.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#gettogglesortinghandler)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getToggleSortingHandler: () => undefined | ((event: unknown) => void);
/**
* Toggles this columns sorting state. If `desc` is provided, it will force the sort direction to that value. If `isMulti` is provided, it will additivity multi-sort the column (or toggle it if it is already sorted).
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#togglesorting)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
toggleSorting: (desc?: boolean, isMulti?: boolean) => void;
}
interface SortingOptionsBase {
/**
* Enables/disables the ability to remove multi-sorts
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#enablemultiremove)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
enableMultiRemove?: boolean;
/**
* Enables/Disables multi-sorting for the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#enablemultisort)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
enableMultiSort?: boolean;
/**
* Enables/Disables sorting for the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#enablesorting)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
enableSorting?: boolean;
/**
* Enables/Disables the ability to remove sorting for the table.
* - If `true` then changing sort order will circle like: 'none' -> 'desc' -> 'asc' -> 'none' -> ...
* - If `false` then changing sort order will circle like: 'none' -> 'desc' -> 'asc' -> 'desc' -> 'asc' -> ...
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#enablesortingremoval)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
enableSortingRemoval?: boolean;
/**
* This function is used to retrieve the sorted row model. If using server-side sorting, this function is not required. To use client-side sorting, pass the exported `getSortedRowModel()` from your adapter to your table or implement your own.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getsortedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getSortedRowModel?: (table: Table<any>) => () => RowModel<any>;
/**
* Pass a custom function that will be used to determine if a multi-sort event should be triggered. It is passed the event from the sort toggle handler and should return `true` if the event should trigger a multi-sort.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#ismultisortevent)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
isMultiSortEvent?: (e: unknown) => boolean;
/**
* Enables manual sorting for the table. If this is `true`, you will be expected to sort your data before it is passed to the table. This is useful if you are doing server-side sorting.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#manualsorting)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
manualSorting?: boolean;
/**
* Set a maximum number of columns that can be multi-sorted.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#maxmultisortcolcount)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
maxMultiSortColCount?: number;
/**
* If provided, this function will be called with an `updaterFn` when `state.sorting` changes. This overrides the default internal state management, so you will need to persist the state change either fully or partially outside of the table.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#onsortingchange)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
onSortingChange?: OnChangeFn<SortingState>;
/**
* If `true`, all sorts will default to descending as their first toggle state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#sortdescfirst)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
sortDescFirst?: boolean;
}
type ResolvedSortingFns = keyof SortingFns extends never ? {
sortingFns?: Record<string, SortingFn<any>>;
} : {
sortingFns: Record<keyof SortingFns, SortingFn<any>>;
};
export interface SortingOptions<TData extends RowData> extends SortingOptionsBase, ResolvedSortingFns {
}
export interface SortingInstance<TData extends RowData> {
_getSortedRowModel?: () => RowModel<TData>;
/**
* Returns the row model for the table before any sorting has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getpresortedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getPreSortedRowModel: () => RowModel<TData>;
/**
* Returns the row model for the table after sorting has been applied.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#getsortedrowmodel)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
getSortedRowModel: () => RowModel<TData>;
/**
* Resets the **sorting** state to `initialState.sorting`, or `true` can be passed to force a default blank state reset to `[]`.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#resetsorting)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
resetSorting: (defaultState?: boolean) => void;
/**
* Sets or updates the `state.sorting` state.
* @link [API Docs](https://tanstack.com/table/v8/docs/api/features/sorting#setsorting)
* @link [Guide](https://tanstack.com/table/v8/docs/guide/sorting)
*/
setSorting: (updater: Updater<SortingState>) => void;
}
export declare const RowSorting: TableFeature;
export {};

View File

@@ -0,0 +1,226 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var sortingFns = require('../sortingFns.js');
var utils = require('../utils.js');
//
const RowSorting = {
getInitialState: state => {
return {
sorting: [],
...state
};
},
getDefaultColumnDef: () => {
return {
sortingFn: 'auto',
sortUndefined: 1
};
},
getDefaultOptions: table => {
return {
onSortingChange: utils.makeStateUpdater('sorting', table),
isMultiSortEvent: e => {
return e.shiftKey;
}
};
},
createColumn: (column, table) => {
column.getAutoSortingFn = () => {
const firstRows = table.getFilteredRowModel().flatRows.slice(10);
let isString = false;
for (const row of firstRows) {
const value = row == null ? void 0 : row.getValue(column.id);
if (Object.prototype.toString.call(value) === '[object Date]') {
return sortingFns.sortingFns.datetime;
}
if (typeof value === 'string') {
isString = true;
if (value.split(sortingFns.reSplitAlphaNumeric).length > 1) {
return sortingFns.sortingFns.alphanumeric;
}
}
}
if (isString) {
return sortingFns.sortingFns.text;
}
return sortingFns.sortingFns.basic;
};
column.getAutoSortDir = () => {
const firstRow = table.getFilteredRowModel().flatRows[0];
const value = firstRow == null ? void 0 : firstRow.getValue(column.id);
if (typeof value === 'string') {
return 'asc';
}
return 'desc';
};
column.getSortingFn = () => {
var _table$options$sortin, _table$options$sortin2;
if (!column) {
throw new Error();
}
return utils.isFunction(column.columnDef.sortingFn) ? column.columnDef.sortingFn : column.columnDef.sortingFn === 'auto' ? column.getAutoSortingFn() : (_table$options$sortin = (_table$options$sortin2 = table.options.sortingFns) == null ? void 0 : _table$options$sortin2[column.columnDef.sortingFn]) != null ? _table$options$sortin : sortingFns.sortingFns[column.columnDef.sortingFn];
};
column.toggleSorting = (desc, multi) => {
// if (column.columns.length) {
// column.columns.forEach((c, i) => {
// if (c.id) {
// table.toggleColumnSorting(c.id, undefined, multi || !!i)
// }
// })
// return
// }
// this needs to be outside of table.setSorting to be in sync with rerender
const nextSortingOrder = column.getNextSortingOrder();
const hasManualValue = typeof desc !== 'undefined' && desc !== null;
table.setSorting(old => {
// Find any existing sorting for this column
const existingSorting = old == null ? void 0 : old.find(d => d.id === column.id);
const existingIndex = old == null ? void 0 : old.findIndex(d => d.id === column.id);
let newSorting = [];
// What should we do with this sort action?
let sortAction;
let nextDesc = hasManualValue ? desc : nextSortingOrder === 'desc';
// Multi-mode
if (old != null && old.length && column.getCanMultiSort() && multi) {
if (existingSorting) {
sortAction = 'toggle';
} else {
sortAction = 'add';
}
} else {
// Normal mode
if (old != null && old.length && existingIndex !== old.length - 1) {
sortAction = 'replace';
} else if (existingSorting) {
sortAction = 'toggle';
} else {
sortAction = 'replace';
}
}
// Handle toggle states that will remove the sorting
if (sortAction === 'toggle') {
// If we are "actually" toggling (not a manual set value), should we remove the sorting?
if (!hasManualValue) {
// Is our intention to remove?
if (!nextSortingOrder) {
sortAction = 'remove';
}
}
}
if (sortAction === 'add') {
var _table$options$maxMul;
newSorting = [...old, {
id: column.id,
desc: nextDesc
}];
// Take latest n columns
newSorting.splice(0, newSorting.length - ((_table$options$maxMul = table.options.maxMultiSortColCount) != null ? _table$options$maxMul : Number.MAX_SAFE_INTEGER));
} else if (sortAction === 'toggle') {
// This flips (or sets) the
newSorting = old.map(d => {
if (d.id === column.id) {
return {
...d,
desc: nextDesc
};
}
return d;
});
} else if (sortAction === 'remove') {
newSorting = old.filter(d => d.id !== column.id);
} else {
newSorting = [{
id: column.id,
desc: nextDesc
}];
}
return newSorting;
});
};
column.getFirstSortDir = () => {
var _ref, _column$columnDef$sor;
const sortDescFirst = (_ref = (_column$columnDef$sor = column.columnDef.sortDescFirst) != null ? _column$columnDef$sor : table.options.sortDescFirst) != null ? _ref : column.getAutoSortDir() === 'desc';
return sortDescFirst ? 'desc' : 'asc';
};
column.getNextSortingOrder = multi => {
var _table$options$enable, _table$options$enable2;
const firstSortDirection = column.getFirstSortDir();
const isSorted = column.getIsSorted();
if (!isSorted) {
return firstSortDirection;
}
if (isSorted !== firstSortDirection && ((_table$options$enable = table.options.enableSortingRemoval) != null ? _table$options$enable : true) && (
// If enableSortRemove, enable in general
multi ? (_table$options$enable2 = table.options.enableMultiRemove) != null ? _table$options$enable2 : true : true) // If multi, don't allow if enableMultiRemove))
) {
return false;
}
return isSorted === 'desc' ? 'asc' : 'desc';
};
column.getCanSort = () => {
var _column$columnDef$ena, _table$options$enable3;
return ((_column$columnDef$ena = column.columnDef.enableSorting) != null ? _column$columnDef$ena : true) && ((_table$options$enable3 = table.options.enableSorting) != null ? _table$options$enable3 : true) && !!column.accessorFn;
};
column.getCanMultiSort = () => {
var _ref2, _column$columnDef$ena2;
return (_ref2 = (_column$columnDef$ena2 = column.columnDef.enableMultiSort) != null ? _column$columnDef$ena2 : table.options.enableMultiSort) != null ? _ref2 : !!column.accessorFn;
};
column.getIsSorted = () => {
var _table$getState$sorti;
const columnSort = (_table$getState$sorti = table.getState().sorting) == null ? void 0 : _table$getState$sorti.find(d => d.id === column.id);
return !columnSort ? false : columnSort.desc ? 'desc' : 'asc';
};
column.getSortIndex = () => {
var _table$getState$sorti2, _table$getState$sorti3;
return (_table$getState$sorti2 = (_table$getState$sorti3 = table.getState().sorting) == null ? void 0 : _table$getState$sorti3.findIndex(d => d.id === column.id)) != null ? _table$getState$sorti2 : -1;
};
column.clearSorting = () => {
//clear sorting for just 1 column
table.setSorting(old => old != null && old.length ? old.filter(d => d.id !== column.id) : []);
};
column.getToggleSortingHandler = () => {
const canSort = column.getCanSort();
return e => {
if (!canSort) return;
e.persist == null || e.persist();
column.toggleSorting == null || column.toggleSorting(undefined, column.getCanMultiSort() ? table.options.isMultiSortEvent == null ? void 0 : table.options.isMultiSortEvent(e) : false);
};
};
},
createTable: table => {
table.setSorting = updater => table.options.onSortingChange == null ? void 0 : table.options.onSortingChange(updater);
table.resetSorting = defaultState => {
var _table$initialState$s, _table$initialState;
table.setSorting(defaultState ? [] : (_table$initialState$s = (_table$initialState = table.initialState) == null ? void 0 : _table$initialState.sorting) != null ? _table$initialState$s : []);
};
table.getPreSortedRowModel = () => table.getGroupedRowModel();
table.getSortedRowModel = () => {
if (!table._getSortedRowModel && table.options.getSortedRowModel) {
table._getSortedRowModel = table.options.getSortedRowModel(table);
}
if (table.options.manualSorting || !table._getSortedRowModel) {
return table.getPreSortedRowModel();
}
return table._getSortedRowModel();
};
}
};
exports.RowSorting = RowSorting;
//# sourceMappingURL=RowSorting.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
import { FilterFn } from './features/ColumnFiltering';
export declare const filterFns: {
includesString: FilterFn<any>;
includesStringSensitive: FilterFn<any>;
equalsString: FilterFn<any>;
arrIncludes: FilterFn<any>;
arrIncludesAll: FilterFn<any>;
arrIncludesSome: FilterFn<any>;
equals: FilterFn<any>;
weakEquals: FilterFn<any>;
inNumberRange: FilterFn<any>;
};
export type BuiltInFilterFn = keyof typeof filterFns;

View File

@@ -0,0 +1,96 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
const includesString = (row, columnId, filterValue) => {
var _filterValue$toString, _row$getValue;
const search = filterValue == null || (_filterValue$toString = filterValue.toString()) == null ? void 0 : _filterValue$toString.toLowerCase();
return Boolean((_row$getValue = row.getValue(columnId)) == null || (_row$getValue = _row$getValue.toString()) == null || (_row$getValue = _row$getValue.toLowerCase()) == null ? void 0 : _row$getValue.includes(search));
};
includesString.autoRemove = val => testFalsey(val);
const includesStringSensitive = (row, columnId, filterValue) => {
var _row$getValue2;
return Boolean((_row$getValue2 = row.getValue(columnId)) == null || (_row$getValue2 = _row$getValue2.toString()) == null ? void 0 : _row$getValue2.includes(filterValue));
};
includesStringSensitive.autoRemove = val => testFalsey(val);
const equalsString = (row, columnId, filterValue) => {
var _row$getValue3;
return ((_row$getValue3 = row.getValue(columnId)) == null || (_row$getValue3 = _row$getValue3.toString()) == null ? void 0 : _row$getValue3.toLowerCase()) === (filterValue == null ? void 0 : filterValue.toLowerCase());
};
equalsString.autoRemove = val => testFalsey(val);
const arrIncludes = (row, columnId, filterValue) => {
var _row$getValue4;
return (_row$getValue4 = row.getValue(columnId)) == null ? void 0 : _row$getValue4.includes(filterValue);
};
arrIncludes.autoRemove = val => testFalsey(val);
const arrIncludesAll = (row, columnId, filterValue) => {
return !filterValue.some(val => {
var _row$getValue5;
return !((_row$getValue5 = row.getValue(columnId)) != null && _row$getValue5.includes(val));
});
};
arrIncludesAll.autoRemove = val => testFalsey(val) || !(val != null && val.length);
const arrIncludesSome = (row, columnId, filterValue) => {
return filterValue.some(val => {
var _row$getValue6;
return (_row$getValue6 = row.getValue(columnId)) == null ? void 0 : _row$getValue6.includes(val);
});
};
arrIncludesSome.autoRemove = val => testFalsey(val) || !(val != null && val.length);
const equals = (row, columnId, filterValue) => {
return row.getValue(columnId) === filterValue;
};
equals.autoRemove = val => testFalsey(val);
const weakEquals = (row, columnId, filterValue) => {
return row.getValue(columnId) == filterValue;
};
weakEquals.autoRemove = val => testFalsey(val);
const inNumberRange = (row, columnId, filterValue) => {
let [min, max] = filterValue;
const rowValue = row.getValue(columnId);
return rowValue >= min && rowValue <= max;
};
inNumberRange.resolveFilterValue = val => {
let [unsafeMin, unsafeMax] = val;
let parsedMin = typeof unsafeMin !== 'number' ? parseFloat(unsafeMin) : unsafeMin;
let parsedMax = typeof unsafeMax !== 'number' ? parseFloat(unsafeMax) : unsafeMax;
let min = unsafeMin === null || Number.isNaN(parsedMin) ? -Infinity : parsedMin;
let max = unsafeMax === null || Number.isNaN(parsedMax) ? Infinity : parsedMax;
if (min > max) {
const temp = min;
min = max;
max = temp;
}
return [min, max];
};
inNumberRange.autoRemove = val => testFalsey(val) || testFalsey(val[0]) && testFalsey(val[1]);
// Export
const filterFns = {
includesString,
includesStringSensitive,
equalsString,
arrIncludes,
arrIncludesAll,
arrIncludesSome,
equals,
weakEquals,
inNumberRange
};
// Utils
function testFalsey(val) {
return val === undefined || val === null || val === '';
}
exports.filterFns = filterFns;
//# sourceMappingURL=filterFns.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,34 @@
export * from './columnHelper';
export * from './types';
export * from './core/cell';
export * from './core/column';
export * from './core/headers';
export * from './core/row';
export * from './core/table';
export * from './features/ColumnFaceting';
export * from './features/ColumnFiltering';
export * from './features/ColumnGrouping';
export * from './features/ColumnOrdering';
export * from './features/ColumnPinning';
export * from './features/ColumnSizing';
export * from './features/ColumnVisibility';
export * from './features/GlobalFaceting';
export * from './features/GlobalFiltering';
export * from './features/RowExpanding';
export * from './features/RowPagination';
export * from './features/RowPinning';
export * from './features/RowSelection';
export * from './features/RowSorting';
export * from './utils';
export * from './utils/getCoreRowModel';
export * from './utils/getExpandedRowModel';
export * from './utils/getFacetedMinMaxValues';
export * from './utils/getFacetedRowModel';
export * from './utils/getFacetedUniqueValues';
export * from './utils/getFilteredRowModel';
export * from './utils/getGroupedRowModel';
export * from './utils/getPaginationRowModel';
export * from './utils/getSortedRowModel';
export * from './aggregationFns';
export * from './filterFns';
export * from './sortingFns';

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,100 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var columnHelper = require('./columnHelper.js');
var cell = require('./core/cell.js');
var column = require('./core/column.js');
var headers = require('./core/headers.js');
var row = require('./core/row.js');
var table = require('./core/table.js');
var ColumnFaceting = require('./features/ColumnFaceting.js');
var ColumnFiltering = require('./features/ColumnFiltering.js');
var ColumnGrouping = require('./features/ColumnGrouping.js');
var ColumnOrdering = require('./features/ColumnOrdering.js');
var ColumnPinning = require('./features/ColumnPinning.js');
var ColumnSizing = require('./features/ColumnSizing.js');
var ColumnVisibility = require('./features/ColumnVisibility.js');
var GlobalFaceting = require('./features/GlobalFaceting.js');
var GlobalFiltering = require('./features/GlobalFiltering.js');
var RowExpanding = require('./features/RowExpanding.js');
var RowPagination = require('./features/RowPagination.js');
var RowPinning = require('./features/RowPinning.js');
var RowSelection = require('./features/RowSelection.js');
var RowSorting = require('./features/RowSorting.js');
var utils = require('./utils.js');
var getCoreRowModel = require('./utils/getCoreRowModel.js');
var getExpandedRowModel = require('./utils/getExpandedRowModel.js');
var getFacetedMinMaxValues = require('./utils/getFacetedMinMaxValues.js');
var getFacetedRowModel = require('./utils/getFacetedRowModel.js');
var getFacetedUniqueValues = require('./utils/getFacetedUniqueValues.js');
var getFilteredRowModel = require('./utils/getFilteredRowModel.js');
var getGroupedRowModel = require('./utils/getGroupedRowModel.js');
var getPaginationRowModel = require('./utils/getPaginationRowModel.js');
var getSortedRowModel = require('./utils/getSortedRowModel.js');
var aggregationFns = require('./aggregationFns.js');
var filterFns = require('./filterFns.js');
var sortingFns = require('./sortingFns.js');
exports.createColumnHelper = columnHelper.createColumnHelper;
exports.createCell = cell.createCell;
exports.createColumn = column.createColumn;
exports.Headers = headers.Headers;
exports.buildHeaderGroups = headers.buildHeaderGroups;
exports.createRow = row.createRow;
exports.createTable = table.createTable;
exports.ColumnFaceting = ColumnFaceting.ColumnFaceting;
exports.ColumnFiltering = ColumnFiltering.ColumnFiltering;
exports.shouldAutoRemoveFilter = ColumnFiltering.shouldAutoRemoveFilter;
exports.ColumnGrouping = ColumnGrouping.ColumnGrouping;
exports.orderColumns = ColumnGrouping.orderColumns;
exports.ColumnOrdering = ColumnOrdering.ColumnOrdering;
exports.ColumnPinning = ColumnPinning.ColumnPinning;
exports.ColumnSizing = ColumnSizing.ColumnSizing;
exports.defaultColumnSizing = ColumnSizing.defaultColumnSizing;
exports.passiveEventSupported = ColumnSizing.passiveEventSupported;
exports.ColumnVisibility = ColumnVisibility.ColumnVisibility;
exports._getVisibleLeafColumns = ColumnVisibility._getVisibleLeafColumns;
exports.GlobalFaceting = GlobalFaceting.GlobalFaceting;
exports.GlobalFiltering = GlobalFiltering.GlobalFiltering;
exports.RowExpanding = RowExpanding.RowExpanding;
exports.RowPagination = RowPagination.RowPagination;
exports.RowPinning = RowPinning.RowPinning;
exports.RowSelection = RowSelection.RowSelection;
exports.isRowSelected = RowSelection.isRowSelected;
exports.isSubRowSelected = RowSelection.isSubRowSelected;
exports.selectRowsFn = RowSelection.selectRowsFn;
exports.RowSorting = RowSorting.RowSorting;
exports.flattenBy = utils.flattenBy;
exports.functionalUpdate = utils.functionalUpdate;
exports.getMemoOptions = utils.getMemoOptions;
exports.isFunction = utils.isFunction;
exports.isNumberArray = utils.isNumberArray;
exports.makeStateUpdater = utils.makeStateUpdater;
exports.memo = utils.memo;
exports.noop = utils.noop;
exports.getCoreRowModel = getCoreRowModel.getCoreRowModel;
exports.expandRows = getExpandedRowModel.expandRows;
exports.getExpandedRowModel = getExpandedRowModel.getExpandedRowModel;
exports.getFacetedMinMaxValues = getFacetedMinMaxValues.getFacetedMinMaxValues;
exports.getFacetedRowModel = getFacetedRowModel.getFacetedRowModel;
exports.getFacetedUniqueValues = getFacetedUniqueValues.getFacetedUniqueValues;
exports.getFilteredRowModel = getFilteredRowModel.getFilteredRowModel;
exports.getGroupedRowModel = getGroupedRowModel.getGroupedRowModel;
exports.getPaginationRowModel = getPaginationRowModel.getPaginationRowModel;
exports.getSortedRowModel = getSortedRowModel.getSortedRowModel;
exports.aggregationFns = aggregationFns.aggregationFns;
exports.filterFns = filterFns.filterFns;
exports.reSplitAlphaNumeric = sortingFns.reSplitAlphaNumeric;
exports.sortingFns = sortingFns.sortingFns;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
import { SortingFn } from './features/RowSorting';
export declare const reSplitAlphaNumeric: RegExp;
export declare const sortingFns: {
alphanumeric: SortingFn<any>;
alphanumericCaseSensitive: SortingFn<any>;
text: SortingFn<any>;
textCaseSensitive: SortingFn<any>;
datetime: SortingFn<any>;
basic: SortingFn<any>;
};
export type BuiltInSortingFn = keyof typeof sortingFns;

View File

@@ -0,0 +1,120 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
const reSplitAlphaNumeric = /([0-9]+)/gm;
const alphanumeric = (rowA, rowB, columnId) => {
return compareAlphanumeric(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase());
};
const alphanumericCaseSensitive = (rowA, rowB, columnId) => {
return compareAlphanumeric(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId)));
};
// The text filter is more basic (less numeric support)
// but is much faster
const text = (rowA, rowB, columnId) => {
return compareBasic(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase());
};
// The text filter is more basic (less numeric support)
// but is much faster
const textCaseSensitive = (rowA, rowB, columnId) => {
return compareBasic(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId)));
};
const datetime = (rowA, rowB, columnId) => {
const a = rowA.getValue(columnId);
const b = rowB.getValue(columnId);
// Can handle nullish values
// Use > and < because == (and ===) doesn't work with
// Date objects (would require calling getTime()).
return a > b ? 1 : a < b ? -1 : 0;
};
const basic = (rowA, rowB, columnId) => {
return compareBasic(rowA.getValue(columnId), rowB.getValue(columnId));
};
// Utils
function compareBasic(a, b) {
return a === b ? 0 : a > b ? 1 : -1;
}
function toString(a) {
if (typeof a === 'number') {
if (isNaN(a) || a === Infinity || a === -Infinity) {
return '';
}
return String(a);
}
if (typeof a === 'string') {
return a;
}
return '';
}
// Mixed sorting is slow, but very inclusive of many edge cases.
// It handles numbers, mixed alphanumeric combinations, and even
// null, undefined, and Infinity
function compareAlphanumeric(aStr, bStr) {
// Split on number groups, but keep the delimiter
// Then remove falsey split values
const a = aStr.split(reSplitAlphaNumeric).filter(Boolean);
const b = bStr.split(reSplitAlphaNumeric).filter(Boolean);
// While
while (a.length && b.length) {
const aa = a.shift();
const bb = b.shift();
const an = parseInt(aa, 10);
const bn = parseInt(bb, 10);
const combo = [an, bn].sort();
// Both are string
if (isNaN(combo[0])) {
if (aa > bb) {
return 1;
}
if (bb > aa) {
return -1;
}
continue;
}
// One is a string, one is a number
if (isNaN(combo[1])) {
return isNaN(an) ? -1 : 1;
}
// Both are numbers
if (an > bn) {
return 1;
}
if (bn > an) {
return -1;
}
}
return a.length - b.length;
}
// Exports
const sortingFns = {
alphanumeric,
alphanumericCaseSensitive,
text,
textCaseSensitive,
datetime,
basic
};
exports.reSplitAlphaNumeric = reSplitAlphaNumeric;
exports.sortingFns = sortingFns;
//# sourceMappingURL=sortingFns.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,119 @@
import { CoreOptions, CoreTableState, CoreInstance } from './core/table';
import { VisibilityInstance, VisibilityTableState, VisibilityColumn as ColumnVisibilityColumn, VisibilityOptions, VisibilityColumnDef, VisibilityRow } from './features/ColumnVisibility';
import { ColumnOrderColumn, ColumnOrderInstance, ColumnOrderOptions, ColumnOrderTableState } from './features/ColumnOrdering';
import { ColumnPinningColumn, ColumnPinningColumnDef, ColumnPinningInstance, ColumnPinningOptions, ColumnPinningRow, ColumnPinningTableState } from './features/ColumnPinning';
import { RowPinningInstance, RowPinningOptions, RowPinningRow, RowPinningTableState } from './features/RowPinning';
import { CoreHeader, CoreHeaderGroup, HeaderContext, HeadersInstance } from './core/headers';
import { FacetedColumn, FacetedOptions } from './features/ColumnFaceting';
import { GlobalFacetingInstance } from './features/GlobalFaceting';
import { ColumnFiltersColumn, ColumnFiltersColumnDef, ColumnFiltersInstance, ColumnFiltersOptions, ColumnFiltersRow, ColumnFiltersTableState } from './features/ColumnFiltering';
import { GlobalFilterColumn, GlobalFilterColumnDef, GlobalFilterInstance, GlobalFilterOptions, GlobalFilterTableState } from './features/GlobalFiltering';
import { SortingColumn, SortingColumnDef, SortingInstance, SortingOptions, SortingTableState } from './features/RowSorting';
import { GroupingCell, GroupingColumn, GroupingColumnDef, GroupingInstance, GroupingOptions, GroupingRow, GroupingTableState } from './features/ColumnGrouping';
import { ExpandedInstance, ExpandedOptions, ExpandedTableState, ExpandedRow } from './features/RowExpanding';
import { ColumnSizingColumn, ColumnSizingColumnDef, ColumnSizingHeader, ColumnSizingInstance, ColumnSizingOptions, ColumnSizingTableState } from './features/ColumnSizing';
import { PaginationInitialTableState, PaginationInstance, PaginationOptions, PaginationTableState } from './features/RowPagination';
import { RowSelectionInstance, RowSelectionOptions, RowSelectionRow, RowSelectionTableState } from './features/RowSelection';
import { CoreRow } from './core/row';
import { PartialKeys, UnionToIntersection } from './utils';
import { CellContext, CoreCell } from './core/cell';
import { CoreColumn } from './core/column';
export interface TableFeature<TData extends RowData = any> {
createCell?: (cell: Cell<TData, unknown>, column: Column<TData>, row: Row<TData>, table: Table<TData>) => void;
createColumn?: (column: Column<TData, unknown>, table: Table<TData>) => void;
createHeader?: (header: Header<TData, unknown>, table: Table<TData>) => void;
createRow?: (row: Row<TData>, table: Table<TData>) => void;
createTable?: (table: Table<TData>) => void;
getDefaultColumnDef?: () => Partial<ColumnDef<TData, unknown>>;
getDefaultOptions?: (table: Table<TData>) => Partial<TableOptionsResolved<TData>>;
getInitialState?: (initialState?: InitialTableState) => Partial<TableState>;
}
export interface TableMeta<TData extends RowData> {
}
export interface ColumnMeta<TData extends RowData, TValue> {
}
export interface FilterMeta {
}
export interface FilterFns {
}
export interface SortingFns {
}
export interface AggregationFns {
}
export type Updater<T> = T | ((old: T) => T);
export type OnChangeFn<T> = (updaterOrValue: Updater<T>) => void;
export type RowData = unknown | object | any[];
export type AnyRender = (Comp: any, props: any) => any;
export interface Table<TData extends RowData> extends CoreInstance<TData>, HeadersInstance<TData>, VisibilityInstance<TData>, ColumnOrderInstance<TData>, ColumnPinningInstance<TData>, RowPinningInstance<TData>, ColumnFiltersInstance<TData>, GlobalFilterInstance<TData>, GlobalFacetingInstance<TData>, SortingInstance<TData>, GroupingInstance<TData>, ColumnSizingInstance, ExpandedInstance<TData>, PaginationInstance<TData>, RowSelectionInstance<TData> {
}
interface FeatureOptions<TData extends RowData> extends VisibilityOptions, ColumnOrderOptions, ColumnPinningOptions, RowPinningOptions<TData>, FacetedOptions<TData>, ColumnFiltersOptions<TData>, GlobalFilterOptions<TData>, SortingOptions<TData>, GroupingOptions, ExpandedOptions<TData>, ColumnSizingOptions, PaginationOptions, RowSelectionOptions<TData> {
}
export interface TableOptionsResolved<TData extends RowData> extends CoreOptions<TData>, FeatureOptions<TData> {
}
export interface TableOptions<TData extends RowData> extends PartialKeys<TableOptionsResolved<TData>, 'state' | 'onStateChange' | 'renderFallbackValue'> {
}
export interface TableState extends CoreTableState, VisibilityTableState, ColumnOrderTableState, ColumnPinningTableState, RowPinningTableState, ColumnFiltersTableState, GlobalFilterTableState, SortingTableState, ExpandedTableState, GroupingTableState, ColumnSizingTableState, PaginationTableState, RowSelectionTableState {
}
interface CompleteInitialTableState extends CoreTableState, VisibilityTableState, ColumnOrderTableState, ColumnPinningTableState, RowPinningTableState, ColumnFiltersTableState, GlobalFilterTableState, SortingTableState, ExpandedTableState, GroupingTableState, ColumnSizingTableState, PaginationInitialTableState, RowSelectionTableState {
}
export interface InitialTableState extends Partial<CompleteInitialTableState> {
}
export interface Row<TData extends RowData> extends CoreRow<TData>, VisibilityRow<TData>, ColumnPinningRow<TData>, RowPinningRow, ColumnFiltersRow<TData>, GroupingRow, RowSelectionRow, ExpandedRow {
}
export interface RowModel<TData extends RowData> {
rows: Row<TData>[];
flatRows: Row<TData>[];
rowsById: Record<string, Row<TData>>;
}
export type AccessorFn<TData extends RowData, TValue = unknown> = (originalRow: TData, index: number) => TValue;
export type ColumnDefTemplate<TProps extends object> = string | ((props: TProps) => any);
export type StringOrTemplateHeader<TData, TValue> = string | ColumnDefTemplate<HeaderContext<TData, TValue>>;
export interface StringHeaderIdentifier {
header: string;
id?: string;
}
export interface IdIdentifier<TData extends RowData, TValue> {
id: string;
header?: StringOrTemplateHeader<TData, TValue>;
}
type ColumnIdentifiers<TData extends RowData, TValue> = IdIdentifier<TData, TValue> | StringHeaderIdentifier;
interface ColumnDefExtensions<TData extends RowData, TValue = unknown> extends VisibilityColumnDef, ColumnPinningColumnDef, ColumnFiltersColumnDef<TData>, GlobalFilterColumnDef, SortingColumnDef<TData>, GroupingColumnDef<TData, TValue>, ColumnSizingColumnDef {
}
export interface ColumnDefBase<TData extends RowData, TValue = unknown> extends ColumnDefExtensions<TData, TValue> {
getUniqueValues?: AccessorFn<TData, unknown[]>;
footer?: ColumnDefTemplate<HeaderContext<TData, TValue>>;
cell?: ColumnDefTemplate<CellContext<TData, TValue>>;
meta?: ColumnMeta<TData, TValue>;
}
export interface IdentifiedColumnDef<TData extends RowData, TValue = unknown> extends ColumnDefBase<TData, TValue> {
id?: string;
header?: StringOrTemplateHeader<TData, TValue>;
}
export type DisplayColumnDef<TData extends RowData, TValue = unknown> = ColumnDefBase<TData, TValue> & ColumnIdentifiers<TData, TValue>;
interface GroupColumnDefBase<TData extends RowData, TValue = unknown> extends ColumnDefBase<TData, TValue> {
columns?: ColumnDef<TData, any>[];
}
export type GroupColumnDef<TData extends RowData, TValue = unknown> = GroupColumnDefBase<TData, TValue> & ColumnIdentifiers<TData, TValue>;
export interface AccessorFnColumnDefBase<TData extends RowData, TValue = unknown> extends ColumnDefBase<TData, TValue> {
accessorFn: AccessorFn<TData, TValue>;
}
export type AccessorFnColumnDef<TData extends RowData, TValue = unknown> = AccessorFnColumnDefBase<TData, TValue> & ColumnIdentifiers<TData, TValue>;
export interface AccessorKeyColumnDefBase<TData extends RowData, TValue = unknown> extends ColumnDefBase<TData, TValue> {
id?: string;
accessorKey: (string & {}) | keyof TData;
}
export type AccessorKeyColumnDef<TData extends RowData, TValue = unknown> = AccessorKeyColumnDefBase<TData, TValue> & Partial<ColumnIdentifiers<TData, TValue>>;
export type AccessorColumnDef<TData extends RowData, TValue = unknown> = AccessorKeyColumnDef<TData, TValue> | AccessorFnColumnDef<TData, TValue>;
export type ColumnDef<TData extends RowData, TValue = unknown> = DisplayColumnDef<TData, TValue> | GroupColumnDef<TData, TValue> | AccessorColumnDef<TData, TValue>;
export type ColumnDefResolved<TData extends RowData, TValue = unknown> = Partial<UnionToIntersection<ColumnDef<TData, TValue>>> & {
accessorKey?: string;
};
export interface Column<TData extends RowData, TValue = unknown> extends CoreColumn<TData, TValue>, ColumnVisibilityColumn, ColumnPinningColumn, FacetedColumn<TData>, ColumnFiltersColumn<TData>, GlobalFilterColumn, SortingColumn<TData>, GroupingColumn<TData>, ColumnSizingColumn, ColumnOrderColumn {
}
export interface Cell<TData extends RowData, TValue> extends CoreCell<TData, TValue>, GroupingCell {
}
export interface Header<TData extends RowData, TValue> extends CoreHeader<TData, TValue>, ColumnSizingHeader {
}
export interface HeaderGroup<TData extends RowData> extends CoreHeaderGroup<TData> {
}
export {};

View File

@@ -0,0 +1,38 @@
import { TableOptionsResolved, TableState, Updater } from './types';
export type PartialKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type RequiredKeys<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
export type Overwrite<T, U extends {
[TKey in keyof T]?: any;
}> = Omit<T, keyof U> & U;
export type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R : never;
export type IsAny<T, Y, N> = 1 extends 0 & T ? Y : N;
export type IsKnown<T, Y, N> = unknown extends T ? N : Y;
type ComputeRange<N extends number, Result extends Array<unknown> = []> = Result['length'] extends N ? Result : ComputeRange<N, [...Result, Result['length']]>;
type Index40 = ComputeRange<40>[number];
type IsTuple<T> = T extends readonly any[] & {
length: infer Length;
} ? Length extends Index40 ? T : never : never;
type AllowedIndexes<Tuple extends ReadonlyArray<any>, Keys extends number = never> = Tuple extends readonly [] ? Keys : Tuple extends readonly [infer _, ...infer Tail] ? AllowedIndexes<Tail, Keys | Tail['length']> : Keys;
export type DeepKeys<T, TDepth extends any[] = []> = TDepth['length'] extends 5 ? never : unknown extends T ? string : T extends readonly any[] & IsTuple<T> ? AllowedIndexes<T> | DeepKeysPrefix<T, AllowedIndexes<T>, TDepth> : T extends any[] ? DeepKeys<T[number], [...TDepth, any]> : T extends Date ? never : T extends object ? (keyof T & string) | DeepKeysPrefix<T, keyof T, TDepth> : never;
type DeepKeysPrefix<T, TPrefix, TDepth extends any[]> = TPrefix extends keyof T & (number | string) ? `${TPrefix}.${DeepKeys<T[TPrefix], [...TDepth, any]> & string}` : never;
export type DeepValue<T, TProp> = T extends Record<string | number, any> ? TProp extends `${infer TBranch}.${infer TDeepProp}` ? DeepValue<T[TBranch], TDeepProp> : T[TProp & string] : never;
export type NoInfer<T> = [T][T extends any ? 0 : never];
export type Getter<TValue> = <TTValue = TValue>() => NoInfer<TTValue>;
export declare function functionalUpdate<T>(updater: Updater<T>, input: T): T;
export declare function noop(): void;
export declare function makeStateUpdater<K extends keyof TableState>(key: K, instance: unknown): (updater: Updater<TableState[K]>) => void;
type AnyFunction = (...args: any) => any;
export declare function isFunction<T extends AnyFunction>(d: any): d is T;
export declare function isNumberArray(d: any): d is number[];
export declare function flattenBy<TNode>(arr: TNode[], getChildren: (item: TNode) => TNode[]): TNode[];
export declare function memo<TDeps extends readonly any[], TDepArgs, TResult>(getDeps: (depArgs?: TDepArgs) => [...TDeps], fn: (...args: NoInfer<[...TDeps]>) => TResult, opts: {
key: any;
debug?: () => any;
onChange?: (result: TResult) => void;
}): (depArgs?: TDepArgs) => TResult;
export declare function getMemoOptions(tableOptions: Partial<TableOptionsResolved<any>>, debugLevel: 'debugAll' | 'debugCells' | 'debugTable' | 'debugColumns' | 'debugRows' | 'debugHeaders', key: string, onChange?: (result: any) => void): {
debug: () => boolean | undefined;
key: string | false;
onChange: ((result: any) => void) | undefined;
};
export {};

View File

@@ -0,0 +1,111 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
// Is this type a tuple?
// If this type is a tuple, what indices are allowed?
///
function functionalUpdate(updater, input) {
return typeof updater === 'function' ? updater(input) : updater;
}
function noop() {
//
}
function makeStateUpdater(key, instance) {
return updater => {
instance.setState(old => {
return {
...old,
[key]: functionalUpdate(updater, old[key])
};
});
};
}
function isFunction(d) {
return d instanceof Function;
}
function isNumberArray(d) {
return Array.isArray(d) && d.every(val => typeof val === 'number');
}
function flattenBy(arr, getChildren) {
const flat = [];
const recurse = subArr => {
subArr.forEach(item => {
flat.push(item);
const children = getChildren(item);
if (children != null && children.length) {
recurse(children);
}
});
};
recurse(arr);
return flat;
}
function memo(getDeps, fn, opts) {
let deps = [];
let result;
return depArgs => {
let depTime;
if (opts.key && opts.debug) depTime = Date.now();
const newDeps = getDeps(depArgs);
const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep);
if (!depsChanged) {
return result;
}
deps = newDeps;
let resultTime;
if (opts.key && opts.debug) resultTime = Date.now();
result = fn(...newDeps);
opts == null || opts.onChange == null || opts.onChange(result);
if (opts.key && opts.debug) {
if (opts != null && opts.debug()) {
const depEndTime = Math.round((Date.now() - depTime) * 100) / 100;
const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100;
const resultFpsPercentage = resultEndTime / 16;
const pad = (str, num) => {
str = String(str);
while (str.length < num) {
str = ' ' + str;
}
return str;
};
console.info(`%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, `
font-size: .6rem;
font-weight: bold;
color: hsl(${Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120))}deg 100% 31%);`, opts == null ? void 0 : opts.key);
}
}
return result;
};
}
function getMemoOptions(tableOptions, debugLevel, key, onChange) {
return {
debug: () => {
var _tableOptions$debugAl;
return (_tableOptions$debugAl = tableOptions == null ? void 0 : tableOptions.debugAll) != null ? _tableOptions$debugAl : tableOptions[debugLevel];
},
key: process.env.NODE_ENV === 'development' && key,
onChange
};
}
exports.flattenBy = flattenBy;
exports.functionalUpdate = functionalUpdate;
exports.getMemoOptions = getMemoOptions;
exports.isFunction = isFunction;
exports.isNumberArray = isNumberArray;
exports.makeStateUpdater = makeStateUpdater;
exports.memo = memo;
exports.noop = noop;
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export declare function safelyAccessDocument(_document?: Document): Document | null;
export declare function safelyAccessDocumentEvent(event: Event): Document | null;

View File

@@ -0,0 +1,18 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
function safelyAccessDocument(_document) {
return _document || (typeof document !== 'undefined' ? document : null);
}
exports.safelyAccessDocument = safelyAccessDocument;
//# sourceMappingURL=document.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"document.js","sources":["../../../src/utils/document.ts"],"sourcesContent":["export function safelyAccessDocument(_document?: Document): Document | null {\n return _document || (typeof document !== 'undefined' ? document : null)\n}\n\nexport function safelyAccessDocumentEvent(event: Event): Document | null {\n return !!event &&\n !!event.target &&\n typeof event.target === 'object' &&\n 'ownerDocument' in event.target\n ? (event.target.ownerDocument as Document | null)\n : null\n}\n"],"names":["safelyAccessDocument","_document","document"],"mappings":";;;;;;;;;;;;AAAO,SAASA,oBAAoBA,CAACC,SAAoB,EAAmB;EAC1E,OAAOA,SAAS,KAAK,OAAOC,QAAQ,KAAK,WAAW,GAAGA,QAAQ,GAAG,IAAI,CAAC,CAAA;AACzE;;;;"}

View File

@@ -0,0 +1,2 @@
import { Row, RowModel, Table, RowData } from '../types';
export declare function filterRows<TData extends RowData>(rows: Row<TData>[], filterRowImpl: (row: Row<TData>) => any, table: Table<TData>): RowModel<TData>;

View File

@@ -0,0 +1,111 @@
/**
* table-core
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var row = require('../core/row.js');
function filterRows(rows, filterRowImpl, table) {
if (table.options.filterFromLeafRows) {
return filterRowModelFromLeafs(rows, filterRowImpl, table);
}
return filterRowModelFromRoot(rows, filterRowImpl, table);
}
function filterRowModelFromLeafs(rowsToFilter, filterRow, table) {
var _table$options$maxLea;
const newFilteredFlatRows = [];
const newFilteredRowsById = {};
const maxDepth = (_table$options$maxLea = table.options.maxLeafRowFilterDepth) != null ? _table$options$maxLea : 100;
const recurseFilterRows = function (rowsToFilter, depth) {
if (depth === void 0) {
depth = 0;
}
const rows = [];
// Filter from children up first
for (let i = 0; i < rowsToFilter.length; i++) {
var _row$subRows;
let row$1 = rowsToFilter[i];
const newRow = row.createRow(table, row$1.id, row$1.original, row$1.index, row$1.depth, undefined, row$1.parentId);
newRow.columnFilters = row$1.columnFilters;
if ((_row$subRows = row$1.subRows) != null && _row$subRows.length && depth < maxDepth) {
newRow.subRows = recurseFilterRows(row$1.subRows, depth + 1);
row$1 = newRow;
if (filterRow(row$1) && !newRow.subRows.length) {
rows.push(row$1);
newFilteredRowsById[row$1.id] = row$1;
newFilteredFlatRows.push(row$1);
continue;
}
if (filterRow(row$1) || newRow.subRows.length) {
rows.push(row$1);
newFilteredRowsById[row$1.id] = row$1;
newFilteredFlatRows.push(row$1);
continue;
}
} else {
row$1 = newRow;
if (filterRow(row$1)) {
rows.push(row$1);
newFilteredRowsById[row$1.id] = row$1;
newFilteredFlatRows.push(row$1);
}
}
}
return rows;
};
return {
rows: recurseFilterRows(rowsToFilter),
flatRows: newFilteredFlatRows,
rowsById: newFilteredRowsById
};
}
function filterRowModelFromRoot(rowsToFilter, filterRow, table) {
var _table$options$maxLea2;
const newFilteredFlatRows = [];
const newFilteredRowsById = {};
const maxDepth = (_table$options$maxLea2 = table.options.maxLeafRowFilterDepth) != null ? _table$options$maxLea2 : 100;
// Filters top level and nested rows
const recurseFilterRows = function (rowsToFilter, depth) {
if (depth === void 0) {
depth = 0;
}
// Filter from parents downward first
const rows = [];
// Apply the filter to any subRows
for (let i = 0; i < rowsToFilter.length; i++) {
let row$1 = rowsToFilter[i];
const pass = filterRow(row$1);
if (pass) {
var _row$subRows2;
if ((_row$subRows2 = row$1.subRows) != null && _row$subRows2.length && depth < maxDepth) {
const newRow = row.createRow(table, row$1.id, row$1.original, row$1.index, row$1.depth, undefined, row$1.parentId);
newRow.subRows = recurseFilterRows(row$1.subRows, depth + 1);
row$1 = newRow;
}
rows.push(row$1);
newFilteredFlatRows.push(row$1);
newFilteredRowsById[row$1.id] = row$1;
}
}
return rows;
};
return {
rows: recurseFilterRows(rowsToFilter),
flatRows: newFilteredFlatRows,
rowsById: newFilteredRowsById
};
}
exports.filterRows = filterRows;
//# sourceMappingURL=filterRowsUtils.js.map

Some files were not shown because too many files have changed in this diff Show More