@rickcedwhat/playwright-smart-table 6.11.0 ā 6.12.0
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.d.ts +3 -1
- package/dist/engine/rowFinder.js +25 -7
- package/dist/engine/tableIteration.js +8 -1
- package/dist/packageVersion.d.ts +1 -1
- package/dist/packageVersion.js +1 -1
- package/dist/plugins/index.d.ts +9 -9
- package/dist/presets/mui.js +15 -2
- package/dist/smartRow.js +13 -2
- package/dist/strategies/index.d.ts +1 -1
- package/dist/strategies/stabilization.js +14 -1
- package/dist/typeContext.d.ts +1 -1
- package/dist/typeContext.js +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/useTable.js +41 -3
- package/dist/utils/elementTracker.d.ts +10 -0
- package/dist/utils/elementTracker.js +31 -7
- package/package.json +16 -15
|
@@ -11,7 +11,7 @@ export declare class RowFinder<T = any> {
|
|
|
11
11
|
private makeSmartRow;
|
|
12
12
|
private tableState;
|
|
13
13
|
private resolve;
|
|
14
|
-
constructor(rootLocator: Locator, config: FinalTableConfig, resolve: (item: Selector, parent: Locator | Page) => Locator, filterEngine: FilterEngine, tableMapper: TableMapper, makeSmartRow: (loc: Locator, map: Map<string, number>, index: number, tablePageIndex?: number) => SmartRow<T>, tableState?: {
|
|
14
|
+
constructor(rootLocator: Locator, config: FinalTableConfig, resolve: (item: Selector, parent: Locator | Page) => Locator, filterEngine: FilterEngine, tableMapper: TableMapper, makeSmartRow: (loc: Locator, map: Map<string, number>, index: number | undefined, tablePageIndex?: number) => SmartRow<T>, tableState?: {
|
|
15
15
|
currentPageIndex: number;
|
|
16
16
|
});
|
|
17
17
|
private log;
|
|
@@ -22,6 +22,8 @@ export declare class RowFinder<T = any> {
|
|
|
22
22
|
findRows(filters?: Record<string, FilterValue>, options?: {
|
|
23
23
|
exact?: boolean;
|
|
24
24
|
maxPages?: number;
|
|
25
|
+
useBulkPagination?: boolean;
|
|
25
26
|
}): Promise<SmartRowArray<T>>;
|
|
26
27
|
private findRowLocator;
|
|
28
|
+
private resolveRowIndex;
|
|
27
29
|
}
|
package/dist/engine/rowFinder.js
CHANGED
|
@@ -26,7 +26,9 @@ class RowFinder {
|
|
|
26
26
|
if (rowLocator) {
|
|
27
27
|
(0, debugUtils_1.logDebug)(this.config, 'info', 'Row found');
|
|
28
28
|
await (0, debugUtils_1.debugDelay)(this.config, 'findRow');
|
|
29
|
-
|
|
29
|
+
const map = await this.tableMapper.getMap();
|
|
30
|
+
const rowIndex = await this.resolveRowIndex(rowLocator);
|
|
31
|
+
return this.makeSmartRow(rowLocator, map, rowIndex, this.tableState.currentPageIndex);
|
|
30
32
|
}
|
|
31
33
|
(0, debugUtils_1.logDebug)(this.config, 'error', 'Row not found', filters);
|
|
32
34
|
await (0, debugUtils_1.debugDelay)(this.config, 'findRow');
|
|
@@ -80,7 +82,8 @@ class RowFinder {
|
|
|
80
82
|
page: this.rootLocator.page()
|
|
81
83
|
};
|
|
82
84
|
let paginationResult;
|
|
83
|
-
|
|
85
|
+
const useBulk = (options === null || options === void 0 ? void 0 : options.useBulkPagination) !== false && !!((_c = this.config.strategies.pagination) === null || _c === void 0 ? void 0 : _c.goNextBulk);
|
|
86
|
+
if (useBulk) {
|
|
84
87
|
paginationResult = await this.config.strategies.pagination.goNextBulk(context);
|
|
85
88
|
}
|
|
86
89
|
else if ((_d = this.config.strategies.pagination) === null || _d === void 0 ? void 0 : _d.goNext) {
|
|
@@ -109,7 +112,7 @@ class RowFinder {
|
|
|
109
112
|
return (0, smartRowArray_1.createSmartRowArray)(allRows);
|
|
110
113
|
}
|
|
111
114
|
async findRowLocator(filters, options = {}) {
|
|
112
|
-
var _a, _b
|
|
115
|
+
var _a, _b;
|
|
113
116
|
const map = await this.tableMapper.getMap();
|
|
114
117
|
const effectiveMaxPages = (_a = options.maxPages) !== null && _a !== void 0 ? _a : this.config.maxPages;
|
|
115
118
|
let pagesScanned = 1;
|
|
@@ -159,11 +162,13 @@ class RowFinder {
|
|
|
159
162
|
page: this.rootLocator.page()
|
|
160
163
|
};
|
|
161
164
|
let paginationResult;
|
|
162
|
-
|
|
163
|
-
|
|
165
|
+
const pagination = this.config.strategies.pagination;
|
|
166
|
+
const useBulk = options.useBulkPagination !== false && !!(pagination === null || pagination === void 0 ? void 0 : pagination.goNextBulk);
|
|
167
|
+
if (useBulk && (pagination === null || pagination === void 0 ? void 0 : pagination.goNextBulk)) {
|
|
168
|
+
paginationResult = await pagination.goNextBulk(context);
|
|
164
169
|
}
|
|
165
|
-
else if (
|
|
166
|
-
paginationResult = await
|
|
170
|
+
else if (pagination === null || pagination === void 0 ? void 0 : pagination.goNext) {
|
|
171
|
+
paginationResult = await pagination.goNext(context);
|
|
167
172
|
}
|
|
168
173
|
else {
|
|
169
174
|
this.log(`Page ${this.tableState.currentPageIndex}: Pagination failed (no goNext or goNextBulk primitive).`);
|
|
@@ -183,5 +188,18 @@ class RowFinder {
|
|
|
183
188
|
return null;
|
|
184
189
|
}
|
|
185
190
|
}
|
|
191
|
+
async resolveRowIndex(rowLocator) {
|
|
192
|
+
const allRows = await this.resolve(this.config.rowSelector, this.rootLocator).all();
|
|
193
|
+
const targetHandle = await rowLocator.elementHandle();
|
|
194
|
+
if (!targetHandle)
|
|
195
|
+
return undefined;
|
|
196
|
+
for (let i = 0; i < allRows.length; i++) {
|
|
197
|
+
const handle = await allRows[i].elementHandle();
|
|
198
|
+
if (handle && await handle.evaluate((el, t) => el === t, targetHandle)) {
|
|
199
|
+
return i;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
186
204
|
}
|
|
187
205
|
exports.RowFinder = RowFinder;
|
|
@@ -50,8 +50,15 @@ async function runMap(env, callback, options = {}, label = 'map') {
|
|
|
50
50
|
};
|
|
51
51
|
while (!stopped) {
|
|
52
52
|
const rowLocators = env.getRowLocators();
|
|
53
|
-
const
|
|
53
|
+
const allIndices = await tracker.peekUnseenIndices(rowLocators);
|
|
54
54
|
const pageRows = await rowLocators.all();
|
|
55
|
+
// In synchronized mode, overscan rows rendered beyond the visible viewport by virtual
|
|
56
|
+
// scrollers can be evicted when the horizontal barrier fires snapFirstColumnIntoView.
|
|
57
|
+
// Filter them out before committing so they stay unseen and are picked up on the next page.
|
|
58
|
+
const newIndices = concurrency === 'synchronized'
|
|
59
|
+
? (await Promise.all(allIndices.map(async (idx) => ({ idx, present: pageRows[idx] != null && (await pageRows[idx].count()) > 0 })))).filter(r => r.present).map(r => r.idx)
|
|
60
|
+
: allIndices;
|
|
61
|
+
await tracker.commitIndices(rowLocators, newIndices);
|
|
55
62
|
const batchSize = newIndices.length;
|
|
56
63
|
if (batchSize === 0) {
|
|
57
64
|
log(env.config, `${label}: page ${pagesScanned} ā no new row(s) found`);
|
package/dist/packageVersion.d.ts
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Generated by scripts/embed-version.mjs from package.json
|
|
4
4
|
*/
|
|
5
5
|
/** Semver of this package. Use in logs or diagnostics to confirm the installed build. */
|
|
6
|
-
export declare const PLAYWRIGHT_SMART_TABLE_VERSION: "6.
|
|
6
|
+
export declare const PLAYWRIGHT_SMART_TABLE_VERSION: "6.12.0";
|
package/dist/packageVersion.js
CHANGED
|
@@ -6,4 +6,4 @@ exports.PLAYWRIGHT_SMART_TABLE_VERSION = void 0;
|
|
|
6
6
|
* Generated by scripts/embed-version.mjs from package.json
|
|
7
7
|
*/
|
|
8
8
|
/** Semver of this package. Use in logs or diagnostics to confirm the installed build. */
|
|
9
|
-
exports.PLAYWRIGHT_SMART_TABLE_VERSION = "6.
|
|
9
|
+
exports.PLAYWRIGHT_SMART_TABLE_VERSION = "6.12.0";
|
package/dist/plugins/index.d.ts
CHANGED
|
@@ -8,15 +8,15 @@ export declare const Plugins: {
|
|
|
8
8
|
/** @deprecated Use `presets.rdg` */
|
|
9
9
|
RDG: {
|
|
10
10
|
Strategies: import("../types").TableStrategies | undefined;
|
|
11
|
-
headerSelector?: string | ((root: import("playwright
|
|
11
|
+
headerSelector?: string | ((root: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
|
|
12
12
|
rowSelector?: string | undefined;
|
|
13
|
-
cellSelector?: string | ((row: import("playwright
|
|
13
|
+
cellSelector?: string | ((row: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
|
|
14
14
|
maxPages?: number | undefined;
|
|
15
15
|
concurrency?: import("../types").RowIterationMode | undefined;
|
|
16
16
|
headerTransformer?: ((args: {
|
|
17
17
|
text: string;
|
|
18
18
|
index: number;
|
|
19
|
-
locator: import("playwright
|
|
19
|
+
locator: import("@playwright/test").Locator;
|
|
20
20
|
seenHeaders: Set<string>;
|
|
21
21
|
}) => string | Promise<string>) | undefined;
|
|
22
22
|
autoScroll?: boolean | undefined;
|
|
@@ -28,15 +28,15 @@ export declare const Plugins: {
|
|
|
28
28
|
/** @deprecated Use `presets.glide` */
|
|
29
29
|
Glide: {
|
|
30
30
|
Strategies: import("../types").TableStrategies | undefined;
|
|
31
|
-
headerSelector?: string | ((root: import("playwright
|
|
31
|
+
headerSelector?: string | ((root: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
|
|
32
32
|
rowSelector?: string | undefined;
|
|
33
|
-
cellSelector?: string | ((row: import("playwright
|
|
33
|
+
cellSelector?: string | ((row: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
|
|
34
34
|
maxPages?: number | undefined;
|
|
35
35
|
concurrency?: import("../types").RowIterationMode | undefined;
|
|
36
36
|
headerTransformer?: ((args: {
|
|
37
37
|
text: string;
|
|
38
38
|
index: number;
|
|
39
|
-
locator: import("playwright
|
|
39
|
+
locator: import("@playwright/test").Locator;
|
|
40
40
|
seenHeaders: Set<string>;
|
|
41
41
|
}) => string | Promise<string>) | undefined;
|
|
42
42
|
autoScroll?: boolean | undefined;
|
|
@@ -48,15 +48,15 @@ export declare const Plugins: {
|
|
|
48
48
|
/** @deprecated Use `presets.muiDataGrid` */
|
|
49
49
|
MUI: {
|
|
50
50
|
Strategies: import("../types").TableStrategies | undefined;
|
|
51
|
-
headerSelector?: string | ((root: import("playwright
|
|
51
|
+
headerSelector?: string | ((root: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
|
|
52
52
|
rowSelector?: string | undefined;
|
|
53
|
-
cellSelector?: string | ((row: import("playwright
|
|
53
|
+
cellSelector?: string | ((row: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
|
|
54
54
|
maxPages?: number | undefined;
|
|
55
55
|
concurrency?: import("../types").RowIterationMode | undefined;
|
|
56
56
|
headerTransformer?: ((args: {
|
|
57
57
|
text: string;
|
|
58
58
|
index: number;
|
|
59
|
-
locator: import("playwright
|
|
59
|
+
locator: import("@playwright/test").Locator;
|
|
60
60
|
seenHeaders: Set<string>;
|
|
61
61
|
}) => string | Promise<string>) | undefined;
|
|
62
62
|
autoScroll?: boolean | undefined;
|
package/dist/presets/mui.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.muiDataGrid = exports.muiTable = void 0;
|
|
4
|
+
const debugUtils_1 = require("../utils/debugUtils");
|
|
4
5
|
/**
|
|
5
6
|
* Safely wait for MUI pagination to stabilize.
|
|
6
7
|
* Polls for displayed row text changes and waits for loading overlays to disappear.
|
|
@@ -86,13 +87,25 @@ exports.muiTable = {
|
|
|
86
87
|
const root = await getPaginationRoot(context);
|
|
87
88
|
const prevBtn = root.locator('button[aria-label="Go to previous page"]');
|
|
88
89
|
const displayedRows = root.locator('.MuiTablePagination-displayedRows');
|
|
89
|
-
let maxRetries = 50;
|
|
90
90
|
let clicked = false;
|
|
91
|
-
|
|
91
|
+
let noProgressCount = 0;
|
|
92
|
+
const NO_PROGRESS_LIMIT = 3;
|
|
93
|
+
while (await prevBtn.count() > 0 && !(await prevBtn.isDisabled())) {
|
|
92
94
|
const oldText = await displayedRows.innerText().catch(() => '');
|
|
93
95
|
await prevBtn.click();
|
|
94
96
|
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
95
97
|
clicked = true;
|
|
98
|
+
const newText = await displayedRows.innerText().catch(() => '');
|
|
99
|
+
if (newText === oldText) {
|
|
100
|
+
noProgressCount++;
|
|
101
|
+
if (noProgressCount >= NO_PROGRESS_LIMIT) {
|
|
102
|
+
(0, debugUtils_1.logDebug)(context.config, 'error', `goToFirst: no pagination progress after ${NO_PROGRESS_LIMIT} consecutive clicks ā aborting to avoid infinite loop`);
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
noProgressCount = 0;
|
|
108
|
+
}
|
|
96
109
|
}
|
|
97
110
|
return clicked;
|
|
98
111
|
}
|
package/dist/smartRow.js
CHANGED
|
@@ -310,7 +310,16 @@ const _navigateToCell = async (params) => {
|
|
|
310
310
|
const finalCell = getCellLocator();
|
|
311
311
|
if (await finalCell.count() > 0)
|
|
312
312
|
return finalCell;
|
|
313
|
-
|
|
313
|
+
const colRange = viewport && viewport.getVisibleColumnRange ? await viewport.getVisibleColumnRange(context) : null;
|
|
314
|
+
const rowRange = viewport && viewport.getVisibleRowRange ? await viewport.getVisibleRowRange(context) : null;
|
|
315
|
+
let errMsg = `SmartTable: could not reach cell for column "${column}" (colIndex ${index}) at row ${rowIndex} after exhausting navigation strategies. Ensure navigation primitives are correctly implemented.\n`;
|
|
316
|
+
if (colRange) {
|
|
317
|
+
errMsg += ` Visible column range: [${colRange.first}ā${colRange.last}].\n`;
|
|
318
|
+
}
|
|
319
|
+
if (rowRange && rowIndex !== undefined) {
|
|
320
|
+
errMsg += ` Visible row range: [${rowRange.first}ā${rowRange.last}].\n`;
|
|
321
|
+
}
|
|
322
|
+
throw new Error(errMsg);
|
|
314
323
|
}
|
|
315
324
|
// No horizontal strategies configured; assume table is 1D or fully rendered,
|
|
316
325
|
// and let standard Playwright auto-waiting handle any lazy-loading delays.
|
|
@@ -508,7 +517,9 @@ const createSmartRow = (rowLocator, map, rowIndex, config, rootLocator, resolve,
|
|
|
508
517
|
};
|
|
509
518
|
smart.bringIntoView = async () => {
|
|
510
519
|
if (rowIndex === undefined) {
|
|
511
|
-
|
|
520
|
+
(0, debugUtils_1.logDebug)(config, 'info', 'bringIntoView called on a row with unknown rowIndex (e.g. from getRow()). ' +
|
|
521
|
+
'Page navigation and scrolling will proceed, but virtual-scroll keyboard navigation will be skipped. ' +
|
|
522
|
+
'Use findRow() if you need accurate rowIndex.');
|
|
512
523
|
}
|
|
513
524
|
const parentTable = smart.table;
|
|
514
525
|
// Cross-page Navigation: when goToPage exists use retry loop (supports windowed UIs); otherwise use path planner or goToFirst+goNext
|
|
@@ -22,7 +22,7 @@ export declare const Strategies: {
|
|
|
22
22
|
}, options?: {
|
|
23
23
|
nextBulkPages?: number;
|
|
24
24
|
previousBulkPages?: number;
|
|
25
|
-
numberOfPages?: number | ((root: import("playwright
|
|
25
|
+
numberOfPages?: number | ((root: import("@playwright/test").Locator) => number | Promise<number>);
|
|
26
26
|
stabilization?: import("./stabilization").StabilizationStrategy;
|
|
27
27
|
timeout?: number;
|
|
28
28
|
}) => import("../types").PaginationStrategy;
|
|
@@ -61,11 +61,23 @@ exports.StabilizationStrategies = {
|
|
|
61
61
|
* Useful for tables that have explicit loading states but might not change content immediately.
|
|
62
62
|
*/
|
|
63
63
|
networkIdle: (options = {}) => {
|
|
64
|
-
return async ({ root, page, resolve }) => {
|
|
64
|
+
return async ({ root, page, resolve }, action) => {
|
|
65
65
|
var _a;
|
|
66
66
|
const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : 5000;
|
|
67
67
|
if (options.spinnerSelector) {
|
|
68
68
|
const spinner = resolve(options.spinnerSelector, root);
|
|
69
|
+
const existedBefore = await spinner.count() > 0;
|
|
70
|
+
await action();
|
|
71
|
+
if (!existedBefore) {
|
|
72
|
+
// Spinner wasn't present before action ā wait briefly for it to appear
|
|
73
|
+
// so we don't declare success before the loading cycle even starts
|
|
74
|
+
const appearDeadline = Date.now() + 500;
|
|
75
|
+
while (Date.now() < appearDeadline && await spinner.count() === 0) {
|
|
76
|
+
await page.waitForTimeout(50);
|
|
77
|
+
}
|
|
78
|
+
if (await spinner.count() === 0)
|
|
79
|
+
return true; // spinner never appeared
|
|
80
|
+
}
|
|
69
81
|
try {
|
|
70
82
|
await spinner.waitFor({ state: 'detached', timeout });
|
|
71
83
|
return true;
|
|
@@ -75,6 +87,7 @@ exports.StabilizationStrategies = {
|
|
|
75
87
|
}
|
|
76
88
|
}
|
|
77
89
|
// Fallback to simple wait if no selector
|
|
90
|
+
await action();
|
|
78
91
|
await page.waitForTimeout(500);
|
|
79
92
|
return true;
|
|
80
93
|
};
|
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 * Use this to scroll off-screen columns into view in horizontally virtualized tables,\n * wait for lazy-rendered content, or perform any pre-read setup.\n *\n * @example\n * // Scroll the column header into view to trigger horizontal virtualization render\n * strategies: {\n * beforeCellRead: async ({ columnName, getHeaderCell }) => {\n * const header = await getHeaderCell(columnName);\n * await header.scrollIntoViewIfNeeded();\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 */\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/**\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 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 }> {\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>;\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;\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;\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>;\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 }\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 * Use this to scroll off-screen columns into view in horizontally virtualized tables,\n * wait for lazy-rendered content, or perform any pre-read setup.\n *\n * @example\n * // Scroll the column header into view to trigger horizontal virtualization render\n * strategies: {\n * beforeCellRead: async ({ columnName, getHeaderCell }) => {\n * const header = await getHeaderCell(columnName);\n * await header.scrollIntoViewIfNeeded();\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 */\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/**\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 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 }> {\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>;\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;\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;\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>;\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";
|
package/dist/typeContext.js
CHANGED
|
@@ -650,7 +650,7 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
|
|
|
650
650
|
*/
|
|
651
651
|
findRows: (
|
|
652
652
|
filters?: Record<string, FilterValue>,
|
|
653
|
-
options?: { exact?: boolean, maxPages?: number }
|
|
653
|
+
options?: { exact?: boolean, maxPages?: number, useBulkPagination?: boolean }
|
|
654
654
|
) => Promise<SmartRowArray<T>>;
|
|
655
655
|
|
|
656
656
|
/**
|
package/dist/types.d.ts
CHANGED
|
@@ -601,6 +601,7 @@ export interface TableResult<T = any> extends AsyncIterable<{
|
|
|
601
601
|
findRows: (filters?: Record<string, FilterValue>, options?: {
|
|
602
602
|
exact?: boolean;
|
|
603
603
|
maxPages?: number;
|
|
604
|
+
useBulkPagination?: boolean;
|
|
604
605
|
}) => Promise<SmartRowArray<T>>;
|
|
605
606
|
/**
|
|
606
607
|
* Navigates to a specific column using the configured CellNavigationStrategy.
|
package/dist/useTable.js
CHANGED
|
@@ -31,6 +31,20 @@ const debugUtils_1 = require("./utils/debugUtils");
|
|
|
31
31
|
const smartRowArray_1 = require("./utils/smartRowArray");
|
|
32
32
|
const elementTracker_1 = require("./utils/elementTracker");
|
|
33
33
|
const navigationBarrier_1 = require("./utils/navigationBarrier");
|
|
34
|
+
// Helper to safely serialize objects containing functions for logging
|
|
35
|
+
const safeStringify = (obj) => {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.stringify(obj, (key, value) => {
|
|
38
|
+
if (typeof value === 'function') {
|
|
39
|
+
return '[Function]';
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
return '[unserializable]';
|
|
46
|
+
}
|
|
47
|
+
};
|
|
34
48
|
/**
|
|
35
49
|
* Main hook to interact with a table.
|
|
36
50
|
*/
|
|
@@ -195,6 +209,10 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
195
209
|
var _a;
|
|
196
210
|
if (tableMapper.isInitialized())
|
|
197
211
|
return result;
|
|
212
|
+
if (config.strategies.sorting)
|
|
213
|
+
(0, validation_1.validateSortingStrategy)(config.strategies.sorting);
|
|
214
|
+
if (config.strategies.fill)
|
|
215
|
+
(0, validation_1.validateFillStrategy)(config.strategies.fill);
|
|
198
216
|
(0, debugUtils_1.warnIfDebugInCI)(config);
|
|
199
217
|
(0, debugUtils_1.logDebug)(config, 'info', 'Initializing table');
|
|
200
218
|
const map = await tableMapper.getMap(options === null || options === void 0 ? void 0 : options.timeout);
|
|
@@ -220,6 +238,7 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
220
238
|
return result;
|
|
221
239
|
},
|
|
222
240
|
scrollToColumn: async (columnName) => {
|
|
241
|
+
log(`scrollToColumn: column="${columnName}"`);
|
|
223
242
|
const map = await tableMapper.getMap();
|
|
224
243
|
const idx = map.get(columnName);
|
|
225
244
|
if (idx === undefined)
|
|
@@ -229,10 +248,12 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
229
248
|
await headerCell.scrollIntoViewIfNeeded();
|
|
230
249
|
},
|
|
231
250
|
getHeaders: async () => {
|
|
251
|
+
log("getHeaders: fetching available columns");
|
|
232
252
|
const map = await tableMapper.getMap();
|
|
233
253
|
return Array.from(map.keys());
|
|
234
254
|
},
|
|
235
255
|
getHeaderCell: async (columnName) => {
|
|
256
|
+
log(`getHeaderCell: column="${columnName}"`);
|
|
236
257
|
const map = await tableMapper.getMap();
|
|
237
258
|
const idx = map.get(columnName);
|
|
238
259
|
if (idx === undefined)
|
|
@@ -240,11 +261,13 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
240
261
|
return resolve(config.headerSelector, rootLocator).nth(idx);
|
|
241
262
|
},
|
|
242
263
|
countRows: async () => {
|
|
264
|
+
log("countRows: counting rows in current viewport");
|
|
243
265
|
await _autoInit();
|
|
244
266
|
const allRows = resolve(config.rowSelector, rootLocator);
|
|
245
267
|
return allRows.count();
|
|
246
268
|
},
|
|
247
269
|
mapColumn: async (columnName, options = {}) => {
|
|
270
|
+
log(`mapColumn: column="${columnName}" options=${safeStringify(options)}`);
|
|
248
271
|
await _autoInit();
|
|
249
272
|
const map = await tableMapper.getMap();
|
|
250
273
|
if (!map.has(columnName))
|
|
@@ -262,6 +285,7 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
262
285
|
}, options);
|
|
263
286
|
},
|
|
264
287
|
getColumnValues: async (columnName, options = {}) => {
|
|
288
|
+
log(`getColumnValues: column="${columnName}" options=${safeStringify(options)}`);
|
|
265
289
|
const values = await result.mapColumn(columnName, options);
|
|
266
290
|
return values.map(v => String(v));
|
|
267
291
|
},
|
|
@@ -288,15 +312,17 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
288
312
|
log("Table revalidated.");
|
|
289
313
|
},
|
|
290
314
|
getRow: (filters, options = { exact: false }) => {
|
|
315
|
+
log(`getRow: filters=${safeStringify(filters)} exact=${options.exact}`);
|
|
291
316
|
const map = tableMapper.getMapSync();
|
|
292
317
|
if (!map)
|
|
293
318
|
throw new Error('Initialization Error: You attempted to access a row before the table structure was mapped. Please call "await table.init()" once before using synchronous row access.');
|
|
294
319
|
const allRows = resolve(config.rowSelector, rootLocator);
|
|
295
320
|
const matchedRows = filterEngine.applyFilters(allRows, filters, map, options.exact || false, rootLocator.page(), rootLocator);
|
|
296
321
|
const rowLocator = matchedRows.first();
|
|
297
|
-
return _makeSmart(rowLocator, map,
|
|
322
|
+
return _makeSmart(rowLocator, map, undefined); // sync path cannot compute real index
|
|
298
323
|
},
|
|
299
324
|
getRowByIndex: (index) => {
|
|
325
|
+
log(`getRowByIndex: index=${index}`);
|
|
300
326
|
const map = tableMapper.getMapSync();
|
|
301
327
|
if (!map)
|
|
302
328
|
throw new Error('Initialization Error: You attempted to access a row before the table structure was mapped. Please call "await table.init()" once before using synchronous row access.');
|
|
@@ -304,13 +330,17 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
304
330
|
return _makeSmart(rowLocator, map, index);
|
|
305
331
|
},
|
|
306
332
|
findRow: async (filters, options) => {
|
|
333
|
+
log(`findRow: filters=${safeStringify(filters)} options=${safeStringify(options)}`);
|
|
307
334
|
return rowFinder.findRow(filters, options);
|
|
308
335
|
},
|
|
309
336
|
findRows: async (filters, options) => {
|
|
337
|
+
log(`findRows: filters=${safeStringify(filters !== null && filters !== void 0 ? filters : {})} options=${safeStringify(options)}`);
|
|
310
338
|
return rowFinder.findRows(filters !== null && filters !== void 0 ? filters : {}, options);
|
|
311
339
|
},
|
|
312
340
|
isInitialized: () => {
|
|
313
|
-
|
|
341
|
+
const initialized = tableMapper.isInitialized();
|
|
342
|
+
log(`isInitialized: ${initialized}`);
|
|
343
|
+
return initialized;
|
|
314
344
|
},
|
|
315
345
|
sorting: {
|
|
316
346
|
apply: async (columnName, direction) => {
|
|
@@ -329,7 +359,10 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
329
359
|
}
|
|
330
360
|
await config.strategies.sorting.doSort({ columnName, direction, context });
|
|
331
361
|
if ((_a = config.strategies.loading) === null || _a === void 0 ? void 0 : _a.isTableLoading) {
|
|
332
|
-
|
|
362
|
+
const deadline = Date.now() + 10000;
|
|
363
|
+
while (Date.now() < deadline && await config.strategies.loading.isTableLoading(context)) {
|
|
364
|
+
await rootLocator.page().waitForTimeout(100);
|
|
365
|
+
}
|
|
333
366
|
}
|
|
334
367
|
else {
|
|
335
368
|
await rootLocator.page().waitForTimeout(200);
|
|
@@ -344,6 +377,7 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
344
377
|
throw new Error(`Failed to sort column "${columnName}" to "${direction}" after ${maxRetries} attempts.`);
|
|
345
378
|
},
|
|
346
379
|
getState: async (columnName) => {
|
|
380
|
+
log(`sorting.getState: column="${columnName}"`);
|
|
347
381
|
await _autoInit();
|
|
348
382
|
if (!config.strategies.sorting)
|
|
349
383
|
throw new Error('No sorting strategy has been configured.');
|
|
@@ -385,6 +419,7 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
385
419
|
},
|
|
386
420
|
// āāā Row iteration (delegated to engine/tableIteration) āāāāāāāāāāāāāāāāāā
|
|
387
421
|
forEach: async (callback, options = {}) => {
|
|
422
|
+
log(`forEach: options=${safeStringify(options)}`);
|
|
388
423
|
await _autoInit();
|
|
389
424
|
await (0, tableIteration_1.runForEach)({
|
|
390
425
|
getRowLocators: () => resolve(config.rowSelector, rootLocator),
|
|
@@ -397,6 +432,7 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
397
432
|
}, callback, options);
|
|
398
433
|
},
|
|
399
434
|
map: async (callback, options = {}) => {
|
|
435
|
+
log(`map: options=${safeStringify(options)}`);
|
|
400
436
|
await _autoInit();
|
|
401
437
|
return (0, tableIteration_1.runMap)({
|
|
402
438
|
getRowLocators: () => resolve(config.rowSelector, rootLocator),
|
|
@@ -409,6 +445,7 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
409
445
|
}, callback, options);
|
|
410
446
|
},
|
|
411
447
|
filter: async (predicate, options = {}) => {
|
|
448
|
+
log(`filter: options=${safeStringify(options)}`);
|
|
412
449
|
await _autoInit();
|
|
413
450
|
return (0, tableIteration_1.runFilter)({
|
|
414
451
|
getRowLocators: () => resolve(config.rowSelector, rootLocator),
|
|
@@ -421,6 +458,7 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
421
458
|
}, predicate, options);
|
|
422
459
|
},
|
|
423
460
|
generateConfig: async () => {
|
|
461
|
+
log("Generating table config prompt...");
|
|
424
462
|
const html = await _getCleanHtml(rootLocator);
|
|
425
463
|
const separator = "=".repeat(50);
|
|
426
464
|
const content = `\n${separator} \nš¤ COPY INTO GEMINI / ChatGPT š¤\n${separator} \nI am using 'playwright-smart-table'.\nTarget Table Locator: ${rootLocator.toString()} \nGenerate config for: \n\`\`\`html\n${html.substring(0, 10000)} ...\n\`\`\`\n${separator}\n`;
|
|
@@ -2,6 +2,16 @@ import { Locator } from '@playwright/test';
|
|
|
2
2
|
export declare class ElementTracker {
|
|
3
3
|
readonly id: string;
|
|
4
4
|
constructor(prefix?: string);
|
|
5
|
+
/**
|
|
6
|
+
* Returns indices of newly seen or recycled elements without marking them as seen.
|
|
7
|
+
* Call {@link commitIndices} to persist the subset you intend to process.
|
|
8
|
+
*/
|
|
9
|
+
peekUnseenIndices(locators: Locator): Promise<number[]>;
|
|
10
|
+
/**
|
|
11
|
+
* Marks the given indices as seen. Only call this for the subset you intend to process;
|
|
12
|
+
* uncommitted indices will be returned again by the next peek/getUnseenIndices call.
|
|
13
|
+
*/
|
|
14
|
+
commitIndices(locators: Locator, indices: number[]): Promise<void>;
|
|
5
15
|
/**
|
|
6
16
|
* Finds the indices of newly seen elements in the browser, storing their text signature
|
|
7
17
|
* in a WeakMap. This gracefully handles both append-only DOMs (by identity) and
|
|
@@ -6,11 +6,10 @@ class ElementTracker {
|
|
|
6
6
|
this.id = `__smartTable_${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* virtualized DOMs (by text signature if nodes are recycled).
|
|
9
|
+
* Returns indices of newly seen or recycled elements without marking them as seen.
|
|
10
|
+
* Call {@link commitIndices} to persist the subset you intend to process.
|
|
12
11
|
*/
|
|
13
|
-
async
|
|
12
|
+
async peekUnseenIndices(locators) {
|
|
14
13
|
return await locators.evaluateAll((elements, trackerId) => {
|
|
15
14
|
const win = window;
|
|
16
15
|
if (!win[trackerId]) {
|
|
@@ -19,17 +18,42 @@ class ElementTracker {
|
|
|
19
18
|
const seenMap = win[trackerId];
|
|
20
19
|
const newIndices = [];
|
|
21
20
|
elements.forEach((el, index) => {
|
|
22
|
-
// Determine a lightweight signature for the row (textContent strips HTML, fast)
|
|
23
21
|
const signature = el.textContent || '';
|
|
24
|
-
// If it's a new element, OR a recycled element with new data
|
|
25
22
|
if (seenMap.get(el) !== signature) {
|
|
26
|
-
seenMap.set(el, signature);
|
|
27
23
|
newIndices.push(index);
|
|
28
24
|
}
|
|
29
25
|
});
|
|
30
26
|
return newIndices;
|
|
31
27
|
}, this.id);
|
|
32
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Marks the given indices as seen. Only call this for the subset you intend to process;
|
|
31
|
+
* uncommitted indices will be returned again by the next peek/getUnseenIndices call.
|
|
32
|
+
*/
|
|
33
|
+
async commitIndices(locators, indices) {
|
|
34
|
+
await locators.evaluateAll((elements, [trackerId, indicesToCommit]) => {
|
|
35
|
+
const win = window;
|
|
36
|
+
if (!win[trackerId]) {
|
|
37
|
+
win[trackerId] = new WeakMap();
|
|
38
|
+
}
|
|
39
|
+
const seenMap = win[trackerId];
|
|
40
|
+
for (const index of indicesToCommit) {
|
|
41
|
+
const el = elements[index];
|
|
42
|
+
if (el)
|
|
43
|
+
seenMap.set(el, el.textContent || '');
|
|
44
|
+
}
|
|
45
|
+
}, [this.id, indices]);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Finds the indices of newly seen elements in the browser, storing their text signature
|
|
49
|
+
* in a WeakMap. This gracefully handles both append-only DOMs (by identity) and
|
|
50
|
+
* virtualized DOMs (by text signature if nodes are recycled).
|
|
51
|
+
*/
|
|
52
|
+
async getUnseenIndices(locators) {
|
|
53
|
+
const indices = await this.peekUnseenIndices(locators);
|
|
54
|
+
await this.commitIndices(locators, indices);
|
|
55
|
+
return indices;
|
|
56
|
+
}
|
|
33
57
|
/**
|
|
34
58
|
* Cleans up the tracking map from the browser window object.
|
|
35
59
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rickcedwhat/playwright-smart-table",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.12.0",
|
|
4
4
|
"description": "Smart, column-aware table interactions for Playwright",
|
|
5
5
|
"author": "Cedrick Catalan",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,19 +28,19 @@
|
|
|
28
28
|
"docs:build:all": "vitepress build docs",
|
|
29
29
|
"docs:verify-links": "node scripts/verify-vitepress-links.mjs",
|
|
30
30
|
"embed-version": "node scripts/embed-version.mjs",
|
|
31
|
-
"build": "
|
|
32
|
-
"prepublishOnly": "
|
|
31
|
+
"build": "pnpm run embed-version && pnpm run generate-types && pnpm run generate-config-types && pnpm run generate-docs && pnpm run generate-all-api-docs && pnpm run update-all-api-signatures && tsc",
|
|
32
|
+
"prepublishOnly": "pnpm run build",
|
|
33
33
|
"clean-port": "lsof -ti:3000 | xargs kill -9 || true",
|
|
34
|
-
"pretest": "
|
|
35
|
-
"posttest": "
|
|
36
|
-
"test": "
|
|
34
|
+
"pretest": "pnpm run clean-port",
|
|
35
|
+
"posttest": "pnpm run clean-port",
|
|
36
|
+
"test": "pnpm run test:unit && pnpm exec playwright test",
|
|
37
37
|
"test:unit": "vitest run --coverage --reporter=verbose --reporter=html",
|
|
38
38
|
"test:unit:ui": "vitest --ui",
|
|
39
|
-
"test:mutate": "
|
|
40
|
-
"pretest:e2e": "
|
|
41
|
-
"posttest:e2e": "
|
|
42
|
-
"test:e2e": "
|
|
43
|
-
"test:playground": "
|
|
39
|
+
"test:mutate": "pnpm exec stryker run",
|
|
40
|
+
"pretest:e2e": "pnpm run clean-port",
|
|
41
|
+
"posttest:e2e": "pnpm run clean-port",
|
|
42
|
+
"test:e2e": "pnpm exec playwright test",
|
|
43
|
+
"test:playground": "pnpm exec playwright test --config tests-external/playground/playwright.config.ts 2>&1 | tee \"tests-external/playground/logs/run-$(date +%Y%m%d-%H%M%S).log\"",
|
|
44
44
|
"dev:playground": "cd playground && npm run dev",
|
|
45
45
|
"dev:mui": "cd tests/apps/mui-datagrid && npm run dev",
|
|
46
46
|
"prepare": "husky"
|
|
@@ -87,17 +87,18 @@
|
|
|
87
87
|
"@stryker-mutator/core": "^9.6.0",
|
|
88
88
|
"@stryker-mutator/vitest-runner": "^9.6.0",
|
|
89
89
|
"@types/node": "^25.5.2",
|
|
90
|
-
"@vitest/coverage-v8": "^
|
|
91
|
-
"@vitest/ui": "^
|
|
90
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
91
|
+
"@vitest/ui": "^3.2.4",
|
|
92
92
|
"happy-dom": "^20.8.3",
|
|
93
93
|
"@commitlint/cli": "^19.7.1",
|
|
94
94
|
"@commitlint/config-conventional": "^19.7.1",
|
|
95
95
|
"husky": "^9.1.7",
|
|
96
96
|
"typescript": "^6.0.2",
|
|
97
97
|
"vitepress": "^1.6.4",
|
|
98
|
-
"vitest": "^
|
|
98
|
+
"vitest": "^3.2.4"
|
|
99
99
|
},
|
|
100
100
|
"dependencies": {
|
|
101
101
|
"@scarf/scarf": "^1.4.0"
|
|
102
|
-
}
|
|
102
|
+
},
|
|
103
|
+
"packageManager": "pnpm@10.33.2"
|
|
103
104
|
}
|