@rickcedwhat/playwright-smart-table 6.16.0 → 6.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/engine/rowFinder.js +15 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -1
- package/dist/packageVersion.d.ts +1 -1
- package/dist/packageVersion.js +1 -1
- package/dist/presets/index.d.ts +2 -1
- package/dist/presets/index.js +3 -1
- package/dist/presets/mui.d.ts +23 -7
- package/dist/presets/mui.js +441 -271
- package/dist/presets/rdg.d.ts +20 -13
- package/dist/presets/rdg.js +5 -5
- package/dist/smartRow.js +34 -27
- package/dist/typeContext.d.ts +1 -1
- package/dist/typeContext.js +44 -0
- package/dist/types.d.ts +39 -0
- package/dist/useTable.js +19 -0
- package/dist/utils/mergeTableConfig.d.ts +22 -0
- package/dist/utils/mergeTableConfig.js +60 -0
- package/dist/utils/navigationBarrier.d.ts +19 -7
- package/dist/utils/navigationBarrier.js +57 -28
- package/package.json +1 -1
package/dist/presets/rdg.d.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Locator } from '@playwright/test';
|
|
2
|
+
import { TableContext, TableConfig, ViewportStrategy, StrategyContext } from '../types';
|
|
2
3
|
/** Full strategies for React Data Grid. Use when you want to supply your own selectors: strategies: Plugins.RDG.Strategies */
|
|
3
4
|
export declare const RDGStrategies: {
|
|
4
5
|
header: (context: TableContext) => Promise<string[]>;
|
|
5
|
-
getCellLocator: ({ row, columnIndex }:
|
|
6
|
+
getCellLocator: ({ row, columnIndex }: {
|
|
7
|
+
row: Locator;
|
|
8
|
+
columnIndex: number;
|
|
9
|
+
}) => Locator;
|
|
6
10
|
navigation: {
|
|
7
|
-
goRight: ({ root
|
|
8
|
-
goLeft: ({ root
|
|
9
|
-
goDown: ({ root
|
|
10
|
-
goUp: ({ root
|
|
11
|
-
goHome: ({ root
|
|
11
|
+
goRight: ({ root }: StrategyContext) => Promise<void>;
|
|
12
|
+
goLeft: ({ root }: StrategyContext) => Promise<void>;
|
|
13
|
+
goDown: ({ root }: StrategyContext) => Promise<void>;
|
|
14
|
+
goUp: ({ root }: StrategyContext) => Promise<void>;
|
|
15
|
+
goHome: ({ root }: StrategyContext) => Promise<void>;
|
|
12
16
|
};
|
|
13
17
|
pagination: import("..").PaginationPrimitives;
|
|
14
18
|
};
|
|
@@ -18,13 +22,16 @@ export declare const RDG: Partial<TableConfig> & {
|
|
|
18
22
|
export declare const RDG2DStrategies: {
|
|
19
23
|
viewport: ViewportStrategy;
|
|
20
24
|
header: (context: TableContext) => Promise<string[]>;
|
|
21
|
-
getCellLocator: ({ row, columnIndex }:
|
|
25
|
+
getCellLocator: ({ row, columnIndex }: {
|
|
26
|
+
row: Locator;
|
|
27
|
+
columnIndex: number;
|
|
28
|
+
}) => Locator;
|
|
22
29
|
navigation: {
|
|
23
|
-
goRight: ({ root
|
|
24
|
-
goLeft: ({ root
|
|
25
|
-
goDown: ({ root
|
|
26
|
-
goUp: ({ root
|
|
27
|
-
goHome: ({ root
|
|
30
|
+
goRight: ({ root }: StrategyContext) => Promise<void>;
|
|
31
|
+
goLeft: ({ root }: StrategyContext) => Promise<void>;
|
|
32
|
+
goDown: ({ root }: StrategyContext) => Promise<void>;
|
|
33
|
+
goUp: ({ root }: StrategyContext) => Promise<void>;
|
|
34
|
+
goHome: ({ root }: StrategyContext) => Promise<void>;
|
|
28
35
|
};
|
|
29
36
|
pagination: import("..").PaginationPrimitives;
|
|
30
37
|
};
|
package/dist/presets/rdg.js
CHANGED
|
@@ -54,35 +54,35 @@ const rdgPaginationStrategy = pagination_1.PaginationStrategies.infiniteScroll({
|
|
|
54
54
|
stabilization: stabilization_1.StabilizationStrategies.contentChanged({ timeout: 5000 })
|
|
55
55
|
});
|
|
56
56
|
const rdgNavigation = {
|
|
57
|
-
goRight: async ({ root
|
|
57
|
+
goRight: async ({ root }) => {
|
|
58
58
|
await root.evaluate((el) => {
|
|
59
59
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
60
60
|
if (grid)
|
|
61
61
|
grid.scrollLeft += 150;
|
|
62
62
|
});
|
|
63
63
|
},
|
|
64
|
-
goLeft: async ({ root
|
|
64
|
+
goLeft: async ({ root }) => {
|
|
65
65
|
await root.evaluate((el) => {
|
|
66
66
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
67
67
|
if (grid)
|
|
68
68
|
grid.scrollLeft -= 150;
|
|
69
69
|
});
|
|
70
70
|
},
|
|
71
|
-
goDown: async ({ root
|
|
71
|
+
goDown: async ({ root }) => {
|
|
72
72
|
await root.evaluate((el) => {
|
|
73
73
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
74
74
|
if (grid)
|
|
75
75
|
grid.scrollTop += 35;
|
|
76
76
|
});
|
|
77
77
|
},
|
|
78
|
-
goUp: async ({ root
|
|
78
|
+
goUp: async ({ root }) => {
|
|
79
79
|
await root.evaluate((el) => {
|
|
80
80
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
81
81
|
if (grid)
|
|
82
82
|
grid.scrollTop -= 35;
|
|
83
83
|
});
|
|
84
84
|
},
|
|
85
|
-
goHome: async ({ root
|
|
85
|
+
goHome: async ({ root }) => {
|
|
86
86
|
await root.evaluate((el) => {
|
|
87
87
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
88
88
|
if (grid) {
|
package/dist/smartRow.js
CHANGED
|
@@ -26,6 +26,9 @@ const _navigateToCell = async (params) => {
|
|
|
26
26
|
// Optimization: Check if we are ALREADY at the target cell
|
|
27
27
|
if (activeCell && activeCell.rowIndex === rowIndex && activeCell.columnIndex === index) {
|
|
28
28
|
(0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: Already at target cell {row: ${rowIndex}, col: ${index}}`);
|
|
29
|
+
// Still participate in the barrier (no-op) so peers are not left waiting.
|
|
30
|
+
if (barrier)
|
|
31
|
+
await barrier.sync(index);
|
|
29
32
|
return activeCell.locator;
|
|
30
33
|
}
|
|
31
34
|
}
|
|
@@ -63,6 +66,10 @@ const _navigateToCell = async (params) => {
|
|
|
63
66
|
const rowVisible = !rowRange || (rowIndex >= rowRange.first && rowIndex <= rowRange.last);
|
|
64
67
|
if (rowVisible && await targetReached()) {
|
|
65
68
|
(0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: col ${index} in visible range [${knownColRange.first}-${knownColRange.last}], reading directly`);
|
|
69
|
+
// Check in to the barrier without a moveAction — peers that need the scroll
|
|
70
|
+
// still supply their own action and will trigger it when all rows arrive.
|
|
71
|
+
if (barrier)
|
|
72
|
+
await barrier.sync(index);
|
|
66
73
|
return getCellLocator();
|
|
67
74
|
}
|
|
68
75
|
}
|
|
@@ -76,33 +83,12 @@ const _navigateToCell = async (params) => {
|
|
|
76
83
|
// Column is out of view. Scroll to bring it in.
|
|
77
84
|
// In synchronized mode, the last row to arrive triggers the scroll once for all rows.
|
|
78
85
|
const scrollIntoViewport = async () => {
|
|
79
|
-
//
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
(0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: col ${index} out of view, scrolling`);
|
|
86
|
-
if (viewport.scrollToColumn) {
|
|
87
|
-
await viewport.scrollToColumn(context, index);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
// Some row locators (notably rows returned by findRow()) have a logical
|
|
91
|
-
// rowIndex that is not the grid's viewport coordinate. If the target cell
|
|
92
|
-
// is already mounted after any column scroll, avoid a misleading row jump.
|
|
93
|
-
if (await targetReached()) {
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
// 2D scroll hazard: horizontal scroll may evict the target row from the DOM.
|
|
97
|
-
// scrollToRow moves the viewport to one specific row, which would evict every
|
|
98
|
-
// other row in a parallel batch — safe only when there are no peers to evict.
|
|
99
|
-
if ((!barrier || !barrier.isParallel()) && viewport.scrollToRow && viewport.getVisibleRowRange) {
|
|
100
|
-
const rowRange = await viewport.getVisibleRowRange(context);
|
|
101
|
-
const rowOutOfView = rowRange && (rowIndex < rowRange.first || rowIndex > rowRange.last);
|
|
102
|
-
if (rowOutOfView) {
|
|
103
|
-
(0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: row ${rowIndex} out of view after col scroll, recovering`);
|
|
104
|
-
await viewport.scrollToRow(context, rowIndex);
|
|
105
|
-
}
|
|
86
|
+
// Always scroll — scrollToColumn is idempotent (bounds-checks before acting).
|
|
87
|
+
// The trigger row may already have the cell via overscan, but other rows in the
|
|
88
|
+
// batch might not; skipping the scroll here would silently starve them.
|
|
89
|
+
(0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: col ${index} out of view, scrolling`);
|
|
90
|
+
if (viewport.scrollToColumn) {
|
|
91
|
+
await viewport.scrollToColumn(context, index);
|
|
106
92
|
}
|
|
107
93
|
};
|
|
108
94
|
if (barrier) {
|
|
@@ -111,6 +97,27 @@ const _navigateToCell = async (params) => {
|
|
|
111
97
|
else {
|
|
112
98
|
await scrollIntoViewport();
|
|
113
99
|
}
|
|
100
|
+
// Per-row 2D recovery: horizontal scroll may evict rows from the vertical viewport
|
|
101
|
+
// (scrollbar layout shift) or rows may simply be outside the virtual row window.
|
|
102
|
+
// Recovery is serialized via the barrier's mutex so concurrent rows don't race on
|
|
103
|
+
// scrollTop — adjacent rows often appear in view for free after the previous recovery.
|
|
104
|
+
// scrollToRow must only adjust scrollTop (not scrollLeft) to preserve the column
|
|
105
|
+
// position established by scrollToColumn.
|
|
106
|
+
if (!await targetReached() && viewport.scrollToRow && typeof rowIndex === 'number') {
|
|
107
|
+
const scrollToRow = viewport.scrollToRow;
|
|
108
|
+
const recover = async () => {
|
|
109
|
+
if (!await targetReached()) {
|
|
110
|
+
(0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: row ${rowIndex} evicted by col scroll, recovering`);
|
|
111
|
+
await scrollToRow(context, rowIndex);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
if (barrier) {
|
|
115
|
+
await barrier.runExclusiveRecovery(recover);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
await recover();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
114
121
|
if (await targetReached()) {
|
|
115
122
|
return getCellLocator();
|
|
116
123
|
}
|
package/dist/typeContext.d.ts
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* This file is generated by scripts/embed-types.mjs
|
|
4
4
|
* It contains the raw text of types.ts to provide context for LLM prompts.
|
|
5
5
|
*/
|
|
6
|
-
export declare const TYPE_CONTEXT = "\n/**\n * Flexible selector type - can be a CSS string, function returning a Locator, or Locator itself.\n * @example\n * // String selector\n * rowSelector: 'tbody tr'\n * \n * // Function selector\n * headerSelector: (root) => root.locator('[role=\"columnheader\"]')\n */\nexport type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);\n\n/**\n * Value used to filter rows.\n * - string/number/RegExp: filter by text content of the cell.\n * - function: filter by custom locator logic within the cell.\n * @example\n * // Text filter\n * { Name: 'John' }\n * \n * // Custom locator filter (e.g. checkbox is checked)\n * { Status: (cell) => cell.locator('input:checked') }\n */\nexport type FilterValue = string | RegExp | number | ((cell: Locator) => Locator);\n\n/**\n * Function to get a cell locator given row, column info.\n * Replaces the old cellResolver.\n */\nexport type GetCellLocatorFn = (args: {\n row: Locator;\n /** The root locator passed to useTable(). Useful for re-querying stale row locators. */\n root: Locator;\n columnName: string;\n columnIndex: number;\n rowIndex?: number;\n page: Page;\n config: FinalTableConfig<any>;\n}) => Locator;\n\n/**\n * Hook called before each cell value is read in `toJSON` (and `columnOverrides.read`).\n *\n * Use this to scroll off-screen columns into view in **horizontally** virtualized tables,\n * wait for lazy-rendered content (popovers, tooltips, async cell renderers), or perform\n * any other pre-read setup that doesn't involve Y-axis scrolling.\n *\n * ---\n *\n * **\u26A0\uFE0F Y-scroll footgun \u2014 do NOT call `scrollIntoViewIfNeeded()` on row-virtualized grids.**\n *\n * `scrollIntoViewIfNeeded` adjusts *both* scroll axes. On grids that recycle DOM nodes\n * based on the Y position (MUI DataGrid, AG Grid, react-window, etc.) calling it will\n * shift the viewport vertically, unmounting the row you are currently reading and\n * silently returning stale or empty cell values for the remainder of the row.\n *\n * Safe uses:\n * - Column-only (X-axis) virtualization where rows are always in the DOM.\n * - Calling `scrollIntoViewIfNeeded` on the **header cell** only, when that header is\n * guaranteed not to trigger a Y-scroll (e.g. sticky header grids).\n *\n * For grids with **both** row and column virtualization, use the `viewport` strategy\n * instead \u2014 it drives explicit `scrollToRow` / `scrollToColumn` calls and is aware of\n * the virtualization lifecycle.\n *\n * @example\n * // Safe: column-only horizontal virtualization (rows always in DOM)\n * strategies: {\n * beforeCellRead: async ({ columnName, getHeaderCell }) => {\n * const header = await getHeaderCell(columnName);\n * await header.scrollIntoViewIfNeeded(); // only scrolls X \u2014 rows stay mounted\n * }\n * }\n *\n * @example\n * // Safe: wait for a lazy-rendered popover/tooltip before reading its text\n * strategies: {\n * beforeCellRead: async ({ cell }) => {\n * await cell.hover();\n * await cell.page().waitForSelector('.cell-tooltip', { state: 'visible' });\n * }\n * }\n */\nexport type BeforeCellReadFn = (args: {\n /** The resolved cell locator */\n cell: Locator;\n columnName: string;\n columnIndex: number;\n row: Locator;\n page: Page;\n root: Locator;\n /** Resolves a column name to its header cell locator */\n getHeaderCell: (columnName: string) => Promise<Locator>;\n}) => Promise<void>;\n\n/**\n * Function to get the currently active/focused cell.\n * Returns null if no cell is active.\n */\nexport type GetActiveCellFn = (args: TableContext) => Promise<{\n rowIndex: number;\n columnIndex: number;\n columnName?: string;\n locator: Locator;\n} | null>;\n\n/**\n * Viewport oracle strategies for virtualized tables.\n *\n * These tell the library *what is currently in the DOM* rather than *how to move*.\n * When present, the cell-reading engine uses them to jump directly to a target\n * row/column instead of stepping blindly with navigation primitives.\n *\n * This is the primary fix for the 2D scroll hazard: scrolling right to bring a\n * column into view can knock rows out of the vertical viewport (and vice versa).\n * With `getVisibleRowRange` the engine detects this and calls `scrollToRow` to\n * restore the row before reading \u2014 eliminating the hazard without polling loops.\n *\n * All members are optional. Supply whichever the underlying grid exposes:\n * - Range oracles alone enable hazard detection with graceful fallback to navigation primitives.\n * - Scroll primitives alone enable direct jumps without range awareness.\n * - Both together give the most reliable, fastest path.\n *\n * @example\n * // MUI DataGrid via apiRef\n * strategies: {\n * viewport: {\n * getVisibleRowRange: async ({ root }) =>\n * root.evaluate(el => {\n * const api = (el as any).__muiDataGrid__;\n * return { first: api.getFirstVisibleRow(), last: api.getLastVisibleRow() };\n * }),\n * scrollToRow: async ({ root }, rowIndex) =>\n * root.evaluate((el, idx) =>\n * (el as any).__muiDataGrid__.scrollToIndexes({ rowIndex: idx }), rowIndex),\n * scrollToColumn: async ({ root }, colIndex) =>\n * root.evaluate((el, idx) =>\n * (el as any).__muiDataGrid__.scrollToIndexes({ colIndex: idx }), colIndex),\n * }\n * }\n *\n * @example\n * // aria-rowindex / aria-colindex DOM fallback (works without internal API access)\n * strategies: {\n * viewport: {\n * getVisibleRowRange: async ({ root }) =>\n * root.evaluate(el => {\n * const rows = [...el.querySelectorAll('[role=\"row\"][aria-rowindex]')];\n * const idxs = rows.map(r => Number(r.getAttribute('aria-rowindex')) - 1);\n * return { first: Math.min(...idxs), last: Math.max(...idxs) };\n * }),\n * }\n * }\n */\nexport interface ViewportStrategy {\n /**\n * Returns the 0-based index range of rows currently rendered in the DOM.\n * Used to detect when a target row has been scrolled out of view and needs recovery.\n */\n getVisibleRowRange?: (context: TableContext) => Promise<{ first: number; last: number }>;\n\n /**\n * Returns the 0-based index range of columns currently rendered in the DOM.\n * Used to detect when a target column is not yet mounted before reading.\n */\n getVisibleColumnRange?: (context: TableContext) => Promise<{ first: number; last: number }>;\n\n /**\n * Scrolls or jumps directly to make a row visible by 0-based index.\n * Replaces blind goDown()/goUp() step loops for grids that expose a scroll API.\n */\n scrollToRow?: (context: TableContext, rowIndex: number) => Promise<void>;\n\n /**\n * Scrolls or jumps directly to make a column visible by 0-based index.\n * Replaces blind goRight()/goLeft() step loops for grids that expose a scroll API.\n */\n scrollToColumn?: (context: TableContext, colIndex: number) => Promise<void>;\n\n /**\n * When true, disables the automatic memoization of getVisibleColumnRange and\n * getVisibleRowRange results. By default the library caches each range value and\n * invalidates it after the corresponding scroll call, eliminating redundant DOM\n * evaluate() round-trips between scrolls.\n */\n disableCache?: boolean;\n}\n\n\n/**\n * SmartCell - A Playwright Locator with table-aware methods for single-cell operations.\n * \n * Extends all standard Locator methods (click, isVisible, etc.).\n */\nexport type SmartCell = Locator & {\n /**\n * Scrolls/paginates to bring this specific cell into view using the configured strategies.\n * Useful when the grid is horizontally virtualized and the column must be scrolled\n * into view before it can be interacted with or read.\n */\n bringIntoView(): Promise<void>;\n};\n\n\n/**\n * SmartRow - A Playwright Locator with table-aware methods.\n * \n * Extends all standard Locator methods (click, isVisible, etc.) with table-specific functionality.\n * \n * @example\n * const row = table.getRow({ Name: 'John Doe' });\n * await row.click(); // Standard Locator method\n * const email = row.getCell('Email'); // Table-aware method\n * const data = await row.toJSON(); // Extract all row data\n * await row.smartFill({ Name: 'Jane', Status: 'Active' }); // Fill form fields\n */\nexport type SmartRow<T = any> = Locator & {\n /** Optional row index (0-based) if known */\n rowIndex?: number;\n\n /** Optional page index this row was found on (0-based) */\n tablePageIndex?: number;\n\n /** Reference to the parent TableResult */\n table: TableResult<T>;\n\n /**\n * Get a cell locator by column name.\n * @param column - Column name (case-sensitive)\n * @returns SmartCell (Locator + bringIntoView)\n * @example\n * const emailCell = row.getCell('Email');\n * await emailCell.bringIntoView();\n * await expect(emailCell).toHaveText('john@example.com');\n */\n getCell(column: string): SmartCell;\n\n /**\n * Extract all cell data as a key-value object.\n * @param options - Optional configuration\n * @param options.columns - Specific columns to extract (extracts all if not specified)\n * @returns Promise resolving to row data\n * @example\n * const data = await row.toJSON();\n * // { Name: 'John', Email: 'john@example.com', ... }\n * \n * const partial = await row.toJSON({ columns: ['Name', 'Email'] });\n * // { Name: 'John', Email: 'john@example.com' }\n */\n toJSON(options?: { columns?: string[] }): Promise<T>;\n\n /**\n * Scrolls/paginates to bring this row into view.\n * Works when row position metadata is known (e.g., from getRowByIndex, findRow,\n * findRows, filter, or async iteration).\n * @throws Error if row position metadata is unknown\n */\n bringIntoView(): Promise<void>;\n\n /**\n * Intelligently fills form fields in the row.\n * Automatically detects input types (text, select, checkbox, contenteditable).\n * \n * @param data - Column-value pairs to fill\n * @param options - Optional configuration\n * @param options.inputMappers - Custom input selectors per column\n * @example\n * // Auto-detection\n * await row.smartFill({ Name: 'John', Status: 'Active', Subscribe: true });\n * \n * // Custom input mappers\n * await row.smartFill(\n * { Name: 'John' },\n * { inputMappers: { Name: (cell) => cell.locator('.custom-input') } }\n * );\n */\n smartFill: (data: Partial<T> | Record<string, any>, options?: FillOptions) => Promise<void>;\n\n /**\n * Returns whether the row exists in the DOM (i.e. is not a sentinel row).\n */\n wasFound(): boolean;\n};\n\nexport type StrategyContext = TableContext & {\n rowLocator?: Locator;\n rowIndex?: number;\n};\n\n/**\n * Defines the contract for a sorting strategy.\n */\nexport interface SortingStrategy {\n /**\n * Performs the sort action on a column.\n */\n doSort(options: {\n columnName: string;\n direction: 'asc' | 'desc';\n context: StrategyContext;\n }): Promise<void>;\n\n /**\n * Retrieves the current sort state of a column.\n */\n getSortState(options: {\n columnName: string;\n context: StrategyContext;\n }): Promise<'asc' | 'desc' | 'none'>;\n}\n\n/**\n * Debug configuration for development and troubleshooting\n */\nexport type DebugConfig = {\n /**\n * Slow down operations for debugging\n * - number: Apply same delay to all operations (ms)\n * - object: Granular delays per operation type\n */\n slow?: number | {\n pagination?: number;\n getCell?: number;\n findRow?: number;\n default?: number;\n };\n /**\n * Log level for debug output\n * - 'verbose': All logs (verbose, info, error)\n * - 'info': Info and error logs only\n * - 'error': Error logs only\n * - 'none': No logs\n */\n logLevel?: 'verbose' | 'info' | 'error' | 'none';\n};\n\nexport interface TableContext<T = any> {\n root: Locator;\n config: FinalTableConfig<T>;\n page: Page;\n resolve: (selector: Selector, parent: Locator | Page) => Locator;\n /** Resolves a column name to its header cell locator. Available after table is initialized. */\n getHeaderCell?: (columnName: string) => Promise<Locator>;\n /** Returns all column names in order. Available after table is initialized. */\n getHeaders?: () => Promise<string[]>;\n /** Scrolls the table horizontally to bring the given column's header into view. */\n scrollToColumn?: (columnName: string) => Promise<void>;\n}\n\nexport interface PaginationPrimitives {\n /** Classic \"Next Page\" or \"Scroll Down\" */\n goNext?: (context: TableContext) => Promise<boolean>;\n\n /** Classic \"Previous Page\" or \"Scroll Up\" */\n goPrevious?: (context: TableContext) => Promise<boolean>;\n\n /** Bulk skip forward multiple pages at once. Returns number of pages skipped. */\n goNextBulk?: (context: TableContext) => Promise<boolean | number>;\n\n /** Bulk skip backward multiple pages at once. Returns number of pages skipped. */\n goPreviousBulk?: (context: TableContext) => Promise<boolean | number>;\n\n /** Jump to first page / scroll to top */\n goToFirst?: (context: TableContext) => Promise<boolean>;\n\n /** Jump to last page / scroll to bottom */\n goToLast?: (context: TableContext) => Promise<boolean>;\n\n /**\n * Fetch the total number of pages currently available.\n * Can be used to optimize pagination paths (e.g. jumping to last page and going backwards).\n */\n getTotalPages?: (context: TableContext) => Promise<number | null>;\n\n /**\n * Jump to specific page index (0-indexed).\n * Can be full-range (e.g. page number input: any page works) or windowed (e.g. only visible links 6\u201314).\n * Return false when the page is not reachable in the current UI; the library will step toward the target (goNextBulk/goNext or goPreviousBulk/goPrevious) and retry goToPage until it succeeds.\n */\n goToPage?: (pageIndex: number, context: TableContext) => Promise<boolean>;\n\n /** How many pages one goNextBulk() advances. Used by navigation path planner for optimal bringIntoView. */\n nextBulkPages?: number;\n\n /** How many pages one goPreviousBulk() goes back. Used by navigation path planner for optimal bringIntoView. */\n previousBulkPages?: number;\n\n /**\n * Called once during init() to sync the library's page counter with the actual DOM state.\n * Use when a table may open on a page other than the first (e.g. a deep-linked URL that\n * lands on page 5). Returns a 0-indexed page number.\n * @example\n * detectCurrentPage: async (root) => {\n * const text = await root.locator('[aria-current=\"page\"]').textContent();\n * return parseInt(text ?? '1') - 1;\n * }\n */\n detectCurrentPage?: (root: import('@playwright/test').Locator) => number | Promise<number>;\n}\n\nexport type PaginationStrategy = PaginationPrimitives;\n\nexport type DedupeStrategy = (row: SmartRow) => string | number | Promise<string | number>;\n\n\n\nexport type FillStrategy = (options: {\n row: SmartRow;\n columnName: string;\n value: any;\n index: number;\n page: Page;\n rootLocator: Locator;\n config: FinalTableConfig<any>;\n table: TableResult; // The parent table instance\n fillOptions?: FillOptions;\n}) => Promise<void>;\n\nexport interface ColumnOverride<TValue = any> {\n /** \n * How to extract the value from the cell.\n * `context` provides access to the parent row, permitting multi-cell logic or bypassing the default cell locator.\n */\n read?: (cell: Locator) => Promise<TValue> | TValue;\n\n /** \n * How to fill the cell with a new value. (Replaces smartFill default logic)\n * Provides the current value (via `read`) if a `write` wants to check state first.\n */\n write?: (params: {\n cell: Locator;\n targetValue: TValue;\n currentValue?: TValue;\n row: SmartRow<any>;\n }) => Promise<void>;\n}\n\nexport type { HeaderStrategy } from './strategies/headers';\n\n/**\n * Strategy to resolve column names (string or regex) to their index.\n */\n// fallow-ignore-next-line unused-type\nexport type { ColumnResolutionStrategy } from './strategies/resolution';\n\n/**\n * Strategy to filter rows based on criteria. Applied when using getRow/findRow/findRows with filters.\n * The default engine handles string, RegExp, number, and function (cell) => Locator filters.\n */\nexport interface FilterStrategy {\n apply(options: {\n rows: Locator;\n filter: { column: string, value: FilterValue };\n colIndex: number;\n tableContext: TableContext;\n }): Locator;\n}\n\n/**\n * Strategy to check if the table or rows are loading. Used after pagination/sort to wait for content.\n * E.g. isHeaderLoading for init stability; isTableLoading after sort/pagination.\n */\nexport interface LoadingStrategy {\n isTableLoading?: (context: TableContext) => Promise<boolean>;\n isRowLoading?: (row: SmartRow) => Promise<boolean>;\n isHeaderLoading?: (context: TableContext) => Promise<boolean>;\n\n /**\n * How long (ms) to wait for a loading row to resolve before applying onRowLoadingTimeout.\n * When not set, loading rows are immediately skipped (backward-compatible behavior).\n */\n rowLoadingTimeout?: number;\n\n /**\n * What to do when a row is still loading after rowLoadingTimeout ms.\n * - 'skip': drop the row from results (matches legacy skip behavior)\n * - 'read-as-is': include the row even though it's still loading (default)\n * - 'throw': throw an error with row index and timeout info\n * Defaults to 'read-as-is' when rowLoadingTimeout is set.\n */\n onRowLoadingTimeout?: 'skip' | 'read-as-is' | 'throw';\n\n /**\n * Predicate called before reading each cell. Return true if the cell is still loading.\n * When cellLoadingTimeout is also set, the engine waits up to that many ms for the\n * cell to resolve before applying onCellLoadingTimeout.\n */\n isCellLoading?: (cell: import('@playwright/test').Locator, columnName: string, row: SmartRow) => Promise<boolean>;\n\n /**\n * How long (ms) to wait for a loading cell to resolve before applying onCellLoadingTimeout.\n * When not set and isCellLoading returns true, the cell is read as-is immediately.\n */\n cellLoadingTimeout?: number;\n\n /**\n * What to do when a cell is still loading after cellLoadingTimeout ms.\n * - 'skip': use empty string for this cell value\n * - 'read-as-is': read the cell content even though it's still loading (default)\n * - 'throw': throw an error with column name, row index and timeout info\n * - callback: called with (cell, columnName, row); its return value becomes the cell's string value\n * Defaults to 'read-as-is' when cellLoadingTimeout is set.\n */\n onCellLoadingTimeout?:\n | 'skip'\n | 'read-as-is'\n | 'throw'\n | ((cell: import('@playwright/test').Locator, columnName: string, row: SmartRow) => Promise<string>);\n}\n\n/**\n * Organized container for all table interaction strategies.\n */\nexport interface TableStrategies {\n /** Strategy for discovering/scanning headers */\n header?: HeaderStrategy;\n /** Primitive navigation functions (goUp, goDown, goLeft, goRight, goHome) */\n navigation?: NavigationPrimitives;\n\n /** Strategy for filling form inputs */\n fill?: FillStrategy;\n /** Strategy for paginating through data */\n pagination?: PaginationStrategy;\n /** Strategy for sorting columns */\n sorting?: SortingStrategy;\n /** Strategy for deduplicating rows during iteration/scrolling */\n dedupe?: DedupeStrategy;\n /** Function to get a cell locator */\n getCellLocator?: GetCellLocatorFn;\n /** Function to get the currently active/focused cell */\n getActiveCell?: GetActiveCellFn;\n /**\n * Strategy for filtering rows. If present, FilterEngine will delegate filter application\n * to this pluggable strategy.\n */\n filter?: FilterStrategy;\n /**\n * Hook called before each cell value is read in toJSON and columnOverrides.read.\n * Fires for both the default innerText extraction and custom read mappers.\n * Useful for scrolling off-screen columns into view in horizontally virtualized tables.\n */\n beforeCellRead?: BeforeCellReadFn;\n /**\n * Strategy for detecting loading states. Use this for table-, row-, and header-level readiness.\n * E.g. after sort/pagination, the engine uses loading.isTableLoading when present.\n */\n loading?: LoadingStrategy;\n\n /**\n * Viewport oracle strategies for 2D virtualized tables (e.g. MUI DataGrid, AG Grid,\n * Braintrust-style grids where both rows and columns are virtualized simultaneously).\n *\n * When present, the cell-reading engine uses these to jump directly to the target\n * row/column and to detect the 2D scroll hazard (scrolling to reveal a column can\n * knock rows out of the vertical viewport, and vice versa).\n *\n * Completely optional and additive \u2014 existing `navigation` primitives remain the fallback.\n */\n viewport?: ViewportStrategy;\n}\n\n\nexport interface TableConfig<T = any> {\n /** Selector for the table headers */\n headerSelector?: string | ((root: Locator) => Locator);\n /** Selector for the table rows */\n rowSelector?: string;\n /** Selector for the cells within a row */\n cellSelector?: string | ((row: Locator) => Locator);\n /** Number of pages to scan for verification */\n maxPages?: number;\n /**\n * Default concurrency strategy for iteration methods.\n * Can be overridden by the options passed to forEach, map, or filter.\n */\n concurrency?: RowIterationMode;\n /** Hook to rename columns dynamically */\n headerTransformer?: (args: { text: string, index: number, locator: Locator, seenHeaders: Set<string> }) => string | Promise<string>;\n /** Automatically scroll to table on init */\n autoScroll?: boolean;\n /** Debug options for development and troubleshooting */\n debug?: DebugConfig;\n /** Reset hook */\n onReset?: (context: TableContext) => Promise<void>;\n /** All interaction strategies */\n strategies?: TableStrategies;\n\n /**\n * Unified interface for reading and writing data to specific columns.\n * Overrides both default extraction (toJSON) and filling (smartFill) logic.\n */\n columnOverrides?: Partial<Record<keyof T, ColumnOverride<T[keyof T]>>>;\n}\n\nexport interface FinalTableConfig<T = any> extends TableConfig<T> {\n headerSelector: string | ((root: Locator) => Locator);\n rowSelector: string;\n cellSelector: string | ((row: Locator) => Locator);\n maxPages: number;\n autoScroll: boolean;\n concurrency?: RowIterationMode;\n debug?: TableConfig['debug'];\n headerTransformer: (args: { text: string, index: number, locator: Locator, seenHeaders: Set<string> }) => string | Promise<string>;\n onReset: (context: TableContext) => Promise<void>;\n strategies: TableStrategies;\n}\n\n\nexport interface FillOptions {\n /**\n * Custom input mappers for specific columns.\n * Maps column names to functions that return the input locator for that cell.\n */\n inputMappers?: Record<string, (cell: Locator) => Locator>;\n}\n\n\n\n/** Callback context passed to forEach, map, and filter. */\nexport type RowIterationContext<T = any> = {\n row: SmartRow<T>;\n /** 0-based iteration counter \u2014 the order this row was visited, not its DOM position or grid identity. @deprecated Use `index` instead. `rowIndex` will be removed in v7.0.0. */\n rowIndex: number;\n /** 0-based iteration counter \u2014 the order this row was visited, not its DOM position or grid identity. */\n index: number;\n /** 0-based page index \u2014 which page this row was collected from. */\n pageIndex: number;\n stop: () => void;\n};\n\n/** Concurrency modes for row iteration. */\nexport type RowIterationMode = 'parallel' | 'sequential' | 'synchronized';\n\n/** Shared options for forEach, map, and filter. */\nexport type RowIterationOptions = {\n /** Maximum number of pages to iterate. Defaults to config.maxPages. */\n maxPages?: number;\n /**\n * Concurrency strategy for iteration.\n * - 'parallel': Full parallel execution of both navigation and actions.\n * - 'synchronized': Parallel navigation (lock-step) with serial actions.\n * - 'sequential': Strictly serial one-at-a-time execution. No parallel navigation.\n * @default 'parallel' (for map), 'sequential' (for forEach/filter)\n */\n concurrency?: RowIterationMode;\n /**\n * Deduplication strategy. Use when rows may repeat across iterations\n * (e.g. infinite scroll tables). Returns a unique key per row.\n */\n dedupe?: DedupeStrategy;\n /**\n * When true, use goNextBulk (if present) to advance pages during iteration.\n * @default false \u2014 uses goNext for one-page-at-a-time advancement\n */\n useBulkPagination?: boolean;\n};\n\nexport interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number; index: number; pageIndex: number }> {\n /**\n * Represents the current page index of the table's DOM.\n * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.\n */\n currentPageIndex: number;\n\n /**\n * Initializes the table by resolving headers. Must be called before using sync methods.\n * @param options Optional timeout for header resolution (default: 3000ms)\n */\n init(options?: { timeout?: number }): Promise<TableResult<T>>;\n\n /**\n * SYNC: Checks if the table has been initialized.\n * @returns true if init() has been called and completed, false otherwise\n */\n isInitialized(): boolean;\n\n getHeaders: () => Promise<string[]>;\n getHeaderCell: (columnName: string) => Promise<Locator>;\n\n /**\n * Finds a row by filters on the current page only. Returns immediately (sync).\n * Throws error if table is not initialized.\n * @note The returned SmartRow may have `rowIndex` as 0 when the match is not the first row.\n * Use getRowByIndex(index) when you need a known index (e.g. for bringIntoView()).\n */\n getRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean }\n ) => SmartRow<T>;\n\n /**\n * Gets a row by 0-based index on the current page.\n * Throws error if table is not initialized.\n * @param index 0-based row index\n */\n getRowByIndex: (\n index: number\n ) => SmartRow<T>;\n\n /**\n * ASYNC: Searches for a single row across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRow<T>>;\n\n /**\n * ASYNC: Searches for all matching rows across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match (omit or pass {} for all rows)\n * @param options - Search options including exact match and max pages\n */\n findRows: (\n filters?: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number, useBulkPagination?: boolean }\n ) => Promise<SmartRowArray<T>>;\n\n /**\n * Navigates to a specific column using the configured CellNavigationStrategy.\n */\n scrollToColumn: (columnName: string) => Promise<void>;\n\n /**\n * Counts the number of rows currently on the page.\n * Does not paginate.\n */\n countRows: () => Promise<number>;\n\n /**\n * Iterates over rows and extracts the value of a single column.\n * More efficient than map + toJSON for single-column extraction.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;\n\n /**\n * Iterates over rows and extracts the value of a single column as strings.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;\n\n\n /**\n * Resets the table state (clears cache, flags) and invokes the onReset strategy.\n */\n reset: () => Promise<void>;\n\n /**\n * Revalidates the table's structure (headers, columns) without resetting pagination or state.\n * Useful when columns change visibility or order dynamically.\n */\n revalidate: () => Promise<void>;\n\n /**\n * Iterates every row across all pages, calling the callback for side effects.\n * Execution is sequential by default (safe for interactions like clicking/filling).\n * Call `stop()` in the callback to end iteration early.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * await table.forEach(async ({ row, stop }) => {\n * if (await row.getCell('Status').innerText() === 'Done') stop();\n * await row.getCell('Checkbox').click();\n * });\n */\n forEach(\n callback: (ctx: RowIterationContext<T>) => void | Promise<void>,\n options?: RowIterationOptions\n ): Promise<void>;\n\n /**\n * Transforms every row across all pages into a value. Returns a flat array.\n * Execution is parallel within each page by default (safe for reads).\n * Call `stop()` to halt after the current page finishes.\n *\n * > **\u26A0\uFE0F UI Interactions:** `map` defaults to `concurrency: 'parallel'`. If your callback opens popovers,\n * > fills inputs, or otherwise mutates UI state, pass `concurrency: 'sequential'` (or `'synchronized'`\n * > when navigation must stay lock-step) to avoid overlapping interactions.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * // Data extraction \u2014 parallel is safe\n * const emails = await table.map(({ row }) => row.getCell('Email').innerText());\n *\n * @example\n * // UI interactions \u2014 use sequential (or synchronized) concurrency\n * const assignees = await table.map(async ({ row }) => {\n * await row.getCell('Assignee').locator('button').click();\n * const name = await page.locator('.popover .name').innerText();\n * await page.keyboard.press('Escape');\n * return name;\n * }, { concurrency: 'sequential' });\n */\n map<R>(\n callback: (ctx: RowIterationContext<T>) => R | Promise<R>,\n options?: RowIterationOptions\n ): Promise<R[]>;\n\n /**\n * Filters rows across all pages by an async predicate. Returns a SmartRowArray.\n * Rows are returned as-is \u2014 call `bringIntoView()` on each if needed.\n * Execution is sequential by default.\n *\n * @param predicate - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * const active = await table.filter(async ({ row }) =>\n * await row.getCell('Status').innerText() === 'Active'\n * );\n */\n filter(\n predicate: (ctx: RowIterationContext<T>) => boolean | Promise<boolean>,\n options?: RowIterationOptions\n ): Promise<SmartRowArray<T>>;\n\n /**\n * Provides access to sorting actions and assertions.\n */\n sorting: {\n /**\n * Applies the configured sorting strategy to the specified column.\n * @param columnName The name of the column to sort.\n * @param direction The direction to sort ('asc' or 'desc').\n */\n apply(columnName: string, direction: 'asc' | 'desc'): Promise<void>;\n /**\n * Gets the current sort state of a column using the configured sorting strategy.\n * @param columnName The name of the column to check.\n * @returns A promise that resolves to 'asc', 'desc', or 'none'.\n */\n getState(columnName: string): Promise<'asc' | 'desc' | 'none'>;\n };\n\n /**\n * Generate an AI-friendly configuration prompt for debugging.\n * Outputs table HTML and TypeScript definitions to help AI assistants generate config.\n * Automatically throws an Error containing the prompt.\n */\n generateConfig: () => Promise<void>;\n\n /**\n * @deprecated Use `generateConfig()` instead. Will be removed in v7.0.0.\n */\n generateConfigPrompt: () => Promise<void>;\n}\n";
|
|
6
|
+
export declare const TYPE_CONTEXT = "\n/**\n * Flexible selector type - can be a CSS string, function returning a Locator, or Locator itself.\n * @example\n * // String selector\n * rowSelector: 'tbody tr'\n * \n * // Function selector\n * headerSelector: (root) => root.locator('[role=\"columnheader\"]')\n */\nexport type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);\n\n/**\n * Value used to filter rows.\n * - string/number/RegExp: filter by text content of the cell.\n * - function: filter by custom locator logic within the cell.\n * @example\n * // Text filter\n * { Name: 'John' }\n * \n * // Custom locator filter (e.g. checkbox is checked)\n * { Status: (cell) => cell.locator('input:checked') }\n */\nexport type FilterValue = string | RegExp | number | ((cell: Locator) => Locator);\n\n/**\n * Function to get a cell locator given row, column info.\n * Replaces the old cellResolver.\n */\nexport type GetCellLocatorFn = (args: {\n row: Locator;\n /** The root locator passed to useTable(). Useful for re-querying stale row locators. */\n root: Locator;\n columnName: string;\n columnIndex: number;\n rowIndex?: number;\n page: Page;\n config: FinalTableConfig<any>;\n}) => Locator;\n\n/**\n * Hook called before each cell value is read in `toJSON` (and `columnOverrides.read`).\n *\n * Use this to scroll off-screen columns into view in **horizontally** virtualized tables,\n * wait for lazy-rendered content (popovers, tooltips, async cell renderers), or perform\n * any other pre-read setup that doesn't involve Y-axis scrolling.\n *\n * ---\n *\n * **\u26A0\uFE0F Y-scroll footgun \u2014 do NOT call `scrollIntoViewIfNeeded()` on row-virtualized grids.**\n *\n * `scrollIntoViewIfNeeded` adjusts *both* scroll axes. On grids that recycle DOM nodes\n * based on the Y position (MUI DataGrid, AG Grid, react-window, etc.) calling it will\n * shift the viewport vertically, unmounting the row you are currently reading and\n * silently returning stale or empty cell values for the remainder of the row.\n *\n * Safe uses:\n * - Column-only (X-axis) virtualization where rows are always in the DOM.\n * - Calling `scrollIntoViewIfNeeded` on the **header cell** only, when that header is\n * guaranteed not to trigger a Y-scroll (e.g. sticky header grids).\n *\n * For grids with **both** row and column virtualization, use the `viewport` strategy\n * instead \u2014 it drives explicit `scrollToRow` / `scrollToColumn` calls and is aware of\n * the virtualization lifecycle.\n *\n * @example\n * // Safe: column-only horizontal virtualization (rows always in DOM)\n * strategies: {\n * beforeCellRead: async ({ columnName, getHeaderCell }) => {\n * const header = await getHeaderCell(columnName);\n * await header.scrollIntoViewIfNeeded(); // only scrolls X \u2014 rows stay mounted\n * }\n * }\n *\n * @example\n * // Safe: wait for a lazy-rendered popover/tooltip before reading its text\n * strategies: {\n * beforeCellRead: async ({ cell }) => {\n * await cell.hover();\n * await cell.page().waitForSelector('.cell-tooltip', { state: 'visible' });\n * }\n * }\n */\nexport type BeforeCellReadFn = (args: {\n /** The resolved cell locator */\n cell: Locator;\n columnName: string;\n columnIndex: number;\n row: Locator;\n page: Page;\n root: Locator;\n /** Resolves a column name to its header cell locator */\n getHeaderCell: (columnName: string) => Promise<Locator>;\n}) => Promise<void>;\n\n/**\n * Function to get the currently active/focused cell.\n * Returns null if no cell is active.\n */\nexport type GetActiveCellFn = (args: TableContext) => Promise<{\n rowIndex: number;\n columnIndex: number;\n columnName?: string;\n locator: Locator;\n} | null>;\n\n/**\n * Viewport oracle strategies for virtualized tables.\n *\n * These tell the library *what is currently in the DOM* rather than *how to move*.\n * When present, the cell-reading engine uses them to jump directly to a target\n * row/column instead of stepping blindly with navigation primitives.\n *\n * This is the primary fix for the 2D scroll hazard: scrolling right to bring a\n * column into view can knock rows out of the vertical viewport (and vice versa).\n * With `getVisibleRowRange` the engine detects this and calls `scrollToRow` to\n * restore the row before reading \u2014 eliminating the hazard without polling loops.\n *\n * All members are optional. Supply whichever the underlying grid exposes:\n * - Range oracles alone enable hazard detection with graceful fallback to navigation primitives.\n * - Scroll primitives alone enable direct jumps without range awareness.\n * - Both together give the most reliable, fastest path.\n *\n * @example\n * // MUI DataGrid via apiRef\n * strategies: {\n * viewport: {\n * getVisibleRowRange: async ({ root }) =>\n * root.evaluate(el => {\n * const api = (el as any).__muiDataGrid__;\n * return { first: api.getFirstVisibleRow(), last: api.getLastVisibleRow() };\n * }),\n * scrollToRow: async ({ root }, rowIndex) =>\n * root.evaluate((el, idx) =>\n * (el as any).__muiDataGrid__.scrollToIndexes({ rowIndex: idx }), rowIndex),\n * scrollToColumn: async ({ root }, colIndex) =>\n * root.evaluate((el, idx) =>\n * (el as any).__muiDataGrid__.scrollToIndexes({ colIndex: idx }), colIndex),\n * }\n * }\n *\n * @example\n * // aria-rowindex / aria-colindex DOM fallback (works without internal API access)\n * strategies: {\n * viewport: {\n * getVisibleRowRange: async ({ root }) =>\n * root.evaluate(el => {\n * const rows = [...el.querySelectorAll('[role=\"row\"][aria-rowindex]')];\n * const idxs = rows.map(r => Number(r.getAttribute('aria-rowindex')) - 1);\n * return { first: Math.min(...idxs), last: Math.max(...idxs) };\n * }),\n * }\n * }\n */\nexport interface ViewportStrategy {\n /**\n * Returns the 0-based index range of rows currently rendered in the DOM.\n * Used to detect when a target row has been scrolled out of view and needs recovery.\n */\n getVisibleRowRange?: (context: TableContext) => Promise<{ first: number; last: number }>;\n\n /**\n * Returns the 0-based index range of columns currently rendered in the DOM.\n * Used to detect when a target column is not yet mounted before reading.\n */\n getVisibleColumnRange?: (context: TableContext) => Promise<{ first: number; last: number }>;\n\n /**\n * Scrolls or jumps directly to make a row visible by 0-based index.\n * Replaces blind goDown()/goUp() step loops for grids that expose a scroll API.\n */\n scrollToRow?: (context: TableContext, rowIndex: number) => Promise<void>;\n\n /**\n * Scrolls or jumps directly to make a column visible by 0-based index.\n * Replaces blind goRight()/goLeft() step loops for grids that expose a scroll API.\n */\n scrollToColumn?: (context: TableContext, colIndex: number) => Promise<void>;\n\n /**\n * When true, disables the automatic memoization of getVisibleColumnRange and\n * getVisibleRowRange results. By default the library caches each range value and\n * invalidates it after the corresponding scroll call, eliminating redundant DOM\n * evaluate() round-trips between scrolls.\n */\n disableCache?: boolean;\n}\n\n\n/**\n * SmartCell - A Playwright Locator with table-aware methods for single-cell operations.\n * \n * Extends all standard Locator methods (click, isVisible, etc.).\n */\nexport type SmartCell = Locator & {\n /**\n * Scrolls/paginates to bring this specific cell into view using the configured strategies.\n * Useful when the grid is horizontally virtualized and the column must be scrolled\n * into view before it can be interacted with or read.\n */\n bringIntoView(): Promise<void>;\n};\n\n\n/**\n * SmartRow - A Playwright Locator with table-aware methods.\n * \n * Extends all standard Locator methods (click, isVisible, etc.) with table-specific functionality.\n * \n * @example\n * const row = table.getRow({ Name: 'John Doe' });\n * await row.click(); // Standard Locator method\n * const email = row.getCell('Email'); // Table-aware method\n * const data = await row.toJSON(); // Extract all row data\n * await row.smartFill({ Name: 'Jane', Status: 'Active' }); // Fill form fields\n */\nexport type SmartRow<T = any> = Locator & {\n /** Optional row index (0-based) if known */\n rowIndex?: number;\n\n /** Optional page index this row was found on (0-based) */\n tablePageIndex?: number;\n\n /** Reference to the parent TableResult */\n table: TableResult<T>;\n\n /**\n * Get a cell locator by column name.\n * @param column - Column name (case-sensitive)\n * @returns SmartCell (Locator + bringIntoView)\n * @example\n * const emailCell = row.getCell('Email');\n * await emailCell.bringIntoView();\n * await expect(emailCell).toHaveText('john@example.com');\n */\n getCell(column: string): SmartCell;\n\n /**\n * Extract all cell data as a key-value object.\n * @param options - Optional configuration\n * @param options.columns - Specific columns to extract (extracts all if not specified)\n * @returns Promise resolving to row data\n * @example\n * const data = await row.toJSON();\n * // { Name: 'John', Email: 'john@example.com', ... }\n * \n * const partial = await row.toJSON({ columns: ['Name', 'Email'] });\n * // { Name: 'John', Email: 'john@example.com' }\n */\n toJSON(options?: { columns?: string[] }): Promise<T>;\n\n /**\n * Scrolls/paginates to bring this row into view.\n * Works when row position metadata is known (e.g., from getRowByIndex, findRow,\n * findRows, filter, or async iteration).\n * @throws Error if row position metadata is unknown\n */\n bringIntoView(): Promise<void>;\n\n /**\n * Intelligently fills form fields in the row.\n * Automatically detects input types (text, select, checkbox, contenteditable).\n * \n * @param data - Column-value pairs to fill\n * @param options - Optional configuration\n * @param options.inputMappers - Custom input selectors per column\n * @example\n * // Auto-detection\n * await row.smartFill({ Name: 'John', Status: 'Active', Subscribe: true });\n * \n * // Custom input mappers\n * await row.smartFill(\n * { Name: 'John' },\n * { inputMappers: { Name: (cell) => cell.locator('.custom-input') } }\n * );\n */\n smartFill: (data: Partial<T> | Record<string, any>, options?: FillOptions) => Promise<void>;\n\n /**\n * Returns whether the row exists in the DOM (i.e. is not a sentinel row).\n */\n wasFound(): boolean;\n};\n\nexport type StrategyContext = TableContext & {\n rowLocator?: Locator;\n rowIndex?: number;\n};\n\n/**\n * Defines the contract for a sorting strategy.\n */\nexport interface SortingStrategy {\n /**\n * Performs the sort action on a column.\n */\n doSort(options: {\n columnName: string;\n direction: 'asc' | 'desc';\n context: StrategyContext;\n }): Promise<void>;\n\n /**\n * Retrieves the current sort state of a column.\n */\n getSortState(options: {\n columnName: string;\n context: StrategyContext;\n }): Promise<'asc' | 'desc' | 'none'>;\n}\n\n/**\n * Debug configuration for development and troubleshooting\n */\nexport type DebugConfig = {\n /**\n * Slow down operations for debugging\n * - number: Apply same delay to all operations (ms)\n * - object: Granular delays per operation type\n */\n slow?: number | {\n pagination?: number;\n getCell?: number;\n findRow?: number;\n default?: number;\n };\n /**\n * Log level for debug output\n * - 'verbose': All logs (verbose, info, error)\n * - 'info': Info and error logs only\n * - 'error': Error logs only\n * - 'none': No logs\n */\n logLevel?: 'verbose' | 'info' | 'error' | 'none';\n};\n\nexport interface TableContext<T = any> {\n root: Locator;\n config: FinalTableConfig<T>;\n page: Page;\n resolve: (selector: Selector, parent: Locator | Page) => Locator;\n /** Resolves a column name to its header cell locator. Available after table is initialized. */\n getHeaderCell?: (columnName: string) => Promise<Locator>;\n /** Returns all column names in order. Available after table is initialized. */\n getHeaders?: () => Promise<string[]>;\n /** Scrolls the table horizontally to bring the given column's header into view. */\n scrollToColumn?: (columnName: string) => Promise<void>;\n}\n\nexport interface PaginationPrimitives {\n /** Classic \"Next Page\" or \"Scroll Down\" */\n goNext?: (context: TableContext) => Promise<boolean>;\n\n /** Classic \"Previous Page\" or \"Scroll Up\" */\n goPrevious?: (context: TableContext) => Promise<boolean>;\n\n /** Bulk skip forward multiple pages at once. Returns number of pages skipped. */\n goNextBulk?: (context: TableContext) => Promise<boolean | number>;\n\n /** Bulk skip backward multiple pages at once. Returns number of pages skipped. */\n goPreviousBulk?: (context: TableContext) => Promise<boolean | number>;\n\n /** Jump to first page / scroll to top */\n goToFirst?: (context: TableContext) => Promise<boolean>;\n\n /** Jump to last page / scroll to bottom */\n goToLast?: (context: TableContext) => Promise<boolean>;\n\n /**\n * Fetch the total number of pages currently available.\n * Can be used to optimize pagination paths (e.g. jumping to last page and going backwards).\n */\n getTotalPages?: (context: TableContext) => Promise<number | null>;\n\n /**\n * Jump to specific page index (0-indexed).\n * Can be full-range (e.g. page number input: any page works) or windowed (e.g. only visible links 6\u201314).\n * Return false when the page is not reachable in the current UI; the library will step toward the target (goNextBulk/goNext or goPreviousBulk/goPrevious) and retry goToPage until it succeeds.\n */\n goToPage?: (pageIndex: number, context: TableContext) => Promise<boolean>;\n\n /** How many pages one goNextBulk() advances. Used by navigation path planner for optimal bringIntoView. */\n nextBulkPages?: number;\n\n /** How many pages one goPreviousBulk() goes back. Used by navigation path planner for optimal bringIntoView. */\n previousBulkPages?: number;\n\n /**\n * Called once during init() to sync the library's page counter with the actual DOM state.\n * Use when a table may open on a page other than the first (e.g. a deep-linked URL that\n * lands on page 5). Returns a 0-indexed page number.\n * @example\n * detectCurrentPage: async (root) => {\n * const text = await root.locator('[aria-current=\"page\"]').textContent();\n * return parseInt(text ?? '1') - 1;\n * }\n */\n detectCurrentPage?: (root: import('@playwright/test').Locator) => number | Promise<number>;\n}\n\nexport type PaginationStrategy = PaginationPrimitives;\n\nexport type DedupeStrategy = (row: SmartRow) => string | number | Promise<string | number>;\n\n\n\nexport type FillStrategy = (options: {\n row: SmartRow;\n columnName: string;\n value: any;\n index: number;\n page: Page;\n rootLocator: Locator;\n config: FinalTableConfig<any>;\n table: TableResult; // The parent table instance\n fillOptions?: FillOptions;\n}) => Promise<void>;\n\nexport interface ColumnOverride<TValue = any> {\n /** \n * How to extract the value from the cell.\n * `context` provides access to the parent row, permitting multi-cell logic or bypassing the default cell locator.\n */\n read?: (cell: Locator) => Promise<TValue> | TValue;\n\n /** \n * How to fill the cell with a new value. (Replaces smartFill default logic)\n * Provides the current value (via `read`) if a `write` wants to check state first.\n */\n write?: (params: {\n cell: Locator;\n targetValue: TValue;\n currentValue?: TValue;\n row: SmartRow<any>;\n }) => Promise<void>;\n}\n\nexport type { HeaderStrategy } from './strategies/headers';\n\n/**\n * Strategy to resolve column names (string or regex) to their index.\n */\n// fallow-ignore-next-line unused-type\nexport type { ColumnResolutionStrategy } from './strategies/resolution';\n\n/**\n * Strategy to filter rows based on criteria. Applied when using getRow/findRow/findRows with filters.\n * The default engine handles string, RegExp, number, and function (cell) => Locator filters.\n */\nexport interface FilterStrategy {\n apply(options: {\n rows: Locator;\n filter: { column: string, value: FilterValue };\n colIndex: number;\n tableContext: TableContext;\n }): Locator;\n}\n\n/**\n * Strategy to check if the table or rows are loading. Used after pagination/sort to wait for content.\n * E.g. isHeaderLoading for init stability; isTableLoading after sort/pagination.\n */\nexport interface LoadingStrategy {\n isTableLoading?: (context: TableContext) => Promise<boolean>;\n isRowLoading?: (row: SmartRow) => Promise<boolean>;\n isHeaderLoading?: (context: TableContext) => Promise<boolean>;\n\n /**\n * How long (ms) to wait for a loading row to resolve before applying onRowLoadingTimeout.\n * When not set, loading rows are immediately skipped (backward-compatible behavior).\n */\n rowLoadingTimeout?: number;\n\n /**\n * What to do when a row is still loading after rowLoadingTimeout ms.\n * - 'skip': drop the row from results (matches legacy skip behavior)\n * - 'read-as-is': include the row even though it's still loading (default)\n * - 'throw': throw an error with row index and timeout info\n * Defaults to 'read-as-is' when rowLoadingTimeout is set.\n */\n onRowLoadingTimeout?: 'skip' | 'read-as-is' | 'throw';\n\n /**\n * Predicate called before reading each cell. Return true if the cell is still loading.\n * When cellLoadingTimeout is also set, the engine waits up to that many ms for the\n * cell to resolve before applying onCellLoadingTimeout.\n */\n isCellLoading?: (cell: import('@playwright/test').Locator, columnName: string, row: SmartRow) => Promise<boolean>;\n\n /**\n * How long (ms) to wait for a loading cell to resolve before applying onCellLoadingTimeout.\n * When not set and isCellLoading returns true, the cell is read as-is immediately.\n */\n cellLoadingTimeout?: number;\n\n /**\n * What to do when a cell is still loading after cellLoadingTimeout ms.\n * - 'skip': use empty string for this cell value\n * - 'read-as-is': read the cell content even though it's still loading (default)\n * - 'throw': throw an error with column name, row index and timeout info\n * - callback: called with (cell, columnName, row); its return value becomes the cell's string value\n * Defaults to 'read-as-is' when cellLoadingTimeout is set.\n */\n onCellLoadingTimeout?:\n | 'skip'\n | 'read-as-is'\n | 'throw'\n | ((cell: import('@playwright/test').Locator, columnName: string, row: SmartRow) => Promise<string>);\n}\n\n/**\n * Organized container for all table interaction strategies.\n */\nexport interface TableStrategies {\n /** Strategy for discovering/scanning headers */\n header?: HeaderStrategy;\n /** Primitive navigation functions (goUp, goDown, goLeft, goRight, goHome) */\n navigation?: NavigationPrimitives;\n\n /** Strategy for filling form inputs */\n fill?: FillStrategy;\n /** Strategy for paginating through data */\n pagination?: PaginationStrategy;\n /** Strategy for sorting columns */\n sorting?: SortingStrategy;\n /** Strategy for deduplicating rows during iteration/scrolling */\n dedupe?: DedupeStrategy;\n /** Function to get a cell locator */\n getCellLocator?: GetCellLocatorFn;\n /** Function to get the currently active/focused cell */\n getActiveCell?: GetActiveCellFn;\n /**\n * Strategy for filtering rows. If present, FilterEngine will delegate filter application\n * to this pluggable strategy.\n */\n filter?: FilterStrategy;\n /**\n * Hook called before each cell value is read in toJSON and columnOverrides.read.\n * Fires for both the default innerText extraction and custom read mappers.\n * Useful for scrolling off-screen columns into view in horizontally virtualized tables.\n */\n beforeCellRead?: BeforeCellReadFn;\n /**\n * Strategy for detecting loading states. Use this for table-, row-, and header-level readiness.\n * E.g. after sort/pagination, the engine uses loading.isTableLoading when present.\n */\n loading?: LoadingStrategy;\n\n /**\n * Resolve the stable data-model index for a row locator.\n *\n * Called by `findRow` / `findRows` to convert a DOM row into the index used for\n * virtual-scroll positioning. Useful for grids where DOM position resets to 0 on\n * each page while the grid itself maintains a monotone counter (e.g. MUI DataGrid's\n * `data-rowindex` attribute).\n *\n * Return `undefined` to fall back to DOM position.\n *\n * @example\n * // MUI DataGrid: read the global monotone counter from the attribute\n * resolveRowIndex: async (row) => {\n * const v = await row.getAttribute('data-rowindex').catch(() => null);\n * return v !== null && !isNaN(Number(v)) ? Number(v) : undefined;\n * }\n */\n resolveRowIndex?: (row: Locator) => Promise<number | undefined>;\n\n /**\n * Viewport oracle strategies for 2D virtualized tables (e.g. MUI DataGrid, AG Grid,\n * Braintrust-style grids where both rows and columns are virtualized simultaneously).\n *\n * When present, the cell-reading engine uses these to jump directly to the target\n * row/column and to detect the 2D scroll hazard (scrolling to reveal a column can\n * knock rows out of the vertical viewport, and vice versa).\n *\n * Completely optional and additive \u2014 existing `navigation` primitives remain the fallback.\n */\n viewport?: ViewportStrategy;\n}\n\n\nexport interface TableConfig<T = any> {\n /** Selector for the table headers */\n headerSelector?: string | ((root: Locator) => Locator);\n /** Selector for the table rows */\n rowSelector?: string;\n /** Selector for the cells within a row */\n cellSelector?: string | ((row: Locator) => Locator);\n /** Number of pages to scan for verification */\n maxPages?: number;\n /**\n * Default concurrency strategy for iteration methods.\n * Can be overridden by the options passed to forEach, map, or filter.\n */\n concurrency?: RowIterationMode;\n /** Hook to rename columns dynamically */\n headerTransformer?: (args: { text: string, index: number, locator: Locator, seenHeaders: Set<string> }) => string | Promise<string>;\n /** Automatically scroll to table on init */\n autoScroll?: boolean;\n /** Debug options for development and troubleshooting */\n debug?: DebugConfig;\n /** Reset hook */\n onReset?: (context: TableContext) => Promise<void>;\n /** All interaction strategies */\n strategies?: TableStrategies;\n\n /**\n * Unified interface for reading and writing data to specific columns.\n * Overrides both default extraction (toJSON) and filling (smartFill) logic.\n */\n columnOverrides?: Partial<Record<keyof T, ColumnOverride<T[keyof T]>>>;\n}\n\nexport interface FinalTableConfig<T = any> extends TableConfig<T> {\n headerSelector: string | ((root: Locator) => Locator);\n rowSelector: string;\n cellSelector: string | ((row: Locator) => Locator);\n maxPages: number;\n autoScroll: boolean;\n concurrency?: RowIterationMode;\n debug?: TableConfig['debug'];\n headerTransformer: (args: { text: string, index: number, locator: Locator, seenHeaders: Set<string> }) => string | Promise<string>;\n onReset: (context: TableContext) => Promise<void>;\n strategies: TableStrategies;\n}\n\n\nexport interface FillOptions {\n /**\n * Custom input mappers for specific columns.\n * Maps column names to functions that return the input locator for that cell.\n */\n inputMappers?: Record<string, (cell: Locator) => Locator>;\n}\n\n\n\n/** Callback context passed to forEach, map, and filter. */\nexport type RowIterationContext<T = any> = {\n row: SmartRow<T>;\n /** 0-based iteration counter \u2014 the order this row was visited, not its DOM position or grid identity. @deprecated Use `index` instead. `rowIndex` will be removed in v7.0.0. */\n rowIndex: number;\n /** 0-based iteration counter \u2014 the order this row was visited, not its DOM position or grid identity. */\n index: number;\n /** 0-based page index \u2014 which page this row was collected from. */\n pageIndex: number;\n stop: () => void;\n};\n\n/** Concurrency modes for row iteration. */\nexport type RowIterationMode = 'parallel' | 'sequential' | 'synchronized';\n\n/** Shared options for forEach, map, and filter. */\nexport type RowIterationOptions = {\n /** Maximum number of pages to iterate. Defaults to config.maxPages. */\n maxPages?: number;\n /**\n * Concurrency strategy for iteration.\n * - 'parallel': Full parallel execution of both navigation and actions.\n * - 'synchronized': Parallel navigation (lock-step) with serial actions.\n * - 'sequential': Strictly serial one-at-a-time execution. No parallel navigation.\n * @default 'parallel' (for map), 'sequential' (for forEach/filter)\n */\n concurrency?: RowIterationMode;\n /**\n * Deduplication strategy. Use when rows may repeat across iterations\n * (e.g. infinite scroll tables). Returns a unique key per row.\n */\n dedupe?: DedupeStrategy;\n /**\n * When true, use goNextBulk (if present) to advance pages during iteration.\n * @default false \u2014 uses goNext for one-page-at-a-time advancement\n */\n useBulkPagination?: boolean;\n};\n\nexport interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number; index: number; pageIndex: number }> {\n /**\n * Represents the current page index of the table's DOM.\n * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.\n */\n currentPageIndex: number;\n\n /**\n * Initializes the table by resolving headers. Must be called before using sync methods.\n * @param options Optional timeout for header resolution (default: 3000ms)\n */\n init(options?: { timeout?: number }): Promise<TableResult<T>>;\n\n /**\n * SYNC: Checks if the table has been initialized.\n * @returns true if init() has been called and completed, false otherwise\n */\n isInitialized(): boolean;\n\n getHeaders: () => Promise<string[]>;\n getHeaderCell: (columnName: string) => Promise<Locator>;\n\n /**\n * Finds a row by filters on the current page only. Returns immediately (sync).\n * Throws error if table is not initialized.\n * @note The returned SmartRow may have `rowIndex` as 0 when the match is not the first row.\n * Use getRowByIndex(index) when you need a known index (e.g. for bringIntoView()).\n */\n getRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean }\n ) => SmartRow<T>;\n\n /**\n * Gets a row by 0-based index on the current page.\n * Throws error if table is not initialized.\n * @param index 0-based row index\n */\n getRowByIndex: (\n index: number\n ) => SmartRow<T>;\n\n /**\n * ASYNC: Searches for a single row across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRow<T>>;\n\n /**\n * ASYNC: Searches for all matching rows across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match (omit or pass {} for all rows)\n * @param options - Search options including exact match and max pages\n */\n findRows: (\n filters?: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number, useBulkPagination?: boolean }\n ) => Promise<SmartRowArray<T>>;\n\n /**\n * Navigates to a specific column using the configured CellNavigationStrategy.\n */\n scrollToColumn: (columnName: string) => Promise<void>;\n\n /**\n * Counts the number of rows currently on the page.\n * Does not paginate.\n */\n countRows: () => Promise<number>;\n\n /**\n * Iterates over rows and extracts the value of a single column.\n * More efficient than map + toJSON for single-column extraction.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;\n\n /**\n * Iterates over rows and extracts the value of a single column as strings.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;\n\n\n /**\n * Resets the table state (clears cache, flags) and invokes the onReset strategy.\n */\n reset: () => Promise<void>;\n\n /**\n * Revalidates the table's structure (headers, columns) without resetting pagination or state.\n * Useful when columns change visibility or order dynamically.\n */\n revalidate: () => Promise<void>;\n\n /**\n * Iterates every row across all pages, calling the callback for side effects.\n * Execution is sequential by default (safe for interactions like clicking/filling).\n * Call `stop()` in the callback to end iteration early.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * await table.forEach(async ({ row, stop }) => {\n * if (await row.getCell('Status').innerText() === 'Done') stop();\n * await row.getCell('Checkbox').click();\n * });\n */\n forEach(\n callback: (ctx: RowIterationContext<T>) => void | Promise<void>,\n options?: RowIterationOptions\n ): Promise<void>;\n\n /**\n * Transforms every row across all pages into a value. Returns a flat array.\n * Execution is parallel within each page by default (safe for reads).\n * Call `stop()` to halt after the current page finishes.\n *\n * > **\u26A0\uFE0F UI Interactions:** `map` defaults to `concurrency: 'parallel'`. If your callback opens popovers,\n * > fills inputs, or otherwise mutates UI state, pass `concurrency: 'sequential'` (or `'synchronized'`\n * > when navigation must stay lock-step) to avoid overlapping interactions.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * // Data extraction \u2014 parallel is safe\n * const emails = await table.map(({ row }) => row.getCell('Email').innerText());\n *\n * @example\n * // UI interactions \u2014 use sequential (or synchronized) concurrency\n * const assignees = await table.map(async ({ row }) => {\n * await row.getCell('Assignee').locator('button').click();\n * const name = await page.locator('.popover .name').innerText();\n * await page.keyboard.press('Escape');\n * return name;\n * }, { concurrency: 'sequential' });\n */\n map<R>(\n callback: (ctx: RowIterationContext<T>) => R | Promise<R>,\n options?: RowIterationOptions\n ): Promise<R[]>;\n\n /**\n * Shorthand for `map()` + `reset()`. Iterates every row across all pages, applies the\n * callback (defaults to `row.toJSON()`), then resets the table back to page 1 \u2014 even if\n * the callback throws.\n *\n * @param callback - Optional map function. Defaults to `({ row }) => row.toJSON()`.\n * @param options - Same options as `map()`.\n *\n * @example\n * // Zero-arg: returns toJSON() for every row\n * const rows = await table.toArray();\n *\n * @example\n * // Custom callback\n * const names = await table.toArray(({ row }) => row.getCell('Name').innerText());\n *\n * @example\n * // With options\n * const rows = await table.toArray(({ row }) => row.toJSON(), { concurrency: 'parallel' });\n */\n toArray<R = Record<string, unknown>>(\n callback?: (ctx: RowIterationContext<T>) => R | Promise<R>,\n options?: RowIterationOptions\n ): Promise<R[]>;\n\n /**\n * Filters rows across all pages by an async predicate. Returns a SmartRowArray.\n * Rows are returned as-is \u2014 call `bringIntoView()` on each if needed.\n * Execution is sequential by default.\n *\n * @param predicate - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * const active = await table.filter(async ({ row }) =>\n * await row.getCell('Status').innerText() === 'Active'\n * );\n */\n filter(\n predicate: (ctx: RowIterationContext<T>) => boolean | Promise<boolean>,\n options?: RowIterationOptions\n ): Promise<SmartRowArray<T>>;\n\n /**\n * Provides access to sorting actions and assertions.\n */\n sorting: {\n /**\n * Applies the configured sorting strategy to the specified column.\n * @param columnName The name of the column to sort.\n * @param direction The direction to sort ('asc' or 'desc').\n */\n apply(columnName: string, direction: 'asc' | 'desc'): Promise<void>;\n /**\n * Gets the current sort state of a column using the configured sorting strategy.\n * @param columnName The name of the column to check.\n * @returns A promise that resolves to 'asc', 'desc', or 'none'.\n */\n getState(columnName: string): Promise<'asc' | 'desc' | 'none'>;\n };\n\n /**\n * Generate an AI-friendly configuration prompt for debugging.\n * Outputs table HTML and TypeScript definitions to help AI assistants generate config.\n * Automatically throws an Error containing the prompt.\n */\n generateConfig: () => Promise<void>;\n\n /**\n * @deprecated Use `generateConfig()` instead. Will be removed in v7.0.0.\n */\n generateConfigPrompt: () => Promise<void>;\n}\n";
|
package/dist/typeContext.js
CHANGED
|
@@ -554,6 +554,25 @@ export interface TableStrategies {
|
|
|
554
554
|
*/
|
|
555
555
|
loading?: LoadingStrategy;
|
|
556
556
|
|
|
557
|
+
/**
|
|
558
|
+
* Resolve the stable data-model index for a row locator.
|
|
559
|
+
*
|
|
560
|
+
* Called by \`findRow\` / \`findRows\` to convert a DOM row into the index used for
|
|
561
|
+
* virtual-scroll positioning. Useful for grids where DOM position resets to 0 on
|
|
562
|
+
* each page while the grid itself maintains a monotone counter (e.g. MUI DataGrid's
|
|
563
|
+
* \`data-rowindex\` attribute).
|
|
564
|
+
*
|
|
565
|
+
* Return \`undefined\` to fall back to DOM position.
|
|
566
|
+
*
|
|
567
|
+
* @example
|
|
568
|
+
* // MUI DataGrid: read the global monotone counter from the attribute
|
|
569
|
+
* resolveRowIndex: async (row) => {
|
|
570
|
+
* const v = await row.getAttribute('data-rowindex').catch(() => null);
|
|
571
|
+
* return v !== null && !isNaN(Number(v)) ? Number(v) : undefined;
|
|
572
|
+
* }
|
|
573
|
+
*/
|
|
574
|
+
resolveRowIndex?: (row: Locator) => Promise<number | undefined>;
|
|
575
|
+
|
|
557
576
|
/**
|
|
558
577
|
* Viewport oracle strategies for 2D virtualized tables (e.g. MUI DataGrid, AG Grid,
|
|
559
578
|
* Braintrust-style grids where both rows and columns are virtualized simultaneously).
|
|
@@ -814,6 +833,31 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
|
|
|
814
833
|
options?: RowIterationOptions
|
|
815
834
|
): Promise<R[]>;
|
|
816
835
|
|
|
836
|
+
/**
|
|
837
|
+
* Shorthand for \`map()\` + \`reset()\`. Iterates every row across all pages, applies the
|
|
838
|
+
* callback (defaults to \`row.toJSON()\`), then resets the table back to page 1 — even if
|
|
839
|
+
* the callback throws.
|
|
840
|
+
*
|
|
841
|
+
* @param callback - Optional map function. Defaults to \`({ row }) => row.toJSON()\`.
|
|
842
|
+
* @param options - Same options as \`map()\`.
|
|
843
|
+
*
|
|
844
|
+
* @example
|
|
845
|
+
* // Zero-arg: returns toJSON() for every row
|
|
846
|
+
* const rows = await table.toArray();
|
|
847
|
+
*
|
|
848
|
+
* @example
|
|
849
|
+
* // Custom callback
|
|
850
|
+
* const names = await table.toArray(({ row }) => row.getCell('Name').innerText());
|
|
851
|
+
*
|
|
852
|
+
* @example
|
|
853
|
+
* // With options
|
|
854
|
+
* const rows = await table.toArray(({ row }) => row.toJSON(), { concurrency: 'parallel' });
|
|
855
|
+
*/
|
|
856
|
+
toArray<R = Record<string, unknown>>(
|
|
857
|
+
callback?: (ctx: RowIterationContext<T>) => R | Promise<R>,
|
|
858
|
+
options?: RowIterationOptions
|
|
859
|
+
): Promise<R[]>;
|
|
860
|
+
|
|
817
861
|
/**
|
|
818
862
|
* Filters rows across all pages by an async predicate. Returns a SmartRowArray.
|
|
819
863
|
* Rows are returned as-is — call \`bringIntoView()\` on each if needed.
|
package/dist/types.d.ts
CHANGED
|
@@ -500,6 +500,24 @@ export interface TableStrategies {
|
|
|
500
500
|
* E.g. after sort/pagination, the engine uses loading.isTableLoading when present.
|
|
501
501
|
*/
|
|
502
502
|
loading?: LoadingStrategy;
|
|
503
|
+
/**
|
|
504
|
+
* Resolve the stable data-model index for a row locator.
|
|
505
|
+
*
|
|
506
|
+
* Called by `findRow` / `findRows` to convert a DOM row into the index used for
|
|
507
|
+
* virtual-scroll positioning. Useful for grids where DOM position resets to 0 on
|
|
508
|
+
* each page while the grid itself maintains a monotone counter (e.g. MUI DataGrid's
|
|
509
|
+
* `data-rowindex` attribute).
|
|
510
|
+
*
|
|
511
|
+
* Return `undefined` to fall back to DOM position.
|
|
512
|
+
*
|
|
513
|
+
* @example
|
|
514
|
+
* // MUI DataGrid: read the global monotone counter from the attribute
|
|
515
|
+
* resolveRowIndex: async (row) => {
|
|
516
|
+
* const v = await row.getAttribute('data-rowindex').catch(() => null);
|
|
517
|
+
* return v !== null && !isNaN(Number(v)) ? Number(v) : undefined;
|
|
518
|
+
* }
|
|
519
|
+
*/
|
|
520
|
+
resolveRowIndex?: (row: Locator) => Promise<number | undefined>;
|
|
503
521
|
/**
|
|
504
522
|
* Viewport oracle strategies for 2D virtualized tables (e.g. MUI DataGrid, AG Grid,
|
|
505
523
|
* Braintrust-style grids where both rows and columns are virtualized simultaneously).
|
|
@@ -740,6 +758,27 @@ export interface TableResult<T = any> extends AsyncIterable<{
|
|
|
740
758
|
* }, { concurrency: 'sequential' });
|
|
741
759
|
*/
|
|
742
760
|
map<R>(callback: (ctx: RowIterationContext<T>) => R | Promise<R>, options?: RowIterationOptions): Promise<R[]>;
|
|
761
|
+
/**
|
|
762
|
+
* Shorthand for `map()` + `reset()`. Iterates every row across all pages, applies the
|
|
763
|
+
* callback (defaults to `row.toJSON()`), then resets the table back to page 1 — even if
|
|
764
|
+
* the callback throws.
|
|
765
|
+
*
|
|
766
|
+
* @param callback - Optional map function. Defaults to `({ row }) => row.toJSON()`.
|
|
767
|
+
* @param options - Same options as `map()`.
|
|
768
|
+
*
|
|
769
|
+
* @example
|
|
770
|
+
* // Zero-arg: returns toJSON() for every row
|
|
771
|
+
* const rows = await table.toArray();
|
|
772
|
+
*
|
|
773
|
+
* @example
|
|
774
|
+
* // Custom callback
|
|
775
|
+
* const names = await table.toArray(({ row }) => row.getCell('Name').innerText());
|
|
776
|
+
*
|
|
777
|
+
* @example
|
|
778
|
+
* // With options
|
|
779
|
+
* const rows = await table.toArray(({ row }) => row.toJSON(), { concurrency: 'parallel' });
|
|
780
|
+
*/
|
|
781
|
+
toArray<R = Record<string, unknown>>(callback?: (ctx: RowIterationContext<T>) => R | Promise<R>, options?: RowIterationOptions): Promise<R[]>;
|
|
743
782
|
/**
|
|
744
783
|
* Filters rows across all pages by an async predicate. Returns a SmartRowArray.
|
|
745
784
|
* Rows are returned as-is — call `bringIntoView()` on each if needed.
|
package/dist/useTable.js
CHANGED
|
@@ -64,10 +64,15 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
64
64
|
const config = Object.assign(Object.assign({ rowSelector: "tbody tr", headerSelector: "thead th", cellSelector: "td", maxPages: 1, headerTransformer: ({ text }) => text, autoScroll: true, onReset: async () => { } }, configOptions), { strategies: Object.assign(Object.assign({}, defaultStrategies), configOptions.strategies) });
|
|
65
65
|
// Automatically memoize viewport range oracles so user-provided functions are
|
|
66
66
|
// pure DOM queries with no cache bookkeeping. Invalidated after each scroll call.
|
|
67
|
+
let _clearViewportCache = null;
|
|
67
68
|
if (config.strategies.viewport && !config.strategies.viewport.disableCache) {
|
|
68
69
|
const vp = config.strategies.viewport;
|
|
69
70
|
let colRangeCache = null;
|
|
70
71
|
let rowRangeCache = null;
|
|
72
|
+
_clearViewportCache = () => {
|
|
73
|
+
colRangeCache = null;
|
|
74
|
+
rowRangeCache = null;
|
|
75
|
+
};
|
|
71
76
|
config.strategies.viewport = Object.assign(Object.assign({}, vp), { getVisibleColumnRange: vp.getVisibleColumnRange
|
|
72
77
|
? async (ctx) => {
|
|
73
78
|
if (!colRangeCache)
|
|
@@ -194,6 +199,10 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
194
199
|
if (pagesJumped > 0) {
|
|
195
200
|
tableState.currentPageIndex += pagesJumped;
|
|
196
201
|
log(`_advancePage: ${primitive} advanced ${pagesJumped} page(s) — now at page ${tableState.currentPageIndex}`);
|
|
202
|
+
// Invalidate viewport caches: after a page advance the row set changes and the
|
|
203
|
+
// column renderer may recalculate (e.g. scrollbar appearance changes available width).
|
|
204
|
+
if (_clearViewportCache)
|
|
205
|
+
_clearViewportCache();
|
|
197
206
|
await (0, debugUtils_1.debugDelay)(config, 'pagination');
|
|
198
207
|
}
|
|
199
208
|
else {
|
|
@@ -469,6 +478,16 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
469
478
|
getCurrentPageIndex: () => tableState.currentPageIndex,
|
|
470
479
|
}, callback, options);
|
|
471
480
|
},
|
|
481
|
+
toArray: async (callback, options = {}) => {
|
|
482
|
+
log(`toArray: options=${safeStringify(options)}`);
|
|
483
|
+
const cb = callback !== null && callback !== void 0 ? callback : (({ row }) => row.toJSON());
|
|
484
|
+
try {
|
|
485
|
+
return await result.map(cb, options);
|
|
486
|
+
}
|
|
487
|
+
finally {
|
|
488
|
+
await result.reset();
|
|
489
|
+
}
|
|
490
|
+
},
|
|
472
491
|
filter: async (predicate, options = {}) => {
|
|
473
492
|
log(`filter: options=${safeStringify(options)}`);
|
|
474
493
|
await _autoInit();
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { TableConfig } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Deep-merges two `TableConfig` objects.
|
|
4
|
+
*
|
|
5
|
+
* Merge semantics:
|
|
6
|
+
* - Top-level keys (`rowSelector`, `maxPages`, etc.): overrides win — same as `{ ...base, ...overrides }`.
|
|
7
|
+
* - `strategies`: each sub-key is merged independently. Object-valued strategies (`loading`,
|
|
8
|
+
* `viewport`, `pagination`) are merged key-by-key so that neither side silently wipes the
|
|
9
|
+
* other's settings. Function-valued strategies (`header`, `dedupe`, `getCellLocator`, etc.)
|
|
10
|
+
* are replaced in full by the override value (a function cannot be meaningfully object-spread).
|
|
11
|
+
* - `columnOverrides`: merged key-by-key (each column entry merged independently).
|
|
12
|
+
* - Everything else: overrides win (shallow merge).
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const config = mergeTableConfig(baseConfig, {
|
|
16
|
+
* maxPages: 20,
|
|
17
|
+
* strategies: {
|
|
18
|
+
* loading: { isTableLoading: myLoadingFn },
|
|
19
|
+
* },
|
|
20
|
+
* });
|
|
21
|
+
*/
|
|
22
|
+
export declare function mergeTableConfig<T = any>(base: TableConfig<T>, overrides: TableConfig<T>): TableConfig<T>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mergeTableConfig = mergeTableConfig;
|
|
4
|
+
/**
|
|
5
|
+
* Deep-merges two `TableConfig` objects.
|
|
6
|
+
*
|
|
7
|
+
* Merge semantics:
|
|
8
|
+
* - Top-level keys (`rowSelector`, `maxPages`, etc.): overrides win — same as `{ ...base, ...overrides }`.
|
|
9
|
+
* - `strategies`: each sub-key is merged independently. Object-valued strategies (`loading`,
|
|
10
|
+
* `viewport`, `pagination`) are merged key-by-key so that neither side silently wipes the
|
|
11
|
+
* other's settings. Function-valued strategies (`header`, `dedupe`, `getCellLocator`, etc.)
|
|
12
|
+
* are replaced in full by the override value (a function cannot be meaningfully object-spread).
|
|
13
|
+
* - `columnOverrides`: merged key-by-key (each column entry merged independently).
|
|
14
|
+
* - Everything else: overrides win (shallow merge).
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* const config = mergeTableConfig(baseConfig, {
|
|
18
|
+
* maxPages: 20,
|
|
19
|
+
* strategies: {
|
|
20
|
+
* loading: { isTableLoading: myLoadingFn },
|
|
21
|
+
* },
|
|
22
|
+
* });
|
|
23
|
+
*/
|
|
24
|
+
function mergeTableConfig(base, overrides) {
|
|
25
|
+
var _a, _b, _c, _d;
|
|
26
|
+
const result = Object.assign(Object.assign({}, base), overrides);
|
|
27
|
+
// Deep-merge strategies one level down
|
|
28
|
+
if (base.strategies || overrides.strategies) {
|
|
29
|
+
result.strategies = Object.assign(Object.assign({}, base.strategies), overrides.strategies);
|
|
30
|
+
// For strategy sub-keys that are plain objects on *both* sides, merge key-by-key
|
|
31
|
+
// so that e.g. base.strategies.loading and overrides.strategies.loading are combined.
|
|
32
|
+
// Function values (pagination, header, dedupe, getCellLocator, etc.) are replaced, not merged.
|
|
33
|
+
const strategyKeys = new Set([
|
|
34
|
+
...Object.keys((_a = base.strategies) !== null && _a !== void 0 ? _a : {}),
|
|
35
|
+
...Object.keys((_b = overrides.strategies) !== null && _b !== void 0 ? _b : {}),
|
|
36
|
+
]);
|
|
37
|
+
for (const key of strategyKeys) {
|
|
38
|
+
const baseVal = (_c = base.strategies) === null || _c === void 0 ? void 0 : _c[key];
|
|
39
|
+
const overrideVal = (_d = overrides.strategies) === null || _d === void 0 ? void 0 : _d[key];
|
|
40
|
+
if (baseVal !== undefined &&
|
|
41
|
+
overrideVal !== undefined &&
|
|
42
|
+
typeof baseVal === 'object' &&
|
|
43
|
+
typeof overrideVal === 'object' &&
|
|
44
|
+
!Array.isArray(baseVal) &&
|
|
45
|
+
!Array.isArray(overrideVal) &&
|
|
46
|
+
typeof baseVal !== 'function' &&
|
|
47
|
+
typeof overrideVal !== 'function') {
|
|
48
|
+
// The spread result can't be expressed as the union of all strategy types;
|
|
49
|
+
// the runtime object-check above guarantees safety.
|
|
50
|
+
result.strategies[key] =
|
|
51
|
+
Object.assign(Object.assign({}, baseVal), overrideVal);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Deep-merge columnOverrides one level down (each column entry merged independently)
|
|
56
|
+
if (base.columnOverrides || overrides.columnOverrides) {
|
|
57
|
+
result.columnOverrides = Object.assign(Object.assign({}, base.columnOverrides), overrides.columnOverrides);
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
@@ -1,23 +1,35 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A synchronization barrier that allows multiple parallel row processors
|
|
3
|
-
* to coordinate their navigation actions.
|
|
4
|
-
*/
|
|
5
1
|
export declare class NavigationBarrier {
|
|
6
2
|
private total;
|
|
7
3
|
private finishedCount;
|
|
8
4
|
private buckets;
|
|
5
|
+
private recoveryMutex;
|
|
9
6
|
constructor(total: number);
|
|
10
7
|
/** True when more than one row shares this barrier (scrollToRow would evict peers). */
|
|
11
8
|
isParallel(): boolean;
|
|
12
9
|
/**
|
|
13
10
|
* Synchronize all active rows at a specific column index.
|
|
14
|
-
* The last row to arrive
|
|
11
|
+
* The last row to arrive (or the last markFinished call) triggers the `moveAction`.
|
|
15
12
|
*/
|
|
16
13
|
sync<T = void>(colIndex: number, moveAction?: () => Promise<T>): Promise<T | void>;
|
|
17
14
|
/**
|
|
18
15
|
* Mark a row as finished (no more cells to process).
|
|
19
|
-
* This ensures the barrier doesn't wait for rows that have exited the loop
|
|
16
|
+
* This ensures the barrier doesn't wait for rows that have exited the loop,
|
|
17
|
+
* and runs the pending move action so waiting peers are not starved.
|
|
20
18
|
*/
|
|
21
19
|
markFinished(): void;
|
|
22
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Run a recovery action exclusively — serialized so concurrent rows don't race
|
|
22
|
+
* on scrollTop after a horizontal scroll evicts rows from the vertical viewport.
|
|
23
|
+
* The fn receives a fresh `targetReached` check; if the previous row's scroll
|
|
24
|
+
* already brought this row into view, fn can no-op immediately.
|
|
25
|
+
*/
|
|
26
|
+
runExclusiveRecovery<T>(fn: () => Promise<T>): Promise<T>;
|
|
27
|
+
/**
|
|
28
|
+
* Detach the bucket for `colIndex`, run the first available moveAction,
|
|
29
|
+
* then resolve or reject all captured waiters.
|
|
30
|
+
*
|
|
31
|
+
* Detaching before the await prevents a concurrent markFinished() from
|
|
32
|
+
* broadcasting the same bucket a second time while the action is in-flight.
|
|
33
|
+
*/
|
|
34
|
+
private triggerBucket;
|
|
23
35
|
}
|