@rickcedwhat/playwright-smart-table 6.10.0 → 6.11.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,233 +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
- // ✅ Auto-pagination across all pages
47
- const allEngineers = await table.findRows({ Department: 'Engineering' });
33
+ // ✅ Search across pages
34
+ const allEngineers = await table.findRows({ Department: 'Engineering' }, { maxPages: 5 });
48
35
 
49
- // ✅ Type-safe
50
- type Employee = { Name: string; Email: string; Department: string };
51
- 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
+ });
52
40
  ```
53
41
 
54
- ## Quick Start
55
-
56
- ### Installation
42
+ ## Installation
57
43
 
58
44
  ```bash
59
45
  npm install @rickcedwhat/playwright-smart-table
60
46
  ```
61
47
 
62
- ### Basic Usage
48
+ ## Quick Start
63
49
 
64
50
  ```typescript
65
51
  import { useTable } from '@rickcedwhat/playwright-smart-table';
66
52
 
67
53
  const table = await useTable(page.locator('#my-table')).init();
68
54
 
69
- // Get row by column values (current page)
70
55
  const row = table.getRow({ Name: 'John Doe' });
71
-
72
- // Access cells by column name
73
56
  const email = await row.getCell('Email').innerText();
74
-
75
- // Search across paginated tables
76
- const allActive = await table.findRows({ Status: 'Active' });
77
- ```
78
-
79
- ### Iterating Across Pages
80
-
81
- ```typescript
82
- // forEach — sequential by default (concurrency: 'sequential') — safe for interactions
83
- await table.forEach(async ({ row, rowIndex, stop }) => {
84
- if (await row.getCell('Status').innerText() === 'Done') stop();
85
- await row.getCell('Checkbox').click();
86
- });
87
-
88
- // map — parallel by default (concurrency: 'parallel') — safe for reads
89
- const emails = await table.map(({ row }) => row.getCell('Email').innerText());
90
-
91
- // filter — sequential by default; returns SmartRowArray
92
- const active = await table.filter(async ({ row }) =>
93
- await row.getCell('Status').innerText() === 'Active'
94
- );
95
-
96
- // for await...of — low-level page-by-page iteration
97
- for await (const { row, rowIndex } of table) {
98
- console.log(rowIndex, await row.getCell('Name').innerText());
99
- }
100
- ```
101
-
102
- 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).
103
-
104
- When your pagination strategy supports bulk jumps (`goNextBulk`), pass `{ useBulkPagination: true }` to `map`/`forEach`/`filter` to advance by multiple pages at once.
105
-
106
- > **`map` + UI interactions:** `map` defaults to `concurrency: 'parallel'`. If your callback opens popovers,
107
- > fills inputs, or otherwise mutates UI state, pass `{ concurrency: 'sequential' }` (or `'synchronized'` if you need lock-step navigation with serialized work).
108
-
109
- ### `filter` vs `findRows`
110
-
111
- | Use case | Best tool |
112
- |---|---|
113
- | Match by column value / regex / locator | `findRows` |
114
- | Computed value (math, range, derived) | `filter` |
115
- | Cross-column OR logic | `filter` |
116
- | Multi-step interaction in predicate (click, read, close) | `filter` |
117
- | Early exit after N matches | `filter` + `stop()` |
118
-
119
- **`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.
120
-
121
- ```typescript
122
- // findRows — structural match, no DOM reads, fast
123
- const notStarted = await table.findRows({
124
- Status: (cell) => cell.locator('[class*="gray"]')
125
- });
126
-
127
- // filter — arbitrary async logic
128
- const expensive = await table.filter(async ({ row }) => {
129
- const price = parseFloat(await row.getCell('Price').innerText());
130
- const qty = parseFloat(await row.getCell('Qty').innerText());
131
- return price * qty > 1000;
132
- });
133
- ```
134
-
135
- ### Advanced: `columnOverrides`
136
-
137
- For complex DOM structures, custom data extraction, or specialized input widgets, use `columnOverrides` to intercept how Smart Table interacts with specific columns:
138
-
139
- ```typescript
140
- const table = useTable(page.locator('#table'), {
141
- columnOverrides: {
142
- // Override how data is read from the 'Status' column (e.g., for .toJSON())
143
- Status: {
144
- read: async (cell) => {
145
- const isChecked = await cell.locator('input[type="checkbox"]').isChecked();
146
- return isChecked ? 'Active' : 'Inactive';
147
- }
148
- },
149
- // Override how data is written to the 'Tags' column (for .smartFill())
150
- Tags: {
151
- write: async ({ cell, targetValue }) => {
152
- await cell.click();
153
- await page.keyboard.type(targetValue);
154
- await page.keyboard.press('Enter');
155
- }
156
- }
157
- }
158
- });
159
57
  ```
160
58
 
161
59
  ## Key Features
162
60
 
163
- - 🎯 **Smart Locators** - Find rows by content, not position
164
- - 🧠 **Fuzzy Matching** - Smart suggestions for typos in column names
165
- - ⚡ **Smart Initialization** - Handles loading states and dynamic headers automatically
166
- - 📄 **Auto-Pagination** - Search across all pages automatically
167
- - 🔍 **Column-Aware Access** - Access cells by column name
168
- - 🔁 **Iteration Methods** - `forEach`, `map`, `filter`, and `for await...of` across all pages
169
- - 🛠️ **Debug Mode** - Visual debugging with slow motion and logging
170
- - 🔌 **[Extensible Strategies](docs/concepts/strategies.md)** - Support any table implementation
171
- - 💪 **Type-Safe** - Full TypeScript support
172
- - 🚀 **Production-Ready** - Battle-tested in real-world applications
173
-
174
- ## When to Use This Library
175
-
176
- **Use this library when you need to:**
177
-
178
- - ✅ Find rows by column values
179
- - ✅ Access cells by column name
180
- - ✅ Search across paginated tables
181
- - ✅ Handle column reordering
182
- - ✅ Extract structured data
183
- - ✅ Fill/edit table cells
184
- - ✅ Work with dynamic tables (MUI DataGrid, AG Grid, etc.)
185
-
186
- **You might not need this library if:**
187
-
188
- - ❌ You don't interact with tables at all
189
- - ❌ You don't need to find a row based on a value in a cell
190
- - ❌ You don't need to find a cell based on a value in another cell in the same row
191
-
192
- ### ⚠️ Important Note on Pagination & Interactions
193
-
194
- When `findRows` or `filter` paginates across pages, returned `SmartRow` locators point to rows that may be off the current DOM page.
195
-
196
- - **Data extraction:** Safe — `toJSON()` and cell reads work while the row is visible during iteration.
197
- - **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**
198
67
 
