@rickcedwhat/playwright-smart-table 6.10.0 → 6.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,8 +43,11 @@ const email = await row.locator('td').nth(emailIndex).textContent();
43
43
  const row = table.getRow({ Name: 'John Doe' });
44
44
  const email = await row.getCell('Email').textContent();
45
45
 
46
- // ✅ Auto-pagination across all pages
47
- const allEngineers = await table.findRows({ Department: 'Engineering' });
46
+ // ✅ Pagination-aware when you raise maxPages
47
+ const allEngineers = await table.findRows(
48
+ { Department: 'Engineering' },
49
+ { maxPages: 5 }
50
+ );
48
51
 
49
52
  // ✅ Type-safe
50
53
  type Employee = { Name: string; Email: string; Department: string };
@@ -72,8 +75,8 @@ const row = table.getRow({ Name: 'John Doe' });
72
75
  // Access cells by column name
73
76
  const email = await row.getCell('Email').innerText();
74
77
 
75
- // Search across paginated tables
76
- const allActive = await table.findRows({ Status: 'Active' });
78
+ // Search more than the current page by raising maxPages
79
+ const allActive = await table.findRows({ Status: 'Active' }, { maxPages: 5 });
77
80
  ```
78
81
 
79
82
  ### Iterating Across Pages
@@ -163,9 +166,9 @@ const table = useTable(page.locator('#table'), {
163
166
  - 🎯 **Smart Locators** - Find rows by content, not position
164
167
  - 🧠 **Fuzzy Matching** - Smart suggestions for typos in column names
165
168
  - ⚡ **Smart Initialization** - Handles loading states and dynamic headers automatically
166
- - 📄 **Auto-Pagination** - Search across all pages automatically
169
+ - 📄 **Pagination-aware search** - Scan beyond the current page when `maxPages` is increased
167
170
  - 🔍 **Column-Aware Access** - Access cells by column name
168
- - 🔁 **Iteration Methods** - `forEach`, `map`, `filter`, and `for await...of` across all pages
171
+ - 🔁 **Iteration Methods** - `forEach`, `map`, `filter`, and `for await...of` across the configured page range
169
172
  - 🛠️ **Debug Mode** - Visual debugging with slow motion and logging
170
173
  - 🔌 **[Extensible Strategies](docs/concepts/strategies.md)** - Support any table implementation
171
174
  - 💪 **Type-Safe** - Full TypeScript support
@@ -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.10.1";
@@ -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.10.1";
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;
@@ -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 rowIndex: number;\n stop: () => void;\n};\n\n/** Concurrency modes for row iteration. */\nexport type RowIterationMode = 'parallel' | 'sequential' | 'synchronized';\n\n/** Shared options for forEach, map, and filter. */\nexport type RowIterationOptions = {\n /** Maximum number of pages to iterate. Defaults to config.maxPages. */\n maxPages?: number;\n /**\n * Concurrency strategy for iteration.\n * - 'parallel': Full parallel execution of both navigation and actions.\n * - 'synchronized': Parallel navigation (lock-step) with serial actions.\n * - 'sequential': Strictly serial one-at-a-time execution. No parallel navigation.\n * @default 'parallel' (for map), 'sequential' (for forEach/filter)\n */\n concurrency?: RowIterationMode;\n /**\n * Deduplication strategy. Use when rows may repeat across iterations\n * (e.g. infinite scroll tables). Returns a unique key per row.\n */\n dedupe?: DedupeStrategy;\n /**\n * When true, use goNextBulk (if present) to advance pages during iteration.\n * @default false \u2014 uses goNext for one-page-at-a-time advancement\n */\n useBulkPagination?: boolean;\n};\n\nexport interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number }> {\n /**\n * Represents the current page index of the table's DOM.\n * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.\n */\n currentPageIndex: number;\n\n /**\n * Initializes the table by resolving headers. Must be called before using sync methods.\n * @param options Optional timeout for header resolution (default: 3000ms)\n */\n init(options?: { timeout?: number }): Promise<TableResult>;\n\n /**\n * SYNC: Checks if the table has been initialized.\n * @returns true if init() has been called and completed, false otherwise\n */\n isInitialized(): boolean;\n\n getHeaders: () => Promise<string[]>;\n getHeaderCell: (columnName: string) => Promise<Locator>;\n\n /**\n * Finds a row by filters on the current page only. Returns immediately (sync).\n * Throws error if table is not initialized.\n * @note The returned SmartRow may have `rowIndex` as 0 when the match is not the first row.\n * Use getRowByIndex(index) when you need a known index (e.g. for bringIntoView()).\n */\n getRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean }\n ) => SmartRow;\n\n /**\n * Gets a row by 0-based index on the current page.\n * Throws error if table is not initialized.\n * @param index 0-based row index\n */\n getRowByIndex: (\n index: number\n ) => SmartRow;\n\n /**\n * ASYNC: Searches for a single row across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRow>;\n\n /**\n * ASYNC: Searches for all matching rows across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match (omit or pass {} for all rows)\n * @param options - Search options including exact match and max pages\n */\n findRows: (\n filters?: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRowArray<T>>;\n\n /**\n * Navigates to a specific column using the configured CellNavigationStrategy.\n */\n scrollToColumn: (columnName: string) => Promise<void>;\n\n /**\n * Counts the number of rows currently on the page.\n * Does not paginate.\n */\n countRows: () => Promise<number>;\n\n /**\n * Iterates over rows and extracts the value of a single column.\n * More efficient than map + toJSON for single-column extraction.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;\n\n /**\n * Iterates over rows and extracts the value of a single column as strings.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;\n\n\n /**\n * Resets the table state (clears cache, flags) and invokes the onReset strategy.\n */\n reset: () => Promise<void>;\n\n /**\n * Revalidates the table's structure (headers, columns) without resetting pagination or state.\n * Useful when columns change visibility or order dynamically.\n */\n revalidate: () => Promise<void>;\n\n /**\n * Iterates every row across all pages, calling the callback for side effects.\n * Execution is sequential by default (safe for interactions like clicking/filling).\n * Call `stop()` in the callback to end iteration early.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * await table.forEach(async ({ row, stop }) => {\n * if (await row.getCell('Status').innerText() === 'Done') stop();\n * await row.getCell('Checkbox').click();\n * });\n */\n forEach(\n callback: (ctx: RowIterationContext<T>) => void | Promise<void>,\n options?: RowIterationOptions\n ): Promise<void>;\n\n /**\n * Transforms every row across all pages into a value. Returns a flat array.\n * Execution is parallel within each page by default (safe for reads).\n * Call `stop()` to halt after the current page finishes.\n *\n * > **\u26A0\uFE0F UI Interactions:** `map` defaults to `concurrency: 'parallel'`. If your callback opens popovers,\n * > fills inputs, or otherwise mutates UI state, pass `concurrency: 'sequential'` (or `'synchronized'`\n * > when navigation must stay lock-step) to avoid overlapping interactions.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * // Data extraction \u2014 parallel is safe\n * const emails = await table.map(({ row }) => row.getCell('Email').innerText());\n *\n * @example\n * // UI interactions \u2014 use sequential (or synchronized) concurrency\n * const assignees = await table.map(async ({ row }) => {\n * await row.getCell('Assignee').locator('button').click();\n * const name = await page.locator('.popover .name').innerText();\n * await page.keyboard.press('Escape');\n * return name;\n * }, { concurrency: 'sequential' });\n */\n map<R>(\n callback: (ctx: RowIterationContext<T>) => R | Promise<R>,\n options?: RowIterationOptions\n ): Promise<R[]>;\n\n /**\n * Filters rows across all pages by an async predicate. Returns a SmartRowArray.\n * Rows are returned as-is \u2014 call `bringIntoView()` on each if needed.\n * Execution is sequential by default.\n *\n * @param predicate - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * const active = await table.filter(async ({ row }) =>\n * await row.getCell('Status').innerText() === 'Active'\n * );\n */\n filter(\n predicate: (ctx: RowIterationContext<T>) => boolean | Promise<boolean>,\n options?: RowIterationOptions\n ): Promise<SmartRowArray<T>>;\n\n /**\n * Provides access to sorting actions and assertions.\n */\n sorting: {\n /**\n * Applies the configured sorting strategy to the specified column.\n * @param columnName The name of the column to sort.\n * @param direction The direction to sort ('asc' or 'desc').\n */\n apply(columnName: string, direction: 'asc' | 'desc'): Promise<void>;\n /**\n * Gets the current sort state of a column using the configured sorting strategy.\n * @param columnName The name of the column to check.\n * @returns A promise that resolves to 'asc', 'desc', or 'none'.\n */\n getState(columnName: string): Promise<'asc' | 'desc' | 'none'>;\n };\n\n /**\n * Generate an AI-friendly configuration prompt for debugging.\n * Outputs table HTML and TypeScript definitions to help AI assistants generate config.\n * Automatically throws an Error containing the prompt.\n */\n generateConfig: () => Promise<void>;\n\n /**\n * @deprecated Use `generateConfig()` instead. Will be removed in v7.0.0.\n */\n generateConfigPrompt: () => Promise<void>;\n}\n";
@@ -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;
@@ -617,6 +655,26 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
617
655
  */
618
656
  scrollToColumn: (columnName: string) => Promise<void>;
619
657
 
658
+ /**
659
+ * Counts the number of rows currently on the page.
660
+ * Does not paginate.
661
+ */
662
+ countRows: () => Promise<number>;
663
+
664
+ /**
665
+ * Iterates over rows and extracts the value of a single column.
666
+ * More efficient than map + toJSON for single-column extraction.
667
+ * @param columnName - The name of the column to extract
668
+ * @param options - Iteration options
669
+ */
670
+ mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;
671
+
672
+ /**
673
+ * Iterates over rows and extracts the value of a single column as strings.
674
+ * @param columnName - The name of the column to extract
675
+ * @param options - Iteration options
676
+ */
677
+ getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;
620
678
 
621
679
 
622
680
  /**
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>;
@@ -569,6 +602,24 @@ export interface TableResult<T = any> extends AsyncIterable<{
569
602
  * Navigates to a specific column using the configured CellNavigationStrategy.
570
603
  */
571
604
  scrollToColumn: (columnName: string) => Promise<void>;
605
+ /**
606
+ * Counts the number of rows currently on the page.
607
+ * Does not paginate.
608
+ */
609
+ countRows: () => Promise<number>;
610
+ /**
611
+ * Iterates over rows and extracts the value of a single column.
612
+ * More efficient than map + toJSON for single-column extraction.
613
+ * @param columnName - The name of the column to extract
614
+ * @param options - Iteration options
615
+ */
616
+ mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;
617
+ /**
618
+ * Iterates over rows and extracts the value of a single column as strings.
619
+ * @param columnName - The name of the column to extract
620
+ * @param options - Iteration options
621
+ */
622
+ getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;
572
623
  /**
573
624
  * Resets the table state (clears cache, flags) and invokes the onReset strategy.
574
625
  */
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...");
@@ -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.10.1",
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
  ".": {