@rickcedwhat/playwright-smart-table 6.10.1 → 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/README.md CHANGED
@@ -5,236 +5,71 @@
5
5
  [![npm version](https://img.shields.io/github/package-json/v/rickcedwhat/playwright-smart-table?label=npm&color=blue&t=2)](https://www.npmjs.com/package/@rickcedwhat/playwright-smart-table)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
7
 
8
- ---
9
-
10
8
  ## šŸ“š [Full Documentation →](https://rickcedwhat.github.io/playwright-smart-table/)
11
9
 
12
- **Visit the complete documentation at: https://rickcedwhat.github.io/playwright-smart-table/**
13
-
14
10
  ---
15
11
 
16
- ## Why Playwright Smart Table?
17
-
18
- Testing HTML tables in Playwright is painful. Traditional approaches are fragile and hard to maintain.
19
-
20
- ### The Problem
12
+ ## The Problem
21
13
 
22
- **Traditional approach:**
14
+ Testing HTML tables in Playwright is fragile by default:
23
15
 
24
16
  ```typescript
25
- // āŒ Fragile - breaks if columns reorder
17
+ // āŒ Breaks if columns reorder
26
18
  const email = await page.locator('tbody tr').nth(2).locator('td').nth(3).textContent();
27
19
 
28
- // āŒ Brittle XPath
29
- const row = page.locator('//tr[td[contains(text(), "John")]]');
30
-
31
- // āŒ Manual column mapping
20
+ // āŒ Manual column mapping every time
32
21
  const headers = await page.locator('thead th').allTextContents();
33
22
  const emailIndex = headers.indexOf('Email');
34
23
  const email = await row.locator('td').nth(emailIndex).textContent();
35
24
  ```
36
25
 
37
- ### The Solution
38
-
39
- **Playwright Smart Table:**
26
+ ## The Solution
40
27
 
41
28
  ```typescript
42
- // āœ… Column-aware - survives column reordering
29
+ // āœ… Column-aware — survives column reordering
43
30
  const row = table.getRow({ Name: 'John Doe' });
44
31
  const email = await row.getCell('Email').textContent();
45
32
 
46
- // āœ… Pagination-aware when you raise maxPages
47
- const allEngineers = await table.findRows(
48
- { Department: 'Engineering' },
49
- { maxPages: 5 }
50
- );
33
+ // āœ… Search across pages
34
+ const allEngineers = await table.findRows({ Department: 'Engineering' }, { maxPages: 5 });
51
35
 
52
- // āœ… Type-safe
53
- type Employee = { Name: string; Email: string; Department: string };
54
- const table = useTable<Employee>(page.locator('#table'));
36
+ // āœ… Iterate with forEach, map, filter, or for await...of
37
+ await table.forEach(async ({ row }) => {
38
+ await row.getCell('Checkbox').click();
39
+ });
55
40
  ```
56
41
 
57
- ## Quick Start
58
-
59
- ### Installation
42
+ ## Installation
60
43
 
61
44
  ```bash
62
45
  npm install @rickcedwhat/playwright-smart-table
63
46
  ```
64
47
 
65
- ### Basic Usage
48
+ ## Quick Start
66
49
 
67
50
  ```typescript
68
51
  import { useTable } from '@rickcedwhat/playwright-smart-table';
69
52
 
70
53
  const table = await useTable(page.locator('#my-table')).init();
71
54
 
72
- // Get row by column values (current page)
73
55
  const row = table.getRow({ Name: 'John Doe' });
74
-
75
- // Access cells by column name
76
56
  const email = await row.getCell('Email').innerText();
77
-
78
- // Search more than the current page by raising maxPages
79
- const allActive = await table.findRows({ Status: 'Active' }, { maxPages: 5 });
80
- ```
81
-
82
- ### Iterating Across Pages
83
-
84
- ```typescript
85
- // forEach — sequential by default (concurrency: 'sequential') — safe for interactions
86
- await table.forEach(async ({ row, rowIndex, stop }) => {
87
- if (await row.getCell('Status').innerText() === 'Done') stop();
88
- await row.getCell('Checkbox').click();
89
- });
90
-
91
- // map — parallel by default (concurrency: 'parallel') — safe for reads
92
- const emails = await table.map(({ row }) => row.getCell('Email').innerText());
93
-
94
- // filter — sequential by default; returns SmartRowArray
95
- const active = await table.filter(async ({ row }) =>
96
- await row.getCell('Status').innerText() === 'Active'
97
- );
98
-
99
- // for await...of — low-level page-by-page iteration
100
- for await (const { row, rowIndex } of table) {
101
- console.log(rowIndex, await row.getCell('Name').innerText());
102
- }
103
- ```
104
-
105
- Set a default for all iteration calls with `useTable(..., { concurrency: 'sequential' })`, or per call: `table.map(fn, { concurrency: 'synchronized' })`. Modes: **`parallel`** (full parallelism), **`sequential`** (strictly one row at a time), **`synchronized`** (parallel navigation with serialized callbacks — useful for virtualized grids).
106
-
107
- When your pagination strategy supports bulk jumps (`goNextBulk`), pass `{ useBulkPagination: true }` to `map`/`forEach`/`filter` to advance by multiple pages at once.
108
-
109
- > **`map` + UI interactions:** `map` defaults to `concurrency: 'parallel'`. If your callback opens popovers,
110
- > fills inputs, or otherwise mutates UI state, pass `{ concurrency: 'sequential' }` (or `'synchronized'` if you need lock-step navigation with serialized work).
111
-
112
- ### `filter` vs `findRows`
113
-
114
- | Use case | Best tool |
115
- |---|---|
116
- | Match by column value / regex / locator | `findRows` |
117
- | Computed value (math, range, derived) | `filter` |
118
- | Cross-column OR logic | `filter` |
119
- | Multi-step interaction in predicate (click, read, close) | `filter` |
120
- | Early exit after N matches | `filter` + `stop()` |
121
-
122
- **`findRows` is faster** for column-value matches — Playwright evaluates the locator natively with no DOM reads. **`filter` is more flexible** for logic that a CSS selector can't express.
123
-
124
- ```typescript
125
- // findRows — structural match, no DOM reads, fast
126
- const notStarted = await table.findRows({
127
- Status: (cell) => cell.locator('[class*="gray"]')
128
- });
129
-
130
- // filter — arbitrary async logic
131
- const expensive = await table.filter(async ({ row }) => {
132
- const price = parseFloat(await row.getCell('Price').innerText());
133
- const qty = parseFloat(await row.getCell('Qty').innerText());
134
- return price * qty > 1000;
135
- });
136
- ```
137
-
138
- ### Advanced: `columnOverrides`
139
-
140
- For complex DOM structures, custom data extraction, or specialized input widgets, use `columnOverrides` to intercept how Smart Table interacts with specific columns:
141
-
142
- ```typescript
143
- const table = useTable(page.locator('#table'), {
144
- columnOverrides: {
145
- // Override how data is read from the 'Status' column (e.g., for .toJSON())
146
- Status: {
147
- read: async (cell) => {
148
- const isChecked = await cell.locator('input[type="checkbox"]').isChecked();
149
- return isChecked ? 'Active' : 'Inactive';
150
- }
151
- },
152
- // Override how data is written to the 'Tags' column (for .smartFill())
153
- Tags: {
154
- write: async ({ cell, targetValue }) => {
155
- await cell.click();
156
- await page.keyboard.type(targetValue);
157
- await page.keyboard.press('Enter');
158
- }
159
- }
160
- }
161
- });
162
57
  ```
163
58
 
164
59
  ## Key Features
165
60
 
166
- - šŸŽÆ **Smart Locators** - Find rows by content, not position
167
- - 🧠 **Fuzzy Matching** - Smart suggestions for typos in column names
168
- - ⚔ **Smart Initialization** - Handles loading states and dynamic headers automatically
169
- - šŸ“„ **Pagination-aware search** - Scan beyond the current page when `maxPages` is increased
170
- - šŸ” **Column-Aware Access** - Access cells by column name
171
- - šŸ” **Iteration Methods** - `forEach`, `map`, `filter`, and `for await...of` across the configured page range
172
- - šŸ› ļø **Debug Mode** - Visual debugging with slow motion and logging
173
- - šŸ”Œ **[Extensible Strategies](docs/concepts/strategies.md)** - Support any table implementation
174
- - šŸ’Ŗ **Type-Safe** - Full TypeScript support
175
- - šŸš€ **Production-Ready** - Battle-tested in real-world applications
176
-
177
- ## When to Use This Library
178
-
179
- **Use this library when you need to:**
180
-
181
- - āœ… Find rows by column values
182
- - āœ… Access cells by column name
183
- - āœ… Search across paginated tables
184
- - āœ… Handle column reordering
185
- - āœ… Extract structured data
186
- - āœ… Fill/edit table cells
187
- - āœ… Work with dynamic tables (MUI DataGrid, AG Grid, etc.)
188
-
189
- **You might not need this library if:**
190
-
191
- - āŒ You don't interact with tables at all
192
- - āŒ You don't need to find a row based on a value in a cell
193
- - āŒ You don't need to find a cell based on a value in another cell in the same row
194
-
195
- ### āš ļø Important Note on Pagination & Interactions
196
-
197
- When `findRows` or `filter` paginates across pages, returned `SmartRow` locators point to rows that may be off the current DOM page.
198
-
199
- - **Data extraction:** Safe — `toJSON()` and cell reads work while the row is visible during iteration.
200
- - **Interactions after pagination:** Use `await row.bringIntoView()` first — it navigates back to the page the row was originally found on, then you can safely click/fill.
61
+ - šŸŽÆ **Column-aware locators** — find rows and cells by name, not index
62
+ - šŸ“„ **Pagination-aware search** — `findRows` and `forEach` scan across pages automatically
63
+ - šŸ” **Iteration methods** — `forEach`, `map`, `filter`, and `for await...of`
64
+ - šŸ› ļø **Debug mode** — slow motion playback and structured logs
65
+ - šŸ”Œ **Extensible strategies** — plug in any table implementation or pagination shape
66
+ - šŸ’Ŗ **Full TypeScript support**
201
67
 
202
- ```typescript
203
- const active = await table.filter(async ({ row }) =>
204
- await row.getCell('Status').innerText() === 'Active'
205
- );
206
-
207
- for (const row of active) {
208
- await row.bringIntoView(); // navigate back to the row's page
209
- await row.getCell('Checkbox').click(); // safe to interact
210
- }
211
- ```
212
-
213
- ## Documentation
214
-
215
- **šŸ“š Full documentation available at: https://rickcedwhat.github.io/playwright-smart-table/**
216
-
217
- - [Getting Started Guide](https://rickcedwhat.github.io/playwright-smart-table/guide/getting-started)
218
- - [Core Concepts](https://rickcedwhat.github.io/playwright-smart-table/guide/core-concepts)
219
- - [API Reference](https://rickcedwhat.github.io/playwright-smart-table/api/)
220
- - [Examples](https://rickcedwhat.github.io/playwright-smart-table/examples/)
221
- - [Troubleshooting](https://rickcedwhat.github.io/playwright-smart-table/troubleshooting)
222
-
223
- ## Contributing
224
-
225
- Contributions are welcome! Please feel free to submit a Pull Request.
226
-
227
- ## Deprecations
228
-
229
- - `generateConfigPrompt()` — deprecated. Use `generateConfig()` instead. `generateConfigPrompt()` will be removed in v7.0.0.
230
-
231
- ## License
232
-
233
- MIT Ā© Cedrick Catalan
234
-
235
- ## Links
68
+ ---
236
69
 
237
70
  - [Documentation](https://rickcedwhat.github.io/playwright-smart-table/)
238
71
  - [npm Package](https://www.npmjs.com/package/@rickcedwhat/playwright-smart-table)
239
72
  - [GitHub Repository](https://github.com/rickcedwhat/playwright-smart-table)
240
73
  - [Issues](https://github.com/rickcedwhat/playwright-smart-table/issues)
74
+
75
+ MIT Ā© Cedrick Catalan
@@ -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
  }
@@ -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
- return this.makeSmartRow(rowLocator, await this.tableMapper.getMap(), 0);
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
- if ((_c = this.config.strategies.pagination) === null || _c === void 0 ? void 0 : _c.goNextBulk) {
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, _c, _d;
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
- if ((_c = this.config.strategies.pagination) === null || _c === void 0 ? void 0 : _c.goNextBulk) {
163
- paginationResult = await this.config.strategies.pagination.goNextBulk(context);
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 ((_d = this.config.strategies.pagination) === null || _d === void 0 ? void 0 : _d.goNext) {
166
- paginationResult = await this.config.strategies.pagination.goNext(context);
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 newIndices = await tracker.getUnseenIndices(rowLocators);
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`);
@@ -79,7 +86,7 @@ async function runMap(env, callback, options = {}, label = 'map') {
79
86
  if (stopped && row.rowIndex > stoppedIndex)
80
87
  return SKIP;
81
88
  log(env.config, `${label}: processing row ${row.rowIndex}`);
82
- return await callback({ row, rowIndex: row.rowIndex, stop: () => stop(row.rowIndex) });
89
+ return await callback({ row, index: row.rowIndex, rowIndex: row.rowIndex, stop: () => stop(row.rowIndex) });
83
90
  };
84
91
  if (actionMutex) {
85
92
  return await actionMutex.run(runCallback);
@@ -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.10.1";
6
+ export declare const PLAYWRIGHT_SMART_TABLE_VERSION: "6.12.0";
@@ -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.10.1";
9
+ exports.PLAYWRIGHT_SMART_TABLE_VERSION = "6.12.0";
@@ -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-core").Locator) => import("playwright-core").Locator) | undefined;
11
+ headerSelector?: string | ((root: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
12
12
  rowSelector?: string | undefined;
13
- cellSelector?: string | ((row: import("playwright-core").Locator) => import("playwright-core").Locator) | undefined;
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-core").Locator;
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-core").Locator) => import("playwright-core").Locator) | undefined;
31
+ headerSelector?: string | ((root: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
32
32
  rowSelector?: string | undefined;
33
- cellSelector?: string | ((row: import("playwright-core").Locator) => import("playwright-core").Locator) | undefined;
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-core").Locator;
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-core").Locator) => import("playwright-core").Locator) | undefined;
51
+ headerSelector?: string | ((root: import("@playwright/test").Locator) => import("@playwright/test").Locator) | undefined;
52
52
  rowSelector?: string | undefined;
53
- cellSelector?: string | ((row: import("playwright-core").Locator) => import("playwright-core").Locator) | undefined;
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-core").Locator;
59
+ locator: import("@playwright/test").Locator;
60
60
  seenHeaders: Set<string>;
61
61
  }) => string | Promise<string>) | undefined;
62
62
  autoScroll?: boolean | undefined;
@@ -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
- while (maxRetries-- > 0 && await prevBtn.count() > 0 && !(await prevBtn.isDisabled())) {
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
- throw new Error(`SmartTable: could not reach cell for column "${column}" (colIndex ${index}) at row ${rowIndex} after exhausting navigation strategies. Ensure navigation primitives are correctly implemented.`);
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
- throw new Error('Cannot bring row into view - row index is unknown. Use getRowByIndex() instead of getRow().');
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-core").Locator) => number | Promise<number>);
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;
@@ -70,7 +70,10 @@ export declare const Strategies: {
70
70
  never: () => Promise<boolean>;
71
71
  };
72
72
  Headers: {
73
- stable: (duration?: number) => (context: import("..").TableContext) => Promise<boolean>;
73
+ stable: (duration?: number, options?: {
74
+ pollMs?: number;
75
+ timeoutMs?: number;
76
+ }) => (context: import("..").TableContext) => Promise<boolean>;
74
77
  never: () => Promise<boolean>;
75
78
  };
76
79
  };
@@ -50,10 +50,20 @@ export declare const LoadingStrategies: {
50
50
  */
51
51
  Headers: {
52
52
  /**
53
- * Checks if the headers are stable (count and text) for a specified duration.
54
- * @param duration Duration in ms for headers to remain unchanged to be considered stable (default: 200).
53
+ * Waits until the header signature (count + text) remains unchanged for `duration` ms.
54
+ *
55
+ * The default single-shot check (read → wait → read) is fine for most grids.
56
+ * For slow or virtualized grids that churn headers for several seconds, supply
57
+ * `pollMs` and optionally `timeoutMs` to poll in a loop until stable.
58
+ *
59
+ * @param duration Stable window in ms — headers must not change for this long (default: 200).
60
+ * @param options.pollMs How often to re-check while waiting (default: same as `duration`, i.e. single-shot).
61
+ * @param options.timeoutMs Hard deadline in ms; throws if stability is never reached (default: no hard timeout).
55
62
  */
56
- stable: (duration?: number) => (context: TableContext) => Promise<boolean>;
63
+ stable: (duration?: number, options?: {
64
+ pollMs?: number;
65
+ timeoutMs?: number;
66
+ }) => (context: TableContext) => Promise<boolean>;
57
67
  /**
58
68
  * Assume headers are never loading (immediate snapshot).
59
69
  */
@@ -75,26 +75,55 @@ exports.LoadingStrategies = {
75
75
  */
76
76
  Headers: {
77
77
  /**
78
- * Checks if the headers are stable (count and text) for a specified duration.
79
- * @param duration Duration in ms for headers to remain unchanged to be considered stable (default: 200).
78
+ * Waits until the header signature (count + text) remains unchanged for `duration` ms.
79
+ *
80
+ * The default single-shot check (read → wait → read) is fine for most grids.
81
+ * For slow or virtualized grids that churn headers for several seconds, supply
82
+ * `pollMs` and optionally `timeoutMs` to poll in a loop until stable.
83
+ *
84
+ * @param duration Stable window in ms — headers must not change for this long (default: 200).
85
+ * @param options.pollMs How often to re-check while waiting (default: same as `duration`, i.e. single-shot).
86
+ * @param options.timeoutMs Hard deadline in ms; throws if stability is never reached (default: no hard timeout).
80
87
  */
81
- stable: (duration = 200) => async (context) => {
88
+ stable: (duration = 200, options = {}) => async (context) => {
82
89
  const { config, resolve, root } = context;
83
- const getHeaderTexts = async () => {
90
+ const { pollMs, timeoutMs } = options;
91
+ const getSignature = async () => {
84
92
  const headers = await resolve(config.headerSelector, root).all();
85
- return Promise.all(headers.map(h => h.innerText()));
93
+ const texts = await Promise.all(headers.map(h => h.innerText()));
94
+ return texts.join('\x00');
86
95
  };
87
- const initial = await getHeaderTexts();
88
- // Wait for duration
89
- await context.page.waitForTimeout(duration);
90
- const current = await getHeaderTexts();
91
- if (initial.length !== current.length)
92
- return true; // Count changed, still loading
93
- for (let i = 0; i < initial.length; i++) {
94
- if (initial[i] !== current[i])
95
- return true; // Content changed, still loading
96
+ // Single-shot path (original behaviour): no polling requested
97
+ if (pollMs === undefined) {
98
+ const initial = await getSignature();
99
+ await context.page.waitForTimeout(duration);
100
+ const current = await getSignature();
101
+ return initial !== current; // true = still loading
102
+ }
103
+ // Polling path
104
+ const deadline = timeoutMs !== undefined ? Date.now() + timeoutMs : Infinity;
105
+ let lastSig = await getSignature();
106
+ let stableStart = Date.now(); // baseline sample counts toward the stable window
107
+ while (true) {
108
+ // Check deadline before sleeping so the loop cannot overshoot timeoutMs by one pollMs interval.
109
+ if (Date.now() > deadline) {
110
+ throw new Error(`Headers.stable: headers did not stabilise within ${timeoutMs}ms`);
111
+ }
112
+ await context.page.waitForTimeout(pollMs);
113
+ const sig = await getSignature();
114
+ if (sig !== lastSig) {
115
+ lastSig = sig;
116
+ stableStart = null; // reset on change
117
+ continue;
118
+ }
119
+ if (stableStart === null) {
120
+ stableStart = Date.now();
121
+ continue;
122
+ }
123
+ if (Date.now() - stableStart >= duration) {
124
+ return false; // Stable — not loading
125
+ }
96
126
  }
97
- return false; // Stable
98
127
  },
99
128
  /**
100
129
  * Assume headers are never loading (immediate snapshot).
@@ -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
  };
@@ -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 rowIndex: 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 }> {\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";
@@ -555,7 +555,10 @@ export interface FillOptions {
555
555
  /** Callback context passed to forEach, map, and filter. */
556
556
  export type RowIterationContext<T = any> = {
557
557
  row: SmartRow<T>;
558
+ /** 0-based iteration counter — 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. */
558
559
  rowIndex: number;
560
+ /** 0-based iteration counter — the order this row was visited, not its DOM position or grid identity. */
561
+ index: number;
559
562
  stop: () => void;
560
563
  };
561
564
 
@@ -586,7 +589,7 @@ export type RowIterationOptions = {
586
589
  useBulkPagination?: boolean;
587
590
  };
588
591
 
589
- export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number }> {
592
+ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number; index: number }> {
590
593
  /**
591
594
  * Represents the current page index of the table's DOM.
592
595
  * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.
@@ -647,7 +650,7 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
647
650
  */
648
651
  findRows: (
649
652
  filters?: Record<string, FilterValue>,
650
- options?: { exact?: boolean, maxPages?: number }
653
+ options?: { exact?: boolean, maxPages?: number, useBulkPagination?: boolean }
651
654
  ) => Promise<SmartRowArray<T>>;
652
655
 
653
656
  /**
package/dist/types.d.ts CHANGED
@@ -512,7 +512,10 @@ export interface FillOptions {
512
512
  /** Callback context passed to forEach, map, and filter. */
513
513
  export type RowIterationContext<T = any> = {
514
514
  row: SmartRow<T>;
515
+ /** 0-based iteration counter — 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. */
515
516
  rowIndex: number;
517
+ /** 0-based iteration counter — the order this row was visited, not its DOM position or grid identity. */
518
+ index: number;
516
519
  stop: () => void;
517
520
  };
518
521
  /** Concurrency modes for row iteration. */
@@ -543,6 +546,7 @@ export type RowIterationOptions = {
543
546
  export interface TableResult<T = any> extends AsyncIterable<{
544
547
  row: SmartRow<T>;
545
548
  rowIndex: number;
549
+ index: number;
546
550
  }> {
547
551
  /**
548
552
  * Represents the current page index of the table's DOM.
@@ -597,6 +601,7 @@ export interface TableResult<T = any> extends AsyncIterable<{
597
601
  findRows: (filters?: Record<string, FilterValue>, options?: {
598
602
  exact?: boolean;
599
603
  maxPages?: number;
604
+ useBulkPagination?: boolean;
600
605
  }) => Promise<SmartRowArray<T>>;
601
606
  /**
602
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, 0); // fallback index 0
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
- return tableMapper.isInitialized();
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
- await config.strategies.loading.isTableLoading(context);
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.');
@@ -368,7 +402,7 @@ const useTable = (rootLocator, configOptions = {}) => {
368
402
  const pageRows = yield __await(rowLocators.all());
369
403
  const barrier = new navigationBarrier_1.NavigationBarrier(newIndices.length);
370
404
  for (const idx of newIndices) {
371
- yield yield __await({ row: _makeSmart(pageRows[idx], map, rowIndex, pagesScanned - 1, barrier), rowIndex });
405
+ yield yield __await({ row: _makeSmart(pageRows[idx], map, rowIndex, pagesScanned - 1, barrier), index: rowIndex, rowIndex });
372
406
  rowIndex++;
373
407
  }
374
408
  if (pagesScanned >= effectiveMaxPages)
@@ -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
- * Finds the indices of newly seen elements in the browser, storing their text signature
10
- * in a WeakMap. This gracefully handles both append-only DOMs (by identity) and
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 getUnseenIndices(locators) {
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.10.1",
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": "npm run embed-version && npm run generate-types && npm run generate-config-types && npm run generate-docs && npm run generate-all-api-docs && npm run update-all-api-signatures && tsc",
32
- "prepublishOnly": "npm run build",
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": "npm run clean-port",
35
- "posttest": "npm run clean-port",
36
- "test": "npm run test:unit && npx playwright 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": "npx stryker run",
40
- "pretest:e2e": "npm run clean-port",
41
- "posttest:e2e": "npm run clean-port",
42
- "test:e2e": "npx playwright test",
43
- "test:playground": "npx 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\"",
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,15 +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": "^4.1.0",
91
- "@vitest/ui": "^4.1.0",
90
+ "@vitest/coverage-v8": "^3.2.4",
91
+ "@vitest/ui": "^3.2.4",
92
92
  "happy-dom": "^20.8.3",
93
+ "@commitlint/cli": "^19.7.1",
94
+ "@commitlint/config-conventional": "^19.7.1",
93
95
  "husky": "^9.1.7",
94
96
  "typescript": "^6.0.2",
95
97
  "vitepress": "^1.6.4",
96
- "vitest": "^4.1.0"
98
+ "vitest": "^3.2.4"
97
99
  },
98
100
  "dependencies": {
99
101
  "@scarf/scarf": "^1.4.0"
100
- }
102
+ },
103
+ "packageManager": "pnpm@10.33.2"
101
104
  }