199
- ```typescript
200
- const active = await table.filter(async ({ row }) =>
201
- await row.getCell('Status').innerText() === 'Active'
202
- );
203
-
204
- for (const row of active) {
205
- await row.bringIntoView(); // navigate back to the row's page
206
- await row.getCell('Checkbox').click(); // safe to interact
207
- }
208
- ```
209
-
210
- ## Documentation
211
-
212
- **📚 Full documentation available at: https://rickcedwhat.github.io/playwright-smart-table/**
213
-
214
- - [Getting Started Guide](https://rickcedwhat.github.io/playwright-smart-table/guide/getting-started)
215
- - [Core Concepts](https://rickcedwhat.github.io/playwright-smart-table/guide/core-concepts)
216
- - [API Reference](https://rickcedwhat.github.io/playwright-smart-table/api/)
217
- - [Examples](https://rickcedwhat.github.io/playwright-smart-table/examples/)
218
- - [Troubleshooting](https://rickcedwhat.github.io/playwright-smart-table/troubleshooting)
219
-
220
- ## Contributing
221
-
222
- Contributions are welcome! Please feel free to submit a Pull Request.
223
-
224
- ## Deprecations
225
-
226
- - `generateConfigPrompt()` — deprecated. Use `generateConfig()` instead. `generateConfigPrompt()` will be removed in v7.0.0.
227
-
228
- ## License
229
-
230
- MIT © Cedrick Catalan
231
-
232
- ## Links
68
+ ---
233
69
 
234
70
  - [Documentation](https://rickcedwhat.github.io/playwright-smart-table/)
235
71
  - [npm Package](https://www.npmjs.com/package/@rickcedwhat/playwright-smart-table)
236
72
  - [GitHub Repository](https://github.com/rickcedwhat/playwright-smart-table)
237
73
  - [Issues](https://github.com/rickcedwhat/playwright-smart-table/issues)
74
+
75
+ MIT © Cedrick Catalan
@@ -79,7 +79,7 @@ async function runMap(env, callback, options = {}, label = 'map') {
79
79
  if (stopped && row.rowIndex > stoppedIndex)
80
80
  return SKIP;
81
81
  log(env.config, `${label}: processing row ${row.rowIndex}`);
82
- return await callback({ row, rowIndex: row.rowIndex, stop: () => stop(row.rowIndex) });
82
+ return await callback({ row, index: row.rowIndex, rowIndex: row.rowIndex, stop: () => stop(row.rowIndex) });
83
83
  };
84
84
  if (actionMutex) {
85
85
  return await actionMutex.run(runCallback);
@@ -3,4 +3,4 @@
3
3
  * This file is generated by scripts/embed-config-types.mjs
4
4
  * It contains minimal type definitions for config generation prompts.
5
5
  */
6
- export declare const MINIMAL_CONFIG_CONTEXT = "\n/**\n * Flexible selector type - can be a CSS string or function returning a Locator.\n * @example\n * // String selector\n * rowSelector: 'tbody tr'\n * \n * // Function selector\n * rowSelector: (root) => root.locator('[role=\"row\"]')\n */\nexport type Selector = string | ((root: Locator | Page) => Locator);\n\n/**\n * Debug configuration for development and troubleshooting\n */\nexport type DebugConfig = {\n slow?: number | {\n pagination?: number;\n getCell?: number;\n findRow?: number;\n default?: number;\n };\n logLevel?: 'verbose' | 'info' | 'error' | 'none';\n};\n\n/**\n * Configuration options for useTable - focus on selectors and basic setup\n */\nexport interface TableConfig<T = any> {\n /** CSS selector or function for table headers */\n headerSelector?: string | ((root: Locator) => Locator);\n \n /** CSS selector or function for table rows */\n rowSelector?: string | ((root: Locator) => Locator);\n \n /** CSS selector or function for cells within a row */\n cellSelector?: string | ((row: Locator) => Locator);\n \n /** Transform header text (e.g., normalize, deduplicate) */\n headerTransformer?: (args: { \n text: string; \n index: number; \n locator: Locator;\n seenHeaders: Set<string>;\n }) => string | Promise<string>;\n \n /** Automatically scroll to table on init (default: true) */\n autoScroll?: boolean;\n \n /** Debug options for development and troubleshooting */\n debug?: DebugConfig;\n \n /** Advanced: Custom strategies for pagination, sorting, navigation, etc. */\n strategies?: TableStrategies;\n}\n\n/**\n * Example usage:\n */\n// const table = useTable(page.locator('table'), {\n// headerSelector: 'thead th',\n// rowSelector: 'tbody tr',\n// cellSelector: 'td',\n// headerTransformer: ({ text }) => text.trim()\n// });\n\n";
6
+ export declare const MINIMAL_CONFIG_CONTEXT = "\n/**\n * Flexible selector type - can be a CSS string or function returning a Locator.\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);\n\n/**\n * Debug configuration for development and troubleshooting\n */\nexport type DebugConfig = {\n slow?: number | {\n pagination?: number;\n getCell?: number;\n findRow?: number;\n default?: number;\n };\n logLevel?: 'verbose' | 'info' | 'error' | 'none';\n};\n\n/**\n * Configuration options for useTable - focus on selectors and basic setup\n */\nexport interface TableConfig<T = any> {\n /** CSS selector or function for table headers */\n headerSelector?: string | ((root: Locator) => Locator);\n \n /** CSS selector or function for table rows */\n rowSelector?: string | ((root: Locator) => Locator);\n \n /** CSS selector or function for cells within a row */\n cellSelector?: string | ((row: Locator) => Locator);\n \n /** Transform header text (e.g., normalize, deduplicate) */\n headerTransformer?: (args: { \n text: string; \n index: number; \n locator: Locator;\n seenHeaders: Set<string>;\n }) => string | Promise<string>;\n \n /** Automatically scroll to table on init (default: true) */\n autoScroll?: boolean;\n \n /** Debug options for development and troubleshooting */\n debug?: DebugConfig;\n \n /** Advanced: Custom strategies for pagination, sorting, navigation, etc. */\n strategies?: TableStrategies;\n}\n\n/**\n * Example usage:\n */\n// const table = useTable(page.locator('table'), {\n// headerSelector: 'thead th',\n// rowSelector: 'tbody tr',\n// cellSelector: 'td',\n// headerTransformer: ({ text }) => text.trim()\n// });\n\n";
@@ -14,7 +14,7 @@ exports.MINIMAL_CONFIG_CONTEXT = `
14
14
  * rowSelector: 'tbody tr'
15
15
  *
16
16
  * // Function selector
17
- * rowSelector: (root) => root.locator('[role="row"]')
17
+ * headerSelector: (root) => root.locator('[role="columnheader"]')
18
18
  */
19
19
  export type Selector = string | ((root: Locator | Page) => Locator);
20
20
 
@@ -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.0";
6
+ export declare const PLAYWRIGHT_SMART_TABLE_VERSION: "6.11.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.0";
9
+ exports.PLAYWRIGHT_SMART_TABLE_VERSION = "6.11.0";
package/dist/smartRow.js CHANGED
@@ -115,8 +115,21 @@ const _navigateToCell = async (params) => {
115
115
  }
116
116
  // Cell still not accessible — fall through to navigation primitives if configured.
117
117
  if (!config.strategies.navigation) {
118
- (0, debugUtils_1.logDebug)(config, 'verbose', '_navigateToCell: viewport phase could not reach cell, no navigation fallback configured');
119
- return null;
118
+ const colRange = viewport.getVisibleColumnRange ? await viewport.getVisibleColumnRange(context) : null;
119
+ const rowRange = viewport.getVisibleRowRange ? await viewport.getVisibleRowRange(context) : null;
120
+ let errMsg = `SmartTable: could not reach cell for column "${column}" (colIndex ${index}) at row ${rowIndex}.\n`;
121
+ if (colRange) {
122
+ errMsg += ` Visible column range: [${colRange.first}–${colRange.last}]. Column is out of view and no navigation fallback is configured.\n`;
123
+ }
124
+ else {
125
+ errMsg += ` Column is out of view and no navigation fallback is configured.\n`;
126
+ }
127
+ if (rowRange && rowIndex !== undefined) {
128
+ const inView = rowIndex >= rowRange.first && rowIndex <= rowRange.last;
129
+ errMsg += ` Visible row range: [${rowRange.first}–${rowRange.last}]. ${inView ? 'Row is in view.' : 'Row is out of view.'}\n`;
130
+ }
131
+ errMsg += ` → Add a \`strategies.navigation\` or \`strategies.viewport.scrollToColumn\` to handle off-screen columns.`;
132
+ throw new Error(errMsg);
120
133
  }
121
134
  }
122
135
  // Use navigation primitives if available
@@ -297,9 +310,11 @@ const _navigateToCell = async (params) => {
297
310
  const finalCell = getCellLocator();
298
311
  if (await finalCell.count() > 0)
299
312
  return finalCell;
300
- return null;
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.`);
301
314
  }
302
- return null;
315
+ // No horizontal strategies configured; assume table is 1D or fully rendered,
316
+ // and let standard Playwright auto-waiting handle any lazy-loading delays.
317
+ return getCellLocator();
303
318
  };
304
319
  /**
305
320
  * Factory to create a SmartRow by extending a Playwright Locator.
@@ -322,8 +337,9 @@ const createSmartRow = (rowLocator, map, rowIndex, config, rootLocator, resolve,
322
337
  if (idx === undefined) {
323
338
  throw new Error((0, stringUtils_1.buildColumnNotFoundError)(colName, Array.from(map.keys())));
324
339
  }
340
+ let baseLocator;
325
341
  if (config.strategies.getCellLocator) {
326
- return config.strategies.getCellLocator({
342
+ baseLocator = config.strategies.getCellLocator({
327
343
  row: rowLocator,
328
344
  root: rootLocator,
329
345
  columnName: colName,
@@ -333,7 +349,27 @@ const createSmartRow = (rowLocator, map, rowIndex, config, rootLocator, resolve,
333
349
  config
334
350
  });
335
351
  }
336
- return resolve(config.cellSelector, rowLocator).nth(idx);
352
+ else {
353
+ baseLocator = resolve(config.cellSelector, rowLocator).nth(idx);
354
+ }
355
+ const smartCell = baseLocator;
356
+ smartCell.bringIntoView = async () => {
357
+ const navigatedCell = await _navigateToCell({
358
+ config,
359
+ rootLocator,
360
+ page: rootLocator.page(),
361
+ resolve,
362
+ column: colName,
363
+ index: idx,
364
+ rowLocator,
365
+ rowIndex,
366
+ barrier: smart._barrier
367
+ });
368
+ if (navigatedCell && navigatedCell._locator) {
369
+ smartCell._locator = navigatedCell._locator;
370
+ }
371
+ };
372
+ return smartCell;
337
373
  };
338
374
  smart.wasFound = () => {
339
375
  return !smart[sentinel_1.SENTINEL_ROW];
@@ -486,7 +522,13 @@ const createSmartRow = (rowLocator, map, rowIndex, config, rootLocator, resolve,
486
522
  await (0, paginationPath_1.executeNavigationWithGoToPageRetry)(tablePageIndex, primitives, context, getCurrent, setCurrent);
487
523
  }
488
524
  else {
489
- const path = (0, paginationPath_1.planNavigationPath)(getCurrent(), tablePageIndex, primitives);
525
+ let totalPages;
526
+ if (primitives.getTotalPages) {
527
+ const tp = await primitives.getTotalPages(context);
528
+ if (tp !== null)
529
+ totalPages = tp;
530
+ }
531
+ const path = (0, paginationPath_1.planNavigationPath)(getCurrent(), tablePageIndex, primitives, totalPages);
490
532
  if (path.length > 0) {
491
533
  (0, debugUtils_1.logDebug)(config, 'info', `bringIntoView: Executing navigation path to page ${tablePageIndex} (${path.length} step(s))`);
492
534
  await (0, paginationPath_1.executeNavigationPath)(path, primitives, context, getCurrent, setCurrent);
@@ -17,9 +17,12 @@ export declare const Strategies: {
17
17
  nextBulk?: import("..").Selector;
18
18
  previousBulk?: import("..").Selector;
19
19
  first?: import("..").Selector;
20
+ last?: import("..").Selector;
21
+ pageNumbers?: import("..").Selector;
20
22
  }, options?: {
21
23
  nextBulkPages?: number;
22
24
  previousBulkPages?: number;
25
+ numberOfPages?: number | ((root: import("playwright-core").Locator) => number | Promise<number>);
23
26
  stabilization?: import("./stabilization").StabilizationStrategy;
24
27
  timeout?: number;
25
28
  }) => import("../types").PaginationStrategy;
@@ -67,7 +70,10 @@ export declare const Strategies: {
67
70
  never: () => Promise<boolean>;
68
71
  };
69
72
  Headers: {
70
- 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>;
71
77
  never: () => Promise<boolean>;
72
78
  };
73
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).
@@ -7,9 +7,19 @@ export declare const PaginationStrategies: {
7
7
  nextBulk?: Selector;
8
8
  previousBulk?: Selector;
9
9
  first?: Selector;
10
+ last?: Selector;
11
+ /**
12
+ * Selector matching all visible page-number buttons/links.
13
+ * Used to implement direct page jumps (goToPage). Works with both full-range pagination
14
+ * (all pages always visible) and windowed pagination (e.g. only pages 6–14 visible) —
15
+ * returns false when the target page is outside the current window, triggering the
16
+ * library's step-and-retry loop until the button scrolls into view.
17
+ */
18
+ pageNumbers?: Selector;
10
19
  }, options?: {
11
20
  nextBulkPages?: number;
12
21
  previousBulkPages?: number;
22
+ numberOfPages?: number | ((root: import("@playwright/test").Locator) => number | Promise<number>);
13
23
  stabilization?: StabilizationStrategy;
14
24
  timeout?: number;
15
25
  }) => PaginationStrategy;
@@ -16,7 +16,8 @@ exports.PaginationStrategies = {
16
16
  return false;
17
17
  }
18
18
  return await defaultStabilize(context, async () => {
19
- await btn.click({ timeout: 2000 }).catch(() => { });
19
+ var _a;
20
+ await btn.click({ timeout: (_a = options.timeout) !== null && _a !== void 0 ? _a : 2000 });
20
21
  }).then(stabilized => stabilized ? returnVal : false);
21
22
  };
22
23
  };
@@ -28,6 +29,33 @@ exports.PaginationStrategies = {
28
29
  goNextBulk: createClicker(selectors.nextBulk, nextBulk),
29
30
  goPreviousBulk: createClicker(selectors.previousBulk, prevBulk),
30
31
  goToFirst: createClicker(selectors.first),
32
+ goToLast: createClicker(selectors.last),
33
+ goToPage: selectors.pageNumbers
34
+ ? async (pageIndex, context) => {
35
+ const { root, resolve } = context;
36
+ const pageLabel = String(pageIndex + 1);
37
+ const btn = resolve(selectors.pageNumbers, root)
38
+ .filter({ hasText: new RegExp(`^\\s*${pageLabel}\\s*$`) })
39
+ .first();
40
+ if (!await btn.isVisible().catch(() => false))
41
+ return false;
42
+ if (!await btn.isEnabled().catch(() => false))
43
+ return false;
44
+ return await defaultStabilize(context, async () => {
45
+ var _a;
46
+ await btn.click({ timeout: (_a = options.timeout) !== null && _a !== void 0 ? _a : 2000 });
47
+ }).then(s => !!s);
48
+ }
49
+ : undefined,
50
+ getTotalPages: options.numberOfPages !== undefined ? async (context) => {
51
+ const result = typeof options.numberOfPages === 'function'
52
+ ? await options.numberOfPages(context.root)
53
+ : options.numberOfPages;
54
+ if (typeof result !== 'number' || !Number.isFinite(result) || !Number.isInteger(result) || result < 1) {
55
+ throw new Error(`[SmartTable] numberOfPages must return a finite integer >= 1 (received: ${result})`);
56
+ }
57
+ return result;
58
+ } : undefined,
31
59
  nextBulkPages: nextBulk,
32
60
  previousBulkPages: prevBulk,
33
61
  };
@@ -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 * rowSelector: (root) => root.locator('[role=\"row\"]')\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 * 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 Locator for the cell\n * @example\n * const emailCell = row.getCell('Email');\n * await expect(emailCell).toHaveText('john@example.com');\n */\n getCell(column: string): Locator;\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 * Only works if rowIndex is known (e.g., from getRowByIndex).\n * @throws Error if rowIndex 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 /**\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\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\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 }\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";
@@ -14,7 +14,7 @@ exports.TYPE_CONTEXT = `
14
14
  * rowSelector: 'tbody tr'
15
15
  *
16
16
  * // Function selector
17
- * rowSelector: (root) => root.locator('[role="row"]')
17
+ * headerSelector: (root) => root.locator('[role="columnheader"]')
18
18
  */
19
19
  export type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);
20
20
 
@@ -166,6 +166,21 @@ export interface ViewportStrategy {
166
166
  }
167
167
 
168
168
 
169
+ /**
170
+ * SmartCell - A Playwright Locator with table-aware methods for single-cell operations.
171
+ *
172
+ * Extends all standard Locator methods (click, isVisible, etc.).
173
+ */
174
+ export type SmartCell = Locator & {
175
+ /**
176
+ * Scrolls/paginates to bring this specific cell into view using the configured strategies.
177
+ * Useful when the grid is horizontally virtualized and the column must be scrolled
178
+ * into view before it can be interacted with or read.
179
+ */
180
+ bringIntoView(): Promise<void>;
181
+ };
182
+
183
+
169
184
  /**
170
185
  * SmartRow - A Playwright Locator with table-aware methods.
171
186
  *
@@ -191,12 +206,13 @@ export type SmartRow<T = any> = Locator & {
191
206
  /**
192
207
  * Get a cell locator by column name.
193
208
  * @param column - Column name (case-sensitive)
194
- * @returns Locator for the cell
209
+ * @returns SmartCell (Locator + bringIntoView)
195
210
  * @example
196
211
  * const emailCell = row.getCell('Email');
212
+ * await emailCell.bringIntoView();
197
213
  * await expect(emailCell).toHaveText('john@example.com');
198
214
  */
199
- getCell(column: string): Locator;
215
+ getCell(column: string): SmartCell;
200
216
 
201
217
  /**
202
218
  * Extract all cell data as a key-value object.
@@ -214,8 +230,9 @@ export type SmartRow<T = any> = Locator & {
214
230
 
215
231
  /**
216
232
  * Scrolls/paginates to bring this row into view.
217
- * Only works if rowIndex is known (e.g., from getRowByIndex).
218
- * @throws Error if rowIndex is unknown
233
+ * Works when row position metadata is known (e.g., from getRowByIndex, findRow,
234
+ * findRows, filter, or async iteration).
235
+ * @throws Error if row position metadata is unknown
219
236
  */
220
237
  bringIntoView(): Promise<void>;
221
238
 
@@ -325,6 +342,15 @@ export interface PaginationPrimitives {
325
342
  /** Jump to first page / scroll to top */
326
343
  goToFirst?: (context: TableContext) => Promise<boolean>;
327
344
 
345
+ /** Jump to last page / scroll to bottom */
346
+ goToLast?: (context: TableContext) => Promise<boolean>;
347
+
348
+ /**
349
+ * Fetch the total number of pages currently available.
350
+ * Can be used to optimize pagination paths (e.g. jumping to last page and going backwards).
351
+ */
352
+ getTotalPages?: (context: TableContext) => Promise<number | null>;
353
+
328
354
  /**
329
355
  * Jump to specific page index (0-indexed).
330
356
  * Can be full-range (e.g. page number input: any page works) or windowed (e.g. only visible links 6–14).
@@ -337,6 +363,18 @@ export interface PaginationPrimitives {
337
363
 
338
364
  /** How many pages one goPreviousBulk() goes back. Used by navigation path planner for optimal bringIntoView. */
339
365
  previousBulkPages?: number;
366
+
367
+ /**
368
+ * Called once during init() to sync the library's page counter with the actual DOM state.
369
+ * Use when a table may open on a page other than the first (e.g. a deep-linked URL that
370
+ * lands on page 5). Returns a 0-indexed page number.
371
+ * @example
372
+ * detectCurrentPage: async (root) => {
373
+ * const text = await root.locator('[aria-current="page"]').textContent();
374
+ * return parseInt(text ?? '1') - 1;
375
+ * }
376
+ */
377
+ detectCurrentPage?: (root: import('@playwright/test').Locator) => number | Promise<number>;
340
378
  }
341
379
 
342
380
  export type PaginationStrategy = PaginationPrimitives;
@@ -517,7 +555,10 @@ export interface FillOptions {
517
555
  /** Callback context passed to forEach, map, and filter. */
518
556
  export type RowIterationContext<T = any> = {
519
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. */
520
559
  rowIndex: number;
560
+ /** 0-based iteration counter — the order this row was visited, not its DOM position or grid identity. */
561
+ index: number;
521
562
  stop: () => void;
522
563
  };
523
564
 
@@ -548,7 +589,7 @@ export type RowIterationOptions = {
548
589
  useBulkPagination?: boolean;
549
590
  };
550
591
 
551
- 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 }> {
552
593
  /**
553
594
  * Represents the current page index of the table's DOM.
554
595
  * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.
@@ -617,6 +658,26 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
617
658
  */
618
659
  scrollToColumn: (columnName: string) => Promise<void>;
619
660
 
661
+ /**
662
+ * Counts the number of rows currently on the page.
663
+ * Does not paginate.
664
+ */
665
+ countRows: () => Promise<number>;
666
+
667
+ /**
668
+ * Iterates over rows and extracts the value of a single column.
669
+ * More efficient than map + toJSON for single-column extraction.
670
+ * @param columnName - The name of the column to extract
671
+ * @param options - Iteration options
672
+ */
673
+ mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;
674
+
675
+ /**
676
+ * Iterates over rows and extracts the value of a single column as strings.
677
+ * @param columnName - The name of the column to extract
678
+ * @param options - Iteration options
679
+ */
680
+ getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;
620
681
 
621
682
 
622
683
  /**
package/dist/types.d.ts CHANGED
@@ -7,7 +7,7 @@ import type { SmartRowArray } from './utils/smartRowArray';
7
7
  * rowSelector: 'tbody tr'
8
8
  *
9
9
  * // Function selector
10
- * rowSelector: (root) => root.locator('[role="row"]')
10
+ * headerSelector: (root) => root.locator('[role="columnheader"]')
11
11
  */
12
12
  export type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);
13
13
  /**
@@ -154,6 +154,19 @@ export interface ViewportStrategy {
154
154
  */
155
155
  disableCache?: boolean;
156
156
  }
157
+ /**
158
+ * SmartCell - A Playwright Locator with table-aware methods for single-cell operations.
159
+ *
160
+ * Extends all standard Locator methods (click, isVisible, etc.).
161
+ */
162
+ export type SmartCell = Locator & {
163
+ /**
164
+ * Scrolls/paginates to bring this specific cell into view using the configured strategies.
165
+ * Useful when the grid is horizontally virtualized and the column must be scrolled
166
+ * into view before it can be interacted with or read.
167
+ */
168
+ bringIntoView(): Promise<void>;
169
+ };
157
170
  /**
158
171
  * SmartRow - A Playwright Locator with table-aware methods.
159
172
  *
@@ -176,12 +189,13 @@ export type SmartRow<T = any> = Locator & {
176
189
  /**
177
190
  * Get a cell locator by column name.
178
191
  * @param column - Column name (case-sensitive)
179
- * @returns Locator for the cell
192
+ * @returns SmartCell (Locator + bringIntoView)
180
193
  * @example
181
194
  * const emailCell = row.getCell('Email');
195
+ * await emailCell.bringIntoView();
182
196
  * await expect(emailCell).toHaveText('john@example.com');
183
197
  */
184
- getCell(column: string): Locator;
198
+ getCell(column: string): SmartCell;
185
199
  /**
186
200
  * Extract all cell data as a key-value object.
187
201
  * @param options - Optional configuration
@@ -199,8 +213,9 @@ export type SmartRow<T = any> = Locator & {
199
213
  }): Promise<T>;
200
214
  /**
201
215
  * Scrolls/paginates to bring this row into view.
202
- * Only works if rowIndex is known (e.g., from getRowByIndex).
203
- * @throws Error if rowIndex is unknown
216
+ * Works when row position metadata is known (e.g., from getRowByIndex, findRow,
217
+ * findRows, filter, or async iteration).
218
+ * @throws Error if row position metadata is unknown
204
219
  */
205
220
  bringIntoView(): Promise<void>;
206
221
  /**
@@ -297,6 +312,13 @@ export interface PaginationPrimitives {
297
312
  goPreviousBulk?: (context: TableContext) => Promise<boolean | number>;
298
313
  /** Jump to first page / scroll to top */
299
314
  goToFirst?: (context: TableContext) => Promise<boolean>;
315
+ /** Jump to last page / scroll to bottom */
316
+ goToLast?: (context: TableContext) => Promise<boolean>;
317
+ /**
318
+ * Fetch the total number of pages currently available.
319
+ * Can be used to optimize pagination paths (e.g. jumping to last page and going backwards).
320
+ */
321
+ getTotalPages?: (context: TableContext) => Promise<number | null>;
300
322
  /**
301
323
  * Jump to specific page index (0-indexed).
302
324
  * Can be full-range (e.g. page number input: any page works) or windowed (e.g. only visible links 6–14).
@@ -307,6 +329,17 @@ export interface PaginationPrimitives {
307
329
  nextBulkPages?: number;
308
330
  /** How many pages one goPreviousBulk() goes back. Used by navigation path planner for optimal bringIntoView. */
309
331
  previousBulkPages?: number;
332
+ /**
333
+ * Called once during init() to sync the library's page counter with the actual DOM state.
334
+ * Use when a table may open on a page other than the first (e.g. a deep-linked URL that
335
+ * lands on page 5). Returns a 0-indexed page number.
336
+ * @example
337
+ * detectCurrentPage: async (root) => {
338
+ * const text = await root.locator('[aria-current="page"]').textContent();
339
+ * return parseInt(text ?? '1') - 1;
340
+ * }
341
+ */
342
+ detectCurrentPage?: (root: import('@playwright/test').Locator) => number | Promise<number>;
310
343
  }
311
344
  export type PaginationStrategy = PaginationPrimitives;
312
345
  export type DedupeStrategy = (row: SmartRow) => string | number | Promise<string | number>;
@@ -479,7 +512,10 @@ export interface FillOptions {
479
512
  /** Callback context passed to forEach, map, and filter. */
480
513
  export type RowIterationContext<T = any> = {
481
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. */
482
516
  rowIndex: number;
517
+ /** 0-based iteration counter — the order this row was visited, not its DOM position or grid identity. */
518
+ index: number;
483
519
  stop: () => void;
484
520
  };
485
521
  /** Concurrency modes for row iteration. */
@@ -510,6 +546,7 @@ export type RowIterationOptions = {
510
546
  export interface TableResult<T = any> extends AsyncIterable<{
511
547
  row: SmartRow<T>;
512
548
  rowIndex: number;
549
+ index: number;
513
550
  }> {
514
551
  /**
515
552
  * Represents the current page index of the table's DOM.
@@ -569,6 +606,24 @@ export interface TableResult<T = any> extends AsyncIterable<{
569
606
  * Navigates to a specific column using the configured CellNavigationStrategy.
570
607
  */
571
608
  scrollToColumn: (columnName: string) => Promise<void>;
609
+ /**
610
+ * Counts the number of rows currently on the page.
611
+ * Does not paginate.
612
+ */
613
+ countRows: () => Promise<number>;
614
+ /**
615
+ * Iterates over rows and extracts the value of a single column.
616
+ * More efficient than map + toJSON for single-column extraction.
617
+ * @param columnName - The name of the column to extract
618
+ * @param options - Iteration options
619
+ */
620
+ mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;
621
+ /**
622
+ * Iterates over rows and extracts the value of a single column as strings.
623
+ * @param columnName - The name of the column to extract
624
+ * @param options - Iteration options
625
+ */
626
+ getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;
572
627
  /**
573
628
  * Resets the table state (clears cache, flags) and invokes the onReset strategy.
574
629
  */
package/dist/useTable.js CHANGED
@@ -192,12 +192,30 @@ const useTable = (rootLocator, configOptions = {}) => {
192
192
  get currentPageIndex() { return tableState.currentPageIndex; },
193
193
  set currentPageIndex(v) { tableState.currentPageIndex = v; },
194
194
  init: async (options) => {
195
+ var _a;
195
196
  if (tableMapper.isInitialized())
196
197
  return result;
197
198
  (0, debugUtils_1.warnIfDebugInCI)(config);
198
199
  (0, debugUtils_1.logDebug)(config, 'info', 'Initializing table');
199
200
  const map = await tableMapper.getMap(options === null || options === void 0 ? void 0 : options.timeout);
200
201
  (0, debugUtils_1.logDebug)(config, 'info', `Table initialized with ${map.size} columns`, Array.from(map.keys()));
202
+ if ((_a = config.strategies.pagination) === null || _a === void 0 ? void 0 : _a.detectCurrentPage) {
203
+ try {
204
+ const detected = await config.strategies.pagination.detectCurrentPage(rootLocator);
205
+ if (Number.isInteger(detected) && detected >= 0) {
206
+ tableState.currentPageIndex = detected;
207
+ (0, debugUtils_1.logDebug)(config, 'info', `init: detected starting page index ${detected}`);
208
+ }
209
+ else {
210
+ tableState.currentPageIndex = 0;
211
+ (0, debugUtils_1.logDebug)(config, 'error', `init: detectCurrentPage returned invalid index (${detected}); defaulting to 0`);
212
+ }
213
+ }
214
+ catch (e) {
215
+ tableState.currentPageIndex = 0;
216
+ (0, debugUtils_1.logDebug)(config, 'error', `init: detectCurrentPage failed`, e);
217
+ }
218
+ }
201
219
  await (0, debugUtils_1.debugDelay)(config, 'default');
202
220
  return result;
203
221
  },
@@ -221,6 +239,32 @@ const useTable = (rootLocator, configOptions = {}) => {
221
239
  throw _createColumnError(columnName, map, 'header cell');
222
240
  return resolve(config.headerSelector, rootLocator).nth(idx);
223
241
  },
242
+ countRows: async () => {
243
+ await _autoInit();
244
+ const allRows = resolve(config.rowSelector, rootLocator);
245
+ return allRows.count();
246
+ },
247
+ mapColumn: async (columnName, options = {}) => {
248
+ await _autoInit();
249
+ const map = await tableMapper.getMap();
250
+ if (!map.has(columnName))
251
+ throw _createColumnError(columnName, map, 'mapColumn iteration');
252
+ return result.map(async ({ row }) => {
253
+ var _a;
254
+ const cell = row.getCell(columnName);
255
+ await cell.bringIntoView();
256
+ const columnOverride = (_a = config.columnOverrides) === null || _a === void 0 ? void 0 : _a[columnName];
257
+ if (columnOverride === null || columnOverride === void 0 ? void 0 : columnOverride.read) {
258
+ return await columnOverride.read(cell);
259
+ }
260
+ const text = await cell.innerText();
261
+ return (text || '').trim();
262
+ }, options);
263
+ },
264
+ getColumnValues: async (columnName, options = {}) => {
265
+ const values = await result.mapColumn(columnName, options);
266
+ return values.map(v => String(v));
267
+ },
224
268
  reset: async () => {
225
269
  var _a;
226
270
  log("Resetting table...");
@@ -324,7 +368,7 @@ const useTable = (rootLocator, configOptions = {}) => {
324
368
  const pageRows = yield __await(rowLocators.all());
325
369
  const barrier = new navigationBarrier_1.NavigationBarrier(newIndices.length);
326
370
  for (const idx of newIndices) {
327
- yield yield __await({ row: _makeSmart(pageRows[idx], map, rowIndex, pagesScanned - 1, barrier), rowIndex });
371
+ yield yield __await({ row: _makeSmart(pageRows[idx], map, rowIndex, pagesScanned - 1, barrier), index: rowIndex, rowIndex });
328
372
  rowIndex++;
329
373
  }
330
374
  if (pagesScanned >= effectiveMaxPages)
@@ -3,6 +3,9 @@ import type { PaginationPrimitives, TableContext } from '../types';
3
3
  export type NavigationStep = {
4
4
  type: 'goToPage';
5
5
  pageIndex: number;
6
+ } | {
7
+ type: 'goToLast';
8
+ targetIndex: number;
6
9
  } | {
7
10
  type: 'goNextBulk';
8
11
  count: number;
@@ -22,7 +25,7 @@ export type NavigationStep = {
22
25
  * single steps (goNext / goPrevious). May choose to overshoot with bulk then step back when
23
26
  * that reduces total primitive calls (e.g. page 3 → 12 with bulk 10: goNextBulk once, goPrevious once).
24
27
  */
25
- export declare function planNavigationPath(currentPageIndex: number, targetPageIndex: number, primitives: PaginationPrimitives): NavigationStep[];
28
+ export declare function planNavigationPath(currentPageIndex: number, targetPageIndex: number, primitives: PaginationPrimitives, totalPages?: number): NavigationStep[];
26
29
  /**
27
30
  * Navigate to targetPageIndex when goToPage is available but may be "windowed"
28
31
  * (e.g. only works for visible page links 6–14). Tries goToPage(target); on false,
@@ -3,13 +3,20 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.planNavigationPath = planNavigationPath;
4
4
  exports.executeNavigationWithGoToPageRetry = executeNavigationWithGoToPageRetry;
5
5
  exports.executeNavigationPath = executeNavigationPath;
6
+ function computeCost(path) {
7
+ return path.reduce((sum, step) => {
8
+ if ('count' in step)
9
+ return sum + step.count;
10
+ return sum + 1; // goToPage and goToLast count as 1
11
+ }, 0);
12
+ }
6
13
  /**
7
14
  * Plans an optimal path from currentPageIndex to targetPageIndex using available primitives.
8
15
  * Prefers goToPage when present; otherwise uses bulk steps (goNextBulk / goPreviousBulk) then
9
16
  * single steps (goNext / goPrevious). May choose to overshoot with bulk then step back when
10
17
  * that reduces total primitive calls (e.g. page 3 → 12 with bulk 10: goNextBulk once, goPrevious once).
11
18
  */
12
- function planNavigationPath(currentPageIndex, targetPageIndex, primitives) {
19
+ function planNavigationPath(currentPageIndex, targetPageIndex, primitives, totalPages) {
13
20
  var _a, _b;
14
21
  if (currentPageIndex === targetPageIndex)
15
22
  return [];
@@ -23,37 +30,58 @@ function planNavigationPath(currentPageIndex, targetPageIndex, primitives) {
23
30
  const stepsForward = targetPageIndex - currentPageIndex;
24
31
  const hasBulk = !!(primitives.goNextBulk && nextBulkSize > 0);
25
32
  const hasPrev = !!primitives.goPrevious;
33
+ let forwardPath = [];
26
34
  if (!hasBulk || nextBulkSize <= 0) {
27
35
  if (primitives.goNext) {
28
- return [{ type: 'goNext', count: stepsForward }];
36
+ forwardPath = [{ type: 'goNext', count: stepsForward }];
29
37
  }
30
- return [];
31
38
  }
32
- const bulkCountA = Math.floor(stepsForward / nextBulkSize);
33
- const remA = stepsForward % nextBulkSize;
34
- const totalA = bulkCountA + remA;
35
- let totalB = Infinity;
36
- let bulkCountB = 0;
37
- let overB = 0;
38
- if (hasPrev && primitives.goPreviousBulk && prevBulkSize > 0) {
39
- bulkCountB = Math.ceil(stepsForward / nextBulkSize);
40
- overB = bulkCountB * nextBulkSize - stepsForward;
41
- totalB = bulkCountB + overB;
39
+ else {
40
+ const bulkCountA = Math.floor(stepsForward / nextBulkSize);
41
+ const remA = stepsForward % nextBulkSize;
42
+ const totalA = (remA === 0 || primitives.goNext)
43
+ ? bulkCountA + remA
44
+ : Infinity;
45
+ let totalB = Infinity;
46
+ let bulkCountB = 0;
47
+ let overB = 0;
48
+ if (hasPrev) {
49
+ bulkCountB = Math.ceil(stepsForward / nextBulkSize);
50
+ overB = bulkCountB * nextBulkSize - stepsForward;
51
+ totalB = bulkCountB + overB;
52
+ }
53
+ forwardPath = (totalB < totalA)
54
+ ? (() => {
55
+ const path = [];
56
+ if (bulkCountB > 0)
57
+ path.push({ type: 'goNextBulk', count: bulkCountB });
58
+ if (overB > 0)
59
+ path.push({ type: 'goPrevious', count: overB });
60
+ return path;
61
+ })()
62
+ : Number.isFinite(totalA) ? (() => {
63
+ const path = [];
64
+ if (bulkCountA > 0)
65
+ path.push({ type: 'goNextBulk', count: bulkCountA });
66
+ if (remA > 0)
67
+ path.push({ type: 'goNext', count: remA });
68
+ return path;
69
+ })() : [];
42
70
  }
43
- if (totalB < totalA) {
44
- const path = [];
45
- if (bulkCountB > 0)
46
- path.push({ type: 'goNextBulk', count: bulkCountB });
47
- if (overB > 0)
48
- path.push({ type: 'goPrevious', count: overB });
49
- return path;
71
+ if (totalPages !== undefined && primitives.goToLast) {
72
+ const lastPageIndex = totalPages - 1;
73
+ if (targetPageIndex <= lastPageIndex) {
74
+ // Evaluate wrap-around path
75
+ const backwardPath = planNavigationPath(lastPageIndex, targetPageIndex, primitives);
76
+ if (backwardPath.length > 0 || targetPageIndex === lastPageIndex) {
77
+ const wrapPath = [{ type: 'goToLast', targetIndex: lastPageIndex }, ...backwardPath];
78
+ if (forwardPath.length === 0 || computeCost(wrapPath) < computeCost(forwardPath)) {
79
+ return wrapPath;
80
+ }
81
+ }
82
+ }
50
83
  }
51
- const path = [];
52
- if (bulkCountA > 0)
53
- path.push({ type: 'goNextBulk', count: bulkCountA });
54
- if (remA > 0)
55
- path.push({ type: 'goNext', count: remA });
56
- return path;
84
+ return forwardPath;
57
85
  }
58
86
  // Backward: current → target
59
87
  const stepsBack = currentPageIndex - targetPageIndex;
@@ -178,6 +206,14 @@ async function executeNavigationPath(path, primitives, context, getCurrentPage,
178
206
  setCurrentPage(step.pageIndex);
179
207
  }
180
208
  break;
209
+ case 'goToLast':
210
+ if (primitives.goToLast) {
211
+ const ok = await primitives.goToLast(context);
212
+ if (!ok)
213
+ throw new Error(`goToLast failed`);
214
+ setCurrentPage(step.targetIndex);
215
+ }
216
+ break;
181
217
  case 'goNextBulk':
182
218
  for (let i = 0; i < step.count && primitives.goNextBulk; i++) {
183
219
  const result = await primitives.goNextBulk(context);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rickcedwhat/playwright-smart-table",
3
- "version": "6.10.0",
3
+ "version": "6.11.0",
4
4
  "description": "Smart, column-aware table interactions for Playwright",
5
5
  "author": "Cedrick Catalan",
6
6
  "license": "MIT",
@@ -23,8 +23,9 @@
23
23
  "generate-docs": "node scripts/generate-readme.mjs",
24
24
  "generate-all-api-docs": "node scripts/generate-all-api-docs.mjs",
25
25
  "update-all-api-signatures": "node scripts/update-all-api-signatures.mjs",
26
- "docs:dev": "vitepress dev docs",
27
- "docs:build": "vitepress build docs",
26
+ "docs:dev": "vitepress dev docs --host",
27
+ "docs:build": "node scripts/docs-build-prod.mjs",
28
+ "docs:build:all": "vitepress build docs",
28
29
  "docs:verify-links": "node scripts/verify-vitepress-links.mjs",
29
30
  "embed-version": "node scripts/embed-version.mjs",
30
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",
@@ -42,7 +43,7 @@
42
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\"",
43
44
  "dev:playground": "cd playground && npm run dev",
44
45
  "dev:mui": "cd tests/apps/mui-datagrid && npm run dev",
45
- "prepare": "husky install"
46
+ "prepare": "husky"
46
47
  },
47
48
  "exports": {
48
49
  ".": {
@@ -89,6 +90,8 @@
89
90
  "@vitest/coverage-v8": "^4.1.0",
90
91
  "@vitest/ui": "^4.1.0",
91
92
  "happy-dom": "^20.8.3",
93
+ "@commitlint/cli": "^19.7.1",
94
+ "@commitlint/config-conventional": "^19.7.1",
92
95
  "husky": "^9.1.7",
93
96
  "typescript": "^6.0.2",
94
97
  "vitepress": "^1.6.4",