diff --git a/.github/workflows/pytest.yaml b/.github/workflows/pytest.yaml index ffdb99196..3bc396917 100644 --- a/.github/workflows/pytest.yaml +++ b/.github/workflows/pytest.yaml @@ -33,25 +33,20 @@ jobs: run: | make check-tests - - name: Type check with pyright + - name: Type check if: steps.install.outcome == 'success' && (success() || failure()) run: | make check-types - - name: Lint with flake8 + - name: Lint code if: steps.install.outcome == 'success' && (success() || failure()) run: | make check-lint - - name: black + - name: Verify code formatting if: steps.install.outcome == 'success' && (success() || failure()) run: | - make check-black - - - name: isort - if: steps.install.outcome == 'success' && (success() || failure()) - run: | - make check-isort + make check-format playwright-shiny: runs-on: ${{ matrix.os }} diff --git a/Makefile b/Makefile index 76c205aa3..40146b192 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,9 @@ -.PHONY: help clean% check% format% docs% lint test pyright playwright% install% testrail% coverage release +# https://www.gnu.org/software/make/manual/make.html#Phony-Targets +# Prerequisites of .PHONY are always interpreted as literal target names, never as patterns (even if they contain ‘%’ characters). +# # .PHONY: help clean% check% format% docs% lint test pyright playwright% install% testrail% coverage release js-* +# Using `FORCE` as prerequisite to _force_ the target to always run; https://www.gnu.org/software/make/manual/make.html#index-FORCE +FORCE: ; + .DEFAULT_GOAL := help define BROWSER_PYSCRIPT @@ -23,114 +28,157 @@ export PRINT_HELP_PYSCRIPT BROWSER := python -c "$$BROWSER_PYSCRIPT" -help: +help: FORCE @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts -clean-build: ## remove build artifacts +# Remove build artifacts +clean-build: FORCE rm -fr build/ rm -fr dist/ rm -fr .eggs/ find . -name '*.egg-info' -exec rm -fr {} + find . -name '*.egg' -exec rm -f {} + -clean-pyc: ## remove Python file artifacts +# Remove Python file artifacts +clean-pyc: FORCE find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + find . -name '__pycache__' -exec rm -fr {} + -clean-test: ## remove test and coverage artifacts +# Remove test and coverage artifacts +clean-test: FORCE rm -fr .tox/ rm -f .coverage rm -fr htmlcov/ rm -fr .pytest_cache rm -rf typings/ +typings/appdirs: + echo "Creating appdirs stubs" + pyright --createstub appdirs +typings/folium: + echo "Creating folium stubs" + pyright --createstub folium typings/uvicorn: + echo "Creating uvicorn stubs" pyright --createstub uvicorn +typings/seaborn: + echo "Creating seaborn stubs" + pyright --createstub seaborn -typings/matplotlib/__init__.pyi: ## grab type stubs from GitHub +typings/matplotlib/__init__.pyi: + echo "Creating matplotlib stubs" mkdir -p typings git clone --depth 1 https://github.com/microsoft/python-type-stubs typings/python-type-stubs mv typings/python-type-stubs/stubs/matplotlib typings/ rm -rf typings/python-type-stubs -typings/seaborn: - pyright --createstub seaborn +pyright-typings: typings/appdirs typings/folium typings/uvicorn typings/seaborn typings/matplotlib/__init__.pyi check: check-format check-lint check-types check-tests ## check code, style, types, and test (basic CI) check-fix: format check-lint check-types check-tests ## check and format code, style, types, and test check-format: check-black check-isort -check-lint: - @echo "-------- Checking style with flake8 --------" +check-lint: check-flake8 +check-types: check-pyright +check-tests: check-pytest + +check-flake8: FORCE + @echo "-------- Checking style with flake8 ---------" flake8 --show-source . -check-black: - @echo "-------- Checking code with black --------" +check-black: FORCE + @echo "-------- Checking code with black -----------" black --check . -check-isort: - @echo "-------- Sorting imports with isort --------" +check-isort: FORCE + @echo "-------- Sorting imports with isort ---------" isort --check-only --diff . -check-types: typings/uvicorn typings/matplotlib/__init__.pyi typings/seaborn +check-pyright: pyright-typings @echo "-------- Checking types with pyright --------" pyright -check-tests: - @echo "-------- Running tests with pytest --------" +check-pytest: FORCE + @echo "-------- Running tests with pytest ----------" python3 tests/pytest/asyncio_prevent.py pytest -pyright: check-types ## check types with pyright -lint: check-lint ## check style with flake8 +# Check types with pyright +pyright: check-types +# Check style with flake8 +lint: check-lint test: check-tests ## check tests quickly with the default Python format: format-black format-isort ## format code with black and isort -format-black: +format-black: FORCE @echo "-------- Formatting code with black --------" black . -format-isort: +format-isort: FORCE @echo "-------- Sorting imports with isort --------" isort . -docs: ## docs: build docs with quartodoc - @echo "-------- Building docs with quartodoc --------" +docs: FORCE ## docs: build docs with quartodoc + @echo "-------- Building docs with quartodoc ------" @cd docs && make quartodoc -docs-preview: ## docs: preview docs in browser +docs-preview: FORCE ## docs: preview docs in browser @echo "-------- Previewing docs in browser --------" @cd docs && make serve + +install-npm: FORCE + $(if $(shell which npm), @echo -n, $(error Please install node.js and npm first. See https://nodejs.org/en/download/ for instructions.)) +js/node_modules: install-npm + @echo "-------- Installing node_modules -----------" + @cd js && npm install +js-build: js/node_modules ## Build JS assets + @echo "-------- Building JS assets ----------------" + @cd js && npm run build +js-watch: js/node_modules + @echo "-------- Continuously building JS assets ---" + @cd js && npm run watch +js-watch-fast: js/node_modules ## Continuously build JS assets (development) + @echo "-------- Previewing docs in browser --------" + @cd js && npm run watch-fast +clean-js: FORCE + @echo "-------- Removing js/node_modules ----------" + rm -rf js/node_modules + # Default `SUB_FILE` to empty SUB_FILE:= -install-playwright: +install-playwright: FORCE playwright install --with-deps -install-trcli: - which trcli || pip install trcli +install-trcli: FORCE + $(if $(shell which trcli), @echo -n, $(shell pip install trcli)) -install-rsconnect: ## install the main version of rsconnect till pypi version supports shiny express +# Installs the main version of rsconnect till pypi version supports shiny express +install-rsconnect: FORCE pip install git+https://github.com/rstudio/rsconnect-python.git#egg=rsconnect-python -playwright-shiny: install-playwright ## end-to-end tests with playwright +# end-to-end tests with playwright; (SUB_FILE="" within tests/playwright/shiny/) +playwright-shiny: install-playwright pytest tests/playwright/shiny/$(SUB_FILE) -playwright-deploys: install-playwright install-rsconnect ## end-to-end tests on examples with playwright +# end-to-end tests on deployed apps with playwright; (SUB_FILE="" within tests/playwright/deploys/) +playwright-deploys: install-playwright install-rsconnect pytest tests/playwright/deploys/$(SUB_FILE) -playwright-examples: install-playwright ## end-to-end tests on examples with playwright +# end-to-end tests on all py-shiny examples with playwright; (SUB_FILE="" within tests/playwright/examples/) +playwright-examples: install-playwright pytest tests/playwright/examples/$(SUB_FILE) -playwright-debug: install-playwright ## All end-to-end tests, chrome only, headed +playwright-debug: install-playwright ## All end-to-end tests, chrome only, headed; (SUB_FILE="" within tests/playwright/) pytest -c tests/playwright/playwright-pytest.ini tests/playwright/$(SUB_FILE) playwright-show-trace: ## Show trace of failed tests npx playwright show-trace test-results/*/trace.zip -testrail-junit: install-playwright install-trcli ## end-to-end tests with playwright and generate junit report +# end-to-end tests with playwright and generate junit report +testrail-junit: install-playwright install-trcli pytest tests/playwright/shiny/$(SUB_FILE) --junitxml=report.xml -coverage: ## check combined code coverage (must run e2e last) +coverage: FORCE ## check combined code coverage (must run e2e last) pytest --cov-report term-missing --cov=shiny tests/pytest/ tests/playwright/shiny/$(SUB_FILE) coverage html $(BROWSER) htmlcov/index.html @@ -151,9 +199,9 @@ install: dist pip uninstall -y shiny python3 -m pip install dist/shiny*.whl -install-deps: ## install dependencies +install-deps: FORCE ## install dependencies pip install -e ".[dev,test]" --upgrade # ## If caching is ever used, we could run: -# install-deps: ## install latest dependencies +# install-deps: FORCE ## install latest dependencies # pip install --editable ".[dev,test]" --upgrade --upgrade-strategy eager diff --git a/examples/dataframe/app.py b/examples/dataframe/app.py index 99374627e..e1d527534 100644 --- a/examples/dataframe/app.py +++ b/examples/dataframe/app.py @@ -92,10 +92,10 @@ def handle_edit(): @render.text def detail(): - selected_rows = input.grid_selected_rows() or () + selected_rows = grid.input_selected_rows() or () if len(selected_rows) > 0: # "split", "records", "index", "columns", "values", "table" - return df().iloc[list(input.grid_selected_rows())] + return df().iloc[list(grid.input_selected_rows())] app = App(app_ui, server) diff --git a/js/.eslintrc.js b/js/.eslintrc.js index fa6f42d5d..ea03295fa 100644 --- a/js/.eslintrc.js +++ b/js/.eslintrc.js @@ -9,6 +9,7 @@ module.exports = { "plugin:react/recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", + "plugin:react-hooks/recommended", ], ignorePatterns: ["dist/*"], overrides: [], diff --git a/js/build.ts b/js/build.ts index ef5c8beee..fcc460646 100644 --- a/js/build.ts +++ b/js/build.ts @@ -2,6 +2,14 @@ import { BuildOptions, build } from "esbuild"; import { sassPlugin } from "esbuild-sass-plugin"; import * as fs from "node:fs/promises"; +let minify = true; +process.argv.forEach((val, index) => { + if (val === "--minify=false") { + console.log("Disabling minification"); + minify = false; + } +}); + const outDir = "../shiny/www/shared/py-shiny"; async function bundle_helper( @@ -11,7 +19,7 @@ async function bundle_helper( const result = await build({ format: "esm", bundle: true, - minify: true, + minify: minify, sourcemap: true, metafile: false, outdir: outDir, diff --git a/js/dataframe/cell.tsx b/js/dataframe/cell.tsx new file mode 100644 index 000000000..653bb19fe --- /dev/null +++ b/js/dataframe/cell.tsx @@ -0,0 +1,366 @@ +import { flexRender } from "@tanstack/react-table"; +import { Cell } from "@tanstack/table-core"; +import React, { + FC, + ChangeEvent as ReactChangeEvent, + FocusEvent as ReactFocusEvent, + KeyboardEvent as ReactKeyboardEvent, + MouseEvent as ReactMouseEvent, + useEffect, + useRef, + useState, +} from "react"; +import { useImmer } from "use-immer"; +import { updateCellsData } from "./data-update"; + +export enum CellState { + EditSaving = "edit-waiting", + EditSuccess = "edit-success", + EditFailure = "edit-failure", + Editing = "editing", + Ready = "ready", +} + +interface TableBodyCellProps { + id: string; + cell: Cell; + columns: readonly string[]; + canEdit: boolean; + editRowIndex: number; + editColumnIndex: number; + setEditRowIndex: (index: number) => void; + setEditColumnIndex: (index: number) => void; + cellEditMap: Map; + setData: (fn: (draft: unknown[][]) => void) => void; + setCellEditMap: ( + fn: (draft: Map) => void + ) => void; + maxRowSize: number; +} + +export const TableBodyCell: FC = ({ + id, + cell, + columns, + canEdit, + editRowIndex, + editColumnIndex, + setEditRowIndex, + setEditColumnIndex, + cellEditMap, + setData, + setCellEditMap, + maxRowSize, +}) => { + const rowIndex = cell.row.index; + const columnIndex = cell.column.columnDef.meta.colIndex; + // const backgroundColor = cellEditMap.has(`[${rowIndex}, ${columnIndex}]`) + // ? "red" + // : null; + + // return ( + // + // {flexRender(cell.column.columnDef.cell, cell.getContext())} + // + // ); + // }; + + // interface EditableCellProps { + // rowIndex: number; + // columnIndex: string; + // getValue: () => unknown; + // editRowIndex: number; + // editColumnIndex: string; + // cellEditMap: Map; + // } + // return ( + // + // ); + + // const EditableCell: FC = (props) => { + // const { + // rowIndex, + // columnIndex, + // getValue, + // editRowIndex, + // editColumnIndex, + // cellEditMap, + // } = props; + + // States + // # Ready + // # Editing + // # Saving / Disabled + // # Error + // # Saved + // # Cancelled (is Ready state?) + // # New + // # Added + // # Removed + const initialValue = cell.getValue(); + // We need to keep and update the state of the cell normally + const [value, setValue] = useImmer(initialValue); + const inputRef = useRef(null); + + const [cellState, setCellState] = useState(CellState.Ready); + + const editable = editRowIndex === rowIndex && editColumnIndex === columnIndex; + if (editable) { + setCellState(CellState.Editing); + } + const hasUpdated = cellEditMap.has(`[${rowIndex}, ${columnIndex}]`); + // if (editable) { + // if (hasUpdated) { + // console.log("Has updated!", rowIndex, columnIndex, cellEditMap); + // } + // } + + // useEffect(() => { + // if (editable) { + // console.log( + // "cell background color: ", + // cellBackground, + // rowIndex, + // columnIndex + // ); + // } + // }, [cellBackground, editable, rowIndex, columnIndex]); + + // useEffect(() => { + + // setCellState(CellState.Ready); + // }, [cellEditMap, rowIndex, columnIndex]); + // useEffect(() => { + // if (!editable) return; + // console.log( + // "Cell map:", + // rowIndex, + // columnIndex, + // cellEditMap, + // cellEditMap.has(`[${rowIndex}, ${columnIndex}]`) + // ); + // }, [cellEditMap, rowIndex, editable, columnIndex]); + + // useEffect(() => { + // if (editable) { + // setCellBackground("red"); + // return; + // } + // // if (!hasUpdated) { + // // setCellBackground("transparent"); + // // return; + // // } + // switch (cellState) { + // case CellState.EditSaving: + // setCellBackground("lightgrey"); + // break; + // case CellState.EditSuccess: + // setCellBackground("#ddffdd"); + // break; + // case CellState.EditFailure: + // setCellBackground("lightcoral"); + // break; + // case CellState.Editing: + // setCellBackground("lightblue"); + // break; + // default: + // setCellBackground("transparent"); + // } + // }, [cellState, editable, hasUpdated]); + + type TableCellClassMap = { + [key in CellState]: string; + }; + const tableCellClassMap_: Record = {}; + tableCellClassMap_[CellState.Ready] = null; + tableCellClassMap_[CellState.Editing] = "cell-edit-editing"; + tableCellClassMap_[CellState.EditSaving] = "cell-edit-saving"; + tableCellClassMap_[CellState.EditSuccess] = "cell-edit-success"; + tableCellClassMap_[CellState.EditFailure] = "cell-edit-failure"; + const tableCellMap: TableCellClassMap = + tableCellClassMap_ as TableCellClassMap; + + const tableCellClass = tableCellMap[cellState]; + + // useEffect(() => { + // console.log("Cell background:", tableCellClass, rowIndex, columnIndex); + // }, [tableCellClass, rowIndex, columnIndex]); + // useEffect(() => { + // console.log("Cell state:", cellState, hasUpdated); + // }, [hasUpdated, cellState]); + + function resetEditInfo() { + setEditRowIndex(null); + setEditColumnIndex(null); + } + + const onEsc = (e: ReactKeyboardEvent) => { + if (e.key !== "Escape") return; + // Prevent default behavior + e.preventDefault(); + + // inputRef.current.blur(); + resetEditInfo(); + // TODO-barret-future; Set focus to table? (state: Editing was aborted) + }; + const onTab = (e: ReactKeyboardEvent) => { + if (e.key !== "Tab") return; + // Prevent default behavior + e.preventDefault(); + + const hasShift = e.shiftKey; + + const newColumnIndex = editColumnIndex + (hasShift ? -1 : 1); + if (newColumnIndex < 0 || newColumnIndex >= columns.length) { + // If the new column index is out of bounds, quit + return; + } + + setEditColumnIndex(newColumnIndex); + }; + const onEnter = (e: ReactKeyboardEvent) => { + if (e.key !== "Enter") return; + // Prevent default behavior + e.preventDefault(); + + const hasShift = e.shiftKey; + + console.log(maxRowSize); + + const newRowIndex = editRowIndex + (hasShift ? -1 : 1); + if (newRowIndex < 0 || newRowIndex >= maxRowSize) { + // If the new row index is out of bounds, quit + // attemptUpdate(); + return; + } + + setEditRowIndex(newRowIndex); + }; + + const onInputKeyDown = (e: ReactKeyboardEvent) => { + [onEsc, onEnter, onTab].forEach((fn) => fn(e)); + }; + + const attemptUpdate = () => { + // Only update if the string form of the value has changed + if (`${initialValue}` !== `${value}`) { + setCellState(CellState.EditSaving); + // console.log("Setting update count"); + // setUpdateCount(updateCount + 1); + updateCellsData({ + id, + cellInfos: [ + { + rowIndex, + columnIndex, + value, + prev: initialValue, + }, + ], + onSuccess: (values) => { + // console.log("success!", values); + setCellState(CellState.EditSuccess); + }, + onError: (err) => { + // console.log("error!", err); + console.error("Error saving tabel cell value!", err); + setCellState(CellState.EditFailure); + }, + columns, + setData, + setCellEditMap, + }); + } + }; + + // When the input is blurred, we'll call our table meta's updateData function + // console.log("rendering cell", rowIndex, id, initialValue, value); + const onBlur = () => { + // console.log("on blur!", initialValue, value, e); + attemptUpdate(); + }; + + // If the initialValue is changed external, sync it up with our state + useEffect(() => { + setValue(initialValue); + }, [initialValue, setValue]); + + // Select the input when it becomes editable + useEffect(() => { + if (editable) { + inputRef.current.focus(); + inputRef.current.select(); + + // Setup global click listener to reset edit info + window.document + .querySelector("body") + .addEventListener("click", (e: MouseEvent) => { + // console.log("body click!", e.target, inputRef.current); + // TODO-barret; Do not reset if target is another table cell! + // Or skip the reset? + resetEditInfo(); + }); + + // Tear down global click listener when we're done + return () => { + window.document + .querySelector("body") + .removeEventListener("click", resetEditInfo); + }; + } + }, [editable]); + + // Reselect the input when it comes into view! + // (It could be scrolled out of view and then back into view) + function onFocus(e: ReactFocusEvent) { + if (editable) { + e.target.select(); + } + } + + function onChange(e: ReactChangeEvent) { + console.log("on change!"); + setValue(e.target.value); + } + + let onClick = undefined; + let content = undefined; + + if (cellState === CellState.EditSaving) { + content = {value as string}; + } else if (editable) { + content = ( + + ); + } else { + onClick = (e: ReactMouseEvent) => { + console.log("on ready click!", e.target); + setEditRowIndex(rowIndex); + setEditColumnIndex(columnIndex); + }; + if (cellState === CellState.EditFailure) { + console.log("Render edit failure"); + } + content = flexRender(cell.column.columnDef.cell, cell.getContext()); + } + + return ( + + {content} + + ); +}; diff --git a/js/dataframe/data-update.tsx b/js/dataframe/data-update.tsx new file mode 100644 index 000000000..77dea6794 --- /dev/null +++ b/js/dataframe/data-update.tsx @@ -0,0 +1,94 @@ +import { ResponseValue, makeRequest } from "./request"; + +import { CellState } from "./cell"; + +export type UpdateCellData = { + rowIndex: number; + columnIndex: number; + value: unknown; + prev: unknown; +}; +export type UpdateCellDataRequest = { + row_index: number; + column_index: number; + value: unknown; + prev: unknown; +}; + +export function updateCellsData({ + id, + cellInfos, + onSuccess, + onError, + columns, + setData, + setCellEditMap, +}: { + id: string; + cellInfos: UpdateCellData[]; + onSuccess: (values: ResponseValue[]) => void; + onError: (err: string) => void; + columns: readonly string[]; + setData: (fn: (draft: unknown[][]) => void) => void; + setCellEditMap: ( + fn: (draft: Map) => void + ) => void; +}) { + // // Skip page index reset until after next rerender + // skipAutoResetPageIndex(); + + const updateInfos: UpdateCellDataRequest[] = cellInfos.map((cellInfo) => { + return { + row_index: cellInfo.rowIndex, + column_index: cellInfo.columnIndex, + value: cellInfo.value, + prev: cellInfo.prev, + }; + }); + + makeRequest( + "outputRPC", + [ + // id: string + id, + // handler: string + "cells_update", + // list[OnCellUpdateParams] + updateInfos, + ], + (values: ResponseValue[]) => { + setData((draft) => { + values.forEach((value: string, i: number) => { + const { rowIndex, columnIndex } = cellInfos[i]; + // const row = draft[rowIndex]; + // // console.log( + // // "Setting new value!", + // // value, + // // columnId, + // // draft[rowIndex] + // // ); + + draft[rowIndex][columnIndex] = value; + }); + }); + setCellEditMap((draft) => { + values.forEach((value: string, i: number) => { + const { rowIndex, columnIndex } = cellInfos[i]; + const key = `[${rowIndex}, ${columnIndex}]`; + + const obj = + draft.get(key) ?? ({} as { value: string; state: CellState }); + obj.value = value; + obj.state = CellState.EditSuccess; + // console.log("Setting cell edit map"); + draft.set(key, obj); + }); + }); + onSuccess(values); + }, + (err: string) => { + onError(err); + }, + undefined + ); +} diff --git a/js/dataframe/index.tsx b/js/dataframe/index.tsx index 877466f5d..21b81adb4 100644 --- a/js/dataframe/index.tsx +++ b/js/dataframe/index.tsx @@ -1,5 +1,4 @@ -import css from "./styles.scss"; - +/* eslint-disable react-hooks/rules-of-hooks */ import { Column, ColumnDef, @@ -12,6 +11,7 @@ import { useReactTable, } from "@tanstack/react-table"; import { Virtualizer, useVirtualizer } from "@tanstack/react-virtual"; +import { enableMapSet } from "immer"; import React, { FC, StrictMode, @@ -20,22 +20,67 @@ import React, { useLayoutEffect, useMemo, useRef, + useState, } from "react"; import { Root, createRoot } from "react-dom/client"; import { ErrorsMessageValue } from "rstudio-shiny/srcts/types/src/shiny/shinyapp"; +import { useImmer } from "use-immer"; +import { CellState, TableBodyCell } from "./cell"; import { findFirstItemInView, getStyle } from "./dom-utils"; import { Filter, useFilter } from "./filter"; import { SelectionMode, useSelection } from "./selection"; import { SortArrow } from "./sort-arrows"; +import css from "./styles.scss"; import { useTabindexGroup } from "./tabindex-group"; import { useSummary } from "./table-summary"; -import { PandasData, TypeHint } from "./types"; +import { EditMode, PandasData, TypeHint } from "./types"; +// setTimeout(() => { +// console.log("Making request!"); +// makeRequest( +// "dataframeUpdateCell", +// [1, 2, 3], +// (value: ResponseValue) => { +// console.log("success!", value); +// }, +// (err: string) => { +// console.error("error!", err); +// }, +// undefined +// ); +// }, 2000); + +// TODO-barret; + +// export interface PandasData { +// columns: ReadonlyArray; +// // index: ReadonlyArray; +// data: unknown[][]; +// type_hints?: ReadonlyArray; +// options: DataGridOptions; +// } declare module "@tanstack/table-core" { interface ColumnMeta { + colIndex: number; typeHint: TypeHint; } + // interface TableMeta { + // updateCellsData: (cellInfos: UpdateCellData[]) => void; + // } } + +// // TODO-barret-future; Use window.setSelectionRange() and this method to reselect text when scrolling out of view +// const useSelectedText = () => { +// const [text, setText] = useState(""); +// const select = () => { +// const selected = window.getSelection() as Selection; +// setText(selected.toString()); +// }; +// return [select, text] as const; +// }; + +// + // TODO: Right-align numeric columns, maybe change font // TODO: Explicit column widths // TODO: Filtering @@ -65,6 +110,33 @@ const ShinyDataGrid: FC> = (props) => { const theadRef = useRef(null); const tbodyRef = useRef(null); + // const [target, setTarget] = useState(null); + + // const [editingInfo, setEdtingInfo] = useImmer({ + // rowIndex: null, + // columnId: null, + // }); + const [editRowIndex, setEditRowIndex] = useState(null); + const [editColumnIndex, setEditColumnIndex] = useState(null); + + useEffect(() => { + console.log("editing info!", editRowIndex, editColumnIndex); + }, [editColumnIndex, editRowIndex]); + + const dataFrameModeIsMissing = data.options["mode"] ? false : true; + const dataFrameMode = data.options["mode"] ?? "none"; + + const canEdit = dataFrameMode === EditMode.Edit; + + const [cellEditMap, setCellEditMap] = useImmer< + Map + >(new Map()); + enableMapSet(); + + useEffect(() => { + console.log("editing info!", editRowIndex, editColumnIndex); + }, [editColumnIndex, editRowIndex]); + const coldefs = useMemo[]>( () => columns.map((colname, i) => { @@ -79,25 +151,51 @@ const ShinyDataGrid: FC> = (props) => { typeHint.type === "numeric" ? "inNumberRange" : "includesString", header: colname, meta: { + colIndex: i, typeHint: typeHint, }, + cell: ({ getValue }) => { + return getValue() as string; + }, }; }), - [columns] + [columns, type_hints, editRowIndex, editColumnIndex, cellEditMap] ); - // Not sure if it's even necessary to clone - const dataClone = useMemo(() => [...rowData], [rowData]); + // function useSkipper() { + // const shouldSkipRef = React.useRef(true); + // const shouldSkip = shouldSkipRef.current; + + // // Wrap a function with this to skip a pagination reset temporarily + // const skip = React.useCallback(() => { + // shouldSkipRef.current = false; + // }, []); + + // React.useEffect(() => { + // shouldSkipRef.current = true; + // }); + + // return [shouldSkip, skip] as const; + // } + // const [autoResetPageIndex, skipAutoResetPageIndex] = useSkipper(); + + const dataOriginal = useMemo(() => rowData, [rowData]); + const [dataState, setData] = useImmer(rowData); const filterOpts = useFilter(withFilters); const options: TableOptions = { - data: dataClone, + data: dataState, columns: coldefs, getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), ...filterOpts, - //debugAll: true, + // debugAll: true, + // Provide our updateCellsData function to our table meta + // autoResetPageIndex, + // meta: { + // updateCellsData: (cellInfos: UpdateCellData[]) => {}, + // }, }; const table = useReactTable(options); @@ -114,7 +212,7 @@ const ShinyDataGrid: FC> = (props) => { // Reset scroll when dataset changes useLayoutEffect(() => { rowVirtualizer.scrollToOffset(0); - }, [data]); + }, [data, rowVirtualizer]); const totalSize = rowVirtualizer.getTotalSize(); const virtualRows = rowVirtualizer.getVirtualItems(); @@ -144,8 +242,20 @@ const ShinyDataGrid: FC> = (props) => { tableStyle === "grid" ? "shiny-data-grid-grid" : "shiny-data-grid-table"; const tableClass = tableStyle === "table" ? "table table-sm" : null; - const rowSelectionMode = - data.options["row_selection_mode"] ?? SelectionMode.MultiNative; + // ### Row selection ############################################################### + // rowSelectionMode + + // If a row selection mode matches one of the enum values, use it. Otherwise, default to none (e.g. `dataFrameMode == "edit"`). + const rowSelectionModeValue = Object.values(SelectionMode).includes( + dataFrameMode as SelectionMode + ) + ? (dataFrameMode as SelectionMode) + : SelectionMode.None; + // If nothing is provided, default to multinative mode + const rowSelectionMode = dataFrameModeIsMissing + ? SelectionMode.None + : rowSelectionModeValue; + const canSelect = rowSelectionMode !== SelectionMode.None; const canMultiSelect = rowSelectionMode === SelectionMode.MultiNative || @@ -178,6 +288,31 @@ const ShinyDataGrid: FC> = (props) => { findKeysBetween(table.getSortedRowModel(), fromKey, toKey) ); + useEffect(() => { + const handleMessage = (event: CustomEvent<{ keys: number[] }>) => { + // We convert "None" to an empty tuple on the python side + // so an empty array indicates that selection should be cleared. + if (!event.detail.keys.length) { + rowSelection.clear(); + } else { + rowSelection.setMultiple(event.detail.keys.map(String)); + } + }; + + const element = document.getElementById(id); + element.addEventListener( + "updateRowSelection", + handleMessage as EventListener + ); + + return () => { + element.removeEventListener( + "updateRowSelection", + handleMessage as EventListener + ); + }; + }, [id, rowSelection]); + useEffect(() => { if (id) { if (rowSelectionMode === SelectionMode.None) { @@ -193,8 +328,31 @@ const ShinyDataGrid: FC> = (props) => { ); } } - }, [[...rowSelection.keys()]]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [id, rowSelectionMode, [...rowSelection.keys()]]); + + // ### End row selection ############################################################ + + // ### Editable cells ############################################################### + // type TKey = DOMStringMap[string]: string + type TKey = typeof HTMLTableRowElement.prototype.dataset.key; + type TElement = HTMLTableRowElement; + if (canEdit && canSelect) { + // TODO-barret; maybe listen for a double click? + // Is is possible to rerender on double click independent of the row selection? + console.error( + "Should not have editable and row selection at the same time" + ); + } + + // ### End editable cells ########################################################### + + // + + // + + // const tbodyTabItems = React.useCallback( () => tbodyRef.current.querySelectorAll("[tabindex='-1']"), [tbodyRef.current] @@ -204,11 +362,13 @@ const ShinyDataGrid: FC> = (props) => { }); // Reset sorting and selection whenever dataset changes. (Should we do this?) + // NOTE-2024-02-21-barret; Maybe only reset sorting if the column information changes? useEffect(() => { return () => { table.resetSorting(); rowSelection.clear(); }; + // eslint-disable-next-line react-hooks/exhaustive-deps }, [data]); const headerRowCount = table.getHeaderGroups().length; @@ -235,6 +395,8 @@ const ShinyDataGrid: FC> = (props) => { className += " html-fill-item"; } + const maxRowSize = table.getSortedRowModel().rows.length; + return ( <>
> = (props) => { > @@ -319,12 +481,22 @@ const ShinyDataGrid: FC> = (props) => { > {row.getVisibleCells().map((cell) => { return ( - + ); })} @@ -530,3 +702,19 @@ export class ShinyDataFrameOutput extends HTMLElement { } customElements.define("shiny-data-frame", ShinyDataFrameOutput); + +// This is the shim between Shiny's messaging passing behaviour and React. +// The python code sends a custom message which includes an id, handler +// and obbject and we use that information to dispatch it to the +// react listener. +// It would be better to have something similar to session.send_input_message +// for updating outputs, but that requires changes to ShinyJS. +$(function () { + Shiny.addCustomMessageHandler("receiveMessage", function (message) { + const evt = new CustomEvent(message.handler, { + detail: message.obj, + }); + const el = document.getElementById(message.id); + el.dispatchEvent(evt); + }); +}); diff --git a/js/dataframe/request.ts b/js/dataframe/request.ts new file mode 100644 index 000000000..0aa934443 --- /dev/null +++ b/js/dataframe/request.ts @@ -0,0 +1,39 @@ +// type JobId = string; +// type UploadUrl = string; +// type UploadInitValue = { jobId: JobId; uploadUrl: UploadUrl }; +// type UploadEndValue = never; + +export type ResponseValue = any; + +export type OnSuccessRequest = (value: ResponseValue) => void; +export type OnErrorRequest = (err: string) => void; + +// Websocket messages are normally one-way--i.e. the client passes a +// message to the server but there is no way for the server to provide +// a response to that specific message. makeRequest provides a way to +// do asynchronous RPC over websocket. Each request has a method name +// and arguments, plus optionally one or more binary blobs can be +// included as well. The request is tagged with a unique number that +// the server will use to label the corresponding response. +// +// @param method A string that tells the server what logic to run. +// @param args An array of objects that should also be passed to the +// server in JSON-ified form. +// @param onSuccess A function that will be called back if the server +// responds with success. If the server provides a value in the +// response, the function will be called with it as the only argument. +// @param onError A function that will be called back if the server +// responds with error, or if the request fails for any other reason. +// The parameter to onError will be a string describing the error. +// @param blobs Optionally, an array of Blob, ArrayBuffer, or string +// objects that will be made available to the server as part of the +// request. Strings will be encoded using UTF-8. +export function makeRequest( + method: string, + args: unknown[], + onSuccess: OnSuccessRequest, + onError: OnErrorRequest, + blobs: Array | undefined +) { + window.Shiny.shinyapp.makeRequest(method, args, onSuccess, onError, blobs); +} diff --git a/js/dataframe/selection.tsx b/js/dataframe/selection.tsx index 14382341d..a4da92920 100644 --- a/js/dataframe/selection.tsx +++ b/js/dataframe/selection.tsx @@ -5,6 +5,7 @@ import { ImmutableSet } from "./immutable-set"; export interface SelectionSet { has(key: TKey): boolean; set(key: TKey, selected: boolean): void; + setMultiple(key_arr: TKey[]): void; clear(): void; keys(): ImmutableSet; itemHandlers(): { @@ -15,9 +16,9 @@ export interface SelectionSet { export enum SelectionMode { None = "none", - Single = "single", - Multiple = "multiple", - MultiNative = "multi-native", + Single = "single_row", + Multiple = "multiple_row", + MultiNative = "multi-native_row", } export function useSelection( @@ -111,6 +112,10 @@ export function useSelection( } }, + setMultiple(key_arr: TKey[]) { + setSelectedKeys(ImmutableSet.just(...key_arr)); + }, + clear() { setSelectedKeys(selectedKeys.clear()); }, diff --git a/js/dataframe/styles.scss b/js/dataframe/styles.scss index 489b7246b..a0b1addde 100644 --- a/js/dataframe/styles.scss +++ b/js/dataframe/styles.scss @@ -4,7 +4,7 @@ box-sizing: border-box; } -.shiny-data-grid { +shiny-data-frame { --shiny-datagrid-font-size: 0.9em; --shiny-datagrid-padding-x: 0.5em; --shiny-datagrid-padding-y: 0.3em; @@ -27,6 +27,19 @@ ); --shiny-datagrid-grid-body-selected-bgcolor: #b4d5fe; --shiny-datagrid-grid-body-selected-color: var(--bs-dark); + + // 2024-03-01: Greg: Do not use warning or info bs colors! Their contrast on white is not enough + // Saved cells + --shiny-datagrid-table-cell-edit-success-border-color: color-mix(in srgb, var(--bs-success) 20%, transparent); + --shiny-datagrid-table-cell-edit-success-border-style: var(--shiny-datagrid-grid-gridlines-style); + --shiny-datagrid-table-cell-edit-success-bgcolor: color-mix(in srgb, var(--bs-success) 10%, transparent); + // Failed to save + --shiny-datagrid-table-cell-edit-failure-border-color: color-mix(in srgb, var(--bs-danger) 40%, transparent); + --shiny-datagrid-table-cell-edit-failure-border-style: var(--shiny-datagrid-grid-gridlines-style); + --shiny-datagrid-table-cell-edit-failure-bgcolor: color-mix(in srgb, var(--bs-danger) 10%, transparent); + // Saving cells + --shiny-datagrid-table-cell-edit-saving-color: var(--bs-gray-500); + --shiny-datagrid-table-cell-edit-saving-font-style: italic; } .shiny-data-grid svg.sort-arrow { @@ -219,3 +232,26 @@ shiny-data-frame { flex: 0 0 auto; } } + +shiny-data-frame .shiny-data-grid-summary { + font-size: var(--shiny-datagrid-font-size); + padding-top: 0.3em; +} +.shiny-data-grid > table > tbody > tr > td { + @keyframes fadeSuccessBorder { + 0% { border: 2px var(--shiny-datagrid-table-cell-edit-success-border-style) var(--shiny-datagrid-table-cell-edit-success-border-color); } + 50% { border: 2px var(--shiny-datagrid-table-cell-edit-success-border-style) var(--shiny-datagrid-table-cell-edit-success-border-color); } + } + &.cell-edit-success { + animation: fadeSuccessBorder 6s; + } + &.cell-edit-saving { + color: var(--shiny-datagrid-table-cell-edit-saving-color); + font-style: var(--shiny-datagrid-table-cell-edit-saving-font-style); + } + + &.cell-edit-failure { + border: 2px var(--shiny-datagrid-table-cell-edit-failure-border-style) var(--shiny-datagrid-table-cell-edit-failure-border-color); + background-color: var(--shiny-datagrid-table-cell-edit-failure-bgcolor); + } +} diff --git a/js/dataframe/types.ts b/js/dataframe/types.ts index 3850dda1e..66a5f200c 100644 --- a/js/dataframe/types.ts +++ b/js/dataframe/types.ts @@ -1,5 +1,10 @@ import { SelectionMode } from "./selection"; +export enum EditMode { + None = "none", + Edit = "edit", +} + export interface TypeHint { type: "string" | "numeric" | "categorical" | "unknown"; } @@ -12,7 +17,9 @@ export interface CategoricalTypeHint extends TypeHint { export interface DataGridOptions { style?: "table" | "grid"; summary?: boolean | string; - row_selection_mode?: SelectionMode; + mode?: SelectionMode | EditMode; + // row_selection_mode?: SelectionMode; + // editable?: boolean; filters?: boolean; width?: string; height?: string; diff --git a/js/package-lock.json b/js/package-lock.json index 876a3f37b..dec5ce955 100644 --- a/js/package-lock.json +++ b/js/package-lock.json @@ -8,7 +8,8 @@ "name": "shiny-dataframe-binding", "license": "MIT", "dependencies": { - "@tanstack/react-table": "^8.9.3" + "@tanstack/react-table": "^8.9.3", + "use-immer": "^0.9.0" }, "devDependencies": { "@preact/compat": "^17.1.2", @@ -23,6 +24,7 @@ "esbuild": "^0.18.11", "esbuild-sass-plugin": "^2.9.0", "eslint-plugin-react": "^7.25.3", + "eslint-plugin-react-hooks": "^4.6.0", "postcss": "^8.4.24", "postcss-modules": "^6.0.0", "preact": "^10.15.1", @@ -2000,6 +2002,18 @@ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8" } }, + "node_modules/eslint-plugin-react-hooks": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-4.6.0.tgz", + "integrity": "sha512-oFc7Itz9Qxh2x4gNHStv3BqJq54ExXmfC+a1NjAta66IAN87Wu0R/QArgIS9qKzX3dXKPI9H5crl9QchNMY9+g==", + "dev": true, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0" + } + }, "node_modules/eslint-plugin-react/node_modules/doctrine": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", @@ -2592,6 +2606,16 @@ "node": ">= 4" } }, + "node_modules/immer": { + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/immer/-/immer-10.0.3.tgz", + "integrity": "sha512-pwupu3eWfouuaowscykeckFmVTpqbzW+rXFCX8rQLkZzM9ftBmU/++Ra+o+L27mz03zJTlyV4UUr+fdKNffo4A==", + "peer": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, "node_modules/immutable": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/immutable/-/immutable-4.3.0.tgz", @@ -4093,6 +4117,15 @@ "punycode": "^2.1.0" } }, + "node_modules/use-immer": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/use-immer/-/use-immer-0.9.0.tgz", + "integrity": "sha512-/L+enLi0nvuZ6j4WlyK0US9/ECUtV5v9RUbtxnn5+WbtaXYUaOBoKHDNL9I5AETdurQ4rIFIj/s+Z5X80ATyKw==", + "peerDependencies": { + "immer": ">=2.0.0", + "react": "^16.8.0 || ^17.0.1 || ^18.0.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -5460,6 +5493,13 @@ } } }, + "eslint-plugin-react-hooks": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-4.6.0.tgz", + "integrity": "sha512-oFc7Itz9Qxh2x4gNHStv3BqJq54ExXmfC+a1NjAta66IAN87Wu0R/QArgIS9qKzX3dXKPI9H5crl9QchNMY9+g==", + "dev": true, + "requires": {} + }, "eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", @@ -5854,6 +5894,12 @@ "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", "dev": true }, + "immer": { + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/immer/-/immer-10.0.3.tgz", + "integrity": "sha512-pwupu3eWfouuaowscykeckFmVTpqbzW+rXFCX8rQLkZzM9ftBmU/++Ra+o+L27mz03zJTlyV4UUr+fdKNffo4A==", + "peer": true + }, "immutable": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/immutable/-/immutable-4.3.0.tgz", @@ -6897,6 +6943,12 @@ "punycode": "^2.1.0" } }, + "use-immer": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/use-immer/-/use-immer-0.9.0.tgz", + "integrity": "sha512-/L+enLi0nvuZ6j4WlyK0US9/ECUtV5v9RUbtxnn5+WbtaXYUaOBoKHDNL9I5AETdurQ4rIFIj/s+Z5X80ATyKw==", + "requires": {} + }, "util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", diff --git a/js/package.json b/js/package.json index 0d46d97a9..b202d7bce 100644 --- a/js/package.json +++ b/js/package.json @@ -7,7 +7,7 @@ "bundle": "tsx build.ts", "build": "npm run lint && npm run bundle", "watch": "npx nodemon --exec 'npm run build' --ext '*' --ignore dist/ --ignore esbuild-metadata.json", - "build-fast": "tsx build.ts", + "build-fast": "tsx build.ts --minify=false", "watch-fast": "npx nodemon --exec 'npm run build-fast' --ext '*' --ignore dist/ --ignore esbuild-metadata.json" }, "devDependencies": { @@ -23,6 +23,7 @@ "esbuild": "^0.18.11", "esbuild-sass-plugin": "^2.9.0", "eslint-plugin-react": "^7.25.3", + "eslint-plugin-react-hooks": "^4.6.0", "postcss": "^8.4.24", "postcss-modules": "^6.0.0", "preact": "^10.15.1", @@ -34,6 +35,7 @@ "typescript": "^5.0.3" }, "dependencies": { - "@tanstack/react-table": "^8.9.3" + "@tanstack/react-table": "^8.9.3", + "use-immer": "^0.9.0" } } diff --git a/setup.cfg b/setup.cfg index 1096d0fbb..9da4fcf0f 100644 --- a/setup.cfg +++ b/setup.cfg @@ -90,6 +90,7 @@ test = rsconnect-python scikit-learn folium + palmerpenguins dev = black>=24.0 diff --git a/shiny/_static.py b/shiny/_static.py index 96583bcd3..96d00c6ef 100644 --- a/shiny/_static.py +++ b/shiny/_static.py @@ -36,9 +36,16 @@ def remove_shinylive_local( def get_default_shinylive_dir() -> Path: - import appdirs # pyright: ignore[reportMissingTypeStubs] - - return Path(appdirs.user_cache_dir("shiny")) / "shinylive" # pyright: ignore + import appdirs + + return ( + Path( + appdirs.user_cache_dir( # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] + "shiny" + ) + ) + / "shinylive" + ) def _installed_shinylive_versions(shinylive_dir: Optional[Path] = None) -> list[str]: diff --git a/shiny/api-examples/data_frame/app-core.py b/shiny/api-examples/data_frame/app-core.py index a592ef238..809bd263e 100644 --- a/shiny/api-examples/data_frame/app-core.py +++ b/shiny/api-examples/data_frame/app-core.py @@ -44,11 +44,11 @@ def summary_data(): @reactive.calc def filtered_df(): - req(input.summary_data_selected_rows()) + req(summary_data.input_selected_rows()) - # input.summary_data_selected_rows() is a tuple, so we must convert it to list, + # summary_data.input_selected_rows() is a tuple, so we must convert it to list, # as that's what Pandas requires for indexing. - selected_idx = list(input.summary_data_selected_rows()) + selected_idx = list(summary_data.input_selected_rows()) countries = summary_df.iloc[selected_idx]["country"] # Filter data for selected countries return df[df["country"].isin(countries)] diff --git a/shiny/api-examples/data_frame/app-express.py b/shiny/api-examples/data_frame/app-express.py index 24a5b47ba..b1064eb9e 100644 --- a/shiny/api-examples/data_frame/app-express.py +++ b/shiny/api-examples/data_frame/app-express.py @@ -66,12 +66,12 @@ def country_detail_percap(): @reactive.calc def filtered_df(): - req(input.summary_data_selected_rows()) + req(summary_data.input_selected_rows()) - # input.summary_data_selected_rows() is a tuple, so we must convert it to list, + # summary_data.input_selected_rows() is a tuple, so we must convert it to list, # as that's what Pandas requires for indexing. - selected_idx = list(input.summary_data_selected_rows()) + selected_idx = list(summary_data.input_selected_rows()) countries = summary_df.iloc[selected_idx]["country"] # Filter data for selected countries return df[df["country"].isin(countries)] diff --git a/shiny/express/_mock_session.py b/shiny/express/_mock_session.py index 9478dc078..998af63d7 100644 --- a/shiny/express/_mock_session.py +++ b/shiny/express/_mock_session.py @@ -24,7 +24,7 @@ class ExpressMockSession: def __init__(self): self.ns = Root self.input = Inputs({}) - self.output = Outputs(cast(Session, self), self.ns, {}, {}) + self.output = Outputs(cast(Session, self), self.ns, outputs={}) # Application-level (not session-level) options that may be set via app_opts(). self.app_opts: AppOpts = {} diff --git a/shiny/render/_dataframe.py b/shiny/render/_dataframe.py index 16c0509f3..9f00deec7 100644 --- a/shiny/render/_dataframe.py +++ b/shiny/render/_dataframe.py @@ -2,24 +2,145 @@ import abc import json -from typing import TYPE_CHECKING, Any, Literal, Protocol, Union, cast, runtime_checkable +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + Any, + Literal, + Optional, + Protocol, + Sequence, + TypedDict, + Union, + cast, + runtime_checkable, +) from htmltools import Tag -from .. import ui +from .. import reactive, ui +from .._deprecated import ShinyDeprecationWarning from .._docstring import add_example, no_example +from .._typing_extensions import Self +from ..session._utils import get_current_session, require_active_session from ._dataframe_unsafe import serialize_numpy_dtypes -from .renderer import Jsonifiable, Renderer +from .renderer import Jsonifiable, Renderer, ValueFn if TYPE_CHECKING: import pandas as pd + from ..session._utils import Session + +# TODO-barret-future; make generic? By currently accepting `object`, it is difficult to capture the generic type of the data. +DataFrameResult = Union[None, "pd.DataFrame", "DataGrid", "DataTable"] + + +class CellUpdateFn(Protocol): + async def __call__( + self, + *, + info: CellUpdateInfo, + # TODO-barret; Remove `**kwargs` + **kwargs: Any, # future proofing + ) -> Any: ... + + +class CellUpdateInfo(TypedDict): + row_index: int + column_index: int + value: str + prev: str + + +class CellsUpdateFn(Protocol): + async def __call__( + self, + *, + infos: list[CellUpdateInfo], + # TODO-barret; Remove `**kwargs` + **kwargs: Any, # future proofing + ) -> Any: ... +@dataclass +class CellPatch: + row_index: int + # TODO-barret; Safeguard against columns with the same name + # TODO-barret; Use column index instead of name + column_index: int + value: str + prev: str + class AbstractTabularData(abc.ABC): @abc.abstractmethod def to_payload(self) -> Jsonifiable: ... +EditMode = Literal["none", "edit"] +RowSelectionMode = Literal["none", "single_row", "multiple_row"] +# ColumnSelectionMode = Literal["single_col", "multiple_col"] +DataFrameMode = Union[ + EditMode, + RowSelectionMode, + # ColumnSelectionMode, + Literal["none"], +] + +RowSelectionModeDeprecated = Literal["single", "multiple", "none", "deprecated"] + + +class SelectedIndicies(TypedDict): + rows: tuple[int] | None + columns: tuple[int] | None + + +# # TODO-future; Use `dataframe-api-compat>=0.2.6` to injest dataframes and return standardized dataframe structures +# # TODO-future: Find this type definition: https://github.com/data-apis/dataframe-api-compat/blob/273c0be45962573985b3a420869d0505a3f9f55d/dataframe_api_compat/polars_standard/dataframe_object.py#L22 +# # Related: https://data-apis.org/dataframe-api-compat/quick_start/ +# # Related: https://github.com/data-apis/dataframe-api-compat +# # Related: `.collect()` is needed. Boo. : https://data-apis.org/dataframe-api-compat/basics/dataframe/#__tabbed_2_2 +# from dataframe_api import DataFrame as DataFrameStandard +# class ConsortiumNamespaceDataframe(Protocol): +# def __dataframe_namespace__(self) -> DataFrameStandard: ... +# class ConsortiumStandardDataframe(Protocol): +# def __dataframe_consortium_standard__(self,api_version: str) -> DataFrameStandard: ... +# # https://data-apis.org/dataframe-protocol/latest/purpose_and_scope.html#this-dataframe-protocol +# def get_compliant_df( +# df: ConsortiumNamespaceDataframe | ConsortiumStandardDataframe, +# ) -> DataFrameStandard: +# """Utility function to support programming against a dataframe API""" +# if hasattr(df, "__dataframe_namespace__"): +# # Is already Standard-compliant DataFrame, nothing to do here. +# pass +# elif hasattr(df, "__dataframe_consortium_standard__"): +# # Convert to Standard-compliant DataFrame. +# df = df.__dataframe_consortium_standard__(api_version="2023.11-beta") +# else: +# # Here we can raise an exception if we only want to support compliant dataframes, +# # or convert to our default choice of dataframe if we want to accept (e.g.) dicts +# raise TypeError( +# "Expected Standard-compliant DataFrame, or DataFrame with Standard-compliant implementation" +# ) +# return df + + +def as_mode( + mode: DataFrameMode, + *, + row_selection_mode: RowSelectionModeDeprecated, +) -> DataFrameMode: + if row_selection_mode == "deprecated": + return mode + ShinyDeprecationWarning( + "`DataGraid(row_selection_mode=)` has been superseded by `DataGrid(mode=)`." + ' Please use `DataGrid(mode="{row_selection_mode}_row")` instead.' + ) + if row_selection_mode == "none": + return "none" + + mode = cast(RowSelectionMode, f"{row_selection_mode}_row") + return mode + + @add_example(ex_dir="../api-examples/data_frame") class DataGrid(AbstractTabularData): """ @@ -50,10 +171,16 @@ class DataGrid(AbstractTabularData): `"Viendo filas {start} a {end} de {total}"`. filters If `True`, shows a row of filter inputs below the headers, one for each column. + mode + Single string to set the mode of the table. + + Supported values: + * Use `"none"` to disable any cell selections or editing. + * Use `"single_row"` to allow a single row to be selected at a time. + * Use `"multiple_row"` to allow multiple rows to be selected by clicking on them individually. + * Use `"edit"` to allow editing of the cells in the table. row_selection_mode - Use `"none"` to disable row selection, `"single"` to allow a single row to be - selected at a time, and `"multiple"` to allow multiple rows to be selected by - clicking on them individually. + Deprecated. Please use `mode={row_selection_mode}_row` instead. Returns ------- @@ -76,7 +203,8 @@ def __init__( height: Union[str, float, None] = None, summary: Union[bool, str] = True, filters: bool = False, - row_selection_mode: Literal["none", "single", "multiple"] = "none", + mode: DataFrameMode = "none", + row_selection_mode: RowSelectionModeDeprecated = "deprecated", ): import pandas as pd @@ -92,7 +220,7 @@ def __init__( self.height = height self.summary = summary self.filters = filters - self.row_selection_mode = row_selection_mode + self.mode: DataFrameMode = as_mode(mode, row_selection_mode=row_selection_mode) def to_payload(self) -> Jsonifiable: res = serialize_pandas_df(self.data) @@ -101,7 +229,7 @@ def to_payload(self) -> Jsonifiable: height=self.height, summary=self.summary, filters=self.filters, - row_selection_mode=self.row_selection_mode, + mode=self.mode, style="grid", fill=self.height is None, ) @@ -138,10 +266,16 @@ class DataTable(AbstractTabularData): `"Viendo filas {start} a {end} de {total}"`. filters If `True`, shows a row of filter inputs below the headers, one for each column. + mode + Single string to set the mode of the table. + + Supported values: + * Use `"none"` to disable any cell selections or editing. + * Use `"single_row"` to allow a single row to be selected at a time. + * Use `"multiple_row"` to allow multiple rows to be selected by clicking on them individually. + * Use `"edit"` to allow editing of the cells in the table. row_selection_mode - Use `"none"` to disable row selection, `"single"` to allow a single row to be - selected at a time, and `"multiple"` to allow multiple rows to be selected by - clicking on them individually. + Deprecated. Please use `mode={row_selection_mode}_row` instead. Returns ------- @@ -164,9 +298,8 @@ def __init__( height: Union[str, float, None] = "500px", summary: Union[bool, str] = True, filters: bool = False, - row_selection_mode: Union[ - Literal["none"], Literal["single"], Literal["multiple"] - ] = "none", + mode: DataFrameMode = "none", + row_selection_mode: Literal["deprecated"] = "deprecated", ): import pandas as pd @@ -182,7 +315,7 @@ def __init__( self.height = height self.summary = summary self.filters = filters - self.row_selection_mode = row_selection_mode + self.mode: DataFrameMode = as_mode(mode, row_selection_mode=row_selection_mode) def to_payload(self) -> Jsonifiable: res = serialize_pandas_df(self.data) @@ -191,13 +324,21 @@ def to_payload(self) -> Jsonifiable: height=self.height, summary=self.summary, filters=self.filters, - row_selection_mode=self.row_selection_mode, + mode=self.mode, style="table", ) return res def serialize_pandas_df(df: "pd.DataFrame") -> dict[str, Any]: + columns = df.columns.tolist() + columns_set = set(columns) + if len(columns_set) != len(columns): + raise ValueError( + "The column names of the pandas DataFrame are not unique." + " This is not supported by the data_frame renderer." + ) + # Currently, we don't make use of the index; drop it so we don't error trying to # serialize it or something df = df.reset_index(drop=True) @@ -212,9 +353,6 @@ def serialize_pandas_df(df: "pd.DataFrame") -> dict[str, Any]: return res -DataFrameResult = Union[None, "pd.DataFrame", DataGrid, DataTable] - - @add_example() class data_frame(Renderer[DataFrameResult]): """ @@ -238,11 +376,14 @@ class data_frame(Renderer[DataFrameResult]): Row selection ------------- When using the row selection feature, you can access the selected rows by using the - `input._selected_rows()` function, where `` is the `id` of the - :func:`~shiny.ui.output_data_frame`. The value returned will be `None` if no rows - are selected, or a tuple of integers representing the indices of the selected rows. - To filter a pandas data frame down to the selected rows, use - `df.iloc[list(input._selected_rows())]`. + `.input_selected_rows()` method, where `` + is the render function name that corresponds with the `id=` used in + :func:`~shiny.ui.outout_data_frame`. Internally, this method retrieves the selected + row value from session's `input._selected_rows()` value. The value returned will + be `None` if the row selection mode is `"none"`, or a tuple of integers representing + the indices of the selected rows. If no rows have been selected (while in a non-`"none"` + row selection mode), an empty tuple will be returned. To filter a pandas data frame + down to the selected rows, use `df.iloc[list(input._selected_rows())]`. Tip ---- @@ -258,12 +399,278 @@ class data_frame(Renderer[DataFrameResult]): objects you can return from the rendering function to specify options. """ - # `.input_selected_rows()` method, where `` is the render function name that corresponds with the `id=` used in :func:`~shiny.ui.outout_data_frame`. Internally, this method retrieves the selected row value from session's `input._selected_rows()` value. The value returned will be `None` if no rows + _session: Session | None # Do not use. Use `_get_session()` instead + + _value: reactive.Value[DataFrameResult | None] + # _data: reactive.Value[pd.DataFrame | None] + + handle_cell_update: CellUpdateFn + handle_cells_update: CellsUpdateFn + + cell_patches: reactive.Value[list[CellPatch]] + + data: reactive.Calc_[pd.DataFrame] + """ + Reactive value of the data frame's output data. + """ + data_patched: reactive.Calc_[pd.DataFrame] + """ + Reactive value of the data frame's edited output data. + """ + table_mode: reactive.Calc_[DataFrameMode] + """ + Reactive value of the data frame's row selection mode. + """ + + input_selected: reactive.Calc_[SelectedIndicies | None] + """ + Reactive value of selected rows indicies. + + This method is a wrapper around `input._selected_rows()`, where `` is + the `id` of the data frame output. This method returns the selected rows and + will cause reactive updates as the selected rows change. + + Returns + ------- + : + * `None` if the row selection mode is None + * `tuple[int]` representing the indices of the selected rows. If no rowws are selected + """ + + data_selected: reactive.Calc_[pd.DataFrame] + """ + Reactive value that returns the edited data frame subsetted to the selected area. + + Returns + ------- + : + * If the row selection mode is `None`, the calculation will throw a silent error (`req(False)`) + * The edited data (`.data_patched()`) at the indices of the selected rows + """ + + def _init_reactives(self) -> None: + + import pandas as pd + + from .. import req + + # Init + self._value: reactive.Value[Union[DataFrameResult, None]] = reactive.Value(None) + self.cell_patches: reactive.Value[list[CellPatch]] = reactive.Value([]) + + @reactive.calc + def self_data() -> pd.DataFrame: + value = self._value() + req(value) + + if not isinstance(value, (DataGrid, DataTable)): + raise TypeError( + f"Unsupported type returned from render function: {type(value)}. Expected `DataGrid` or `DataTable`" + ) + + if not isinstance(value.data, pd.DataFrame): + raise TypeError(f"Unexpected type for self._data: {type(value.data)}") + + return value.data + + self.data = self_data + + @reactive.calc + def self_table_mode() -> DataFrameMode: + value = self._value() + req(value) + if not isinstance(value, (DataGrid, DataTable)): + raise TypeError( + f"Unsupported type returned from render function: {type(value)}. Expected `DataGrid` or `DataTable`" + ) + + return value.mode + + self.table_mode = self_table_mode + + @reactive.calc + def self_input_selected() -> SelectedIndicies | None: + mode = self.table_mode() + if mode == "none": + return None + return { + "rows": self._get_session().input[f"{self.output_id}_selected_rows"](), + "columns": None, + } + + self.input_selected = self_input_selected + + @reactive.calc + def self_data_selected() -> pd.DataFrame: + indicies = self.input_selected() + if indicies is None: + req(False) + raise RuntimeError("This should never be reached for typing purposes") + + data_selected = self.data_patched() + if indicies["rows"] is not None: + data_selected = data_selected.iloc[list(indicies["rows"])] + if indicies["columns"] is not None: + data_selected = data_selected.iloc[:, list(indicies["columns"])] + return data_selected + + self.data_selected = self_data_selected + + @reactive.calc + def self_data_patched() -> pd.DataFrame: + data = self.data() + + with pd.option_context("mode.copy_on_write", True): + for cell_patch in self.cell_patches(): + data.iat[ # pyright: ignore[reportUnknownMemberType] + cell_patch.row_index, + cell_patch.column_index, + ] = cell_patch.value + return data + + self.data_patched = self_data_patched + + def _get_session(self) -> Session: + if self._session is None: + raise RuntimeError( + "The data frame's session can only be accessed within a reactive context" + ) + return self._session + + # TODO-barret; `on` sounds like a registration. Maybe use `set` instead? `set_cell_update_fn`? + def on_cell_update(self, fn: CellUpdateFn) -> Self: + self.handle_cell_update = fn + return self + + def on_cells_update(self, fn: CellsUpdateFn) -> Self: + self.handle_cells_update = fn + return self + + def _init_handlers(self) -> None: + async def _on_cell_update_default( + *, + info: CellUpdateInfo, + # row_index: int, + # column_index: int, + # value: str, + # prev: str, + **kwargs: Any, + ) -> str: + return info["value"] + + async def _on_cells_update_default( + *, + infos: list[CellUpdateInfo], + **kwargs: Any, + ): + with reactive.isolate(): + formatted_values: list[Any] = [] + for update_info in infos: + # row_index = update_info["row_index"] + # column_index = update_info["column_index"] + # value = update_info["value"] + # prev = update_info["prev"] + + formatted_value = await self.handle_cell_update(info=update_info) + # row_index=row_index, + # column_index=column_index, + # value=value, + # prev=prev, + # ) + # TODO-barret; check type here? + # TODO-barret; The return value should be coerced by pandas to the correct type + formatted_values.append(formatted_value) + + return formatted_values + + self.on_cell_update(_on_cell_update_default) + self.on_cells_update(_on_cells_update_default) + # self._add_message_handlers() + + # To be called by session's outputRPC message handler on this data_frame + # Do not change this method unless you update corresponding code in `/js/dataframe/`!! + # @outputRPC_handler + async def _handle_cells_update(self, update_infos: list[CellUpdateInfo]): + + # if len(self.cell_patches()) > 1: + # raise RuntimeError("Barret testing!") + + # Make new array to trigger reactive update + patches = [p for p in self.cell_patches()] + + # Call user's on_cells_update method to retrieve formatted values + # TODO-barret; REname `formatted` to `raw_values` + formatted_values = await self.handle_cells_update(infos=update_infos) + + if len(formatted_values) != len(update_infos): + raise ValueError( + f"The return value of {self.output_id}'s `handle_cells_update()` (typically set by `@{self.output_id}.on_cells_update`) must be a list of the same length as the input list of cell updates. Received {len(formatted_values)} items and expected {len(update_infos)}." + ) + + # Add new patches + for formatted_value, update_info in zip(formatted_values, update_infos): + patches.append( + CellPatch( + row_index=update_info["row_index"], + column_index=update_info["column_index"], + value=formatted_value, + prev=update_info["prev"], + ) + ) + + # Remove duplicate patches + patch_map: dict[tuple[int, int], CellPatch] = {} + for patch in patches: + patch_map[(patch.row_index, patch.column_index)] = patch + patches = list(patch_map.values()) + + # Set new patches + self.cell_patches.set(patches) + + return formatted_values def auto_output_ui(self) -> Tag: return ui.output_data_frame(id=self.output_id) - async def transform(self, value: DataFrameResult) -> Jsonifiable: + def __init__(self, fn: ValueFn[DataFrameResult]): + # Must be done before super().__init__ is called + session = get_current_session() + self._session = session + + super().__init__(fn) + + # Set reactives from calculated properties + self._init_reactives() + # Set update functions + self._init_handlers() + + def _set_output_metadata(self, *, output_id: str) -> None: + super()._set_output_metadata(output_id=output_id) + + # Verify that the session used when creating the renderer is the same session used + # when executing the renderer. This is to prevent a user from creating a renderer + # in one module and setting an output on another. + + active_session = require_active_session(None) + if self._get_session() != active_session: + raise RuntimeError( + "The session used when creating the renderer " + "is not the same session used when executing the renderer. " + "Please file an issue on " + "GitHub " + "with an example of how you are reproducing this error. " + "We would be curious to know your use case!" + ) + + async def render(self) -> Jsonifiable: + # Reset value + self._value.set(None) + self.cell_patches.set([]) + + value = await self.fn() + if value is None: + return None + if not isinstance(value, AbstractTabularData): value = DataGrid( cast_to_pandas( @@ -271,16 +678,55 @@ async def transform(self, value: DataFrameResult) -> Jsonifiable: "@render.data_frame doesn't know how to render objects of type", ) ) + + self._value.set(value) return value.to_payload() - # def input_selected_rows(self) -> Optional[tuple[int]]: - # """ - # When `row_selection_mode` is set to "single" or "multiple" this will return - # a tuple of integers representing the rows selected by a user. - # """ + async def _send_message_to_browser(self, handler: str, obj: dict[str, Any]): + # TODO-barret; capture data in render method + # TODO-barret; invalidate data in render method before user fn has been called + + session = self._get_session() + id = session.ns(self.output_id) + + await session.send_custom_message( + "receiveMessage", + { + "id": id, + "handler": handler, + "obj": obj, + }, + ) + + async def update_row_selection( + self, idx: Optional[Sequence[int] | int] = None + ) -> None: + if idx is None: + idx = () + elif isinstance(idx, int): + idx = (idx,) + + with reactive.isolate(): + mode = self.table_mode() + if mode == "none": + raise ValueError( + "You can't update row selections when row_selection_mode is 'none'" + ) + + if mode == "single_row" and len(idx) > 1: + raise ValueError( + "Attempted to set multiple row selection values when row_selection_mode is 'single'" + ) + await self._send_message_to_browser("updateRowSelection", {"keys": idx}) + + def input_selected_rows(self) -> Optional[tuple[int]]: + """ + When `row_selection_mode` is set to "single" or "multiple" this will return + a tuple of integers representing the rows selected by a user. + """ - # active_session = require_active_session(None) - # return active_session.input[self.output_id + "_selected_rows"]() + active_session = require_active_session(None) + return active_session.input[self.output_id + "_selected_rows"]() @runtime_checkable diff --git a/shiny/render/renderer/_renderer.py b/shiny/render/renderer/_renderer.py index ba4b28d88..bec6e0350 100644 --- a/shiny/render/renderer/_renderer.py +++ b/shiny/render/renderer/_renderer.py @@ -1,24 +1,13 @@ from __future__ import annotations -from typing import ( - Any, - Awaitable, - Callable, - Dict, - Generic, - List, - Optional, - Tuple, - TypeVar, - Union, - cast, -) +from typing import Any, Awaitable, Callable, Generic, Optional, TypeVar, Union, cast from htmltools import MetadataNode, Tag, TagList from ..._docstring import add_example from ..._typing_extensions import Self from ..._utils import is_async_callable, wrap_async +from ...types import Jsonifiable # TODO-barret-future: Double check docs are rendererd # Missing first paragraph from some classes: Example: TransformerMetadata. @@ -52,36 +41,6 @@ """ -# https://github.com/python/cpython/blob/df1eec3dae3b1eddff819fd70f58b03b3fbd0eda/Lib/json/encoder.py#L77-L95 -# +-------------------+---------------+ -# | Python | JSON | -# +===================+===============+ -# | dict | object | -# +-------------------+---------------+ -# | list, tuple | array | -# +-------------------+---------------+ -# | str | string | -# +-------------------+---------------+ -# | int, float | number | -# +-------------------+---------------+ -# | True | true | -# +-------------------+---------------+ -# | False | false | -# +-------------------+---------------+ -# | None | null | -# +-------------------+---------------+ -Jsonifiable = Union[ - str, - int, - float, - bool, - None, - List["Jsonifiable"], - Tuple["Jsonifiable"], - Dict[str, "Jsonifiable"], -] - - DefaultUIFnResult = Union[TagList, Tag, MetadataNode, str] DefaultUIFnResultOrNone = Union[DefaultUIFnResult, None] DefaultUIFn = Callable[[str], DefaultUIFnResultOrNone] diff --git a/shiny/session/_session.py b/shiny/session/_session.py index 12bc3e578..dc6982bb7 100644 --- a/shiny/session/_session.py +++ b/shiny/session/_session.py @@ -36,18 +36,13 @@ from starlette.responses import HTMLResponse, PlainTextResponse, StreamingResponse from starlette.types import ASGIApp -from .._typing_extensions import NotRequired - -if TYPE_CHECKING: - from .._app import App - from .. import _utils, reactive, render from .._connection import Connection, ConnectionClosed from .._deprecated import warn_deprecated from .._docstring import add_example from .._fileupload import FileInfo, FileUploadManager from .._namespaces import Id, ResolvedId, Root -from .._typing_extensions import TypedDict +from .._typing_extensions import NotRequired, TypedDict from .._utils import wrap_async from ..http_staticfiles import FileResponse from ..input_handler import input_handlers @@ -55,6 +50,7 @@ from ..reactive._core import lock, on_flushed from ..render.renderer import Renderer, RendererT from ..types import ( + Jsonifiable, SafeException, SilentCancelOutputException, SilentException, @@ -62,6 +58,9 @@ ) from ._utils import RenderedDeps, read_thunk_opt, session_context +if TYPE_CHECKING: + from .._app import App + class ConnectionState(enum.Enum): Start = 0 @@ -185,13 +184,17 @@ def __init__( self.id: str = id self._conn: Connection = conn self._debug: bool = debug + self._message_handlers: dict[ + str, + Callable[..., Awaitable[Jsonifiable]], + ] = self._create_message_handlers() # The HTTPConnection representing the WebSocket. This is used so that we can # query information about the request, like headers, cookies, etc. self.http_conn: HTTPConnection = conn.get_http_conn() self.input: Inputs = Inputs(dict()) - self.output: Outputs = Outputs(self, self.ns, dict(), dict()) + self.output: Outputs = Outputs(self, self.ns, outputs=dict()) self.user: str | None = None self.groups: list[str] | None = None @@ -214,10 +217,6 @@ def __init__( self._outbound_message_queues = OutBoundMessageQueues() - self._message_handlers: dict[ - str, - Callable[..., Awaitable[object]], - ] = self._create_message_handlers() self._file_upload_manager: FileUploadManager = FileUploadManager() self._on_ended_callbacks = _utils.AsyncCallbacks() self._has_run_session_end_tasks: bool = False @@ -289,7 +288,10 @@ def verify_state(expected_state: ConnectionState) -> None: return if "method" not in message_obj: - self._send_error_response("Message does not contain 'method'.") + await self._send_error_response( + message_obj, + "Message does not contain 'method'.", + ) return async with lock(): @@ -338,7 +340,7 @@ def verify_state(expected_state: ConnectionState) -> None: try: # Starting in Python 3.10 this could be traceback.print_exception(e) traceback.print_exception(*sys.exc_info()) - self._send_error_response(str(e)) + await self._send_error_response(None, str(e)) except Exception: pass finally: @@ -386,15 +388,22 @@ def _is_hidden(self, name: str) -> bool: async def _dispatch(self, message: ClientMessageOther) -> None: try: func = self._message_handlers[message["method"]] + except KeyError: + await self._send_error_response( + message, "Unknown method: " + message["method"] + ) + return except AttributeError: - self._send_error_response("Unknown method: " + message["method"]) + await self._send_error_response( + message, "Unknown method: " + message["method"] + ) return try: # TODO: handle `blobs` - value: object = await func(*message["args"]) + value = await func(*message["args"]) except Exception as e: - self._send_error_response("Error: " + str(e)) + await self._send_error_response(message, str(e)) return await self._send_response(message, value) @@ -403,8 +412,12 @@ async def _send_response(self, message: ClientMessageOther, value: object) -> No await self._send_message({"response": {"tag": message["tag"], "value": value}}) # This is called during __init__. - def _create_message_handlers(self) -> dict[str, Callable[..., Awaitable[object]]]: - async def uploadInit(file_infos: list[FileInfo]) -> dict[str, object]: + def _create_message_handlers( + self, + ) -> dict[str, Callable[..., Awaitable[Jsonifiable]]]: + # TODO-future; Make sure these methods work within MockSession + + async def uploadInit(file_infos: list[FileInfo]) -> dict[str, Jsonifiable]: with session_context(self): if self._debug: print("Upload init: " + str(file_infos), flush=True) @@ -675,9 +688,17 @@ def _send_message_sync(self, message: dict[str, object]) -> None: """ _utils.run_coro_hybrid(self._send_message(message)) - def _send_error_response(self, message_str: str) -> None: - print("_send_error_response: " + message_str) - pass + async def _send_error_response( + self, + message: ClientMessageOther | None, + error: object, + ) -> None: + # { tag: number; value?: ResponseValue; error?: string } + tag = None + if message is not None: + if "tag" in message: + tag = message["tag"] + await self._send_message({"response": {"tag": tag, "error": error}}) # ========================================================================== # Flush @@ -913,10 +934,9 @@ def __init__(self, parent: Session, ns: ResolvedId) -> None: self.ns = ns self.input = Inputs(values=parent.input._map, ns=ns) self.output = Outputs( - session=cast(Session, self), - effects=self.output._effects, - suspend_when_hidden=self.output._suspend_when_hidden, + cast(Session, self), ns=ns, + outputs=self.output._outputs, ) def __getattr__(self, attr: str) -> Any: @@ -1020,6 +1040,13 @@ def __contains__(self, key: str) -> bool: # ====================================================================================== +@dataclasses.dataclass +class OutputInfo: + renderer: Renderer[Any] + effect: Effect_ + suspend_when_hidden: bool + + class Outputs: """ A class representing Shiny output definitions. @@ -1029,13 +1056,64 @@ def __init__( self, session: Session, ns: Callable[[str], ResolvedId], - effects: dict[str, Effect_], - suspend_when_hidden: dict[str, bool], + *, + outputs: dict[str, OutputInfo], ) -> None: self._session = session self._ns = ns - self._effects = effects - self._suspend_when_hidden = suspend_when_hidden + self._outputs = outputs + + self._init_message_handlers() + + def _init_message_handlers(self) -> None: + async def outputRPC( + outputId: str, + handler: str, + msg: object, + ) -> Jsonifiable: + """ + Used to handle request messages from an Output Renderer. + + Typically, this is used when an Output Renderer needs to set an input value. + E.g. a @render.data_frame result with a `mode="edit"` parameter will use + this to set the value of the data frame when a cell is edited. + + The value returned by the handler is sent back to the client with the original unique id (`tag`). + """ + if not (outputId in self._outputs): + raise RuntimeError( + f"Received request message for an unknown Output Renderer with id `{outputId}`" + ) + + output_info = self._outputs[outputId] + renderer = output_info.renderer + handler = f"_handle_{handler}" + if not ( + hasattr(renderer, handler) and callable(getattr(renderer, handler)) + ): + raise RuntimeError( + f"Output Renderer with id `{outputId}` does not have method `{handler}` to handler request message" + ) + + # Make a new session proxy if the output is namespaced; + # No need to make recursive proxies as the important part is a prefix exists + sessProxy = self._session + if "-" in outputId: + modPrefix, _ = outputId.rsplit("-", 1) + sessProxy = self._session.make_scope(modPrefix) + with session_context(sessProxy): + with isolate(): + try: + # TODO-barret assert that the function has been marked as an outputRPC handler + return await getattr(renderer, handler)(msg) + except Exception as e: + print("error: ", e) + raise RuntimeError( + f"Error while handling request message for Output Renderer with id `{outputId}`" + ) + + # Add the message handler + self._session._message_handlers["outputRPC"] = outputRPC @overload def __call__(self, renderer: RendererT) -> RendererT: @@ -1077,8 +1155,6 @@ def set_renderer(renderer: RendererT) -> RendererT: self.remove(output_name) - self._suspend_when_hidden[output_name] = suspend_when_hidden - @effect( suspended=suspend_when_hidden and self._session._is_hidden(output_name), priority=priority, @@ -1136,7 +1212,12 @@ async def output_obs(): lambda: self._session._send_progress("binding", {"id": output_name}) ) - self._effects[output_name] = output_obs + # Store the renderer and effect info + self._outputs[output_name] = OutputInfo( + renderer=renderer, + effect=output_obs, + suspend_when_hidden=suspend_when_hidden, + ) return renderer @@ -1147,19 +1228,19 @@ async def output_obs(): def remove(self, id: Id) -> None: output_name = self._ns(id) - if output_name in self._effects: - self._effects[output_name].destroy() - del self._effects[output_name] - del self._suspend_when_hidden[output_name] + if output_name in self._outputs: + self._outputs[output_name].effect.destroy() + del self._outputs[output_name] def _manage_hidden(self) -> None: "Suspends execution of hidden outputs and resumes execution of visible outputs." - output_names = list(self._suspend_when_hidden.keys()) - for name in output_names: + for name, output in self._outputs.items(): if self._should_suspend(name): - self._effects[name].suspend() + output.effect.suspend() else: - self._effects[name].resume() + output.effect.resume() def _should_suspend(self, name: str) -> bool: - return self._suspend_when_hidden[name] and self._session._is_hidden(name) + return self._outputs[name].suspend_when_hidden and self._session._is_hidden( + name + ) diff --git a/shiny/types.py b/shiny/types.py index 89a22ac68..f081061fe 100644 --- a/shiny/types.py +++ b/shiny/types.py @@ -12,7 +12,19 @@ "SilentCancelOutputException", ) -from typing import TYPE_CHECKING, Any, BinaryIO, Literal, NamedTuple, Optional, Protocol +from typing import ( + TYPE_CHECKING, + Any, + BinaryIO, + Dict, + List, + Literal, + NamedTuple, + Optional, + Protocol, + Tuple, + Union, +) from htmltools import TagChild @@ -310,3 +322,33 @@ class BrushInfo(TypedDict): log: CoordmapPanelLog direction: Literal["x", "y", "xy"] # .nonce: float + + +# https://github.com/python/cpython/blob/df1eec3dae3b1eddff819fd70f58b03b3fbd0eda/Lib/json/encoder.py#L77-L95 +# +-------------------+---------------+ +# | Python | JSON | +# +===================+===============+ +# | dict | object | +# +-------------------+---------------+ +# | list, tuple | array | +# +-------------------+---------------+ +# | str | string | +# +-------------------+---------------+ +# | int, float | number | +# +-------------------+---------------+ +# | True | true | +# +-------------------+---------------+ +# | False | false | +# +-------------------+---------------+ +# | None | null | +# +-------------------+---------------+ +Jsonifiable = Union[ + str, + int, + float, + bool, + None, + List["Jsonifiable"], + Tuple["Jsonifiable"], + Dict[str, "Jsonifiable"], +] diff --git a/shiny/www/shared/py-shiny/dataframe/dataframe.js b/shiny/www/shared/py-shiny/dataframe/dataframe.js index 6c9f5c5ad..32a74beb2 100644 --- a/shiny/www/shared/py-shiny/dataframe/dataframe.js +++ b/shiny/www/shared/py-shiny/dataframe/dataframe.js @@ -1,11 +1,17 @@ -var ft=` +var Fe,h,an,po,ce,rn,un,ut,dn,Ne={},cn=[],_o=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Le=Array.isArray;function te(e,n){for(var t in n)e[t]=n[t];return e}function gn(e){var n=e.parentNode;n&&n.removeChild(e)}function P(e,n,t){var r,o,i,l={};for(i in n)i=="key"?r=n[i]:i=="ref"?o=n[i]:l[i]=n[i];if(arguments.length>2&&(l.children=arguments.length>3?Fe.call(arguments,2):t),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)l[i]===void 0&&(l[i]=e.defaultProps[i]);return xe(e,l,r,o,null)}function xe(e,n,t,r,o){var i={type:e,props:n,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:o??++an};return o==null&&h.vnode!=null&&h.vnode(i),i}function ct(){return{current:null}}function W(e){return e.children}function z(e,n){this.props=e,this.context=n}function Me(e,n){if(n==null)return e.__?Me(e.__,e.__.__k.indexOf(e)+1):null;for(var t;nn&&ce.sort(ut));He.__r=0}function pn(e,n,t,r,o,i,l,u,a,d){var s,f,g,c,p,_,m,v=r&&r.__k||cn,w=v.length;for(t.__k=[],s=0;s0?xe(c.type,c.props,c.key,c.ref?c.ref:null,c.__v):c)!=null){if(c.__=t,c.__b=t.__b+1,(g=v[s])===null||g&&c.key==g.key&&c.type===g.type)v[s]=void 0;else for(f=0;f=0;n--)if((t=e.__k[n])&&(r=hn(t)))return r}return null}function mo(e,n,t,r,o){var i;for(i in t)i==="children"||i==="key"||i in n||ze(e,i,null,t[i],r);for(i in n)o&&typeof n[i]!="function"||i==="children"||i==="key"||i==="value"||i==="checked"||t[i]===n[i]||ze(e,i,n[i],t[i],r)}function on(e,n,t){n[0]==="-"?e.setProperty(n,t??""):e[n]=t==null?"":typeof t!="number"||_o.test(n)?t:t+"px"}function ze(e,n,t,r,o){var i;e:if(n==="style")if(typeof t=="string")e.style.cssText=t;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(n in r)t&&n in t||on(e.style,n,"");if(t)for(n in t)r&&t[n]===r[n]||on(e.style,n,t[n])}else if(n[0]==="o"&&n[1]==="n")i=n!==(n=n.replace(/Capture$/,"")),n=n.toLowerCase()in e?n.toLowerCase().slice(2):n.slice(2),e.l||(e.l={}),e.l[n+i]=t,t?r||e.addEventListener(n,i?sn:ln,i):e.removeEventListener(n,i?sn:ln,i);else if(n!=="dangerouslySetInnerHTML"){if(o)n=n.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(n!=="width"&&n!=="height"&&n!=="href"&&n!=="list"&&n!=="form"&&n!=="tabIndex"&&n!=="download"&&n!=="rowSpan"&&n!=="colSpan"&&n in e)try{e[n]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&n[4]!=="-"?e.removeAttribute(n):e.setAttribute(n,t))}}function ln(e){return this.l[e.type+!1](h.event?h.event(e):e)}function sn(e){return this.l[e.type+!0](h.event?h.event(e):e)}function gt(e,n,t,r,o,i,l,u,a){var d,s,f,g,c,p,_,m,v,w,C,E,O,A,ie,D=n.type;if(n.constructor!==void 0)return null;t.__h!=null&&(a=t.__h,u=n.__e=t.__e,n.__h=null,i=[u]),(d=h.__b)&&d(n);try{e:if(typeof D=="function"){if(m=n.props,v=(d=D.contextType)&&r[d.__c],w=d?v?v.props.value:d.__:r,t.__c?_=(s=n.__c=t.__c).__=s.__E:("prototype"in D&&D.prototype.render?n.__c=s=new D(m,w):(n.__c=s=new z(m,w),s.constructor=D,s.render=vo),v&&v.sub(s),s.props=m,s.state||(s.state={}),s.context=w,s.__n=r,f=s.__d=!0,s.__h=[],s._sb=[]),s.__s==null&&(s.__s=s.state),D.getDerivedStateFromProps!=null&&(s.__s==s.state&&(s.__s=te({},s.__s)),te(s.__s,D.getDerivedStateFromProps(m,s.__s))),g=s.props,c=s.state,s.__v=n,f)D.getDerivedStateFromProps==null&&s.componentWillMount!=null&&s.componentWillMount(),s.componentDidMount!=null&&s.__h.push(s.componentDidMount);else{if(D.getDerivedStateFromProps==null&&m!==g&&s.componentWillReceiveProps!=null&&s.componentWillReceiveProps(m,w),!s.__e&&s.shouldComponentUpdate!=null&&s.shouldComponentUpdate(m,s.__s,w)===!1||n.__v===t.__v){for(n.__v!==t.__v&&(s.props=m,s.state=s.__s,s.__d=!1),s.__e=!1,n.__e=t.__e,n.__k=t.__k,n.__k.forEach(function(U){U&&(U.__=n)}),C=0;C2&&(u.children=arguments.length>3?Fe.call(arguments,2):t),xe(e.type,u,r||e.key,o||e.ref,null)}function pt(e,n){var t={__c:n="__cC"+dn++,__:e,Consumer:function(r,o){return r.children(o)},Provider:function(r){var o,i;return this.getChildContext||(o=[],(i={})[n]=this,this.getChildContext=function(){return i},this.shouldComponentUpdate=function(l){this.props.value!==l.value&&o.some(function(u){u.__e=!0,dt(u)})},this.sub=function(l){o.push(l);var u=l.componentWillUnmount;l.componentWillUnmount=function(){o.splice(o.indexOf(l),1),u&&u.call(l)}}),r.children}};return t.Provider.__=t.Consumer.contextType=t}Fe=cn.slice,h={__e:function(e,n,t,r){for(var o,i,l;n=n.__;)if((o=n.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),l=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),l=o.__d),l)return o.__E=o}catch(u){e=u}throw e}},an=0,po=function(e){return e!=null&&e.constructor===void 0},z.prototype.setState=function(e,n){var t;t=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=te({},this.state),typeof e=="function"&&(e=e(te({},t),this.props)),e&&te(t,e),e!=null&&this.__v&&(n&&this._sb.push(n),dt(this))},z.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),dt(this))},z.prototype.render=W,ce=[],un=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ut=function(e,n){return e.__v.__b-n.__v.__b},He.__r=0,dn=0;var se,M,_t,wn,he=0,$n=[],Ge=[],Cn=h.__b,En=h.__r,Rn=h.diffed,xn=h.__c,Mn=h.unmount;function ve(e,n){h.__h&&h.__h(M,e,he||n),he=0;var t=M.__H||(M.__H={__:[],__h:[]});return e>=t.__.length&&t.__.push({__V:Ge}),t.__[e]}function V(e){return he=1,ye(On,e)}function ye(e,n,t){var r=ve(se++,2);if(r.t=e,!r.__c&&(r.__=[t?t(n):On(void 0,n),function(u){var a=r.__N?r.__N[0]:r.__[0],d=r.t(a,u);a!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=M,!M.u)){var o=function(u,a,d){if(!r.__c.__H)return!0;var s=r.__c.__H.__.filter(function(g){return g.__c});if(s.every(function(g){return!g.__N}))return!i||i.call(this,u,a,d);var f=!1;return s.forEach(function(g){if(g.__N){var c=g.__[0];g.__=g.__N,g.__N=void 0,c!==g.__[0]&&(f=!0)}}),!(!f&&r.__c.props===u)&&(!i||i.call(this,u,a,d))};M.u=!0;var i=M.shouldComponentUpdate,l=M.componentWillUpdate;M.componentWillUpdate=function(u,a,d){if(this.__e){var s=i;i=void 0,o(u,a,d),i=s}l&&l.call(this,u,a,d)},M.shouldComponentUpdate=o}return r.__N||r.__}function k(e,n){var t=ve(se++,3);!h.__s&&ht(t.__H,n)&&(t.__=e,t.i=n,M.__H.__h.push(t))}function J(e,n){var t=ve(se++,4);!h.__s&&ht(t.__H,n)&&(t.__=e,t.i=n,M.__h.push(t))}function L(e){return he=5,Y(function(){return{current:e}},[])}function Vn(e,n,t){he=6,J(function(){return typeof e=="function"?(e(n()),function(){return e(null)}):e?(e.current=n(),function(){return e.current=null}):void 0},t==null?t:t.concat(e))}function Y(e,n){var t=ve(se++,7);return ht(t.__H,n)?(t.__V=e(),t.i=n,t.__h=e,t.__V):t.__}function be(e,n){return he=8,Y(function(){return e},n)}function In(e){var n=M.context[e.__c],t=ve(se++,9);return t.c=e,n?(t.__==null&&(t.__=!0,n.sub(M)),n.props.value):e.__}function Dn(e,n){h.useDebugValue&&h.useDebugValue(n?n(e):e)}function Tn(){var e=ve(se++,11);if(!e.__){for(var n=M.__v;n!==null&&!n.__m&&n.__!==null;)n=n.__;var t=n.__m||(n.__m=[0,0]);e.__="P"+t[0]+"-"+t[1]++}return e.__}function yo(){for(var e;e=$n.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Be),e.__H.__h.forEach(mt),e.__H.__h=[]}catch(n){e.__H.__h=[],h.__e(n,e.__v)}}h.__b=function(e){M=null,Cn&&Cn(e)},h.__r=function(e){En&&En(e),se=0;var n=(M=e.__c).__H;n&&(_t===M?(n.__h=[],M.__h=[],n.__.forEach(function(t){t.__N&&(t.__=t.__N),t.__V=Ge,t.__N=t.i=void 0})):(n.__h.forEach(Be),n.__h.forEach(mt),n.__h=[],se=0)),_t=M},h.diffed=function(e){Rn&&Rn(e);var n=e.__c;n&&n.__H&&(n.__H.__h.length&&($n.push(n)!==1&&wn===h.requestAnimationFrame||((wn=h.requestAnimationFrame)||bo)(yo)),n.__H.__.forEach(function(t){t.i&&(t.__H=t.i),t.__V!==Ge&&(t.__=t.__V),t.i=void 0,t.__V=Ge})),_t=M=null},h.__c=function(e,n){n.some(function(t){try{t.__h.forEach(Be),t.__h=t.__h.filter(function(r){return!r.__||mt(r)})}catch(r){n.some(function(o){o.__h&&(o.__h=[])}),n=[],h.__e(r,t.__v)}}),xn&&xn(e,n)},h.unmount=function(e){Mn&&Mn(e);var n,t=e.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{Be(r)}catch(o){n=o}}),t.__H=void 0,n&&h.__e(n,t.__v))};var Fn=typeof requestAnimationFrame=="function";function bo(e){var n,t=function(){clearTimeout(r),Fn&&cancelAnimationFrame(n),setTimeout(e)},r=setTimeout(t,100);Fn&&(n=requestAnimationFrame(t))}function Be(e){var n=M,t=e.__c;typeof t=="function"&&(e.__c=void 0,t()),M=n}function mt(e){var n=M;e.__c=e.__(),M=n}function ht(e,n){return!e||e.length!==n.length||n.some(function(t,r){return t!==e[r]})}function On(e,n){return typeof n=="function"?n(e):n}function Bn(e,n){for(var t in n)e[t]=n[t];return e}function yt(e,n){for(var t in e)if(t!=="__source"&&!(t in n))return!0;for(var r in n)if(r!=="__source"&&e[r]!==n[r])return!0;return!1}function vt(e,n){return e===n&&(e!==0||1/e==1/n)||e!=e&&n!=n}function bt(e){this.props=e}function So(e,n){function t(o){var i=this.props.ref,l=i==o.ref;return!l&&i&&(i.call?i(null):i.current=null),n?!n(this.props,o)||!l:yt(this.props,o)}function r(o){return this.shouldComponentUpdate=t,P(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r}(bt.prototype=new z).isPureReactComponent=!0,bt.prototype.shouldComponentUpdate=function(e,n){return yt(this.props,e)||yt(this.state,n)};var An=h.__b;h.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),An&&An(e)};var wo=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Co(e){function n(t){var r=Bn({},t);return delete r.ref,e(r,t.ref||null)}return n.$$typeof=wo,n.render=n,n.prototype.isReactComponent=n.__f=!0,n.displayName="ForwardRef("+(e.displayName||e.name)+")",n}var kn=function(e,n){return e==null?null:X(X(e).map(n))},Eo={map:kn,forEach:kn,count:function(e){return e?X(e).length:0},only:function(e){var n=X(e);if(n.length!==1)throw"Children.only";return n[0]},toArray:X},Ro=h.__e;h.__e=function(e,n,t,r){if(e.then){for(var o,i=n;i=i.__;)if((o=i.__c)&&o.__c)return n.__e==null&&(n.__e=t.__e,n.__k=t.__k),o.__c(e,n)}Ro(e,n,t,r)};var Pn=h.unmount;function Un(e,n,t){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Bn({},e)).__c!=null&&(e.__c.__P===t&&(e.__c.__P=n),e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return Un(r,n,t)})),e}function jn(e,n,t){return e&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return jn(r,n,t)}),e.__c&&e.__c.__P===n&&(e.__e&&t.insertBefore(e.__e,e.__d),e.__c.__e=!0,e.__c.__P=t)),e}function Ue(){this.__u=0,this.t=null,this.__b=null}function Kn(e){var n=e.__.__c;return n&&n.__a&&n.__a(e)}function xo(e){var n,t,r;function o(i){if(n||(n=e()).then(function(l){t=l.default||l},function(l){r=l}),r)throw r;if(!t)throw n;return P(t,i)}return o.displayName="Lazy",o.__f=!0,o}function $e(){this.u=null,this.o=null}h.unmount=function(e){var n=e.__c;n&&n.__R&&n.__R(),n&&e.__h===!0&&(e.type=null),Pn&&Pn(e)},(Ue.prototype=new z).__c=function(e,n){var t=n.__c,r=this;r.t==null&&(r.t=[]),r.t.push(t);var o=Kn(r.__v),i=!1,l=function(){i||(i=!0,t.__R=null,o?o(u):u())};t.__R=l;var u=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=jn(d,d.__c.__P,d.__c.__O)}var s;for(r.setState({__a:r.__b=null});s=r.t.pop();)s.forceUpdate()}},a=n.__h===!0;r.__u++||a||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(l,l)},Ue.prototype.componentWillUnmount=function(){this.t=[]},Ue.prototype.render=function(e,n){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Un(this.__b,t,r.__O=r.__P)}this.__b=null}var o=n.__a&&P(W,null,e.fallback);return o&&(o.__h=null),[P(W,null,n.__a?null:e.children),o]};var Nn=function(e,n,t){if(++t[1]===t[0]&&e.o.delete(n),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.o.size))for(t=e.u;t;){for(;t.length>3;)t.pop()();if(t[1]>>1,1),n.i.removeChild(r)}}),me(P(Mo,{context:n.context},e.__v),n.l)):n.l&&n.componentWillUnmount()}function $o(e,n){var t=P(Fo,{__v:e,i:n});return t.containerInfo=n,t}($e.prototype=new z).__a=function(e){var n=this,t=Kn(n.__v),r=n.o.get(e);return r[0]++,function(o){var i=function(){n.props.revealOrder?(r.push(o),Nn(n,e,r)):o()};t?t(i):i()}},$e.prototype.render=function(e){this.u=null,this.o=new Map;var n=X(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&n.reverse();for(var t=n.length;t--;)this.o.set(n[t],this.u=[1,0,this.u]);return e.children},$e.prototype.componentDidUpdate=$e.prototype.componentDidMount=function(){var e=this;this.o.forEach(function(n,t){Nn(e,t,n)})};var qn=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Vo=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Io=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Do=/[A-Z0-9]/g,To=typeof document<"u",Oo=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function St(e,n,t){return n.__k==null&&(n.textContent=""),me(e,n),typeof t=="function"&&t(),e?e.__c:null}function Wn(e,n,t){return ft(e,n),typeof t=="function"&&t(),e?e.__c:null}z.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(z.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(n){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:n})}})});var Hn=h.event;function Ao(){}function ko(){return this.cancelBubble}function Po(){return this.defaultPrevented}h.event=function(e){return Hn&&(e=Hn(e)),e.persist=Ao,e.isPropagationStopped=ko,e.isDefaultPrevented=Po,e.nativeEvent=e};var wt,No={enumerable:!1,configurable:!0,get:function(){return this.class}},zn=h.vnode;h.vnode=function(e){typeof e.type=="string"&&function(n){var t=n.props,r=n.type,o={};for(var i in t){var l=t[i];if(!(i==="value"&&"defaultValue"in t&&l==null||To&&i==="children"&&r==="noscript"||i==="class"||i==="className")){var u=i.toLowerCase();i==="defaultValue"&&"value"in t&&t.value==null?i="value":i==="download"&&l===!0?l="":u==="ondoubleclick"?i="ondblclick":u!=="onchange"||r!=="input"&&r!=="textarea"||Oo(t.type)?u==="onfocus"?i="onfocusin":u==="onblur"?i="onfocusout":Io.test(i)?i=u:r.indexOf("-")===-1&&Vo.test(i)?i=i.replace(Do,"-$&").toLowerCase():l===null&&(l=void 0):u=i="oninput",u==="oninput"&&o[i=u]&&(i="oninputCapture"),o[i]=l}}r=="select"&&o.multiple&&Array.isArray(o.value)&&(o.value=X(t.children).forEach(function(a){a.props.selected=o.value.indexOf(a.props.value)!=-1})),r=="select"&&o.defaultValue!=null&&(o.value=X(t.children).forEach(function(a){a.props.selected=o.multiple?o.defaultValue.indexOf(a.props.value)!=-1:o.defaultValue==a.props.value})),t.class&&!t.className?(o.class=t.class,Object.defineProperty(o,"className",No)):(t.className&&!t.class||t.class&&t.className)&&(o.class=o.className=t.className),n.props=o}(e),e.$$typeof=qn,zn&&zn(e)};var Ln=h.__r;h.__r=function(e){Ln&&Ln(e),wt=e.__c};var Gn=h.diffed;h.diffed=function(e){Gn&&Gn(e);var n=e.props,t=e.__e;t!=null&&e.type==="textarea"&&"value"in n&&n.value!==t.value&&(t.value=n.value==null?"":n.value),wt=null};var Ho={ReactCurrentDispatcher:{current:{readContext:function(e){return wt.__n[e.__c].props.value}}}};function zo(e){return P.bind(null,e)}function Xn(e){return!!e&&e.$$typeof===qn}function Lo(e){return Xn(e)?Sn.apply(null,arguments):e}function Ct(e){return!!e.__k&&(me(null,e),!0)}function Go(e){return e&&(e.base||e.nodeType===1&&e)||null}var Bo=function(e,n){return e(n)},Uo=function(e,n){return e(n)},Et=W;function Jn(e){e()}function jo(e){return e}function Ko(){return[!1,Jn]}var qo=J;function Wo(e,n){var t=n(),r=V({h:{__:t,v:n}}),o=r[0].h,i=r[1];return J(function(){o.__=t,o.v=n,vt(o.__,n())||i({h:o})},[e,t,n]),k(function(){return vt(o.__,o.v())||i({h:o}),e(function(){vt(o.__,o.v())||i({h:o})})},[e]),t}var b={useState:V,useId:Tn,useReducer:ye,useEffect:k,useLayoutEffect:J,useInsertionEffect:qo,useTransition:Ko,useDeferredValue:jo,useSyncExternalStore:Wo,startTransition:Jn,useRef:L,useImperativeHandle:Vn,useMemo:Y,useCallback:be,useContext:In,useDebugValue:Dn,version:"17.0.2",Children:Eo,render:St,hydrate:Wn,unmountComponentAtNode:Ct,createPortal:$o,createElement:P,createContext:pt,createFactory:zo,cloneElement:Lo,createRef:ct,Fragment:W,isValidElement:Xn,findDOMNode:Go,Component:z,PureComponent:bt,memo:So,forwardRef:Co,flushSync:Uo,unstable_batchedUpdates:Bo,StrictMode:Et,Suspense:Ue,SuspenseList:$e,lazy:xo,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ho};function ae(e,n){return typeof e=="function"?e(n):e}function G(e,n){return t=>{n.setState(r=>({...r,[e]:ae(t,r[e])}))}}function We(e){return e instanceof Function}function Xo(e){return Array.isArray(e)&&e.every(n=>typeof n=="number")}function Jo(e,n){let t=[],r=o=>{o.forEach(i=>{t.push(i);let l=n(i);l!=null&&l.length&&r(l)})};return r(e),t}function y(e,n,t){let r=[],o;return()=>{let i;t.key&&t.debug&&(i=Date.now());let l=e();if(!(l.length!==r.length||l.some((d,s)=>r[s]!==d)))return o;r=l;let a;if(t.key&&t.debug&&(a=Date.now()),o=n(...l),t==null||t.onChange==null||t.onChange(o),t.key&&t.debug&&t!=null&&t.debug()){let d=Math.round((Date.now()-i)*100)/100,s=Math.round((Date.now()-a)*100)/100,f=s/16,g=(c,p)=>{for(c=String(c);c.length{let c=g;for(let _ of a.split(".")){var p;c=(p=c)==null?void 0:p[_]}return c}:s=g=>g[u.accessorKey]),!d)throw new Error;let f={id:`${String(d)}`,accessorFn:s,parent:r,depth:t,columnDef:u,columns:[],getFlatColumns:y(()=>[!0],()=>{var g;return[f,...(g=f.columns)==null?void 0:g.flatMap(c=>c.getFlatColumns())]},{key:"column.getFlatColumns",debug:()=>{var g;return(g=e.options.debugAll)!=null?g:e.options.debugColumns}}),getLeafColumns:y(()=>[e._getOrderColumnsFn()],g=>{var c;if((c=f.columns)!=null&&c.length){let p=f.columns.flatMap(_=>_.getLeafColumns());return g(p)}return[f]},{key:"column.getLeafColumns",debug:()=>{var g;return(g=e.options.debugAll)!=null?g:e.options.debugColumns}})};return f=e._features.reduce((g,c)=>Object.assign(g,c.createColumn==null?void 0:c.createColumn(f,e)),f),f}function Qn(e,n,t){var r;let i={id:(r=t.id)!=null?r:n.id,column:n,index:t.index,isPlaceholder:!!t.isPlaceholder,placeholderId:t.placeholderId,depth:t.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{let l=[],u=a=>{a.subHeaders&&a.subHeaders.length&&a.subHeaders.map(u),l.push(a)};return u(i),l},getContext:()=>({table:e,header:i,column:n})};return e._features.forEach(l=>{Object.assign(i,l.createHeader==null?void 0:l.createHeader(i,e))}),i}var Qo={createTable:e=>({getHeaderGroups:y(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(n,t,r,o)=>{var i,l;let u=(i=r?.map(f=>t.find(g=>g.id===f)).filter(Boolean))!=null?i:[],a=(l=o?.map(f=>t.find(g=>g.id===f)).filter(Boolean))!=null?l:[],d=t.filter(f=>!(r!=null&&r.includes(f.id))&&!(o!=null&&o.includes(f.id)));return je(n,[...u,...d,...a],e)},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getCenterHeaderGroups:y(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(n,t,r,o)=>(t=t.filter(i=>!(r!=null&&r.includes(i.id))&&!(o!=null&&o.includes(i.id))),je(n,t,e,"center")),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeftHeaderGroups:y(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(n,t,r)=>{var o;let i=(o=r?.map(l=>t.find(u=>u.id===l)).filter(Boolean))!=null?o:[];return je(n,i,e,"left")},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getRightHeaderGroups:y(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(n,t,r)=>{var o;let i=(o=r?.map(l=>t.find(u=>u.id===l)).filter(Boolean))!=null?o:[];return je(n,i,e,"right")},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getFooterGroups:y(()=>[e.getHeaderGroups()],n=>[...n].reverse(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeftFooterGroups:y(()=>[e.getLeftHeaderGroups()],n=>[...n].reverse(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getCenterFooterGroups:y(()=>[e.getCenterHeaderGroups()],n=>[...n].reverse(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getRightFooterGroups:y(()=>[e.getRightHeaderGroups()],n=>[...n].reverse(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getFlatHeaders:y(()=>[e.getHeaderGroups()],n=>n.map(t=>t.headers).flat(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeftFlatHeaders:y(()=>[e.getLeftHeaderGroups()],n=>n.map(t=>t.headers).flat(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getCenterFlatHeaders:y(()=>[e.getCenterHeaderGroups()],n=>n.map(t=>t.headers).flat(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getRightFlatHeaders:y(()=>[e.getRightHeaderGroups()],n=>n.map(t=>t.headers).flat(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getCenterLeafHeaders:y(()=>[e.getCenterFlatHeaders()],n=>n.filter(t=>{var r;return!((r=t.subHeaders)!=null&&r.length)}),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeftLeafHeaders:y(()=>[e.getLeftFlatHeaders()],n=>n.filter(t=>{var r;return!((r=t.subHeaders)!=null&&r.length)}),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getRightLeafHeaders:y(()=>[e.getRightFlatHeaders()],n=>n.filter(t=>{var r;return!((r=t.subHeaders)!=null&&r.length)}),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeafHeaders:y(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(n,t,r)=>{var o,i,l,u,a,d;return[...(o=(i=n[0])==null?void 0:i.headers)!=null?o:[],...(l=(u=t[0])==null?void 0:u.headers)!=null?l:[],...(a=(d=r[0])==null?void 0:d.headers)!=null?a:[]].map(s=>s.getLeafHeaders()).flat()},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}})})};function je(e,n,t,r){var o,i;let l=0,u=function(g,c){c===void 0&&(c=1),l=Math.max(l,c),g.filter(p=>p.getIsVisible()).forEach(p=>{var _;(_=p.columns)!=null&&_.length&&u(p.columns,c+1)},0)};u(e);let a=[],d=(g,c)=>{let p={depth:c,id:[r,`${c}`].filter(Boolean).join("_"),headers:[]},_=[];g.forEach(m=>{let v=[..._].reverse()[0],w=m.column.depth===p.depth,C,E=!1;if(w&&m.column.parent?C=m.column.parent:(C=m.column,E=!0),v&&v?.column===C)v.subHeaders.push(m);else{let O=Qn(t,C,{id:[r,c,C.id,m?.id].filter(Boolean).join("_"),isPlaceholder:E,placeholderId:E?`${_.filter(A=>A.column===C).length}`:void 0,depth:c,index:_.length});O.subHeaders.push(m),_.push(O)}p.headers.push(m),m.headerGroup=p}),a.push(p),c>0&&d(_,c-1)},s=n.map((g,c)=>Qn(t,g,{depth:l,index:c}));d(s,l-1),a.reverse();let f=g=>g.filter(p=>p.column.getIsVisible()).map(p=>{let _=0,m=0,v=[0];p.subHeaders&&p.subHeaders.length?(v=[],f(p.subHeaders).forEach(C=>{let{colSpan:E,rowSpan:O}=C;_+=E,v.push(O)})):_=1;let w=Math.min(...v);return m=m+w,p.colSpan=_,p.rowSpan=m,{colSpan:_,rowSpan:m}});return f((o=(i=a[0])==null?void 0:i.headers)!=null?o:[]),a}var Ke={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},Rt=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),Zo={getDefaultColumnDef:()=>Ke,getInitialState:e=>({columnSizing:{},columnSizingInfo:Rt(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",onColumnSizingChange:G("columnSizing",e),onColumnSizingInfoChange:G("columnSizingInfo",e)}),createColumn:(e,n)=>({getSize:()=>{var t,r,o;let i=n.getState().columnSizing[e.id];return Math.min(Math.max((t=e.columnDef.minSize)!=null?t:Ke.minSize,(r=i??e.columnDef.size)!=null?r:Ke.size),(o=e.columnDef.maxSize)!=null?o:Ke.maxSize)},getStart:t=>{let r=t?t==="left"?n.getLeftVisibleLeafColumns():n.getRightVisibleLeafColumns():n.getVisibleLeafColumns(),o=r.findIndex(i=>i.id===e.id);if(o>0){let i=r[o-1];return i.getStart(t)+i.getSize()}return 0},resetSize:()=>{n.setColumnSizing(t=>{let{[e.id]:r,...o}=t;return o})},getCanResize:()=>{var t,r;return((t=e.columnDef.enableResizing)!=null?t:!0)&&((r=n.options.enableColumnResizing)!=null?r:!0)},getIsResizing:()=>n.getState().columnSizingInfo.isResizingColumn===e.id}),createHeader:(e,n)=>({getSize:()=>{let t=0,r=o=>{if(o.subHeaders.length)o.subHeaders.forEach(r);else{var i;t+=(i=o.column.getSize())!=null?i:0}};return r(e),t},getStart:()=>{if(e.index>0){let t=e.headerGroup.headers[e.index-1];return t.getStart()+t.getSize()}return 0},getResizeHandler:()=>{let t=n.getColumn(e.column.id),r=t?.getCanResize();return o=>{if(!t||!r||(o.persist==null||o.persist(),xt(o)&&o.touches&&o.touches.length>1))return;let i=e.getSize(),l=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[t.id,t.getSize()]],u=xt(o)?Math.round(o.touches[0].clientX):o.clientX,a={},d=(_,m)=>{typeof m=="number"&&(n.setColumnSizingInfo(v=>{var w,C;let E=m-((w=v?.startOffset)!=null?w:0),O=Math.max(E/((C=v?.startSize)!=null?C:0),-.999999);return v.columnSizingStart.forEach(A=>{let[ie,D]=A;a[ie]=Math.round(Math.max(D+D*O,0)*100)/100}),{...v,deltaOffset:E,deltaPercentage:O}}),(n.options.columnResizeMode==="onChange"||_==="end")&&n.setColumnSizing(v=>({...v,...a})))},s=_=>d("move",_),f=_=>{d("end",_),n.setColumnSizingInfo(m=>({...m,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},g={moveHandler:_=>s(_.clientX),upHandler:_=>{document.removeEventListener("mousemove",g.moveHandler),document.removeEventListener("mouseup",g.upHandler),f(_.clientX)}},c={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),s(_.touches[0].clientX),!1),upHandler:_=>{var m;document.removeEventListener("touchmove",c.moveHandler),document.removeEventListener("touchend",c.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),f((m=_.touches[0])==null?void 0:m.clientX)}},p=ei()?{passive:!1}:!1;xt(o)?(document.addEventListener("touchmove",c.moveHandler,p),document.addEventListener("touchend",c.upHandler,p)):(document.addEventListener("mousemove",g.moveHandler,p),document.addEventListener("mouseup",g.upHandler,p)),n.setColumnSizingInfo(_=>({..._,startOffset:u,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:l,isResizingColumn:t.id}))}}}),createTable:e=>({setColumnSizing:n=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(n),setColumnSizingInfo:n=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(n),resetColumnSizing:n=>{var t;e.setColumnSizing(n?{}:(t=e.initialState.columnSizing)!=null?t:{})},resetHeaderSizeInfo:n=>{var t;e.setColumnSizingInfo(n?Rt():(t=e.initialState.columnSizingInfo)!=null?t:Rt())},getTotalSize:()=>{var n,t;return(n=(t=e.getHeaderGroups()[0])==null?void 0:t.headers.reduce((r,o)=>r+o.getSize(),0))!=null?n:0},getLeftTotalSize:()=>{var n,t;return(n=(t=e.getLeftHeaderGroups()[0])==null?void 0:t.headers.reduce((r,o)=>r+o.getSize(),0))!=null?n:0},getCenterTotalSize:()=>{var n,t;return(n=(t=e.getCenterHeaderGroups()[0])==null?void 0:t.headers.reduce((r,o)=>r+o.getSize(),0))!=null?n:0},getRightTotalSize:()=>{var n,t;return(n=(t=e.getRightHeaderGroups()[0])==null?void 0:t.headers.reduce((r,o)=>r+o.getSize(),0))!=null?n:0}})},qe=null;function ei(){if(typeof qe=="boolean")return qe;let e=!1;try{let n={get passive(){return e=!0,!1}},t=()=>{};window.addEventListener("test",t,n),window.removeEventListener("test",t)}catch{e=!1}return qe=e,qe}function xt(e){return e.type==="touchstart"}var ti={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:G("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let n=!1,t=!1;return{_autoResetExpanded:()=>{var r,o;if(!n){e._queue(()=>{n=!0});return}if((r=(o=e.options.autoResetAll)!=null?o:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(t)return;t=!0,e._queue(()=>{e.resetExpanded(),t=!1})}},setExpanded:r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),toggleAllRowsExpanded:r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},resetExpanded:r=>{var o,i;e.setExpanded(r?{}:(o=(i=e.initialState)==null?void 0:i.expanded)!=null?o:{})},getCanSomeRowsExpand:()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),getToggleAllRowsExpandedHandler:()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},getIsSomeRowsExpanded:()=>{let r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},getIsAllRowsExpanded:()=>{let r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(o=>!o.getIsExpanded()))},getExpandedDepth:()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(i=>{let l=i.split(".");r=Math.max(r,l.length)}),r},getPreExpandedRowModel:()=>e.getSortedRowModel(),getExpandedRowModel:()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())}},createRow:(e,n)=>({toggleExpanded:t=>{n.setExpanded(r=>{var o;let i=r===!0?!0:!!(r!=null&&r[e.id]),l={};if(r===!0?Object.keys(n.getRowModel().rowsById).forEach(u=>{l[u]=!0}):l=r,t=(o=t)!=null?o:!i,!i&&t)return{...l,[e.id]:!0};if(i&&!t){let{[e.id]:u,...a}=l;return a}return r})},getIsExpanded:()=>{var t;let r=n.getState().expanded;return!!((t=n.options.getIsRowExpanded==null?void 0:n.options.getIsRowExpanded(e))!=null?t:r===!0||r?.[e.id])},getCanExpand:()=>{var t,r,o;return(t=n.options.getRowCanExpand==null?void 0:n.options.getRowCanExpand(e))!=null?t:((r=n.options.enableExpanding)!=null?r:!0)&&!!((o=e.subRows)!=null&&o.length)},getToggleExpandedHandler:()=>{let t=e.getCanExpand();return()=>{t&&e.toggleExpanded()}}})},nr=(e,n,t)=>{var r,o,i;let l=t.toLowerCase();return!!(!((r=e.getValue(n))==null||(o=r.toString())==null||(i=o.toLowerCase())==null)&&i.includes(l))};nr.autoRemove=e=>K(e);var rr=(e,n,t)=>{var r,o;return!!(!((r=e.getValue(n))==null||(o=r.toString())==null)&&o.includes(t))};rr.autoRemove=e=>K(e);var or=(e,n,t)=>{var r,o;return((r=e.getValue(n))==null||(o=r.toString())==null?void 0:o.toLowerCase())===t?.toLowerCase()};or.autoRemove=e=>K(e);var ir=(e,n,t)=>{var r;return(r=e.getValue(n))==null?void 0:r.includes(t)};ir.autoRemove=e=>K(e)||!(e!=null&&e.length);var lr=(e,n,t)=>!t.some(r=>{var o;return!((o=e.getValue(n))!=null&&o.includes(r))});lr.autoRemove=e=>K(e)||!(e!=null&&e.length);var sr=(e,n,t)=>t.some(r=>{var o;return(o=e.getValue(n))==null?void 0:o.includes(r)});sr.autoRemove=e=>K(e)||!(e!=null&&e.length);var ar=(e,n,t)=>e.getValue(n)===t;ar.autoRemove=e=>K(e);var ur=(e,n,t)=>e.getValue(n)==t;ur.autoRemove=e=>K(e);var At=(e,n,t)=>{let[r,o]=t,i=e.getValue(n);return i>=r&&i<=o};At.resolveFilterValue=e=>{let[n,t]=e,r=typeof n!="number"?parseFloat(n):n,o=typeof t!="number"?parseFloat(t):t,i=n===null||Number.isNaN(r)?-1/0:r,l=t===null||Number.isNaN(o)?1/0:o;if(i>l){let u=i;i=l,l=u}return[i,l]};At.autoRemove=e=>K(e)||K(e[0])&&K(e[1]);var ne={includesString:nr,includesStringSensitive:rr,equalsString:or,arrIncludes:ir,arrIncludesAll:lr,arrIncludesSome:sr,equals:ar,weakEquals:ur,inNumberRange:At};function K(e){return e==null||e===""}var ni={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],globalFilter:void 0,...e}),getDefaultOptions:e=>({onColumnFiltersChange:G("columnFilters",e),onGlobalFilterChange:G("globalFilter",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100,globalFilterFn:"auto",getColumnCanGlobalFilter:n=>{var t,r;let o=(t=e.getCoreRowModel().flatRows[0])==null||(r=t._getAllCellsByColumnId()[n.id])==null?void 0:r.getValue();return typeof o=="string"||typeof o=="number"}}),createColumn:(e,n)=>({getAutoFilterFn:()=>{let t=n.getCoreRowModel().flatRows[0],r=t?.getValue(e.id);return typeof r=="string"?ne.includesString:typeof r=="number"?ne.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?ne.equals:Array.isArray(r)?ne.arrIncludes:ne.weakEquals},getFilterFn:()=>{var t,r;return We(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(t=(r=n.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?t:ne[e.columnDef.filterFn]},getCanFilter:()=>{var t,r,o;return((t=e.columnDef.enableColumnFilter)!=null?t:!0)&&((r=n.options.enableColumnFilters)!=null?r:!0)&&((o=n.options.enableFilters)!=null?o:!0)&&!!e.accessorFn},getCanGlobalFilter:()=>{var t,r,o,i;return((t=e.columnDef.enableGlobalFilter)!=null?t:!0)&&((r=n.options.enableGlobalFilter)!=null?r:!0)&&((o=n.options.enableFilters)!=null?o:!0)&&((i=n.options.getColumnCanGlobalFilter==null?void 0:n.options.getColumnCanGlobalFilter(e))!=null?i:!0)&&!!e.accessorFn},getIsFiltered:()=>e.getFilterIndex()>-1,getFilterValue:()=>{var t,r;return(t=n.getState().columnFilters)==null||(r=t.find(o=>o.id===e.id))==null?void 0:r.value},getFilterIndex:()=>{var t,r;return(t=(r=n.getState().columnFilters)==null?void 0:r.findIndex(o=>o.id===e.id))!=null?t:-1},setFilterValue:t=>{n.setColumnFilters(r=>{let o=e.getFilterFn(),i=r?.find(s=>s.id===e.id),l=ae(t,i?i.value:void 0);if(Zn(o,l,e)){var u;return(u=r?.filter(s=>s.id!==e.id))!=null?u:[]}let a={id:e.id,value:l};if(i){var d;return(d=r?.map(s=>s.id===e.id?a:s))!=null?d:[]}return r!=null&&r.length?[...r,a]:[a]})},_getFacetedRowModel:n.options.getFacetedRowModel&&n.options.getFacetedRowModel(n,e.id),getFacetedRowModel:()=>e._getFacetedRowModel?e._getFacetedRowModel():n.getPreFilteredRowModel(),_getFacetedUniqueValues:n.options.getFacetedUniqueValues&&n.options.getFacetedUniqueValues(n,e.id),getFacetedUniqueValues:()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,_getFacetedMinMaxValues:n.options.getFacetedMinMaxValues&&n.options.getFacetedMinMaxValues(n,e.id),getFacetedMinMaxValues:()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}),createRow:(e,n)=>({columnFilters:{},columnFiltersMeta:{}}),createTable:e=>({getGlobalAutoFilterFn:()=>ne.includesString,getGlobalFilterFn:()=>{var n,t;let{globalFilterFn:r}=e.options;return We(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(n=(t=e.options.filterFns)==null?void 0:t[r])!=null?n:ne[r]},setColumnFilters:n=>{let t=e.getAllLeafColumns(),r=o=>{var i;return(i=ae(n,o))==null?void 0:i.filter(l=>{let u=t.find(a=>a.id===l.id);if(u){let a=u.getFilterFn();if(Zn(a,l.value,u))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},setGlobalFilter:n=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(n)},resetGlobalFilter:n=>{e.setGlobalFilter(n?void 0:e.initialState.globalFilter)},resetColumnFilters:n=>{var t,r;e.setColumnFilters(n?[]:(t=(r=e.initialState)==null?void 0:r.columnFilters)!=null?t:[])},getPreFilteredRowModel:()=>e.getCoreRowModel(),getFilteredRowModel:()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel()),_getGlobalFacetedRowModel:e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),getGlobalFacetedRowModel:()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),_getGlobalFacetedUniqueValues:e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),getGlobalFacetedUniqueValues:()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,_getGlobalFacetedMinMaxValues:e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),getGlobalFacetedMinMaxValues:()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}})};function Zn(e,n,t){return(e&&e.autoRemove?e.autoRemove(n,t):!1)||typeof n>"u"||typeof n=="string"&&!n}var ri=(e,n,t)=>t.reduce((r,o)=>{let i=o.getValue(e);return r+(typeof i=="number"?i:0)},0),oi=(e,n,t)=>{let r;return t.forEach(o=>{let i=o.getValue(e);i!=null&&(r>i||r===void 0&&i>=i)&&(r=i)}),r},ii=(e,n,t)=>{let r;return t.forEach(o=>{let i=o.getValue(e);i!=null&&(r=i)&&(r=i)}),r},li=(e,n,t)=>{let r,o;return t.forEach(i=>{let l=i.getValue(e);l!=null&&(r===void 0?l>=l&&(r=o=l):(r>l&&(r=l),o{let t=0,r=0;if(n.forEach(o=>{let i=o.getValue(e);i!=null&&(i=+i)>=i&&(++t,r+=i)}),t)return r/t},ai=(e,n)=>{if(!n.length)return;let t=n.map(i=>i.getValue(e));if(!Xo(t))return;if(t.length===1)return t[0];let r=Math.floor(t.length/2),o=t.sort((i,l)=>i-l);return t.length%2!==0?o[r]:(o[r-1]+o[r])/2},ui=(e,n)=>Array.from(new Set(n.map(t=>t.getValue(e))).values()),di=(e,n)=>new Set(n.map(t=>t.getValue(e))).size,ci=(e,n)=>n.length,Mt={sum:ri,min:oi,max:ii,extent:li,mean:si,median:ai,unique:ui,uniqueCount:di,count:ci},gi={getDefaultColumnDef:()=>({aggregatedCell:e=>{var n,t;return(n=(t=e.getValue())==null||t.toString==null?void 0:t.toString())!=null?n:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:G("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,n)=>({toggleGrouping:()=>{n.setGrouping(t=>t!=null&&t.includes(e.id)?t.filter(r=>r!==e.id):[...t??[],e.id])},getCanGroup:()=>{var t,r,o,i;return(t=(r=(o=(i=e.columnDef.enableGrouping)!=null?i:!0)!=null?o:n.options.enableGrouping)!=null?r:!0)!=null?t:!!e.accessorFn},getIsGrouped:()=>{var t;return(t=n.getState().grouping)==null?void 0:t.includes(e.id)},getGroupedIndex:()=>{var t;return(t=n.getState().grouping)==null?void 0:t.indexOf(e.id)},getToggleGroupingHandler:()=>{let t=e.getCanGroup();return()=>{t&&e.toggleGrouping()}},getAutoAggregationFn:()=>{let t=n.getCoreRowModel().flatRows[0],r=t?.getValue(e.id);if(typeof r=="number")return Mt.sum;if(Object.prototype.toString.call(r)==="[object Date]")return Mt.extent},getAggregationFn:()=>{var t,r;if(!e)throw new Error;return We(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(t=(r=n.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?t:Mt[e.columnDef.aggregationFn]}}),createTable:e=>({setGrouping:n=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(n),resetGrouping:n=>{var t,r;e.setGrouping(n?[]:(t=(r=e.initialState)==null?void 0:r.grouping)!=null?t:[])},getPreGroupedRowModel:()=>e.getFilteredRowModel(),getGroupedRowModel:()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())}),createRow:(e,n)=>({getIsGrouped:()=>!!e.groupingColumnId,getGroupingValue:t=>{if(e._groupingValuesCache.hasOwnProperty(t))return e._groupingValuesCache[t];let r=n.getColumn(t);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[t]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[t]):e.getValue(t)},_groupingValuesCache:{}}),createCell:(e,n,t,r)=>({getIsGrouped:()=>n.getIsGrouped()&&n.id===t.groupingColumnId,getIsPlaceholder:()=>!e.getIsGrouped()&&n.getIsGrouped(),getIsAggregated:()=>{var o;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((o=t.subRows)!=null&&o.length)}})};function fi(e,n,t){if(!(n!=null&&n.length)||!t)return e;let r=e.filter(i=>!n.includes(i.id));return t==="remove"?r:[...n.map(i=>e.find(l=>l.id===i)).filter(Boolean),...r]}var pi={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:G("columnOrder",e)}),createTable:e=>({setColumnOrder:n=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(n),resetColumnOrder:n=>{var t;e.setColumnOrder(n?[]:(t=e.initialState.columnOrder)!=null?t:[])},_getOrderColumnsFn:y(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(n,t,r)=>o=>{let i=[];if(!(n!=null&&n.length))i=o;else{let l=[...n],u=[...o];for(;u.length&&l.length;){let a=l.shift(),d=u.findIndex(s=>s.id===a);d>-1&&i.push(u.splice(d,1)[0])}i=[...i,...u]}return fi(i,t,r)},{key:!1})})},It=0,Dt=10,Ft=()=>({pageIndex:It,pageSize:Dt}),_i={getInitialState:e=>({...e,pagination:{...Ft(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:G("pagination",e)}),createTable:e=>{let n=!1,t=!1;return{_autoResetPageIndex:()=>{var r,o;if(!n){e._queue(()=>{n=!0});return}if((r=(o=e.options.autoResetAll)!=null?o:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(t)return;t=!0,e._queue(()=>{e.resetPageIndex(),t=!1})}},setPagination:r=>{let o=i=>ae(r,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(o)},resetPagination:r=>{var o;e.setPagination(r?Ft():(o=e.initialState.pagination)!=null?o:Ft())},setPageIndex:r=>{e.setPagination(o=>{let i=ae(r,o.pageIndex),l=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return i=Math.max(0,Math.min(i,l)),{...o,pageIndex:i}})},resetPageIndex:r=>{var o,i,l;e.setPageIndex(r?It:(o=(i=e.initialState)==null||(l=i.pagination)==null?void 0:l.pageIndex)!=null?o:It)},resetPageSize:r=>{var o,i,l;e.setPageSize(r?Dt:(o=(i=e.initialState)==null||(l=i.pagination)==null?void 0:l.pageSize)!=null?o:Dt)},setPageSize:r=>{e.setPagination(o=>{let i=Math.max(1,ae(r,o.pageSize)),l=o.pageSize*o.pageIndex,u=Math.floor(l/i);return{...o,pageIndex:u,pageSize:i}})},setPageCount:r=>e.setPagination(o=>{var i;let l=ae(r,(i=e.options.pageCount)!=null?i:-1);return typeof l=="number"&&(l=Math.max(-1,l)),{...o,pageCount:l}}),getPageOptions:y(()=>[e.getPageCount()],r=>{let o=[];return r&&r>0&&(o=[...new Array(r)].fill(null).map((i,l)=>l)),o},{key:!1,debug:()=>{var r;return(r=e.options.debugAll)!=null?r:e.options.debugTable}}),getCanPreviousPage:()=>e.getState().pagination.pageIndex>0,getCanNextPage:()=>{let{pageIndex:r}=e.getState().pagination,o=e.getPageCount();return o===-1?!0:o===0?!1:re.setPageIndex(r=>r-1),nextPage:()=>e.setPageIndex(r=>r+1),getPrePaginationRowModel:()=>e.getExpandedRowModel(),getPaginationRowModel:()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),getPageCount:()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getPrePaginationRowModel().rows.length/e.getState().pagination.pageSize)}}}},$t=()=>({left:[],right:[]}),mi={getInitialState:e=>({columnPinning:$t(),...e}),getDefaultOptions:e=>({onColumnPinningChange:G("columnPinning",e)}),createColumn:(e,n)=>({pin:t=>{let r=e.getLeafColumns().map(o=>o.id).filter(Boolean);n.setColumnPinning(o=>{var i,l;if(t==="right"){var u,a;return{left:((u=o?.left)!=null?u:[]).filter(f=>!(r!=null&&r.includes(f))),right:[...((a=o?.right)!=null?a:[]).filter(f=>!(r!=null&&r.includes(f))),...r]}}if(t==="left"){var d,s;return{left:[...((d=o?.left)!=null?d:[]).filter(f=>!(r!=null&&r.includes(f))),...r],right:((s=o?.right)!=null?s:[]).filter(f=>!(r!=null&&r.includes(f)))}}return{left:((i=o?.left)!=null?i:[]).filter(f=>!(r!=null&&r.includes(f))),right:((l=o?.right)!=null?l:[]).filter(f=>!(r!=null&&r.includes(f)))}})},getCanPin:()=>e.getLeafColumns().some(r=>{var o,i;return((o=r.columnDef.enablePinning)!=null?o:!0)&&((i=n.options.enablePinning)!=null?i:!0)}),getIsPinned:()=>{let t=e.getLeafColumns().map(u=>u.id),{left:r,right:o}=n.getState().columnPinning,i=t.some(u=>r?.includes(u)),l=t.some(u=>o?.includes(u));return i?"left":l?"right":!1},getPinnedIndex:()=>{var t,r,o;let i=e.getIsPinned();return i?(t=(r=n.getState().columnPinning)==null||(o=r[i])==null?void 0:o.indexOf(e.id))!=null?t:-1:0}}),createRow:(e,n)=>({getCenterVisibleCells:y(()=>[e._getAllVisibleCells(),n.getState().columnPinning.left,n.getState().columnPinning.right],(t,r,o)=>{let i=[...r??[],...o??[]];return t.filter(l=>!i.includes(l.column.id))},{key:"row.getCenterVisibleCells",debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}}),getLeftVisibleCells:y(()=>[e._getAllVisibleCells(),n.getState().columnPinning.left,,],(t,r)=>(r??[]).map(i=>t.find(l=>l.column.id===i)).filter(Boolean).map(i=>({...i,position:"left"})),{key:"row.getLeftVisibleCells",debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}}),getRightVisibleCells:y(()=>[e._getAllVisibleCells(),n.getState().columnPinning.right],(t,r)=>(r??[]).map(i=>t.find(l=>l.column.id===i)).filter(Boolean).map(i=>({...i,position:"right"})),{key:"row.getRightVisibleCells",debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}})}),createTable:e=>({setColumnPinning:n=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(n),resetColumnPinning:n=>{var t,r;return e.setColumnPinning(n?$t():(t=(r=e.initialState)==null?void 0:r.columnPinning)!=null?t:$t())},getIsSomeColumnsPinned:n=>{var t;let r=e.getState().columnPinning;if(!n){var o,i;return!!((o=r.left)!=null&&o.length||(i=r.right)!=null&&i.length)}return!!((t=r[n])!=null&&t.length)},getLeftLeafColumns:y(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(n,t)=>(t??[]).map(r=>n.find(o=>o.id===r)).filter(Boolean),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugColumns}}),getRightLeafColumns:y(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(n,t)=>(t??[]).map(r=>n.find(o=>o.id===r)).filter(Boolean),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugColumns}}),getCenterLeafColumns:y(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(n,t,r)=>{let o=[...t??[],...r??[]];return n.filter(i=>!o.includes(i.id))},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugColumns}})})},hi={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:G("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>({setRowSelection:n=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(n),resetRowSelection:n=>{var t;return e.setRowSelection(n?{}:(t=e.initialState.rowSelection)!=null?t:{})},toggleAllRowsSelected:n=>{e.setRowSelection(t=>{n=typeof n<"u"?n:!e.getIsAllRowsSelected();let r={...t},o=e.getPreGroupedRowModel().flatRows;return n?o.forEach(i=>{i.getCanSelect()&&(r[i.id]=!0)}):o.forEach(i=>{delete r[i.id]}),r})},toggleAllPageRowsSelected:n=>e.setRowSelection(t=>{let r=typeof n<"u"?n:!e.getIsAllPageRowsSelected(),o={...t};return e.getRowModel().rows.forEach(i=>{Tt(o,i.id,r,e)}),o}),getPreSelectedRowModel:()=>e.getCoreRowModel(),getSelectedRowModel:y(()=>[e.getState().rowSelection,e.getCoreRowModel()],(n,t)=>Object.keys(n).length?Vt(e,t):{rows:[],flatRows:[],rowsById:{}},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable}}),getFilteredSelectedRowModel:y(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(n,t)=>Object.keys(n).length?Vt(e,t):{rows:[],flatRows:[],rowsById:{}},{key:"getFilteredSelectedRowModel",debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable}}),getGroupedSelectedRowModel:y(()=>[e.getState().rowSelection,e.getSortedRowModel()],(n,t)=>Object.keys(n).length?Vt(e,t):{rows:[],flatRows:[],rowsById:{}},{key:"getGroupedSelectedRowModel",debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable}}),getIsAllRowsSelected:()=>{let n=e.getFilteredRowModel().flatRows,{rowSelection:t}=e.getState(),r=!!(n.length&&Object.keys(t).length);return r&&n.some(o=>o.getCanSelect()&&!t[o.id])&&(r=!1),r},getIsAllPageRowsSelected:()=>{let n=e.getPaginationRowModel().flatRows.filter(o=>o.getCanSelect()),{rowSelection:t}=e.getState(),r=!!n.length;return r&&n.some(o=>!t[o.id])&&(r=!1),r},getIsSomeRowsSelected:()=>{var n;let t=Object.keys((n=e.getState().rowSelection)!=null?n:{}).length;return t>0&&t{let n=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:n.filter(t=>t.getCanSelect()).some(t=>t.getIsSelected()||t.getIsSomeSelected())},getToggleAllRowsSelectedHandler:()=>n=>{e.toggleAllRowsSelected(n.target.checked)},getToggleAllPageRowsSelectedHandler:()=>n=>{e.toggleAllPageRowsSelected(n.target.checked)}}),createRow:(e,n)=>({toggleSelected:t=>{let r=e.getIsSelected();n.setRowSelection(o=>{if(t=typeof t<"u"?t:!r,r===t)return o;let i={...o};return Tt(i,e.id,t,n),i})},getIsSelected:()=>{let{rowSelection:t}=n.getState();return kt(e,t)},getIsSomeSelected:()=>{let{rowSelection:t}=n.getState();return er(e,t)==="some"},getIsAllSubRowsSelected:()=>{let{rowSelection:t}=n.getState();return er(e,t)==="all"},getCanSelect:()=>{var t;return typeof n.options.enableRowSelection=="function"?n.options.enableRowSelection(e):(t=n.options.enableRowSelection)!=null?t:!0},getCanSelectSubRows:()=>{var t;return typeof n.options.enableSubRowSelection=="function"?n.options.enableSubRowSelection(e):(t=n.options.enableSubRowSelection)!=null?t:!0},getCanMultiSelect:()=>{var t;return typeof n.options.enableMultiRowSelection=="function"?n.options.enableMultiRowSelection(e):(t=n.options.enableMultiRowSelection)!=null?t:!0},getToggleSelectedHandler:()=>{let t=e.getCanSelect();return r=>{var o;t&&e.toggleSelected((o=r.target)==null?void 0:o.checked)}}})},Tt=(e,n,t,r)=>{var o;let i=r.getRow(n);t?(i.getCanMultiSelect()||Object.keys(e).forEach(l=>delete e[l]),i.getCanSelect()&&(e[n]=!0)):delete e[n],(o=i.subRows)!=null&&o.length&&i.getCanSelectSubRows()&&i.subRows.forEach(l=>Tt(e,l.id,t,r))};function Vt(e,n){let t=e.getState().rowSelection,r=[],o={},i=function(l,u){return l.map(a=>{var d;let s=kt(a,t);if(s&&(r.push(a),o[a.id]=a),(d=a.subRows)!=null&&d.length&&(a={...a,subRows:i(a.subRows)}),s)return a}).filter(Boolean)};return{rows:i(n.rows),flatRows:r,rowsById:o}}function kt(e,n){var t;return(t=n[e.id])!=null?t:!1}function er(e,n,t){if(e.subRows&&e.subRows.length){let r=!0,o=!1;return e.subRows.forEach(i=>{o&&!r||(kt(i,n)?o=!0:r=!1)}),r?"all":o?"some":!1}return!1}var Ot=/([0-9]+)/gm,vi=(e,n,t)=>dr(ue(e.getValue(t)).toLowerCase(),ue(n.getValue(t)).toLowerCase()),yi=(e,n,t)=>dr(ue(e.getValue(t)),ue(n.getValue(t))),bi=(e,n,t)=>Pt(ue(e.getValue(t)).toLowerCase(),ue(n.getValue(t)).toLowerCase()),Si=(e,n,t)=>Pt(ue(e.getValue(t)),ue(n.getValue(t))),wi=(e,n,t)=>{let r=e.getValue(t),o=n.getValue(t);return r>o?1:rPt(e.getValue(t),n.getValue(t));function Pt(e,n){return e===n?0:e>n?1:-1}function ue(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function dr(e,n){let t=e.split(Ot).filter(Boolean),r=n.split(Ot).filter(Boolean);for(;t.length&&r.length;){let o=t.shift(),i=r.shift(),l=parseInt(o,10),u=parseInt(i,10),a=[l,u].sort();if(isNaN(a[0])){if(o>i)return 1;if(i>o)return-1;continue}if(isNaN(a[1]))return isNaN(l)?-1:1;if(l>u)return 1;if(u>l)return-1}return t.length-r.length}var Ve={alphanumeric:vi,alphanumericCaseSensitive:yi,text:bi,textCaseSensitive:Si,datetime:wi,basic:Ci},Ei={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:G("sorting",e),isMultiSortEvent:n=>n.shiftKey}),createColumn:(e,n)=>({getAutoSortingFn:()=>{let t=n.getFilteredRowModel().flatRows.slice(10),r=!1;for(let o of t){let i=o?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return Ve.datetime;if(typeof i=="string"&&(r=!0,i.split(Ot).length>1))return Ve.alphanumeric}return r?Ve.text:Ve.basic},getAutoSortDir:()=>{let t=n.getFilteredRowModel().flatRows[0];return typeof t?.getValue(e.id)=="string"?"asc":"desc"},getSortingFn:()=>{var t,r;if(!e)throw new Error;return We(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(t=(r=n.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?t:Ve[e.columnDef.sortingFn]},toggleSorting:(t,r)=>{let o=e.getNextSortingOrder(),i=typeof t<"u"&&t!==null;n.setSorting(l=>{let u=l?.find(c=>c.id===e.id),a=l?.findIndex(c=>c.id===e.id),d=[],s,f=i?t:o==="desc";if(l!=null&&l.length&&e.getCanMultiSort()&&r?u?s="toggle":s="add":l!=null&&l.length&&a!==l.length-1?s="replace":u?s="toggle":s="replace",s==="toggle"&&(i||o||(s="remove")),s==="add"){var g;d=[...l,{id:e.id,desc:f}],d.splice(0,d.length-((g=n.options.maxMultiSortColCount)!=null?g:Number.MAX_SAFE_INTEGER))}else s==="toggle"?d=l.map(c=>c.id===e.id?{...c,desc:f}:c):s==="remove"?d=l.filter(c=>c.id!==e.id):d=[{id:e.id,desc:f}];return d})},getFirstSortDir:()=>{var t,r;return((t=(r=e.columnDef.sortDescFirst)!=null?r:n.options.sortDescFirst)!=null?t:e.getAutoSortDir()==="desc")?"desc":"asc"},getNextSortingOrder:t=>{var r,o;let i=e.getFirstSortDir(),l=e.getIsSorted();return l?l!==i&&((r=n.options.enableSortingRemoval)==null||r)&&(!(t&&(o=n.options.enableMultiRemove)!=null)||o)?!1:l==="desc"?"asc":"desc":i},getCanSort:()=>{var t,r;return((t=e.columnDef.enableSorting)!=null?t:!0)&&((r=n.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},getCanMultiSort:()=>{var t,r;return(t=(r=e.columnDef.enableMultiSort)!=null?r:n.options.enableMultiSort)!=null?t:!!e.accessorFn},getIsSorted:()=>{var t;let r=(t=n.getState().sorting)==null?void 0:t.find(o=>o.id===e.id);return r?r.desc?"desc":"asc":!1},getSortIndex:()=>{var t,r;return(t=(r=n.getState().sorting)==null?void 0:r.findIndex(o=>o.id===e.id))!=null?t:-1},clearSorting:()=>{n.setSorting(t=>t!=null&&t.length?t.filter(r=>r.id!==e.id):[])},getToggleSortingHandler:()=>{let t=e.getCanSort();return r=>{t&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?n.options.isMultiSortEvent==null?void 0:n.options.isMultiSortEvent(r):!1))}}}),createTable:e=>({setSorting:n=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(n),resetSorting:n=>{var t,r;e.setSorting(n?[]:(t=(r=e.initialState)==null?void 0:r.sorting)!=null?t:[])},getPreSortedRowModel:()=>e.getGroupedRowModel(),getSortedRowModel:()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())})},Ri={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:G("columnVisibility",e)}),createColumn:(e,n)=>({toggleVisibility:t=>{e.getCanHide()&&n.setColumnVisibility(r=>({...r,[e.id]:t??!e.getIsVisible()}))},getIsVisible:()=>{var t,r;return(t=(r=n.getState().columnVisibility)==null?void 0:r[e.id])!=null?t:!0},getCanHide:()=>{var t,r;return((t=e.columnDef.enableHiding)!=null?t:!0)&&((r=n.options.enableHiding)!=null?r:!0)},getToggleVisibilityHandler:()=>t=>{e.toggleVisibility==null||e.toggleVisibility(t.target.checked)}}),createRow:(e,n)=>({_getAllVisibleCells:y(()=>[e.getAllCells(),n.getState().columnVisibility],t=>t.filter(r=>r.column.getIsVisible()),{key:"row._getAllVisibleCells",debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}}),getVisibleCells:y(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(t,r,o)=>[...t,...r,...o],{key:!1,debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}})}),createTable:e=>{let n=(t,r)=>y(()=>[r(),r().filter(o=>o.getIsVisible()).map(o=>o.id).join("_")],o=>o.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),{key:t,debug:()=>{var o;return(o=e.options.debugAll)!=null?o:e.options.debugColumns}});return{getVisibleFlatColumns:n("getVisibleFlatColumns",()=>e.getAllFlatColumns()),getVisibleLeafColumns:n("getVisibleLeafColumns",()=>e.getAllLeafColumns()),getLeftVisibleLeafColumns:n("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),getRightVisibleLeafColumns:n("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),getCenterVisibleLeafColumns:n("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),setColumnVisibility:t=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(t),resetColumnVisibility:t=>{var r;e.setColumnVisibility(t?{}:(r=e.initialState.columnVisibility)!=null?r:{})},toggleAllColumnsVisible:t=>{var r;t=(r=t)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((o,i)=>({...o,[i.id]:t||!(i.getCanHide!=null&&i.getCanHide())}),{}))},getIsAllColumnsVisible:()=>!e.getAllLeafColumns().some(t=>!(t.getIsVisible!=null&&t.getIsVisible())),getIsSomeColumnsVisible:()=>e.getAllLeafColumns().some(t=>t.getIsVisible==null?void 0:t.getIsVisible()),getToggleAllColumnsVisibilityHandler:()=>t=>{var r;e.toggleAllColumnsVisible((r=t.target)==null?void 0:r.checked)}}}},tr=[Qo,Ri,pi,mi,ni,Ei,gi,ti,_i,hi,Zo];function cr(e){var n;(e.debugAll||e.debugTable)&&console.info("Creating Table Instance...");let t={_features:tr},r=t._features.reduce((s,f)=>Object.assign(s,f.getDefaultOptions==null?void 0:f.getDefaultOptions(t)),{}),o=s=>t.options.mergeOptions?t.options.mergeOptions(r,s):{...r,...s},l={...{},...(n=e.initialState)!=null?n:{}};t._features.forEach(s=>{var f;l=(f=s.getInitialState==null?void 0:s.getInitialState(l))!=null?f:l});let u=[],a=!1,d={_features:tr,options:{...r,...e},initialState:l,_queue:s=>{u.push(s),a||(a=!0,Promise.resolve().then(()=>{for(;u.length;)u.shift()();a=!1}).catch(f=>setTimeout(()=>{throw f})))},reset:()=>{t.setState(t.initialState)},setOptions:s=>{let f=ae(s,t.options);t.options=o(f)},getState:()=>t.options.state,setState:s=>{t.options.onStateChange==null||t.options.onStateChange(s)},_getRowId:(s,f,g)=>{var c;return(c=t.options.getRowId==null?void 0:t.options.getRowId(s,f,g))!=null?c:`${g?[g.id,f].join("."):f}`},getCoreRowModel:()=>(t._getCoreRowModel||(t._getCoreRowModel=t.options.getCoreRowModel(t)),t._getCoreRowModel()),getRowModel:()=>t.getPaginationRowModel(),getRow:s=>{let f=t.getRowModel().rowsById[s];if(!f)throw new Error;return f},_getDefaultColumnDef:y(()=>[t.options.defaultColumn],s=>{var f;return s=(f=s)!=null?f:{},{header:g=>{let c=g.header.column.columnDef;return c.accessorKey?c.accessorKey:c.accessorFn?c.id:null},cell:g=>{var c,p;return(c=(p=g.renderValue())==null||p.toString==null?void 0:p.toString())!=null?c:null},...t._features.reduce((g,c)=>Object.assign(g,c.getDefaultColumnDef==null?void 0:c.getDefaultColumnDef()),{}),...s}},{debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns},key:!1}),_getColumnDefs:()=>t.options.columns,getAllColumns:y(()=>[t._getColumnDefs()],s=>{let f=function(g,c,p){return p===void 0&&(p=0),g.map(_=>{let m=Yo(t,_,p,c),v=_;return m.columns=v.columns?f(v.columns,m,p+1):[],m})};return f(s)},{key:!1,debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns}}),getAllFlatColumns:y(()=>[t.getAllColumns()],s=>s.flatMap(f=>f.getFlatColumns()),{key:!1,debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns}}),_getAllFlatColumnsById:y(()=>[t.getAllFlatColumns()],s=>s.reduce((f,g)=>(f[g.id]=g,f),{}),{key:!1,debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns}}),getAllLeafColumns:y(()=>[t.getAllColumns(),t._getOrderColumnsFn()],(s,f)=>{let g=s.flatMap(c=>c.getLeafColumns());return f(g)},{key:!1,debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns}}),getColumn:s=>t._getAllFlatColumnsById()[s]};return Object.assign(t,d),t._features.forEach(s=>Object.assign(t,s.createTable==null?void 0:s.createTable(t))),t}function xi(e,n,t,r){let o=()=>{var l;return(l=i.getValue())!=null?l:e.options.renderFallbackValue},i={id:`${n.id}_${t.id}`,row:n,column:t,getValue:()=>n.getValue(r),renderValue:o,getContext:y(()=>[e,t,n,i],(l,u,a,d)=>({table:l,column:u,row:a,cell:d,getValue:d.getValue,renderValue:d.renderValue}),{key:!1,debug:()=>e.options.debugAll})};return e._features.forEach(l=>{Object.assign(i,l.createCell==null?void 0:l.createCell(i,t,n,e))},{}),i}var Nt=(e,n,t,r,o,i,l)=>{let u={id:n,index:r,original:t,depth:o,parentId:l,_valuesCache:{},_uniqueValuesCache:{},getValue:a=>{if(u._valuesCache.hasOwnProperty(a))return u._valuesCache[a];let d=e.getColumn(a);if(d!=null&&d.accessorFn)return u._valuesCache[a]=d.accessorFn(u.original,r),u._valuesCache[a]},getUniqueValues:a=>{if(u._uniqueValuesCache.hasOwnProperty(a))return u._uniqueValuesCache[a];let d=e.getColumn(a);if(d!=null&&d.accessorFn)return d.columnDef.getUniqueValues?(u._uniqueValuesCache[a]=d.columnDef.getUniqueValues(u.original,r),u._uniqueValuesCache[a]):(u._uniqueValuesCache[a]=[u.getValue(a)],u._uniqueValuesCache[a])},renderValue:a=>{var d;return(d=u.getValue(a))!=null?d:e.options.renderFallbackValue},subRows:i??[],getLeafRows:()=>Jo(u.subRows,a=>a.subRows),getParentRow:()=>u.parentId?e.getRow(u.parentId):void 0,getParentRows:()=>{let a=[],d=u;for(;;){let s=d.getParentRow();if(!s)break;a.push(s),d=s}return a.reverse()},getAllCells:y(()=>[e.getAllLeafColumns()],a=>a.map(d=>xi(e,u,d,d.id)),{key:!1,debug:()=>{var a;return(a=e.options.debugAll)!=null?a:e.options.debugRows}}),_getAllCellsByColumnId:y(()=>[u.getAllCells()],a=>a.reduce((d,s)=>(d[s.column.id]=s,d),{}),{key:"row.getAllCellsByColumnId",debug:()=>{var a;return(a=e.options.debugAll)!=null?a:e.options.debugRows}})};for(let a=0;ay(()=>[e.options.data],n=>{let t={rows:[],flatRows:[],rowsById:{}},r=function(o,i,l){i===void 0&&(i=0);let u=[];for(let d=0;d{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable},onChange:()=>{e._autoResetPageIndex()}})}function fr(e,n,t){return t.options.filterFromLeafRows?Mi(e,n,t):Fi(e,n,t)}function Mi(e,n,t){var r;let o=[],i={},l=(r=t.options.maxLeafRowFilterDepth)!=null?r:100,u=function(a,d){d===void 0&&(d=0);let s=[];for(let g=0;gy(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(n,t,r)=>{if(!n.rows.length||!(t!=null&&t.length)&&!r){for(let g=0;g{var c;let p=e.getColumn(g.id);if(!p)return;let _=p.getFilterFn();_&&o.push({id:g.id,filterFn:_,resolvedValue:(c=_.resolveFilterValue==null?void 0:_.resolveFilterValue(g.value))!=null?c:g.value})});let l=t.map(g=>g.id),u=e.getGlobalFilterFn(),a=e.getAllLeafColumns().filter(g=>g.getCanGlobalFilter());r&&u&&a.length&&(l.push("__global__"),a.forEach(g=>{var c;i.push({id:g.id,filterFn:u,resolvedValue:(c=u.resolveFilterValue==null?void 0:u.resolveFilterValue(r))!=null?c:r})}));let d,s;for(let g=0;g{c.columnFiltersMeta[_]=m})}if(i.length){for(let p=0;p{c.columnFiltersMeta[_]=m})){c.columnFilters.__global__=!0;break}}c.columnFilters.__global__!==!0&&(c.columnFilters.__global__=!1)}}let f=g=>{for(let c=0;c{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable},onChange:()=>{e._autoResetPageIndex()}})}function _r(){return(e,n)=>y(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter,e.getFilteredRowModel()],(t,r,o)=>{if(!t.rows.length||!(r!=null&&r.length)&&!o)return t;let i=[...r.map(u=>u.id).filter(u=>u!==n),o?"__global__":void 0].filter(Boolean),l=u=>{for(let a=0;a{var t;return(t=e.options.debugAll)!=null?t:e.options.debugTable},onChange:()=>{}})}function mr(){return(e,n)=>y(()=>{var t;return[(t=e.getColumn(n))==null?void 0:t.getFacetedRowModel()]},t=>{if(!t)return new Map;let r=new Map;for(let i=0;i{var t;return(t=e.options.debugAll)!=null?t:e.options.debugTable},onChange:()=>{}})}function hr(){return(e,n)=>y(()=>{var t;return[(t=e.getColumn(n))==null?void 0:t.getFacetedRowModel()]},t=>{var r;if(!t)return;let o=(r=t.flatRows[0])==null?void 0:r.getUniqueValues(n);if(typeof o>"u")return;let i=[o,o];for(let l=0;li[1]&&(i[1]=d)}}return i},{key:!1,debug:()=>{var t;return(t=e.options.debugAll)!=null?t:e.options.debugTable},onChange:()=>{}})}function vr(){return e=>y(()=>[e.getState().sorting,e.getPreSortedRowModel()],(n,t)=>{if(!t.rows.length||!(n!=null&&n.length))return t;let r=e.getState().sorting,o=[],i=r.filter(a=>{var d;return(d=e.getColumn(a.id))==null?void 0:d.getCanSort()}),l={};i.forEach(a=>{let d=e.getColumn(a.id);d&&(l[a.id]={sortUndefined:d.columnDef.sortUndefined,invertSorting:d.columnDef.invertSorting,sortingFn:d.getSortingFn()})});let u=a=>{let d=[...a];return d.sort((s,f)=>{for(let c=0;c{var f;o.push(s),(f=s.subRows)!=null&&f.length&&(s.subRows=u(s.subRows))}),d};return{rows:u(t.rows),flatRows:o,rowsById:t.rowsById}},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable},onChange:()=>{e._autoResetPageIndex()}})}function Xe(e,n){return e?$i(e)?P(e,n):e:null}function $i(e){return Vi(e)||typeof e=="function"||Ii(e)}function Vi(e){return typeof e=="function"&&(()=>{let n=Object.getPrototypeOf(e);return n.prototype&&n.prototype.isReactComponent})()}function Ii(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function yr(e){let n={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[t]=V(()=>({current:cr(n)})),[r,o]=V(()=>t.current.initialState);return t.current.setOptions(i=>({...i,...e,state:{...r,...e.state},onStateChange:l=>{o(l),e.onStateChange==null||e.onStateChange(l)}})),t.current}function Ie(){return Ie=Object.assign?Object.assign.bind():function(e){for(var n=1;n"u"&&delete r[i]}),t.options=De({debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Di,rangeExtractor:Ti,onChange:function(){},measureElement:Oi,initialRect:{width:0,height:0},scrollMargin:0,scrollingDelay:150,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1},r)},this.notify=function(){t.options.onChange==null||t.options.onChange(t)},this.cleanup=function(){t.unsubs.filter(Boolean).forEach(function(r){return r()}),t.unsubs=[],t.scrollElement=null},this._didMount=function(){return t.measureElementCache.forEach(t.observer.observe),function(){t.observer.disconnect(),t.cleanup()}},this._willUpdate=function(){var r=t.options.getScrollElement();t.scrollElement!==r&&(t.cleanup(),t.scrollElement=r,t._scrollToOffset(t.scrollOffset,{adjustments:void 0,behavior:void 0}),t.unsubs.push(t.options.observeElementRect(t,function(o){var i=t.scrollRect;t.scrollRect=o,(t.options.horizontal?o.width!==i.width:o.height!==i.height)&&t.maybeNotify()})),t.unsubs.push(t.options.observeElementOffset(t,function(o){t.scrollAdjustments=0,t.scrollOffset!==o&&(t.isScrollingTimeoutId!==null&&(clearTimeout(t.isScrollingTimeoutId),t.isScrollingTimeoutId=null),t.isScrolling=!0,t.scrollDirection=t.scrollOffset=0;u--){var a=r[u];if(!i.has(a.lane)){var d=l.get(a.lane);if(d==null||a.end>d.end?l.set(a.lane,a):a.end0?Math.min.apply(Math,t.pendingMeasuredCacheIndexes):0;t.pendingMeasuredCacheIndexes=[];for(var s=t.measurementsCache.slice(0,d),f=d;f=t.scrollOffset+i?o="end":o="start"),o==="start"?r=r:o==="end"?r=r-i:o==="center"&&(r=r-i/2);var l=t.options.horizontal?"scrollWidth":"scrollHeight",u=t.scrollElement?"document"in t.scrollElement?t.scrollElement.document.documentElement[l]:t.scrollElement[l]:0,a=u-t.getSize();return Math.max(Math.min(a,r),0)},this.getOffsetForIndex=function(r,o){o===void 0&&(o="auto"),r=Math.max(0,Math.min(r,t.options.count-1));var i=Je(t.getMeasurements()[r]);if(o==="auto")if(i.end>=t.scrollOffset+t.getSize()-t.options.scrollPaddingEnd)o="end";else if(i.start<=t.scrollOffset+t.options.scrollPaddingStart)o="start";else return[t.scrollOffset,o];var l=o==="end"?i.end+t.options.scrollPaddingEnd:i.start-t.options.scrollPaddingStart;return[t.getOffsetForAlignment(l,o),o]},this.isDynamicMode=function(){return t.measureElementCache.size>0},this.cancelScrollToIndex=function(){t.scrollToIndexTimeoutId!==null&&(clearTimeout(t.scrollToIndexTimeoutId),t.scrollToIndexTimeoutId=null)},this.scrollToOffset=function(r,o){var i=o===void 0?{}:o,l=i.align,u=l===void 0?"start":l,a=i.behavior;t.cancelScrollToIndex(),a==="smooth"&&t.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),t._scrollToOffset(t.getOffsetForAlignment(r,u),{adjustments:void 0,behavior:a})},this.scrollToIndex=function(r,o){var i=o===void 0?{}:o,l=i.align,u=l===void 0?"auto":l,a=i.behavior;r=Math.max(0,Math.min(r,t.options.count-1)),t.cancelScrollToIndex(),a==="smooth"&&t.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size.");var d=t.getOffsetForIndex(r,u),s=d[0],f=d[1];t._scrollToOffset(s,{adjustments:void 0,behavior:a}),a!=="smooth"&&t.isDynamicMode()&&(t.scrollToIndexTimeoutId=setTimeout(function(){t.scrollToIndexTimeoutId=null;var g=t.measureElementCache.has(t.options.getItemKey(r));if(g){var c=t.getOffsetForIndex(r,f),p=c[0];br(p,t.scrollOffset)||t.scrollToIndex(r,{align:f,behavior:a})}else t.scrollToIndex(r,{align:f,behavior:a})}))},this.scrollBy=function(r,o){var i=o===void 0?{}:o,l=i.behavior;t.cancelScrollToIndex(),l==="smooth"&&t.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),t._scrollToOffset(t.scrollOffset+r,{adjustments:void 0,behavior:l})},this.getTotalSize=function(){var r;return(((r=t.getMeasurements()[t.options.count-1])==null?void 0:r.end)||t.options.paddingStart)-t.options.scrollMargin+t.options.paddingEnd},this._scrollToOffset=function(r,o){var i=o.adjustments,l=o.behavior;t.options.scrollToFn(r,{behavior:l,adjustments:i},t)},this.measure=function(){t.itemSizeCache=new Map,t.notify()},this.setOptions(n),this.scrollRect=this.options.initialRect,this.scrollOffset=this.options.initialOffset,this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(function(r){t.itemSizeCache.set(r.key,r.size)}),this.maybeNotify()},Rr=function(n,t,r,o){for(;n<=t;){var i=(n+t)/2|0,l=r(i);if(lo)t=i-1;else return i}return n>0?n-1:0};function Ai(e){for(var n=e.measurements,t=e.outerSize,r=e.scrollOffset,o=n.length-1,i=function(d){return n[d].start},l=Rr(0,o,i,r),u=l;u{n(t,r,e)}):e.forEach((t,r)=>n(r,t,e))}function et(e){let n=e[S];return n?n.type_:Array.isArray(e)?1:tt(e)?2:nt(e)?3:0}function Lt(e,n){return et(e)===2?e.has(n):Object.prototype.hasOwnProperty.call(e,n)}function Or(e,n,t){let r=et(e);r===2?e.set(n,t):r===3?e.add(t):e[n]=t}function Hi(e,n){return e===n?e!==0||1/e===1/n:e!==e&&n!==n}function tt(e){return e instanceof Map}function nt(e){return e instanceof Set}function T(e){return e.copy_||e.base_}function Gt(e,n){if(tt(e))return new Map(e);if(nt(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!n&&Tr(e))return Se(e)?{...e}:Object.assign(Object.create(null),e);let t=Object.getOwnPropertyDescriptors(e);delete t[S];let r=Reflect.ownKeys(t);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=zi),Object.freeze(e),n&&Ce(e,(t,r)=>Ee(r,!0),!0)),e}function zi(){B(2)}function rt(e){return Object.isFrozen(e)}var Bt={};function fe(e){let n=Bt[e];return n||B(0,e),n}function Li(e,n){Bt[e]||(Bt[e]=n)}var Te;function Ye(){return Te}function Gi(e,n){return{drafts_:[],parent_:e,immer_:n,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Fr(e,n){n&&(fe("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=n)}function Ut(e){jt(e),e.drafts_.forEach(Bi),e.drafts_=null}function jt(e){e===Te&&(Te=e.parent_)}function $r(e){return Te=Gi(Te,e)}function Bi(e){let n=e[S];n.type_===0||n.type_===1?n.revoke_():n.revoked_=!0}function Vr(e,n){n.unfinalizedDrafts_=n.drafts_.length;let t=n.drafts_[0];return e!==void 0&&e!==t?(t[S].modified_&&(Ut(n),B(4)),oe(e)&&(e=Qe(n,e),n.parent_||Ze(n,e)),n.patches_&&fe("Patches").generateReplacementPatches_(t[S].base_,e,n.patches_,n.inversePatches_)):e=Qe(n,t,[]),Ut(n),n.patches_&&n.patchListener_(n.patches_,n.inversePatches_),e!==Dr?e:void 0}function Qe(e,n,t){if(rt(n))return n;let r=n[S];if(!r)return Ce(n,(o,i)=>Ir(e,r,n,o,i,t),!0),n;if(r.scope_!==e)return n;if(!r.modified_)return Ze(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;let o=r.copy_,i=o,l=!1;r.type_===3&&(i=new Set(o),o.clear(),l=!0),Ce(i,(u,a)=>Ir(e,r,o,u,a,t,l)),Ze(e,o,!1),t&&e.patches_&&fe("Patches").generatePatches_(r,t,e.patches_,e.inversePatches_)}return r.copy_}function Ir(e,n,t,r,o,i,l){if(we(o)){let u=i&&n&&n.type_!==3&&!Lt(n.assigned_,r)?i.concat(r):void 0,a=Qe(e,o,u);if(Or(t,r,a),we(a))e.canAutoFreeze_=!1;else return}else l&&t.add(o);if(oe(o)&&!rt(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Qe(e,o),(!n||!n.scope_.parent_)&&Ze(e,o)}}function Ze(e,n,t=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Ee(n,t)}function Ui(e,n){let t=Array.isArray(e),r={type_:t?1:0,scope_:n?n.scope_:Ye(),modified_:!1,finalized_:!1,assigned_:{},parent_:n,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=r,i=Kt;t&&(o=[r],i=Oe);let{revoke:l,proxy:u}=Proxy.revocable(o,i);return r.draft_=u,r.revoke_=l,u}var Kt={get(e,n){if(n===S)return e;let t=T(e);if(!Lt(t,n))return ji(e,t,n);let r=t[n];return e.finalized_||!oe(r)?r:r===Ht(e.base_,n)?(zt(e),e.copy_[n]=Ae(r,e)):r},has(e,n){return n in T(e)},ownKeys(e){return Reflect.ownKeys(T(e))},set(e,n,t){let r=Ar(T(e),n);if(r?.set)return r.set.call(e.draft_,t),!0;if(!e.modified_){let o=Ht(T(e),n),i=o?.[S];if(i&&i.base_===t)return e.copy_[n]=t,e.assigned_[n]=!1,!0;if(Hi(t,o)&&(t!==void 0||Lt(e.base_,n)))return!0;zt(e),re(e)}return e.copy_[n]===t&&(t!==void 0||n in e.copy_)||Number.isNaN(t)&&Number.isNaN(e.copy_[n])||(e.copy_[n]=t,e.assigned_[n]=!0),!0},deleteProperty(e,n){return Ht(e.base_,n)!==void 0||n in e.base_?(e.assigned_[n]=!1,zt(e),re(e)):delete e.assigned_[n],e.copy_&&delete e.copy_[n],!0},getOwnPropertyDescriptor(e,n){let t=T(e),r=Reflect.getOwnPropertyDescriptor(t,n);return r&&{writable:!0,configurable:e.type_!==1||n!=="length",enumerable:r.enumerable,value:t[n]}},defineProperty(){B(11)},getPrototypeOf(e){return Se(e.base_)},setPrototypeOf(){B(12)}},Oe={};Ce(Kt,(e,n)=>{Oe[e]=function(){return arguments[0]=arguments[0][0],n.apply(this,arguments)}});Oe.deleteProperty=function(e,n){return Oe.set.call(this,e,n,void 0)};Oe.set=function(e,n,t){return Kt.set.call(this,e[0],n,t,e[0])};function Ht(e,n){let t=e[S];return(t?T(t):e)[n]}function ji(e,n,t){let r=Ar(n,t);return r?"value"in r?r.value:r.get?.call(e.draft_):void 0}function Ar(e,n){if(!(n in e))return;let t=Se(e);for(;t;){let r=Object.getOwnPropertyDescriptor(t,n);if(r)return r;t=Se(t)}}function re(e){e.modified_||(e.modified_=!0,e.parent_&&re(e.parent_))}function zt(e){e.copy_||(e.copy_=Gt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ki=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(n,t,r)=>{if(typeof n=="function"&&typeof t!="function"){let i=t;t=n;let l=this;return function(a=i,...d){return l.produce(a,s=>t.call(this,s,...d))}}typeof t!="function"&&B(6),r!==void 0&&typeof r!="function"&&B(7);let o;if(oe(n)){let i=$r(this),l=Ae(n,void 0),u=!0;try{o=t(l),u=!1}finally{u?Ut(i):jt(i)}return Fr(i,r),Vr(o,i)}else if(!n||typeof n!="object"){if(o=t(n),o===void 0&&(o=n),o===Dr&&(o=void 0),this.autoFreeze_&&Ee(o,!0),r){let i=[],l=[];fe("Patches").generateReplacementPatches_(n,o,i,l),r(i,l)}return o}else B(1,n)},this.produceWithPatches=(n,t)=>{if(typeof n=="function")return(l,...u)=>this.produceWithPatches(l,a=>n(a,...u));let r,o;return[this.produce(n,t,(l,u)=>{r=l,o=u}),r,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){oe(e)||B(8),we(e)&&(e=qi(e));let n=$r(this),t=Ae(e,void 0);return t[S].isManual_=!0,jt(n),t}finishDraft(e,n){let t=e&&e[S];(!t||!t.isManual_)&&B(9);let{scope_:r}=t;return Fr(r,n),Vr(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,n){let t;for(t=n.length-1;t>=0;t--){let o=n[t];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}t>-1&&(n=n.slice(t+1));let r=fe("Patches").applyPatches_;return we(e)?r(e,n):this.produce(e,o=>r(o,n))}};function Ae(e,n){let t=tt(e)?fe("MapSet").proxyMap_(e,n):nt(e)?fe("MapSet").proxySet_(e,n):Ui(e,n);return(n?n.scope_:Ye()).drafts_.push(t),t}function qi(e){return we(e)||B(10,e),kr(e)}function kr(e){if(!oe(e)||rt(e))return e;let n=e[S],t;if(n){if(!n.modified_)return n.base_;n.finalized_=!0,t=Gt(e,n.scope_.immer_.useStrictShallowCopy_)}else t=Gt(e,!0);return Ce(t,(r,o)=>{Or(t,r,kr(o))}),n&&(n.finalized_=!1),t}function Pr(){class e extends Map{constructor(a,d){super(),this[S]={type_:2,parent_:d,scope_:d?d.scope_:Ye(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:a,draft_:this,isManual_:!1,revoked_:!1}}get size(){return T(this[S]).size}has(a){return T(this[S]).has(a)}set(a,d){let s=this[S];return l(s),(!T(s).has(a)||T(s).get(a)!==d)&&(t(s),re(s),s.assigned_.set(a,!0),s.copy_.set(a,d),s.assigned_.set(a,!0)),this}delete(a){if(!this.has(a))return!1;let d=this[S];return l(d),t(d),re(d),d.base_.has(a)?d.assigned_.set(a,!1):d.assigned_.delete(a),d.copy_.delete(a),!0}clear(){let a=this[S];l(a),T(a).size&&(t(a),re(a),a.assigned_=new Map,Ce(a.base_,d=>{a.assigned_.set(d,!1)}),a.copy_.clear())}forEach(a,d){let s=this[S];T(s).forEach((f,g,c)=>{a.call(d,this.get(g),g,this)})}get(a){let d=this[S];l(d);let s=T(d).get(a);if(d.finalized_||!oe(s)||s!==d.base_.get(a))return s;let f=Ae(s,d);return t(d),d.copy_.set(a,f),f}keys(){return T(this[S]).keys()}values(){let a=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let d=a.next();return d.done?d:{done:!1,value:this.get(d.value)}}}}entries(){let a=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let d=a.next();if(d.done)return d;let s=this.get(d.value);return{done:!1,value:[d.value,s]}}}}[Symbol.iterator](){return this.entries()}}function n(u,a){return new e(u,a)}function t(u){u.copy_||(u.assigned_=new Map,u.copy_=new Map(u.base_))}class r extends Set{constructor(a,d){super(),this[S]={type_:3,parent_:d,scope_:d?d.scope_:Ye(),modified_:!1,finalized_:!1,copy_:void 0,base_:a,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return T(this[S]).size}has(a){let d=this[S];return l(d),d.copy_?!!(d.copy_.has(a)||d.drafts_.has(a)&&d.copy_.has(d.drafts_.get(a))):d.base_.has(a)}add(a){let d=this[S];return l(d),this.has(a)||(i(d),re(d),d.copy_.add(a)),this}delete(a){if(!this.has(a))return!1;let d=this[S];return l(d),i(d),re(d),d.copy_.delete(a)||(d.drafts_.has(a)?d.copy_.delete(d.drafts_.get(a)):!1)}clear(){let a=this[S];l(a),T(a).size&&(i(a),re(a),a.copy_.clear())}values(){let a=this[S];return l(a),i(a),a.copy_.values()}entries(){let a=this[S];return l(a),i(a),a.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(a,d){let s=this.values(),f=s.next();for(;!f.done;)a.call(d,f.value,f.value,this),f=s.next()}}function o(u,a){return new r(u,a)}function i(u){u.copy_||(u.copy_=new Set,u.base_.forEach(a=>{if(oe(a)){let d=Ae(a,u);u.drafts_.set(a,d),u.copy_.add(d)}else u.copy_.add(a)}))}function l(u){u.revoked_&&B(3,JSON.stringify(T(u)))}Li("MapSet",{proxyMap_:n,proxySet_:o})}var N=new Ki,Nr=N.produce,Vl=N.produceWithPatches.bind(N),Il=N.setAutoFreeze.bind(N),Dl=N.setUseStrictShallowCopy.bind(N),Tl=N.applyPatches.bind(N),Ol=N.createDraft.bind(N),Al=N.finishDraft.bind(N);function Hr(e){return{render(n){St(n,e)},unmount(){Ct(e)}}}function ke(e){var n=V(function(){return Ee(typeof e=="function"?e():e,!0)}),t=n[1];return[n[0],be(function(r){t(typeof r=="function"?Nr(r):Ee(r))},[])]}function zr(e,n,t,r,o){window.Shiny.shinyapp.makeRequest(e,n,t,r,o)}function Lr({id:e,cellInfos:n,onSuccess:t,onError:r,columns:o,setData:i,setCellEditMap:l}){let u=n.map(a=>({row_index:a.rowIndex,column_index:a.columnIndex,value:a.value,prev:a.prev}));zr("outputRPC",[e,"cells_update",u],a=>{i(d=>{a.forEach((s,f)=>{let{rowIndex:g,columnIndex:c}=n[f];d[g][c]=s})}),l(d=>{a.forEach((s,f)=>{let{rowIndex:g,columnIndex:c}=n[f],p=`[${g}, ${c}]`,_=d.get(p)??{};_.value=s,_.state="edit-success",d.set(p,_)})}),t(a)},a=>{r(a)},void 0)}var Gr=({id:e,cell:n,columns:t,canEdit:r,editRowIndex:o,editColumnIndex:i,setEditRowIndex:l,setEditColumnIndex:u,cellEditMap:a,setData:d,setCellEditMap:s,maxRowSize:f})=>{let g=n.row.index,c=n.column.columnDef.meta.colIndex,p=n.getValue(),[_,m]=ke(p),v=L(null),[w,C]=V("ready"),E=o===g&&i===c;E&&C("editing");let O=a.has(`[${g}, ${c}]`),A={};A.ready=null,A.editing="cell-edit-editing",A["edit-waiting"]="cell-edit-saving",A["edit-success"]="cell-edit-success",A["edit-failure"]="cell-edit-failure";let D=A[w];function U(){l(null),u(null)}let ot=R=>{R.key==="Escape"&&(R.preventDefault(),U())},it=R=>{if(R.key!=="Tab")return;R.preventDefault();let de=R.shiftKey,ee=i+(de?-1:1);ee<0||ee>=t.length||u(ee)},lt=R=>{if(R.key!=="Enter")return;R.preventDefault();let de=R.shiftKey;console.log(f);let ee=o+(de?-1:1);ee<0||ee>=f||l(ee)},j=R=>{[ot,lt,it].forEach(de=>de(R))},Q=()=>{`${p}`!=`${_}`&&(C("edit-waiting"),Lr({id:e,cellInfos:[{rowIndex:g,columnIndex:c,value:_,prev:p}],onSuccess:R=>{C("edit-success")},onError:R=>{console.error("Error saving tabel cell value!",R),C("edit-failure")},columns:t,setData:d,setCellEditMap:s}))},st=()=>{Q()};k(()=>{m(p)},[p,m]),k(()=>{if(E)return v.current.focus(),v.current.select(),window.document.querySelector("body").addEventListener("click",R=>{U()}),()=>{window.document.querySelector("body").removeEventListener("click",U)}},[E]);function Z(R){E&&R.target.select()}function Pe(R){console.log("on change!"),m(R.target.value)}let Re,pe;return w==="edit-waiting"?pe=b.createElement("em",null,_):E?pe=b.createElement("input",{value:_,onChange:Pe,onBlur:st,onFocus:Z,onKeyDown:j,ref:v}):(Re=R=>{console.log("on ready click!",R.target),l(g),u(c)},w==="edit-failure"&&console.log("Render edit failure"),pe=Xe(n.column.columnDef.cell,n.getContext())),b.createElement("td",{key:n.id,onClick:Re,className:D},pe)};function Br(e,n,t){let r=Object.assign({top:0,right:0,bottom:0,left:0},t),o=e,i=o.scrollTop+r.top,l=o.scrollLeft+r.left,u=i+o.clientHeight-r.top-r.bottom,a=l+o.clientWidth-r.left-r.right;for(let d=0;d=i&&f<=u&&g>=l&&g<=a)return s}return null}function qt(e,n){return document?.defaultView?.getComputedStyle(e,null)?.getPropertyValue(n)}var Kr=e=>{let[n,t]=V(!1),{range:r,from:o,to:i,onRangeChange:l}=e;return b.createElement(Wi,{range:r,value:[o,i],editing:n,onValueChange:u=>l(...u),onFocus:()=>t(!0),onBlur:()=>t(!1)})};var Wi=e=>{let[n,t]=e.value,{editing:r,onFocus:o}=e,i=L(null),l=L(null);return b.createElement("div",{onBlur:u=>{if(!u.currentTarget.contains(u.relatedTarget))return e.onBlur()},onFocus:()=>o(),style:{display:"flex",gap:"0.5rem"}},b.createElement("input",{ref:i,className:`form-control form-control-sm ${i.current?.checkValidity()?"":"is-invalid"}`,style:{flex:"1 1 0",width:"0"},type:"number",placeholder:Ur(r,"Min",e.range()[0]),defaultValue:n,step:"any",onChange:u=>{let a=jr(u.target.value);i.current.classList.toggle("is-invalid",!u.target.checkValidity()),e.onValueChange([a,t])}}),b.createElement("input",{ref:l,className:`form-control form-control-sm ${l.current?.checkValidity()?"":"is-invalid"}`,style:{flex:"1 1 0",width:"0"},type:"number",placeholder:Ur(r,"Max",e.range()[1]),defaultValue:t,step:"any",onChange:u=>{let a=jr(u.target.value);l.current.classList.toggle("is-invalid",!u.target.checkValidity()),e.onValueChange([n,a])}}))};function Ur(e,n,t){return e?typeof t>"u"?n:`${n} (${t})`:null}function jr(e){if(e!=="")return+e}function qr(e){return e?{getFilteredRowModel:pr(),getFacetedRowModel:_r(),getFacetedUniqueValues:mr(),getFacetedMinMaxValues:hr(),filterFns:{substring:(n,t,r,o)=>n.getValue(t).toString().includes(r)}}:{}}var Wr=({header:e,className:n,...t})=>{if((e.column.columnDef.meta?.typeHint).type==="numeric"){let[o,i]=e.column.getFilterValue()??[void 0,void 0];return Kr({from:o,to:i,range:()=>e.column.getFacetedMinMaxValues()??[void 0,void 0],onRangeChange:(u,a)=>e.column.setFilterValue([u,a])})}return b.createElement("input",{...t,className:`form-control form-control-sm ${n}`,type:"text",onChange:o=>e.column.setFilterValue(o.target.value)})};var H=class e{static{this._empty=new e(new Set)}constructor(n){this._set=n}static empty(){return this._empty}static just(...n){return this.empty().add(...n)}has(n){return this._set.has(n)}add(...n){let t=new Set(this._set.keys());for(let r of n)t.add(r);return new e(t)}toggle(n){return this.has(n)?this.delete(n):this.add(n)}delete(n){let t=new Set(this._set.keys());return t.delete(n),new e(t)}clear(){return e.empty()}[Symbol.iterator](){return this._set[Symbol.iterator]()}toList(){return[...this._set.keys()]}};var Wt=(o=>(o.None="none",o.Single="single_row",o.Multiple="multiple_row",o.MultiNative="multi-native_row",o))(Wt||{});function Jr(e,n,t,r){let[o,i]=V(H.empty()),[l,u]=V(null),a=s=>{if(e==="none")return;let f=s.currentTarget,g=n(f),c=Xi(e,r,o,s,g,l);c&&(i(c.selection),c.anchor&&(u(g),f.focus()),s.preventDefault())},d=s=>{if(e==="none")return;let f=s.currentTarget,g=n(f),c=o.has(g);if(e==="single_row"){if(s.key===" "||s.key==="Enter")o.has(g)?i(H.empty()):i(H.just(g)),s.preventDefault();else if(s.key==="ArrowUp"||s.key==="ArrowDown"){let p=t(g,s.key==="ArrowUp"?-1:1);p&&(s.preventDefault(),c&&i(H.just(p)))}}else e==="multiple_row"&&(s.key===" "||s.key==="Enter"?(i(o.toggle(g)),s.preventDefault()):(s.key==="ArrowUp"||s.key==="ArrowDown")&&t(g,s.key==="ArrowUp"?-1:1)&&s.preventDefault())};return{has(s){return o.has(s)},set(s,f){i(f?o.add(s):o.delete(s))},setMultiple(s){i(H.just(...s))},clear(){i(o.clear())},keys(){return o},itemHandlers(){return{onMouseDown:a,onKeyDown:d}}}}var Xr=/^mac/i.test(window.navigator.userAgentData?.platform??window.navigator.platform);function Xi(e,n,t,r,o,i){let{shiftKey:l,altKey:u}=r,a=Xr?r.metaKey:r.ctrlKey;if((Xr?r.ctrlKey:r.metaKey)||u)return null;if(e==="multiple_row")return{selection:t.toggle(o),anchor:!0};if(e==="single_row")return a&&!l?t.has(o)?{selection:H.empty(),anchor:!0}:{selection:H.just(o),anchor:!0}:{selection:H.just(o),anchor:!0};if(e==="multi-native_row")if(l&&a){let s=n(i,o);return{selection:t.add(...s)}}else{if(a)return{selection:t.toggle(o),anchor:!0};if(l){if(i!==null&&n){let s=n(i,o);return{selection:H.just(...s)}}}else return{selection:H.just(o),anchor:!0}}}var Yr={className:"sort-arrow",viewBox:[-1,-1,2,2].map(e=>e*1.4).join(" "),width:"100%",height:"100%",style:{paddingLeft:"3px"}},Qr={stroke:"#333333",strokeWidth:"0.6",fill:"transparent"},Ji=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",...Yr},b.createElement("path",{d:"M -1 0.5 L 0 -0.5 L 1 0.5",...Qr,strokeLinecap:"round"})),Yi=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",...Yr},b.createElement("path",{d:"M -1 -0.5 L 0 0.5 L 1 -0.5",...Qr,strokeLinecap:"round"})),Zr=({direction:e})=>{if(!e)return null;if(e==="asc")return Ji;if(e==="desc")return Yi;throw new Error(`Unexpected sort direction: '${e}'`)};var eo=` *, *::before, *::after { box-sizing: border-box; } -.shiny-data-grid { +shiny-data-frame { --shiny-datagrid-font-size: 0.9em; --shiny-datagrid-padding-x: 0.5em; --shiny-datagrid-padding-y: 0.3em; @@ -24,6 +30,14 @@ var ft=` ); --shiny-datagrid-grid-body-selected-bgcolor: #b4d5fe; --shiny-datagrid-grid-body-selected-color: var(--bs-dark); + --shiny-datagrid-table-cell-edit-success-border-color: color-mix(in srgb, var(--bs-success) 20%, transparent); + --shiny-datagrid-table-cell-edit-success-border-style: var(--shiny-datagrid-grid-gridlines-style); + --shiny-datagrid-table-cell-edit-success-bgcolor: color-mix(in srgb, var(--bs-success) 10%, transparent); + --shiny-datagrid-table-cell-edit-failure-border-color: color-mix(in srgb, var(--bs-danger) 40%, transparent); + --shiny-datagrid-table-cell-edit-failure-border-style: var(--shiny-datagrid-grid-gridlines-style); + --shiny-datagrid-table-cell-edit-failure-bgcolor: color-mix(in srgb, var(--bs-danger) 10%, transparent); + --shiny-datagrid-table-cell-edit-saving-color: var(--bs-gray-500); + --shiny-datagrid-table-cell-edit-saving-font-style: italic; } .shiny-data-grid svg.sort-arrow { @@ -171,13 +185,32 @@ shiny-data-frame:has(> div > .shiny-data-grid:not(.scrolling)) { } shiny-data-frame > div:has(> .shiny-data-grid:not(.scrolling)) { flex: 0 0 auto; -}`;var se,h,vt,sr,Q,pt,yt,Fe,bt,fe={},St=[],ur=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,me=Array.isArray;function G(e,n){for(var t in n)e[t]=n[t];return e}function Ct(e){var n=e.parentNode;n&&n.removeChild(e)}function D(e,n,t){var r,o,i,l={};for(i in n)i=="key"?r=n[i]:i=="ref"?o=n[i]:l[i]=n[i];if(arguments.length>2&&(l.children=arguments.length>3?se.call(arguments,2):t),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)l[i]===void 0&&(l[i]=e.defaultProps[i]);return ie(e,l,r,o,null)}function ie(e,n,t,r,o){var i={type:e,props:n,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:o??++vt};return o==null&&h.vnode!=null&&h.vnode(i),i}function Me(){return{current:null}}function H(e){return e.children}function T(e,n){this.props=e,this.context=n}function le(e,n){if(n==null)return e.__?le(e.__,e.__.__k.indexOf(e)+1):null;for(var t;nn&&Q.sort(Fe));pe.__r=0}function Rt(e,n,t,r,o,i,l,u,a,c){var s,f,g,d,p,_,m,v=r&&r.__k||St,S=v.length;for(t.__k=[],s=0;s0?ie(d.type,d.props,d.key,d.ref?d.ref:null,d.__v):d)!=null){if(d.__=t,d.__b=t.__b+1,(g=v[s])===null||g&&d.key==g.key&&d.type===g.type)v[s]=void 0;else for(f=0;f=0;n--)if((t=e.__k[n])&&(r=Ft(t)))return r}return null}function ar(e,n,t,r,o){var i;for(i in t)i==="children"||i==="key"||i in n||_e(e,i,null,t[i],r);for(i in n)o&&typeof n[i]!="function"||i==="children"||i==="key"||i==="value"||i==="checked"||t[i]===n[i]||_e(e,i,n[i],t[i],r)}function _t(e,n,t){n[0]==="-"?e.setProperty(n,t??""):e[n]=t==null?"":typeof t!="number"||ur.test(n)?t:t+"px"}function _e(e,n,t,r,o){var i;e:if(n==="style")if(typeof t=="string")e.style.cssText=t;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(n in r)t&&n in t||_t(e.style,n,"");if(t)for(n in t)r&&t[n]===r[n]||_t(e.style,n,t[n])}else if(n[0]==="o"&&n[1]==="n")i=n!==(n=n.replace(/Capture$/,"")),n=n.toLowerCase()in e?n.toLowerCase().slice(2):n.slice(2),e.l||(e.l={}),e.l[n+i]=t,t?r||e.addEventListener(n,i?ht:mt,i):e.removeEventListener(n,i?ht:mt,i);else if(n!=="dangerouslySetInnerHTML"){if(o)n=n.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(n!=="width"&&n!=="height"&&n!=="href"&&n!=="list"&&n!=="form"&&n!=="tabIndex"&&n!=="download"&&n!=="rowSpan"&&n!=="colSpan"&&n in e)try{e[n]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&n[4]!=="-"?e.removeAttribute(n):e.setAttribute(n,t))}}function mt(e){return this.l[e.type+!1](h.event?h.event(e):e)}function ht(e){return this.l[e.type+!0](h.event?h.event(e):e)}function Ve(e,n,t,r,o,i,l,u,a){var c,s,f,g,d,p,_,m,v,S,C,F,x,N,q,M=n.type;if(n.constructor!==void 0)return null;t.__h!=null&&(a=t.__h,u=n.__e=t.__e,n.__h=null,i=[u]),(c=h.__b)&&c(n);try{e:if(typeof M=="function"){if(m=n.props,v=(c=M.contextType)&&r[c.__c],S=c?v?v.props.value:c.__:r,t.__c?_=(s=n.__c=t.__c).__=s.__E:("prototype"in M&&M.prototype.render?n.__c=s=new M(m,S):(n.__c=s=new T(m,S),s.constructor=M,s.render=cr),v&&v.sub(s),s.props=m,s.state||(s.state={}),s.context=S,s.__n=r,f=s.__d=!0,s.__h=[],s._sb=[]),s.__s==null&&(s.__s=s.state),M.getDerivedStateFromProps!=null&&(s.__s==s.state&&(s.__s=G({},s.__s)),G(s.__s,M.getDerivedStateFromProps(m,s.__s))),g=s.props,d=s.state,s.__v=n,f)M.getDerivedStateFromProps==null&&s.componentWillMount!=null&&s.componentWillMount(),s.componentDidMount!=null&&s.__h.push(s.componentDidMount);else{if(M.getDerivedStateFromProps==null&&m!==g&&s.componentWillReceiveProps!=null&&s.componentWillReceiveProps(m,S),!s.__e&&s.shouldComponentUpdate!=null&&s.shouldComponentUpdate(m,s.__s,S)===!1||n.__v===t.__v){for(n.__v!==t.__v&&(s.props=m,s.state=s.__s,s.__d=!1),s.__e=!1,n.__e=t.__e,n.__k=t.__k,n.__k.forEach(function(Y){Y&&(Y.__=n)}),C=0;C2&&(u.children=arguments.length>3?se.call(arguments,2):t),ie(e.type,u,r||e.key,o||e.ref,null)}function De(e,n){var t={__c:n="__cC"+bt++,__:e,Consumer:function(r,o){return r.children(o)},Provider:function(r){var o,i;return this.getChildContext||(o=[],(i={})[n]=this,this.getChildContext=function(){return i},this.shouldComponentUpdate=function(l){this.props.value!==l.value&&o.some(function(u){u.__e=!0,$e(u)})},this.sub=function(l){o.push(l);var u=l.componentWillUnmount;l.componentWillUnmount=function(){o.splice(o.indexOf(l),1),u&&u.call(l)}}),r.children}};return t.Provider.__=t.Consumer.contextType=t}se=St.slice,h={__e:function(e,n,t,r){for(var o,i,l;n=n.__;)if((o=n.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),l=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),l=o.__d),l)return o.__E=o}catch(u){e=u}throw e}},vt=0,sr=function(e){return e!=null&&e.constructor===void 0},T.prototype.setState=function(e,n){var t;t=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=G({},this.state),typeof e=="function"&&(e=e(G({},t),this.props)),e&&G(t,e),e!=null&&this.__v&&(n&&this._sb.push(n),$e(this))},T.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),$e(this))},T.prototype.render=H,Q=[],yt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Fe=function(e,n){return e.__v.__b-n.__v.__b},pe.__r=0,bt=0;var W,w,Te,Dt,te=0,Pt=[],he=[],Tt=h.__b,At=h.__r,Ot=h.diffed,Nt=h.__c,kt=h.unmount;function ne(e,n){h.__h&&h.__h(w,e,te||n),te=0;var t=w.__H||(w.__H={__:[],__h:[]});return e>=t.__.length&&t.__.push({__V:he}),t.__[e]}function I(e){return te=1,ue(Ut,e)}function ue(e,n,t){var r=ne(W++,2);if(r.t=e,!r.__c&&(r.__=[t?t(n):Ut(void 0,n),function(u){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,u);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=w,!w.u)){var o=function(u,a,c){if(!r.__c.__H)return!0;var s=r.__c.__H.__.filter(function(g){return g.__c});if(s.every(function(g){return!g.__N}))return!i||i.call(this,u,a,c);var f=!1;return s.forEach(function(g){if(g.__N){var d=g.__[0];g.__=g.__N,g.__N=void 0,d!==g.__[0]&&(f=!0)}}),!(!f&&r.__c.props===u)&&(!i||i.call(this,u,a,c))};w.u=!0;var i=w.shouldComponentUpdate,l=w.componentWillUpdate;w.componentWillUpdate=function(u,a,c){if(this.__e){var s=i;i=void 0,o(u,a,c),i=s}l&&l.call(this,u,a,c)},w.shouldComponentUpdate=o}return r.__N||r.__}function B(e,n){var t=ne(W++,3);!h.__s&&Oe(t.__H,n)&&(t.__=e,t.i=n,w.__H.__h.push(t))}function L(e,n){var t=ne(W++,4);!h.__s&&Oe(t.__H,n)&&(t.__=e,t.i=n,w.__h.push(t))}function z(e){return te=5,U(function(){return{current:e}},[])}function Lt(e,n,t){te=6,L(function(){return typeof e=="function"?(e(n()),function(){return e(null)}):e?(e.current=n(),function(){return e.current=null}):void 0},t==null?t:t.concat(e))}function U(e,n){var t=ne(W++,7);return Oe(t.__H,n)?(t.__V=e(),t.i=n,t.__h=e,t.__V):t.__}function ye(e,n){return te=8,U(function(){return e},n)}function zt(e){var n=w.context[e.__c],t=ne(W++,9);return t.c=e,n?(t.__==null&&(t.__=!0,n.sub(w)),n.props.value):e.__}function Gt(e,n){h.useDebugValue&&h.useDebugValue(n?n(e):e)}function Bt(){var e=ne(W++,11);if(!e.__){for(var n=w.__v;n!==null&&!n.__m&&n.__!==null;)n=n.__;var t=n.__m||(n.__m=[0,0]);e.__="P"+t[0]+"-"+t[1]++}return e.__}function gr(){for(var e;e=Pt.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(ve),e.__H.__h.forEach(Ae),e.__H.__h=[]}catch(n){e.__H.__h=[],h.__e(n,e.__v)}}h.__b=function(e){w=null,Tt&&Tt(e)},h.__r=function(e){At&&At(e),W=0;var n=(w=e.__c).__H;n&&(Te===w?(n.__h=[],w.__h=[],n.__.forEach(function(t){t.__N&&(t.__=t.__N),t.__V=he,t.__N=t.i=void 0})):(n.__h.forEach(ve),n.__h.forEach(Ae),n.__h=[],W=0)),Te=w},h.diffed=function(e){Ot&&Ot(e);var n=e.__c;n&&n.__H&&(n.__H.__h.length&&(Pt.push(n)!==1&&Dt===h.requestAnimationFrame||((Dt=h.requestAnimationFrame)||fr)(gr)),n.__H.__.forEach(function(t){t.i&&(t.__H=t.i),t.__V!==he&&(t.__=t.__V),t.i=void 0,t.__V=he})),Te=w=null},h.__c=function(e,n){n.some(function(t){try{t.__h.forEach(ve),t.__h=t.__h.filter(function(r){return!r.__||Ae(r)})}catch(r){n.some(function(o){o.__h&&(o.__h=[])}),n=[],h.__e(r,t.__v)}}),Nt&&Nt(e,n)},h.unmount=function(e){kt&&kt(e);var n,t=e.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{ve(r)}catch(o){n=o}}),t.__H=void 0,n&&h.__e(n,t.__v))};var Ht=typeof requestAnimationFrame=="function";function fr(e){var n,t=function(){clearTimeout(r),Ht&&cancelAnimationFrame(n),setTimeout(e)},r=setTimeout(t,100);Ht&&(n=requestAnimationFrame(t))}function ve(e){var n=w,t=e.__c;typeof t=="function"&&(e.__c=void 0,t()),w=n}function Ae(e){var n=w;e.__c=e.__(),w=n}function Oe(e,n){return!e||e.length!==n.length||n.some(function(t,r){return t!==e[r]})}function Ut(e,n){return typeof n=="function"?n(e):n}function Zt(e,n){for(var t in n)e[t]=n[t];return e}function ke(e,n){for(var t in e)if(t!=="__source"&&!(t in n))return!0;for(var r in n)if(r!=="__source"&&e[r]!==n[r])return!0;return!1}function Ne(e,n){return e===n&&(e!==0||1/e==1/n)||e!=e&&n!=n}function He(e){this.props=e}function pr(e,n){function t(o){var i=this.props.ref,l=i==o.ref;return!l&&i&&(i.call?i(null):i.current=null),n?!n(this.props,o)||!l:ke(this.props,o)}function r(o){return this.shouldComponentUpdate=t,D(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r}(He.prototype=new T).isPureReactComponent=!0,He.prototype.shouldComponentUpdate=function(e,n){return ke(this.props,e)||ke(this.state,n)};var jt=h.__b;h.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),jt&&jt(e)};var _r=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function mr(e){function n(t){var r=Zt({},t);return delete r.ref,e(r,t.ref||null)}return n.$$typeof=_r,n.render=n,n.prototype.isReactComponent=n.__f=!0,n.displayName="ForwardRef("+(e.displayName||e.name)+")",n}var qt=function(e,n){return e==null?null:P(P(e).map(n))},hr={map:qt,forEach:qt,count:function(e){return e?P(e).length:0},only:function(e){var n=P(e);if(n.length!==1)throw"Children.only";return n[0]},toArray:P},vr=h.__e;h.__e=function(e,n,t,r){if(e.then){for(var o,i=n;i=i.__;)if((o=i.__c)&&o.__c)return n.__e==null&&(n.__e=t.__e,n.__k=t.__k),o.__c(e,n)}vr(e,n,t,r)};var Kt=h.unmount;function en(e,n,t){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Zt({},e)).__c!=null&&(e.__c.__P===t&&(e.__c.__P=n),e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return en(r,n,t)})),e}function tn(e,n,t){return e&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return tn(r,n,t)}),e.__c&&e.__c.__P===n&&(e.__e&&t.insertBefore(e.__e,e.__d),e.__c.__e=!0,e.__c.__P=t)),e}function be(){this.__u=0,this.t=null,this.__b=null}function nn(e){var n=e.__.__c;return n&&n.__a&&n.__a(e)}function yr(e){var n,t,r;function o(i){if(n||(n=e()).then(function(l){t=l.default||l},function(l){r=l}),r)throw r;if(!t)throw n;return D(t,i)}return o.displayName="Lazy",o.__f=!0,o}function ae(){this.u=null,this.o=null}h.unmount=function(e){var n=e.__c;n&&n.__R&&n.__R(),n&&e.__h===!0&&(e.type=null),Kt&&Kt(e)},(be.prototype=new T).__c=function(e,n){var t=n.__c,r=this;r.t==null&&(r.t=[]),r.t.push(t);var o=nn(r.__v),i=!1,l=function(){i||(i=!0,t.__R=null,o?o(u):u())};t.__R=l;var u=function(){if(!--r.__u){if(r.state.__a){var c=r.state.__a;r.__v.__k[0]=tn(c,c.__c.__P,c.__c.__O)}var s;for(r.setState({__a:r.__b=null});s=r.t.pop();)s.forceUpdate()}},a=n.__h===!0;r.__u++||a||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(l,l)},be.prototype.componentWillUnmount=function(){this.t=[]},be.prototype.render=function(e,n){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=en(this.__b,t,r.__O=r.__P)}this.__b=null}var o=n.__a&&D(H,null,e.fallback);return o&&(o.__h=null),[D(H,null,n.__a?null:e.children),o]};var Wt=function(e,n,t){if(++t[1]===t[0]&&e.o.delete(n),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.o.size))for(t=e.u;t;){for(;t.length>3;)t.pop()();if(t[1]>>1,1),n.i.removeChild(r)}}),ee(D(br,{context:n.context},e.__v),n.l)):n.l&&n.componentWillUnmount()}function Cr(e,n){var t=D(Sr,{__v:e,i:n});return t.containerInfo=n,t}(ae.prototype=new T).__a=function(e){var n=this,t=nn(n.__v),r=n.o.get(e);return r[0]++,function(o){var i=function(){n.props.revealOrder?(r.push(o),Wt(n,e,r)):o()};t?t(i):i()}},ae.prototype.render=function(e){this.u=null,this.o=new Map;var n=P(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&n.reverse();for(var t=n.length;t--;)this.o.set(n[t],this.u=[1,0,this.u]);return e.children},ae.prototype.componentDidUpdate=ae.prototype.componentDidMount=function(){var e=this;this.o.forEach(function(n,t){Wt(e,t,n)})};var rn=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,wr=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Rr=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Er=/[A-Z0-9]/g,xr=typeof document<"u",Fr=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Pe(e,n,t){return n.__k==null&&(n.textContent=""),ee(e,n),typeof t=="function"&&t(),e?e.__c:null}function on(e,n,t){return Ie(e,n),typeof t=="function"&&t(),e?e.__c:null}T.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(T.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(n){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:n})}})});var Xt=h.event;function $r(){}function Mr(){return this.cancelBubble}function Vr(){return this.defaultPrevented}h.event=function(e){return Xt&&(e=Xt(e)),e.persist=$r,e.isPropagationStopped=Mr,e.isDefaultPrevented=Vr,e.nativeEvent=e};var Le,Ir={enumerable:!1,configurable:!0,get:function(){return this.class}},Jt=h.vnode;h.vnode=function(e){typeof e.type=="string"&&function(n){var t=n.props,r=n.type,o={};for(var i in t){var l=t[i];if(!(i==="value"&&"defaultValue"in t&&l==null||xr&&i==="children"&&r==="noscript"||i==="class"||i==="className")){var u=i.toLowerCase();i==="defaultValue"&&"value"in t&&t.value==null?i="value":i==="download"&&l===!0?l="":u==="ondoubleclick"?i="ondblclick":u!=="onchange"||r!=="input"&&r!=="textarea"||Fr(t.type)?u==="onfocus"?i="onfocusin":u==="onblur"?i="onfocusout":Rr.test(i)?i=u:r.indexOf("-")===-1&&wr.test(i)?i=i.replace(Er,"-$&").toLowerCase():l===null&&(l=void 0):u=i="oninput",u==="oninput"&&o[i=u]&&(i="oninputCapture"),o[i]=l}}r=="select"&&o.multiple&&Array.isArray(o.value)&&(o.value=P(t.children).forEach(function(a){a.props.selected=o.value.indexOf(a.props.value)!=-1})),r=="select"&&o.defaultValue!=null&&(o.value=P(t.children).forEach(function(a){a.props.selected=o.multiple?o.defaultValue.indexOf(a.props.value)!=-1:o.defaultValue==a.props.value})),t.class&&!t.className?(o.class=t.class,Object.defineProperty(o,"className",Ir)):(t.className&&!t.class||t.class&&t.className)&&(o.class=o.className=t.className),n.props=o}(e),e.$$typeof=rn,Jt&&Jt(e)};var Yt=h.__r;h.__r=function(e){Yt&&Yt(e),Le=e.__c};var Qt=h.diffed;h.diffed=function(e){Qt&&Qt(e);var n=e.props,t=e.__e;t!=null&&e.type==="textarea"&&"value"in n&&n.value!==t.value&&(t.value=n.value==null?"":n.value),Le=null};var Dr={ReactCurrentDispatcher:{current:{readContext:function(e){return Le.__n[e.__c].props.value}}}};function Tr(e){return D.bind(null,e)}function ln(e){return!!e&&e.$$typeof===rn}function Ar(e){return ln(e)?It.apply(null,arguments):e}function ze(e){return!!e.__k&&(ee(null,e),!0)}function Or(e){return e&&(e.base||e.nodeType===1&&e)||null}var Nr=function(e,n){return e(n)},kr=function(e,n){return e(n)},Ge=H;function sn(e){e()}function Hr(e){return e}function Pr(){return[!1,sn]}var Lr=L;function zr(e,n){var t=n(),r=I({h:{__:t,v:n}}),o=r[0].h,i=r[1];return L(function(){o.__=t,o.v=n,Ne(o.__,n())||i({h:o})},[e,t,n]),B(function(){return Ne(o.__,o.v())||i({h:o}),e(function(){Ne(o.__,o.v())||i({h:o})})},[e]),t}var b={useState:I,useId:Bt,useReducer:ue,useEffect:B,useLayoutEffect:L,useInsertionEffect:Lr,useTransition:Pr,useDeferredValue:Hr,useSyncExternalStore:zr,startTransition:sn,useRef:z,useImperativeHandle:Lt,useMemo:U,useCallback:ye,useContext:zt,useDebugValue:Gt,version:"17.0.2",Children:hr,render:Pe,hydrate:on,unmountComponentAtNode:ze,createPortal:Cr,createElement:D,createContext:De,createFactory:Tr,cloneElement:Ar,createRef:Me,Fragment:H,isValidElement:ln,findDOMNode:Or,Component:T,PureComponent:He,memo:pr,forwardRef:mr,flushSync:kr,unstable_batchedUpdates:Nr,StrictMode:Ge,Suspense:be,SuspenseList:ae,lazy:yr,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Dr};function X(e,n){return typeof e=="function"?e(n):e}function A(e,n){return t=>{n.setState(r=>({...r,[e]:X(t,r[e])}))}}function Re(e){return e instanceof Function}function Gr(e){return Array.isArray(e)&&e.every(n=>typeof n=="number")}function Br(e,n){let t=[],r=o=>{o.forEach(i=>{t.push(i);let l=n(i);l!=null&&l.length&&r(l)})};return r(e),t}function y(e,n,t){let r=[],o;return()=>{let i;t.key&&t.debug&&(i=Date.now());let l=e();if(!(l.length!==r.length||l.some((c,s)=>r[s]!==c)))return o;r=l;let a;if(t.key&&t.debug&&(a=Date.now()),o=n(...l),t==null||t.onChange==null||t.onChange(o),t.key&&t.debug&&t!=null&&t.debug()){let c=Math.round((Date.now()-i)*100)/100,s=Math.round((Date.now()-a)*100)/100,f=s/16,g=(d,p)=>{for(d=String(d);d.length{let d=g;for(let _ of a.split(".")){var p;d=(p=d)==null?void 0:p[_]}return d}:s=g=>g[u.accessorKey]),!c)throw new Error;let f={id:`${String(c)}`,accessorFn:s,parent:r,depth:t,columnDef:u,columns:[],getFlatColumns:y(()=>[!0],()=>{var g;return[f,...(g=f.columns)==null?void 0:g.flatMap(d=>d.getFlatColumns())]},{key:"column.getFlatColumns",debug:()=>{var g;return(g=e.options.debugAll)!=null?g:e.options.debugColumns}}),getLeafColumns:y(()=>[e._getOrderColumnsFn()],g=>{var d;if((d=f.columns)!=null&&d.length){let p=f.columns.flatMap(_=>_.getLeafColumns());return g(p)}return[f]},{key:"column.getLeafColumns",debug:()=>{var g;return(g=e.options.debugAll)!=null?g:e.options.debugColumns}})};return f=e._features.reduce((g,d)=>Object.assign(g,d.createColumn==null?void 0:d.createColumn(f,e)),f),f}function an(e,n,t){var r;let i={id:(r=t.id)!=null?r:n.id,column:n,index:t.index,isPlaceholder:!!t.isPlaceholder,placeholderId:t.placeholderId,depth:t.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{let l=[],u=a=>{a.subHeaders&&a.subHeaders.length&&a.subHeaders.map(u),l.push(a)};return u(i),l},getContext:()=>({table:e,header:i,column:n})};return e._features.forEach(l=>{Object.assign(i,l.createHeader==null?void 0:l.createHeader(i,e))}),i}var jr={createTable:e=>({getHeaderGroups:y(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(n,t,r,o)=>{var i,l;let u=(i=r?.map(f=>t.find(g=>g.id===f)).filter(Boolean))!=null?i:[],a=(l=o?.map(f=>t.find(g=>g.id===f)).filter(Boolean))!=null?l:[],c=t.filter(f=>!(r!=null&&r.includes(f.id))&&!(o!=null&&o.includes(f.id)));return Se(n,[...u,...c,...a],e)},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getCenterHeaderGroups:y(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(n,t,r,o)=>(t=t.filter(i=>!(r!=null&&r.includes(i.id))&&!(o!=null&&o.includes(i.id))),Se(n,t,e,"center")),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeftHeaderGroups:y(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(n,t,r)=>{var o;let i=(o=r?.map(l=>t.find(u=>u.id===l)).filter(Boolean))!=null?o:[];return Se(n,i,e,"left")},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getRightHeaderGroups:y(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(n,t,r)=>{var o;let i=(o=r?.map(l=>t.find(u=>u.id===l)).filter(Boolean))!=null?o:[];return Se(n,i,e,"right")},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getFooterGroups:y(()=>[e.getHeaderGroups()],n=>[...n].reverse(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeftFooterGroups:y(()=>[e.getLeftHeaderGroups()],n=>[...n].reverse(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getCenterFooterGroups:y(()=>[e.getCenterHeaderGroups()],n=>[...n].reverse(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getRightFooterGroups:y(()=>[e.getRightHeaderGroups()],n=>[...n].reverse(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getFlatHeaders:y(()=>[e.getHeaderGroups()],n=>n.map(t=>t.headers).flat(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeftFlatHeaders:y(()=>[e.getLeftHeaderGroups()],n=>n.map(t=>t.headers).flat(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getCenterFlatHeaders:y(()=>[e.getCenterHeaderGroups()],n=>n.map(t=>t.headers).flat(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getRightFlatHeaders:y(()=>[e.getRightHeaderGroups()],n=>n.map(t=>t.headers).flat(),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getCenterLeafHeaders:y(()=>[e.getCenterFlatHeaders()],n=>n.filter(t=>{var r;return!((r=t.subHeaders)!=null&&r.length)}),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeftLeafHeaders:y(()=>[e.getLeftFlatHeaders()],n=>n.filter(t=>{var r;return!((r=t.subHeaders)!=null&&r.length)}),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getRightLeafHeaders:y(()=>[e.getRightFlatHeaders()],n=>n.filter(t=>{var r;return!((r=t.subHeaders)!=null&&r.length)}),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}}),getLeafHeaders:y(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(n,t,r)=>{var o,i,l,u,a,c;return[...(o=(i=n[0])==null?void 0:i.headers)!=null?o:[],...(l=(u=t[0])==null?void 0:u.headers)!=null?l:[],...(a=(c=r[0])==null?void 0:c.headers)!=null?a:[]].map(s=>s.getLeafHeaders()).flat()},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugHeaders}})})};function Se(e,n,t,r){var o,i;let l=0,u=function(g,d){d===void 0&&(d=1),l=Math.max(l,d),g.filter(p=>p.getIsVisible()).forEach(p=>{var _;(_=p.columns)!=null&&_.length&&u(p.columns,d+1)},0)};u(e);let a=[],c=(g,d)=>{let p={depth:d,id:[r,`${d}`].filter(Boolean).join("_"),headers:[]},_=[];g.forEach(m=>{let v=[..._].reverse()[0],S=m.column.depth===p.depth,C,F=!1;if(S&&m.column.parent?C=m.column.parent:(C=m.column,F=!0),v&&v?.column===C)v.subHeaders.push(m);else{let x=an(t,C,{id:[r,d,C.id,m?.id].filter(Boolean).join("_"),isPlaceholder:F,placeholderId:F?`${_.filter(N=>N.column===C).length}`:void 0,depth:d,index:_.length});x.subHeaders.push(m),_.push(x)}p.headers.push(m),m.headerGroup=p}),a.push(p),d>0&&c(_,d-1)},s=n.map((g,d)=>an(t,g,{depth:l,index:d}));c(s,l-1),a.reverse();let f=g=>g.filter(p=>p.column.getIsVisible()).map(p=>{let _=0,m=0,v=[0];p.subHeaders&&p.subHeaders.length?(v=[],f(p.subHeaders).forEach(C=>{let{colSpan:F,rowSpan:x}=C;_+=F,v.push(x)})):_=1;let S=Math.min(...v);return m=m+S,p.colSpan=_,p.rowSpan=m,{colSpan:_,rowSpan:m}});return f((o=(i=a[0])==null?void 0:i.headers)!=null?o:[]),a}var Ce={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},Be=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),qr={getDefaultColumnDef:()=>Ce,getInitialState:e=>({columnSizing:{},columnSizingInfo:Be(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",onColumnSizingChange:A("columnSizing",e),onColumnSizingInfoChange:A("columnSizingInfo",e)}),createColumn:(e,n)=>({getSize:()=>{var t,r,o;let i=n.getState().columnSizing[e.id];return Math.min(Math.max((t=e.columnDef.minSize)!=null?t:Ce.minSize,(r=i??e.columnDef.size)!=null?r:Ce.size),(o=e.columnDef.maxSize)!=null?o:Ce.maxSize)},getStart:t=>{let r=t?t==="left"?n.getLeftVisibleLeafColumns():n.getRightVisibleLeafColumns():n.getVisibleLeafColumns(),o=r.findIndex(i=>i.id===e.id);if(o>0){let i=r[o-1];return i.getStart(t)+i.getSize()}return 0},resetSize:()=>{n.setColumnSizing(t=>{let{[e.id]:r,...o}=t;return o})},getCanResize:()=>{var t,r;return((t=e.columnDef.enableResizing)!=null?t:!0)&&((r=n.options.enableColumnResizing)!=null?r:!0)},getIsResizing:()=>n.getState().columnSizingInfo.isResizingColumn===e.id}),createHeader:(e,n)=>({getSize:()=>{let t=0,r=o=>{if(o.subHeaders.length)o.subHeaders.forEach(r);else{var i;t+=(i=o.column.getSize())!=null?i:0}};return r(e),t},getStart:()=>{if(e.index>0){let t=e.headerGroup.headers[e.index-1];return t.getStart()+t.getSize()}return 0},getResizeHandler:()=>{let t=n.getColumn(e.column.id),r=t?.getCanResize();return o=>{if(!t||!r||(o.persist==null||o.persist(),Ue(o)&&o.touches&&o.touches.length>1))return;let i=e.getSize(),l=e?e.getLeafHeaders().map(_=>[_.column.id,_.column.getSize()]):[[t.id,t.getSize()]],u=Ue(o)?Math.round(o.touches[0].clientX):o.clientX,a={},c=(_,m)=>{typeof m=="number"&&(n.setColumnSizingInfo(v=>{var S,C;let F=m-((S=v?.startOffset)!=null?S:0),x=Math.max(F/((C=v?.startSize)!=null?C:0),-.999999);return v.columnSizingStart.forEach(N=>{let[q,M]=N;a[q]=Math.round(Math.max(M+M*x,0)*100)/100}),{...v,deltaOffset:F,deltaPercentage:x}}),(n.options.columnResizeMode==="onChange"||_==="end")&&n.setColumnSizing(v=>({...v,...a})))},s=_=>c("move",_),f=_=>{c("end",_),n.setColumnSizingInfo(m=>({...m,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},g={moveHandler:_=>s(_.clientX),upHandler:_=>{document.removeEventListener("mousemove",g.moveHandler),document.removeEventListener("mouseup",g.upHandler),f(_.clientX)}},d={moveHandler:_=>(_.cancelable&&(_.preventDefault(),_.stopPropagation()),s(_.touches[0].clientX),!1),upHandler:_=>{var m;document.removeEventListener("touchmove",d.moveHandler),document.removeEventListener("touchend",d.upHandler),_.cancelable&&(_.preventDefault(),_.stopPropagation()),f((m=_.touches[0])==null?void 0:m.clientX)}},p=Kr()?{passive:!1}:!1;Ue(o)?(document.addEventListener("touchmove",d.moveHandler,p),document.addEventListener("touchend",d.upHandler,p)):(document.addEventListener("mousemove",g.moveHandler,p),document.addEventListener("mouseup",g.upHandler,p)),n.setColumnSizingInfo(_=>({..._,startOffset:u,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:l,isResizingColumn:t.id}))}}}),createTable:e=>({setColumnSizing:n=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(n),setColumnSizingInfo:n=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(n),resetColumnSizing:n=>{var t;e.setColumnSizing(n?{}:(t=e.initialState.columnSizing)!=null?t:{})},resetHeaderSizeInfo:n=>{var t;e.setColumnSizingInfo(n?Be():(t=e.initialState.columnSizingInfo)!=null?t:Be())},getTotalSize:()=>{var n,t;return(n=(t=e.getHeaderGroups()[0])==null?void 0:t.headers.reduce((r,o)=>r+o.getSize(),0))!=null?n:0},getLeftTotalSize:()=>{var n,t;return(n=(t=e.getLeftHeaderGroups()[0])==null?void 0:t.headers.reduce((r,o)=>r+o.getSize(),0))!=null?n:0},getCenterTotalSize:()=>{var n,t;return(n=(t=e.getCenterHeaderGroups()[0])==null?void 0:t.headers.reduce((r,o)=>r+o.getSize(),0))!=null?n:0},getRightTotalSize:()=>{var n,t;return(n=(t=e.getRightHeaderGroups()[0])==null?void 0:t.headers.reduce((r,o)=>r+o.getSize(),0))!=null?n:0}})},we=null;function Kr(){if(typeof we=="boolean")return we;let e=!1;try{let n={get passive(){return e=!0,!1}},t=()=>{};window.addEventListener("test",t,n),window.removeEventListener("test",t)}catch{e=!1}return we=e,we}function Ue(e){return e.type==="touchstart"}var Wr={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:A("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let n=!1,t=!1;return{_autoResetExpanded:()=>{var r,o;if(!n){e._queue(()=>{n=!0});return}if((r=(o=e.options.autoResetAll)!=null?o:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(t)return;t=!0,e._queue(()=>{e.resetExpanded(),t=!1})}},setExpanded:r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),toggleAllRowsExpanded:r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},resetExpanded:r=>{var o,i;e.setExpanded(r?{}:(o=(i=e.initialState)==null?void 0:i.expanded)!=null?o:{})},getCanSomeRowsExpand:()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),getToggleAllRowsExpandedHandler:()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},getIsSomeRowsExpanded:()=>{let r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},getIsAllRowsExpanded:()=>{let r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(o=>!o.getIsExpanded()))},getExpandedDepth:()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(i=>{let l=i.split(".");r=Math.max(r,l.length)}),r},getPreExpandedRowModel:()=>e.getSortedRowModel(),getExpandedRowModel:()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())}},createRow:(e,n)=>({toggleExpanded:t=>{n.setExpanded(r=>{var o;let i=r===!0?!0:!!(r!=null&&r[e.id]),l={};if(r===!0?Object.keys(n.getRowModel().rowsById).forEach(u=>{l[u]=!0}):l=r,t=(o=t)!=null?o:!i,!i&&t)return{...l,[e.id]:!0};if(i&&!t){let{[e.id]:u,...a}=l;return a}return r})},getIsExpanded:()=>{var t;let r=n.getState().expanded;return!!((t=n.options.getIsRowExpanded==null?void 0:n.options.getIsRowExpanded(e))!=null?t:r===!0||r?.[e.id])},getCanExpand:()=>{var t,r,o;return(t=n.options.getRowCanExpand==null?void 0:n.options.getRowCanExpand(e))!=null?t:((r=n.options.enableExpanding)!=null?r:!0)&&!!((o=e.subRows)!=null&&o.length)},getToggleExpandedHandler:()=>{let t=e.getCanExpand();return()=>{t&&e.toggleExpanded()}}})},fn=(e,n,t)=>{var r,o,i;let l=t.toLowerCase();return!!(!((r=e.getValue(n))==null||(o=r.toString())==null||(i=o.toLowerCase())==null)&&i.includes(l))};fn.autoRemove=e=>k(e);var pn=(e,n,t)=>{var r,o;return!!(!((r=e.getValue(n))==null||(o=r.toString())==null)&&o.includes(t))};pn.autoRemove=e=>k(e);var _n=(e,n,t)=>{var r,o;return((r=e.getValue(n))==null||(o=r.toString())==null?void 0:o.toLowerCase())===t?.toLowerCase()};_n.autoRemove=e=>k(e);var mn=(e,n,t)=>{var r;return(r=e.getValue(n))==null?void 0:r.includes(t)};mn.autoRemove=e=>k(e)||!(e!=null&&e.length);var hn=(e,n,t)=>!t.some(r=>{var o;return!((o=e.getValue(n))!=null&&o.includes(r))});hn.autoRemove=e=>k(e)||!(e!=null&&e.length);var vn=(e,n,t)=>t.some(r=>{var o;return(o=e.getValue(n))==null?void 0:o.includes(r)});vn.autoRemove=e=>k(e)||!(e!=null&&e.length);var yn=(e,n,t)=>e.getValue(n)===t;yn.autoRemove=e=>k(e);var bn=(e,n,t)=>e.getValue(n)==t;bn.autoRemove=e=>k(e);var Ze=(e,n,t)=>{let[r,o]=t,i=e.getValue(n);return i>=r&&i<=o};Ze.resolveFilterValue=e=>{let[n,t]=e,r=typeof n!="number"?parseFloat(n):n,o=typeof t!="number"?parseFloat(t):t,i=n===null||Number.isNaN(r)?-1/0:r,l=t===null||Number.isNaN(o)?1/0:o;if(i>l){let u=i;i=l,l=u}return[i,l]};Ze.autoRemove=e=>k(e)||k(e[0])&&k(e[1]);var j={includesString:fn,includesStringSensitive:pn,equalsString:_n,arrIncludes:mn,arrIncludesAll:hn,arrIncludesSome:vn,equals:yn,weakEquals:bn,inNumberRange:Ze};function k(e){return e==null||e===""}var Xr={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],globalFilter:void 0,...e}),getDefaultOptions:e=>({onColumnFiltersChange:A("columnFilters",e),onGlobalFilterChange:A("globalFilter",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100,globalFilterFn:"auto",getColumnCanGlobalFilter:n=>{var t,r;let o=(t=e.getCoreRowModel().flatRows[0])==null||(r=t._getAllCellsByColumnId()[n.id])==null?void 0:r.getValue();return typeof o=="string"||typeof o=="number"}}),createColumn:(e,n)=>({getAutoFilterFn:()=>{let t=n.getCoreRowModel().flatRows[0],r=t?.getValue(e.id);return typeof r=="string"?j.includesString:typeof r=="number"?j.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?j.equals:Array.isArray(r)?j.arrIncludes:j.weakEquals},getFilterFn:()=>{var t,r;return Re(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(t=(r=n.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?t:j[e.columnDef.filterFn]},getCanFilter:()=>{var t,r,o;return((t=e.columnDef.enableColumnFilter)!=null?t:!0)&&((r=n.options.enableColumnFilters)!=null?r:!0)&&((o=n.options.enableFilters)!=null?o:!0)&&!!e.accessorFn},getCanGlobalFilter:()=>{var t,r,o,i;return((t=e.columnDef.enableGlobalFilter)!=null?t:!0)&&((r=n.options.enableGlobalFilter)!=null?r:!0)&&((o=n.options.enableFilters)!=null?o:!0)&&((i=n.options.getColumnCanGlobalFilter==null?void 0:n.options.getColumnCanGlobalFilter(e))!=null?i:!0)&&!!e.accessorFn},getIsFiltered:()=>e.getFilterIndex()>-1,getFilterValue:()=>{var t,r;return(t=n.getState().columnFilters)==null||(r=t.find(o=>o.id===e.id))==null?void 0:r.value},getFilterIndex:()=>{var t,r;return(t=(r=n.getState().columnFilters)==null?void 0:r.findIndex(o=>o.id===e.id))!=null?t:-1},setFilterValue:t=>{n.setColumnFilters(r=>{let o=e.getFilterFn(),i=r?.find(s=>s.id===e.id),l=X(t,i?i.value:void 0);if(dn(o,l,e)){var u;return(u=r?.filter(s=>s.id!==e.id))!=null?u:[]}let a={id:e.id,value:l};if(i){var c;return(c=r?.map(s=>s.id===e.id?a:s))!=null?c:[]}return r!=null&&r.length?[...r,a]:[a]})},_getFacetedRowModel:n.options.getFacetedRowModel&&n.options.getFacetedRowModel(n,e.id),getFacetedRowModel:()=>e._getFacetedRowModel?e._getFacetedRowModel():n.getPreFilteredRowModel(),_getFacetedUniqueValues:n.options.getFacetedUniqueValues&&n.options.getFacetedUniqueValues(n,e.id),getFacetedUniqueValues:()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,_getFacetedMinMaxValues:n.options.getFacetedMinMaxValues&&n.options.getFacetedMinMaxValues(n,e.id),getFacetedMinMaxValues:()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}),createRow:(e,n)=>({columnFilters:{},columnFiltersMeta:{}}),createTable:e=>({getGlobalAutoFilterFn:()=>j.includesString,getGlobalFilterFn:()=>{var n,t;let{globalFilterFn:r}=e.options;return Re(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(n=(t=e.options.filterFns)==null?void 0:t[r])!=null?n:j[r]},setColumnFilters:n=>{let t=e.getAllLeafColumns(),r=o=>{var i;return(i=X(n,o))==null?void 0:i.filter(l=>{let u=t.find(a=>a.id===l.id);if(u){let a=u.getFilterFn();if(dn(a,l.value,u))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},setGlobalFilter:n=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(n)},resetGlobalFilter:n=>{e.setGlobalFilter(n?void 0:e.initialState.globalFilter)},resetColumnFilters:n=>{var t,r;e.setColumnFilters(n?[]:(t=(r=e.initialState)==null?void 0:r.columnFilters)!=null?t:[])},getPreFilteredRowModel:()=>e.getCoreRowModel(),getFilteredRowModel:()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel()),_getGlobalFacetedRowModel:e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),getGlobalFacetedRowModel:()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),_getGlobalFacetedUniqueValues:e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),getGlobalFacetedUniqueValues:()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,_getGlobalFacetedMinMaxValues:e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),getGlobalFacetedMinMaxValues:()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}})};function dn(e,n,t){return(e&&e.autoRemove?e.autoRemove(n,t):!1)||typeof n>"u"||typeof n=="string"&&!n}var Jr=(e,n,t)=>t.reduce((r,o)=>{let i=o.getValue(e);return r+(typeof i=="number"?i:0)},0),Yr=(e,n,t)=>{let r;return t.forEach(o=>{let i=o.getValue(e);i!=null&&(r>i||r===void 0&&i>=i)&&(r=i)}),r},Qr=(e,n,t)=>{let r;return t.forEach(o=>{let i=o.getValue(e);i!=null&&(r=i)&&(r=i)}),r},Zr=(e,n,t)=>{let r,o;return t.forEach(i=>{let l=i.getValue(e);l!=null&&(r===void 0?l>=l&&(r=o=l):(r>l&&(r=l),o{let t=0,r=0;if(n.forEach(o=>{let i=o.getValue(e);i!=null&&(i=+i)>=i&&(++t,r+=i)}),t)return r/t},to=(e,n)=>{if(!n.length)return;let t=n.map(i=>i.getValue(e));if(!Gr(t))return;if(t.length===1)return t[0];let r=Math.floor(t.length/2),o=t.sort((i,l)=>i-l);return t.length%2!==0?o[r]:(o[r-1]+o[r])/2},no=(e,n)=>Array.from(new Set(n.map(t=>t.getValue(e))).values()),ro=(e,n)=>new Set(n.map(t=>t.getValue(e))).size,oo=(e,n)=>n.length,je={sum:Jr,min:Yr,max:Qr,extent:Zr,mean:eo,median:to,unique:no,uniqueCount:ro,count:oo},io={getDefaultColumnDef:()=>({aggregatedCell:e=>{var n,t;return(n=(t=e.getValue())==null||t.toString==null?void 0:t.toString())!=null?n:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:A("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,n)=>({toggleGrouping:()=>{n.setGrouping(t=>t!=null&&t.includes(e.id)?t.filter(r=>r!==e.id):[...t??[],e.id])},getCanGroup:()=>{var t,r,o,i;return(t=(r=(o=(i=e.columnDef.enableGrouping)!=null?i:!0)!=null?o:n.options.enableGrouping)!=null?r:!0)!=null?t:!!e.accessorFn},getIsGrouped:()=>{var t;return(t=n.getState().grouping)==null?void 0:t.includes(e.id)},getGroupedIndex:()=>{var t;return(t=n.getState().grouping)==null?void 0:t.indexOf(e.id)},getToggleGroupingHandler:()=>{let t=e.getCanGroup();return()=>{t&&e.toggleGrouping()}},getAutoAggregationFn:()=>{let t=n.getCoreRowModel().flatRows[0],r=t?.getValue(e.id);if(typeof r=="number")return je.sum;if(Object.prototype.toString.call(r)==="[object Date]")return je.extent},getAggregationFn:()=>{var t,r;if(!e)throw new Error;return Re(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(t=(r=n.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?t:je[e.columnDef.aggregationFn]}}),createTable:e=>({setGrouping:n=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(n),resetGrouping:n=>{var t,r;e.setGrouping(n?[]:(t=(r=e.initialState)==null?void 0:r.grouping)!=null?t:[])},getPreGroupedRowModel:()=>e.getFilteredRowModel(),getGroupedRowModel:()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())}),createRow:(e,n)=>({getIsGrouped:()=>!!e.groupingColumnId,getGroupingValue:t=>{if(e._groupingValuesCache.hasOwnProperty(t))return e._groupingValuesCache[t];let r=n.getColumn(t);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[t]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[t]):e.getValue(t)},_groupingValuesCache:{}}),createCell:(e,n,t,r)=>({getIsGrouped:()=>n.getIsGrouped()&&n.id===t.groupingColumnId,getIsPlaceholder:()=>!e.getIsGrouped()&&n.getIsGrouped(),getIsAggregated:()=>{var o;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((o=t.subRows)!=null&&o.length)}})};function lo(e,n,t){if(!(n!=null&&n.length)||!t)return e;let r=e.filter(i=>!n.includes(i.id));return t==="remove"?r:[...n.map(i=>e.find(l=>l.id===i)).filter(Boolean),...r]}var so={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:A("columnOrder",e)}),createTable:e=>({setColumnOrder:n=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(n),resetColumnOrder:n=>{var t;e.setColumnOrder(n?[]:(t=e.initialState.columnOrder)!=null?t:[])},_getOrderColumnsFn:y(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(n,t,r)=>o=>{let i=[];if(!(n!=null&&n.length))i=o;else{let l=[...n],u=[...o];for(;u.length&&l.length;){let a=l.shift(),c=u.findIndex(s=>s.id===a);c>-1&&i.push(u.splice(c,1)[0])}i=[...i,...u]}return lo(i,t,r)},{key:!1})})},Xe=0,Je=10,qe=()=>({pageIndex:Xe,pageSize:Je}),uo={getInitialState:e=>({...e,pagination:{...qe(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:A("pagination",e)}),createTable:e=>{let n=!1,t=!1;return{_autoResetPageIndex:()=>{var r,o;if(!n){e._queue(()=>{n=!0});return}if((r=(o=e.options.autoResetAll)!=null?o:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(t)return;t=!0,e._queue(()=>{e.resetPageIndex(),t=!1})}},setPagination:r=>{let o=i=>X(r,i);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(o)},resetPagination:r=>{var o;e.setPagination(r?qe():(o=e.initialState.pagination)!=null?o:qe())},setPageIndex:r=>{e.setPagination(o=>{let i=X(r,o.pageIndex),l=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return i=Math.max(0,Math.min(i,l)),{...o,pageIndex:i}})},resetPageIndex:r=>{var o,i,l;e.setPageIndex(r?Xe:(o=(i=e.initialState)==null||(l=i.pagination)==null?void 0:l.pageIndex)!=null?o:Xe)},resetPageSize:r=>{var o,i,l;e.setPageSize(r?Je:(o=(i=e.initialState)==null||(l=i.pagination)==null?void 0:l.pageSize)!=null?o:Je)},setPageSize:r=>{e.setPagination(o=>{let i=Math.max(1,X(r,o.pageSize)),l=o.pageSize*o.pageIndex,u=Math.floor(l/i);return{...o,pageIndex:u,pageSize:i}})},setPageCount:r=>e.setPagination(o=>{var i;let l=X(r,(i=e.options.pageCount)!=null?i:-1);return typeof l=="number"&&(l=Math.max(-1,l)),{...o,pageCount:l}}),getPageOptions:y(()=>[e.getPageCount()],r=>{let o=[];return r&&r>0&&(o=[...new Array(r)].fill(null).map((i,l)=>l)),o},{key:!1,debug:()=>{var r;return(r=e.options.debugAll)!=null?r:e.options.debugTable}}),getCanPreviousPage:()=>e.getState().pagination.pageIndex>0,getCanNextPage:()=>{let{pageIndex:r}=e.getState().pagination,o=e.getPageCount();return o===-1?!0:o===0?!1:re.setPageIndex(r=>r-1),nextPage:()=>e.setPageIndex(r=>r+1),getPrePaginationRowModel:()=>e.getExpandedRowModel(),getPaginationRowModel:()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),getPageCount:()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getPrePaginationRowModel().rows.length/e.getState().pagination.pageSize)}}}},Ke=()=>({left:[],right:[]}),ao={getInitialState:e=>({columnPinning:Ke(),...e}),getDefaultOptions:e=>({onColumnPinningChange:A("columnPinning",e)}),createColumn:(e,n)=>({pin:t=>{let r=e.getLeafColumns().map(o=>o.id).filter(Boolean);n.setColumnPinning(o=>{var i,l;if(t==="right"){var u,a;return{left:((u=o?.left)!=null?u:[]).filter(f=>!(r!=null&&r.includes(f))),right:[...((a=o?.right)!=null?a:[]).filter(f=>!(r!=null&&r.includes(f))),...r]}}if(t==="left"){var c,s;return{left:[...((c=o?.left)!=null?c:[]).filter(f=>!(r!=null&&r.includes(f))),...r],right:((s=o?.right)!=null?s:[]).filter(f=>!(r!=null&&r.includes(f)))}}return{left:((i=o?.left)!=null?i:[]).filter(f=>!(r!=null&&r.includes(f))),right:((l=o?.right)!=null?l:[]).filter(f=>!(r!=null&&r.includes(f)))}})},getCanPin:()=>e.getLeafColumns().some(r=>{var o,i;return((o=r.columnDef.enablePinning)!=null?o:!0)&&((i=n.options.enablePinning)!=null?i:!0)}),getIsPinned:()=>{let t=e.getLeafColumns().map(u=>u.id),{left:r,right:o}=n.getState().columnPinning,i=t.some(u=>r?.includes(u)),l=t.some(u=>o?.includes(u));return i?"left":l?"right":!1},getPinnedIndex:()=>{var t,r,o;let i=e.getIsPinned();return i?(t=(r=n.getState().columnPinning)==null||(o=r[i])==null?void 0:o.indexOf(e.id))!=null?t:-1:0}}),createRow:(e,n)=>({getCenterVisibleCells:y(()=>[e._getAllVisibleCells(),n.getState().columnPinning.left,n.getState().columnPinning.right],(t,r,o)=>{let i=[...r??[],...o??[]];return t.filter(l=>!i.includes(l.column.id))},{key:"row.getCenterVisibleCells",debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}}),getLeftVisibleCells:y(()=>[e._getAllVisibleCells(),n.getState().columnPinning.left,,],(t,r)=>(r??[]).map(i=>t.find(l=>l.column.id===i)).filter(Boolean).map(i=>({...i,position:"left"})),{key:"row.getLeftVisibleCells",debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}}),getRightVisibleCells:y(()=>[e._getAllVisibleCells(),n.getState().columnPinning.right],(t,r)=>(r??[]).map(i=>t.find(l=>l.column.id===i)).filter(Boolean).map(i=>({...i,position:"right"})),{key:"row.getRightVisibleCells",debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}})}),createTable:e=>({setColumnPinning:n=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(n),resetColumnPinning:n=>{var t,r;return e.setColumnPinning(n?Ke():(t=(r=e.initialState)==null?void 0:r.columnPinning)!=null?t:Ke())},getIsSomeColumnsPinned:n=>{var t;let r=e.getState().columnPinning;if(!n){var o,i;return!!((o=r.left)!=null&&o.length||(i=r.right)!=null&&i.length)}return!!((t=r[n])!=null&&t.length)},getLeftLeafColumns:y(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(n,t)=>(t??[]).map(r=>n.find(o=>o.id===r)).filter(Boolean),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugColumns}}),getRightLeafColumns:y(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(n,t)=>(t??[]).map(r=>n.find(o=>o.id===r)).filter(Boolean),{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugColumns}}),getCenterLeafColumns:y(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(n,t,r)=>{let o=[...t??[],...r??[]];return n.filter(i=>!o.includes(i.id))},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugColumns}})})},co={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:A("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>({setRowSelection:n=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(n),resetRowSelection:n=>{var t;return e.setRowSelection(n?{}:(t=e.initialState.rowSelection)!=null?t:{})},toggleAllRowsSelected:n=>{e.setRowSelection(t=>{n=typeof n<"u"?n:!e.getIsAllRowsSelected();let r={...t},o=e.getPreGroupedRowModel().flatRows;return n?o.forEach(i=>{i.getCanSelect()&&(r[i.id]=!0)}):o.forEach(i=>{delete r[i.id]}),r})},toggleAllPageRowsSelected:n=>e.setRowSelection(t=>{let r=typeof n<"u"?n:!e.getIsAllPageRowsSelected(),o={...t};return e.getRowModel().rows.forEach(i=>{Ye(o,i.id,r,e)}),o}),getPreSelectedRowModel:()=>e.getCoreRowModel(),getSelectedRowModel:y(()=>[e.getState().rowSelection,e.getCoreRowModel()],(n,t)=>Object.keys(n).length?We(e,t):{rows:[],flatRows:[],rowsById:{}},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable}}),getFilteredSelectedRowModel:y(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(n,t)=>Object.keys(n).length?We(e,t):{rows:[],flatRows:[],rowsById:{}},{key:"getFilteredSelectedRowModel",debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable}}),getGroupedSelectedRowModel:y(()=>[e.getState().rowSelection,e.getSortedRowModel()],(n,t)=>Object.keys(n).length?We(e,t):{rows:[],flatRows:[],rowsById:{}},{key:"getGroupedSelectedRowModel",debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable}}),getIsAllRowsSelected:()=>{let n=e.getFilteredRowModel().flatRows,{rowSelection:t}=e.getState(),r=!!(n.length&&Object.keys(t).length);return r&&n.some(o=>o.getCanSelect()&&!t[o.id])&&(r=!1),r},getIsAllPageRowsSelected:()=>{let n=e.getPaginationRowModel().flatRows.filter(o=>o.getCanSelect()),{rowSelection:t}=e.getState(),r=!!n.length;return r&&n.some(o=>!t[o.id])&&(r=!1),r},getIsSomeRowsSelected:()=>{var n;let t=Object.keys((n=e.getState().rowSelection)!=null?n:{}).length;return t>0&&t{let n=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:n.filter(t=>t.getCanSelect()).some(t=>t.getIsSelected()||t.getIsSomeSelected())},getToggleAllRowsSelectedHandler:()=>n=>{e.toggleAllRowsSelected(n.target.checked)},getToggleAllPageRowsSelectedHandler:()=>n=>{e.toggleAllPageRowsSelected(n.target.checked)}}),createRow:(e,n)=>({toggleSelected:t=>{let r=e.getIsSelected();n.setRowSelection(o=>{if(t=typeof t<"u"?t:!r,r===t)return o;let i={...o};return Ye(i,e.id,t,n),i})},getIsSelected:()=>{let{rowSelection:t}=n.getState();return et(e,t)},getIsSomeSelected:()=>{let{rowSelection:t}=n.getState();return cn(e,t)==="some"},getIsAllSubRowsSelected:()=>{let{rowSelection:t}=n.getState();return cn(e,t)==="all"},getCanSelect:()=>{var t;return typeof n.options.enableRowSelection=="function"?n.options.enableRowSelection(e):(t=n.options.enableRowSelection)!=null?t:!0},getCanSelectSubRows:()=>{var t;return typeof n.options.enableSubRowSelection=="function"?n.options.enableSubRowSelection(e):(t=n.options.enableSubRowSelection)!=null?t:!0},getCanMultiSelect:()=>{var t;return typeof n.options.enableMultiRowSelection=="function"?n.options.enableMultiRowSelection(e):(t=n.options.enableMultiRowSelection)!=null?t:!0},getToggleSelectedHandler:()=>{let t=e.getCanSelect();return r=>{var o;t&&e.toggleSelected((o=r.target)==null?void 0:o.checked)}}})},Ye=(e,n,t,r)=>{var o;let i=r.getRow(n);t?(i.getCanMultiSelect()||Object.keys(e).forEach(l=>delete e[l]),i.getCanSelect()&&(e[n]=!0)):delete e[n],(o=i.subRows)!=null&&o.length&&i.getCanSelectSubRows()&&i.subRows.forEach(l=>Ye(e,l.id,t,r))};function We(e,n){let t=e.getState().rowSelection,r=[],o={},i=function(l,u){return l.map(a=>{var c;let s=et(a,t);if(s&&(r.push(a),o[a.id]=a),(c=a.subRows)!=null&&c.length&&(a={...a,subRows:i(a.subRows)}),s)return a}).filter(Boolean)};return{rows:i(n.rows),flatRows:r,rowsById:o}}function et(e,n){var t;return(t=n[e.id])!=null?t:!1}function cn(e,n,t){if(e.subRows&&e.subRows.length){let r=!0,o=!1;return e.subRows.forEach(i=>{o&&!r||(et(i,n)?o=!0:r=!1)}),r?"all":o?"some":!1}return!1}var Qe=/([0-9]+)/gm,go=(e,n,t)=>Sn(J(e.getValue(t)).toLowerCase(),J(n.getValue(t)).toLowerCase()),fo=(e,n,t)=>Sn(J(e.getValue(t)),J(n.getValue(t))),po=(e,n,t)=>tt(J(e.getValue(t)).toLowerCase(),J(n.getValue(t)).toLowerCase()),_o=(e,n,t)=>tt(J(e.getValue(t)),J(n.getValue(t))),mo=(e,n,t)=>{let r=e.getValue(t),o=n.getValue(t);return r>o?1:rtt(e.getValue(t),n.getValue(t));function tt(e,n){return e===n?0:e>n?1:-1}function J(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function Sn(e,n){let t=e.split(Qe).filter(Boolean),r=n.split(Qe).filter(Boolean);for(;t.length&&r.length;){let o=t.shift(),i=r.shift(),l=parseInt(o,10),u=parseInt(i,10),a=[l,u].sort();if(isNaN(a[0])){if(o>i)return 1;if(i>o)return-1;continue}if(isNaN(a[1]))return isNaN(l)?-1:1;if(l>u)return 1;if(u>l)return-1}return t.length-r.length}var de={alphanumeric:go,alphanumericCaseSensitive:fo,text:po,textCaseSensitive:_o,datetime:mo,basic:ho},vo={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:A("sorting",e),isMultiSortEvent:n=>n.shiftKey}),createColumn:(e,n)=>({getAutoSortingFn:()=>{let t=n.getFilteredRowModel().flatRows.slice(10),r=!1;for(let o of t){let i=o?.getValue(e.id);if(Object.prototype.toString.call(i)==="[object Date]")return de.datetime;if(typeof i=="string"&&(r=!0,i.split(Qe).length>1))return de.alphanumeric}return r?de.text:de.basic},getAutoSortDir:()=>{let t=n.getFilteredRowModel().flatRows[0];return typeof t?.getValue(e.id)=="string"?"asc":"desc"},getSortingFn:()=>{var t,r;if(!e)throw new Error;return Re(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(t=(r=n.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?t:de[e.columnDef.sortingFn]},toggleSorting:(t,r)=>{let o=e.getNextSortingOrder(),i=typeof t<"u"&&t!==null;n.setSorting(l=>{let u=l?.find(d=>d.id===e.id),a=l?.findIndex(d=>d.id===e.id),c=[],s,f=i?t:o==="desc";if(l!=null&&l.length&&e.getCanMultiSort()&&r?u?s="toggle":s="add":l!=null&&l.length&&a!==l.length-1?s="replace":u?s="toggle":s="replace",s==="toggle"&&(i||o||(s="remove")),s==="add"){var g;c=[...l,{id:e.id,desc:f}],c.splice(0,c.length-((g=n.options.maxMultiSortColCount)!=null?g:Number.MAX_SAFE_INTEGER))}else s==="toggle"?c=l.map(d=>d.id===e.id?{...d,desc:f}:d):s==="remove"?c=l.filter(d=>d.id!==e.id):c=[{id:e.id,desc:f}];return c})},getFirstSortDir:()=>{var t,r;return((t=(r=e.columnDef.sortDescFirst)!=null?r:n.options.sortDescFirst)!=null?t:e.getAutoSortDir()==="desc")?"desc":"asc"},getNextSortingOrder:t=>{var r,o;let i=e.getFirstSortDir(),l=e.getIsSorted();return l?l!==i&&((r=n.options.enableSortingRemoval)==null||r)&&(!(t&&(o=n.options.enableMultiRemove)!=null)||o)?!1:l==="desc"?"asc":"desc":i},getCanSort:()=>{var t,r;return((t=e.columnDef.enableSorting)!=null?t:!0)&&((r=n.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},getCanMultiSort:()=>{var t,r;return(t=(r=e.columnDef.enableMultiSort)!=null?r:n.options.enableMultiSort)!=null?t:!!e.accessorFn},getIsSorted:()=>{var t;let r=(t=n.getState().sorting)==null?void 0:t.find(o=>o.id===e.id);return r?r.desc?"desc":"asc":!1},getSortIndex:()=>{var t,r;return(t=(r=n.getState().sorting)==null?void 0:r.findIndex(o=>o.id===e.id))!=null?t:-1},clearSorting:()=>{n.setSorting(t=>t!=null&&t.length?t.filter(r=>r.id!==e.id):[])},getToggleSortingHandler:()=>{let t=e.getCanSort();return r=>{t&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?n.options.isMultiSortEvent==null?void 0:n.options.isMultiSortEvent(r):!1))}}}),createTable:e=>({setSorting:n=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(n),resetSorting:n=>{var t,r;e.setSorting(n?[]:(t=(r=e.initialState)==null?void 0:r.sorting)!=null?t:[])},getPreSortedRowModel:()=>e.getGroupedRowModel(),getSortedRowModel:()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())})},yo={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:A("columnVisibility",e)}),createColumn:(e,n)=>({toggleVisibility:t=>{e.getCanHide()&&n.setColumnVisibility(r=>({...r,[e.id]:t??!e.getIsVisible()}))},getIsVisible:()=>{var t,r;return(t=(r=n.getState().columnVisibility)==null?void 0:r[e.id])!=null?t:!0},getCanHide:()=>{var t,r;return((t=e.columnDef.enableHiding)!=null?t:!0)&&((r=n.options.enableHiding)!=null?r:!0)},getToggleVisibilityHandler:()=>t=>{e.toggleVisibility==null||e.toggleVisibility(t.target.checked)}}),createRow:(e,n)=>({_getAllVisibleCells:y(()=>[e.getAllCells(),n.getState().columnVisibility],t=>t.filter(r=>r.column.getIsVisible()),{key:"row._getAllVisibleCells",debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}}),getVisibleCells:y(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(t,r,o)=>[...t,...r,...o],{key:!1,debug:()=>{var t;return(t=n.options.debugAll)!=null?t:n.options.debugRows}})}),createTable:e=>{let n=(t,r)=>y(()=>[r(),r().filter(o=>o.getIsVisible()).map(o=>o.id).join("_")],o=>o.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),{key:t,debug:()=>{var o;return(o=e.options.debugAll)!=null?o:e.options.debugColumns}});return{getVisibleFlatColumns:n("getVisibleFlatColumns",()=>e.getAllFlatColumns()),getVisibleLeafColumns:n("getVisibleLeafColumns",()=>e.getAllLeafColumns()),getLeftVisibleLeafColumns:n("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),getRightVisibleLeafColumns:n("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),getCenterVisibleLeafColumns:n("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),setColumnVisibility:t=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(t),resetColumnVisibility:t=>{var r;e.setColumnVisibility(t?{}:(r=e.initialState.columnVisibility)!=null?r:{})},toggleAllColumnsVisible:t=>{var r;t=(r=t)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((o,i)=>({...o,[i.id]:t||!(i.getCanHide!=null&&i.getCanHide())}),{}))},getIsAllColumnsVisible:()=>!e.getAllLeafColumns().some(t=>!(t.getIsVisible!=null&&t.getIsVisible())),getIsSomeColumnsVisible:()=>e.getAllLeafColumns().some(t=>t.getIsVisible==null?void 0:t.getIsVisible()),getToggleAllColumnsVisibilityHandler:()=>t=>{var r;e.toggleAllColumnsVisible((r=t.target)==null?void 0:r.checked)}}}},gn=[jr,yo,so,ao,Xr,vo,io,Wr,uo,co,qr];function Cn(e){var n;(e.debugAll||e.debugTable)&&console.info("Creating Table Instance...");let t={_features:gn},r=t._features.reduce((s,f)=>Object.assign(s,f.getDefaultOptions==null?void 0:f.getDefaultOptions(t)),{}),o=s=>t.options.mergeOptions?t.options.mergeOptions(r,s):{...r,...s},l={...{},...(n=e.initialState)!=null?n:{}};t._features.forEach(s=>{var f;l=(f=s.getInitialState==null?void 0:s.getInitialState(l))!=null?f:l});let u=[],a=!1,c={_features:gn,options:{...r,...e},initialState:l,_queue:s=>{u.push(s),a||(a=!0,Promise.resolve().then(()=>{for(;u.length;)u.shift()();a=!1}).catch(f=>setTimeout(()=>{throw f})))},reset:()=>{t.setState(t.initialState)},setOptions:s=>{let f=X(s,t.options);t.options=o(f)},getState:()=>t.options.state,setState:s=>{t.options.onStateChange==null||t.options.onStateChange(s)},_getRowId:(s,f,g)=>{var d;return(d=t.options.getRowId==null?void 0:t.options.getRowId(s,f,g))!=null?d:`${g?[g.id,f].join("."):f}`},getCoreRowModel:()=>(t._getCoreRowModel||(t._getCoreRowModel=t.options.getCoreRowModel(t)),t._getCoreRowModel()),getRowModel:()=>t.getPaginationRowModel(),getRow:s=>{let f=t.getRowModel().rowsById[s];if(!f)throw new Error;return f},_getDefaultColumnDef:y(()=>[t.options.defaultColumn],s=>{var f;return s=(f=s)!=null?f:{},{header:g=>{let d=g.header.column.columnDef;return d.accessorKey?d.accessorKey:d.accessorFn?d.id:null},cell:g=>{var d,p;return(d=(p=g.renderValue())==null||p.toString==null?void 0:p.toString())!=null?d:null},...t._features.reduce((g,d)=>Object.assign(g,d.getDefaultColumnDef==null?void 0:d.getDefaultColumnDef()),{}),...s}},{debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns},key:!1}),_getColumnDefs:()=>t.options.columns,getAllColumns:y(()=>[t._getColumnDefs()],s=>{let f=function(g,d,p){return p===void 0&&(p=0),g.map(_=>{let m=Ur(t,_,p,d),v=_;return m.columns=v.columns?f(v.columns,m,p+1):[],m})};return f(s)},{key:!1,debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns}}),getAllFlatColumns:y(()=>[t.getAllColumns()],s=>s.flatMap(f=>f.getFlatColumns()),{key:!1,debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns}}),_getAllFlatColumnsById:y(()=>[t.getAllFlatColumns()],s=>s.reduce((f,g)=>(f[g.id]=g,f),{}),{key:!1,debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns}}),getAllLeafColumns:y(()=>[t.getAllColumns(),t._getOrderColumnsFn()],(s,f)=>{let g=s.flatMap(d=>d.getLeafColumns());return f(g)},{key:!1,debug:()=>{var s;return(s=t.options.debugAll)!=null?s:t.options.debugColumns}}),getColumn:s=>t._getAllFlatColumnsById()[s]};return Object.assign(t,c),t._features.forEach(s=>Object.assign(t,s.createTable==null?void 0:s.createTable(t))),t}function bo(e,n,t,r){let o=()=>{var l;return(l=i.getValue())!=null?l:e.options.renderFallbackValue},i={id:`${n.id}_${t.id}`,row:n,column:t,getValue:()=>n.getValue(r),renderValue:o,getContext:y(()=>[e,t,n,i],(l,u,a,c)=>({table:l,column:u,row:a,cell:c,getValue:c.getValue,renderValue:c.renderValue}),{key:!1,debug:()=>e.options.debugAll})};return e._features.forEach(l=>{Object.assign(i,l.createCell==null?void 0:l.createCell(i,t,n,e))},{}),i}var nt=(e,n,t,r,o,i,l)=>{let u={id:n,index:r,original:t,depth:o,parentId:l,_valuesCache:{},_uniqueValuesCache:{},getValue:a=>{if(u._valuesCache.hasOwnProperty(a))return u._valuesCache[a];let c=e.getColumn(a);if(c!=null&&c.accessorFn)return u._valuesCache[a]=c.accessorFn(u.original,r),u._valuesCache[a]},getUniqueValues:a=>{if(u._uniqueValuesCache.hasOwnProperty(a))return u._uniqueValuesCache[a];let c=e.getColumn(a);if(c!=null&&c.accessorFn)return c.columnDef.getUniqueValues?(u._uniqueValuesCache[a]=c.columnDef.getUniqueValues(u.original,r),u._uniqueValuesCache[a]):(u._uniqueValuesCache[a]=[u.getValue(a)],u._uniqueValuesCache[a])},renderValue:a=>{var c;return(c=u.getValue(a))!=null?c:e.options.renderFallbackValue},subRows:i??[],getLeafRows:()=>Br(u.subRows,a=>a.subRows),getParentRow:()=>u.parentId?e.getRow(u.parentId):void 0,getParentRows:()=>{let a=[],c=u;for(;;){let s=c.getParentRow();if(!s)break;a.push(s),c=s}return a.reverse()},getAllCells:y(()=>[e.getAllLeafColumns()],a=>a.map(c=>bo(e,u,c,c.id)),{key:!1,debug:()=>{var a;return(a=e.options.debugAll)!=null?a:e.options.debugRows}}),_getAllCellsByColumnId:y(()=>[u.getAllCells()],a=>a.reduce((c,s)=>(c[s.column.id]=s,c),{}),{key:"row.getAllCellsByColumnId",debug:()=>{var a;return(a=e.options.debugAll)!=null?a:e.options.debugRows}})};for(let a=0;ay(()=>[e.options.data],n=>{let t={rows:[],flatRows:[],rowsById:{}},r=function(o,i,l){i===void 0&&(i=0);let u=[];for(let c=0;c{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable},onChange:()=>{e._autoResetPageIndex()}})}function Rn(e,n,t){return t.options.filterFromLeafRows?So(e,n,t):Co(e,n,t)}function So(e,n,t){var r;let o=[],i={},l=(r=t.options.maxLeafRowFilterDepth)!=null?r:100,u=function(a,c){c===void 0&&(c=0);let s=[];for(let g=0;gy(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(n,t,r)=>{if(!n.rows.length||!(t!=null&&t.length)&&!r){for(let g=0;g{var d;let p=e.getColumn(g.id);if(!p)return;let _=p.getFilterFn();_&&o.push({id:g.id,filterFn:_,resolvedValue:(d=_.resolveFilterValue==null?void 0:_.resolveFilterValue(g.value))!=null?d:g.value})});let l=t.map(g=>g.id),u=e.getGlobalFilterFn(),a=e.getAllLeafColumns().filter(g=>g.getCanGlobalFilter());r&&u&&a.length&&(l.push("__global__"),a.forEach(g=>{var d;i.push({id:g.id,filterFn:u,resolvedValue:(d=u.resolveFilterValue==null?void 0:u.resolveFilterValue(r))!=null?d:r})}));let c,s;for(let g=0;g{d.columnFiltersMeta[_]=m})}if(i.length){for(let p=0;p{d.columnFiltersMeta[_]=m})){d.columnFilters.__global__=!0;break}}d.columnFilters.__global__!==!0&&(d.columnFilters.__global__=!1)}}let f=g=>{for(let d=0;d{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable},onChange:()=>{e._autoResetPageIndex()}})}function xn(){return(e,n)=>y(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter,e.getFilteredRowModel()],(t,r,o)=>{if(!t.rows.length||!(r!=null&&r.length)&&!o)return t;let i=[...r.map(u=>u.id).filter(u=>u!==n),o?"__global__":void 0].filter(Boolean),l=u=>{for(let a=0;a{var t;return(t=e.options.debugAll)!=null?t:e.options.debugTable},onChange:()=>{}})}function Fn(){return(e,n)=>y(()=>{var t;return[(t=e.getColumn(n))==null?void 0:t.getFacetedRowModel()]},t=>{if(!t)return new Map;let r=new Map;for(let i=0;i{var t;return(t=e.options.debugAll)!=null?t:e.options.debugTable},onChange:()=>{}})}function $n(){return(e,n)=>y(()=>{var t;return[(t=e.getColumn(n))==null?void 0:t.getFacetedRowModel()]},t=>{var r;if(!t)return;let o=(r=t.flatRows[0])==null?void 0:r.getUniqueValues(n);if(typeof o>"u")return;let i=[o,o];for(let l=0;li[1]&&(i[1]=c)}}return i},{key:!1,debug:()=>{var t;return(t=e.options.debugAll)!=null?t:e.options.debugTable},onChange:()=>{}})}function Mn(){return e=>y(()=>[e.getState().sorting,e.getPreSortedRowModel()],(n,t)=>{if(!t.rows.length||!(n!=null&&n.length))return t;let r=e.getState().sorting,o=[],i=r.filter(a=>{var c;return(c=e.getColumn(a.id))==null?void 0:c.getCanSort()}),l={};i.forEach(a=>{let c=e.getColumn(a.id);c&&(l[a.id]={sortUndefined:c.columnDef.sortUndefined,invertSorting:c.columnDef.invertSorting,sortingFn:c.getSortingFn()})});let u=a=>{let c=[...a];return c.sort((s,f)=>{for(let d=0;d{var f;o.push(s),(f=s.subRows)!=null&&f.length&&(s.subRows=u(s.subRows))}),c};return{rows:u(t.rows),flatRows:o,rowsById:t.rowsById}},{key:!1,debug:()=>{var n;return(n=e.options.debugAll)!=null?n:e.options.debugTable},onChange:()=>{e._autoResetPageIndex()}})}function rt(e,n){return e?wo(e)?D(e,n):e:null}function wo(e){return Ro(e)||typeof e=="function"||Eo(e)}function Ro(e){return typeof e=="function"&&(()=>{let n=Object.getPrototypeOf(e);return n.prototype&&n.prototype.isReactComponent})()}function Eo(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Vn(e){let n={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[t]=I(()=>({current:Cn(n)})),[r,o]=I(()=>t.current.initialState);return t.current.setOptions(i=>({...i,...e,state:{...r,...e.state},onStateChange:l=>{o(l),e.onStateChange==null||e.onStateChange(l)}})),t.current}function ce(){return ce=Object.assign?Object.assign.bind():function(e){for(var n=1;n"u"&&delete r[i]}),t.options=ge({debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:xo,rangeExtractor:Fo,onChange:function(){},measureElement:$o,initialRect:{width:0,height:0},scrollMargin:0,scrollingDelay:150,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1},r)},this.notify=function(){t.options.onChange==null||t.options.onChange(t)},this.cleanup=function(){t.unsubs.filter(Boolean).forEach(function(r){return r()}),t.unsubs=[],t.scrollElement=null},this._didMount=function(){return t.measureElementCache.forEach(t.observer.observe),function(){t.observer.disconnect(),t.cleanup()}},this._willUpdate=function(){var r=t.options.getScrollElement();t.scrollElement!==r&&(t.cleanup(),t.scrollElement=r,t._scrollToOffset(t.scrollOffset,{adjustments:void 0,behavior:void 0}),t.unsubs.push(t.options.observeElementRect(t,function(o){var i=t.scrollRect;t.scrollRect=o,(t.options.horizontal?o.width!==i.width:o.height!==i.height)&&t.maybeNotify()})),t.unsubs.push(t.options.observeElementOffset(t,function(o){t.scrollAdjustments=0,t.scrollOffset!==o&&(t.isScrollingTimeoutId!==null&&(clearTimeout(t.isScrollingTimeoutId),t.isScrollingTimeoutId=null),t.isScrolling=!0,t.scrollDirection=t.scrollOffset=0;u--){var a=r[u];if(!i.has(a.lane)){var c=l.get(a.lane);if(c==null||a.end>c.end?l.set(a.lane,a):a.end0?Math.min.apply(Math,t.pendingMeasuredCacheIndexes):0;t.pendingMeasuredCacheIndexes=[];for(var s=t.measurementsCache.slice(0,c),f=c;f=t.scrollOffset+i?o="end":o="start"),o==="start"?r=r:o==="end"?r=r-i:o==="center"&&(r=r-i/2);var l=t.options.horizontal?"scrollWidth":"scrollHeight",u=t.scrollElement?"document"in t.scrollElement?t.scrollElement.document.documentElement[l]:t.scrollElement[l]:0,a=u-t.getSize();return Math.max(Math.min(a,r),0)},this.getOffsetForIndex=function(r,o){o===void 0&&(o="auto"),r=Math.max(0,Math.min(r,t.options.count-1));var i=Ee(t.getMeasurements()[r]);if(o==="auto")if(i.end>=t.scrollOffset+t.getSize()-t.options.scrollPaddingEnd)o="end";else if(i.start<=t.scrollOffset+t.options.scrollPaddingStart)o="start";else return[t.scrollOffset,o];var l=o==="end"?i.end+t.options.scrollPaddingEnd:i.start-t.options.scrollPaddingStart;return[t.getOffsetForAlignment(l,o),o]},this.isDynamicMode=function(){return t.measureElementCache.size>0},this.cancelScrollToIndex=function(){t.scrollToIndexTimeoutId!==null&&(clearTimeout(t.scrollToIndexTimeoutId),t.scrollToIndexTimeoutId=null)},this.scrollToOffset=function(r,o){var i=o===void 0?{}:o,l=i.align,u=l===void 0?"start":l,a=i.behavior;t.cancelScrollToIndex(),a==="smooth"&&t.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),t._scrollToOffset(t.getOffsetForAlignment(r,u),{adjustments:void 0,behavior:a})},this.scrollToIndex=function(r,o){var i=o===void 0?{}:o,l=i.align,u=l===void 0?"auto":l,a=i.behavior;r=Math.max(0,Math.min(r,t.options.count-1)),t.cancelScrollToIndex(),a==="smooth"&&t.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size.");var c=t.getOffsetForIndex(r,u),s=c[0],f=c[1];t._scrollToOffset(s,{adjustments:void 0,behavior:a}),a!=="smooth"&&t.isDynamicMode()&&(t.scrollToIndexTimeoutId=setTimeout(function(){t.scrollToIndexTimeoutId=null;var g=t.measureElementCache.has(t.options.getItemKey(r));if(g){var d=t.getOffsetForIndex(r,f),p=d[0];In(p,t.scrollOffset)||t.scrollToIndex(r,{align:f,behavior:a})}else t.scrollToIndex(r,{align:f,behavior:a})}))},this.scrollBy=function(r,o){var i=o===void 0?{}:o,l=i.behavior;t.cancelScrollToIndex(),l==="smooth"&&t.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),t._scrollToOffset(t.scrollOffset+r,{adjustments:void 0,behavior:l})},this.getTotalSize=function(){var r;return(((r=t.getMeasurements()[t.options.count-1])==null?void 0:r.end)||t.options.paddingStart)-t.options.scrollMargin+t.options.paddingEnd},this._scrollToOffset=function(r,o){var i=o.adjustments,l=o.behavior;t.options.scrollToFn(r,{behavior:l,adjustments:i},t)},this.measure=function(){t.itemSizeCache=new Map,t.notify()},this.setOptions(n),this.scrollRect=this.options.initialRect,this.scrollOffset=this.options.initialOffset,this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(function(r){t.itemSizeCache.set(r.key,r.size)}),this.maybeNotify()},Nn=function(n,t,r,o){for(;n<=t;){var i=(n+t)/2|0,l=r(i);if(lo)t=i-1;else return i}return n>0?n-1:0};function Mo(e){for(var n=e.measurements,t=e.outerSize,r=e.scrollOffset,o=n.length-1,i=function(c){return n[c].start},l=Nn(0,o,i,r),u=l;u=i&&f<=u&&g>=l&&g<=a)return s}return null}function ot(e,n){return document?.defaultView?.getComputedStyle(e,null)?.getPropertyValue(n)}var Gn=e=>{let[n,t]=I(!1),{range:r,from:o,to:i,onRangeChange:l}=e;return b.createElement(Do,{range:r,value:[o,i],editing:n,onValueChange:u=>l(...u),onFocus:()=>t(!0),onBlur:()=>t(!1)})};var Do=e=>{let[n,t]=e.value,{editing:r,onFocus:o}=e,i=z(null),l=z(null);return b.createElement("div",{onBlur:u=>{if(!u.currentTarget.contains(u.relatedTarget))return e.onBlur()},onFocus:()=>o(),style:{display:"flex",gap:"0.5rem"}},b.createElement("input",{ref:i,className:`form-control form-control-sm ${i.current?.checkValidity()?"":"is-invalid"}`,style:{flex:"1 1 0",width:"0"},type:"number",placeholder:Ln(r,"Min",e.range()[0]),defaultValue:n,step:"any",onChange:u=>{let a=zn(u.target.value);i.current.classList.toggle("is-invalid",!u.target.checkValidity()),e.onValueChange([a,t])}}),b.createElement("input",{ref:l,className:`form-control form-control-sm ${l.current?.checkValidity()?"":"is-invalid"}`,style:{flex:"1 1 0",width:"0"},type:"number",placeholder:Ln(r,"Max",e.range()[1]),defaultValue:t,step:"any",onChange:u=>{let a=zn(u.target.value);l.current.classList.toggle("is-invalid",!u.target.checkValidity()),e.onValueChange([n,a])}}))};function Ln(e,n,t){return e?typeof t>"u"?n:`${n} (${t})`:null}function zn(e){if(e!=="")return+e}function Bn(e){return e?{getFilteredRowModel:En(),getFacetedRowModel:xn(),getFacetedUniqueValues:Fn(),getFacetedMinMaxValues:$n(),filterFns:{substring:(n,t,r,o)=>n.getValue(t).toString().includes(r)}}:{}}var Un=({header:e,className:n,...t})=>{if((e.column.columnDef.meta?.typeHint).type==="numeric"){let[o,i]=e.column.getFilterValue()??[void 0,void 0];return Gn({from:o,to:i,range:()=>e.column.getFacetedMinMaxValues()??[void 0,void 0],onRangeChange:(u,a)=>e.column.setFilterValue([u,a])})}return b.createElement("input",{...t,className:`form-control form-control-sm ${n}`,type:"text",onChange:o=>e.column.setFilterValue(o.target.value)})};var O=class e{static{this._empty=new e(new Set)}constructor(n){this._set=n}static empty(){return this._empty}static just(...n){return this.empty().add(...n)}has(n){return this._set.has(n)}add(...n){let t=new Set(this._set.keys());for(let r of n)t.add(r);return new e(t)}toggle(n){return this.has(n)?this.delete(n):this.add(n)}delete(n){let t=new Set(this._set.keys());return t.delete(n),new e(t)}clear(){return e.empty()}[Symbol.iterator](){return this._set[Symbol.iterator]()}toList(){return[...this._set.keys()]}};function qn(e,n,t,r){let[o,i]=I(O.empty()),[l,u]=I(null),a=s=>{if(e==="none")return;let f=s.currentTarget,g=n(f),d=To(e,r,o,s,g,l);d&&(i(d.selection),d.anchor&&(u(g),f.focus()),s.preventDefault())},c=s=>{if(e==="none")return;let f=s.currentTarget,g=n(f),d=o.has(g);if(e==="single"){if(s.key===" "||s.key==="Enter")o.has(g)?i(O.empty()):i(O.just(g)),s.preventDefault();else if(s.key==="ArrowUp"||s.key==="ArrowDown"){let p=t(g,s.key==="ArrowUp"?-1:1);p&&(s.preventDefault(),d&&i(O.just(p)))}}else e==="multiple"&&(s.key===" "||s.key==="Enter"?(i(o.toggle(g)),s.preventDefault()):(s.key==="ArrowUp"||s.key==="ArrowDown")&&t(g,s.key==="ArrowUp"?-1:1)&&s.preventDefault())};return{has(s){return o.has(s)},set(s,f){i(f?o.add(s):o.delete(s))},clear(){i(o.clear())},keys(){return o},itemHandlers(){return{onMouseDown:a,onKeyDown:c}}}}var jn=/^mac/i.test(window.navigator.userAgentData?.platform??window.navigator.platform);function To(e,n,t,r,o,i){let{shiftKey:l,altKey:u}=r,a=jn?r.metaKey:r.ctrlKey;if((jn?r.ctrlKey:r.metaKey)||u)return null;if(e==="multiple")return{selection:t.toggle(o),anchor:!0};if(e==="single")return a&&!l?t.has(o)?{selection:O.empty(),anchor:!0}:{selection:O.just(o),anchor:!0}:{selection:O.just(o),anchor:!0};if(e==="multi-native")if(l&&a){let s=n(i,o);return{selection:t.add(...s)}}else{if(a)return{selection:t.toggle(o),anchor:!0};if(l){if(i!==null&&n){let s=n(i,o);return{selection:O.just(...s)}}}else return{selection:O.just(o),anchor:!0}}}var Kn={className:"sort-arrow",viewBox:[-1,-1,2,2].map(e=>e*1.4).join(" "),width:"100%",height:"100%",style:{paddingLeft:"3px"}},Wn={stroke:"#333333",strokeWidth:"0.6",fill:"transparent"},Ao=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",...Kn},b.createElement("path",{d:"M -1 0.5 L 0 -0.5 L 1 0.5",...Wn,strokeLinecap:"round"})),Oo=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",...Kn},b.createElement("path",{d:"M -1 -0.5 L 0 0.5 L 1 -0.5",...Wn,strokeLinecap:"round"})),Xn=({direction:e})=>{if(!e)return null;if(e==="asc")return Ao;if(e==="desc")return Oo;throw new Error(`Unexpected sort direction: '${e}'`)};function Jn(e,n,t){let[r,o]=I(0),i=b.useCallback(u=>{o(-1),u.target===u.currentTarget&&Pn(e,n(),t)?.focus()},[e,n,t]),l=b.useCallback(u=>{o(0)},[]);return{containerTabIndex:r,containerHandlers:{onFocus:i,onBlur:l}}}function Yn(e,n,t,r,o){return U(()=>{let i=e??!0;if(!i)return null;let l=typeof i=="string"?i:"Viewing rows {start} through {end} of {total}";if(!n||t.length===0)return null;let u=n.scrollTop+r.clientHeight,a=n.scrollTop+n.clientHeight,[c,s]=No(u,a,t,(p,_)=>p.start+p.size/2);if(c===null||s===null)return null;let f=t[c],g=t[s];if(f.index===0&&g.index===o-1)return null;let d=ko(l,f.index+1,g.index+1,o);return b.createElement("div",{className:"shiny-data-grid-summary"},d)},[e,n,t,r,o])}function No(e,n,t,r){let o=null,i=null;for(let l=0;l=e&&(o=l,i=l);else if(r(u,!1)<=n)i=l;else break}return[o,i]}function ko(e,n,t,r){return e.replace(/\{(start|end|total)\}/g,(o,i)=>i==="start"?n+"":i==="end"?t+"":i==="total"?r+"":o)}var Ho=e=>{let{id:n,data:t,bgcolor:r}=e,{columns:o,type_hints:i,data:l}=t,{width:u,height:a,fill:c,filters:s}=t.options,f=z(null),g=z(null),d=z(null),p=U(()=>o.map((R,V)=>{let E=i?.[V];return{accessorFn:(K,xe)=>K[V],filterFn:E.type==="numeric"?"inNumberRange":"includesString",header:R,meta:{typeHint:E}}}),[o]),_=U(()=>[...l],[l]),m=Bn(s),v={data:_,columns:p,getCoreRowModel:wn(),getSortedRowModel:Mn(),...m},S=Vn(v),C=kn({count:S.getFilteredRowModel().rows.length,getScrollElement:()=>f.current,estimateSize:()=>31,paddingStart:g.current?.clientHeight??0,scrollingDelay:10});L(()=>{C.scrollToOffset(0)},[t]);let F=C.getTotalSize(),x=C.getVirtualItems(),N=(x.length>0&&x?.[0]?.start||0)-g.current?.clientHeight,q=x.length>0?F-(x?.[x.length-1]?.end||0):0,M=Yn(t.options.summary,f?.current,x,g.current,C.options.count),Y=t.options.style??"grid",er=Y==="grid"?"shiny-data-grid-grid":"shiny-data-grid-table",tr=Y==="table"?"table table-sm":null,re=t.options.row_selection_mode??"multi-native",zo=re!=="none",nr=re==="multi-native"||re==="multiple",oe=qn(re,R=>R.dataset.key,(R,V)=>{let E=S.getSortedRowModel(),K=E.rows.findIndex(gt=>gt.id===R);if(K<0||(K+=V,K<0||K>=E.rows.length))return null;let xe=E.rows[K].id;return C.scrollToIndex(K),setTimeout(()=>{f.current?.querySelector(`[data-key='${xe}']`)?.focus()},0),xe},(R,V)=>Po(S.getSortedRowModel(),R,V));B(()=>{n&&(re==="none"?Shiny.setInputValue(`${n}_selected_rows`,null):Shiny.setInputValue(`${n}_selected_rows`,oe.keys().toList().map(R=>parseInt(R)).sort()))},[[...oe.keys()]]);let rr=b.useCallback(()=>d.current.querySelectorAll("[tabindex='-1']"),[d.current]),st=Jn(f.current,rr,{top:g.current?.clientHeight??0});B(()=>()=>{S.resetSorting(),oe.clear()},[t]);let or=S.getHeaderGroups().length,ut="scrolling",at=f.current?.scrollHeight,dt=f.current?.clientHeight;at&&dt&&at<=dt&&(ut="");let ir=R=>V=>{(V.key===" "||V.key==="Enter")&&R.toggleSorting(void 0,V.shiftKey)},lr=Lo(C),ct=`shiny-data-grid ${er} ${ut}`;return c&&(ct+=" html-fill-item"),b.createElement(b.Fragment,null,b.createElement("div",{className:ct,ref:f,style:{width:u,height:a,overflow:"auto"}},b.createElement("table",{className:tr+(s?" filtering":""),"aria-rowcount":l.length,"aria-multiselectable":nr,style:{width:u===null||u==="auto"?null:"100%"}},b.createElement("thead",{ref:g,style:{backgroundColor:r}},S.getHeaderGroups().map((R,V)=>b.createElement("tr",{key:R.id,"aria-rowindex":V+1},R.headers.map(E=>b.createElement("th",{key:E.id,colSpan:E.colSpan,style:{width:E.getSize()},scope:"col",tabIndex:0,onClick:E.column.getToggleSortingHandler(),onKeyDown:ir(E.column)},E.isPlaceholder?null:b.createElement("div",{style:{cursor:E.column.getCanSort()?"pointer":null,userSelect:E.column.getCanSort()?"none":null}},rt(E.column.columnDef.header,E.getContext()),b.createElement(Xn,{direction:E.column.getIsSorted()})))))),s&&b.createElement("tr",{className:"filters"},S.getFlatHeaders().map(R=>b.createElement("th",{key:`filter-${R.id}`},b.createElement(Un,{header:R}))))),b.createElement("tbody",{ref:d,tabIndex:st.containerTabIndex,...st.containerHandlers},N>0&&b.createElement("tr",{style:{height:`${N}px`}}),x.map(R=>{let V=S.getRowModel().rows[R.index];return V&&b.createElement("tr",{key:R.key,"data-index":R.index,"aria-rowindex":R.index+or,"data-key":V.id,ref:lr,"aria-selected":oe.has(V.id),tabIndex:-1,...oe.itemHandlers()},V.getVisibleCells().map(E=>b.createElement("td",{key:E.id},rt(E.column.columnDef.cell,E.getContext()))))}),q>0&&b.createElement("tr",{style:{height:`${q}px`}})))),M)};function Po(e,n,t){let r=e.rows.findIndex(l=>l.id===n),o=e.rows.findIndex(l=>l.id===t);if(r<0||o<0)return[];r>o&&([r,o]=[o,r]);let i=[];for(let l=r;l<=o;l++)i.push(e.rows[l].id);return i}function Lo(e){let n=z([]),t=ye(r=>{r&&(r.isConnected?e.measureElement(r):n.current.push(r))},[e]);return L(()=>{n.current.length>0&&n.current.splice(0).forEach(e.measureElement)}),t}var it=class extends Shiny.OutputBinding{find(n){return $(n).find("shiny-data-frame")}renderValue(n,t){n.renderValue(t)}renderError(n,t){n.classList.add("shiny-output-error"),n.renderError(t)}clearError(n){n.classList.remove("shiny-output-error"),n.clearError()}};Shiny.outputBindings.register(new it,"shinyDataFrame");function Qn(e){if(!e)return null;let n=ot(e,"background-color");if(!n)return n;let t=n.match(/^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/);if(n==="transparent"||t&&parseFloat(t[4])===0){let r=ot(e,"background-image");return r&&r!=="none"?null:Qn(e.parentElement)}return n}var Zn=document.createElement("template");Zn.innerHTML=``;var lt=class extends HTMLElement{connectedCallback(){let[t]=[this];t.appendChild(Zn.content.cloneNode(!0)),this.errorRoot=document.createElement("span"),t.appendChild(this.errorRoot);let r=document.createElement("div");r.classList.add("html-fill-container","html-fill-item"),t.appendChild(r),this.reactRoot=Hn(r);let o=this.querySelector("script.data");if(o){let i=JSON.parse(o.innerText);this.renderValue(i)}}renderValue(t){if(this.clearError(),!t){this.reactRoot.render(null);return}this.reactRoot.render(b.createElement(Ge,null,b.createElement(Ho,{id:this.id,data:t,bgcolor:Qn(this)})))}renderError(t){this.reactRoot.render(null),this.errorRoot.innerText=t.message}clearError(){this.reactRoot.render(null),this.errorRoot.innerText=""}};customElements.define("shiny-data-frame",lt);export{lt as ShinyDataFrameOutput}; +} + +shiny-data-frame .shiny-data-grid-summary { + font-size: var(--shiny-datagrid-font-size); + padding-top: 0.3em; +} + +@keyframes fadeSuccessBorder { + 0% { + border: 2px var(--shiny-datagrid-table-cell-edit-success-border-style) var(--shiny-datagrid-table-cell-edit-success-border-color); + } + 50% { + border: 2px var(--shiny-datagrid-table-cell-edit-success-border-style) var(--shiny-datagrid-table-cell-edit-success-border-color); + } +} +.shiny-data-grid > table > tbody > tr > td.cell-edit-success { + animation: fadeSuccessBorder 6s; +} +.shiny-data-grid > table > tbody > tr > td.cell-edit-saving { + color: var(--shiny-datagrid-table-cell-edit-saving-color); + font-style: var(--shiny-datagrid-table-cell-edit-saving-font-style); +} +.shiny-data-grid > table > tbody > tr > td.cell-edit-failure { + border: 2px var(--shiny-datagrid-table-cell-edit-failure-border-style) var(--shiny-datagrid-table-cell-edit-failure-border-color); + background-color: var(--shiny-datagrid-table-cell-edit-failure-bgcolor); +}`;function to(e,n,t){let[r,o]=V(0),i=b.useCallback(u=>{o(-1),u.target===u.currentTarget&&Br(e,n(),t)?.focus()},[e,n,t]),l=b.useCallback(u=>{o(0)},[]);return{containerTabIndex:r,containerHandlers:{onFocus:i,onBlur:l}}}function no(e,n,t,r,o){return Y(()=>{let i=e??!0;if(!i)return null;let l=typeof i=="string"?i:"Viewing rows {start} through {end} of {total}";if(!n||t.length===0)return null;let u=n.scrollTop+r.clientHeight,a=n.scrollTop+n.clientHeight,[d,s]=Qi(u,a,t,(p,_)=>p.start+p.size/2);if(d===null||s===null)return null;let f=t[d],g=t[s];if(f.index===0&&g.index===o-1)return null;let c=Zi(l,f.index+1,g.index+1,o);return b.createElement("div",{className:"shiny-data-grid-summary"},c)},[e,n,t,r,o])}function Qi(e,n,t,r){let o=null,i=null;for(let l=0;l=e&&(o=l,i=l);else if(r(u,!1)<=n)i=l;else break}return[o,i]}function Zi(e,n,t,r){return e.replace(/\{(start|end|total)\}/g,(o,i)=>i==="start"?n+"":i==="end"?t+"":i==="total"?r+"":o)}var el=e=>{let{id:n,data:t,bgcolor:r}=e,{columns:o,type_hints:i,data:l}=t,{width:u,height:a,fill:d,filters:s}=t.options,f=L(null),g=L(null),c=L(null),[p,_]=V(null),[m,v]=V(null);k(()=>{console.log("editing info!",p,m)},[m,p]);let w=!t.options.mode,C=t.options.mode??"none",E=C==="edit",[O,A]=ke(new Map);Pr(),k(()=>{console.log("editing info!",p,m)},[m,p]);let ie=Y(()=>o.map((x,I)=>{let F=i?.[I];return{accessorFn:(q,at)=>q[I],filterFn:F.type==="numeric"?"inNumberRange":"includesString",header:x,meta:{colIndex:I,typeHint:F},cell:({getValue:q})=>q()}}),[o,i,p,m,O]),D=Y(()=>l,[l]),[U,ot]=ke(l),it=qr(s),lt={data:U,columns:ie,getCoreRowModel:gr(),getSortedRowModel:vr(),...it},j=yr(lt),Q=xr({count:j.getFilteredRowModel().rows.length,getScrollElement:()=>f.current,estimateSize:()=>31,paddingStart:g.current?.clientHeight??0,scrollingDelay:10});J(()=>{Q.scrollToOffset(0)},[t,Q]);let st=Q.getTotalSize(),Z=Q.getVirtualItems(),Pe=(Z.length>0&&Z?.[0]?.start||0)-g.current?.clientHeight,Re=Z.length>0?st-(Z?.[Z.length-1]?.end||0):0,pe=no(t.options.summary,f?.current,Z,g.current,Q.options.count),R=t.options.style??"grid",de=R==="grid"?"shiny-data-grid-grid":"shiny-data-grid-table",ee=R==="table"?"table table-sm":null,io=Object.values(Wt).includes(C)?C:"none",_e=w?"none":io,lo=_e!=="none",so=_e==="multi-native_row"||_e==="multiple_row",le=Jr(_e,x=>x.dataset.key,(x,I)=>{let F=j.getSortedRowModel(),q=F.rows.findIndex(nn=>nn.id===x);if(q<0||(q+=I,q<0||q>=F.rows.length))return null;let at=F.rows[q].id;return Q.scrollToIndex(q),setTimeout(()=>{f.current?.querySelector(`[data-key='${at}']`)?.focus()},0),at},(x,I)=>tl(j.getSortedRowModel(),x,I));k(()=>{let x=F=>{F.detail.keys.length?le.setMultiple(F.detail.keys.map(String)):le.clear()},I=document.getElementById(n);return I.addEventListener("updateRowSelection",x),()=>{I.removeEventListener("updateRowSelection",x)}},[n,le]),k(()=>{n&&(_e==="none"?Shiny.setInputValue(`${n}_selected_rows`,null):Shiny.setInputValue(`${n}_selected_rows`,le.keys().toList().map(x=>parseInt(x)).sort()))},[n,_e,[...le.keys()]]),E&&lo&&console.error("Should not have editable and row selection at the same time");let ao=b.useCallback(()=>c.current.querySelectorAll("[tabindex='-1']"),[c.current]),Yt=to(f.current,ao,{top:g.current?.clientHeight??0});k(()=>()=>{j.resetSorting(),le.clear()},[t]);let uo=j.getHeaderGroups().length,Qt="scrolling",Zt=f.current?.scrollHeight,en=f.current?.clientHeight;Zt&&en&&Zt<=en&&(Qt="");let co=x=>I=>{(I.key===" "||I.key==="Enter")&&x.toggleSorting(void 0,I.shiftKey)},go=nl(Q),tn=`shiny-data-grid ${de} ${Qt}`;d&&(tn+=" html-fill-item");let fo=j.getSortedRowModel().rows.length;return b.createElement(b.Fragment,null,b.createElement("div",{className:tn,ref:f,style:{width:u,height:a,overflow:"auto"}},b.createElement("table",{className:ee+(s?" filtering":""),"aria-rowcount":U.length,"aria-multiselectable":so,style:{width:u===null||u==="auto"?null:"100%"}},b.createElement("thead",{ref:g,style:{backgroundColor:r}},j.getHeaderGroups().map((x,I)=>b.createElement("tr",{key:x.id,"aria-rowindex":I+1},x.headers.map(F=>b.createElement("th",{key:F.id,colSpan:F.colSpan,style:{width:F.getSize()},scope:"col",tabIndex:0,onClick:F.column.getToggleSortingHandler(),onKeyDown:co(F.column)},F.isPlaceholder?null:b.createElement("div",{style:{cursor:F.column.getCanSort()?"pointer":null,userSelect:F.column.getCanSort()?"none":null}},Xe(F.column.columnDef.header,F.getContext()),b.createElement(Zr,{direction:F.column.getIsSorted()})))))),s&&b.createElement("tr",{className:"filters"},j.getFlatHeaders().map(x=>b.createElement("th",{key:`filter-${x.id}`},b.createElement(Wr,{header:x}))))),b.createElement("tbody",{ref:c,tabIndex:Yt.containerTabIndex,...Yt.containerHandlers},Pe>0&&b.createElement("tr",{style:{height:`${Pe}px`}}),Z.map(x=>{let I=j.getRowModel().rows[x.index];return I&&b.createElement("tr",{key:x.key,"data-index":x.index,"aria-rowindex":x.index+uo,"data-key":I.id,ref:go,"aria-selected":le.has(I.id),tabIndex:-1,...le.itemHandlers()},I.getVisibleCells().map(F=>b.createElement(Gr,{id:n,key:F.id,cell:F,canEdit:E,columns:o,editRowIndex:p,editColumnIndex:m,setEditRowIndex:_,setEditColumnIndex:v,cellEditMap:O,maxRowSize:fo,setData:ot,setCellEditMap:A})))}),Re>0&&b.createElement("tr",{style:{height:`${Re}px`}})))),pe)};function tl(e,n,t){let r=e.rows.findIndex(l=>l.id===n),o=e.rows.findIndex(l=>l.id===t);if(r<0||o<0)return[];r>o&&([r,o]=[o,r]);let i=[];for(let l=r;l<=o;l++)i.push(e.rows[l].id);return i}function nl(e){let n=L([]),t=be(r=>{r&&(r.isConnected?e.measureElement(r):n.current.push(r))},[e]);return J(()=>{n.current.length>0&&n.current.splice(0).forEach(e.measureElement)}),t}var Xt=class extends Shiny.OutputBinding{find(n){return $(n).find("shiny-data-frame")}renderValue(n,t){n.renderValue(t)}renderError(n,t){n.classList.add("shiny-output-error"),n.renderError(t)}clearError(n){n.classList.remove("shiny-output-error"),n.clearError()}};Shiny.outputBindings.register(new Xt,"shinyDataFrame");function ro(e){if(!e)return null;let n=qt(e,"background-color");if(!n)return n;let t=n.match(/^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/);if(n==="transparent"||t&&parseFloat(t[4])===0){let r=qt(e,"background-image");return r&&r!=="none"?null:ro(e.parentElement)}return n}var oo=document.createElement("template");oo.innerHTML=``;var Jt=class extends HTMLElement{connectedCallback(){let[t]=[this];t.appendChild(oo.content.cloneNode(!0)),this.errorRoot=document.createElement("span"),t.appendChild(this.errorRoot);let r=document.createElement("div");r.classList.add("html-fill-container","html-fill-item"),t.appendChild(r),this.reactRoot=Hr(r);let o=this.querySelector("script.data");if(o){let i=JSON.parse(o.innerText);this.renderValue(i)}}renderValue(t){if(this.clearError(),!t){this.reactRoot.render(null);return}this.reactRoot.render(b.createElement(Et,null,b.createElement(el,{id:this.id,data:t,bgcolor:ro(this)})))}renderError(t){this.reactRoot.render(null),this.errorRoot.innerText=t.message}clearError(){this.reactRoot.render(null),this.errorRoot.innerText=""}};customElements.define("shiny-data-frame",Jt);$(function(){Shiny.addCustomMessageHandler("receiveMessage",function(e){let n=new CustomEvent(e.handler,{detail:e.obj});document.getElementById(e.id).dispatchEvent(n)})});export{Jt as ShinyDataFrameOutput}; /*! Bundled license information: @tanstack/table-core/build/lib/index.mjs: diff --git a/shiny/www/shared/py-shiny/dataframe/dataframe.js.map b/shiny/www/shared/py-shiny/dataframe/dataframe.js.map index 778a88488..6bdd252bd 100644 --- a/shiny/www/shared/py-shiny/dataframe/dataframe.js.map +++ b/shiny/www/shared/py-shiny/dataframe/dataframe.js.map @@ -1,7 +1,7 @@ { "version": 3, - "sources": ["../../../../../js/dataframe/styles.scss", "../../../../../js/node_modules/preact/src/util.js", "../../../../../js/node_modules/preact/src/options.js", "../../../../../js/node_modules/preact/src/create-element.js", "../../../../../js/node_modules/preact/src/component.js", "../../../../../js/node_modules/preact/src/create-context.js", "../../../../../js/node_modules/preact/src/constants.js", "../../../../../js/node_modules/preact/src/diff/children.js", "../../../../../js/node_modules/preact/src/diff/props.js", "../../../../../js/node_modules/preact/src/diff/index.js", "../../../../../js/node_modules/preact/src/render.js", "../../../../../js/node_modules/preact/src/clone-element.js", "../../../../../js/node_modules/preact/src/diff/catch-error.js", "../../../../../js/node_modules/preact/hooks/src/index.js", "../../../../../js/node_modules/preact/compat/src/util.js", "../../../../../js/node_modules/preact/compat/src/PureComponent.js", "../../../../../js/node_modules/preact/compat/src/memo.js", "../../../../../js/node_modules/preact/compat/src/forwardRef.js", "../../../../../js/node_modules/preact/compat/src/Children.js", "../../../../../js/node_modules/preact/compat/src/suspense.js", "../../../../../js/node_modules/preact/compat/src/suspense-list.js", "../../../../../js/node_modules/preact/compat/src/portals.js", "../../../../../js/node_modules/preact/compat/src/render.js", "../../../../../js/node_modules/preact/compat/src/index.js", "../../../../../js/node_modules/@tanstack/table-core/src/utils.ts", "../../../../../js/node_modules/@tanstack/table-core/src/core/column.ts", "../../../../../js/node_modules/@tanstack/table-core/src/core/headers.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/ColumnSizing.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/Expanding.ts", "../../../../../js/node_modules/@tanstack/table-core/src/filterFns.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/Filters.ts", "../../../../../js/node_modules/@tanstack/table-core/src/aggregationFns.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/Grouping.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/Ordering.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/Pagination.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/Pinning.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/RowSelection.ts", "../../../../../js/node_modules/@tanstack/table-core/src/sortingFns.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/Sorting.ts", "../../../../../js/node_modules/@tanstack/table-core/src/features/Visibility.ts", "../../../../../js/node_modules/@tanstack/table-core/src/core/table.ts", "../../../../../js/node_modules/@tanstack/table-core/src/core/cell.ts", "../../../../../js/node_modules/@tanstack/table-core/src/core/row.ts", "../../../../../js/node_modules/@tanstack/table-core/src/columnHelper.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getCoreRowModel.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/filterRowsUtils.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getFilteredRowModel.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getFacetedRowModel.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getFacetedUniqueValues.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getFacetedMinMaxValues.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getSortedRowModel.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getGroupedRowModel.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getExpandedRowModel.ts", "../../../../../js/node_modules/@tanstack/table-core/src/utils/getPaginationRowModel.ts", "../../../../../js/node_modules/@tanstack/react-table/src/index.tsx", "../../../../../js/node_modules/@tanstack/react-virtual/build/lib/_virtual/_rollupPluginBabelHelpers.mjs", "../../../../../js/node_modules/@tanstack/virtual-core/build/lib/_virtual/_rollupPluginBabelHelpers.mjs", "../../../../../js/node_modules/@tanstack/virtual-core/src/utils.ts", "../../../../../js/node_modules/@tanstack/virtual-core/src/index.ts", "../../../../../js/node_modules/@tanstack/react-virtual/src/index.tsx", "../../../../../js/node_modules/preact/compat/client.mjs", "../../../../../js/dataframe/dom-utils.tsx", "../../../../../js/dataframe/filter-numeric.tsx", "../../../../../js/dataframe/filter.tsx", "../../../../../js/dataframe/immutable-set.tsx", "../../../../../js/dataframe/selection.tsx", "../../../../../js/dataframe/sort-arrows.tsx", "../../../../../js/dataframe/tabindex-group.ts", "../../../../../js/dataframe/table-summary.tsx", "../../../../../js/dataframe/index.tsx"], - "sourcesContent": ["export default `\n*,\n*::before,\n*::after {\n box-sizing: border-box;\n}\n\n.shiny-data-grid {\n --shiny-datagrid-font-size: 0.9em;\n --shiny-datagrid-padding-x: 0.5em;\n --shiny-datagrid-padding-y: 0.3em;\n --shiny-datagrid-padding: var(--shiny-datagrid-padding-y)\n var(--shiny-datagrid-padding-x);\n --shiny-datagrid-grid-header-bgcolor: var(--bs-light, #eee);\n --shiny-datagrid-grid-header-gridlines-color: var(--bs-border-color, #ccc);\n --shiny-datagrid-grid-header-gridlines-style: solid;\n --shiny-datagrid-grid-gridlines-color: var(--bs-border-color, #ccc);\n --shiny-datagrid-grid-gridlines-style: solid;\n --shiny-datagrid-table-header-bottom-border: 1px solid;\n --shiny-datagrid-table-top-border: 1px solid;\n --shiny-datagrid-table-bottom-border: 1px solid;\n --shiny-datagrid-grid-body-hover-bgcolor: var(\n --shiny-datagrid-grid-header-bgcolor\n );\n --shiny-datagrid-grid-body-selected-bgcolor: #b4d5fe;\n --shiny-datagrid-grid-body-selected-color: var(--bs-dark);\n}\n\n.shiny-data-grid svg.sort-arrow {\n display: inline-block;\n width: 0.85em;\n height: 0.85em;\n margin-bottom: 0.15em;\n}\n\n.shiny-data-grid {\n max-width: 100%;\n height: 500px;\n}\n.shiny-data-grid:not(.scrolling) {\n height: auto;\n}\n.shiny-data-grid > table {\n border-collapse: separate;\n border-spacing: 0;\n}\n.shiny-data-grid > table > thead {\n position: sticky;\n top: 0;\n}\n.shiny-data-grid > table > thead > tr > th {\n text-align: left;\n white-space: nowrap;\n}\n.shiny-data-grid > table > thead > tr > th:focus-visible {\n outline: 5px auto Highlight;\n outline: 5px auto -webkit-focus-ring-color;\n}\n.shiny-data-grid > table.filtering > thead > tr:nth-last-child(2) > th {\n border-bottom: none;\n}\n.shiny-data-grid > table.filtering > thead > tr.filters > th {\n font-weight: unset;\n padding-top: 0;\n /* Slight boost to bottom padding */\n padding-bottom: var(--shiny-datagrid-padding-x);\n}\n.shiny-data-grid > table.filtering > thead > tr.filters > th > input {\n width: 100%;\n}\n\n.shiny-data-grid.shiny-data-grid-table {\n border-top: var(--shiny-datagrid-table-top-border);\n}\n.shiny-data-grid.shiny-data-grid-table.scrolling {\n border-bottom: var(--shiny-datagrid-table-bottom-border);\n}\n.shiny-data-grid.shiny-data-grid-table > table > thead > tr:last-child > th {\n border-bottom: var(--shiny-datagrid-table-header-bottom-border);\n}\n.shiny-data-grid.shiny-data-grid-table > table > tbody > tr[aria-selected=true] {\n --shiny-datagrid-grid-gridlines-color: var(\n --shiny-datagrid-grid-body-selected-bgcolor\n );\n background-color: var(--shiny-datagrid-grid-body-selected-bgcolor);\n color: var(--shiny-datagrid-grid-body-selected-color);\n}\n\n/*\n *\n * # GRID STYLES\n *\n */\n.shiny-data-grid.shiny-data-grid-grid > table {\n font-size: var(--shiny-datagrid-font-size);\n}\n.shiny-data-grid.shiny-data-grid-grid > table > thead > tr > th,\n.shiny-data-grid.shiny-data-grid-grid > table > thead > tr > td {\n background-color: var(--shiny-datagrid-grid-header-bgcolor);\n padding: var(--shiny-datagrid-padding);\n}\n.shiny-data-grid.shiny-data-grid-grid > table > tbody > tr:focus-visible {\n outline: 5px auto Highlight;\n outline: 5px auto -webkit-focus-ring-color;\n}\n.shiny-data-grid.shiny-data-grid-grid > table > tbody > tr:hover {\n --shiny-datagrid-grid-gridlines-color: inherit;\n background-color: var(--shiny-datagrid-grid-body-hover-bgcolor);\n}\n.shiny-data-grid.shiny-data-grid-grid > table > tbody > tr[aria-selected=true] {\n --shiny-datagrid-grid-gridlines-color: var(\n --shiny-datagrid-grid-body-selected-bgcolor\n );\n background-color: var(--shiny-datagrid-grid-body-selected-bgcolor);\n color: var(--shiny-datagrid-grid-body-selected-color);\n}\n.shiny-data-grid.shiny-data-grid-grid > table > tbody > tr > td {\n padding: var(--shiny-datagrid-padding);\n}\n\n/* ## Grid borders */\n.shiny-data-grid.shiny-data-grid-grid > table {\n border-collapse: separate;\n}\n.shiny-data-grid.shiny-data-grid-grid > table > thead > tr:first-child > th {\n border-top-style: var(--shiny-datagrid-grid-gridlines-style);\n}\n.shiny-data-grid.shiny-data-grid-grid > table > thead > tr > th {\n border: 1px var(--shiny-datagrid-grid-gridlines-style) var(--shiny-datagrid-grid-header-gridlines-color);\n border-top-style: none;\n border-left-style: none;\n}\n.shiny-data-grid.shiny-data-grid-grid > table > thead > tr > th:first-child {\n border-left-style: var(--shiny-datagrid-grid-gridlines-style);\n}\n.shiny-data-grid.shiny-data-grid-grid > table > tbody > tr > td {\n border: 1px var(--shiny-datagrid-grid-gridlines-style) var(--shiny-datagrid-grid-gridlines-color);\n border-top-style: none;\n border-left-style: none;\n}\n.shiny-data-grid.shiny-data-grid-grid > table > tbody > tr > td:first-child {\n border-left-style: var(--shiny-datagrid-grid-gridlines-style);\n}\n.shiny-data-grid.shiny-data-grid-grid.scrolling {\n border: var(--shiny-datagrid-grid-gridlines-style) 1px var(--shiny-datagrid-grid-header-gridlines-color);\n}\n.shiny-data-grid.shiny-data-grid-grid.scrolling > table > thead > tr:first-child > th {\n border-top-style: none;\n}\n.shiny-data-grid.shiny-data-grid-grid.scrolling > table > tbody > tr:last-child > td {\n border-bottom-style: none;\n}\n.shiny-data-grid.shiny-data-grid-grid.scrolling > table > thead > tr > th:first-child,\n.shiny-data-grid.shiny-data-grid-grid.scrolling > table > tbody > tr > td:first-child {\n border-left-style: none;\n}\n.shiny-data-grid.shiny-data-grid-grid.scrolling > table > thead > tr > th:last-child,\n.shiny-data-grid.shiny-data-grid-grid.scrolling > table > tbody > tr > td:last-child {\n border-right-style: none;\n}\n\n/* Center the table when inside of a card */\n.card-body .shiny-data-grid {\n margin-left: auto;\n margin-right: auto;\n}\n\n/* When .shiny-data-grid is not scrolling, the containers shouldn't flex */\nshiny-data-frame:has(> div > .shiny-data-grid:not(.scrolling)) {\n flex: 0 0 auto;\n}\nshiny-data-frame > div:has(> .shiny-data-grid:not(.scrolling)) {\n flex: 0 0 auto;\n}`;\n", "import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-ignore We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {Node} node The node to remove\n */\nexport function removeNode(node) {\n\tlet parentNode = node.parentNode;\n\tif (parentNode) parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n", "import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n", "import { slice } from './util';\nimport options from './options';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * constructor for this virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array} [children] The children of the virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != null) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === undefined) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, null);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: null,\n\t\t_parent: null,\n\t\t_depth: 0,\n\t\t_dom: null,\n\t\t// _nextDom must be initialized to undefined b/c it will eventually\n\t\t// be set to dom.nextSibling which can return `null` and it is important\n\t\t// to be able to distinguish between an uninitialized _nextDom and\n\t\t// a _nextDom that has been set to `null`\n\t\t_nextDom: undefined,\n\t\t_component: null,\n\t\t_hydrating: null,\n\t\tconstructor: undefined,\n\t\t_original: original == null ? ++vnodeId : original\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == null && options.vnode != null) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: null };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is import('./internal').VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != null && vnode.constructor === undefined;\n", "import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function Component(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != null && this._nextState !== this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == null) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](http://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {import('./index').ComponentChildren | void}\n */\nComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == null) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._parent._children.indexOf(vnode) + 1)\n\t\t\t: null;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != null && sibling._dom != null) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : null;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tlet vnode = component._vnode,\n\t\toldDom = vnode._dom,\n\t\tparentDom = component._parentDom;\n\n\tif (parentDom) {\n\t\tlet commitQueue = [];\n\t\tconst oldVNode = assign({}, vnode);\n\t\toldVNode._original = vnode._original + 1;\n\n\t\tdiff(\n\t\t\tparentDom,\n\t\t\tvnode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tparentDom.ownerSVGElement !== undefined,\n\t\t\tvnode._hydrating != null ? [oldDom] : null,\n\t\t\tcommitQueue,\n\t\t\toldDom == null ? getDomSibling(vnode) : oldDom,\n\t\t\tvnode._hydrating\n\t\t);\n\t\tcommitRoot(commitQueue, vnode);\n\n\t\tif (vnode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(vnode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != null && vnode._component != null) {\n\t\tvnode._dom = vnode._component.base = null;\n\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child != null && child._dom != null) {\n\t\t\t\tvnode._dom = vnode._component.base = child._dom;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce !== options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {import('./internal').Component} a\n * @param {import('./internal').Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\tlet c;\n\trerenderQueue.sort(depthSort);\n\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t// process() calls from getting scheduled while `queue` is still being consumed.\n\twhile ((c = rerenderQueue.shift())) {\n\t\tif (c._dirty) {\n\t\t\tlet renderQueueLength = rerenderQueue.length;\n\t\t\trenderComponent(c);\n\t\t\tif (rerenderQueue.length > renderQueueLength) {\n\t\t\t\t// When i.e. rerendering a provider additional new items can be injected, we want to\n\t\t\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t\t\t// single pass\n\t\t\t\trerenderQueue.sort(depthSort);\n\t\t\t}\n\t\t}\n\t}\n\tprocess._rerenderCount = 0;\n}\n\nprocess._rerenderCount = 0;\n", "import { enqueueRender } from './component';\n\nexport let i = 0;\n\nexport function createContext(defaultValue, contextId) {\n\tcontextId = '__cC' + i++;\n\n\tconst context = {\n\t\t_id: contextId,\n\t\t_defaultValue: defaultValue,\n\t\t/** @type {import('./internal').FunctionComponent} */\n\t\tConsumer(props, contextValue) {\n\t\t\t// return props.children(\n\t\t\t// \tcontext[contextId] ? context[contextId].props.value : defaultValue\n\t\t\t// );\n\t\t\treturn props.children(contextValue);\n\t\t},\n\t\t/** @type {import('./internal').FunctionComponent} */\n\t\tProvider(props) {\n\t\t\tif (!this.getChildContext) {\n\t\t\t\t/** @type {import('./internal').Component[]} */\n\t\t\t\tlet subs = [];\n\t\t\t\tlet ctx = {};\n\t\t\t\tctx[contextId] = this;\n\n\t\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t\tif (this.props.value !== _props.value) {\n\t\t\t\t\t\t// I think the forced value propagation here was only needed when `options.debounceRendering` was being bypassed:\n\t\t\t\t\t\t// https://github.com/preactjs/preact/commit/4d339fb803bea09e9f198abf38ca1bf8ea4b7771#diff-54682ce380935a717e41b8bfc54737f6R358\n\t\t\t\t\t\t// In those cases though, even with the value corrected, we're double-rendering all nodes.\n\t\t\t\t\t\t// It might be better to just tell folks not to use force-sync mode.\n\t\t\t\t\t\t// Currently, using `useContext()` in a class component will overwrite its `this.context` value.\n\t\t\t\t\t\t// subs.some(c => {\n\t\t\t\t\t\t// \tc.context = _props.value;\n\t\t\t\t\t\t// \tenqueueRender(c);\n\t\t\t\t\t\t// });\n\n\t\t\t\t\t\t// subs.some(c => {\n\t\t\t\t\t\t// \tc.context[contextId] = _props.value;\n\t\t\t\t\t\t// \tenqueueRender(c);\n\t\t\t\t\t\t// });\n\t\t\t\t\t\tsubs.some(c => {\n\t\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tthis.sub = c => {\n\t\t\t\t\tsubs.push(c);\n\t\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\t\tsubs.splice(subs.indexOf(c), 1);\n\t\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn props.children;\n\t\t}\n\t};\n\n\t// Devtools needs access to the context object when it\n\t// encounters a Provider. This is necessary to support\n\t// setting `displayName` on the context object instead\n\t// of on the component itself. See:\n\t// https://reactjs.org/docs/context.html#contextdisplayname\n\n\treturn (context.Provider._contextRef = context.Consumer.contextType =\n\t\tcontext);\n}\n", "export const EMPTY_OBJ = {};\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n", "import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport { EMPTY_OBJ, EMPTY_ARR } from '../constants';\nimport { getDomSibling } from '../component';\nimport { isArray } from '../util';\n\n/**\n * Diff the children of a virtual node\n * @param {import('../internal').PreactElement} parentDom The DOM element whose\n * children are being diffed\n * @param {import('../internal').ComponentChildren[]} renderResult\n * @param {import('../internal').VNode} newParentVNode The new virtual\n * node whose children should be diff'ed against oldParentVNode\n * @param {import('../internal').VNode} oldParentVNode The old virtual\n * node whose children should be diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by getChildContext\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').PreactElement} oldDom The current attached DOM\n * element any new dom elements should be placed around. Likely `null` on first\n * render (except when hydrating). Can be a sibling DOM element when diffing\n * Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating\n) {\n\tlet i, j, oldVNode, childVNode, newDom, firstChildDom, refs;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet oldChildrenLength = oldChildren.length;\n\n\tnewParentVNode._children = [];\n\tfor (i = 0; i < renderResult.length; i++) {\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == null ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = null;\n\t\t}\n\t\t// If this newVNode is being reused (e.g.
{reuse}{reuse}
) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint'\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tnull,\n\t\t\t\tchildVNode,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull\n\t\t\t);\n\t\t} else if (childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse =
\n\t\t\t//
{reuse}{reuse}
\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : null,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tchildVNode = newParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\t// Terser removes the `continue` here and wraps the loop body\n\t\t// in a `if (childVNode) { ... } condition\n\t\tif (childVNode == null) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Check if we find a corresponding element in oldChildren.\n\t\t// If found, delete the array item by setting to `undefined`.\n\t\t// We use `undefined`, as `null` is reserved for empty placeholders\n\t\t// (holes).\n\t\toldVNode = oldChildren[i];\n\n\t\tif (\n\t\t\toldVNode === null ||\n\t\t\t(oldVNode &&\n\t\t\t\tchildVNode.key == oldVNode.key &&\n\t\t\t\tchildVNode.type === oldVNode.type)\n\t\t) {\n\t\t\toldChildren[i] = undefined;\n\t\t} else {\n\t\t\t// Either oldVNode === undefined or oldChildrenLength > 0,\n\t\t\t// so after this loop oldVNode == null or oldVNode is a valid value.\n\t\t\tfor (j = 0; j < oldChildrenLength; j++) {\n\t\t\t\toldVNode = oldChildren[j];\n\t\t\t\t// If childVNode is unkeyed, we only match similarly unkeyed nodes, otherwise we match by key.\n\t\t\t\t// We always match by type (in either case).\n\t\t\t\tif (\n\t\t\t\t\toldVNode &&\n\t\t\t\t\tchildVNode.key == oldVNode.key &&\n\t\t\t\t\tchildVNode.type === oldVNode.type\n\t\t\t\t) {\n\t\t\t\t\toldChildren[j] = undefined;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toldVNode = null;\n\t\t\t}\n\t\t}\n\n\t\toldVNode = oldVNode || EMPTY_OBJ;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tdiff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tisSvg,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating\n\t\t);\n\n\t\tnewDom = childVNode._dom;\n\n\t\tif ((j = childVNode.ref) && oldVNode.ref != j) {\n\t\t\tif (!refs) refs = [];\n\t\t\tif (oldVNode.ref) refs.push(oldVNode.ref, null, childVNode);\n\t\t\trefs.push(j, childVNode._component || newDom, childVNode);\n\t\t}\n\n\t\tif (newDom != null) {\n\t\t\tif (firstChildDom == null) {\n\t\t\t\tfirstChildDom = newDom;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\ttypeof childVNode.type == 'function' &&\n\t\t\t\tchildVNode._children === oldVNode._children\n\t\t\t) {\n\t\t\t\tchildVNode._nextDom = oldDom = reorderChildren(\n\t\t\t\t\tchildVNode,\n\t\t\t\t\toldDom,\n\t\t\t\t\tparentDom\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\toldDom = placeChild(\n\t\t\t\t\tparentDom,\n\t\t\t\t\tchildVNode,\n\t\t\t\t\toldVNode,\n\t\t\t\t\toldChildren,\n\t\t\t\t\tnewDom,\n\t\t\t\t\toldDom\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (typeof newParentVNode.type == 'function') {\n\t\t\t\t// Because the newParentVNode is Fragment-like, we need to set it's\n\t\t\t\t// _nextDom property to the nextSibling of its last child DOM node.\n\t\t\t\t//\n\t\t\t\t// `oldDom` contains the correct value here because if the last child\n\t\t\t\t// is a Fragment-like, then oldDom has already been set to that child's _nextDom.\n\t\t\t\t// If the last child is a DOM VNode, then oldDom will be set to that DOM\n\t\t\t\t// node's nextSibling.\n\t\t\t\tnewParentVNode._nextDom = oldDom;\n\t\t\t}\n\t\t} else if (\n\t\t\toldDom &&\n\t\t\toldVNode._dom == oldDom &&\n\t\t\toldDom.parentNode != parentDom\n\t\t) {\n\t\t\t// The above condition is to handle null placeholders. See test in placeholder.test.js:\n\t\t\t// `efficiently replace null placeholders in parent rerenders`\n\t\t\toldDom = getDomSibling(oldVNode);\n\t\t}\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\t// Remove remaining oldChildren if there are any.\n\tfor (i = oldChildrenLength; i--; ) {\n\t\tif (oldChildren[i] != null) {\n\t\t\tif (\n\t\t\t\ttypeof newParentVNode.type == 'function' &&\n\t\t\t\toldChildren[i]._dom != null &&\n\t\t\t\toldChildren[i]._dom == newParentVNode._nextDom\n\t\t\t) {\n\t\t\t\t// If the newParentVNode.__nextDom points to a dom node that is about to\n\t\t\t\t// be unmounted, then get the next sibling of that vnode and set\n\t\t\t\t// _nextDom to it\n\t\t\t\tnewParentVNode._nextDom = getLastDom(oldParentVNode).nextSibling;\n\t\t\t}\n\n\t\t\tunmount(oldChildren[i], oldChildren[i]);\n\t\t}\n\t}\n\n\t// Set refs only after unmount\n\tif (refs) {\n\t\tfor (i = 0; i < refs.length; i++) {\n\t\t\tapplyRef(refs[i], refs[++i], refs[++i]);\n\t\t}\n\t}\n}\n\nfunction reorderChildren(childVNode, oldDom, parentDom) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\tlet c = childVNode._children;\n\tlet tmp = 0;\n\tfor (; c && tmp < c.length; tmp++) {\n\t\tlet vnode = c[tmp];\n\t\tif (vnode) {\n\t\t\t// We typically enter this code path on sCU bailout, where we copy\n\t\t\t// oldVNode._children to newVNode._children. If that is the case, we need\n\t\t\t// to update the old children's _parent pointer to point to the newVNode\n\t\t\t// (childVNode here).\n\t\t\tvnode._parent = childVNode;\n\n\t\t\tif (typeof vnode.type == 'function') {\n\t\t\t\toldDom = reorderChildren(vnode, oldDom, parentDom);\n\t\t\t} else {\n\t\t\t\toldDom = placeChild(parentDom, vnode, vnode, c, vnode._dom, oldDom);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {import('../index').ComponentChildren} children The unflattened\n * children of a virtual node\n * @returns {import('../internal').VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == null || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\nfunction placeChild(\n\tparentDom,\n\tchildVNode,\n\toldVNode,\n\toldChildren,\n\tnewDom,\n\toldDom\n) {\n\tlet nextDom;\n\tif (childVNode._nextDom !== undefined) {\n\t\t// Only Fragments or components that return Fragment like VNodes will\n\t\t// have a non-undefined _nextDom. Continue the diff from the sibling\n\t\t// of last DOM child of this child VNode\n\t\tnextDom = childVNode._nextDom;\n\n\t\t// Eagerly cleanup _nextDom. We don't need to persist the value because\n\t\t// it is only used by `diffChildren` to determine where to resume the diff after\n\t\t// diffing Components and Fragments. Once we store it the nextDOM local var, we\n\t\t// can clean up the property\n\t\tchildVNode._nextDom = undefined;\n\t} else if (\n\t\toldVNode == null ||\n\t\tnewDom != oldDom ||\n\t\tnewDom.parentNode == null\n\t) {\n\t\touter: if (oldDom == null || oldDom.parentNode !== parentDom) {\n\t\t\tparentDom.appendChild(newDom);\n\t\t\tnextDom = null;\n\t\t} else {\n\t\t\t// `j= 0; i--) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child) {\n\t\t\t\tlet lastDom = getLastDom(child);\n\t\t\t\tif (lastDom) {\n\t\t\t\t\treturn lastDom;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n", "import { IS_NON_DIMENSIONAL } from '../constants';\nimport options from '../options';\n\n/**\n * Diff the old and new properties of a VNode and apply changes to the DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to apply\n * changes to\n * @param {object} newProps The new props\n * @param {object} oldProps The old props\n * @param {boolean} isSvg Whether or not this node is an SVG node\n * @param {boolean} hydrate Whether or not we are in hydration mode\n */\nexport function diffProps(dom, newProps, oldProps, isSvg, hydrate) {\n\tlet i;\n\n\tfor (i in oldProps) {\n\t\tif (i !== 'children' && i !== 'key' && !(i in newProps)) {\n\t\t\tsetProperty(dom, i, null, oldProps[i], isSvg);\n\t\t}\n\t}\n\n\tfor (i in newProps) {\n\t\tif (\n\t\t\t(!hydrate || typeof newProps[i] == 'function') &&\n\t\t\ti !== 'children' &&\n\t\t\ti !== 'key' &&\n\t\t\ti !== 'value' &&\n\t\t\ti !== 'checked' &&\n\t\t\toldProps[i] !== newProps[i]\n\t\t) {\n\t\t\tsetProperty(dom, i, newProps[i], oldProps[i], isSvg);\n\t\t}\n\t}\n}\n\nfunction setStyle(style, key, value) {\n\tif (key[0] === '-') {\n\t\tstyle.setProperty(key, value == null ? '' : value);\n\t} else if (value == null) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, isSvg) {\n\tlet useCapture;\n\n\to: if (name === 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] !== oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] === 'o' && name[1] === 'n') {\n\t\tuseCapture = name !== (name = name.replace(/Capture$/, ''));\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (name.toLowerCase() in dom) name = name.toLowerCase().slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tconst handler = useCapture ? eventProxyCapture : eventProxy;\n\t\t\t\tdom.addEventListener(name, handler, useCapture);\n\t\t\t}\n\t\t} else {\n\t\t\tconst handler = useCapture ? eventProxyCapture : eventProxy;\n\t\t\tdom.removeEventListener(name, handler, useCapture);\n\t\t}\n\t} else if (name !== 'dangerouslySetInnerHTML') {\n\t\tif (isSvg) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname !== 'width' &&\n\t\t\tname !== 'height' &&\n\t\t\tname !== 'href' &&\n\t\t\tname !== 'list' &&\n\t\t\tname !== 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname !== 'tabIndex' &&\n\t\t\tname !== 'download' &&\n\t\t\tname !== 'rowSpan' &&\n\t\t\tname !== 'colSpan' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == null ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value === 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != null && (value !== false || name[4] === '-')) {\n\t\t\tdom.setAttribute(name, value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Proxy an event to hooked event handlers\n * @param {Event} e The event object from the browser\n * @private\n */\nfunction eventProxy(e) {\n\treturn this._listeners[e.type + false](options.event ? options.event(e) : e);\n}\n\nfunction eventProxyCapture(e) {\n\treturn this._listeners[e.type + true](options.event ? options.event(e) : e);\n}\n", "import { EMPTY_OBJ } from '../constants';\nimport { Component, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { diffProps, setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {import('../internal').PreactElement} parentDom The parent of the DOM element\n * @param {import('../internal').VNode} newVNode The new virtual node\n * @param {import('../internal').VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by getChildContext\n * @param {boolean} isSvg Whether or not this element is an SVG node\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').PreactElement} oldDom The current attached DOM\n * element any new dom elements should be placed around. Likely `null` on first\n * render (except when hydrating). Can be a sibling DOM element when diffing\n * Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} [isHydrating] Whether or not we are in hydration\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating\n) {\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== undefined) return null;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._hydrating != null) {\n\t\tisHydrating = oldVNode._hydrating;\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\t// if we resume, we want the tree to be \"unlocked\"\n\t\tnewVNode._hydrating = null;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\ttry {\n\t\touter: if (typeof newType == 'function') {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif ('prototype' in newType && newType.prototype.render) {\n\t\t\t\t\t// @ts-ignore The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-ignore Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new Component(newProps, componentContext);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tc.props = newProps;\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc.context = componentContext;\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (c._nextState == null) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (newType.getDerivedStateFromProps != null) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tc.componentWillMount != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (c.componentDidMount != null) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != null &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false) ||\n\t\t\t\t\tnewVNode._original === oldVNode._original\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original !== oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\t// In cases of bailing due to strict-equality we have to reset force as well\n\t\t\t\t\tc._force = false;\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.forEach(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t\t}\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != null) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (c.componentDidUpdate != null) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif ('prototype' in newType && newType.prototype.render) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t}\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != null) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (!isNew && c.getSnapshotBeforeUpdate != null) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet isTopLevelFragment =\n\t\t\t\ttmp != null && tmp.type === Fragment && tmp.key == null;\n\t\t\tlet renderResult = isTopLevelFragment ? tmp.props.children : tmp;\n\n\t\t\tdiffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._hydrating = null;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = null;\n\t\t\t}\n\n\t\t\tc._force = false;\n\t\t} else if (\n\t\t\texcessDomChildren == null &&\n\t\t\tnewVNode._original === oldVNode._original\n\t\t) {\n\t\t\tnewVNode._children = oldVNode._children;\n\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t} else {\n\t\t\tnewVNode._dom = diffElementNodes(\n\t\t\t\toldVNode._dom,\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\tisHydrating\n\t\t\t);\n\t\t}\n\n\t\tif ((tmp = options.diffed)) tmp(newVNode);\n\t} catch (e) {\n\t\tnewVNode._original = null;\n\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\tif (isHydrating || excessDomChildren != null) {\n\t\t\tnewVNode._dom = oldDom;\n\t\t\tnewVNode._hydrating = !!isHydrating;\n\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = null;\n\t\t\t// ^ could possibly be simplified to:\n\t\t\t// excessDomChildren.length = 0;\n\t\t}\n\t\toptions._catchError(e, newVNode, oldVNode);\n\t}\n}\n\n/**\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {import('../internal').VNode} root\n */\nexport function commitRoot(commitQueue, root) {\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-ignore Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-ignore See above ts-ignore on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {import('../internal').PreactElement} dom The DOM element representing\n * the virtual nodes being diffed\n * @param {import('../internal').VNode} newVNode The new virtual node\n * @param {import('../internal').VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {boolean} isSvg Whether or not this DOM node is an SVG node\n * @param {*} excessDomChildren\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @returns {import('../internal').PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tisSvg,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating\n) {\n\tlet oldProps = oldVNode.props;\n\tlet newProps = newVNode.props;\n\tlet nodeType = newVNode.type;\n\tlet i = 0;\n\n\t// Tracks entering and exiting SVG namespace when descending through the tree.\n\tif (nodeType === 'svg') isSvg = true;\n\n\tif (excessDomChildren != null) {\n\t\tfor (; i < excessDomChildren.length; i++) {\n\t\t\tconst child = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tchild &&\n\t\t\t\t'setAttribute' in child === !!nodeType &&\n\t\t\t\t(nodeType ? child.localName === nodeType : child.nodeType === 3)\n\t\t\t) {\n\t\t\t\tdom = child;\n\t\t\t\texcessDomChildren[i] = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == null) {\n\t\tif (nodeType === null) {\n\t\t\t// @ts-ignore createTextNode returns Text, we expect PreactElement\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tif (isSvg) {\n\t\t\tdom = document.createElementNS(\n\t\t\t\t'http://www.w3.org/2000/svg',\n\t\t\t\t// @ts-ignore We know `newVNode.type` is a string\n\t\t\t\tnodeType\n\t\t\t);\n\t\t} else {\n\t\t\tdom = document.createElement(\n\t\t\t\t// @ts-ignore We know `newVNode.type` is a string\n\t\t\t\tnodeType,\n\t\t\t\tnewProps.is && newProps\n\t\t\t);\n\t\t}\n\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = null;\n\t\t// we are creating a new node, so we can assume this is a new subtree (in case we are hydrating), this deopts the hydrate\n\t\tisHydrating = false;\n\t}\n\n\tif (nodeType === null) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data !== newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren = excessDomChildren && slice.call(dom.childNodes);\n\n\t\toldProps = oldVNode.props || EMPTY_OBJ;\n\n\t\tlet oldHtml = oldProps.dangerouslySetInnerHTML;\n\t\tlet newHtml = newProps.dangerouslySetInnerHTML;\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tif (!isHydrating) {\n\t\t\t// But, if we are in a situation where we are using existing DOM (e.g. replaceNode)\n\t\t\t// we should read the existing DOM attributes to diff them\n\t\t\tif (excessDomChildren != null) {\n\t\t\t\toldProps = {};\n\t\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\t\toldProps[dom.attributes[i].name] = dom.attributes[i].value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (newHtml || oldHtml) {\n\t\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\t\tif (\n\t\t\t\t\t!newHtml ||\n\t\t\t\t\t((!oldHtml || newHtml.__html != oldHtml.__html) &&\n\t\t\t\t\t\tnewHtml.__html !== dom.innerHTML)\n\t\t\t\t) {\n\t\t\t\t\tdom.innerHTML = (newHtml && newHtml.__html) || '';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdiffProps(dom, newProps, oldProps, isSvg, isHydrating);\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\ti = newVNode.props.children;\n\t\t\tdiffChildren(\n\t\t\t\tdom,\n\t\t\t\tisArray(i) ? i : [i],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tisSvg && nodeType !== 'foreignObject',\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != null) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tif (excessDomChildren[i] != null) removeNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// (as above, don't diff props during hydration)\n\t\tif (!isHydrating) {\n\t\t\tif (\n\t\t\t\t'value' in newProps &&\n\t\t\t\t(i = newProps.value) !== undefined &&\n\t\t\t\t// #2756 For the -element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(i !== dom.value ||\n\t\t\t\t\t(nodeType === 'progress' && !i) ||\n\t\t\t\t\t// This is only for IE 11 to fix \n\tif (\n\t\ttype == 'select' &&\n\t\tnormalizedProps.multiple &&\n\t\tArray.isArray(normalizedProps.value)\n\t) {\n\t\t// forEach() always returns undefined, which we abuse here to unset the value prop.\n\t\tnormalizedProps.value = toChildArray(props.children).forEach(child => {\n\t\t\tchild.props.selected =\n\t\t\t\tnormalizedProps.value.indexOf(child.props.value) != -1;\n\t\t});\n\t}\n\n\t// Adding support for defaultValue in select tag\n\tif (type == 'select' && normalizedProps.defaultValue != null) {\n\t\tnormalizedProps.value = toChildArray(props.children).forEach(child => {\n\t\t\tif (normalizedProps.multiple) {\n\t\t\t\tchild.props.selected =\n\t\t\t\t\tnormalizedProps.defaultValue.indexOf(child.props.value) != -1;\n\t\t\t} else {\n\t\t\t\tchild.props.selected =\n\t\t\t\t\tnormalizedProps.defaultValue == child.props.value;\n\t\t\t}\n\t\t});\n\t}\n\n\tif (props.class && !props.className) {\n\t\tnormalizedProps.class = props.class;\n\t\tObject.defineProperty(\n\t\t\tnormalizedProps,\n\t\t\t'className',\n\t\t\tclassNameDescriptorNonEnumberable\n\t\t);\n\t} else if (props.className && !props.class) {\n\t\tnormalizedProps.class = normalizedProps.className = props.className;\n\t} else if (props.class && props.className) {\n\t\tnormalizedProps.class = normalizedProps.className = props.className;\n\t}\n\n\tvnode.props = normalizedProps;\n}\n\nlet oldVNodeHook = options.vnode;\noptions.vnode = vnode => {\n\t// only normalize props on Element nodes\n\tif (typeof vnode.type === 'string') {\n\t\thandleDomVNode(vnode);\n\t}\n\n\tvnode.$$typeof = REACT_ELEMENT_TYPE;\n\n\tif (oldVNodeHook) oldVNodeHook(vnode);\n};\n\n// Only needed for react-relay\nlet currentComponent;\nconst oldBeforeRender = options._render;\noptions._render = function (vnode) {\n\tif (oldBeforeRender) {\n\t\toldBeforeRender(vnode);\n\t}\n\tcurrentComponent = vnode._component;\n};\n\nconst oldDiffed = options.diffed;\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.diffed = function (vnode) {\n\tif (oldDiffed) {\n\t\toldDiffed(vnode);\n\t}\n\n\tconst props = vnode.props;\n\tconst dom = vnode._dom;\n\n\tif (\n\t\tdom != null &&\n\t\tvnode.type === 'textarea' &&\n\t\t'value' in props &&\n\t\tprops.value !== dom.value\n\t) {\n\t\tdom.value = props.value == null ? '' : props.value;\n\t}\n\n\tcurrentComponent = null;\n};\n\n// This is a very very private internal function for React it\n// is used to sort-of do runtime dependency injection. So far\n// only `react-relay` makes use of it. It uses it to read the\n// context value.\nexport const __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = {\n\tReactCurrentDispatcher: {\n\t\tcurrent: {\n\t\t\treadContext(context) {\n\t\t\t\treturn currentComponent._globalContext[context._id].props.value;\n\t\t\t}\n\t\t}\n\t}\n};\n", "import {\n\tcreateElement,\n\trender as preactRender,\n\tcloneElement as preactCloneElement,\n\tcreateRef,\n\tComponent,\n\tcreateContext,\n\tFragment\n} from 'preact';\nimport {\n\tuseState,\n\tuseId,\n\tuseReducer,\n\tuseEffect,\n\tuseLayoutEffect,\n\tuseRef,\n\tuseImperativeHandle,\n\tuseMemo,\n\tuseCallback,\n\tuseContext,\n\tuseDebugValue\n} from 'preact/hooks';\nimport { PureComponent } from './PureComponent';\nimport { memo } from './memo';\nimport { forwardRef } from './forwardRef';\nimport { Children } from './Children';\nimport { Suspense, lazy } from './suspense';\nimport { SuspenseList } from './suspense-list';\nimport { createPortal } from './portals';\nimport { is } from './util';\nimport {\n\thydrate,\n\trender,\n\tREACT_ELEMENT_TYPE,\n\t__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n} from './render';\n\nconst version = '17.0.2'; // trick libraries to think we are react\n\n/**\n * Legacy version of createElement.\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component constructor\n */\nfunction createFactory(type) {\n\treturn createElement.bind(null, type);\n}\n\n/**\n * Check if the passed element is a valid (p)react node.\n * @param {*} element The element to check\n * @returns {boolean}\n */\nfunction isValidElement(element) {\n\treturn !!element && element.$$typeof === REACT_ELEMENT_TYPE;\n}\n\n/**\n * Wrap `cloneElement` to abort if the passed element is not a valid element and apply\n * all vnode normalizations.\n * @param {import('./internal').VNode} element The vnode to clone\n * @param {object} props Props to add when cloning\n * @param {Array} rest Optional component children\n */\nfunction cloneElement(element) {\n\tif (!isValidElement(element)) return element;\n\treturn preactCloneElement.apply(null, arguments);\n}\n\n/**\n * Remove a component tree from the DOM, including state and event handlers.\n * @param {import('./internal').PreactElement} container\n * @returns {boolean}\n */\nfunction unmountComponentAtNode(container) {\n\tif (container._children) {\n\t\tpreactRender(null, container);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n/**\n * Get the matching DOM node for a component\n * @param {import('./internal').Component} component\n * @returns {import('./internal').PreactElement | null}\n */\nfunction findDOMNode(component) {\n\treturn (\n\t\t(component &&\n\t\t\t(component.base || (component.nodeType === 1 && component))) ||\n\t\tnull\n\t);\n}\n\n/**\n * Deprecated way to control batched rendering inside the reconciler, but we\n * already schedule in batches inside our rendering code\n * @template Arg\n * @param {(arg: Arg) => void} callback function that triggers the updated\n * @param {Arg} [arg] Optional argument that can be passed to the callback\n */\n// eslint-disable-next-line camelcase\nconst unstable_batchedUpdates = (callback, arg) => callback(arg);\n\n/**\n * In React, `flushSync` flushes the entire tree and forces a rerender. It's\n * implmented here as a no-op.\n * @template Arg\n * @template Result\n * @param {(arg: Arg) => Result} callback function that runs before the flush\n * @param {Arg} [arg] Optional argument that can be passed to the callback\n * @returns\n */\nconst flushSync = (callback, arg) => callback(arg);\n\n/**\n * Strict Mode is not implemented in Preact, so we provide a stand-in for it\n * that just renders its children without imposing any restrictions.\n */\nconst StrictMode = Fragment;\n\nexport function startTransition(cb) {\n\tcb();\n}\n\nexport function useDeferredValue(val) {\n\treturn val;\n}\n\nexport function useTransition() {\n\treturn [false, startTransition];\n}\n\n// TODO: in theory this should be done after a VNode is diffed as we want to insert\n// styles/... before it attaches\nexport const useInsertionEffect = useLayoutEffect;\n\n/**\n * This is taken from https://github.com/facebook/react/blob/main/packages/use-sync-external-store/src/useSyncExternalStoreShimClient.js#L84\n * on a high level this cuts out the warnings, ... and attempts a smaller implementation\n */\nexport function useSyncExternalStore(subscribe, getSnapshot) {\n\tconst value = getSnapshot();\n\n\tconst [{ _instance }, forceUpdate] = useState({\n\t\t_instance: { _value: value, _getSnapshot: getSnapshot }\n\t});\n\n\tuseLayoutEffect(() => {\n\t\t_instance._value = value;\n\t\t_instance._getSnapshot = getSnapshot;\n\n\t\tif (!is(_instance._value, getSnapshot())) {\n\t\t\tforceUpdate({ _instance });\n\t\t}\n\t}, [subscribe, value, getSnapshot]);\n\n\tuseEffect(() => {\n\t\tif (!is(_instance._value, _instance._getSnapshot())) {\n\t\t\tforceUpdate({ _instance });\n\t\t}\n\n\t\treturn subscribe(() => {\n\t\t\tif (!is(_instance._value, _instance._getSnapshot())) {\n\t\t\t\tforceUpdate({ _instance });\n\t\t\t}\n\t\t});\n\t}, [subscribe]);\n\n\treturn value;\n}\n\nexport * from 'preact/hooks';\nexport {\n\tversion,\n\tChildren,\n\trender,\n\thydrate,\n\tunmountComponentAtNode,\n\tcreatePortal,\n\tcreateElement,\n\tcreateContext,\n\tcreateFactory,\n\tcloneElement,\n\tcreateRef,\n\tFragment,\n\tisValidElement,\n\tfindDOMNode,\n\tComponent,\n\tPureComponent,\n\tmemo,\n\tforwardRef,\n\tflushSync,\n\t// eslint-disable-next-line camelcase\n\tunstable_batchedUpdates,\n\tStrictMode,\n\tSuspense,\n\tSuspenseList,\n\tlazy,\n\t__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n};\n\n// React copies the named exports to the default one.\nexport default {\n\tuseState,\n\tuseId,\n\tuseReducer,\n\tuseEffect,\n\tuseLayoutEffect,\n\tuseInsertionEffect,\n\tuseTransition,\n\tuseDeferredValue,\n\tuseSyncExternalStore,\n\tstartTransition,\n\tuseRef,\n\tuseImperativeHandle,\n\tuseMemo,\n\tuseCallback,\n\tuseContext,\n\tuseDebugValue,\n\tversion,\n\tChildren,\n\trender,\n\thydrate,\n\tunmountComponentAtNode,\n\tcreatePortal,\n\tcreateElement,\n\tcreateContext,\n\tcreateFactory,\n\tcloneElement,\n\tcreateRef,\n\tFragment,\n\tisValidElement,\n\tfindDOMNode,\n\tComponent,\n\tPureComponent,\n\tmemo,\n\tforwardRef,\n\tflushSync,\n\tunstable_batchedUpdates,\n\tStrictMode,\n\tSuspense,\n\tSuspenseList,\n\tlazy,\n\t__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n};\n", "import { TableState, Updater } from './types'\n\nexport type PartialKeys = Omit & Partial>\nexport type RequiredKeys = Omit &\n Required>\nexport type Overwrite = Omit<\n T,\n keyof U\n> &\n U\n\nexport type UnionToIntersection = (\n T extends any ? (x: T) => any : never\n) extends (x: infer R) => any\n ? R\n : never\n\nexport type IsAny = 1 extends 0 & T ? Y : N\nexport type IsKnown = unknown extends T ? N : Y\n\ntype ComputeRange<\n N extends number,\n Result extends Array = []\n> = Result['length'] extends N\n ? Result\n : ComputeRange\ntype Index40 = ComputeRange<40>[number]\n\n// Is this type a tuple?\ntype IsTuple = T extends readonly any[] & { length: infer Length }\n ? Length extends Index40\n ? T\n : never\n : never\n\n// If this type is a tuple, what indices are allowed?\ntype AllowedIndexes<\n Tuple extends ReadonlyArray,\n Keys extends number = never\n> = Tuple extends readonly []\n ? Keys\n : Tuple extends readonly [infer _, ...infer Tail]\n ? AllowedIndexes\n : Keys\n\nexport type DeepKeys = unknown extends T\n ? keyof T\n : object extends T\n ? string\n : T extends readonly any[] & IsTuple\n ? AllowedIndexes | DeepKeysPrefix>\n : T extends any[]\n ? never & 'Dynamic length array indexing is not supported'\n : T extends Date\n ? never\n : T extends object\n ? (keyof T & string) | DeepKeysPrefix\n : never\n\ntype DeepKeysPrefix = TPrefix extends keyof T & (number | string)\n ? `${TPrefix}.${DeepKeys & string}`\n : never\n\nexport type DeepValue = T extends Record\n ? TProp extends `${infer TBranch}.${infer TDeepProp}`\n ? DeepValue\n : T[TProp & string]\n : never\n\nexport type NoInfer = [T][T extends any ? 0 : never]\n\nexport type Getter = () => NoInfer\n\n///\n\nexport function functionalUpdate(updater: Updater, input: T): T {\n return typeof updater === 'function'\n ? (updater as (input: T) => T)(input)\n : updater\n}\n\nexport function noop() {\n //\n}\n\nexport function makeStateUpdater(\n key: K,\n instance: unknown\n) {\n return (updater: Updater) => {\n ;(instance as any).setState((old: TTableState) => {\n return {\n ...old,\n [key]: functionalUpdate(updater, (old as any)[key]),\n }\n })\n }\n}\n\ntype AnyFunction = (...args: any) => any\n\nexport function isFunction(d: any): d is T {\n return d instanceof Function\n}\n\nexport function isNumberArray(d: any): d is number[] {\n return Array.isArray(d) && d.every(val => typeof val === 'number')\n}\n\nexport function flattenBy(\n arr: TNode[],\n getChildren: (item: TNode) => TNode[]\n) {\n const flat: TNode[] = []\n\n const recurse = (subArr: TNode[]) => {\n subArr.forEach(item => {\n flat.push(item)\n const children = getChildren(item)\n if (children?.length) {\n recurse(children)\n }\n })\n }\n\n recurse(arr)\n\n return flat\n}\n\nexport function memo(\n getDeps: () => [...TDeps],\n fn: (...args: NoInfer<[...TDeps]>) => TResult,\n opts: {\n key: any\n debug?: () => any\n onChange?: (result: TResult) => void\n }\n): () => TResult {\n let deps: any[] = []\n let result: TResult | undefined\n\n return () => {\n let depTime: number\n if (opts.key && opts.debug) depTime = Date.now()\n\n const newDeps = getDeps()\n\n const depsChanged =\n newDeps.length !== deps.length ||\n newDeps.some((dep: any, index: number) => deps[index] !== dep)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n let resultTime: number\n if (opts.key && opts.debug) resultTime = Date.now()\n\n result = fn(...newDeps)\n opts?.onChange?.(result)\n\n if (opts.key && opts.debug) {\n if (opts?.debug()) {\n const depEndTime = Math.round((Date.now() - depTime!) * 100) / 100\n const resultEndTime = Math.round((Date.now() - resultTime!) * 100) / 100\n const resultFpsPercentage = resultEndTime / 16\n\n const pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n }\n\n console.info(\n `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,\n `\n font-size: .6rem;\n font-weight: bold;\n color: hsl(${Math.max(\n 0,\n Math.min(120 - 120 * resultFpsPercentage, 120)\n )}deg 100% 31%);`,\n opts?.key\n )\n }\n }\n\n return result!\n }\n}\n", "import {\n Column,\n Table,\n AccessorFn,\n ColumnDef,\n RowData,\n ColumnDefResolved,\n} from '../types'\nimport { memo } from '../utils'\n\nexport interface CoreColumn {\n id: string\n depth: number\n accessorFn?: AccessorFn\n columnDef: ColumnDef\n columns: Column[]\n parent?: Column\n getFlatColumns: () => Column[]\n getLeafColumns: () => Column[]\n}\n\nexport function createColumn(\n table: Table,\n columnDef: ColumnDef,\n depth: number,\n parent?: Column\n): Column {\n const defaultColumn = table._getDefaultColumnDef()\n\n const resolvedColumnDef = {\n ...defaultColumn,\n ...columnDef,\n } as ColumnDefResolved\n\n const accessorKey = resolvedColumnDef.accessorKey\n\n let id =\n resolvedColumnDef.id ??\n (accessorKey ? accessorKey.replace('.', '_') : undefined) ??\n (typeof resolvedColumnDef.header === 'string'\n ? resolvedColumnDef.header\n : undefined)\n\n let accessorFn: AccessorFn | undefined\n\n if (resolvedColumnDef.accessorFn) {\n accessorFn = resolvedColumnDef.accessorFn\n } else if (accessorKey) {\n // Support deep accessor keys\n if (accessorKey.includes('.')) {\n accessorFn = (originalRow: TData) => {\n let result = originalRow as Record\n\n for (const key of accessorKey.split('.')) {\n result = result?.[key]\n if (process.env.NODE_ENV !== 'production' && result === undefined) {\n console.warn(\n `\"${key}\" in deeply nested key \"${accessorKey}\" returned undefined.`\n )\n }\n }\n\n return result\n }\n } else {\n accessorFn = (originalRow: TData) =>\n (originalRow as any)[resolvedColumnDef.accessorKey]\n }\n }\n\n if (!id) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n resolvedColumnDef.accessorFn\n ? `Columns require an id when using an accessorFn`\n : `Columns require an id when using a non-string header`\n )\n }\n throw new Error()\n }\n\n let column: CoreColumn = {\n id: `${String(id)}`,\n accessorFn,\n parent: parent as any,\n depth,\n columnDef: resolvedColumnDef as ColumnDef,\n columns: [],\n getFlatColumns: memo(\n () => [true],\n () => {\n return [\n column as Column,\n ...column.columns?.flatMap(d => d.getFlatColumns()),\n ]\n },\n {\n key: process.env.NODE_ENV === 'production' && 'column.getFlatColumns',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n getLeafColumns: memo(\n () => [table._getOrderColumnsFn()],\n orderColumns => {\n if (column.columns?.length) {\n let leafColumns = column.columns.flatMap(column =>\n column.getLeafColumns()\n )\n\n return orderColumns(leafColumns)\n }\n\n return [column as Column]\n },\n {\n key: process.env.NODE_ENV === 'production' && 'column.getLeafColumns',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n }\n\n column = table._features.reduce((obj, feature) => {\n return Object.assign(obj, feature.createColumn?.(column, table))\n }, column)\n\n // Yes, we have to convert table to uknown, because we know more than the compiler here.\n return column as Column\n}\n", "import { RowData, Column, Header, HeaderGroup, Table } from '../types'\nimport { memo } from '../utils'\nimport { TableFeature } from './table'\n\nexport interface CoreHeaderGroup {\n id: string\n depth: number\n headers: Header[]\n}\n\nexport interface HeaderContext {\n table: Table\n header: Header\n column: Column\n}\n\nexport interface CoreHeader {\n id: string\n index: number\n depth: number\n column: Column\n headerGroup: HeaderGroup\n subHeaders: Header[]\n colSpan: number\n rowSpan: number\n getLeafHeaders: () => Header[]\n isPlaceholder: boolean\n placeholderId?: string\n getContext: () => HeaderContext\n}\n\nexport interface HeadersInstance {\n getHeaderGroups: () => HeaderGroup[]\n getLeftHeaderGroups: () => HeaderGroup[]\n getCenterHeaderGroups: () => HeaderGroup[]\n getRightHeaderGroups: () => HeaderGroup[]\n\n getFooterGroups: () => HeaderGroup[]\n getLeftFooterGroups: () => HeaderGroup[]\n getCenterFooterGroups: () => HeaderGroup[]\n getRightFooterGroups: () => HeaderGroup[]\n\n getFlatHeaders: () => Header[]\n getLeftFlatHeaders: () => Header[]\n getCenterFlatHeaders: () => Header[]\n getRightFlatHeaders: () => Header[]\n\n getLeafHeaders: () => Header[]\n getLeftLeafHeaders: () => Header[]\n getCenterLeafHeaders: () => Header[]\n getRightLeafHeaders: () => Header[]\n}\n\n//\n\nfunction createHeader(\n table: Table,\n column: Column,\n options: {\n id?: string\n isPlaceholder?: boolean\n placeholderId?: string\n index: number\n depth: number\n }\n): Header {\n const id = options.id ?? column.id\n\n let header: CoreHeader = {\n id,\n column,\n index: options.index,\n isPlaceholder: !!options.isPlaceholder,\n placeholderId: options.placeholderId,\n depth: options.depth,\n subHeaders: [],\n colSpan: 0,\n rowSpan: 0,\n headerGroup: null!,\n getLeafHeaders: (): Header[] => {\n const leafHeaders: Header[] = []\n\n const recurseHeader = (h: CoreHeader) => {\n if (h.subHeaders && h.subHeaders.length) {\n h.subHeaders.map(recurseHeader)\n }\n leafHeaders.push(h as Header)\n }\n\n recurseHeader(header)\n\n return leafHeaders\n },\n getContext: () => ({\n table,\n header: header as Header,\n column,\n }),\n }\n\n table._features.forEach(feature => {\n Object.assign(header, feature.createHeader?.(header, table))\n })\n\n return header as Header\n}\n\nexport const Headers: TableFeature = {\n createTable: (\n table: Table\n ): HeadersInstance => {\n return {\n // Header Groups\n\n getHeaderGroups: memo(\n () => [\n table.getAllColumns(),\n table.getVisibleLeafColumns(),\n table.getState().columnPinning.left,\n table.getState().columnPinning.right,\n ],\n (allColumns, leafColumns, left, right) => {\n const leftColumns =\n left\n ?.map(columnId => leafColumns.find(d => d.id === columnId)!)\n .filter(Boolean) ?? []\n\n const rightColumns =\n right\n ?.map(columnId => leafColumns.find(d => d.id === columnId)!)\n .filter(Boolean) ?? []\n\n const centerColumns = leafColumns.filter(\n column => !left?.includes(column.id) && !right?.includes(column.id)\n )\n\n const headerGroups = buildHeaderGroups(\n allColumns,\n [...leftColumns, ...centerColumns, ...rightColumns],\n table\n )\n\n return headerGroups\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getHeaderGroups',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getCenterHeaderGroups: memo(\n () => [\n table.getAllColumns(),\n table.getVisibleLeafColumns(),\n table.getState().columnPinning.left,\n table.getState().columnPinning.right,\n ],\n (allColumns, leafColumns, left, right) => {\n leafColumns = leafColumns.filter(\n column => !left?.includes(column.id) && !right?.includes(column.id)\n )\n return buildHeaderGroups(allColumns, leafColumns, table, 'center')\n },\n {\n key:\n process.env.NODE_ENV === 'development' && 'getCenterHeaderGroups',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getLeftHeaderGroups: memo(\n () => [\n table.getAllColumns(),\n table.getVisibleLeafColumns(),\n table.getState().columnPinning.left,\n ],\n (allColumns, leafColumns, left) => {\n const orderedLeafColumns =\n left\n ?.map(columnId => leafColumns.find(d => d.id === columnId)!)\n .filter(Boolean) ?? []\n\n return buildHeaderGroups(\n allColumns,\n orderedLeafColumns,\n table,\n 'left'\n )\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getLeftHeaderGroups',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getRightHeaderGroups: memo(\n () => [\n table.getAllColumns(),\n table.getVisibleLeafColumns(),\n table.getState().columnPinning.right,\n ],\n (allColumns, leafColumns, right) => {\n const orderedLeafColumns =\n right\n ?.map(columnId => leafColumns.find(d => d.id === columnId)!)\n .filter(Boolean) ?? []\n\n return buildHeaderGroups(\n allColumns,\n orderedLeafColumns,\n table,\n 'right'\n )\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getRightHeaderGroups',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n // Footer Groups\n\n getFooterGroups: memo(\n () => [table.getHeaderGroups()],\n headerGroups => {\n return [...headerGroups].reverse()\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getFooterGroups',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getLeftFooterGroups: memo(\n () => [table.getLeftHeaderGroups()],\n headerGroups => {\n return [...headerGroups].reverse()\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getLeftFooterGroups',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getCenterFooterGroups: memo(\n () => [table.getCenterHeaderGroups()],\n headerGroups => {\n return [...headerGroups].reverse()\n },\n {\n key:\n process.env.NODE_ENV === 'development' && 'getCenterFooterGroups',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getRightFooterGroups: memo(\n () => [table.getRightHeaderGroups()],\n headerGroups => {\n return [...headerGroups].reverse()\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getRightFooterGroups',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n // Flat Headers\n\n getFlatHeaders: memo(\n () => [table.getHeaderGroups()],\n headerGroups => {\n return headerGroups\n .map(headerGroup => {\n return headerGroup.headers\n })\n .flat()\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getFlatHeaders',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getLeftFlatHeaders: memo(\n () => [table.getLeftHeaderGroups()],\n left => {\n return left\n .map(headerGroup => {\n return headerGroup.headers\n })\n .flat()\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getLeftFlatHeaders',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getCenterFlatHeaders: memo(\n () => [table.getCenterHeaderGroups()],\n left => {\n return left\n .map(headerGroup => {\n return headerGroup.headers\n })\n .flat()\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getCenterFlatHeaders',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getRightFlatHeaders: memo(\n () => [table.getRightHeaderGroups()],\n left => {\n return left\n .map(headerGroup => {\n return headerGroup.headers\n })\n .flat()\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getRightFlatHeaders',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n // Leaf Headers\n\n getCenterLeafHeaders: memo(\n () => [table.getCenterFlatHeaders()],\n flatHeaders => {\n return flatHeaders.filter(header => !header.subHeaders?.length)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getCenterLeafHeaders',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getLeftLeafHeaders: memo(\n () => [table.getLeftFlatHeaders()],\n flatHeaders => {\n return flatHeaders.filter(header => !header.subHeaders?.length)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getLeftLeafHeaders',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getRightLeafHeaders: memo(\n () => [table.getRightFlatHeaders()],\n flatHeaders => {\n return flatHeaders.filter(header => !header.subHeaders?.length)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getRightLeafHeaders',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n\n getLeafHeaders: memo(\n () => [\n table.getLeftHeaderGroups(),\n table.getCenterHeaderGroups(),\n table.getRightHeaderGroups(),\n ],\n (left, center, right) => {\n return [\n ...(left[0]?.headers ?? []),\n ...(center[0]?.headers ?? []),\n ...(right[0]?.headers ?? []),\n ]\n .map(header => {\n return header.getLeafHeaders()\n })\n .flat()\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getLeafHeaders',\n debug: () => table.options.debugAll ?? table.options.debugHeaders,\n }\n ),\n }\n },\n}\n\nexport function buildHeaderGroups(\n allColumns: Column[],\n columnsToGroup: Column[],\n table: Table,\n headerFamily?: 'center' | 'left' | 'right'\n) {\n // Find the max depth of the columns:\n // build the leaf column row\n // build each buffer row going up\n // placeholder for non-existent level\n // real column for existing level\n\n let maxDepth = 0\n\n const findMaxDepth = (columns: Column[], depth = 1) => {\n maxDepth = Math.max(maxDepth, depth)\n\n columns\n .filter(column => column.getIsVisible())\n .forEach(column => {\n if (column.columns?.length) {\n findMaxDepth(column.columns, depth + 1)\n }\n }, 0)\n }\n\n findMaxDepth(allColumns)\n\n let headerGroups: HeaderGroup[] = []\n\n const createHeaderGroup = (\n headersToGroup: Header[],\n depth: number\n ) => {\n // The header group we are creating\n const headerGroup: HeaderGroup = {\n depth,\n id: [headerFamily, `${depth}`].filter(Boolean).join('_'),\n headers: [],\n }\n\n // The parent columns we're going to scan next\n const pendingParentHeaders: Header[] = []\n\n // Scan each column for parents\n headersToGroup.forEach(headerToGroup => {\n // What is the latest (last) parent column?\n\n const latestPendingParentHeader = [...pendingParentHeaders].reverse()[0]\n\n const isLeafHeader = headerToGroup.column.depth === headerGroup.depth\n\n let column: Column\n let isPlaceholder = false\n\n if (isLeafHeader && headerToGroup.column.parent) {\n // The parent header is new\n column = headerToGroup.column.parent\n } else {\n // The parent header is repeated\n column = headerToGroup.column\n isPlaceholder = true\n }\n\n if (\n latestPendingParentHeader &&\n latestPendingParentHeader?.column === column\n ) {\n // This column is repeated. Add it as a sub header to the next batch\n latestPendingParentHeader.subHeaders.push(headerToGroup)\n } else {\n // This is a new header. Let's create it\n const header = createHeader(table, column, {\n id: [headerFamily, depth, column.id, headerToGroup?.id]\n .filter(Boolean)\n .join('_'),\n isPlaceholder,\n placeholderId: isPlaceholder\n ? `${pendingParentHeaders.filter(d => d.column === column).length}`\n : undefined,\n depth,\n index: pendingParentHeaders.length,\n })\n\n // Add the headerToGroup as a subHeader of the new header\n header.subHeaders.push(headerToGroup)\n // Add the new header to the pendingParentHeaders to get grouped\n // in the next batch\n pendingParentHeaders.push(header)\n }\n\n headerGroup.headers.push(headerToGroup)\n headerToGroup.headerGroup = headerGroup\n })\n\n headerGroups.push(headerGroup)\n\n if (depth > 0) {\n createHeaderGroup(pendingParentHeaders, depth - 1)\n }\n }\n\n const bottomHeaders = columnsToGroup.map((column, index) =>\n createHeader(table, column, {\n depth: maxDepth,\n index,\n })\n )\n\n createHeaderGroup(bottomHeaders, maxDepth - 1)\n\n headerGroups.reverse()\n\n // headerGroups = headerGroups.filter(headerGroup => {\n // return !headerGroup.headers.every(header => header.isPlaceholder)\n // })\n\n const recurseHeadersForSpans = (\n headers: Header[]\n ): { colSpan: number; rowSpan: number }[] => {\n const filteredHeaders = headers.filter(header =>\n header.column.getIsVisible()\n )\n\n return filteredHeaders.map(header => {\n let colSpan = 0\n let rowSpan = 0\n let childRowSpans = [0]\n\n if (header.subHeaders && header.subHeaders.length) {\n childRowSpans = []\n\n recurseHeadersForSpans(header.subHeaders).forEach(\n ({ colSpan: childColSpan, rowSpan: childRowSpan }) => {\n colSpan += childColSpan\n childRowSpans.push(childRowSpan)\n }\n )\n } else {\n colSpan = 1\n }\n\n const minChildRowSpan = Math.min(...childRowSpans)\n rowSpan = rowSpan + minChildRowSpan\n\n header.colSpan = colSpan\n header.rowSpan = rowSpan\n\n return { colSpan, rowSpan }\n })\n }\n\n recurseHeadersForSpans(headerGroups[0]?.headers ?? [])\n\n return headerGroups\n}\n", "import { TableFeature } from '../core/table'\nimport { RowData, Column, Header, OnChangeFn, Table, Updater } from '../types'\nimport { makeStateUpdater } from '../utils'\nimport { ColumnPinningPosition } from './Pinning'\n\n//\n\nexport interface ColumnSizingTableState {\n columnSizing: ColumnSizingState\n columnSizingInfo: ColumnSizingInfoState\n}\n\nexport type ColumnSizingState = Record\n\nexport interface ColumnSizingInfoState {\n startOffset: null | number\n startSize: null | number\n deltaOffset: null | number\n deltaPercentage: null | number\n isResizingColumn: false | string\n columnSizingStart: [string, number][]\n}\n\nexport type ColumnResizeMode = 'onChange' | 'onEnd'\n\nexport interface ColumnSizingOptions {\n enableColumnResizing?: boolean\n columnResizeMode?: ColumnResizeMode\n onColumnSizingChange?: OnChangeFn\n onColumnSizingInfoChange?: OnChangeFn\n}\n\nexport interface ColumnSizingDefaultOptions {\n columnResizeMode: ColumnResizeMode\n onColumnSizingChange: OnChangeFn\n onColumnSizingInfoChange: OnChangeFn\n}\n\nexport interface ColumnSizingInstance {\n setColumnSizing: (updater: Updater) => void\n setColumnSizingInfo: (updater: Updater) => void\n resetColumnSizing: (defaultState?: boolean) => void\n resetHeaderSizeInfo: (defaultState?: boolean) => void\n getTotalSize: () => number\n getLeftTotalSize: () => number\n getCenterTotalSize: () => number\n getRightTotalSize: () => number\n}\n\nexport interface ColumnSizingColumnDef {\n enableResizing?: boolean\n size?: number\n minSize?: number\n maxSize?: number\n}\n\nexport interface ColumnSizingColumn {\n getSize: () => number\n getStart: (position?: ColumnPinningPosition) => number\n getCanResize: () => boolean\n getIsResizing: () => boolean\n resetSize: () => void\n}\n\nexport interface ColumnSizingHeader {\n getSize: () => number\n getStart: (position?: ColumnPinningPosition) => number\n getResizeHandler: () => (event: unknown) => void\n}\n\n//\n\nexport const defaultColumnSizing = {\n size: 150,\n minSize: 20,\n maxSize: Number.MAX_SAFE_INTEGER,\n}\n\nconst getDefaultColumnSizingInfoState = (): ColumnSizingInfoState => ({\n startOffset: null,\n startSize: null,\n deltaOffset: null,\n deltaPercentage: null,\n isResizingColumn: false,\n columnSizingStart: [],\n})\n\nexport const ColumnSizing: TableFeature = {\n getDefaultColumnDef: (): ColumnSizingColumnDef => {\n return defaultColumnSizing\n },\n getInitialState: (state): ColumnSizingTableState => {\n return {\n columnSizing: {},\n columnSizingInfo: getDefaultColumnSizingInfoState(),\n ...state,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): ColumnSizingDefaultOptions => {\n return {\n columnResizeMode: 'onEnd',\n onColumnSizingChange: makeStateUpdater('columnSizing', table),\n onColumnSizingInfoChange: makeStateUpdater('columnSizingInfo', table),\n }\n },\n\n createColumn: (\n column: Column,\n table: Table\n ): ColumnSizingColumn => {\n return {\n getSize: () => {\n const columnSize = table.getState().columnSizing[column.id]\n\n return Math.min(\n Math.max(\n column.columnDef.minSize ?? defaultColumnSizing.minSize,\n columnSize ?? column.columnDef.size ?? defaultColumnSizing.size\n ),\n column.columnDef.maxSize ?? defaultColumnSizing.maxSize\n )\n },\n getStart: position => {\n const columns = !position\n ? table.getVisibleLeafColumns()\n : position === 'left'\n ? table.getLeftVisibleLeafColumns()\n : table.getRightVisibleLeafColumns()\n\n const index = columns.findIndex(d => d.id === column.id)\n\n if (index > 0) {\n const prevSiblingColumn = columns[index - 1]!\n\n return (\n prevSiblingColumn.getStart(position) + prevSiblingColumn.getSize()\n )\n }\n\n return 0\n },\n resetSize: () => {\n table.setColumnSizing(({ [column.id]: _, ...rest }) => {\n return rest\n })\n },\n getCanResize: () => {\n return (\n (column.columnDef.enableResizing ?? true) &&\n (table.options.enableColumnResizing ?? true)\n )\n },\n getIsResizing: () => {\n return table.getState().columnSizingInfo.isResizingColumn === column.id\n },\n }\n },\n\n createHeader: (\n header: Header,\n table: Table\n ): ColumnSizingHeader => {\n return {\n getSize: () => {\n let sum = 0\n\n const recurse = (header: Header) => {\n if (header.subHeaders.length) {\n header.subHeaders.forEach(recurse)\n } else {\n sum += header.column.getSize() ?? 0\n }\n }\n\n recurse(header)\n\n return sum\n },\n getStart: () => {\n if (header.index > 0) {\n const prevSiblingHeader =\n header.headerGroup.headers[header.index - 1]!\n return prevSiblingHeader.getStart() + prevSiblingHeader.getSize()\n }\n\n return 0\n },\n getResizeHandler: () => {\n const column = table.getColumn(header.column.id)\n const canResize = column?.getCanResize()\n\n return (e: unknown) => {\n if (!column || !canResize) {\n return\n }\n\n ;(e as any).persist?.()\n\n if (isTouchStartEvent(e)) {\n // lets not respond to multiple touches (e.g. 2 or 3 fingers)\n if (e.touches && e.touches.length > 1) {\n return\n }\n }\n\n const startSize = header.getSize()\n\n const columnSizingStart: [string, number][] = header\n ? header\n .getLeafHeaders()\n .map(d => [d.column.id, d.column.getSize()])\n : [[column.id, column.getSize()]]\n\n const clientX = isTouchStartEvent(e)\n ? Math.round(e.touches[0]!.clientX)\n : (e as MouseEvent).clientX\n\n const newColumnSizing: ColumnSizingState = {}\n\n const updateOffset = (\n eventType: 'move' | 'end',\n clientXPos?: number\n ) => {\n if (typeof clientXPos !== 'number') {\n return\n }\n\n table.setColumnSizingInfo(old => {\n const deltaOffset = clientXPos - (old?.startOffset ?? 0)\n const deltaPercentage = Math.max(\n deltaOffset / (old?.startSize ?? 0),\n -0.999999\n )\n\n old.columnSizingStart.forEach(([columnId, headerSize]) => {\n newColumnSizing[columnId] =\n Math.round(\n Math.max(headerSize + headerSize * deltaPercentage, 0) * 100\n ) / 100\n })\n\n return {\n ...old,\n deltaOffset,\n deltaPercentage,\n }\n })\n\n if (\n table.options.columnResizeMode === 'onChange' ||\n eventType === 'end'\n ) {\n table.setColumnSizing(old => ({\n ...old,\n ...newColumnSizing,\n }))\n }\n }\n\n const onMove = (clientXPos?: number) =>\n updateOffset('move', clientXPos)\n\n const onEnd = (clientXPos?: number) => {\n updateOffset('end', clientXPos)\n\n table.setColumnSizingInfo(old => ({\n ...old,\n isResizingColumn: false,\n startOffset: null,\n startSize: null,\n deltaOffset: null,\n deltaPercentage: null,\n columnSizingStart: [],\n }))\n }\n\n const mouseEvents = {\n moveHandler: (e: MouseEvent) => onMove(e.clientX),\n upHandler: (e: MouseEvent) => {\n document.removeEventListener('mousemove', mouseEvents.moveHandler)\n document.removeEventListener('mouseup', mouseEvents.upHandler)\n onEnd(e.clientX)\n },\n }\n\n const touchEvents = {\n moveHandler: (e: TouchEvent) => {\n if (e.cancelable) {\n e.preventDefault()\n e.stopPropagation()\n }\n onMove(e.touches[0]!.clientX)\n return false\n },\n upHandler: (e: TouchEvent) => {\n document.removeEventListener('touchmove', touchEvents.moveHandler)\n document.removeEventListener('touchend', touchEvents.upHandler)\n if (e.cancelable) {\n e.preventDefault()\n e.stopPropagation()\n }\n onEnd(e.touches[0]?.clientX)\n },\n }\n\n const passiveIfSupported = passiveEventSupported()\n ? { passive: false }\n : false\n\n if (isTouchStartEvent(e)) {\n document.addEventListener(\n 'touchmove',\n touchEvents.moveHandler,\n passiveIfSupported\n )\n document.addEventListener(\n 'touchend',\n touchEvents.upHandler,\n passiveIfSupported\n )\n } else {\n document.addEventListener(\n 'mousemove',\n mouseEvents.moveHandler,\n passiveIfSupported\n )\n document.addEventListener(\n 'mouseup',\n mouseEvents.upHandler,\n passiveIfSupported\n )\n }\n\n table.setColumnSizingInfo(old => ({\n ...old,\n startOffset: clientX,\n startSize,\n deltaOffset: 0,\n deltaPercentage: 0,\n columnSizingStart,\n isResizingColumn: column.id,\n }))\n }\n },\n }\n },\n\n createTable: (\n table: Table\n ): ColumnSizingInstance => {\n return {\n setColumnSizing: updater => table.options.onColumnSizingChange?.(updater),\n setColumnSizingInfo: updater =>\n table.options.onColumnSizingInfoChange?.(updater),\n resetColumnSizing: defaultState => {\n table.setColumnSizing(\n defaultState ? {} : table.initialState.columnSizing ?? {}\n )\n },\n resetHeaderSizeInfo: defaultState => {\n table.setColumnSizingInfo(\n defaultState\n ? getDefaultColumnSizingInfoState()\n : table.initialState.columnSizingInfo ??\n getDefaultColumnSizingInfoState()\n )\n },\n getTotalSize: () =>\n table.getHeaderGroups()[0]?.headers.reduce((sum, header) => {\n return sum + header.getSize()\n }, 0) ?? 0,\n getLeftTotalSize: () =>\n table.getLeftHeaderGroups()[0]?.headers.reduce((sum, header) => {\n return sum + header.getSize()\n }, 0) ?? 0,\n getCenterTotalSize: () =>\n table.getCenterHeaderGroups()[0]?.headers.reduce((sum, header) => {\n return sum + header.getSize()\n }, 0) ?? 0,\n getRightTotalSize: () =>\n table.getRightHeaderGroups()[0]?.headers.reduce((sum, header) => {\n return sum + header.getSize()\n }, 0) ?? 0,\n }\n },\n}\n\nlet passiveSupported: boolean | null = null\nexport function passiveEventSupported() {\n if (typeof passiveSupported === 'boolean') return passiveSupported\n\n let supported = false\n try {\n const options = {\n get passive() {\n supported = true\n return false\n },\n }\n\n const noop = () => {}\n\n window.addEventListener('test', noop, options)\n window.removeEventListener('test', noop)\n } catch (err) {\n supported = false\n }\n passiveSupported = supported\n return passiveSupported\n}\n\nfunction isTouchStartEvent(e: unknown): e is TouchEvent {\n return (e as TouchEvent).type === 'touchstart'\n}\n", "import { RowModel } from '..'\nimport { TableFeature } from '../core/table'\nimport { OnChangeFn, Table, Row, Updater, RowData } from '../types'\nimport { makeStateUpdater } from '../utils'\n\nexport type ExpandedStateList = Record\nexport type ExpandedState = true | Record\nexport interface ExpandedTableState {\n expanded: ExpandedState\n}\n\nexport interface ExpandedRow {\n toggleExpanded: (expanded?: boolean) => void\n getIsExpanded: () => boolean\n getCanExpand: () => boolean\n getToggleExpandedHandler: () => () => void\n}\n\nexport interface ExpandedOptions {\n manualExpanding?: boolean\n onExpandedChange?: OnChangeFn\n autoResetExpanded?: boolean\n enableExpanding?: boolean\n getExpandedRowModel?: (table: Table) => () => RowModel\n getIsRowExpanded?: (row: Row) => boolean\n getRowCanExpand?: (row: Row) => boolean\n paginateExpandedRows?: boolean\n}\n\nexport interface ExpandedInstance {\n _autoResetExpanded: () => void\n setExpanded: (updater: Updater) => void\n toggleAllRowsExpanded: (expanded?: boolean) => void\n resetExpanded: (defaultState?: boolean) => void\n getCanSomeRowsExpand: () => boolean\n getToggleAllRowsExpandedHandler: () => (event: unknown) => void\n getIsSomeRowsExpanded: () => boolean\n getIsAllRowsExpanded: () => boolean\n getExpandedDepth: () => number\n getExpandedRowModel: () => RowModel\n _getExpandedRowModel?: () => RowModel\n getPreExpandedRowModel: () => RowModel\n}\n\n//\n\nexport const Expanding: TableFeature = {\n getInitialState: (state): ExpandedTableState => {\n return {\n expanded: {},\n ...state,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): ExpandedOptions => {\n return {\n onExpandedChange: makeStateUpdater('expanded', table),\n paginateExpandedRows: true,\n }\n },\n\n createTable: (\n table: Table\n ): ExpandedInstance => {\n let registered = false\n let queued = false\n\n return {\n _autoResetExpanded: () => {\n if (!registered) {\n table._queue(() => {\n registered = true\n })\n return\n }\n\n if (\n table.options.autoResetAll ??\n table.options.autoResetExpanded ??\n !table.options.manualExpanding\n ) {\n if (queued) return\n queued = true\n table._queue(() => {\n table.resetExpanded()\n queued = false\n })\n }\n },\n setExpanded: updater => table.options.onExpandedChange?.(updater),\n toggleAllRowsExpanded: expanded => {\n if (expanded ?? !table.getIsAllRowsExpanded()) {\n table.setExpanded(true)\n } else {\n table.setExpanded({})\n }\n },\n resetExpanded: defaultState => {\n table.setExpanded(\n defaultState ? {} : table.initialState?.expanded ?? {}\n )\n },\n getCanSomeRowsExpand: () => {\n return table\n .getPrePaginationRowModel()\n .flatRows.some(row => row.getCanExpand())\n },\n getToggleAllRowsExpandedHandler: () => {\n return (e: unknown) => {\n ;(e as any).persist?.()\n table.toggleAllRowsExpanded()\n }\n },\n getIsSomeRowsExpanded: () => {\n const expanded = table.getState().expanded\n return expanded === true || Object.values(expanded).some(Boolean)\n },\n getIsAllRowsExpanded: () => {\n const expanded = table.getState().expanded\n\n // If expanded is true, save some cycles and return true\n if (typeof expanded === 'boolean') {\n return expanded === true\n }\n\n if (!Object.keys(expanded).length) {\n return false\n }\n\n // If any row is not expanded, return false\n if (table.getRowModel().flatRows.some(row => !row.getIsExpanded())) {\n return false\n }\n\n // They must all be expanded :shrug:\n return true\n },\n getExpandedDepth: () => {\n let maxDepth = 0\n\n const rowIds =\n table.getState().expanded === true\n ? Object.keys(table.getRowModel().rowsById)\n : Object.keys(table.getState().expanded)\n\n rowIds.forEach(id => {\n const splitId = id.split('.')\n maxDepth = Math.max(maxDepth, splitId.length)\n })\n\n return maxDepth\n },\n getPreExpandedRowModel: () => table.getSortedRowModel(),\n getExpandedRowModel: () => {\n if (!table._getExpandedRowModel && table.options.getExpandedRowModel) {\n table._getExpandedRowModel = table.options.getExpandedRowModel(table)\n }\n\n if (table.options.manualExpanding || !table._getExpandedRowModel) {\n return table.getPreExpandedRowModel()\n }\n\n return table._getExpandedRowModel()\n },\n }\n },\n\n createRow: (\n row: Row,\n table: Table\n ): ExpandedRow => {\n return {\n toggleExpanded: expanded => {\n table.setExpanded(old => {\n const exists = old === true ? true : !!old?.[row.id]\n\n let oldExpanded: ExpandedStateList = {}\n\n if (old === true) {\n Object.keys(table.getRowModel().rowsById).forEach(rowId => {\n oldExpanded[rowId] = true\n })\n } else {\n oldExpanded = old\n }\n\n expanded = expanded ?? !exists\n\n if (!exists && expanded) {\n return {\n ...oldExpanded,\n [row.id]: true,\n }\n }\n\n if (exists && !expanded) {\n const { [row.id]: _, ...rest } = oldExpanded\n return rest\n }\n\n return old\n })\n },\n getIsExpanded: () => {\n const expanded = table.getState().expanded\n\n return !!(\n table.options.getIsRowExpanded?.(row) ??\n (expanded === true || expanded?.[row.id])\n )\n },\n getCanExpand: () => {\n return (\n table.options.getRowCanExpand?.(row) ??\n ((table.options.enableExpanding ?? true) && !!row.subRows?.length)\n )\n },\n getToggleExpandedHandler: () => {\n const canExpand = row.getCanExpand()\n\n return () => {\n if (!canExpand) return\n row.toggleExpanded()\n }\n },\n }\n },\n}\n", "import { FilterFn } from './features/Filters'\n\nconst includesString: FilterFn = (\n row,\n columnId: string,\n filterValue: string\n) => {\n const search = filterValue.toLowerCase()\n return Boolean(\n row\n .getValue(columnId)\n ?.toString()\n ?.toLowerCase()\n ?.includes(search)\n )\n}\n\nincludesString.autoRemove = (val: any) => testFalsey(val)\n\nconst includesStringSensitive: FilterFn = (\n row,\n columnId: string,\n filterValue: string\n) => {\n return Boolean(\n row.getValue(columnId)?.toString()?.includes(filterValue)\n )\n}\n\nincludesStringSensitive.autoRemove = (val: any) => testFalsey(val)\n\nconst equalsString: FilterFn = (\n row,\n columnId: string,\n filterValue: string\n) => {\n return (\n row.getValue(columnId)?.toString()?.toLowerCase() ===\n filterValue?.toLowerCase()\n )\n}\n\nequalsString.autoRemove = (val: any) => testFalsey(val)\n\nconst arrIncludes: FilterFn = (\n row,\n columnId: string,\n filterValue: unknown\n) => {\n return row.getValue(columnId)?.includes(filterValue)\n}\n\narrIncludes.autoRemove = (val: any) => testFalsey(val) || !val?.length\n\nconst arrIncludesAll: FilterFn = (\n row,\n columnId: string,\n filterValue: unknown[]\n) => {\n return !filterValue.some(\n val => !row.getValue(columnId)?.includes(val)\n )\n}\n\narrIncludesAll.autoRemove = (val: any) => testFalsey(val) || !val?.length\n\nconst arrIncludesSome: FilterFn = (\n row,\n columnId: string,\n filterValue: unknown[]\n) => {\n return filterValue.some(val =>\n row.getValue(columnId)?.includes(val)\n )\n}\n\narrIncludesSome.autoRemove = (val: any) => testFalsey(val) || !val?.length\n\nconst equals: FilterFn = (row, columnId: string, filterValue: unknown) => {\n return row.getValue(columnId) === filterValue\n}\n\nequals.autoRemove = (val: any) => testFalsey(val)\n\nconst weakEquals: FilterFn = (\n row,\n columnId: string,\n filterValue: unknown\n) => {\n return row.getValue(columnId) == filterValue\n}\n\nweakEquals.autoRemove = (val: any) => testFalsey(val)\n\nconst inNumberRange: FilterFn = (\n row,\n columnId: string,\n filterValue: [number, number]\n) => {\n let [min, max] = filterValue\n\n const rowValue = row.getValue(columnId)\n return rowValue >= min && rowValue <= max\n}\n\ninNumberRange.resolveFilterValue = (val: [any, any]) => {\n let [unsafeMin, unsafeMax] = val\n\n let parsedMin =\n typeof unsafeMin !== 'number' ? parseFloat(unsafeMin as string) : unsafeMin\n let parsedMax =\n typeof unsafeMax !== 'number' ? parseFloat(unsafeMax as string) : unsafeMax\n\n let min =\n unsafeMin === null || Number.isNaN(parsedMin) ? -Infinity : parsedMin\n let max = unsafeMax === null || Number.isNaN(parsedMax) ? Infinity : parsedMax\n\n if (min > max) {\n const temp = min\n min = max\n max = temp\n }\n\n return [min, max] as const\n}\n\ninNumberRange.autoRemove = (val: any) =>\n testFalsey(val) || (testFalsey(val[0]) && testFalsey(val[1]))\n\n// Export\n\nexport const filterFns = {\n includesString,\n includesStringSensitive,\n equalsString,\n arrIncludes,\n arrIncludesAll,\n arrIncludesSome,\n equals,\n weakEquals,\n inNumberRange,\n}\n\nexport type BuiltInFilterFn = keyof typeof filterFns\n\n// Utils\n\nfunction testFalsey(val: any) {\n return val === undefined || val === null || val === ''\n}\n", "import { RowModel } from '..'\nimport { TableFeature } from '../core/table'\nimport { BuiltInFilterFn, filterFns } from '../filterFns'\nimport {\n Column,\n OnChangeFn,\n Table,\n Row,\n Updater,\n RowData,\n FilterMeta,\n FilterFns,\n} from '../types'\nimport { functionalUpdate, isFunction, makeStateUpdater } from '../utils'\n\nexport interface FiltersTableState {\n columnFilters: ColumnFiltersState\n globalFilter: any\n}\n\nexport type ColumnFiltersState = ColumnFilter[]\n\nexport interface ColumnFilter {\n id: string\n value: unknown\n}\n\nexport interface ResolvedColumnFilter {\n id: string\n resolvedValue: unknown\n filterFn: FilterFn\n}\n\nexport interface FilterFn {\n (\n row: Row,\n columnId: string,\n filterValue: any,\n addMeta: (meta: FilterMeta) => void\n ): boolean\n\n resolveFilterValue?: TransformFilterValueFn\n autoRemove?: ColumnFilterAutoRemoveTestFn\n}\n\nexport type TransformFilterValueFn = (\n value: any,\n column?: Column\n) => unknown\n\nexport type ColumnFilterAutoRemoveTestFn = (\n value: any,\n column?: Column\n) => boolean\n\nexport type CustomFilterFns = Record<\n string,\n FilterFn\n>\n\nexport type FilterFnOption =\n | 'auto'\n | BuiltInFilterFn\n | keyof FilterFns\n | FilterFn\n\nexport interface FiltersColumnDef {\n filterFn?: FilterFnOption\n enableColumnFilter?: boolean\n enableGlobalFilter?: boolean\n}\n\nexport interface FiltersColumn {\n getAutoFilterFn: () => FilterFn | undefined\n getFilterFn: () => FilterFn | undefined\n setFilterValue: (updater: Updater) => void\n getCanFilter: () => boolean\n getCanGlobalFilter: () => boolean\n getFacetedRowModel: () => RowModel\n _getFacetedRowModel?: () => RowModel\n getIsFiltered: () => boolean\n getFilterValue: () => unknown\n getFilterIndex: () => number\n getFacetedUniqueValues: () => Map\n _getFacetedUniqueValues?: () => Map\n getFacetedMinMaxValues: () => undefined | [number, number]\n _getFacetedMinMaxValues?: () => undefined | [number, number]\n}\n\nexport interface FiltersRow {\n columnFilters: Record\n columnFiltersMeta: Record\n}\n\ninterface FiltersOptionsBase {\n enableFilters?: boolean\n manualFiltering?: boolean\n filterFromLeafRows?: boolean\n maxLeafRowFilterDepth?: number\n getFilteredRowModel?: (table: Table) => () => RowModel\n\n // Column\n onColumnFiltersChange?: OnChangeFn\n enableColumnFilters?: boolean\n\n // Global\n globalFilterFn?: FilterFnOption\n onGlobalFilterChange?: OnChangeFn\n enableGlobalFilter?: boolean\n getColumnCanGlobalFilter?: (column: Column) => boolean\n\n // Faceting\n getFacetedRowModel?: (\n table: Table,\n columnId: string\n ) => () => RowModel\n getFacetedUniqueValues?: (\n table: Table,\n columnId: string\n ) => () => Map\n getFacetedMinMaxValues?: (\n table: Table,\n columnId: string\n ) => () => undefined | [number, number]\n}\n\ntype ResolvedFilterFns = keyof FilterFns extends never\n ? {\n filterFns?: Record>\n }\n : {\n filterFns: Record>\n }\n\nexport interface FiltersOptions\n extends FiltersOptionsBase,\n ResolvedFilterFns {}\n\nexport interface FiltersInstance {\n setColumnFilters: (updater: Updater) => void\n\n resetColumnFilters: (defaultState?: boolean) => void\n\n // Column Filters\n getPreFilteredRowModel: () => RowModel\n getFilteredRowModel: () => RowModel\n _getFilteredRowModel?: () => RowModel\n\n // Global Filters\n setGlobalFilter: (updater: Updater) => void\n resetGlobalFilter: (defaultState?: boolean) => void\n getGlobalAutoFilterFn: () => FilterFn | undefined\n getGlobalFilterFn: () => FilterFn | undefined\n getGlobalFacetedRowModel: () => RowModel\n _getGlobalFacetedRowModel?: () => RowModel\n getGlobalFacetedUniqueValues: () => Map\n _getGlobalFacetedUniqueValues?: () => Map\n getGlobalFacetedMinMaxValues: () => undefined | [number, number]\n _getGlobalFacetedMinMaxValues?: () => undefined | [number, number]\n}\n\n//\n\nexport const Filters: TableFeature = {\n getDefaultColumnDef: (): FiltersColumnDef => {\n return {\n filterFn: 'auto',\n }\n },\n\n getInitialState: (state): FiltersTableState => {\n return {\n columnFilters: [],\n globalFilter: undefined,\n // filtersProgress: 1,\n // facetProgress: {},\n ...state,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): FiltersOptions => {\n return {\n onColumnFiltersChange: makeStateUpdater('columnFilters', table),\n onGlobalFilterChange: makeStateUpdater('globalFilter', table),\n filterFromLeafRows: false,\n maxLeafRowFilterDepth: 100,\n globalFilterFn: 'auto',\n getColumnCanGlobalFilter: column => {\n const value = table\n .getCoreRowModel()\n .flatRows[0]?._getAllCellsByColumnId()\n [column.id]?.getValue()\n\n return typeof value === 'string' || typeof value === 'number'\n },\n } as FiltersOptions\n },\n\n createColumn: (\n column: Column,\n table: Table\n ): FiltersColumn => {\n return {\n getAutoFilterFn: () => {\n const firstRow = table.getCoreRowModel().flatRows[0]\n\n const value = firstRow?.getValue(column.id)\n\n if (typeof value === 'string') {\n return filterFns.includesString\n }\n\n if (typeof value === 'number') {\n return filterFns.inNumberRange\n }\n\n if (typeof value === 'boolean') {\n return filterFns.equals\n }\n\n if (value !== null && typeof value === 'object') {\n return filterFns.equals\n }\n\n if (Array.isArray(value)) {\n return filterFns.arrIncludes\n }\n\n return filterFns.weakEquals\n },\n getFilterFn: () => {\n return isFunction(column.columnDef.filterFn)\n ? column.columnDef.filterFn\n : column.columnDef.filterFn === 'auto'\n ? column.getAutoFilterFn()\n // @ts-ignore \n : table.options.filterFns?.[column.columnDef.filterFn as string] ??\n filterFns[column.columnDef.filterFn as BuiltInFilterFn]\n },\n getCanFilter: () => {\n return (\n (column.columnDef.enableColumnFilter ?? true) &&\n (table.options.enableColumnFilters ?? true) &&\n (table.options.enableFilters ?? true) &&\n !!column.accessorFn\n )\n },\n\n getCanGlobalFilter: () => {\n return (\n (column.columnDef.enableGlobalFilter ?? true) &&\n (table.options.enableGlobalFilter ?? true) &&\n (table.options.enableFilters ?? true) &&\n (table.options.getColumnCanGlobalFilter?.(column) ?? true) &&\n !!column.accessorFn\n )\n },\n\n getIsFiltered: () => column.getFilterIndex() > -1,\n\n getFilterValue: () =>\n table.getState().columnFilters?.find(d => d.id === column.id)?.value,\n\n getFilterIndex: () =>\n table.getState().columnFilters?.findIndex(d => d.id === column.id) ??\n -1,\n\n setFilterValue: value => {\n table.setColumnFilters(old => {\n const filterFn = column.getFilterFn()\n const previousfilter = old?.find(d => d.id === column.id)\n\n const newFilter = functionalUpdate(\n value,\n previousfilter ? previousfilter.value : undefined\n )\n\n //\n if (\n shouldAutoRemoveFilter(\n filterFn as FilterFn,\n newFilter,\n column\n )\n ) {\n return old?.filter(d => d.id !== column.id) ?? []\n }\n\n const newFilterObj = { id: column.id, value: newFilter }\n\n if (previousfilter) {\n return (\n old?.map(d => {\n if (d.id === column.id) {\n return newFilterObj\n }\n return d\n }) ?? []\n )\n }\n\n if (old?.length) {\n return [...old, newFilterObj]\n }\n\n return [newFilterObj]\n })\n },\n _getFacetedRowModel:\n table.options.getFacetedRowModel &&\n table.options.getFacetedRowModel(table, column.id),\n getFacetedRowModel: () => {\n if (!column._getFacetedRowModel) {\n return table.getPreFilteredRowModel()\n }\n\n return column._getFacetedRowModel()\n },\n _getFacetedUniqueValues:\n table.options.getFacetedUniqueValues &&\n table.options.getFacetedUniqueValues(table, column.id),\n getFacetedUniqueValues: () => {\n if (!column._getFacetedUniqueValues) {\n return new Map()\n }\n\n return column._getFacetedUniqueValues()\n },\n _getFacetedMinMaxValues:\n table.options.getFacetedMinMaxValues &&\n table.options.getFacetedMinMaxValues(table, column.id),\n getFacetedMinMaxValues: () => {\n if (!column._getFacetedMinMaxValues) {\n return undefined\n }\n\n return column._getFacetedMinMaxValues()\n },\n // () => [column.getFacetedRowModel()],\n // facetedRowModel => getRowModelMinMaxValues(facetedRowModel, column.id),\n }\n },\n\n createRow: (\n row: Row,\n table: Table\n ): FiltersRow => {\n return {\n columnFilters: {},\n columnFiltersMeta: {},\n }\n },\n\n createTable: (\n table: Table\n ): FiltersInstance => {\n return {\n getGlobalAutoFilterFn: () => {\n return filterFns.includesString\n },\n\n getGlobalFilterFn: () => {\n const { globalFilterFn: globalFilterFn } = table.options\n\n return isFunction(globalFilterFn)\n ? globalFilterFn\n : globalFilterFn === 'auto'\n ? table.getGlobalAutoFilterFn()\n // @ts-ignore\n : table.options.filterFns?.[globalFilterFn as string] ??\n filterFns[globalFilterFn as BuiltInFilterFn]\n },\n\n setColumnFilters: (updater: Updater) => {\n const leafColumns = table.getAllLeafColumns()\n\n const updateFn = (old: ColumnFiltersState) => {\n return functionalUpdate(updater, old)?.filter(filter => {\n const column = leafColumns.find(d => d.id === filter.id)\n\n if (column) {\n const filterFn = column.getFilterFn()\n\n if (shouldAutoRemoveFilter(filterFn, filter.value, column)) {\n return false\n }\n }\n\n return true\n })\n }\n\n table.options.onColumnFiltersChange?.(updateFn)\n },\n\n setGlobalFilter: updater => {\n table.options.onGlobalFilterChange?.(updater)\n },\n\n resetGlobalFilter: defaultState => {\n table.setGlobalFilter(\n defaultState ? undefined : table.initialState.globalFilter\n )\n },\n\n resetColumnFilters: defaultState => {\n table.setColumnFilters(\n defaultState ? [] : table.initialState?.columnFilters ?? []\n )\n },\n\n getPreFilteredRowModel: () => table.getCoreRowModel(),\n getFilteredRowModel: () => {\n if (!table._getFilteredRowModel && table.options.getFilteredRowModel) {\n table._getFilteredRowModel = table.options.getFilteredRowModel(table)\n }\n\n if (table.options.manualFiltering || !table._getFilteredRowModel) {\n return table.getPreFilteredRowModel()\n }\n\n return table._getFilteredRowModel()\n },\n\n _getGlobalFacetedRowModel:\n table.options.getFacetedRowModel &&\n table.options.getFacetedRowModel(table, '__global__'),\n\n getGlobalFacetedRowModel: () => {\n if (table.options.manualFiltering || !table._getGlobalFacetedRowModel) {\n return table.getPreFilteredRowModel()\n }\n\n return table._getGlobalFacetedRowModel()\n },\n\n _getGlobalFacetedUniqueValues:\n table.options.getFacetedUniqueValues &&\n table.options.getFacetedUniqueValues(table, '__global__'),\n getGlobalFacetedUniqueValues: () => {\n if (!table._getGlobalFacetedUniqueValues) {\n return new Map()\n }\n\n return table._getGlobalFacetedUniqueValues()\n },\n\n _getGlobalFacetedMinMaxValues:\n table.options.getFacetedMinMaxValues &&\n table.options.getFacetedMinMaxValues(table, '__global__'),\n getGlobalFacetedMinMaxValues: () => {\n if (!table._getGlobalFacetedMinMaxValues) {\n return\n }\n\n return table._getGlobalFacetedMinMaxValues()\n },\n }\n },\n}\n\nexport function shouldAutoRemoveFilter(\n filterFn?: FilterFn,\n value?: any,\n column?: Column\n) {\n return (\n (filterFn && filterFn.autoRemove\n ? filterFn.autoRemove(value, column)\n : false) ||\n typeof value === 'undefined' ||\n (typeof value === 'string' && !value)\n )\n}\n", "import { AggregationFn } from './features/Grouping'\nimport { isNumberArray } from './utils'\n\nconst sum: AggregationFn = (columnId, _leafRows, childRows) => {\n // It's faster to just add the aggregations together instead of\n // process leaf nodes individually\n return childRows.reduce((sum, next) => {\n const nextValue = next.getValue(columnId)\n return sum + (typeof nextValue === 'number' ? nextValue : 0)\n }, 0)\n}\n\nconst min: AggregationFn = (columnId, _leafRows, childRows) => {\n let min: number | undefined\n\n childRows.forEach(row => {\n const value = row.getValue(columnId)\n\n if (\n value != null &&\n (min! > value || (min === undefined && value >= value))\n ) {\n min = value\n }\n })\n\n return min\n}\n\nconst max: AggregationFn = (columnId, _leafRows, childRows) => {\n let max: number | undefined\n\n childRows.forEach(row => {\n const value = row.getValue(columnId)\n if (\n value != null &&\n (max! < value || (max === undefined && value >= value))\n ) {\n max = value\n }\n })\n\n return max\n}\n\nconst extent: AggregationFn = (columnId, _leafRows, childRows) => {\n let min: number | undefined\n let max: number | undefined\n\n childRows.forEach(row => {\n const value = row.getValue(columnId)\n if (value != null) {\n if (min === undefined) {\n if (value >= value) min = max = value\n } else {\n if (min > value) min = value\n if (max! < value) max = value\n }\n }\n })\n\n return [min, max]\n}\n\nconst mean: AggregationFn = (columnId, leafRows) => {\n let count = 0\n let sum = 0\n\n leafRows.forEach(row => {\n let value = row.getValue(columnId)\n if (value != null && (value = +value) >= value) {\n ++count, (sum += value)\n }\n })\n\n if (count) return sum / count\n\n return\n}\n\nconst median: AggregationFn = (columnId, leafRows) => {\n if (!leafRows.length) {\n return\n }\n\n const values = leafRows.map(row => row.getValue(columnId))\n if (!isNumberArray(values)) {\n return\n }\n if (values.length === 1) {\n return values[0]\n }\n\n const mid = Math.floor(values.length / 2)\n const nums = values.sort((a, b) => a - b)\n return values.length % 2 !== 0 ? nums[mid] : (nums[mid - 1]! + nums[mid]!) / 2\n}\n\nconst unique: AggregationFn = (columnId, leafRows) => {\n return Array.from(new Set(leafRows.map(d => d.getValue(columnId))).values())\n}\n\nconst uniqueCount: AggregationFn = (columnId, leafRows) => {\n return new Set(leafRows.map(d => d.getValue(columnId))).size\n}\n\nconst count: AggregationFn = (_columnId, leafRows) => {\n return leafRows.length\n}\n\nexport const aggregationFns = {\n sum,\n min,\n max,\n extent,\n mean,\n median,\n unique,\n uniqueCount,\n count,\n}\n\nexport type BuiltInAggregationFn = keyof typeof aggregationFns\n", "import { RowModel } from '..'\nimport { BuiltInAggregationFn, aggregationFns } from '../aggregationFns'\nimport { TableFeature } from '../core/table'\nimport {\n Cell,\n Column,\n OnChangeFn,\n Table,\n Row,\n Updater,\n ColumnDefTemplate,\n RowData,\n AggregationFns,\n} from '../types'\nimport { isFunction, makeStateUpdater } from '../utils'\n\nexport type GroupingState = string[]\n\nexport interface GroupingTableState {\n grouping: GroupingState\n}\n\nexport type AggregationFn = (\n columnId: string,\n leafRows: Row[],\n childRows: Row[]\n) => any\n\nexport type CustomAggregationFns = Record>\n\nexport type AggregationFnOption =\n | 'auto'\n | keyof AggregationFns\n | BuiltInAggregationFn\n | AggregationFn\n\nexport interface GroupingColumnDef {\n aggregationFn?: AggregationFnOption\n aggregatedCell?: ColumnDefTemplate<\n ReturnType['getContext']>\n >\n enableGrouping?: boolean\n getGroupingValue?: (row: TData) => any\n}\n\nexport interface GroupingColumn {\n getCanGroup: () => boolean\n getIsGrouped: () => boolean\n getGroupedIndex: () => number\n toggleGrouping: () => void\n getToggleGroupingHandler: () => () => void\n getAutoAggregationFn: () => AggregationFn | undefined\n getAggregationFn: () => AggregationFn | undefined\n}\n\nexport interface GroupingRow {\n groupingColumnId?: string\n groupingValue?: unknown\n getIsGrouped: () => boolean\n getGroupingValue: (columnId: string) => unknown\n _groupingValuesCache: Record\n}\n\nexport interface GroupingCell {\n getIsGrouped: () => boolean\n getIsPlaceholder: () => boolean\n getIsAggregated: () => boolean\n}\n\nexport interface ColumnDefaultOptions {\n // Column\n onGroupingChange: OnChangeFn\n enableGrouping: boolean\n}\n\ninterface GroupingOptionsBase {\n manualGrouping?: boolean\n onGroupingChange?: OnChangeFn\n enableGrouping?: boolean\n getGroupedRowModel?: (table: Table) => () => RowModel\n groupedColumnMode?: false | 'reorder' | 'remove'\n}\n\ntype ResolvedAggregationFns = keyof AggregationFns extends never\n ? {\n aggregationFns?: Record>\n }\n : {\n aggregationFns: Record>\n }\n\nexport interface GroupingOptions\n extends GroupingOptionsBase,\n ResolvedAggregationFns {}\n\nexport type GroupingColumnMode = false | 'reorder' | 'remove'\n\nexport interface GroupingInstance {\n setGrouping: (updater: Updater) => void\n resetGrouping: (defaultState?: boolean) => void\n getPreGroupedRowModel: () => RowModel\n getGroupedRowModel: () => RowModel\n _getGroupedRowModel?: () => RowModel\n}\n\n//\n\nexport const Grouping: TableFeature = {\n getDefaultColumnDef: (): GroupingColumnDef<\n TData,\n unknown\n > => {\n return {\n aggregatedCell: props => (props.getValue() as any)?.toString?.() ?? null,\n aggregationFn: 'auto',\n }\n },\n\n getInitialState: (state): GroupingTableState => {\n return {\n grouping: [],\n ...state,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): GroupingOptions => {\n return {\n onGroupingChange: makeStateUpdater('grouping', table),\n groupedColumnMode: 'reorder',\n }\n },\n\n createColumn: (\n column: Column,\n table: Table\n ): GroupingColumn => {\n return {\n toggleGrouping: () => {\n table.setGrouping(old => {\n // Find any existing grouping for this column\n if (old?.includes(column.id)) {\n return old.filter(d => d !== column.id)\n }\n\n return [...(old ?? []), column.id]\n })\n },\n\n getCanGroup: () => {\n return (\n column.columnDef.enableGrouping ??\n true ??\n table.options.enableGrouping ??\n true ??\n !!column.accessorFn\n )\n },\n\n getIsGrouped: () => {\n return table.getState().grouping?.includes(column.id)\n },\n\n getGroupedIndex: () => table.getState().grouping?.indexOf(column.id),\n\n getToggleGroupingHandler: () => {\n const canGroup = column.getCanGroup()\n\n return () => {\n if (!canGroup) return\n column.toggleGrouping()\n }\n },\n getAutoAggregationFn: () => {\n const firstRow = table.getCoreRowModel().flatRows[0]\n\n const value = firstRow?.getValue(column.id)\n\n if (typeof value === 'number') {\n return aggregationFns.sum\n }\n\n if (Object.prototype.toString.call(value) === '[object Date]') {\n return aggregationFns.extent\n }\n },\n getAggregationFn: () => {\n if (!column) {\n throw new Error()\n }\n\n return isFunction(column.columnDef.aggregationFn)\n ? column.columnDef.aggregationFn\n : column.columnDef.aggregationFn === 'auto'\n ? column.getAutoAggregationFn()\n : table.options.aggregationFns?.[\n column.columnDef.aggregationFn as string\n ] ??\n aggregationFns[\n column.columnDef.aggregationFn as BuiltInAggregationFn\n ]\n },\n }\n },\n\n createTable: (\n table: Table\n ): GroupingInstance => {\n return {\n setGrouping: updater => table.options.onGroupingChange?.(updater),\n\n resetGrouping: defaultState => {\n table.setGrouping(\n defaultState ? [] : table.initialState?.grouping ?? []\n )\n },\n\n getPreGroupedRowModel: () => table.getFilteredRowModel(),\n getGroupedRowModel: () => {\n if (!table._getGroupedRowModel && table.options.getGroupedRowModel) {\n table._getGroupedRowModel = table.options.getGroupedRowModel(table)\n }\n\n if (table.options.manualGrouping || !table._getGroupedRowModel) {\n return table.getPreGroupedRowModel()\n }\n\n return table._getGroupedRowModel()\n },\n }\n },\n\n createRow: (\n row: Row,\n table: Table\n ): GroupingRow => {\n return {\n getIsGrouped: () => !!row.groupingColumnId,\n getGroupingValue: columnId => {\n if (row._groupingValuesCache.hasOwnProperty(columnId)) {\n return row._groupingValuesCache[columnId]\n }\n\n const column = table.getColumn(columnId)\n\n if (!column?.columnDef.getGroupingValue) {\n return row.getValue(columnId)\n }\n\n row._groupingValuesCache[columnId] = column.columnDef.getGroupingValue(\n row.original\n )\n\n return row._groupingValuesCache[columnId]\n },\n _groupingValuesCache: {},\n }\n },\n\n createCell: (\n cell: Cell,\n column: Column,\n row: Row,\n table: Table\n ): GroupingCell => {\n const getRenderValue = () =>\n cell.getValue() ?? table.options.renderFallbackValue\n\n return {\n getIsGrouped: () =>\n column.getIsGrouped() && column.id === row.groupingColumnId,\n getIsPlaceholder: () => !cell.getIsGrouped() && column.getIsGrouped(),\n getIsAggregated: () =>\n !cell.getIsGrouped() &&\n !cell.getIsPlaceholder() &&\n !!row.subRows?.length,\n }\n },\n}\n\nexport function orderColumns(\n leafColumns: Column[],\n grouping: string[],\n groupedColumnMode?: GroupingColumnMode\n) {\n if (!grouping?.length || !groupedColumnMode) {\n return leafColumns\n }\n\n const nonGroupingColumns = leafColumns.filter(\n col => !grouping.includes(col.id)\n )\n\n if (groupedColumnMode === 'remove') {\n return nonGroupingColumns\n }\n\n const groupingColumns = grouping\n .map(g => leafColumns.find(col => col.id === g)!)\n .filter(Boolean)\n\n return [...groupingColumns, ...nonGroupingColumns]\n}\n", "import { makeStateUpdater, memo } from '../utils'\n\nimport { Table, OnChangeFn, Updater, Column, RowData } from '../types'\n\nimport { orderColumns } from './Grouping'\nimport { TableFeature } from '../core/table'\n\nexport interface ColumnOrderTableState {\n columnOrder: ColumnOrderState\n}\n\nexport type ColumnOrderState = string[]\n\nexport interface ColumnOrderOptions {\n onColumnOrderChange?: OnChangeFn\n}\n\nexport interface ColumnOrderDefaultOptions {\n onColumnOrderChange: OnChangeFn\n}\n\nexport interface ColumnOrderInstance {\n setColumnOrder: (updater: Updater) => void\n resetColumnOrder: (defaultState?: boolean) => void\n _getOrderColumnsFn: () => (\n columns: Column[]\n ) => Column[]\n}\n\n//\n\nexport const Ordering: TableFeature = {\n getInitialState: (state): ColumnOrderTableState => {\n return {\n columnOrder: [],\n ...state,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): ColumnOrderDefaultOptions => {\n return {\n onColumnOrderChange: makeStateUpdater('columnOrder', table),\n }\n },\n\n createTable: (\n table: Table\n ): ColumnOrderInstance => {\n return {\n setColumnOrder: updater => table.options.onColumnOrderChange?.(updater),\n resetColumnOrder: defaultState => {\n table.setColumnOrder(\n defaultState ? [] : table.initialState.columnOrder ?? []\n )\n },\n _getOrderColumnsFn: memo(\n () => [\n table.getState().columnOrder,\n table.getState().grouping,\n table.options.groupedColumnMode,\n ],\n (columnOrder, grouping, groupedColumnMode) => columns => {\n // Sort grouped columns to the start of the column list\n // before the headers are built\n let orderedColumns: Column[] = []\n\n // If there is no order, return the normal columns\n if (!columnOrder?.length) {\n orderedColumns = columns\n } else {\n const columnOrderCopy = [...columnOrder]\n\n // If there is an order, make a copy of the columns\n const columnsCopy = [...columns]\n\n // And make a new ordered array of the columns\n\n // Loop over the columns and place them in order into the new array\n while (columnsCopy.length && columnOrderCopy.length) {\n const targetColumnId = columnOrderCopy.shift()\n const foundIndex = columnsCopy.findIndex(\n d => d.id === targetColumnId\n )\n if (foundIndex > -1) {\n orderedColumns.push(columnsCopy.splice(foundIndex, 1)[0]!)\n }\n }\n\n // If there are any columns left, add them to the end\n orderedColumns = [...orderedColumns, ...columnsCopy]\n }\n\n return orderColumns(orderedColumns, grouping, groupedColumnMode)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getOrderColumnsFn',\n // debug: () => table.options.debugAll ?? table.options.debugTable,\n }\n ),\n }\n },\n}\n", "import { TableFeature } from '../core/table'\nimport { OnChangeFn, Table, RowModel, Updater, RowData } from '../types'\nimport { functionalUpdate, makeStateUpdater, memo } from '../utils'\n\nexport interface PaginationState {\n pageIndex: number\n pageSize: number\n}\n\nexport interface PaginationTableState {\n pagination: PaginationState\n}\n\nexport interface PaginationInitialTableState {\n pagination?: Partial\n}\n\nexport interface PaginationOptions {\n pageCount?: number\n manualPagination?: boolean\n onPaginationChange?: OnChangeFn\n autoResetPageIndex?: boolean\n getPaginationRowModel?: (table: Table) => () => RowModel\n}\n\nexport interface PaginationDefaultOptions {\n onPaginationChange: OnChangeFn\n}\n\nexport interface PaginationInstance {\n _autoResetPageIndex: () => void\n setPagination: (updater: Updater) => void\n resetPagination: (defaultState?: boolean) => void\n setPageIndex: (updater: Updater) => void\n resetPageIndex: (defaultState?: boolean) => void\n setPageSize: (updater: Updater) => void\n resetPageSize: (defaultState?: boolean) => void\n setPageCount: (updater: Updater) => void\n getPageOptions: () => number[]\n getCanPreviousPage: () => boolean\n getCanNextPage: () => boolean\n previousPage: () => void\n nextPage: () => void\n getPrePaginationRowModel: () => RowModel\n getPaginationRowModel: () => RowModel\n _getPaginationRowModel?: () => RowModel\n getPageCount: () => number\n}\n\n//\n\nconst defaultPageIndex = 0\nconst defaultPageSize = 10\n\nconst getDefaultPaginationState = (): PaginationState => ({\n pageIndex: defaultPageIndex,\n pageSize: defaultPageSize,\n})\n\nexport const Pagination: TableFeature = {\n getInitialState: (state): PaginationTableState => {\n return {\n ...state,\n pagination: {\n ...getDefaultPaginationState(),\n ...state?.pagination,\n },\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): PaginationDefaultOptions => {\n return {\n onPaginationChange: makeStateUpdater('pagination', table),\n }\n },\n\n createTable: (\n table: Table\n ): PaginationInstance => {\n let registered = false\n let queued = false\n\n return {\n _autoResetPageIndex: () => {\n if (!registered) {\n table._queue(() => {\n registered = true\n })\n return\n }\n\n if (\n table.options.autoResetAll ??\n table.options.autoResetPageIndex ??\n !table.options.manualPagination\n ) {\n if (queued) return\n queued = true\n table._queue(() => {\n table.resetPageIndex()\n queued = false\n })\n }\n },\n setPagination: updater => {\n const safeUpdater: Updater = old => {\n let newState = functionalUpdate(updater, old)\n\n return newState\n }\n\n return table.options.onPaginationChange?.(safeUpdater)\n },\n resetPagination: defaultState => {\n table.setPagination(\n defaultState\n ? getDefaultPaginationState()\n : table.initialState.pagination ?? getDefaultPaginationState()\n )\n },\n setPageIndex: updater => {\n table.setPagination(old => {\n let pageIndex = functionalUpdate(updater, old.pageIndex)\n\n const maxPageIndex =\n typeof table.options.pageCount === 'undefined' ||\n table.options.pageCount === -1\n ? Number.MAX_SAFE_INTEGER\n : table.options.pageCount - 1\n\n pageIndex = Math.max(0, Math.min(pageIndex, maxPageIndex))\n\n return {\n ...old,\n pageIndex,\n }\n })\n },\n resetPageIndex: defaultState => {\n table.setPageIndex(\n defaultState\n ? defaultPageIndex\n : table.initialState?.pagination?.pageIndex ?? defaultPageIndex\n )\n },\n resetPageSize: defaultState => {\n table.setPageSize(\n defaultState\n ? defaultPageSize\n : table.initialState?.pagination?.pageSize ?? defaultPageSize\n )\n },\n setPageSize: updater => {\n table.setPagination(old => {\n const pageSize = Math.max(1, functionalUpdate(updater, old.pageSize))\n const topRowIndex = old.pageSize * old.pageIndex!\n const pageIndex = Math.floor(topRowIndex / pageSize)\n\n return {\n ...old,\n pageIndex,\n pageSize,\n }\n })\n },\n setPageCount: updater =>\n table.setPagination(old => {\n let newPageCount = functionalUpdate(\n updater,\n table.options.pageCount ?? -1\n )\n\n if (typeof newPageCount === 'number') {\n newPageCount = Math.max(-1, newPageCount)\n }\n\n return {\n ...old,\n pageCount: newPageCount,\n }\n }),\n\n getPageOptions: memo(\n () => [table.getPageCount()],\n pageCount => {\n let pageOptions: number[] = []\n if (pageCount && pageCount > 0) {\n pageOptions = [...new Array(pageCount)].fill(null).map((_, i) => i)\n }\n return pageOptions\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getPageOptions',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n }\n ),\n\n getCanPreviousPage: () => table.getState().pagination.pageIndex > 0,\n\n getCanNextPage: () => {\n const { pageIndex } = table.getState().pagination\n\n const pageCount = table.getPageCount()\n\n if (pageCount === -1) {\n return true\n }\n\n if (pageCount === 0) {\n return false\n }\n\n return pageIndex < pageCount - 1\n },\n\n previousPage: () => {\n return table.setPageIndex(old => old - 1)\n },\n\n nextPage: () => {\n return table.setPageIndex(old => {\n return old + 1\n })\n },\n\n getPrePaginationRowModel: () => table.getExpandedRowModel(),\n getPaginationRowModel: () => {\n if (\n !table._getPaginationRowModel &&\n table.options.getPaginationRowModel\n ) {\n table._getPaginationRowModel =\n table.options.getPaginationRowModel(table)\n }\n\n if (table.options.manualPagination || !table._getPaginationRowModel) {\n return table.getPrePaginationRowModel()\n }\n\n return table._getPaginationRowModel()\n },\n\n getPageCount: () => {\n return (\n table.options.pageCount ??\n Math.ceil(\n table.getPrePaginationRowModel().rows.length /\n table.getState().pagination.pageSize\n )\n )\n },\n }\n },\n}\n", "import { TableFeature } from '../core/table'\nimport {\n OnChangeFn,\n Updater,\n Table,\n Column,\n Row,\n Cell,\n RowData,\n} from '../types'\nimport { makeStateUpdater, memo } from '../utils'\n\nexport type ColumnPinningPosition = false | 'left' | 'right'\n\nexport interface ColumnPinningState {\n left?: string[]\n right?: string[]\n}\n\nexport interface ColumnPinningTableState {\n columnPinning: ColumnPinningState\n}\n\nexport interface ColumnPinningOptions {\n onColumnPinningChange?: OnChangeFn\n enablePinning?: boolean\n}\n\nexport interface ColumnPinningDefaultOptions {\n onColumnPinningChange: OnChangeFn\n}\n\nexport interface ColumnPinningColumnDef {\n enablePinning?: boolean\n}\n\nexport interface ColumnPinningColumn {\n getCanPin: () => boolean\n getPinnedIndex: () => number\n getIsPinned: () => ColumnPinningPosition\n pin: (position: ColumnPinningPosition) => void\n}\n\nexport interface ColumnPinningRow {\n getLeftVisibleCells: () => Cell[]\n getCenterVisibleCells: () => Cell[]\n getRightVisibleCells: () => Cell[]\n}\n\nexport interface ColumnPinningInstance {\n setColumnPinning: (updater: Updater) => void\n resetColumnPinning: (defaultState?: boolean) => void\n getIsSomeColumnsPinned: (position?: ColumnPinningPosition) => boolean\n getLeftLeafColumns: () => Column[]\n getRightLeafColumns: () => Column[]\n getCenterLeafColumns: () => Column[]\n}\n\n//\n\nconst getDefaultPinningState = (): ColumnPinningState => ({\n left: [],\n right: [],\n})\n\nexport const Pinning: TableFeature = {\n getInitialState: (state): ColumnPinningTableState => {\n return {\n columnPinning: getDefaultPinningState(),\n ...state,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): ColumnPinningDefaultOptions => {\n return {\n onColumnPinningChange: makeStateUpdater('columnPinning', table),\n }\n },\n\n createColumn: (\n column: Column,\n table: Table\n ): ColumnPinningColumn => {\n return {\n pin: position => {\n const columnIds = column\n .getLeafColumns()\n .map(d => d.id)\n .filter(Boolean) as string[]\n\n table.setColumnPinning(old => {\n if (position === 'right') {\n return {\n left: (old?.left ?? []).filter(d => !columnIds?.includes(d)),\n right: [\n ...(old?.right ?? []).filter(d => !columnIds?.includes(d)),\n ...columnIds,\n ],\n }\n }\n\n if (position === 'left') {\n return {\n left: [\n ...(old?.left ?? []).filter(d => !columnIds?.includes(d)),\n ...columnIds,\n ],\n right: (old?.right ?? []).filter(d => !columnIds?.includes(d)),\n }\n }\n\n return {\n left: (old?.left ?? []).filter(d => !columnIds?.includes(d)),\n right: (old?.right ?? []).filter(d => !columnIds?.includes(d)),\n }\n })\n },\n\n getCanPin: () => {\n const leafColumns = column.getLeafColumns()\n\n return leafColumns.some(\n d =>\n (d.columnDef.enablePinning ?? true) &&\n (table.options.enablePinning ?? true)\n )\n },\n\n getIsPinned: () => {\n const leafColumnIds = column.getLeafColumns().map(d => d.id)\n\n const { left, right } = table.getState().columnPinning\n\n const isLeft = leafColumnIds.some(d => left?.includes(d))\n const isRight = leafColumnIds.some(d => right?.includes(d))\n\n return isLeft ? 'left' : isRight ? 'right' : false\n },\n\n getPinnedIndex: () => {\n const position = column.getIsPinned()\n\n return position\n ? table.getState().columnPinning?.[position]?.indexOf(column.id) ?? -1\n : 0\n },\n }\n },\n\n createRow: (\n row: Row,\n table: Table\n ): ColumnPinningRow => {\n return {\n getCenterVisibleCells: memo(\n () => [\n row._getAllVisibleCells(),\n table.getState().columnPinning.left,\n table.getState().columnPinning.right,\n ],\n (allCells, left, right) => {\n const leftAndRight: string[] = [...(left ?? []), ...(right ?? [])]\n\n return allCells.filter(d => !leftAndRight.includes(d.column.id))\n },\n {\n key:\n process.env.NODE_ENV === 'production' &&\n 'row.getCenterVisibleCells',\n debug: () => table.options.debugAll ?? table.options.debugRows,\n }\n ),\n getLeftVisibleCells: memo(\n () => [\n row._getAllVisibleCells(),\n table.getState().columnPinning.left,\n ,\n ],\n (allCells, left) => {\n const cells = (left ?? [])\n .map(\n columnId => allCells.find(cell => cell.column.id === columnId)!\n )\n .filter(Boolean)\n .map(d => ({ ...d, position: 'left' } as Cell))\n\n return cells\n },\n {\n key:\n process.env.NODE_ENV === 'production' && 'row.getLeftVisibleCells',\n debug: () => table.options.debugAll ?? table.options.debugRows,\n }\n ),\n getRightVisibleCells: memo(\n () => [row._getAllVisibleCells(), table.getState().columnPinning.right],\n (allCells, right) => {\n const cells = (right ?? [])\n .map(\n columnId => allCells.find(cell => cell.column.id === columnId)!\n )\n .filter(Boolean)\n .map(d => ({ ...d, position: 'right' } as Cell))\n\n return cells\n },\n {\n key:\n process.env.NODE_ENV === 'production' && 'row.getRightVisibleCells',\n debug: () => table.options.debugAll ?? table.options.debugRows,\n }\n ),\n }\n },\n\n createTable: (\n table: Table\n ): ColumnPinningInstance => {\n return {\n setColumnPinning: updater =>\n table.options.onColumnPinningChange?.(updater),\n\n resetColumnPinning: defaultState =>\n table.setColumnPinning(\n defaultState\n ? getDefaultPinningState()\n : table.initialState?.columnPinning ?? getDefaultPinningState()\n ),\n\n getIsSomeColumnsPinned: position => {\n const pinningState = table.getState().columnPinning\n\n if (!position) {\n return Boolean(\n pinningState.left?.length || pinningState.right?.length\n )\n }\n return Boolean(pinningState[position]?.length)\n },\n\n getLeftLeafColumns: memo(\n () => [table.getAllLeafColumns(), table.getState().columnPinning.left],\n (allColumns, left) => {\n return (left ?? [])\n .map(columnId => allColumns.find(column => column.id === columnId)!)\n .filter(Boolean)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getLeftLeafColumns',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n\n getRightLeafColumns: memo(\n () => [table.getAllLeafColumns(), table.getState().columnPinning.right],\n (allColumns, right) => {\n return (right ?? [])\n .map(columnId => allColumns.find(column => column.id === columnId)!)\n .filter(Boolean)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getRightLeafColumns',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n\n getCenterLeafColumns: memo(\n () => [\n table.getAllLeafColumns(),\n table.getState().columnPinning.left,\n table.getState().columnPinning.right,\n ],\n (allColumns, left, right) => {\n const leftAndRight: string[] = [...(left ?? []), ...(right ?? [])]\n\n return allColumns.filter(d => !leftAndRight.includes(d.id))\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getCenterLeafColumns',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n }\n },\n}\n", "import { TableFeature } from '../core/table'\nimport { OnChangeFn, Table, Row, RowModel, Updater, RowData } from '../types'\nimport { makeStateUpdater, memo } from '../utils'\n\nexport type RowSelectionState = Record\n\nexport interface RowSelectionTableState {\n rowSelection: RowSelectionState\n}\n\nexport interface RowSelectionOptions {\n enableRowSelection?: boolean | ((row: Row) => boolean)\n enableMultiRowSelection?: boolean | ((row: Row) => boolean)\n enableSubRowSelection?: boolean | ((row: Row) => boolean)\n onRowSelectionChange?: OnChangeFn\n // enableGroupingRowSelection?:\n // | boolean\n // | ((\n // row: Row\n // ) => boolean)\n // isAdditiveSelectEvent?: (e: unknown) => boolean\n // isInclusiveSelectEvent?: (e: unknown) => boolean\n // selectRowsFn?: (\n // table: Table,\n // rowModel: RowModel\n // ) => RowModel\n}\n\nexport interface RowSelectionRow {\n getIsSelected: () => boolean\n getIsSomeSelected: () => boolean\n getIsAllSubRowsSelected: () => boolean\n getCanSelect: () => boolean\n getCanMultiSelect: () => boolean\n getCanSelectSubRows: () => boolean\n toggleSelected: (value?: boolean) => void\n getToggleSelectedHandler: () => (event: unknown) => void\n}\n\nexport interface RowSelectionInstance {\n getToggleAllRowsSelectedHandler: () => (event: unknown) => void\n getToggleAllPageRowsSelectedHandler: () => (event: unknown) => void\n setRowSelection: (updater: Updater) => void\n resetRowSelection: (defaultState?: boolean) => void\n getIsAllRowsSelected: () => boolean\n getIsAllPageRowsSelected: () => boolean\n getIsSomeRowsSelected: () => boolean\n getIsSomePageRowsSelected: () => boolean\n toggleAllRowsSelected: (value?: boolean) => void\n toggleAllPageRowsSelected: (value?: boolean) => void\n getPreSelectedRowModel: () => RowModel\n getSelectedRowModel: () => RowModel\n getFilteredSelectedRowModel: () => RowModel\n getGroupedSelectedRowModel: () => RowModel\n}\n\n//\n\nexport const RowSelection: TableFeature = {\n getInitialState: (state): RowSelectionTableState => {\n return {\n rowSelection: {},\n ...state,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): RowSelectionOptions => {\n return {\n onRowSelectionChange: makeStateUpdater('rowSelection', table),\n enableRowSelection: true,\n enableMultiRowSelection: true,\n enableSubRowSelection: true,\n // enableGroupingRowSelection: false,\n // isAdditiveSelectEvent: (e: unknown) => !!e.metaKey,\n // isInclusiveSelectEvent: (e: unknown) => !!e.shiftKey,\n }\n },\n\n createTable: (\n table: Table\n ): RowSelectionInstance => {\n return {\n setRowSelection: updater => table.options.onRowSelectionChange?.(updater),\n resetRowSelection: defaultState =>\n table.setRowSelection(\n defaultState ? {} : table.initialState.rowSelection ?? {}\n ),\n toggleAllRowsSelected: value => {\n table.setRowSelection(old => {\n value =\n typeof value !== 'undefined' ? value : !table.getIsAllRowsSelected()\n\n const rowSelection = { ...old }\n\n const preGroupedFlatRows = table.getPreGroupedRowModel().flatRows\n\n // We don't use `mutateRowIsSelected` here for performance reasons.\n // All of the rows are flat already, so it wouldn't be worth it\n if (value) {\n preGroupedFlatRows.forEach(row => {\n if (!row.getCanSelect()) {\n return\n }\n rowSelection[row.id] = true\n })\n } else {\n preGroupedFlatRows.forEach(row => {\n delete rowSelection[row.id]\n })\n }\n\n return rowSelection\n })\n },\n toggleAllPageRowsSelected: value =>\n table.setRowSelection(old => {\n const resolvedValue =\n typeof value !== 'undefined'\n ? value\n : !table.getIsAllPageRowsSelected()\n\n const rowSelection: RowSelectionState = { ...old }\n\n table.getRowModel().rows.forEach(row => {\n mutateRowIsSelected(rowSelection, row.id, resolvedValue, table)\n })\n\n return rowSelection\n }),\n\n // addRowSelectionRange: rowId => {\n // const {\n // rows,\n // rowsById,\n // options: { selectGroupingRows, selectSubRows },\n // } = table\n\n // const findSelectedRow = (rows: Row[]) => {\n // let found\n // rows.find(d => {\n // if (d.getIsSelected()) {\n // found = d\n // return true\n // }\n // const subFound = findSelectedRow(d.subRows || [])\n // if (subFound) {\n // found = subFound\n // return true\n // }\n // return false\n // })\n // return found\n // }\n\n // const firstRow = findSelectedRow(rows) || rows[0]\n // const lastRow = rowsById[rowId]\n\n // let include = false\n // const selectedRowIds = {}\n\n // const addRow = (row: Row) => {\n // mutateRowIsSelected(selectedRowIds, row.id, true, {\n // rowsById,\n // selectGroupingRows: selectGroupingRows!,\n // selectSubRows: selectSubRows!,\n // })\n // }\n\n // table.rows.forEach(row => {\n // const isFirstRow = row.id === firstRow.id\n // const isLastRow = row.id === lastRow.id\n\n // if (isFirstRow || isLastRow) {\n // if (!include) {\n // include = true\n // } else if (include) {\n // addRow(row)\n // include = false\n // }\n // }\n\n // if (include) {\n // addRow(row)\n // }\n // })\n\n // table.setRowSelection(selectedRowIds)\n // },\n getPreSelectedRowModel: () => table.getCoreRowModel(),\n getSelectedRowModel: memo(\n () => [table.getState().rowSelection, table.getCoreRowModel()],\n (rowSelection, rowModel) => {\n if (!Object.keys(rowSelection).length) {\n return {\n rows: [],\n flatRows: [],\n rowsById: {},\n }\n }\n\n return selectRowsFn(table, rowModel)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getSelectedRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n }\n ),\n\n getFilteredSelectedRowModel: memo(\n () => [table.getState().rowSelection, table.getFilteredRowModel()],\n (rowSelection, rowModel) => {\n if (!Object.keys(rowSelection).length) {\n return {\n rows: [],\n flatRows: [],\n rowsById: {},\n }\n }\n\n return selectRowsFn(table, rowModel)\n },\n {\n key:\n process.env.NODE_ENV === 'production' &&\n 'getFilteredSelectedRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n }\n ),\n\n getGroupedSelectedRowModel: memo(\n () => [table.getState().rowSelection, table.getSortedRowModel()],\n (rowSelection, rowModel) => {\n if (!Object.keys(rowSelection).length) {\n return {\n rows: [],\n flatRows: [],\n rowsById: {},\n }\n }\n\n return selectRowsFn(table, rowModel)\n },\n {\n key:\n process.env.NODE_ENV === 'production' &&\n 'getGroupedSelectedRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n }\n ),\n\n ///\n\n // getGroupingRowCanSelect: rowId => {\n // const row = table.getRow(rowId)\n\n // if (!row) {\n // throw new Error()\n // }\n\n // if (typeof table.options.enableGroupingRowSelection === 'function') {\n // return table.options.enableGroupingRowSelection(row)\n // }\n\n // return table.options.enableGroupingRowSelection ?? false\n // },\n\n getIsAllRowsSelected: () => {\n const preGroupedFlatRows = table.getFilteredRowModel().flatRows\n const { rowSelection } = table.getState()\n\n let isAllRowsSelected = Boolean(\n preGroupedFlatRows.length && Object.keys(rowSelection).length\n )\n\n if (isAllRowsSelected) {\n if (\n preGroupedFlatRows.some(\n row => row.getCanSelect() && !rowSelection[row.id]\n )\n ) {\n isAllRowsSelected = false\n }\n }\n\n return isAllRowsSelected\n },\n\n getIsAllPageRowsSelected: () => {\n const paginationFlatRows = table\n .getPaginationRowModel()\n .flatRows.filter(row => row.getCanSelect())\n const { rowSelection } = table.getState()\n\n let isAllPageRowsSelected = !!paginationFlatRows.length\n\n if (\n isAllPageRowsSelected &&\n paginationFlatRows.some(row => !rowSelection[row.id])\n ) {\n isAllPageRowsSelected = false\n }\n\n return isAllPageRowsSelected\n },\n\n getIsSomeRowsSelected: () => {\n const totalSelected = Object.keys(\n table.getState().rowSelection ?? {}\n ).length\n return (\n totalSelected > 0 &&\n totalSelected < table.getFilteredRowModel().flatRows.length\n )\n },\n\n getIsSomePageRowsSelected: () => {\n const paginationFlatRows = table.getPaginationRowModel().flatRows\n return table.getIsAllPageRowsSelected()\n ? false\n : paginationFlatRows\n .filter(row => row.getCanSelect())\n .some(d => d.getIsSelected() || d.getIsSomeSelected())\n },\n\n getToggleAllRowsSelectedHandler: () => {\n return (e: unknown) => {\n table.toggleAllRowsSelected(\n ((e as MouseEvent).target as HTMLInputElement).checked\n )\n }\n },\n\n getToggleAllPageRowsSelectedHandler: () => {\n return (e: unknown) => {\n table.toggleAllPageRowsSelected(\n ((e as MouseEvent).target as HTMLInputElement).checked\n )\n }\n },\n }\n },\n\n createRow: (\n row: Row,\n table: Table\n ): RowSelectionRow => {\n return {\n toggleSelected: value => {\n const isSelected = row.getIsSelected()\n\n table.setRowSelection(old => {\n value = typeof value !== 'undefined' ? value : !isSelected\n\n if (isSelected === value) {\n return old\n }\n\n const selectedRowIds = { ...old }\n\n mutateRowIsSelected(selectedRowIds, row.id, value, table)\n\n return selectedRowIds\n })\n },\n getIsSelected: () => {\n const { rowSelection } = table.getState()\n return isRowSelected(row, rowSelection)\n },\n\n getIsSomeSelected: () => {\n const { rowSelection } = table.getState()\n return isSubRowSelected(row, rowSelection, table) === 'some'\n },\n\n getIsAllSubRowsSelected: () => {\n const { rowSelection } = table.getState()\n return isSubRowSelected(row, rowSelection, table) === 'all'\n },\n\n getCanSelect: () => {\n if (typeof table.options.enableRowSelection === 'function') {\n return table.options.enableRowSelection(row)\n }\n\n return table.options.enableRowSelection ?? true\n },\n\n getCanSelectSubRows: () => {\n if (typeof table.options.enableSubRowSelection === 'function') {\n return table.options.enableSubRowSelection(row)\n }\n\n return table.options.enableSubRowSelection ?? true\n },\n\n getCanMultiSelect: () => {\n if (typeof table.options.enableMultiRowSelection === 'function') {\n return table.options.enableMultiRowSelection(row)\n }\n\n return table.options.enableMultiRowSelection ?? true\n },\n getToggleSelectedHandler: () => {\n const canSelect = row.getCanSelect()\n\n return (e: unknown) => {\n if (!canSelect) return\n row.toggleSelected(\n ((e as MouseEvent).target as HTMLInputElement)?.checked\n )\n }\n },\n }\n },\n}\n\nconst mutateRowIsSelected = (\n selectedRowIds: Record,\n id: string,\n value: boolean,\n table: Table\n) => {\n const row = table.getRow(id)\n\n // const isGrouped = row.getIsGrouped()\n\n // if ( // TODO: enforce grouping row selection rules\n // !isGrouped ||\n // (isGrouped && table.options.enableGroupingRowSelection)\n // ) {\n if (value) {\n if (!row.getCanMultiSelect()) {\n Object.keys(selectedRowIds).forEach(key => delete selectedRowIds[key])\n }\n if (row.getCanSelect()) {\n selectedRowIds[id] = true\n }\n } else {\n delete selectedRowIds[id]\n }\n // }\n\n if (row.subRows?.length && row.getCanSelectSubRows()) {\n row.subRows.forEach(row =>\n mutateRowIsSelected(selectedRowIds, row.id, value, table)\n )\n }\n}\n\nexport function selectRowsFn(\n table: Table,\n rowModel: RowModel\n): RowModel {\n const rowSelection = table.getState().rowSelection\n\n const newSelectedFlatRows: Row[] = []\n const newSelectedRowsById: Record> = {}\n\n // Filters top level and nested rows\n const recurseRows = (rows: Row[], depth = 0): Row[] => {\n return rows\n .map(row => {\n const isSelected = isRowSelected(row, rowSelection)\n\n if (isSelected) {\n newSelectedFlatRows.push(row)\n newSelectedRowsById[row.id] = row\n }\n\n if (row.subRows?.length) {\n row = {\n ...row,\n subRows: recurseRows(row.subRows, depth + 1),\n }\n }\n\n if (isSelected) {\n return row\n }\n })\n .filter(Boolean) as Row[]\n }\n\n return {\n rows: recurseRows(rowModel.rows),\n flatRows: newSelectedFlatRows,\n rowsById: newSelectedRowsById,\n }\n}\n\nexport function isRowSelected(\n row: Row,\n selection: Record\n): boolean {\n return selection[row.id] ?? false\n}\n\nexport function isSubRowSelected(\n row: Row,\n selection: Record,\n table: Table\n): boolean | 'some' | 'all' {\n if (row.subRows && row.subRows.length) {\n let allChildrenSelected = true\n let someSelected = false\n\n row.subRows.forEach(subRow => {\n // Bail out early if we know both of these\n if (someSelected && !allChildrenSelected) {\n return\n }\n\n if (isRowSelected(subRow, selection)) {\n someSelected = true\n } else {\n allChildrenSelected = false\n }\n })\n\n return allChildrenSelected ? 'all' : someSelected ? 'some' : false\n }\n\n return false\n}\n", "import { SortingFn } from './features/Sorting'\n\nexport const reSplitAlphaNumeric = /([0-9]+)/gm\n\nconst alphanumeric: SortingFn = (rowA, rowB, columnId) => {\n return compareAlphanumeric(\n toString(rowA.getValue(columnId)).toLowerCase(),\n toString(rowB.getValue(columnId)).toLowerCase()\n )\n}\n\nconst alphanumericCaseSensitive: SortingFn = (rowA, rowB, columnId) => {\n return compareAlphanumeric(\n toString(rowA.getValue(columnId)),\n toString(rowB.getValue(columnId))\n )\n}\n\n// The text filter is more basic (less numeric support)\n// but is much faster\nconst text: SortingFn = (rowA, rowB, columnId) => {\n return compareBasic(\n toString(rowA.getValue(columnId)).toLowerCase(),\n toString(rowB.getValue(columnId)).toLowerCase()\n )\n}\n\n// The text filter is more basic (less numeric support)\n// but is much faster\nconst textCaseSensitive: SortingFn = (rowA, rowB, columnId) => {\n return compareBasic(\n toString(rowA.getValue(columnId)),\n toString(rowB.getValue(columnId))\n )\n}\n\nconst datetime: SortingFn = (rowA, rowB, columnId) => {\n const a = rowA.getValue(columnId)\n const b = rowB.getValue(columnId)\n\n // Can handle nullish values\n // Use > and < because == (and ===) doesn't work with\n // Date objects (would require calling getTime()).\n return a > b ? 1 : a < b ? -1 : 0\n}\n\nconst basic: SortingFn = (rowA, rowB, columnId) => {\n return compareBasic(rowA.getValue(columnId), rowB.getValue(columnId))\n}\n\n// Utils\n\nfunction compareBasic(a: any, b: any) {\n return a === b ? 0 : a > b ? 1 : -1\n}\n\nfunction toString(a: any) {\n if (typeof a === 'number') {\n if (isNaN(a) || a === Infinity || a === -Infinity) {\n return ''\n }\n return String(a)\n }\n if (typeof a === 'string') {\n return a\n }\n return ''\n}\n\n// Mixed sorting is slow, but very inclusive of many edge cases.\n// It handles numbers, mixed alphanumeric combinations, and even\n// null, undefined, and Infinity\nfunction compareAlphanumeric(aStr: string, bStr: string) {\n // Split on number groups, but keep the delimiter\n // Then remove falsey split values\n const a = aStr.split(reSplitAlphaNumeric).filter(Boolean)\n const b = bStr.split(reSplitAlphaNumeric).filter(Boolean)\n\n // While\n while (a.length && b.length) {\n const aa = a.shift()!\n const bb = b.shift()!\n\n const an = parseInt(aa, 10)\n const bn = parseInt(bb, 10)\n\n const combo = [an, bn].sort()\n\n // Both are string\n if (isNaN(combo[0]!)) {\n if (aa > bb) {\n return 1\n }\n if (bb > aa) {\n return -1\n }\n continue\n }\n\n // One is a string, one is a number\n if (isNaN(combo[1]!)) {\n return isNaN(an) ? -1 : 1\n }\n\n // Both are numbers\n if (an > bn) {\n return 1\n }\n if (bn > an) {\n return -1\n }\n }\n\n return a.length - b.length\n}\n\n// Exports\n\nexport const sortingFns = {\n alphanumeric,\n alphanumericCaseSensitive,\n text,\n textCaseSensitive,\n datetime,\n basic,\n}\n\nexport type BuiltInSortingFn = keyof typeof sortingFns\n", "import { RowModel } from '..'\nimport { TableFeature } from '../core/table'\nimport {\n BuiltInSortingFn,\n reSplitAlphaNumeric,\n sortingFns,\n} from '../sortingFns'\n\nimport {\n Column,\n OnChangeFn,\n Table,\n Row,\n Updater,\n RowData,\n SortingFns,\n} from '../types'\n\nimport { isFunction, makeStateUpdater } from '../utils'\n\nexport type SortDirection = 'asc' | 'desc'\n\nexport interface ColumnSort {\n id: string\n desc: boolean\n}\n\nexport type SortingState = ColumnSort[]\n\nexport interface SortingTableState {\n sorting: SortingState\n}\n\nexport interface SortingFn {\n (rowA: Row, rowB: Row, columnId: string): number\n}\n\nexport type CustomSortingFns = Record<\n string,\n SortingFn\n>\n\nexport type SortingFnOption =\n | 'auto'\n | keyof SortingFns\n | BuiltInSortingFn\n | SortingFn\n\nexport interface SortingColumnDef {\n sortingFn?: SortingFnOption\n sortDescFirst?: boolean\n enableSorting?: boolean\n enableMultiSort?: boolean\n invertSorting?: boolean\n sortUndefined?: false | -1 | 1\n}\n\nexport interface SortingColumn {\n getAutoSortingFn: () => SortingFn\n getAutoSortDir: () => SortDirection\n getSortingFn: () => SortingFn\n getFirstSortDir: () => SortDirection\n getNextSortingOrder: () => SortDirection | false\n getCanSort: () => boolean\n getCanMultiSort: () => boolean\n getSortIndex: () => number\n getIsSorted: () => false | SortDirection\n clearSorting: () => void\n toggleSorting: (desc?: boolean, isMulti?: boolean) => void\n getToggleSortingHandler: () => undefined | ((event: unknown) => void)\n}\n\ninterface SortingOptionsBase {\n manualSorting?: boolean\n onSortingChange?: OnChangeFn\n enableSorting?: boolean\n enableSortingRemoval?: boolean\n enableMultiRemove?: boolean\n enableMultiSort?: boolean\n sortDescFirst?: boolean\n getSortedRowModel?: (table: Table) => () => RowModel\n maxMultiSortColCount?: number\n isMultiSortEvent?: (e: unknown) => boolean\n}\n\ntype ResolvedSortingFns = keyof SortingFns extends never\n ? {\n sortingFns?: Record>\n }\n : {\n sortingFns: Record>\n }\n\nexport interface SortingOptions\n extends SortingOptionsBase,\n ResolvedSortingFns {}\n\nexport interface SortingInstance {\n setSorting: (updater: Updater) => void\n resetSorting: (defaultState?: boolean) => void\n getPreSortedRowModel: () => RowModel\n getSortedRowModel: () => RowModel\n _getSortedRowModel?: () => RowModel\n}\n\n//\n\nexport const Sorting: TableFeature = {\n getInitialState: (state): SortingTableState => {\n return {\n sorting: [],\n ...state,\n }\n },\n\n getDefaultColumnDef: (): SortingColumnDef => {\n return {\n sortingFn: 'auto',\n sortUndefined: 1,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): SortingOptions => {\n return {\n onSortingChange: makeStateUpdater('sorting', table),\n isMultiSortEvent: (e: unknown) => {\n return (e as MouseEvent).shiftKey\n },\n }\n },\n\n createColumn: (\n column: Column,\n table: Table\n ): SortingColumn => {\n return {\n getAutoSortingFn: () => {\n const firstRows = table.getFilteredRowModel().flatRows.slice(10)\n\n let isString = false\n\n for (const row of firstRows) {\n const value = row?.getValue(column.id)\n\n if (Object.prototype.toString.call(value) === '[object Date]') {\n return sortingFns.datetime\n }\n\n if (typeof value === 'string') {\n isString = true\n\n if (value.split(reSplitAlphaNumeric).length > 1) {\n return sortingFns.alphanumeric\n }\n }\n }\n\n if (isString) {\n return sortingFns.text\n }\n\n return sortingFns.basic\n },\n getAutoSortDir: () => {\n const firstRow = table.getFilteredRowModel().flatRows[0]\n\n const value = firstRow?.getValue(column.id)\n\n if (typeof value === 'string') {\n return 'asc'\n }\n\n return 'desc'\n },\n getSortingFn: () => {\n if (!column) {\n throw new Error()\n }\n\n return isFunction(column.columnDef.sortingFn)\n ? column.columnDef.sortingFn\n : column.columnDef.sortingFn === 'auto'\n ? column.getAutoSortingFn()\n : table.options.sortingFns?.[column.columnDef.sortingFn as string] ??\n sortingFns[column.columnDef.sortingFn as BuiltInSortingFn]\n },\n toggleSorting: (desc, multi) => {\n // if (column.columns.length) {\n // column.columns.forEach((c, i) => {\n // if (c.id) {\n // table.toggleColumnSorting(c.id, undefined, multi || !!i)\n // }\n // })\n // return\n // }\n\n // this needs to be outside of table.setSorting to be in sync with rerender\n const nextSortingOrder = column.getNextSortingOrder()\n const hasManualValue = typeof desc !== 'undefined' && desc !== null\n\n table.setSorting(old => {\n // Find any existing sorting for this column\n const existingSorting = old?.find(d => d.id === column.id)\n const existingIndex = old?.findIndex(d => d.id === column.id)\n\n let newSorting: SortingState = []\n\n // What should we do with this sort action?\n let sortAction: 'add' | 'remove' | 'toggle' | 'replace'\n let nextDesc = hasManualValue ? desc : nextSortingOrder === 'desc'\n\n // Multi-mode\n if (old?.length && column.getCanMultiSort() && multi) {\n if (existingSorting) {\n sortAction = 'toggle'\n } else {\n sortAction = 'add'\n }\n } else {\n // Normal mode\n if (old?.length && existingIndex !== old.length - 1) {\n sortAction = 'replace'\n } else if (existingSorting) {\n sortAction = 'toggle'\n } else {\n sortAction = 'replace'\n }\n }\n\n // Handle toggle states that will remove the sorting\n if (sortAction === 'toggle') {\n // If we are \"actually\" toggling (not a manual set value), should we remove the sorting?\n if (!hasManualValue) {\n // Is our intention to remove?\n if (!nextSortingOrder) {\n sortAction = 'remove'\n }\n }\n }\n\n if (sortAction === 'add') {\n newSorting = [\n ...old,\n {\n id: column.id,\n desc: nextDesc,\n },\n ]\n // Take latest n columns\n newSorting.splice(\n 0,\n newSorting.length -\n (table.options.maxMultiSortColCount ?? Number.MAX_SAFE_INTEGER)\n )\n } else if (sortAction === 'toggle') {\n // This flips (or sets) the\n newSorting = old.map(d => {\n if (d.id === column.id) {\n return {\n ...d,\n desc: nextDesc,\n }\n }\n return d\n })\n } else if (sortAction === 'remove') {\n newSorting = old.filter(d => d.id !== column.id)\n } else {\n newSorting = [\n {\n id: column.id,\n desc: nextDesc,\n },\n ]\n }\n\n return newSorting\n })\n },\n\n getFirstSortDir: () => {\n const sortDescFirst =\n column.columnDef.sortDescFirst ??\n table.options.sortDescFirst ??\n column.getAutoSortDir() === 'desc'\n return sortDescFirst ? 'desc' : 'asc'\n },\n\n getNextSortingOrder: (multi?: boolean) => {\n const firstSortDirection = column.getFirstSortDir()\n const isSorted = column.getIsSorted()\n\n if (!isSorted) {\n return firstSortDirection\n }\n\n if (\n isSorted !== firstSortDirection &&\n (table.options.enableSortingRemoval ?? true) && // If enableSortRemove, enable in general\n (multi ? table.options.enableMultiRemove ?? true : true) // If multi, don't allow if enableMultiRemove))\n ) {\n return false\n }\n return isSorted === 'desc' ? 'asc' : 'desc'\n },\n\n getCanSort: () => {\n return (\n (column.columnDef.enableSorting ?? true) &&\n (table.options.enableSorting ?? true) &&\n !!column.accessorFn\n )\n },\n\n getCanMultiSort: () => {\n return (\n column.columnDef.enableMultiSort ??\n table.options.enableMultiSort ??\n !!column.accessorFn\n )\n },\n\n getIsSorted: () => {\n const columnSort = table\n .getState()\n .sorting?.find(d => d.id === column.id)\n\n return !columnSort ? false : columnSort.desc ? 'desc' : 'asc'\n },\n\n getSortIndex: () =>\n table.getState().sorting?.findIndex(d => d.id === column.id) ?? -1,\n\n clearSorting: () => {\n //clear sorting for just 1 column\n table.setSorting(old =>\n old?.length ? old.filter(d => d.id !== column.id) : []\n )\n },\n\n getToggleSortingHandler: () => {\n const canSort = column.getCanSort()\n\n return (e: unknown) => {\n if (!canSort) return\n ;(e as any).persist?.()\n column.toggleSorting?.(\n undefined,\n column.getCanMultiSort()\n ? table.options.isMultiSortEvent?.(e)\n : false\n )\n }\n },\n }\n },\n\n createTable: (\n table: Table\n ): SortingInstance => {\n return {\n setSorting: updater => table.options.onSortingChange?.(updater),\n resetSorting: defaultState => {\n table.setSorting(defaultState ? [] : table.initialState?.sorting ?? [])\n },\n getPreSortedRowModel: () => table.getGroupedRowModel(),\n getSortedRowModel: () => {\n if (!table._getSortedRowModel && table.options.getSortedRowModel) {\n table._getSortedRowModel = table.options.getSortedRowModel(table)\n }\n\n if (table.options.manualSorting || !table._getSortedRowModel) {\n return table.getPreSortedRowModel()\n }\n\n return table._getSortedRowModel()\n },\n }\n },\n}\n", "import { TableFeature } from '../core/table'\nimport {\n Cell,\n Column,\n OnChangeFn,\n Table,\n Updater,\n Row,\n RowData,\n} from '../types'\nimport { makeStateUpdater, memo } from '../utils'\n\nexport type VisibilityState = Record\n\nexport interface VisibilityTableState {\n columnVisibility: VisibilityState\n}\n\nexport interface VisibilityOptions {\n onColumnVisibilityChange?: OnChangeFn\n enableHiding?: boolean\n}\n\nexport interface VisibilityDefaultOptions {\n onColumnVisibilityChange: OnChangeFn\n}\n\nexport interface VisibilityInstance {\n getVisibleFlatColumns: () => Column[]\n getVisibleLeafColumns: () => Column[]\n getLeftVisibleLeafColumns: () => Column[]\n getRightVisibleLeafColumns: () => Column[]\n getCenterVisibleLeafColumns: () => Column[]\n setColumnVisibility: (updater: Updater) => void\n resetColumnVisibility: (defaultState?: boolean) => void\n toggleAllColumnsVisible: (value?: boolean) => void\n getIsAllColumnsVisible: () => boolean\n getIsSomeColumnsVisible: () => boolean\n getToggleAllColumnsVisibilityHandler: () => (event: unknown) => void\n}\n\nexport interface VisibilityColumnDef {\n enableHiding?: boolean\n}\n\nexport interface VisibilityRow {\n _getAllVisibleCells: () => Cell[]\n getVisibleCells: () => Cell[]\n}\n\nexport interface VisibilityColumn {\n getCanHide: () => boolean\n getIsVisible: () => boolean\n toggleVisibility: (value?: boolean) => void\n getToggleVisibilityHandler: () => (event: unknown) => void\n}\n\n//\n\nexport const Visibility: TableFeature = {\n getInitialState: (state): VisibilityTableState => {\n return {\n columnVisibility: {},\n ...state,\n }\n },\n\n getDefaultOptions: (\n table: Table\n ): VisibilityDefaultOptions => {\n return {\n onColumnVisibilityChange: makeStateUpdater('columnVisibility', table),\n }\n },\n\n createColumn: (\n column: Column,\n table: Table\n ): VisibilityColumn => {\n return {\n toggleVisibility: value => {\n if (column.getCanHide()) {\n table.setColumnVisibility(old => ({\n ...old,\n [column.id]: value ?? !column.getIsVisible(),\n }))\n }\n },\n getIsVisible: () => {\n return table.getState().columnVisibility?.[column.id] ?? true\n },\n\n getCanHide: () => {\n return (\n (column.columnDef.enableHiding ?? true) &&\n (table.options.enableHiding ?? true)\n )\n },\n getToggleVisibilityHandler: () => {\n return (e: unknown) => {\n column.toggleVisibility?.(\n ((e as MouseEvent).target as HTMLInputElement).checked\n )\n }\n },\n }\n },\n\n createRow: (\n row: Row,\n table: Table\n ): VisibilityRow => {\n return {\n _getAllVisibleCells: memo(\n () => [row.getAllCells(), table.getState().columnVisibility],\n cells => {\n return cells.filter(cell => cell.column.getIsVisible())\n },\n {\n key:\n process.env.NODE_ENV === 'production' && 'row._getAllVisibleCells',\n debug: () => table.options.debugAll ?? table.options.debugRows,\n }\n ),\n getVisibleCells: memo(\n () => [\n row.getLeftVisibleCells(),\n row.getCenterVisibleCells(),\n row.getRightVisibleCells(),\n ],\n (left, center, right) => [...left, ...center, ...right],\n {\n key: process.env.NODE_ENV === 'development' && 'row.getVisibleCells',\n debug: () => table.options.debugAll ?? table.options.debugRows,\n }\n ),\n }\n },\n\n createTable: (\n table: Table\n ): VisibilityInstance => {\n const makeVisibleColumnsMethod = (\n key: string,\n getColumns: () => Column[]\n ): (() => Column[]) => {\n return memo(\n () => [\n getColumns(),\n getColumns()\n .filter(d => d.getIsVisible())\n .map(d => d.id)\n .join('_'),\n ],\n columns => {\n return columns.filter(d => d.getIsVisible?.())\n },\n {\n key,\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n )\n }\n\n return {\n getVisibleFlatColumns: makeVisibleColumnsMethod(\n 'getVisibleFlatColumns',\n () => table.getAllFlatColumns()\n ),\n getVisibleLeafColumns: makeVisibleColumnsMethod(\n 'getVisibleLeafColumns',\n () => table.getAllLeafColumns()\n ),\n getLeftVisibleLeafColumns: makeVisibleColumnsMethod(\n 'getLeftVisibleLeafColumns',\n () => table.getLeftLeafColumns()\n ),\n getRightVisibleLeafColumns: makeVisibleColumnsMethod(\n 'getRightVisibleLeafColumns',\n () => table.getRightLeafColumns()\n ),\n getCenterVisibleLeafColumns: makeVisibleColumnsMethod(\n 'getCenterVisibleLeafColumns',\n () => table.getCenterLeafColumns()\n ),\n\n setColumnVisibility: updater =>\n table.options.onColumnVisibilityChange?.(updater),\n\n resetColumnVisibility: defaultState => {\n table.setColumnVisibility(\n defaultState ? {} : table.initialState.columnVisibility ?? {}\n )\n },\n\n toggleAllColumnsVisible: value => {\n value = value ?? !table.getIsAllColumnsVisible()\n\n table.setColumnVisibility(\n table.getAllLeafColumns().reduce(\n (obj, column) => ({\n ...obj,\n [column.id]: !value ? !column.getCanHide?.() : value,\n }),\n {}\n )\n )\n },\n\n getIsAllColumnsVisible: () =>\n !table.getAllLeafColumns().some(column => !column.getIsVisible?.()),\n\n getIsSomeColumnsVisible: () =>\n table.getAllLeafColumns().some(column => column.getIsVisible?.()),\n\n getToggleAllColumnsVisibilityHandler: () => {\n return (e: unknown) => {\n table.toggleAllColumnsVisible(\n ((e as MouseEvent).target as HTMLInputElement)?.checked\n )\n }\n },\n }\n },\n}\n", "import { functionalUpdate, memo, RequiredKeys } from '../utils'\n\nimport {\n Updater,\n TableOptionsResolved,\n TableState,\n Table,\n InitialTableState,\n Row,\n Column,\n RowModel,\n ColumnDef,\n TableOptions,\n RowData,\n TableMeta,\n ColumnDefResolved,\n GroupColumnDef,\n} from '../types'\n\n//\nimport { createColumn } from './column'\nimport { Headers } from './headers'\n//\n\nimport { ColumnSizing } from '../features/ColumnSizing'\nimport { Expanding } from '../features/Expanding'\nimport { Filters } from '../features/Filters'\nimport { Grouping } from '../features/Grouping'\nimport { Ordering } from '../features/Ordering'\nimport { Pagination } from '../features/Pagination'\nimport { Pinning } from '../features/Pinning'\nimport { RowSelection } from '../features/RowSelection'\nimport { Sorting } from '../features/Sorting'\nimport { Visibility } from '../features/Visibility'\n\nexport interface TableFeature {\n getDefaultOptions?: (table: any) => any\n getInitialState?: (initialState?: InitialTableState) => any\n createTable?: (table: any) => any\n getDefaultColumnDef?: () => any\n createColumn?: (column: any, table: any) => any\n createHeader?: (column: any, table: any) => any\n createCell?: (cell: any, column: any, row: any, table: any) => any\n createRow?: (row: any, table: any) => any\n}\n\nconst features = [\n Headers,\n Visibility,\n Ordering,\n Pinning,\n Filters,\n Sorting,\n Grouping,\n Expanding,\n Pagination,\n RowSelection,\n ColumnSizing,\n] as const\n\n//\n\nexport interface CoreTableState {}\n\nexport interface CoreOptions {\n data: TData[]\n state: Partial\n onStateChange: (updater: Updater) => void\n debugAll?: boolean\n debugTable?: boolean\n debugHeaders?: boolean\n debugColumns?: boolean\n debugRows?: boolean\n initialState?: InitialTableState\n autoResetAll?: boolean\n mergeOptions?: (\n defaultOptions: TableOptions,\n options: Partial>\n ) => TableOptions\n meta?: TableMeta\n getCoreRowModel: (table: Table) => () => RowModel\n getSubRows?: (originalRow: TData, index: number) => undefined | TData[]\n getRowId?: (originalRow: TData, index: number, parent?: Row) => string\n columns: ColumnDef[]\n defaultColumn?: Partial>\n renderFallbackValue: any\n}\n\nexport interface CoreInstance {\n initialState: TableState\n reset: () => void\n options: RequiredKeys, 'state'>\n setOptions: (newOptions: Updater>) => void\n getState: () => TableState\n setState: (updater: Updater) => void\n _features: readonly TableFeature[]\n _queue: (cb: () => void) => void\n _getRowId: (_: TData, index: number, parent?: Row) => string\n getCoreRowModel: () => RowModel\n _getCoreRowModel?: () => RowModel\n getRowModel: () => RowModel\n getRow: (id: string) => Row\n _getDefaultColumnDef: () => Partial>\n _getColumnDefs: () => ColumnDef[]\n _getAllFlatColumnsById: () => Record>\n getAllColumns: () => Column[]\n getAllFlatColumns: () => Column[]\n getAllLeafColumns: () => Column[]\n getColumn: (columnId: string) => Column | undefined\n}\n\nexport function createTable(\n options: TableOptionsResolved\n): Table {\n if (options.debugAll || options.debugTable) {\n console.info('Creating Table Instance...')\n }\n\n let table = { _features: features } as unknown as Table\n\n const defaultOptions = table._features.reduce((obj, feature) => {\n return Object.assign(obj, feature.getDefaultOptions?.(table))\n }, {}) as TableOptionsResolved\n\n const mergeOptions = (options: TableOptionsResolved) => {\n if (table.options.mergeOptions) {\n return table.options.mergeOptions(defaultOptions, options)\n }\n\n return {\n ...defaultOptions,\n ...options,\n }\n }\n\n const coreInitialState: CoreTableState = {}\n\n let initialState = {\n ...coreInitialState,\n ...(options.initialState ?? {}),\n } as TableState\n\n table._features.forEach(feature => {\n initialState = feature.getInitialState?.(initialState) ?? initialState\n })\n\n const queued: (() => void)[] = []\n let queuedTimeout = false\n\n const coreInstance: CoreInstance = {\n _features: features,\n options: {\n ...defaultOptions,\n ...options,\n },\n initialState,\n _queue: cb => {\n queued.push(cb)\n\n if (!queuedTimeout) {\n queuedTimeout = true\n\n // Schedule a microtask to run the queued callbacks after\n // the current call stack (render, etc) has finished.\n Promise.resolve()\n .then(() => {\n while (queued.length) {\n queued.shift()!()\n }\n queuedTimeout = false\n })\n .catch(error =>\n setTimeout(() => {\n throw error\n })\n )\n }\n },\n reset: () => {\n table.setState(table.initialState)\n },\n setOptions: updater => {\n const newOptions = functionalUpdate(updater, table.options)\n table.options = mergeOptions(newOptions) as RequiredKeys<\n TableOptionsResolved,\n 'state'\n >\n },\n\n getState: () => {\n return table.options.state as TableState\n },\n\n setState: (updater: Updater) => {\n table.options.onStateChange?.(updater)\n },\n\n _getRowId: (row: TData, index: number, parent?: Row) =>\n table.options.getRowId?.(row, index, parent) ??\n `${parent ? [parent.id, index].join('.') : index}`,\n\n getCoreRowModel: () => {\n if (!table._getCoreRowModel) {\n table._getCoreRowModel = table.options.getCoreRowModel(table)\n }\n\n return table._getCoreRowModel!()\n },\n\n // The final calls start at the bottom of the model,\n // expanded rows, which then work their way up\n\n getRowModel: () => {\n return table.getPaginationRowModel()\n },\n getRow: (id: string) => {\n const row = table.getRowModel().rowsById[id]\n\n if (!row) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(`getRow expected an ID, but got ${id}`)\n }\n throw new Error()\n }\n\n return row\n },\n _getDefaultColumnDef: memo(\n () => [table.options.defaultColumn],\n defaultColumn => {\n defaultColumn = (defaultColumn ?? {}) as Partial<\n ColumnDef\n >\n\n return {\n header: props => {\n const resolvedColumnDef = props.header.column\n .columnDef as ColumnDefResolved\n\n if (resolvedColumnDef.accessorKey) {\n return resolvedColumnDef.accessorKey\n }\n\n if (resolvedColumnDef.accessorFn) {\n return resolvedColumnDef.id\n }\n\n return null\n },\n // footer: props => props.header.column.id,\n cell: props => props.renderValue()?.toString?.() ?? null,\n ...table._features.reduce((obj, feature) => {\n return Object.assign(obj, feature.getDefaultColumnDef?.())\n }, {}),\n ...defaultColumn,\n } as Partial>\n },\n {\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n key: process.env.NODE_ENV === 'development' && 'getDefaultColumnDef',\n }\n ),\n\n _getColumnDefs: () => table.options.columns,\n\n getAllColumns: memo(\n () => [table._getColumnDefs()],\n columnDefs => {\n const recurseColumns = (\n columnDefs: ColumnDef[],\n parent?: Column,\n depth = 0\n ): Column[] => {\n return columnDefs.map(columnDef => {\n const column = createColumn(table, columnDef, depth, parent)\n\n const groupingColumnDef = columnDef as GroupColumnDef<\n TData,\n unknown\n >\n\n column.columns = groupingColumnDef.columns\n ? recurseColumns(groupingColumnDef.columns, column, depth + 1)\n : []\n\n return column\n })\n }\n\n return recurseColumns(columnDefs)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getAllColumns',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n\n getAllFlatColumns: memo(\n () => [table.getAllColumns()],\n allColumns => {\n return allColumns.flatMap(column => {\n return column.getFlatColumns()\n })\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getAllFlatColumns',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n\n _getAllFlatColumnsById: memo(\n () => [table.getAllFlatColumns()],\n flatColumns => {\n return flatColumns.reduce((acc, column) => {\n acc[column.id] = column\n return acc\n }, {} as Record>)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getAllFlatColumnsById',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n\n getAllLeafColumns: memo(\n () => [table.getAllColumns(), table._getOrderColumnsFn()],\n (allColumns, orderColumns) => {\n let leafColumns = allColumns.flatMap(column => column.getLeafColumns())\n return orderColumns(leafColumns)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getAllLeafColumns',\n debug: () => table.options.debugAll ?? table.options.debugColumns,\n }\n ),\n\n getColumn: columnId => {\n const column = table._getAllFlatColumnsById()[columnId]\n\n if (process.env.NODE_ENV !== 'production' && !column) {\n console.error(`[Table] Column with id '${columnId}' does not exist.`)\n }\n\n return column\n },\n }\n\n Object.assign(table, coreInstance)\n\n table._features.forEach(feature => {\n return Object.assign(table, feature.createTable?.(table))\n })\n\n return table\n}\n", "import { RowData, Cell, Column, Row, Table } from '../types'\nimport { Getter, memo } from '../utils'\n\nexport interface CellContext {\n table: Table\n column: Column\n row: Row\n cell: Cell\n getValue: Getter\n renderValue: Getter\n}\n\nexport interface CoreCell {\n id: string\n getValue: CellContext['getValue']\n renderValue: CellContext['renderValue']\n row: Row\n column: Column\n getContext: () => CellContext\n}\n\nexport function createCell(\n table: Table,\n row: Row,\n column: Column,\n columnId: string\n): Cell {\n const getRenderValue = () =>\n cell.getValue() ?? table.options.renderFallbackValue\n\n const cell: CoreCell = {\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,\n getValue: cell.getValue,\n renderValue: cell.renderValue,\n }),\n {\n key: process.env.NODE_ENV === 'development' && 'cell.getContext',\n debug: () => table.options.debugAll,\n }\n ),\n }\n\n table._features.forEach(feature => {\n Object.assign(\n cell,\n feature.createCell?.(\n cell as Cell,\n column,\n row as Row,\n table\n )\n )\n }, {})\n\n return cell as Cell\n}\n", "import { RowData, Cell, Row, Table } from '../types'\nimport { flattenBy, memo } from '../utils'\nimport { createCell } from './cell'\n\nexport interface CoreRow {\n id: string\n index: number\n original: TData\n depth: number\n parentId?: string\n _valuesCache: Record\n _uniqueValuesCache: Record\n getValue: (columnId: string) => TValue\n getUniqueValues: (columnId: string) => TValue[]\n renderValue: (columnId: string) => TValue\n subRows: Row[]\n getLeafRows: () => Row[]\n originalSubRows?: TData[]\n getAllCells: () => Cell[]\n _getAllCellsByColumnId: () => Record>\n getParentRow: () => Row | undefined\n getParentRows: () => Row[]\n}\n\nexport const createRow = (\n table: Table,\n id: string,\n original: TData,\n rowIndex: number,\n depth: number,\n subRows?: Row[],\n parentId?: string\n): Row => {\n let row: CoreRow = {\n id,\n index: rowIndex,\n original,\n depth,\n parentId,\n _valuesCache: {},\n _uniqueValuesCache: {},\n getValue: columnId => {\n if (row._valuesCache.hasOwnProperty(columnId)) {\n return row._valuesCache[columnId]\n }\n\n const column = table.getColumn(columnId)\n\n if (!column?.accessorFn) {\n return undefined\n }\n\n row._valuesCache[columnId] = column.accessorFn(\n row.original as TData,\n rowIndex\n )\n\n return row._valuesCache[columnId] as any\n },\n getUniqueValues: columnId => {\n if (row._uniqueValuesCache.hasOwnProperty(columnId)) {\n return row._uniqueValuesCache[columnId]\n }\n\n const column = table.getColumn(columnId)\n\n if (!column?.accessorFn) {\n return undefined\n }\n\n if (!column.columnDef.getUniqueValues) {\n row._uniqueValuesCache[columnId] = [row.getValue(columnId)]\n return row._uniqueValuesCache[columnId]\n }\n\n row._uniqueValuesCache[columnId] = column.columnDef.getUniqueValues(\n row.original as TData,\n rowIndex\n )\n\n return row._uniqueValuesCache[columnId] as any\n },\n renderValue: columnId =>\n row.getValue(columnId) ?? table.options.renderFallbackValue,\n subRows: subRows ?? [],\n getLeafRows: () => flattenBy(row.subRows, d => d.subRows),\n getParentRow: () => (row.parentId ? table.getRow(row.parentId) : undefined),\n getParentRows: () => {\n let parentRows: Row[] = []\n let currentRow = row\n while (true) {\n const parentRow = currentRow.getParentRow()\n if (!parentRow) break\n parentRows.push(parentRow)\n currentRow = parentRow\n }\n return parentRows.reverse()\n },\n getAllCells: memo(\n () => [table.getAllLeafColumns()],\n leafColumns => {\n return leafColumns.map(column => {\n return createCell(table, row as Row, column, column.id)\n })\n },\n {\n key: process.env.NODE_ENV === 'development' && 'row.getAllCells',\n debug: () => table.options.debugAll ?? table.options.debugRows,\n }\n ),\n\n _getAllCellsByColumnId: memo(\n () => [row.getAllCells()],\n allCells => {\n return allCells.reduce((acc, cell) => {\n acc[cell.column.id] = cell\n return acc\n }, {} as Record>)\n },\n {\n key:\n process.env.NODE_ENV === 'production' && 'row.getAllCellsByColumnId',\n debug: () => table.options.debugAll ?? table.options.debugRows,\n }\n ),\n }\n\n for (let i = 0; i < table._features.length; i++) {\n const feature = table._features[i]\n Object.assign(row, feature?.createRow?.(row, table))\n }\n\n return row as Row\n}\n", "import {\n AccessorFn,\n ColumnDef,\n DisplayColumnDef,\n GroupColumnDef,\n IdentifiedColumnDef,\n RowData,\n} from './types'\nimport { DeepKeys, DeepValue, RequiredKeys } 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 = 'nested.foo.0.bar'\n// const test2: DeepKeys = 'nested.bar'\n\n// const helper = createColumnHelper()\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 = {\n accessor: <\n TAccessor extends AccessorFn | DeepKeys,\n TValue extends TAccessor extends AccessorFn\n ? TReturn\n : TAccessor extends DeepKeys\n ? DeepValue\n : never\n >(\n accessor: TAccessor,\n column: TAccessor extends AccessorFn\n ? DisplayColumnDef\n : IdentifiedColumnDef\n ) => ColumnDef\n display: (column: DisplayColumnDef) => ColumnDef\n group: (column: GroupColumnDef) => ColumnDef\n}\n\nexport function createColumnHelper<\n TData extends RowData\n>(): ColumnHelper {\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 as ColumnDef,\n group: column => column as ColumnDef,\n }\n}\n", "import { createRow } from '../core/row'\nimport { Table, Row, RowModel, RowData } from '../types'\nimport { memo } from '../utils'\n\nexport function getCoreRowModel(): (\n table: Table\n) => () => RowModel {\n return table =>\n memo(\n () => [table.options.data],\n (\n data\n ): {\n rows: Row[]\n flatRows: Row[]\n rowsById: Record>\n } => {\n const rowModel: RowModel = {\n rows: [],\n flatRows: [],\n rowsById: {},\n }\n\n const accessRows = (\n originalRows: TData[],\n depth = 0,\n parentRow?: Row\n ): Row[] => {\n const rows = [] as Row[]\n\n for (let i = 0; i < originalRows.length; i++) {\n // This could be an expensive check at scale, so we should move it somewhere else, but where?\n // if (!id) {\n // if (process.env.NODE_ENV !== 'production') {\n // throw new Error(`getRowId expected an ID, but got ${id}`)\n // }\n // }\n\n // Make the row\n const row = createRow(\n table,\n table._getRowId(originalRows[i]!, i, parentRow),\n originalRows[i]!,\n i,\n depth,\n undefined,\n parentRow?.id\n )\n\n // Keep track of every row in a flat array\n rowModel.flatRows.push(row)\n // Also keep track of every row by its ID\n rowModel.rowsById[row.id] = row\n // Push table row into parent\n rows.push(row)\n\n // Get the original subrows\n if (table.options.getSubRows) {\n row.originalSubRows = table.options.getSubRows(\n originalRows[i]!,\n i\n )\n\n // Then recursively access them\n if (row.originalSubRows?.length) {\n row.subRows = accessRows(row.originalSubRows, depth + 1, row)\n }\n }\n }\n\n return rows\n }\n\n rowModel.rows = accessRows(data)\n\n return rowModel\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n onChange: () => {\n table._autoResetPageIndex()\n },\n }\n )\n}\n", "import { createRow } from '../core/row'\nimport { Row, RowModel, Table, RowData } from '../types'\n\nexport function filterRows(\n rows: Row[],\n filterRowImpl: (row: Row) => any,\n table: Table\n) {\n if (table.options.filterFromLeafRows) {\n return filterRowModelFromLeafs(rows, filterRowImpl, table)\n }\n\n return filterRowModelFromRoot(rows, filterRowImpl, table)\n}\n\nexport function filterRowModelFromLeafs(\n rowsToFilter: Row[],\n filterRow: (row: Row) => Row[],\n table: Table\n): RowModel {\n const newFilteredFlatRows: Row[] = []\n const newFilteredRowsById: Record> = {}\n const maxDepth = table.options.maxLeafRowFilterDepth ?? 100\n\n const recurseFilterRows = (rowsToFilter: Row[], depth = 0) => {\n const rows: Row[] = []\n\n // Filter from children up first\n for (let i = 0; i < rowsToFilter.length; i++) {\n let row = rowsToFilter[i]!\n\n const newRow = createRow(\n table,\n row.id,\n row.original,\n row.index,\n row.depth,\n undefined,\n row.parentId\n )\n newRow.columnFilters = row.columnFilters\n\n if (row.subRows?.length && depth < maxDepth) {\n newRow.subRows = recurseFilterRows(row.subRows, depth + 1)\n row = newRow\n\n if (filterRow(row) && !newRow.subRows.length) {\n rows.push(row)\n newFilteredRowsById[row.id] = row\n newFilteredRowsById[i] = row\n continue\n }\n\n if (filterRow(row) || newRow.subRows.length) {\n rows.push(row)\n newFilteredRowsById[row.id] = row\n newFilteredRowsById[i] = row\n continue\n }\n } else {\n row = newRow\n if (filterRow(row)) {\n rows.push(row)\n newFilteredRowsById[row.id] = row\n newFilteredRowsById[i] = row\n }\n }\n }\n\n return rows\n }\n\n return {\n rows: recurseFilterRows(rowsToFilter),\n flatRows: newFilteredFlatRows,\n rowsById: newFilteredRowsById,\n }\n}\n\nexport function filterRowModelFromRoot(\n rowsToFilter: Row[],\n filterRow: (row: Row) => any,\n table: Table\n): RowModel {\n const newFilteredFlatRows: Row[] = []\n const newFilteredRowsById: Record> = {}\n const maxDepth = table.options.maxLeafRowFilterDepth ?? 100\n\n // Filters top level and nested rows\n const recurseFilterRows = (rowsToFilter: Row[], depth = 0) => {\n // Filter from parents downward first\n\n const rows: Row[] = []\n\n // Apply the filter to any subRows\n for (let i = 0; i < rowsToFilter.length; i++) {\n let row = rowsToFilter[i]!\n\n const pass = filterRow(row)\n\n if (pass) {\n if (row.subRows?.length && depth < maxDepth) {\n const newRow = createRow(\n table,\n row.id,\n row.original,\n row.index,\n row.depth,\n undefined,\n row.parentId\n )\n newRow.subRows = recurseFilterRows(row.subRows, depth + 1)\n row = newRow\n }\n\n rows.push(row)\n newFilteredFlatRows.push(row)\n newFilteredRowsById[row.id] = row\n }\n }\n\n return rows\n }\n\n return {\n rows: recurseFilterRows(rowsToFilter),\n flatRows: newFilteredFlatRows,\n rowsById: newFilteredRowsById,\n }\n}\n", "import { ResolvedColumnFilter } from '../features/Filters'\nimport { Table, RowModel, Row, RowData } from '../types'\nimport { memo } from '../utils'\nimport { filterRows } from './filterRowsUtils'\n\nexport function getFilteredRowModel(): (\n table: Table\n) => () => RowModel {\n return table =>\n memo(\n () => [\n table.getPreFilteredRowModel(),\n table.getState().columnFilters,\n table.getState().globalFilter,\n ],\n (rowModel, columnFilters, globalFilter) => {\n if (\n !rowModel.rows.length ||\n (!columnFilters?.length && !globalFilter)\n ) {\n for (let i = 0; i < rowModel.flatRows.length; i++) {\n rowModel.flatRows[i]!.columnFilters = {}\n rowModel.flatRows[i]!.columnFiltersMeta = {}\n }\n return rowModel\n }\n\n const resolvedColumnFilters: ResolvedColumnFilter[] = []\n const resolvedGlobalFilters: ResolvedColumnFilter[] = []\n\n ;(columnFilters ?? []).forEach(d => {\n const column = table.getColumn(d.id)\n\n if (!column) {\n return\n }\n\n const filterFn = column.getFilterFn()\n\n if (!filterFn) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `Could not find a valid 'column.filterFn' for column with the ID: ${column.id}.`\n )\n }\n return\n }\n\n resolvedColumnFilters.push({\n id: d.id,\n filterFn,\n resolvedValue: filterFn.resolveFilterValue?.(d.value) ?? d.value,\n })\n })\n\n const filterableIds = columnFilters.map(d => d.id)\n\n const globalFilterFn = table.getGlobalFilterFn()\n\n const globallyFilterableColumns = table\n .getAllLeafColumns()\n .filter(column => column.getCanGlobalFilter())\n\n if (\n globalFilter &&\n globalFilterFn &&\n globallyFilterableColumns.length\n ) {\n filterableIds.push('__global__')\n\n globallyFilterableColumns.forEach(column => {\n resolvedGlobalFilters.push({\n id: column.id,\n filterFn: globalFilterFn,\n resolvedValue:\n globalFilterFn.resolveFilterValue?.(globalFilter) ??\n globalFilter,\n })\n })\n }\n\n let currentColumnFilter\n let currentGlobalFilter\n\n // Flag the prefiltered row model with each filter state\n for (let j = 0; j < rowModel.flatRows.length; j++) {\n const row = rowModel.flatRows[j]!\n\n row.columnFilters = {}\n\n if (resolvedColumnFilters.length) {\n for (let i = 0; i < resolvedColumnFilters.length; i++) {\n currentColumnFilter = resolvedColumnFilters[i]!\n const id = currentColumnFilter.id\n\n // Tag the row with the column filter state\n row.columnFilters[id] = currentColumnFilter.filterFn(\n row,\n id,\n currentColumnFilter.resolvedValue,\n filterMeta => {\n row.columnFiltersMeta[id] = filterMeta\n }\n )\n }\n }\n\n if (resolvedGlobalFilters.length) {\n for (let i = 0; i < resolvedGlobalFilters.length; i++) {\n currentGlobalFilter = resolvedGlobalFilters[i]!\n const id = currentGlobalFilter.id\n // Tag the row with the first truthy global filter state\n if (\n currentGlobalFilter.filterFn(\n row,\n id,\n currentGlobalFilter.resolvedValue,\n filterMeta => {\n row.columnFiltersMeta[id] = filterMeta\n }\n )\n ) {\n row.columnFilters.__global__ = true\n break\n }\n }\n\n if (row.columnFilters.__global__ !== true) {\n row.columnFilters.__global__ = false\n }\n }\n }\n\n const filterRowsImpl = (row: Row) => {\n // Horizontally filter rows through each column\n for (let i = 0; i < filterableIds.length; i++) {\n if (row.columnFilters[filterableIds[i]!] === false) {\n return false\n }\n }\n return true\n }\n\n // Filter final rows using all of the active filters\n return filterRows(rowModel.rows, filterRowsImpl, table)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getFilteredRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n onChange: () => {\n table._autoResetPageIndex()\n },\n }\n )\n}\n", "import { Table, RowModel, Row, RowData } from '../types'\nimport { memo } from '../utils'\nimport { filterRows } from './filterRowsUtils'\n\nexport function getFacetedRowModel(): (\n table: Table,\n columnId: string\n) => () => RowModel {\n return (table, columnId) =>\n memo(\n () => [\n table.getPreFilteredRowModel(),\n table.getState().columnFilters,\n table.getState().globalFilter,\n table.getFilteredRowModel(),\n ],\n (preRowModel, columnFilters, globalFilter) => {\n if (\n !preRowModel.rows.length ||\n (!columnFilters?.length && !globalFilter)\n ) {\n return preRowModel\n }\n\n const filterableIds = [\n ...columnFilters.map(d => d.id).filter(d => d !== columnId),\n globalFilter ? '__global__' : undefined,\n ].filter(Boolean) as string[]\n\n const filterRowsImpl = (row: Row) => {\n // Horizontally filter rows through each column\n for (let i = 0; i < filterableIds.length; i++) {\n if (row.columnFilters[filterableIds[i]!] === false) {\n return false\n }\n }\n return true\n }\n\n return filterRows(preRowModel.rows, filterRowsImpl, table)\n },\n {\n key:\n process.env.NODE_ENV === 'development' &&\n 'getFacetedRowModel_' + columnId,\n debug: () => table.options.debugAll ?? table.options.debugTable,\n onChange: () => {},\n }\n )\n}\n", "import { Table, RowData } from '../types'\nimport { memo } from '../utils'\n\nexport function getFacetedUniqueValues(): (\n table: Table,\n columnId: string\n) => () => Map {\n return (table, columnId) =>\n memo(\n () => [table.getColumn(columnId)?.getFacetedRowModel()],\n facetedRowModel => {\n if (!facetedRowModel) return new Map()\n\n let facetedUniqueValues = new Map()\n\n for (let i = 0; i < facetedRowModel.flatRows.length; i++) {\n const values =\n facetedRowModel.flatRows[i]!.getUniqueValues(columnId)\n\n for (let j = 0; j < values.length; j++) {\n const value = values[j]!\n\n if (facetedUniqueValues.has(value)) {\n facetedUniqueValues.set(\n value,\n (facetedUniqueValues.get(value) ?? 0) + 1\n )\n } else {\n facetedUniqueValues.set(value, 1)\n }\n }\n }\n\n return facetedUniqueValues\n },\n {\n key:\n process.env.NODE_ENV === 'development' &&\n 'getFacetedUniqueValues_' + columnId,\n debug: () => table.options.debugAll ?? table.options.debugTable,\n onChange: () => {},\n }\n )\n}\n", "import { Table, RowData } from '../types'\nimport { memo } from '../utils'\n\nexport function getFacetedMinMaxValues(): (\n table: Table,\n columnId: string\n) => () => undefined | [number, number] {\n return (table, columnId) =>\n memo(\n () => [table.getColumn(columnId)?.getFacetedRowModel()],\n facetedRowModel => {\n if (!facetedRowModel) return undefined\n\n const firstValue =\n facetedRowModel.flatRows[0]?.getUniqueValues(columnId)\n\n if (typeof firstValue === 'undefined') {\n return undefined\n }\n\n let facetedMinMaxValues: [any, any] = [firstValue, firstValue]\n\n for (let i = 0; i < facetedRowModel.flatRows.length; i++) {\n const values =\n facetedRowModel.flatRows[i]!.getUniqueValues(columnId)\n\n for (let j = 0; j < values.length; j++) {\n const value = values[j]!\n\n if (value < facetedMinMaxValues[0]) {\n facetedMinMaxValues[0] = value\n } else if (value > facetedMinMaxValues[1]) {\n facetedMinMaxValues[1] = value\n }\n }\n }\n\n return facetedMinMaxValues\n },\n {\n key:\n process.env.NODE_ENV === 'development' &&\n 'getFacetedMinMaxValues_' + columnId,\n debug: () => table.options.debugAll ?? table.options.debugTable,\n onChange: () => {},\n }\n )\n}\n", "import { Table, Row, RowModel, RowData } from '../types'\nimport { SortingFn } from '../features/Sorting'\nimport { memo } from '../utils'\n\nexport function getSortedRowModel(): (\n table: Table\n) => () => RowModel {\n return table =>\n memo(\n () => [table.getState().sorting, table.getPreSortedRowModel()],\n (sorting, rowModel) => {\n if (!rowModel.rows.length || !sorting?.length) {\n return rowModel\n }\n\n const sortingState = table.getState().sorting\n\n const sortedFlatRows: Row[] = []\n\n // Filter out sortings that correspond to non existing columns\n const availableSorting = sortingState.filter(sort =>\n table.getColumn(sort.id)?.getCanSort()\n )\n\n const columnInfoById: Record<\n string,\n {\n sortUndefined?: false | -1 | 1\n invertSorting?: boolean\n sortingFn: SortingFn\n }\n > = {}\n\n availableSorting.forEach(sortEntry => {\n const column = table.getColumn(sortEntry.id)\n if (!column) return\n\n columnInfoById[sortEntry.id] = {\n sortUndefined: column.columnDef.sortUndefined,\n invertSorting: column.columnDef.invertSorting,\n sortingFn: column.getSortingFn(),\n }\n })\n\n const sortData = (rows: Row[]) => {\n // This will also perform a stable sorting using the row index\n // if needed.\n const sortedData = [...rows]\n\n sortedData.sort((rowA, rowB) => {\n for (let i = 0; i < availableSorting.length; i += 1) {\n const sortEntry = availableSorting[i]!\n const columnInfo = columnInfoById[sortEntry.id]!\n const isDesc = sortEntry?.desc ?? false\n\n let sortInt = 0\n\n // All sorting ints should always return in ascending order\n if (columnInfo.sortUndefined) {\n const aValue = rowA.getValue(sortEntry.id)\n const bValue = rowB.getValue(sortEntry.id)\n\n const aUndefined = aValue === undefined\n const bUndefined = bValue === undefined\n\n if (aUndefined || bUndefined) {\n sortInt =\n aUndefined && bUndefined\n ? 0\n : aUndefined\n ? columnInfo.sortUndefined\n : -columnInfo.sortUndefined\n }\n }\n\n if (sortInt === 0) {\n sortInt = columnInfo.sortingFn(rowA, rowB, sortEntry.id)\n }\n\n // If sorting is non-zero, take care of desc and inversion\n if (sortInt !== 0) {\n if (isDesc) {\n sortInt *= -1\n }\n\n if (columnInfo.invertSorting) {\n sortInt *= -1\n }\n\n return sortInt\n }\n }\n\n return rowA.index - rowB.index\n })\n\n // If there are sub-rows, sort them\n sortedData.forEach(row => {\n sortedFlatRows.push(row)\n if (row.subRows?.length) {\n row.subRows = sortData(row.subRows)\n }\n })\n\n return sortedData\n }\n\n return {\n rows: sortData(rowModel.rows),\n flatRows: sortedFlatRows,\n rowsById: rowModel.rowsById,\n }\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getSortedRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n onChange: () => {\n table._autoResetPageIndex()\n },\n }\n )\n}\n", "import { createRow } from '../core/row'\nimport { Table, Row, RowModel, RowData } from '../types'\nimport { flattenBy, memo } from '../utils'\n\nexport function getGroupedRowModel(): (\n table: Table\n) => () => RowModel {\n return table =>\n memo(\n () => [table.getState().grouping, table.getPreGroupedRowModel()],\n (grouping, rowModel) => {\n if (!rowModel.rows.length || !grouping.length) {\n return rowModel\n }\n\n // Filter the grouping list down to columns that exist\n const existingGrouping = grouping.filter(columnId =>\n table.getColumn(columnId)\n )\n\n const groupedFlatRows: Row[] = []\n const groupedRowsById: Record> = {}\n // const onlyGroupedFlatRows: Row[] = [];\n // const onlyGroupedRowsById: Record = {};\n // const nonGroupedFlatRows: Row[] = [];\n // const nonGroupedRowsById: Record = {};\n\n // Recursively group the data\n const groupUpRecursively = (\n rows: Row[],\n depth = 0,\n parentId?: string\n ) => {\n // Grouping depth has been been met\n // Stop grouping and simply rewrite thd depth and row relationships\n if (depth >= existingGrouping.length) {\n return rows.map(row => {\n row.depth = depth\n\n groupedFlatRows.push(row)\n groupedRowsById[row.id] = row\n\n if (row.subRows) {\n row.subRows = groupUpRecursively(row.subRows, depth + 1, row.id)\n }\n\n return row\n })\n }\n\n const columnId: string = existingGrouping[depth]!\n\n // Group the rows together for this level\n const rowGroupsMap = groupBy(rows, columnId)\n\n // Peform aggregations for each group\n const aggregatedGroupedRows = Array.from(rowGroupsMap.entries()).map(\n ([groupingValue, groupedRows], index) => {\n let id = `${columnId}:${groupingValue}`\n id = parentId ? `${parentId}>${id}` : id\n\n // First, Recurse to group sub rows before aggregation\n const subRows = groupUpRecursively(groupedRows, depth + 1, id)\n\n // Flatten the leaf rows of the rows in this group\n const leafRows = depth\n ? flattenBy(groupedRows, row => row.subRows)\n : groupedRows\n\n const row = createRow(\n table,\n id,\n leafRows[0]!.original,\n index,\n depth,\n undefined,\n parentId\n )\n\n Object.assign(row, {\n groupingColumnId: columnId,\n groupingValue,\n subRows,\n leafRows,\n getValue: (columnId: string) => {\n // Don't aggregate columns that are in the grouping\n if (existingGrouping.includes(columnId)) {\n if (row._valuesCache.hasOwnProperty(columnId)) {\n return row._valuesCache[columnId]\n }\n\n if (groupedRows[0]) {\n row._valuesCache[columnId] =\n groupedRows[0].getValue(columnId) ?? undefined\n }\n\n return row._valuesCache[columnId]\n }\n\n if (row._groupingValuesCache.hasOwnProperty(columnId)) {\n return row._groupingValuesCache[columnId]\n }\n\n // Aggregate the values\n const column = table.getColumn(columnId)\n const aggregateFn = column?.getAggregationFn()\n\n if (aggregateFn) {\n row._groupingValuesCache[columnId] = aggregateFn(\n columnId,\n leafRows,\n groupedRows\n )\n\n return row._groupingValuesCache[columnId]\n }\n },\n })\n\n subRows.forEach(subRow => {\n groupedFlatRows.push(subRow)\n groupedRowsById[subRow.id] = subRow\n // if (subRow.getIsGrouped?.()) {\n // onlyGroupedFlatRows.push(subRow);\n // onlyGroupedRowsById[subRow.id] = subRow;\n // } else {\n // nonGroupedFlatRows.push(subRow);\n // nonGroupedRowsById[subRow.id] = subRow;\n // }\n })\n\n return row\n }\n )\n\n return aggregatedGroupedRows\n }\n\n const groupedRows = groupUpRecursively(rowModel.rows, 0)\n\n groupedRows.forEach(subRow => {\n groupedFlatRows.push(subRow)\n groupedRowsById[subRow.id] = subRow\n // if (subRow.getIsGrouped?.()) {\n // onlyGroupedFlatRows.push(subRow);\n // onlyGroupedRowsById[subRow.id] = subRow;\n // } else {\n // nonGroupedFlatRows.push(subRow);\n // nonGroupedRowsById[subRow.id] = subRow;\n // }\n })\n\n return {\n rows: groupedRows,\n flatRows: groupedFlatRows,\n rowsById: groupedRowsById,\n }\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getGroupedRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n onChange: () => {\n table._queue(() => {\n table._autoResetExpanded()\n table._autoResetPageIndex()\n })\n },\n }\n )\n}\n\nfunction groupBy(rows: Row[], columnId: string) {\n const groupMap = new Map[]>()\n\n return rows.reduce((map, row) => {\n const resKey = `${row.getGroupingValue(columnId)}`\n const previous = map.get(resKey)\n if (!previous) {\n map.set(resKey, [row])\n } else {\n previous.push(row)\n }\n return map\n }, groupMap)\n}\n", "import { Table, Row, RowModel, RowData } from '../types'\nimport { memo } from '../utils'\n\nexport function getExpandedRowModel(): (\n table: Table\n) => () => RowModel {\n return table =>\n memo(\n () => [\n table.getState().expanded,\n table.getPreExpandedRowModel(),\n table.options.paginateExpandedRows,\n ],\n (expanded, rowModel, paginateExpandedRows) => {\n if (\n !rowModel.rows.length ||\n (expanded !== true && !Object.keys(expanded ?? {}).length)\n ) {\n return rowModel\n }\n\n if (!paginateExpandedRows) {\n // Only expand rows at this point if they are being paginated\n return rowModel\n }\n\n return expandRows(rowModel)\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getExpandedRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n }\n )\n}\n\nexport function expandRows(rowModel: RowModel) {\n const expandedRows: Row[] = []\n\n const handleRow = (row: Row) => {\n expandedRows.push(row)\n\n if (row.subRows?.length && row.getIsExpanded()) {\n row.subRows.forEach(handleRow)\n }\n }\n\n rowModel.rows.forEach(handleRow)\n\n return {\n rows: expandedRows,\n flatRows: rowModel.flatRows,\n rowsById: rowModel.rowsById,\n }\n}\n", "import { Table, RowModel, Row, RowData } from '../types'\nimport { memo } from '../utils'\nimport { expandRows } from './getExpandedRowModel'\n\nexport function getPaginationRowModel(opts?: {\n initialSync: boolean\n}): (table: Table) => () => RowModel {\n return table =>\n memo(\n () => [\n table.getState().pagination,\n table.getPrePaginationRowModel(),\n table.options.paginateExpandedRows\n ? undefined\n : table.getState().expanded,\n ],\n (pagination, rowModel) => {\n if (!rowModel.rows.length) {\n return rowModel\n }\n\n const { pageSize, pageIndex } = pagination\n let { rows, flatRows, rowsById } = rowModel\n const pageStart = pageSize * pageIndex\n const pageEnd = pageStart + pageSize\n\n rows = rows.slice(pageStart, pageEnd)\n\n let paginatedRowModel: RowModel\n\n if (!table.options.paginateExpandedRows) {\n paginatedRowModel = expandRows({\n rows,\n flatRows,\n rowsById,\n })\n } else {\n paginatedRowModel = {\n rows,\n flatRows,\n rowsById,\n }\n }\n\n paginatedRowModel.flatRows = []\n\n const handleRow = (row: Row) => {\n paginatedRowModel.flatRows.push(row)\n if (row.subRows.length) {\n row.subRows.forEach(handleRow)\n }\n }\n\n paginatedRowModel.rows.forEach(handleRow)\n\n return paginatedRowModel\n },\n {\n key: process.env.NODE_ENV === 'development' && 'getPaginationRowModel',\n debug: () => table.options.debugAll ?? table.options.debugTable,\n }\n )\n}\n", "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 = React.ReactNode | React.ComponentType\n\n//\n\nexport function flexRender(\n Comp: Renderable,\n props: TProps\n): React.ReactNode | JSX.Element {\n return !Comp ? null : isReactComponent(Comp) ? (\n \n ) : (\n Comp\n )\n}\n\nfunction isReactComponent(\n component: unknown\n): component is React.ComponentType {\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(\n options: TableOptions\n) {\n // Compose in the generic options to the user options\n const resolvedOptions: TableOptionsResolved = {\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(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", "/**\n * react-virtual\n *\n * Copyright (c) TanStack\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\nexport { _extends as extends };\n//# sourceMappingURL=_rollupPluginBabelHelpers.mjs.map\n", "/**\n * virtual-core\n *\n * Copyright (c) TanStack\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\nexport { _extends as extends };\n//# sourceMappingURL=_rollupPluginBabelHelpers.mjs.map\n", "export type NoInfer = [A][A extends any ? 0 : never]\n\nexport type PartialKeys = Omit & Partial>\n\nexport function memo(\n getDeps: () => [...TDeps],\n fn: (...args: NoInfer<[...TDeps]>) => TResult,\n opts: {\n key: false | string\n debug?: () => any\n onChange?: (result: TResult) => void\n initialDeps?: TDeps\n },\n) {\n let deps = opts.initialDeps ?? []\n let result: TResult | undefined\n\n return (): TResult => {\n let depTime: number\n if (opts.key && opts.debug?.()) depTime = Date.now()\n\n const newDeps = getDeps()\n\n const depsChanged =\n newDeps.length !== deps.length ||\n newDeps.some((dep: any, index: number) => deps[index] !== dep)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n let resultTime: number\n if (opts.key && opts.debug?.()) resultTime = Date.now()\n\n result = fn(...newDeps)\n\n if (opts.key && opts.debug?.()) {\n const depEndTime = Math.round((Date.now() - depTime!) * 100) / 100\n const resultEndTime = Math.round((Date.now() - resultTime!) * 100) / 100\n const resultFpsPercentage = resultEndTime / 16\n\n const pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n }\n\n console.info(\n `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,\n `\n font-size: .6rem;\n font-weight: bold;\n color: hsl(${Math.max(\n 0,\n Math.min(120 - 120 * resultFpsPercentage, 120),\n )}deg 100% 31%);`,\n opts?.key,\n )\n }\n\n opts?.onChange?.(result)\n\n return result!\n }\n}\n\nexport function notUndefined(value: T | undefined, msg?: string): T {\n if (value === undefined) {\n throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ''}`)\n } else {\n return value\n }\n}\n\nexport const approxEqual = (a: number, b: number) => Math.abs(a - b) < 1\n", "import { approxEqual, memo, notUndefined } from './utils'\n\nexport * from './utils'\n\n//\n\ntype ScrollDirection = 'forward' | 'backward'\n\ntype ScrollAlignment = 'start' | 'center' | 'end' | 'auto'\n\ntype ScrollBehavior = 'auto' | 'smooth'\n\nexport interface ScrollToOptions {\n align?: ScrollAlignment\n behavior?: ScrollBehavior\n}\n\ntype ScrollToOffsetOptions = ScrollToOptions\n\ntype ScrollToIndexOptions = ScrollToOptions\n\nexport interface Range {\n startIndex: number\n endIndex: number\n overscan: number\n count: number\n}\n\ntype Key = number | string\n\nexport interface VirtualItem {\n key: Key\n index: number\n start: number\n end: number\n size: number\n lane: number\n}\n\ninterface Rect {\n width: number\n height: number\n}\n\n//\n\nexport const defaultKeyExtractor = (index: number) => index\n\nexport const defaultRangeExtractor = (range: Range) => {\n const start = Math.max(range.startIndex - range.overscan, 0)\n const end = Math.min(range.endIndex + range.overscan, range.count - 1)\n\n const arr = []\n\n for (let i = start; i <= end; i++) {\n arr.push(i)\n }\n\n return arr\n}\n\nexport const observeElementRect = (\n instance: Virtualizer,\n cb: (rect: Rect) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n\n const handler = (rect: Rect) => {\n const { width, height } = rect\n cb({ width: Math.round(width), height: Math.round(height) })\n }\n\n handler(element.getBoundingClientRect())\n\n const observer = new ResizeObserver((entries) => {\n const entry = entries[0]\n if (entry?.borderBoxSize) {\n const box = entry.borderBoxSize[0]\n if (box) {\n handler({ width: box.inlineSize, height: box.blockSize })\n return\n }\n }\n handler(element.getBoundingClientRect())\n })\n\n observer.observe(element, { box: 'border-box' })\n\n return () => {\n observer.unobserve(element)\n }\n}\n\nexport const observeWindowRect = (\n instance: Virtualizer,\n cb: (rect: Rect) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n\n const handler = () => {\n cb({ width: element.innerWidth, height: element.innerHeight })\n }\n handler()\n\n element.addEventListener('resize', handler, {\n passive: true,\n })\n\n return () => {\n element.removeEventListener('resize', handler)\n }\n}\n\nexport const observeElementOffset = (\n instance: Virtualizer,\n cb: (offset: number) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n\n const handler = () => {\n cb(element[instance.options.horizontal ? 'scrollLeft' : 'scrollTop'])\n }\n handler()\n\n element.addEventListener('scroll', handler, {\n passive: true,\n })\n\n return () => {\n element.removeEventListener('scroll', handler)\n }\n}\n\nexport const observeWindowOffset = (\n instance: Virtualizer,\n cb: (offset: number) => void,\n) => {\n const element = instance.scrollElement\n if (!element) {\n return\n }\n\n const handler = () => {\n cb(element[instance.options.horizontal ? 'scrollX' : 'scrollY'])\n }\n handler()\n\n element.addEventListener('scroll', handler, {\n passive: true,\n })\n\n return () => {\n element.removeEventListener('scroll', handler)\n }\n}\n\nexport const measureElement = (\n element: TItemElement,\n entry: ResizeObserverEntry | undefined,\n instance: Virtualizer,\n) => {\n if (entry?.borderBoxSize) {\n const box = entry.borderBoxSize[0]\n if (box) {\n const size = Math.round(\n box[instance.options.horizontal ? 'inlineSize' : 'blockSize'],\n )\n return size\n }\n }\n return Math.round(\n element.getBoundingClientRect()[\n instance.options.horizontal ? 'width' : 'height'\n ],\n )\n}\n\nexport const windowScroll = (\n offset: number,\n {\n adjustments = 0,\n behavior,\n }: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer,\n) => {\n const toOffset = offset + adjustments\n\n instance.scrollElement?.scrollTo?.({\n [instance.options.horizontal ? 'left' : 'top']: toOffset,\n behavior,\n })\n}\n\nexport const elementScroll = (\n offset: number,\n {\n adjustments = 0,\n behavior,\n }: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer,\n) => {\n const toOffset = offset + adjustments\n\n instance.scrollElement?.scrollTo?.({\n [instance.options.horizontal ? 'left' : 'top']: toOffset,\n behavior,\n })\n}\n\nexport interface VirtualizerOptions<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n> {\n // Required from the user\n count: number\n getScrollElement: () => TScrollElement | null\n estimateSize: (index: number) => number\n\n // Required from the framework adapter (but can be overridden)\n scrollToFn: (\n offset: number,\n options: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer,\n ) => void\n observeElementRect: (\n instance: Virtualizer,\n cb: (rect: Rect) => void,\n ) => void | (() => void)\n observeElementOffset: (\n instance: Virtualizer,\n cb: (offset: number) => void,\n ) => void | (() => void)\n\n // Optional\n debug?: any\n initialRect?: Rect\n onChange?: (instance: Virtualizer) => void\n measureElement?: (\n element: TItemElement,\n entry: ResizeObserverEntry | undefined,\n instance: Virtualizer,\n ) => number\n overscan?: number\n horizontal?: boolean\n paddingStart?: number\n paddingEnd?: number\n scrollPaddingStart?: number\n scrollPaddingEnd?: number\n initialOffset?: number\n getItemKey?: (index: number) => Key\n rangeExtractor?: (range: Range) => number[]\n scrollMargin?: number\n scrollingDelay?: number\n indexAttribute?: string\n initialMeasurementsCache?: VirtualItem[]\n lanes?: number\n}\n\nexport class Virtualizer<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n> {\n private unsubs: (void | (() => void))[] = []\n options!: Required>\n scrollElement: TScrollElement | null = null\n isScrolling: boolean = false\n private isScrollingTimeoutId: ReturnType | null = null\n private scrollToIndexTimeoutId: ReturnType | null = null\n measurementsCache: VirtualItem[] = []\n private itemSizeCache = new Map()\n private pendingMeasuredCacheIndexes: number[] = []\n private scrollRect: Rect\n scrollOffset: number\n scrollDirection: ScrollDirection | null = null\n private scrollAdjustments: number = 0\n measureElementCache = new Map()\n private observer = (() => {\n let _ro: ResizeObserver | null = null\n\n const get = () => {\n if (_ro) {\n return _ro\n } else if (typeof ResizeObserver !== 'undefined') {\n return (_ro = new ResizeObserver((entries) => {\n entries.forEach((entry) => {\n this._measureElement(entry.target as TItemElement, entry)\n })\n }))\n } else {\n return null\n }\n }\n\n return {\n disconnect: () => get()?.disconnect(),\n observe: (target: Element) =>\n get()?.observe(target, { box: 'border-box' }),\n unobserve: (target: Element) => get()?.unobserve(target),\n }\n })()\n range: { startIndex: number; endIndex: number } = {\n startIndex: 0,\n endIndex: 0,\n }\n\n constructor(opts: VirtualizerOptions) {\n this.setOptions(opts)\n this.scrollRect = this.options.initialRect\n this.scrollOffset = this.options.initialOffset\n this.measurementsCache = this.options.initialMeasurementsCache\n this.measurementsCache.forEach((item) => {\n this.itemSizeCache.set(item.key, item.size)\n })\n\n this.maybeNotify()\n }\n\n setOptions = (opts: VirtualizerOptions) => {\n Object.entries(opts).forEach(([key, value]) => {\n if (typeof value === 'undefined') delete (opts as any)[key]\n })\n\n this.options = {\n debug: false,\n initialOffset: 0,\n overscan: 1,\n paddingStart: 0,\n paddingEnd: 0,\n scrollPaddingStart: 0,\n scrollPaddingEnd: 0,\n horizontal: false,\n getItemKey: defaultKeyExtractor,\n rangeExtractor: defaultRangeExtractor,\n onChange: () => {},\n measureElement,\n initialRect: { width: 0, height: 0 },\n scrollMargin: 0,\n scrollingDelay: 150,\n indexAttribute: 'data-index',\n initialMeasurementsCache: [],\n lanes: 1,\n ...opts,\n }\n }\n\n private notify = () => {\n this.options.onChange?.(this)\n }\n\n private cleanup = () => {\n this.unsubs.filter(Boolean).forEach((d) => d!())\n this.unsubs = []\n this.scrollElement = null\n }\n\n _didMount = () => {\n this.measureElementCache.forEach(this.observer.observe)\n return () => {\n this.observer.disconnect()\n this.cleanup()\n }\n }\n\n _willUpdate = () => {\n const scrollElement = this.options.getScrollElement()\n\n if (this.scrollElement !== scrollElement) {\n this.cleanup()\n\n this.scrollElement = scrollElement\n\n this._scrollToOffset(this.scrollOffset, {\n adjustments: undefined,\n behavior: undefined,\n })\n\n this.unsubs.push(\n this.options.observeElementRect(this, (rect) => {\n const prev = this.scrollRect\n this.scrollRect = rect\n if (\n this.options.horizontal\n ? rect.width !== prev.width\n : rect.height !== prev.height\n ) {\n this.maybeNotify()\n }\n }),\n )\n\n this.unsubs.push(\n this.options.observeElementOffset(this, (offset) => {\n this.scrollAdjustments = 0\n\n if (this.scrollOffset === offset) {\n return\n }\n\n if (this.isScrollingTimeoutId !== null) {\n clearTimeout(this.isScrollingTimeoutId)\n this.isScrollingTimeoutId = null\n }\n\n this.isScrolling = true\n this.scrollDirection =\n this.scrollOffset < offset ? 'forward' : 'backward'\n this.scrollOffset = offset\n\n this.maybeNotify()\n\n this.isScrollingTimeoutId = setTimeout(() => {\n this.isScrollingTimeoutId = null\n this.isScrolling = false\n this.scrollDirection = null\n\n this.maybeNotify()\n }, this.options.scrollingDelay)\n }),\n )\n }\n }\n\n private getSize = () => {\n return this.scrollRect[this.options.horizontal ? 'width' : 'height']\n }\n\n private memoOptions = memo(\n () => [\n this.options.count,\n this.options.paddingStart,\n this.options.scrollMargin,\n this.options.getItemKey,\n ],\n (count, paddingStart, scrollMargin, getItemKey) => {\n this.pendingMeasuredCacheIndexes = []\n return {\n count,\n paddingStart,\n scrollMargin,\n getItemKey,\n }\n },\n {\n key: false,\n },\n )\n\n private getFurthestMeasurement = (\n measurements: VirtualItem[],\n index: number,\n ) => {\n const furthestMeasurementsFound = new Map()\n const furthestMeasurements = new Map()\n for (let m = index - 1; m >= 0; m--) {\n const measurement = measurements[m]!\n\n if (furthestMeasurementsFound.has(measurement.lane)) {\n continue\n }\n\n const previousFurthestMeasurement = furthestMeasurements.get(\n measurement.lane,\n )\n if (\n previousFurthestMeasurement == null ||\n measurement.end > previousFurthestMeasurement.end\n ) {\n furthestMeasurements.set(measurement.lane, measurement)\n } else if (measurement.end < previousFurthestMeasurement.end) {\n furthestMeasurementsFound.set(measurement.lane, true)\n }\n\n if (furthestMeasurementsFound.size === this.options.lanes) {\n break\n }\n }\n\n return furthestMeasurements.size === this.options.lanes\n ? Array.from(furthestMeasurements.values()).sort(\n (a, b) => a.end - b.end,\n )[0]\n : undefined\n }\n\n private getMeasurements = memo(\n () => [this.memoOptions(), this.itemSizeCache],\n ({ count, paddingStart, scrollMargin, getItemKey }, itemSizeCache) => {\n const min =\n this.pendingMeasuredCacheIndexes.length > 0\n ? Math.min(...this.pendingMeasuredCacheIndexes)\n : 0\n this.pendingMeasuredCacheIndexes = []\n\n const measurements = this.measurementsCache.slice(0, min)\n\n for (let i = min; i < count; i++) {\n const key = getItemKey(i)\n\n const furthestMeasurement =\n this.options.lanes === 1\n ? measurements[i - 1]\n : this.getFurthestMeasurement(measurements, i)\n\n const start = furthestMeasurement\n ? furthestMeasurement.end\n : paddingStart + scrollMargin\n\n const measuredSize = itemSizeCache.get(key)\n const size =\n typeof measuredSize === 'number'\n ? measuredSize\n : this.options.estimateSize(i)\n\n const end = start + size\n\n const lane = furthestMeasurement\n ? furthestMeasurement.lane\n : i % this.options.lanes\n\n measurements[i] = {\n index: i,\n start,\n size,\n end,\n key,\n lane,\n }\n }\n\n this.measurementsCache = measurements\n\n return measurements\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getMeasurements',\n debug: () => this.options.debug,\n },\n )\n\n calculateRange = memo(\n () => [this.getMeasurements(), this.getSize(), this.scrollOffset],\n (measurements, outerSize, scrollOffset) => {\n return (this.range = calculateRange({\n measurements,\n outerSize,\n scrollOffset,\n }))\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'calculateRange',\n debug: () => this.options.debug,\n },\n )\n\n private maybeNotify = memo(\n () => {\n const range = this.calculateRange()\n\n return [range.startIndex, range.endIndex, this.isScrolling]\n },\n () => {\n this.notify()\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'maybeNotify',\n debug: () => this.options.debug,\n initialDeps: [\n this.range.startIndex,\n this.range.endIndex,\n this.isScrolling,\n ],\n },\n )\n\n private getIndexes = memo(\n () => [\n this.options.rangeExtractor,\n this.calculateRange(),\n this.options.overscan,\n this.options.count,\n ],\n (rangeExtractor, range, overscan, count) => {\n return rangeExtractor({\n ...range,\n overscan,\n count,\n })\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getIndexes',\n debug: () => this.options.debug,\n },\n )\n\n indexFromElement = (node: TItemElement) => {\n const attributeName = this.options.indexAttribute\n const indexStr = node.getAttribute(attributeName)\n\n if (!indexStr) {\n console.warn(\n `Missing attribute name '${attributeName}={index}' on measured element.`,\n )\n return -1\n }\n\n return parseInt(indexStr, 10)\n }\n\n private _measureElement = (\n node: TItemElement,\n entry: ResizeObserverEntry | undefined,\n ) => {\n const index = this.indexFromElement(node)\n\n const item = this.measurementsCache[index]\n if (!item) {\n return\n }\n\n const prevNode = this.measureElementCache.get(item.key)\n\n if (!node.isConnected) {\n this.observer.unobserve(node)\n if (node === prevNode) {\n this.measureElementCache.delete(item.key)\n }\n return\n }\n\n if (prevNode !== node) {\n if (prevNode) {\n this.observer.unobserve(prevNode)\n }\n this.observer.observe(node)\n this.measureElementCache.set(item.key, node)\n }\n\n const measuredItemSize = this.options.measureElement(node, entry, this)\n\n const itemSize = this.itemSizeCache.get(item.key) ?? item.size\n\n const delta = measuredItemSize - itemSize\n\n if (delta !== 0) {\n if (item.start < this.scrollOffset) {\n if (process.env.NODE_ENV !== 'production' && this.options.debug) {\n console.info('correction', delta)\n }\n\n this._scrollToOffset(this.scrollOffset, {\n adjustments: (this.scrollAdjustments += delta),\n behavior: undefined,\n })\n }\n\n this.pendingMeasuredCacheIndexes.push(index)\n\n this.itemSizeCache = new Map(\n this.itemSizeCache.set(item.key, measuredItemSize),\n )\n\n this.notify()\n }\n }\n\n measureElement = (node: TItemElement | null) => {\n if (!node) {\n return\n }\n\n this._measureElement(node, undefined)\n }\n\n getVirtualItems = memo(\n () => [this.getIndexes(), this.getMeasurements()],\n (indexes, measurements) => {\n const virtualItems: VirtualItem[] = []\n\n for (let k = 0, len = indexes.length; k < len; k++) {\n const i = indexes[k]!\n const measurement = measurements[i]!\n\n virtualItems.push(measurement)\n }\n\n return virtualItems\n },\n {\n key: process.env.NODE_ENV !== 'production' && 'getIndexes',\n debug: () => this.options.debug,\n },\n )\n\n getVirtualItemForOffset = (offset: number) => {\n const measurements = this.getMeasurements()\n\n return notUndefined(\n measurements[\n findNearestBinarySearch(\n 0,\n measurements.length - 1,\n (index: number) => notUndefined(measurements[index]).start,\n offset,\n )\n ],\n )\n }\n\n getOffsetForAlignment = (toOffset: number, align: ScrollAlignment) => {\n const size = this.getSize()\n\n if (align === 'auto') {\n if (toOffset <= this.scrollOffset) {\n align = 'start'\n } else if (toOffset >= this.scrollOffset + size) {\n align = 'end'\n } else {\n align = 'start'\n }\n }\n\n if (align === 'start') {\n toOffset = toOffset\n } else if (align === 'end') {\n toOffset = toOffset - size\n } else if (align === 'center') {\n toOffset = toOffset - size / 2\n }\n\n const scrollSizeProp = this.options.horizontal\n ? 'scrollWidth'\n : 'scrollHeight'\n const scrollSize = this.scrollElement\n ? 'document' in this.scrollElement\n ? this.scrollElement.document.documentElement[scrollSizeProp]\n : this.scrollElement[scrollSizeProp]\n : 0\n\n const maxOffset = scrollSize - this.getSize()\n\n return Math.max(Math.min(maxOffset, toOffset), 0)\n }\n\n getOffsetForIndex = (index: number, align: ScrollAlignment = 'auto') => {\n index = Math.max(0, Math.min(index, this.options.count - 1))\n\n const measurement = notUndefined(this.getMeasurements()[index])\n\n if (align === 'auto') {\n if (\n measurement.end >=\n this.scrollOffset + this.getSize() - this.options.scrollPaddingEnd\n ) {\n align = 'end'\n } else if (\n measurement.start <=\n this.scrollOffset + this.options.scrollPaddingStart\n ) {\n align = 'start'\n } else {\n return [this.scrollOffset, align] as const\n }\n }\n\n const toOffset =\n align === 'end'\n ? measurement.end + this.options.scrollPaddingEnd\n : measurement.start - this.options.scrollPaddingStart\n\n return [this.getOffsetForAlignment(toOffset, align), align] as const\n }\n\n private isDynamicMode = () => this.measureElementCache.size > 0\n\n private cancelScrollToIndex = () => {\n if (this.scrollToIndexTimeoutId !== null) {\n clearTimeout(this.scrollToIndexTimeoutId)\n this.scrollToIndexTimeoutId = null\n }\n }\n\n scrollToOffset = (\n toOffset: number,\n { align = 'start', behavior }: ScrollToOffsetOptions = {},\n ) => {\n this.cancelScrollToIndex()\n\n if (behavior === 'smooth' && this.isDynamicMode()) {\n console.warn(\n 'The `smooth` scroll behavior is not fully supported with dynamic size.',\n )\n }\n\n this._scrollToOffset(this.getOffsetForAlignment(toOffset, align), {\n adjustments: undefined,\n behavior,\n })\n }\n\n scrollToIndex = (\n index: number,\n { align: initialAlign = 'auto', behavior }: ScrollToIndexOptions = {},\n ) => {\n index = Math.max(0, Math.min(index, this.options.count - 1))\n\n this.cancelScrollToIndex()\n\n if (behavior === 'smooth' && this.isDynamicMode()) {\n console.warn(\n 'The `smooth` scroll behavior is not fully supported with dynamic size.',\n )\n }\n\n const [toOffset, align] = this.getOffsetForIndex(index, initialAlign)\n\n this._scrollToOffset(toOffset, { adjustments: undefined, behavior })\n\n if (behavior !== 'smooth' && this.isDynamicMode()) {\n this.scrollToIndexTimeoutId = setTimeout(() => {\n this.scrollToIndexTimeoutId = null\n\n const elementInDOM = this.measureElementCache.has(\n this.options.getItemKey(index),\n )\n\n if (elementInDOM) {\n const [toOffset] = this.getOffsetForIndex(index, align)\n\n if (!approxEqual(toOffset, this.scrollOffset)) {\n this.scrollToIndex(index, { align, behavior })\n }\n } else {\n this.scrollToIndex(index, { align, behavior })\n }\n })\n }\n }\n\n scrollBy = (delta: number, { behavior }: ScrollToOffsetOptions = {}) => {\n this.cancelScrollToIndex()\n\n if (behavior === 'smooth' && this.isDynamicMode()) {\n console.warn(\n 'The `smooth` scroll behavior is not fully supported with dynamic size.',\n )\n }\n\n this._scrollToOffset(this.scrollOffset + delta, {\n adjustments: undefined,\n behavior,\n })\n }\n\n getTotalSize = () =>\n (this.getMeasurements()[this.options.count - 1]?.end ||\n this.options.paddingStart) -\n this.options.scrollMargin +\n this.options.paddingEnd\n\n private _scrollToOffset = (\n offset: number,\n {\n adjustments,\n behavior,\n }: {\n adjustments: number | undefined\n behavior: ScrollBehavior | undefined\n },\n ) => {\n this.options.scrollToFn(offset, { behavior, adjustments }, this)\n }\n\n measure = () => {\n this.itemSizeCache = new Map()\n this.notify()\n }\n}\n\nconst findNearestBinarySearch = (\n low: number,\n high: number,\n getCurrentValue: (i: number) => number,\n value: number,\n) => {\n while (low <= high) {\n const middle = ((low + high) / 2) | 0\n const currentValue = getCurrentValue(middle)\n\n if (currentValue < value) {\n low = middle + 1\n } else if (currentValue > value) {\n high = middle - 1\n } else {\n return middle\n }\n }\n\n if (low > 0) {\n return low - 1\n } else {\n return 0\n }\n}\n\nfunction calculateRange({\n measurements,\n outerSize,\n scrollOffset,\n}: {\n measurements: VirtualItem[]\n outerSize: number\n scrollOffset: number\n}) {\n const count = measurements.length - 1\n const getOffset = (index: number) => measurements[index]!.start\n\n const startIndex = findNearestBinarySearch(0, count, getOffset, scrollOffset)\n let endIndex = startIndex\n\n while (\n endIndex < count &&\n measurements[endIndex]!.end < scrollOffset + outerSize\n ) {\n endIndex++\n }\n\n return { startIndex, endIndex }\n}\n", "import * as React from 'react'\nimport {\n elementScroll,\n observeElementOffset,\n observeElementRect,\n observeWindowOffset,\n observeWindowRect,\n PartialKeys,\n Virtualizer,\n VirtualizerOptions,\n windowScroll,\n} from '@tanstack/virtual-core'\nexport * from '@tanstack/virtual-core'\n\n//\n\nconst useIsomorphicLayoutEffect =\n typeof document !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nfunction useVirtualizerBase<\n TScrollElement extends Element | Window,\n TItemElement extends Element,\n>(\n options: VirtualizerOptions,\n): Virtualizer {\n const rerender = React.useReducer(() => ({}), {})[1]\n\n const resolvedOptions: VirtualizerOptions = {\n ...options,\n onChange: (instance) => {\n rerender()\n options.onChange?.(instance)\n },\n }\n\n const [instance] = React.useState(\n () => new Virtualizer(resolvedOptions),\n )\n\n instance.setOptions(resolvedOptions)\n\n React.useEffect(() => {\n return instance._didMount()\n }, [])\n\n useIsomorphicLayoutEffect(() => {\n return instance._willUpdate()\n })\n\n return instance\n}\n\nexport function useVirtualizer<\n TScrollElement extends Element,\n TItemElement extends Element,\n>(\n options: PartialKeys<\n VirtualizerOptions,\n 'observeElementRect' | 'observeElementOffset' | 'scrollToFn'\n >,\n): Virtualizer {\n return useVirtualizerBase({\n observeElementRect: observeElementRect,\n observeElementOffset: observeElementOffset,\n scrollToFn: elementScroll,\n ...options,\n })\n}\n\nexport function useWindowVirtualizer(\n options: PartialKeys<\n VirtualizerOptions,\n | 'getScrollElement'\n | 'observeElementRect'\n | 'observeElementOffset'\n | 'scrollToFn'\n >,\n): Virtualizer {\n return useVirtualizerBase({\n getScrollElement: () => (typeof document !== 'undefined' ? window : null),\n observeElementRect: observeWindowRect,\n observeElementOffset: observeWindowOffset,\n scrollToFn: windowScroll,\n ...options,\n })\n}\n", "import { render, hydrate, unmountComponentAtNode } from 'preact/compat';\n\nexport function createRoot(container) {\n\treturn {\n\t\trender(children) {\n\t\t\trender(children, container);\n\t\t},\n\t\tunmount() {\n\t\t\tunmountComponentAtNode(container);\n\t\t}\n\t};\n}\n\nexport function hydrateRoot(container, children) {\n\thydrate(children, container);\n\treturn createRoot(container);\n}\n\nexport default {\n\tcreateRoot,\n\thydrateRoot\n};\n", "// Find the first item whose top-left corner is fully inside the visible portion of the\n// scroll container\nexport function findFirstItemInView(\n scrollContainer: HTMLElement,\n items: NodeList,\n extraPadding?: {\n top?: number;\n right?: number;\n bottom?: number;\n left?: number;\n }\n) {\n const pad = Object.assign(\n { top: 0, right: 0, bottom: 0, left: 0 },\n extraPadding\n );\n const container = scrollContainer;\n const top = container.scrollTop + pad.top;\n const left = container.scrollLeft + pad.left;\n const bottom = top + container.clientHeight - pad.top - pad.bottom;\n const right = left + container.clientWidth - pad.left - pad.right;\n\n for (let i = 0; i < items.length; i++) {\n const el = items[i] as HTMLElement;\n const y = el.offsetTop,\n x = el.offsetLeft;\n if (y >= top && y <= bottom && x >= left && x <= right) {\n return el;\n }\n }\n return null;\n}\n\nexport function getStyle(el: Element, styleProp: string): string | undefined {\n // getComputedStyle can return null when we're inside a hidden iframe on\n // Firefox; don't attempt to retrieve style props in this case.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=548397\n return document?.defaultView\n ?.getComputedStyle(el, null)\n ?.getPropertyValue(styleProp);\n}\n", "import React, { FC, useEffect, useRef, useState } from \"react\";\n\nexport interface FilterNumericProps\n extends React.InputHTMLAttributes {\n // The absolute min/max possible values\n range: () => [number | undefined, number | undefined];\n\n // The currently selected min/max values\n from: number | undefined;\n to: number | undefined;\n\n onRangeChange: (from?: number, to?: number) => void;\n}\n\nexport const FilterNumeric: FC = (props) => {\n const [editing, setEditing] = useState(false);\n const { range, from, to, onRangeChange } = props;\n\n return (\n onRangeChange(...x)}\n onFocus={() => setEditing(true)}\n onBlur={() => setEditing(false)}\n />\n );\n};\n\nfunction generateLabel(from?: number, to?: number) {\n if (typeof from === \"undefined\" && typeof to === \"undefined\") {\n return \"\";\n } else if (typeof from === \"undefined\") {\n return `\u2264 ${to}`;\n } else if (typeof to === \"undefined\") {\n return `\u2265 ${from}`;\n } else {\n return `\u2265${from}, \u2264${to}`;\n }\n}\n\ninterface FilterNumericImplProps {\n range: () => [number | undefined, number | undefined];\n value: [number | undefined, number | undefined];\n editing: boolean;\n onValueChange: (range: [number | undefined, number | undefined]) => void;\n onFocus: () => void;\n onBlur: () => void;\n}\n\nconst FilterNumericImpl: React.FC = (props) => {\n const [min, max] = props.value;\n const { editing, onFocus } = props;\n\n const minInputRef = useRef(null);\n const maxInputRef = useRef(null);\n\n return (\n {\n if (e.currentTarget.contains(e.relatedTarget)) {\n return;\n }\n return props.onBlur();\n }}\n onFocus={() => onFocus()}\n style={{\n display: \"flex\",\n gap: \"0.5rem\",\n }}\n >\n {\n const value = coerceToNum(e.target.value);\n minInputRef.current.classList.toggle(\n \"is-invalid\",\n !e.target.checkValidity()\n );\n props.onValueChange([value, max]);\n }}\n />\n {\n const value = coerceToNum(e.target.value);\n maxInputRef.current.classList.toggle(\n \"is-invalid\",\n !e.target.checkValidity()\n );\n props.onValueChange([min, value]);\n }}\n />\n
\n );\n};\n\nfunction createPlaceholder(\n editing: boolean,\n label: string,\n value: number | undefined\n) {\n if (!editing) {\n return null;\n } else if (typeof value === \"undefined\") {\n return label;\n } else {\n return `${label} (${value})`;\n }\n}\n\nfunction coerceToNum(value: string): number | undefined {\n if (value === \"\") {\n return undefined;\n }\n return +value;\n}\n", "import {\n FiltersOptions,\n Header,\n TableOptions,\n getFacetedMinMaxValues,\n getFacetedRowModel,\n getFacetedUniqueValues,\n getFilteredRowModel,\n} from \"@tanstack/react-table\";\nimport React, {\n FC,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport { FilterNumeric } from \"./filter-numeric\";\n\nexport function useFilter(enabled: boolean): FiltersOptions {\n if (enabled) {\n return {\n getFilteredRowModel: getFilteredRowModel(),\n getFacetedRowModel: getFacetedRowModel(),\n getFacetedUniqueValues: getFacetedUniqueValues(),\n getFacetedMinMaxValues: getFacetedMinMaxValues(),\n filterFns: {\n substring: (row, columnId, value, addMeta) => {\n return row.getValue(columnId).toString().includes(value);\n },\n },\n };\n } else {\n return {};\n }\n}\n\nexport interface FilterProps\n extends React.InputHTMLAttributes {\n header: Header;\n}\n\nexport const Filter: FC = ({ header, className, ...props }) => {\n const typeHint = header.column.columnDef.meta?.typeHint;\n\n if (typeHint.type === \"numeric\") {\n const [from, to] = (header.column.getFilterValue() as\n | [number | undefined, number | undefined]\n | undefined) ?? [undefined, undefined];\n\n const range = () => {\n return header.column.getFacetedMinMaxValues() ?? [undefined, undefined];\n };\n\n return FilterNumeric({\n from,\n to,\n range,\n onRangeChange: (from, to) => header.column.setFilterValue([from, to]),\n });\n }\n\n return (\n header.column.setFilterValue(e.target.value)}\n />\n );\n};\n", "export class ImmutableSet {\n private _set: Set;\n private static _empty: ImmutableSet = new ImmutableSet(new Set());\n\n private constructor(set: Set) {\n this._set = set;\n }\n\n static empty(): ImmutableSet {\n return this._empty as ImmutableSet;\n }\n\n static just(...values: T[]): ImmutableSet {\n return this.empty().add(...values);\n }\n\n has(value: T): boolean {\n return this._set.has(value);\n }\n\n add(...values: T[]): ImmutableSet {\n const newSet = new Set(this._set.keys());\n for (const value of values) {\n newSet.add(value);\n }\n return new ImmutableSet(newSet);\n }\n\n toggle(value: T): ImmutableSet {\n if (this.has(value)) {\n return this.delete(value);\n } else {\n return this.add(value);\n }\n }\n\n delete(value: T): ImmutableSet {\n const newSet = new Set(this._set.keys());\n newSet.delete(value);\n return new ImmutableSet(newSet);\n }\n\n clear(): ImmutableSet {\n return ImmutableSet.empty();\n }\n\n [Symbol.iterator]() {\n return this._set[Symbol.iterator]();\n }\n\n toList(): T[] {\n return [...this._set.keys()];\n }\n}\n", "import * as React from \"react\";\nimport { useState } from \"react\";\nimport { ImmutableSet } from \"./immutable-set\";\n\nexport interface SelectionSet {\n has(key: TKey): boolean;\n set(key: TKey, selected: boolean): void;\n clear(): void;\n keys(): ImmutableSet;\n itemHandlers(): {\n onMouseDown: (event: React.MouseEvent) => void;\n onKeyDown: (event: React.KeyboardEvent) => void;\n };\n}\n\nexport enum SelectionMode {\n None = \"none\",\n Single = \"single\",\n Multiple = \"multiple\",\n MultiNative = \"multi-native\",\n}\n\nexport function useSelection(\n mode: SelectionMode,\n keyAccessor: (el: TElement) => TKey,\n focusOffset: (start: TKey, offset: number) => TKey,\n between?: (from: TKey, to: TKey) => ReadonlyArray\n): SelectionSet {\n const [selectedKeys, setSelectedKeys] = useState>(\n ImmutableSet.empty()\n );\n\n // The anchor is the item that was most recently selected with a click or ctrl-click,\n // and is used to determine the \"other end\" of a shift-click selection operation.\n const [anchor, setAnchor] = useState(null);\n\n const onMouseDown = (event: React.MouseEvent): void => {\n if (mode === SelectionMode.None) {\n return;\n }\n\n const el = event.currentTarget as TElement;\n const key = keyAccessor(el);\n\n const result = performMouseDownAction(\n mode,\n between,\n selectedKeys,\n event,\n key,\n anchor\n );\n if (result) {\n setSelectedKeys(result.selection);\n if (result.anchor) {\n setAnchor(key);\n el.focus();\n }\n event.preventDefault();\n }\n };\n\n const onKeyDown = (event: React.KeyboardEvent): void => {\n if (mode === SelectionMode.None) {\n return;\n }\n\n const el = event.currentTarget as TElement;\n const key = keyAccessor(el);\n const selected = selectedKeys.has(key);\n\n if (mode === SelectionMode.Single) {\n if (event.key === \" \" || event.key === \"Enter\") {\n if (selectedKeys.has(key)) {\n setSelectedKeys(ImmutableSet.empty());\n } else {\n setSelectedKeys(ImmutableSet.just(key));\n }\n event.preventDefault();\n } else if (event.key === \"ArrowUp\" || event.key === \"ArrowDown\") {\n const targetKey = focusOffset(key, event.key === \"ArrowUp\" ? -1 : 1);\n if (targetKey) {\n event.preventDefault();\n if (selected) {\n setSelectedKeys(ImmutableSet.just(targetKey));\n }\n }\n }\n } else if (mode === SelectionMode.Multiple) {\n if (event.key === \" \" || event.key === \"Enter\") {\n setSelectedKeys(selectedKeys.toggle(key));\n event.preventDefault();\n } else if (event.key === \"ArrowUp\" || event.key === \"ArrowDown\") {\n if (focusOffset(key, event.key === \"ArrowUp\" ? -1 : 1)) {\n event.preventDefault();\n }\n }\n }\n };\n\n return {\n has(key: TKey): boolean {\n return selectedKeys.has(key);\n },\n\n set(key: TKey, selected: boolean) {\n if (selected) {\n setSelectedKeys(selectedKeys.add(key));\n } else {\n setSelectedKeys(selectedKeys.delete(key));\n }\n },\n\n clear() {\n setSelectedKeys(selectedKeys.clear());\n },\n\n keys() {\n return selectedKeys;\n },\n\n itemHandlers() {\n return { onMouseDown, onKeyDown };\n },\n };\n}\n\ndeclare global {\n interface Navigator {\n readonly userAgentData?: NavigatorUAData;\n }\n interface NavigatorUAData {\n readonly brands?: { brand: string; version: string }[];\n readonly mobile?: boolean;\n readonly platform?: string;\n }\n}\n\nconst isMac = /^mac/i.test(\n window.navigator.userAgentData?.platform ?? window.navigator.platform\n);\n\nfunction performMouseDownAction(\n mode: SelectionMode,\n between: (from: TKey, to: TKey) => readonly TKey[],\n selectedKeys: ImmutableSet,\n event: React.MouseEvent,\n key: TKey,\n anchor: TKey | null\n): { selection: ImmutableSet; anchor?: true } {\n const { shiftKey, altKey } = event;\n const ctrlKey = isMac ? event.metaKey : event.ctrlKey;\n const metaKey = isMac ? event.ctrlKey : event.metaKey;\n\n if (metaKey || altKey) {\n return null;\n }\n\n if (mode === SelectionMode.Multiple) {\n return { selection: selectedKeys.toggle(key), anchor: true };\n } else if (mode === SelectionMode.Single) {\n if (ctrlKey && !shiftKey) {\n // Ctrl-click is like simple click, except it removes selection if an item is\n // already selected\n if (selectedKeys.has(key)) {\n return { selection: ImmutableSet.empty(), anchor: true };\n } else {\n return { selection: ImmutableSet.just(key), anchor: true };\n }\n } else {\n // Simple click sets selection, always\n return { selection: ImmutableSet.just(key), anchor: true };\n }\n } else if (mode === SelectionMode.MultiNative) {\n if (shiftKey && ctrlKey) {\n // Ctrl-Shift-click: Add anchor row through current row to selection\n const toSelect = between(anchor, key);\n return { selection: selectedKeys.add(...toSelect) };\n } else if (ctrlKey) {\n // Ctrl-click: toggle the current row and make it anchor\n return { selection: selectedKeys.toggle(key), anchor: true };\n } else if (shiftKey) {\n // Shift-click: replace selection with anchor row through current row\n if (anchor !== null && between) {\n const toSelect = between(anchor, key);\n return { selection: ImmutableSet.just(...toSelect) };\n }\n } else {\n // Regular click: Select the current row and make it anchor\n return { selection: ImmutableSet.just(key), anchor: true };\n }\n }\n}\n", "import { SortDirection } from \"@tanstack/react-table\";\nimport React, { FC } from \"react\";\n\nconst sortCommonProps = {\n className: \"sort-arrow\",\n viewBox: [-1, -1, 2, 2].map((x) => x * 1.4).join(\" \"),\n width: \"100%\",\n height: \"100%\",\n style: { paddingLeft: \"3px\" },\n};\n\nconst sortPathCommonProps = {\n stroke: \"#333333\",\n strokeWidth: \"0.6\",\n fill: \"transparent\",\n};\n\nconst sortArrowUp = (\n \n \n \n);\n\nconst sortArrowDown = (\n \n \n \n);\n\ninterface SortArrowProps {\n direction: SortDirection | false;\n}\n\nexport const SortArrow: FC = ({ direction }) => {\n if (!direction) {\n return null;\n }\n if (direction === \"asc\") {\n return sortArrowUp;\n }\n if (direction === \"desc\") {\n return sortArrowDown;\n }\n throw new Error(`Unexpected sort direction: '${direction}'`);\n};\n\n//const sortArrowUp = \u25B2;\n//const sortArrowDown = \u25BC;\n", "import React, { useState } from \"react\";\nimport { findFirstItemInView } from \"./dom-utils\";\n\nexport interface TabindexGroup {\n containerTabIndex: number;\n containerHandlers: {\n onFocus: (event: React.FocusEvent) => void;\n onBlur: (event: React.FocusEvent) => void;\n };\n}\n\nexport function useTabindexGroup(\n container: TContainerElement,\n focusableItems: () => NodeList,\n extraPadding?: {\n top?: number;\n right?: number;\n bottom?: number;\n left?: number;\n }\n): TabindexGroup {\n const [tabIndex, setTabIndex] = useState(0);\n\n const onFocus = React.useCallback(\n (event: React.FocusEvent) => {\n // When focus is within (or on, but we only really care about within) the\n // container, remove it from the tab order. If we don't set the tab stop to -1,\n // then the logic below (that, on container focus, moves focus to the first item)\n // causes Shift-Tab from a focused item to break, as focus moves to the container\n // and then (back) to the first item.\n setTabIndex(-1);\n\n if (event.target !== event.currentTarget) {\n // Not interested in capturing, only care about focus on the container itself\n return;\n }\n findFirstItemInView(container, focusableItems(), extraPadding)?.focus();\n },\n [container, focusableItems, extraPadding]\n );\n\n const onBlur = React.useCallback(\n (event: React.FocusEvent) => {\n setTabIndex(0);\n },\n []\n );\n\n return {\n containerTabIndex: tabIndex,\n containerHandlers: {\n onFocus,\n onBlur,\n },\n };\n}\n", "import { VirtualItem } from \"@tanstack/react-virtual\";\nimport React, { useMemo } from \"react\";\n\n/**\n * Create a summary\n *\n * @param summaryTemplate A string with \"{start}\", \"{end}\", and \"{total}\"\n * @param scrollContainer Scrolling container of the table/grid\n * @param virtualRows VirtualItem objects that might currently be visible\n * @param thead The thead tag of the table\n * @param nrows Number of total rows of data that exist\n */\nexport function useSummary(\n summaryTemplate: string | boolean | null,\n scrollContainer: HTMLElement | null,\n virtualRows: VirtualItem[],\n thead: HTMLTableSectionElement,\n nrows: number\n): JSX.Element | null {\n return useMemo(() => {\n const summaryOption = summaryTemplate ?? true;\n if (!summaryOption) {\n return null;\n }\n\n const template =\n typeof summaryOption === \"string\"\n ? summaryOption\n : \"Viewing rows {start} through {end} of {total}\";\n\n if (!scrollContainer) {\n return null;\n }\n if (virtualRows.length === 0) {\n return null;\n }\n\n const top = scrollContainer.scrollTop + thead.clientHeight;\n const bot = scrollContainer.scrollTop + scrollContainer.clientHeight;\n\n const [firstIndex, lastIndex] = findRangeIndex(\n top,\n bot,\n virtualRows,\n (vrow, start) => vrow.start + vrow.size / 2\n );\n\n if (firstIndex === null || lastIndex === null) {\n // Something must've gone wrong if there are rows but none of them are within the\n // visible scroll area... shrug\n return null;\n }\n\n const firstRow = virtualRows[firstIndex];\n const lastRow = virtualRows[lastIndex];\n\n if (firstRow.index === 0 && lastRow.index === nrows - 1) {\n // Viewing all rows; no need for a summary\n return null;\n }\n\n const summaryMessage = formatSummary(\n template,\n firstRow.index + 1,\n lastRow.index + 1,\n nrows\n );\n\n return
{summaryMessage}
;\n }, [summaryTemplate, scrollContainer, virtualRows, thead, nrows]);\n}\n\n/**\n * Find the subset of (sorted) items that are between start and end (inclusive), where\n * each item's value to compare is calculated by a mapping function. The mapping\n * function may behave differently when comparing to start vs. end.\n *\n * @param start The smallest value to include.\n * @param end The largest value to include.\n * @param items A set of items to be evaluated, in sorted order.\n * @param map A function for converting from an item to a comparison value; for example,\n * if 'start' and 'end' are vertical pixel coordinates, then the function might\n * return the item's vertical top (for start) or bottom (for end) coordinate.\n * @returns The start and end indexes into the 'items' array indicating the first and\n * last item that is included.\n */\nfunction findRangeIndex(\n start: number,\n end: number,\n items: TItem[],\n map: (x: TItem, start: boolean) => number\n): [first: number | null, last: number | null] {\n let first: number | null = null;\n let last: number | null = null;\n\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n if (first === null) {\n if (map(item, true) >= start) {\n first = i;\n last = i;\n }\n } else {\n if (map(item, false) <= end) {\n last = i;\n } else {\n break;\n }\n }\n }\n\n return [first, last];\n}\n\nfunction formatSummary(\n template: string,\n start: number,\n end: number,\n total: number\n) {\n return template.replace(/\\{(start|end|total)\\}/g, (substr, token) => {\n if (token === \"start\") {\n return start + \"\";\n } else if (token === \"end\") {\n return end + \"\";\n } else if (token === \"total\") {\n return total + \"\";\n } else {\n return substr;\n }\n });\n}\n", "import css from \"./styles.scss\";\n\nimport {\n Column,\n ColumnDef,\n RowData,\n RowModel,\n TableOptions,\n flexRender,\n getCoreRowModel,\n getSortedRowModel,\n useReactTable,\n} from \"@tanstack/react-table\";\nimport { Virtualizer, useVirtualizer } from \"@tanstack/react-virtual\";\nimport React, {\n FC,\n StrictMode,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n} from \"react\";\nimport { Root, createRoot } from \"react-dom/client\";\nimport { ErrorsMessageValue } from \"rstudio-shiny/srcts/types/src/shiny/shinyapp\";\nimport { findFirstItemInView, getStyle } from \"./dom-utils\";\nimport { Filter, useFilter } from \"./filter\";\nimport { SelectionMode, useSelection } from \"./selection\";\nimport { SortArrow } from \"./sort-arrows\";\nimport { useTabindexGroup } from \"./tabindex-group\";\nimport { useSummary } from \"./table-summary\";\nimport { PandasData, TypeHint } from \"./types\";\n\ndeclare module \"@tanstack/table-core\" {\n interface ColumnMeta {\n typeHint: TypeHint;\n }\n}\n// TODO: Right-align numeric columns, maybe change font\n// TODO: Explicit column widths\n// TODO: Filtering\n// TODO: Editing\n// TODO: Pagination\n// TODO: Range selection + copying\n// TODO: Find\n// TODO: Server-side mode (don't pull all data to client at once)\n// TODO: Localization of summary\n// TODO: Accessibility review\n// TODO: Drag to resize columns\n// TODO: Drag to resize table/grid\n// TODO: Row numbers\n\ninterface ShinyDataGridProps {\n id: string | null;\n data: PandasData;\n bgcolor?: string;\n}\n\nconst ShinyDataGrid: FC> = (props) => {\n const { id, data, bgcolor } = props;\n const { columns, type_hints, data: rowData } = data;\n const { width, height, fill, filters: withFilters } = data.options;\n\n const containerRef = useRef(null);\n const theadRef = useRef(null);\n const tbodyRef = useRef(null);\n\n const coldefs = useMemo[]>(\n () =>\n columns.map((colname, i) => {\n const typeHint = type_hints?.[i];\n\n return {\n accessorFn: (row, index) => {\n return row[i];\n },\n // TODO: delegate this decision to something in filter.tsx\n filterFn:\n typeHint.type === \"numeric\" ? \"inNumberRange\" : \"includesString\",\n header: colname,\n meta: {\n typeHint: typeHint,\n },\n };\n }),\n [columns]\n );\n\n // Not sure if it's even necessary to clone\n const dataClone = useMemo(() => [...rowData], [rowData]);\n\n const filterOpts = useFilter(withFilters);\n\n const options: TableOptions = {\n data: dataClone,\n columns: coldefs,\n getCoreRowModel: getCoreRowModel(),\n getSortedRowModel: getSortedRowModel(),\n ...filterOpts,\n //debugAll: true,\n };\n const table = useReactTable(options);\n\n const rowVirtualizer = useVirtualizer({\n count: table.getFilteredRowModel().rows.length,\n getScrollElement: () => containerRef.current,\n estimateSize: () => 31,\n paddingStart: theadRef.current?.clientHeight ?? 0,\n // In response to https://github.com/posit-dev/py-shiny/pull/538/files#r1228352446\n // (the default scrollingDelay is 150)\n scrollingDelay: 10,\n });\n\n // Reset scroll when dataset changes\n useLayoutEffect(() => {\n rowVirtualizer.scrollToOffset(0);\n }, [data]);\n\n const totalSize = rowVirtualizer.getTotalSize();\n const virtualRows = rowVirtualizer.getVirtualItems();\n\n // paddingTop and paddingBottom are to force the
to add up to the correct\n // virtual height.\n // paddingTop must subtract out the thead height, since thead is inside the scroll\n // container but not virtualized.\n const paddingTop =\n (virtualRows.length > 0 ? virtualRows?.[0]?.start || 0 : 0) -\n theadRef.current?.clientHeight ?? 0;\n const paddingBottom =\n virtualRows.length > 0\n ? totalSize - (virtualRows?.[virtualRows.length - 1]?.end || 0)\n : 0;\n\n const summary = useSummary(\n data.options[\"summary\"],\n containerRef?.current,\n virtualRows,\n theadRef.current,\n rowVirtualizer.options.count\n );\n\n const tableStyle = data.options[\"style\"] ?? \"grid\";\n const containerClass =\n tableStyle === \"grid\" ? \"shiny-data-grid-grid\" : \"shiny-data-grid-table\";\n const tableClass = tableStyle === \"table\" ? \"table table-sm\" : null;\n\n const rowSelectionMode =\n data.options[\"row_selection_mode\"] ?? SelectionMode.MultiNative;\n const canSelect = rowSelectionMode !== SelectionMode.None;\n const canMultiSelect =\n rowSelectionMode === SelectionMode.MultiNative ||\n rowSelectionMode === SelectionMode.Multiple;\n\n const rowSelection = useSelection(\n rowSelectionMode,\n (el) => el.dataset.key,\n (key, offset) => {\n const rowModel = table.getSortedRowModel();\n let index = rowModel.rows.findIndex((row) => row.id === key);\n if (index < 0) {\n return null;\n }\n index += offset;\n if (index < 0 || index >= rowModel.rows.length) {\n return null;\n }\n const targetKey = rowModel.rows[index].id;\n rowVirtualizer.scrollToIndex(index);\n setTimeout(() => {\n const targetEl = containerRef.current?.querySelector(\n `[data-key='${targetKey}']`\n ) as HTMLElement | null;\n targetEl?.focus();\n }, 0);\n return targetKey;\n },\n (fromKey, toKey) =>\n findKeysBetween(table.getSortedRowModel(), fromKey, toKey)\n );\n\n useEffect(() => {\n if (id) {\n if (rowSelectionMode === SelectionMode.None) {\n Shiny.setInputValue(`${id}_selected_rows`, null);\n } else {\n Shiny.setInputValue(\n `${id}_selected_rows`,\n rowSelection\n .keys()\n .toList()\n .map((key) => parseInt(key))\n .sort()\n );\n }\n }\n }, [[...rowSelection.keys()]]);\n\n const tbodyTabItems = React.useCallback(\n () => tbodyRef.current.querySelectorAll(\"[tabindex='-1']\"),\n [tbodyRef.current]\n );\n const tbodyTabGroup = useTabindexGroup(containerRef.current, tbodyTabItems, {\n top: theadRef.current?.clientHeight ?? 0,\n });\n\n // Reset sorting and selection whenever dataset changes. (Should we do this?)\n useEffect(() => {\n return () => {\n table.resetSorting();\n rowSelection.clear();\n };\n }, [data]);\n\n const headerRowCount = table.getHeaderGroups().length;\n\n // Assume we're scrolling until proven otherwise\n let scrollingClass = \"scrolling\";\n const scrollHeight = containerRef.current?.scrollHeight;\n const clientHeight = containerRef.current?.clientHeight;\n if (scrollHeight && clientHeight && scrollHeight <= clientHeight) {\n scrollingClass = \"\";\n }\n\n const makeHeaderKeyDown =\n (column: Column) => (event: React.KeyboardEvent) => {\n if (event.key === \" \" || event.key === \"Enter\") {\n column.toggleSorting(undefined, event.shiftKey);\n }\n };\n\n const measureEl = useVirtualizerMeasureWorkaround(rowVirtualizer);\n\n let className = `shiny-data-grid ${containerClass} ${scrollingClass}`;\n if (fill) {\n className += \" html-fill-item\";\n }\n\n return (\n <>\n \n \n \n {table.getHeaderGroups().map((headerGroup, i) => (\n \n {headerGroup.headers.map((header) => {\n return (\n \n {header.isPlaceholder ? null : (\n \n {flexRender(\n header.column.columnDef.header,\n header.getContext()\n )}\n \n \n )}\n \n );\n })}\n \n ))}\n {withFilters && (\n \n {table.getFlatHeaders().map((header) => {\n return (\n \n );\n })}\n \n )}\n \n \n {paddingTop > 0 && }\n {virtualRows.map((virtualRow) => {\n const row = table.getRowModel().rows[virtualRow.index];\n return (\n row && (\n \n {row.getVisibleCells().map((cell) => {\n return (\n \n );\n })}\n \n )\n );\n })}\n {paddingBottom > 0 && (\n \n )}\n \n
- {flexRender( - cell.column.columnDef.cell, - cell.getContext() - )} -
\n \n
\n {flexRender(\n cell.column.columnDef.cell,\n cell.getContext()\n )}\n
\n
\n {summary}\n \n );\n};\n\nfunction findKeysBetween(\n rowModel: RowModel,\n fromKey: string,\n toKey: string\n): readonly string[] {\n let fromIdx = rowModel.rows.findIndex((row) => row.id === fromKey);\n let toIdx = rowModel.rows.findIndex((row) => row.id === toKey);\n if (fromIdx < 0 || toIdx < 0) {\n return [];\n }\n if (fromIdx > toIdx) {\n // Swap order to simplify things\n [fromIdx, toIdx] = [toIdx, fromIdx];\n }\n const keys = [];\n for (let i = fromIdx; i <= toIdx; i++) {\n keys.push(rowModel.rows[i].id);\n }\n return keys;\n}\n\n/**\n * Works around a problem where the ref={...} callback is called before the element to\n * be measured is attached to the DOM, which will result in the virtualizer using its\n * estimated size instead of the actual size. This hook will detect when elements that\n * are not yet attached to the DOM are measured, and will retry measuring them in the\n * useEffect.\n * @returns A callback that can be used as a ref for an element that needs to be measured.\n */\nfunction useVirtualizerMeasureWorkaround(\n rowVirtualizer: Virtualizer\n) {\n // Tracks elements that need to be measured, but are not yet attached to the DOM\n const measureTodoQueue = useRef([]);\n\n // This is the callback that will be passed back to the caller, intended to be used as\n // a ref for each virtual item's element.\n const measureElementWithRetry = useCallback(\n (el: Element) => {\n if (!el) {\n return;\n }\n\n if (el.isConnected) {\n rowVirtualizer.measureElement(el);\n } else {\n measureTodoQueue.current.push(el as HTMLElement);\n }\n },\n [rowVirtualizer]\n );\n\n // Once the DOM is updated, try to measure any elements that were not yet attached\n useLayoutEffect(() => {\n if (measureTodoQueue.current.length > 0) {\n const todo = measureTodoQueue.current.splice(0);\n // The next line can mutate measureTodoQueue.current, hence the need to splice out\n // all the items to work on before actually calling measureElement on any of them.\n todo.forEach(rowVirtualizer.measureElement);\n }\n });\n\n return measureElementWithRetry;\n}\n\nclass ShinyDataFrameOutputBinding extends Shiny.OutputBinding {\n find(scope: HTMLElement | JQuery): JQuery {\n return $(scope).find(\"shiny-data-frame\");\n }\n\n renderValue(el: ShinyDataFrameOutput, data: unknown): void {\n el.renderValue(data);\n }\n\n renderError(el: ShinyDataFrameOutput, err: ErrorsMessageValue): void {\n el.classList.add(\"shiny-output-error\");\n el.renderError(err);\n }\n\n clearError(el: ShinyDataFrameOutput): void {\n el.classList.remove(\"shiny-output-error\");\n el.clearError();\n }\n}\nShiny.outputBindings.register(\n new ShinyDataFrameOutputBinding(),\n \"shinyDataFrame\"\n);\n\nfunction getComputedBgColor(el: HTMLElement | null): string | null | undefined {\n if (!el) {\n // Top of document, can't recurse further\n return null;\n }\n\n const bgColor = getStyle(el, \"background-color\");\n\n if (!bgColor) return bgColor;\n const m = bgColor.match(\n /^rgba\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*\\)$/\n );\n\n if (bgColor === \"transparent\" || (m && parseFloat(m[4]) === 0)) {\n // No background color on this element. See if it has a background image.\n const bgImage = getStyle(el, \"background-image\");\n\n if (bgImage && bgImage !== \"none\") {\n // Failed to detect background color, since it has a background image\n return null;\n } else {\n // Recurse\n return getComputedBgColor(el.parentElement);\n }\n }\n return bgColor;\n}\n\nconst cssTemplate = document.createElement(\"template\");\ncssTemplate.innerHTML = ``;\n\nexport class ShinyDataFrameOutput extends HTMLElement {\n reactRoot?: Root;\n errorRoot: HTMLSpanElement;\n\n connectedCallback() {\n // Currently not using shadow DOM since Bootstrap's table styling is pretty nice and\n // I don't have time to duplicate all that right now.\n // this.attachShadow({ mode: \"open\" });\n // const target = this.shadowRoot!;\n\n const [target] = [this]; // brackets are to avoid linter\n\n target.appendChild(cssTemplate.content.cloneNode(true));\n\n // Need to put error messages in an inline element () instead of in the\n // reactRoot div, because we want the error messages to appear on the same line as\n // \"Error:\".\n this.errorRoot = document.createElement(\"span\");\n target.appendChild(this.errorRoot);\n\n const myDiv = document.createElement(\"div\");\n myDiv.classList.add(\"html-fill-container\", \"html-fill-item\");\n target.appendChild(myDiv);\n\n this.reactRoot = createRoot(myDiv);\n\n // If there is a