@rickcedwhat/playwright-smart-table 6.12.0 → 6.13.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
@@ -45,6 +45,7 @@ await table.forEach(async ({ row }) => {
45
45
  npm install @rickcedwhat/playwright-smart-table
46
46
  ```
47
47
 
48
+
48
49
  ## Quick Start
49
50
 
50
51
  ```typescript
@@ -14,7 +14,6 @@ export declare class RowFinder<T = any> {
14
14
  constructor(rootLocator: Locator, config: FinalTableConfig, resolve: (item: Selector, parent: Locator | Page) => Locator, filterEngine: FilterEngine, tableMapper: TableMapper, makeSmartRow: (loc: Locator, map: Map<string, number>, index: number | undefined, tablePageIndex?: number) => SmartRow<T>, tableState?: {
15
15
  currentPageIndex: number;
16
16
  });
17
- private log;
18
17
  findRow(filters: Record<string, FilterValue>, options?: {
19
18
  exact?: boolean;
20
19
  maxPages?: number;
@@ -16,9 +16,6 @@ class RowFinder {
16
16
  this.tableState = tableState;
17
17
  this.resolve = resolve;
18
18
  }
19
- log(msg) {
20
- (0, debugUtils_1.logDebug)(this.config, 'verbose', msg);
21
- }
22
19
  async findRow(filters, options = {}) {
23
20
  (0, debugUtils_1.logDebug)(this.config, 'info', 'Searching for row', filters);
24
21
  await this.tableMapper.getMap();
@@ -45,7 +42,7 @@ class RowFinder {
45
42
  const allRows = [];
46
43
  const effectiveMaxPages = (_b = (_a = options === null || options === void 0 ? void 0 : options.maxPages) !== null && _a !== void 0 ? _a : this.config.maxPages) !== null && _b !== void 0 ? _b : Infinity;
47
44
  let pagesScanned = 1;
48
- this.log(`findRows: starting (maxPages=${effectiveMaxPages}, filters=${JSON.stringify(filtersRecord)})`);
45
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `findRows: starting (maxPages=${effectiveMaxPages}, filters=${JSON.stringify(filtersRecord)})`);
49
46
  const tracker = new elementTracker_1.ElementTracker('findRows');
50
47
  try {
51
48
  const collectMatches = async () => {
@@ -63,13 +60,13 @@ class RowFinder {
63
60
  for (const idx of newIndices) {
64
61
  const smartRow = this.makeSmartRow(currentRows[idx], map, allRows.length, this.tableState.currentPageIndex);
65
62
  if (isRowLoading && await isRowLoading(smartRow)) {
66
- this.log(`findRows: page ${this.tableState.currentPageIndex} — row skipped (isRowLoading=true)`);
63
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `findRows: page ${this.tableState.currentPageIndex} — row skipped (isRowLoading=true)`);
67
64
  continue;
68
65
  }
69
66
  allRows.push(smartRow);
70
67
  added++;
71
68
  }
72
- this.log(`findRows: page ${this.tableState.currentPageIndex} — ${added} new match(es) (total: ${allRows.length})`);
69
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `findRows: page ${this.tableState.currentPageIndex} — ${added} new match(es) (total: ${allRows.length})`);
73
70
  };
74
71
  // Scan first page
75
72
  await collectMatches();
@@ -90,25 +87,26 @@ class RowFinder {
90
87
  paginationResult = await this.config.strategies.pagination.goNext(context);
91
88
  }
92
89
  else {
93
- this.log(`findRows: no pagination primitive — stopping`);
90
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `findRows: no pagination primitive — stopping`);
94
91
  break;
95
92
  }
96
93
  const didPaginate = (0, validation_1.validatePaginationResult)(paginationResult, 'Pagination Strategy');
97
94
  if (!didPaginate) {
98
- this.log(`findRows: pagination returned false — end of data`);
95
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `findRows: pagination returned false — end of data`);
99
96
  break;
100
97
  }
101
98
  const pagesJumped = typeof paginationResult === 'number' ? paginationResult : 1;
102
99
  this.tableState.currentPageIndex += pagesJumped;
103
100
  pagesScanned += pagesJumped;
104
- this.log(`findRows: advanced ${pagesJumped} page(s), now at page ${this.tableState.currentPageIndex}`);
101
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `findRows: advanced ${pagesJumped} page(s), now at page ${this.tableState.currentPageIndex}`);
102
+ await (0, debugUtils_1.debugDelay)(this.config, 'pagination');
105
103
  await collectMatches();
106
104
  }
107
105
  }
108
106
  finally {
109
107
  await tracker.cleanup(this.rootLocator.page());
110
108
  }
111
- this.log(`findRows: done — ${allRows.length} row(s) collected across ${pagesScanned} page(s)`);
109
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `findRows: done — ${allRows.length} row(s) collected across ${pagesScanned} page(s)`);
112
110
  return (0, smartRowArray_1.createSmartRowArray)(allRows);
113
111
  }
114
112
  async findRowLocator(filters, options = {}) {
@@ -116,7 +114,7 @@ class RowFinder {
116
114
  const map = await this.tableMapper.getMap();
117
115
  const effectiveMaxPages = (_a = options.maxPages) !== null && _a !== void 0 ? _a : this.config.maxPages;
118
116
  let pagesScanned = 1;
119
- this.log(`Looking for row: ${JSON.stringify(filters)} (MaxPages: ${effectiveMaxPages})`);
117
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `Looking for row: ${JSON.stringify(filters)} (MaxPages: ${effectiveMaxPages})`);
120
118
  while (true) {
121
119
  // Check Loading
122
120
  if ((_b = this.config.strategies.loading) === null || _b === void 0 ? void 0 : _b.isTableLoading) {
@@ -127,7 +125,7 @@ class RowFinder {
127
125
  resolve: this.resolve
128
126
  });
129
127
  if (isLoading) {
130
- this.log('Table is loading... waiting');
128
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', 'Table is loading... waiting');
131
129
  await this.rootLocator.page().waitForTimeout(200);
132
130
  continue;
133
131
  }
@@ -135,7 +133,7 @@ class RowFinder {
135
133
  const allRows = this.resolve(this.config.rowSelector, this.rootLocator);
136
134
  const matchedRows = this.filterEngine.applyFilters(allRows, filters, map, options.exact || false, this.rootLocator.page(), this.rootLocator);
137
135
  const count = await matchedRows.count();
138
- this.log(`Page ${this.tableState.currentPageIndex}: Found ${count} matches.`);
136
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `Page ${this.tableState.currentPageIndex}: Found ${count} matches.`);
139
137
  if (count > 1) {
140
138
  const sampleData = [];
141
139
  try {
@@ -154,7 +152,7 @@ class RowFinder {
154
152
  if (count === 1)
155
153
  return matchedRows.first();
156
154
  if (pagesScanned < effectiveMaxPages) {
157
- this.log(`Page ${this.tableState.currentPageIndex}: Not found. Attempting pagination...`);
155
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `Page ${this.tableState.currentPageIndex}: Not found. Attempting pagination...`);
158
156
  const context = {
159
157
  root: this.rootLocator,
160
158
  config: this.config,
@@ -171,7 +169,7 @@ class RowFinder {
171
169
  paginationResult = await pagination.goNext(context);
172
170
  }
173
171
  else {
174
- this.log(`Page ${this.tableState.currentPageIndex}: Pagination failed (no goNext or goNextBulk primitive).`);
172
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `Page ${this.tableState.currentPageIndex}: Pagination failed (no goNext or goNextBulk primitive).`);
175
173
  return null;
176
174
  }
177
175
  const didLoadMore = (0, validation_1.validatePaginationResult)(paginationResult, 'Pagination Strategy');
@@ -179,10 +177,12 @@ class RowFinder {
179
177
  const pagesJumped = typeof paginationResult === 'number' ? paginationResult : 1;
180
178
  this.tableState.currentPageIndex += pagesJumped;
181
179
  pagesScanned += pagesJumped;
180
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `findRowLocator: advanced ${pagesJumped} page(s), now at page ${this.tableState.currentPageIndex}`);
181
+ await (0, debugUtils_1.debugDelay)(this.config, 'pagination');
182
182
  continue;
183
183
  }
184
184
  else {
185
- this.log(`Page ${this.tableState.currentPageIndex}: Pagination failed (end of data).`);
185
+ (0, debugUtils_1.logDebug)(this.config, 'verbose', `Page ${this.tableState.currentPageIndex}: Pagination failed (end of data).`);
186
186
  }
187
187
  }
188
188
  return null;
@@ -11,6 +11,7 @@ export interface TableIterationEnv<T = any> {
11
11
  createSmartRowArray: (rows: SmartRow<T>[]) => SmartRowArray<T>;
12
12
  config: FinalTableConfig<T>;
13
13
  getPage: () => Page;
14
+ getCurrentPageIndex: () => number;
14
15
  }
15
16
  /** Delegates to {@link runMap}; void results are discarded. */
16
17
  export declare function runForEach<T>(env: TableIterationEnv<T>, callback: (ctx: RowIterationContext<T>) => void | Promise<void>, options?: RowIterationOptions): Promise<void>;
@@ -27,7 +27,7 @@ async function runMap(env, callback, options = {}, label = 'map') {
27
27
  const dedupeKeys = dedupeStrategy ? new Set() : null;
28
28
  const defaultMode = label === 'map' ? 'parallel' : 'sequential';
29
29
  const concurrency = (_d = (_c = options.concurrency) !== null && _c !== void 0 ? _c : env.config.concurrency) !== null && _d !== void 0 ? _d : defaultMode;
30
- const useBarrier = concurrency !== 'sequential';
30
+ const useBarrier = concurrency === 'synchronized';
31
31
  // Mutex must not pair with the navigation barrier: synchronized mode needs every row
32
32
  // to enter barrier.sync concurrently; serializing callbacks here deadlocks (first row waits
33
33
  // for batchSize peers that never reach the barrier).
@@ -67,7 +67,7 @@ async function runMap(env, callback, options = {}, label = 'map') {
67
67
  log(env.config, `${label}: scanning page ${pagesScanned} — ${batchSize} new row(s)`);
68
68
  const barrier = useBarrier ? new navigationBarrier_1.NavigationBarrier(batchSize) : undefined;
69
69
  const actionMutex = useMutex ? new mutex_1.Mutex() : null;
70
- const smartRows = newIndices.map((idx, i) => env.makeSmartRow(pageRows[idx], map, rowIndex + i, pagesScanned - 1, barrier));
70
+ const smartRows = newIndices.map((idx, i) => env.makeSmartRow(pageRows[idx], map, rowIndex + i, env.getCurrentPageIndex(), barrier));
71
71
  const processRow = async (row) => {
72
72
  try {
73
73
  if (stopped && row.rowIndex > stoppedIndex) {
@@ -86,7 +86,7 @@ async function runMap(env, callback, options = {}, label = 'map') {
86
86
  if (stopped && row.rowIndex > stoppedIndex)
87
87
  return SKIP;
88
88
  log(env.config, `${label}: processing row ${row.rowIndex}`);
89
- return await callback({ row, index: row.rowIndex, rowIndex: row.rowIndex, stop: () => stop(row.rowIndex) });
89
+ return await callback({ row, index: row.rowIndex, rowIndex: row.rowIndex, pageIndex: env.getCurrentPageIndex(), stop: () => stop(row.rowIndex) });
90
90
  };
91
91
  if (actionMutex) {
92
92
  return await actionMutex.run(runCallback);
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { PLAYWRIGHT_SMART_TABLE_VERSION } from './packageVersion';
2
2
  export { useTable } from './useTable';
3
- export type { TableConfig, TableResult, SmartRow, Selector, FilterValue, PaginationPrimitives, SortingStrategy, FillOptions, RowIterationContext, RowIterationOptions, TableContext, StrategyContext, BeforeCellReadFn, GetCellLocatorFn, GetActiveCellFn, DebugConfig, } from './types';
3
+ export type { TableConfig, TableResult, SmartRow, SmartCell, Selector, FilterValue, PaginationPrimitives, SortingStrategy, FillOptions, RowIterationContext, RowIterationOptions, TableContext, StrategyContext, BeforeCellReadFn, GetCellLocatorFn, GetActiveCellFn, DebugConfig, } from './types';
4
4
  export { Strategies } from './strategies';
5
5
  export * as presets from './presets';
6
6
  /** @deprecated Use `presets` instead. Plugins will be removed in v7.0.0. */
@@ -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.12.0";
6
+ export declare const PLAYWRIGHT_SMART_TABLE_VERSION: "6.13.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.12.0";
9
+ exports.PLAYWRIGHT_SMART_TABLE_VERSION = "6.13.0";
@@ -1,4 +1,7 @@
1
1
  import { FillStrategy, TableConfig } from '../../types';
2
+ export { createGlideViewport } from './viewport';
3
+ export type { GlideViewportOptions } from './viewport';
4
+ import { GlideViewportOptions } from './viewport';
2
5
  /** Strategies only for Glide Data Grid. Includes fillSimple; use when you want to supply your own selectors or override fill. */
3
6
  export declare const GlideStrategies: {
4
7
  fillSimple: FillStrategy;
@@ -9,15 +12,7 @@ export declare const GlideStrategies: {
9
12
  selector?: string;
10
13
  scrollAmount?: number;
11
14
  }) => Promise<string[]>;
12
- navigation: {
13
- goUp: (context: import("../..").StrategyContext) => Promise<void>;
14
- goDown: (context: import("../..").StrategyContext) => Promise<void>;
15
- goLeft: (context: import("../..").StrategyContext) => Promise<void>;
16
- goRight: (context: import("../..").StrategyContext) => Promise<void>;
17
- goHome: (context: import("../..").StrategyContext) => Promise<void>;
18
- snapFirstColumnIntoView: (context: import("../..").StrategyContext) => Promise<void>;
19
- seekColumnIndex: (context: import("../..").StrategyContext, columnIndex: number) => Promise<void>;
20
- };
15
+ viewport: import("../../types").ViewportStrategy;
21
16
  loading: {
22
17
  isHeaderLoading: () => Promise<boolean>;
23
18
  };
@@ -28,6 +23,16 @@ export declare const GlideStrategies: {
28
23
  locator: any;
29
24
  } | null>;
30
25
  };
26
+ /** Alias of {@link GlideViewportOptions}. All fields are forwarded to the viewport strategy. */
27
+ export type GlideOptions = GlideViewportOptions;
28
+ /**
29
+ * Factory that returns a configured Glide preset.
30
+ * Use when your grid differs from the defaults:
31
+ * ```ts
32
+ * useTable(loc, { ...createGlide({ attachTimeout: 5000 }), maxPages: 5 })
33
+ * ```
34
+ */
35
+ export declare function createGlide(options?: GlideOptions): Partial<TableConfig>;
31
36
  export declare const Glide: Partial<TableConfig> & {
32
37
  Strategies: typeof GlideStrategies;
33
38
  };
@@ -1,10 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Glide = exports.GlideStrategies = void 0;
4
- const columns_1 = require("./columns");
3
+ exports.Glide = exports.GlideStrategies = exports.createGlideViewport = void 0;
4
+ exports.createGlide = createGlide;
5
5
  const headers_1 = require("./headers");
6
6
  const pagination_1 = require("../../strategies/pagination");
7
7
  const stabilization_1 = require("../../strategies/stabilization");
8
+ var viewport_1 = require("./viewport");
9
+ Object.defineProperty(exports, "createGlideViewport", { enumerable: true, get: function () { return viewport_1.createGlideViewport; } });
10
+ const viewport_2 = require("./viewport");
8
11
  const glideFillStrategy = async ({ row, columnName, value, page }) => {
9
12
  // Canvas-aware click: Glide is a canvas grid. The accessibility 'td' elements
10
13
  // may not trigger internal focus on a simple click. We click the canvas at the cell's location.
@@ -86,15 +89,7 @@ const GlideDefaultStrategies = {
86
89
  fill: glideFillStrategy,
87
90
  pagination: glidePaginationStrategy,
88
91
  header: headers_1.scrollRightHeader,
89
- navigation: {
90
- goUp: columns_1.glideGoUp,
91
- goDown: columns_1.glideGoDown,
92
- goLeft: columns_1.glideGoLeft,
93
- goRight: columns_1.glideGoRight,
94
- goHome: columns_1.glideSnapFirstColumnIntoView,
95
- snapFirstColumnIntoView: columns_1.glideSnapFirstColumnIntoView,
96
- seekColumnIndex: columns_1.glideSeekColumnIndex
97
- },
92
+ viewport: (0, viewport_2.createGlideViewport)(),
98
93
  loading: {
99
94
  isHeaderLoading: async () => false
100
95
  },
@@ -103,10 +98,27 @@ const GlideDefaultStrategies = {
103
98
  };
104
99
  /** Strategies only for Glide Data Grid. Includes fillSimple; use when you want to supply your own selectors or override fill. */
105
100
  exports.GlideStrategies = Object.assign(Object.assign({}, GlideDefaultStrategies), { fillSimple: glideFillSimple });
101
+ /**
102
+ * Factory that returns a configured Glide preset.
103
+ * Use when your grid differs from the defaults:
104
+ * ```ts
105
+ * useTable(loc, { ...createGlide({ attachTimeout: 5000 }), maxPages: 5 })
106
+ * ```
107
+ */
108
+ function createGlide(options = {}) {
109
+ return {
110
+ headerSelector: 'table[role="grid"] thead tr th',
111
+ rowSelector: 'table[role="grid"] tbody tr',
112
+ cellSelector: 'td',
113
+ concurrency: 'sequential',
114
+ strategies: Object.assign(Object.assign({}, GlideDefaultStrategies), { viewport: (0, viewport_2.createGlideViewport)(options) })
115
+ };
116
+ }
106
117
  /**
107
118
  * Full preset for Glide Data Grid (selectors + default strategies only).
108
119
  * Spread: useTable(loc, { ...Plugins.Glide, maxPages: 5 }).
109
120
  * Strategies only (including fillSimple): useTable(loc, { rowSelector: '...', strategies: Plugins.Glide.Strategies }).
121
+ * For a non-64-column grid, use `createGlide({ columnCount })` instead.
110
122
  */
111
123
  const GlidePreset = {
112
124
  headerSelector: 'table[role="grid"] thead tr th',
@@ -0,0 +1,9 @@
1
+ import { ViewportStrategy } from '../../types';
2
+ export interface GlideViewportOptions {
3
+ /**
4
+ * Milliseconds to wait for a cell/row to appear in the DOM after a scroll.
5
+ * Default: 3000.
6
+ */
7
+ attachTimeout?: number;
8
+ }
9
+ export declare const createGlideViewport: (options?: GlideViewportOptions) => ViewportStrategy;
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createGlideViewport = void 0;
4
+ /**
5
+ * Viewport strategy for Glide Data Grid.
6
+ *
7
+ * Glide renders an ARIA accessibility table (`table[role="grid"]`) alongside its
8
+ * canvas. Rows and cells are virtualized: only the currently visible window of
9
+ * `tbody tr` / `td[aria-colindex]` elements exists in the DOM at any moment.
10
+ *
11
+ * This strategy:
12
+ * - `getVisibleColumnRange` — reads `aria-colindex` values from the first visible row
13
+ * - `getVisibleRowRange` — reads `aria-rowindex` values from visible rows (2-based: header = 1)
14
+ * - `scrollToColumn` — sets `.dvn-scroller.scrollLeft` via ratio derived from header count, waits for cell mount
15
+ * - `scrollToRow` — sets `.dvn-scroller.scrollTop` via measured row height, waits for row mount
16
+ */
17
+ const sanitize = (value, fallback) => {
18
+ const n = Number(value);
19
+ return Number.isFinite(n) && n > 0 ? n : fallback;
20
+ };
21
+ const createGlideViewport = (options = {}) => {
22
+ const attachTimeout = sanitize(options.attachTimeout, 3000);
23
+ return {
24
+ getVisibleColumnRange: async ({ page }) => {
25
+ const indices = await page
26
+ .locator('table[role="grid"] tbody tr')
27
+ .first()
28
+ .locator('td[aria-colindex]')
29
+ .evaluateAll((tds) => tds.map((td) => parseInt(td.getAttribute('aria-colindex') || '1') - 1));
30
+ if (!indices.length)
31
+ return { first: 0, last: 0 };
32
+ return { first: Math.min(...indices), last: Math.max(...indices) };
33
+ },
34
+ getVisibleRowRange: async ({ page }) => {
35
+ // aria-rowindex is 1-based; header row = 1, so data row 0 → aria-rowindex="2"
36
+ const indices = await page
37
+ .locator('table[role="grid"] tbody tr[aria-rowindex]')
38
+ .evaluateAll((trs) => trs.map((tr) => parseInt(tr.getAttribute('aria-rowindex') || '2') - 2));
39
+ if (!indices.length)
40
+ return { first: 0, last: 0 };
41
+ return { first: Math.min(...indices), last: Math.max(...indices) };
42
+ },
43
+ scrollToColumn: async (context, colIndex) => {
44
+ var _a, _b;
45
+ const { page } = context;
46
+ const scroller = page.locator('.dvn-scroller').first();
47
+ // Derive total column count from the initialized header map (available post-init).
48
+ // Falls back to a ratio seek only by position if headers are unavailable.
49
+ const headers = await ((_a = context.getHeaders) === null || _a === void 0 ? void 0 : _a.call(context));
50
+ const totalColumns = (_b = headers === null || headers === void 0 ? void 0 : headers.length) !== null && _b !== void 0 ? _b : 0;
51
+ if (totalColumns > 0) {
52
+ await scroller.evaluate((el, { idx, count }) => {
53
+ const max = Math.max(0, el.scrollWidth - el.clientWidth);
54
+ const ratio = Math.min(1, Math.max(0, (idx + 0.5) / count));
55
+ el.scrollLeft = Math.floor(ratio * max);
56
+ }, { idx: colIndex, count: totalColumns });
57
+ }
58
+ const target = page
59
+ .locator(`table[role="grid"] tbody tr td[aria-colindex="${colIndex + 1}"]`)
60
+ .first();
61
+ // Wait for the cell to attach. The first probe is short (800ms fast path); after
62
+ // any nudge the probe uses the full remaining budget so Glide has time to re-render.
63
+ // Total ceiling = 800ms + attachTimeout, matching the original two-phase behaviour.
64
+ const deadline = Date.now() + 800 + attachTimeout;
65
+ let nudged = false;
66
+ while (true) {
67
+ const remaining = deadline - Date.now();
68
+ if (remaining <= 0)
69
+ throw Object.assign(new Error(`Timed out after ${attachTimeout}ms waiting for aria-colindex="${colIndex + 1}" to attach`), { name: 'TimeoutError' });
70
+ try {
71
+ await target.waitFor({ state: 'attached', timeout: nudged ? remaining : Math.min(800, remaining) });
72
+ break;
73
+ }
74
+ catch (err) {
75
+ if (!(err instanceof Error) || err.name !== 'TimeoutError')
76
+ throw err;
77
+ await scroller.evaluate((el) => {
78
+ el.scrollLeft = Math.min(el.scrollLeft + el.clientWidth, el.scrollWidth);
79
+ });
80
+ nudged = true;
81
+ }
82
+ }
83
+ },
84
+ scrollToRow: async ({ page }, rowIndex) => {
85
+ const scroller = page.locator('.dvn-scroller').first();
86
+ // aria-rowindex is 2-based for data rows (header = 1)
87
+ const ariaRowIndex = rowIndex + 2;
88
+ const rowSel = `table[role="grid"] tbody tr[aria-rowindex="${ariaRowIndex}"]`;
89
+ // If the row is already mounted, scroll it into view directly.
90
+ const isAttached = await page.locator(rowSel).count() > 0;
91
+ if (isAttached) {
92
+ await page.locator(rowSel).first().scrollIntoViewIfNeeded();
93
+ }
94
+ else {
95
+ // Measure actual row height from the DOM; fall back to Glide's default (34px).
96
+ const rowHeight = await page
97
+ .locator('table[role="grid"] tbody tr')
98
+ .first()
99
+ .evaluate((el) => el.getBoundingClientRect().height)
100
+ .catch(() => 34);
101
+ const height = rowHeight > 0 ? rowHeight : 34;
102
+ await scroller.evaluate((el, { idx, height: h }) => {
103
+ const targetTop = idx * h;
104
+ el.scrollTop = Math.max(0, targetTop - Math.floor(el.clientHeight / 2));
105
+ }, { idx: rowIndex, height });
106
+ await page
107
+ .locator(rowSel)
108
+ .waitFor({ state: 'attached', timeout: attachTimeout });
109
+ }
110
+ },
111
+ };
112
+ };
113
+ exports.createGlideViewport = createGlideViewport;
@@ -1,3 +1,4 @@
1
1
  export { muiTable, muiDataGrid } from './mui';
2
2
  export { RDG as rdg } from './rdg';
3
- export { Glide as glide } from './glide';
3
+ export { Glide as glide, createGlide, createGlideViewport } from './glide';
4
+ export type { GlideOptions, GlideViewportOptions } from './glide';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.glide = exports.rdg = exports.muiDataGrid = exports.muiTable = void 0;
3
+ exports.createGlideViewport = exports.createGlide = exports.glide = exports.rdg = exports.muiDataGrid = exports.muiTable = void 0;
4
4
  var mui_1 = require("./mui");
5
5
  Object.defineProperty(exports, "muiTable", { enumerable: true, get: function () { return mui_1.muiTable; } });
6
6
  Object.defineProperty(exports, "muiDataGrid", { enumerable: true, get: function () { return mui_1.muiDataGrid; } });
@@ -8,3 +8,5 @@ var rdg_1 = require("./rdg");
8
8
  Object.defineProperty(exports, "rdg", { enumerable: true, get: function () { return rdg_1.RDG; } });
9
9
  var glide_1 = require("./glide");
10
10
  Object.defineProperty(exports, "glide", { enumerable: true, get: function () { return glide_1.Glide; } });
11
+ Object.defineProperty(exports, "createGlide", { enumerable: true, get: function () { return glide_1.createGlide; } });
12
+ Object.defineProperty(exports, "createGlideViewport", { enumerable: true, get: function () { return glide_1.createGlideViewport; } });
package/dist/smartRow.js CHANGED
@@ -11,7 +11,7 @@ const sentinel_1 = require("./utils/sentinel");
11
11
  * Returns the target cell locator after navigation.
12
12
  */
13
13
  const _navigateToCell = async (params) => {
14
- const { config, rootLocator, page, resolve, column, index, rowLocator, rowIndex, barrier } = params;
14
+ const { config, rootLocator, page, resolve, getHeaders, column, index, rowLocator, rowIndex, barrier } = params;
15
15
  const rowLabel = typeof rowIndex === 'number' ? `row ${rowIndex}` : 'row ?';
16
16
  (0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: resolving column "${column}" (colIndex ${index}), ${rowLabel}`);
17
17
  // Get active cell if strategy is available
@@ -29,7 +29,7 @@ const _navigateToCell = async (params) => {
29
29
  return activeCell.locator;
30
30
  }
31
31
  }
32
- const context = { config, root: rootLocator, page, resolve };
32
+ const context = { config, root: rootLocator, page, resolve, getHeaders };
33
33
  // Shared helper: is the target cell currently in the DOM?
34
34
  const targetReached = async () => {
35
35
  if (config.strategies.getActiveCell) {
@@ -51,18 +51,18 @@ const _navigateToCell = async (params) => {
51
51
  // Runs before navigation primitives; falls through to them if cell still not accessible.
52
52
  const viewport = config.strategies.viewport;
53
53
  if (viewport && typeof rowIndex === 'number') {
54
- // Fast path via range oracle: if the user provides getVisibleColumnRange (and memoizes it),
55
- // this check is a near-instant JS lookup — no DOM count() round-trip needed.
54
+ // Fast path via range oracle: re-used below to avoid a second DOM round-trip.
56
55
  // Rows do NOT sync at the barrier here — only scroll boundaries need coordination.
56
+ let knownColRange = null;
57
57
  if (viewport.getVisibleColumnRange) {
58
- const colRange = await viewport.getVisibleColumnRange(context);
59
- if (colRange && index >= colRange.first && index <= colRange.last) {
58
+ knownColRange = await viewport.getVisibleColumnRange(context);
59
+ if (knownColRange && index >= knownColRange.first && index <= knownColRange.last) {
60
60
  const rowRange = viewport.getVisibleRowRange
61
61
  ? await viewport.getVisibleRowRange(context)
62
62
  : null;
63
63
  const rowVisible = !rowRange || (rowIndex >= rowRange.first && rowIndex <= rowRange.last);
64
64
  if (rowVisible && await targetReached()) {
65
- (0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: col ${index} in visible range [${colRange.first}-${colRange.last}], reading directly`);
65
+ (0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: col ${index} in visible range [${knownColRange.first}-${knownColRange.last}], reading directly`);
66
66
  return getCellLocator();
67
67
  }
68
68
  }
@@ -76,9 +76,10 @@ const _navigateToCell = async (params) => {
76
76
  // Column is out of view. Scroll to bring it in.
77
77
  // In synchronized mode, the last row to arrive triggers the scroll once for all rows.
78
78
  const scrollIntoViewport = async () => {
79
- const colRange = viewport.getVisibleColumnRange
79
+ // Reuse the range fetched during the fast-path check; re-query only if unknown.
80
+ const colRange = knownColRange !== null && knownColRange !== void 0 ? knownColRange : (viewport.getVisibleColumnRange
80
81
  ? await viewport.getVisibleColumnRange(context)
81
- : null;
82
+ : null);
82
83
  const colOutOfView = !colRange || index < colRange.first || index > colRange.last;
83
84
  if (colOutOfView) {
84
85
  (0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: col ${index} out of view, scrolling`);
@@ -92,14 +93,14 @@ const _navigateToCell = async (params) => {
92
93
  if (await targetReached()) {
93
94
  return;
94
95
  }
95
- // 2D scroll hazard guard: scrolling horizontally may have unmounted the target row.
96
- const rowRange = viewport.getVisibleRowRange
97
- ? await viewport.getVisibleRowRange(context)
98
- : null;
99
- const rowOutOfView = rowRange && (rowIndex < rowRange.first || rowIndex > rowRange.last);
100
- if (rowOutOfView) {
101
- (0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: row ${rowIndex} out of view after col scroll, recovering`);
102
- if (viewport.scrollToRow) {
96
+ // 2D scroll hazard: horizontal scroll may evict the target row from the DOM.
97
+ // scrollToRow moves the viewport to one specific row, which would evict every
98
+ // other row in a parallel batch — safe only when there are no peers to evict.
99
+ if ((!barrier || !barrier.isParallel()) && viewport.scrollToRow && viewport.getVisibleRowRange) {
100
+ const rowRange = await viewport.getVisibleRowRange(context);
101
+ const rowOutOfView = rowRange && (rowIndex < rowRange.first || rowIndex > rowRange.last);
102
+ if (rowOutOfView) {
103
+ (0, debugUtils_1.logDebug)(config, 'verbose', `_navigateToCell: row ${rowIndex} out of view after col scroll, recovering`);
103
104
  await viewport.scrollToRow(context, rowIndex);
104
105
  }
105
106
  }
@@ -272,13 +273,15 @@ const _navigateToCell = async (params) => {
272
273
  }
273
274
  const horizontalSteps = Math.abs(cDiff);
274
275
  if (horizontalSteps > 0) {
275
- const settleMs = Math.min(2500, 60 + horizontalSteps * 12);
276
+ const computed = Math.min(2500, 60 + horizontalSteps * 12);
277
+ const settleMs = (Number.isFinite(nav.settleMs) && nav.settleMs >= 0) ? nav.settleMs : computed;
276
278
  await page.waitForTimeout(settleMs);
277
279
  }
278
280
  // Wait for active cell to match target: poll getActiveCell or fallback to fixed delay
279
281
  // This is the "Midas Touch" buffer needed for Glide's async accessibility updates.
280
282
  const pollIntervalMs = 10;
281
- const maxWaitMs = Math.min(6000, 250 + horizontalSteps * 25);
283
+ const computedMax = Math.min(6000, 250 + horizontalSteps * 25);
284
+ const maxWaitMs = (Number.isFinite(nav.maxWaitMs) && nav.maxWaitMs >= 0) ? nav.maxWaitMs : computedMax;
282
285
  const start = Date.now();
283
286
  while (Date.now() - start < maxWaitMs) {
284
287
  if (config.strategies.getActiveCell) {
@@ -363,19 +366,38 @@ const createSmartRow = (rowLocator, map, rowIndex, config, rootLocator, resolve,
363
366
  }
364
367
  const smartCell = baseLocator;
365
368
  smartCell.bringIntoView = async () => {
369
+ const page = rootLocator.page();
366
370
  const navigatedCell = await _navigateToCell({
367
371
  config,
368
372
  rootLocator,
369
- page: rootLocator.page(),
373
+ page,
370
374
  resolve,
375
+ getHeaders: table === null || table === void 0 ? void 0 : table.getHeaders,
371
376
  column: colName,
372
377
  index: idx,
373
378
  rowLocator,
374
379
  rowIndex,
375
380
  barrier: smart._barrier
376
381
  });
377
- if (navigatedCell && navigatedCell._locator) {
378
- smartCell._locator = navigatedCell._locator;
382
+ // Run beforeCellRead hook (same as toJSON does after navigation).
383
+ if (config.strategies.beforeCellRead) {
384
+ const getHeaderCell = (table === null || table === void 0 ? void 0 : table.getHeaderCell)
385
+ ? table.getHeaderCell.bind(table)
386
+ : async (colNameArg) => {
387
+ const i = map.get(colNameArg);
388
+ if (i === undefined)
389
+ throw new Error(`Column "${colNameArg}" not found`);
390
+ return resolve(config.headerSelector, rootLocator).nth(i);
391
+ };
392
+ await config.strategies.beforeCellRead({
393
+ cell: navigatedCell !== null && navigatedCell !== void 0 ? navigatedCell : baseLocator,
394
+ columnName: colName,
395
+ columnIndex: idx,
396
+ row: rowLocator,
397
+ page,
398
+ root: rootLocator,
399
+ getHeaderCell,
400
+ });
379
401
  }
380
402
  };
381
403
  return smartCell;
@@ -424,6 +446,7 @@ const createSmartRow = (rowLocator, map, rowIndex, config, rootLocator, resolve,
424
446
  rootLocator,
425
447
  page,
426
448
  resolve,
449
+ getHeaders: table === null || table === void 0 ? void 0 : table.getHeaders,
427
450
  column: col,
428
451
  index: idx,
429
452
  rowLocator,
@@ -475,6 +498,7 @@ const createSmartRow = (rowLocator, map, rowIndex, config, rootLocator, resolve,
475
498
  rootLocator,
476
499
  page: rootLocator.page(),
477
500
  resolve,
501
+ getHeaders: table === null || table === void 0 ? void 0 : table.getHeaders,
478
502
  column: colName,
479
503
  index: colIdx,
480
504
  rowLocator,
@@ -21,6 +21,16 @@ export interface NavigationPrimitives {
21
21
  * Implementations should leave a small delta for the caller to correct with primitives.
22
22
  */
23
23
  seekColumnIndex?: (context: StrategyContext, columnIndex: number) => Promise<void>;
24
+ /**
25
+ * Override the settle delay (ms) after horizontal goLeft/goRight steps.
26
+ * Defaults to `Math.min(2500, 60 + steps * 12)`. Tune when your grid settles faster or slower.
27
+ */
28
+ settleMs?: number;
29
+ /**
30
+ * Override the maximum poll window (ms) waiting for the active cell to confirm position.
31
+ * Defaults to `Math.min(6000, 250 + steps * 25)`. Tune when accessibility updates lag differently.
32
+ */
33
+ maxWaitMs?: number;
24
34
  }
25
35
  /**
26
36
  * @deprecated Use NavigationPrimitives instead. This will be removed in a future version.
@@ -3,4 +3,4 @@
3
3
  * This file is generated by scripts/embed-types.mjs
4
4
  * It contains the raw text of types.ts to provide context for LLM prompts.
5
5
  */
6
- export declare const TYPE_CONTEXT = "\n/**\n * Flexible selector type - can be a CSS string, function returning a Locator, or Locator itself.\n * @example\n * // String selector\n * rowSelector: 'tbody tr'\n * \n * // Function selector\n * headerSelector: (root) => root.locator('[role=\"columnheader\"]')\n */\nexport type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);\n\n/**\n * Value used to filter rows.\n * - string/number/RegExp: filter by text content of the cell.\n * - function: filter by custom locator logic within the cell.\n * @example\n * // Text filter\n * { Name: 'John' }\n * \n * // Custom locator filter (e.g. checkbox is checked)\n * { Status: (cell) => cell.locator('input:checked') }\n */\nexport type FilterValue = string | RegExp | number | ((cell: Locator) => Locator);\n\n/**\n * Function to get a cell locator given row, column info.\n * Replaces the old cellResolver.\n */\nexport type GetCellLocatorFn = (args: {\n row: Locator;\n /** The root locator passed to useTable(). Useful for re-querying stale row locators. */\n root: Locator;\n columnName: string;\n columnIndex: number;\n rowIndex?: number;\n page: Page;\n config: FinalTableConfig<any>;\n}) => Locator;\n\n/**\n * Hook called before each cell value is read in toJSON (and columnOverrides.read).\n * Use this to scroll off-screen columns into view in horizontally virtualized tables,\n * wait for lazy-rendered content, or perform any pre-read setup.\n *\n * @example\n * // Scroll the column header into view to trigger horizontal virtualization render\n * strategies: {\n * beforeCellRead: async ({ columnName, getHeaderCell }) => {\n * const header = await getHeaderCell(columnName);\n * await header.scrollIntoViewIfNeeded();\n * }\n * }\n */\nexport type BeforeCellReadFn = (args: {\n /** The resolved cell locator */\n cell: Locator;\n columnName: string;\n columnIndex: number;\n row: Locator;\n page: Page;\n root: Locator;\n /** Resolves a column name to its header cell locator */\n getHeaderCell: (columnName: string) => Promise<Locator>;\n}) => Promise<void>;\n\n/**\n * Function to get the currently active/focused cell.\n * Returns null if no cell is active.\n */\nexport type GetActiveCellFn = (args: TableContext) => Promise<{\n rowIndex: number;\n columnIndex: number;\n columnName?: string;\n locator: Locator;\n} | null>;\n\n/**\n * Viewport oracle strategies for virtualized tables.\n *\n * These tell the library *what is currently in the DOM* rather than *how to move*.\n * When present, the cell-reading engine uses them to jump directly to a target\n * row/column instead of stepping blindly with navigation primitives.\n *\n * This is the primary fix for the 2D scroll hazard: scrolling right to bring a\n * column into view can knock rows out of the vertical viewport (and vice versa).\n * With `getVisibleRowRange` the engine detects this and calls `scrollToRow` to\n * restore the row before reading \u2014 eliminating the hazard without polling loops.\n *\n * All members are optional. Supply whichever the underlying grid exposes:\n * - Range oracles alone enable hazard detection with graceful fallback to navigation primitives.\n * - Scroll primitives alone enable direct jumps without range awareness.\n * - Both together give the most reliable, fastest path.\n *\n * @example\n * // MUI DataGrid via apiRef\n * strategies: {\n * viewport: {\n * getVisibleRowRange: async ({ root }) =>\n * root.evaluate(el => {\n * const api = (el as any).__muiDataGrid__;\n * return { first: api.getFirstVisibleRow(), last: api.getLastVisibleRow() };\n * }),\n * scrollToRow: async ({ root }, rowIndex) =>\n * root.evaluate((el, idx) =>\n * (el as any).__muiDataGrid__.scrollToIndexes({ rowIndex: idx }), rowIndex),\n * scrollToColumn: async ({ root }, colIndex) =>\n * root.evaluate((el, idx) =>\n * (el as any).__muiDataGrid__.scrollToIndexes({ colIndex: idx }), colIndex),\n * }\n * }\n *\n * @example\n * // aria-rowindex / aria-colindex DOM fallback (works without internal API access)\n * strategies: {\n * viewport: {\n * getVisibleRowRange: async ({ root }) =>\n * root.evaluate(el => {\n * const rows = [...el.querySelectorAll('[role=\"row\"][aria-rowindex]')];\n * const idxs = rows.map(r => Number(r.getAttribute('aria-rowindex')) - 1);\n * return { first: Math.min(...idxs), last: Math.max(...idxs) };\n * }),\n * }\n * }\n */\nexport interface ViewportStrategy {\n /**\n * Returns the 0-based index range of rows currently rendered in the DOM.\n * Used to detect when a target row has been scrolled out of view and needs recovery.\n */\n getVisibleRowRange?: (context: TableContext) => Promise<{ first: number; last: number }>;\n\n /**\n * Returns the 0-based index range of columns currently rendered in the DOM.\n * Used to detect when a target column is not yet mounted before reading.\n */\n getVisibleColumnRange?: (context: TableContext) => Promise<{ first: number; last: number }>;\n\n /**\n * Scrolls or jumps directly to make a row visible by 0-based index.\n * Replaces blind goDown()/goUp() step loops for grids that expose a scroll API.\n */\n scrollToRow?: (context: TableContext, rowIndex: number) => Promise<void>;\n\n /**\n * Scrolls or jumps directly to make a column visible by 0-based index.\n * Replaces blind goRight()/goLeft() step loops for grids that expose a scroll API.\n */\n scrollToColumn?: (context: TableContext, colIndex: number) => Promise<void>;\n\n /**\n * When true, disables the automatic memoization of getVisibleColumnRange and\n * getVisibleRowRange results. By default the library caches each range value and\n * invalidates it after the corresponding scroll call, eliminating redundant DOM\n * evaluate() round-trips between scrolls.\n */\n disableCache?: boolean;\n}\n\n\n/**\n * SmartCell - A Playwright Locator with table-aware methods for single-cell operations.\n * \n * Extends all standard Locator methods (click, isVisible, etc.).\n */\nexport type SmartCell = Locator & {\n /**\n * Scrolls/paginates to bring this specific cell into view using the configured strategies.\n * Useful when the grid is horizontally virtualized and the column must be scrolled\n * into view before it can be interacted with or read.\n */\n bringIntoView(): Promise<void>;\n};\n\n\n/**\n * SmartRow - A Playwright Locator with table-aware methods.\n * \n * Extends all standard Locator methods (click, isVisible, etc.) with table-specific functionality.\n * \n * @example\n * const row = table.getRow({ Name: 'John Doe' });\n * await row.click(); // Standard Locator method\n * const email = row.getCell('Email'); // Table-aware method\n * const data = await row.toJSON(); // Extract all row data\n * await row.smartFill({ Name: 'Jane', Status: 'Active' }); // Fill form fields\n */\nexport type SmartRow<T = any> = Locator & {\n /** Optional row index (0-based) if known */\n rowIndex?: number;\n\n /** Optional page index this row was found on (0-based) */\n tablePageIndex?: number;\n\n /** Reference to the parent TableResult */\n table: TableResult<T>;\n\n /**\n * Get a cell locator by column name.\n * @param column - Column name (case-sensitive)\n * @returns SmartCell (Locator + bringIntoView)\n * @example\n * const emailCell = row.getCell('Email');\n * await emailCell.bringIntoView();\n * await expect(emailCell).toHaveText('john@example.com');\n */\n getCell(column: string): SmartCell;\n\n /**\n * Extract all cell data as a key-value object.\n * @param options - Optional configuration\n * @param options.columns - Specific columns to extract (extracts all if not specified)\n * @returns Promise resolving to row data\n * @example\n * const data = await row.toJSON();\n * // { Name: 'John', Email: 'john@example.com', ... }\n * \n * const partial = await row.toJSON({ columns: ['Name', 'Email'] });\n * // { Name: 'John', Email: 'john@example.com' }\n */\n toJSON(options?: { columns?: string[] }): Promise<T>;\n\n /**\n * Scrolls/paginates to bring this row into view.\n * Works when row position metadata is known (e.g., from getRowByIndex, findRow,\n * findRows, filter, or async iteration).\n * @throws Error if row position metadata is unknown\n */\n bringIntoView(): Promise<void>;\n\n /**\n * Intelligently fills form fields in the row.\n * Automatically detects input types (text, select, checkbox, contenteditable).\n * \n * @param data - Column-value pairs to fill\n * @param options - Optional configuration\n * @param options.inputMappers - Custom input selectors per column\n * @example\n * // Auto-detection\n * await row.smartFill({ Name: 'John', Status: 'Active', Subscribe: true });\n * \n * // Custom input mappers\n * await row.smartFill(\n * { Name: 'John' },\n * { inputMappers: { Name: (cell) => cell.locator('.custom-input') } }\n * );\n */\n smartFill: (data: Partial<T> | Record<string, any>, options?: FillOptions) => Promise<void>;\n\n /**\n * Returns whether the row exists in the DOM (i.e. is not a sentinel row).\n */\n wasFound(): boolean;\n};\n\nexport type StrategyContext = TableContext & {\n rowLocator?: Locator;\n rowIndex?: number;\n};\n\n/**\n * Defines the contract for a sorting strategy.\n */\nexport interface SortingStrategy {\n /**\n * Performs the sort action on a column.\n */\n doSort(options: {\n columnName: string;\n direction: 'asc' | 'desc';\n context: StrategyContext;\n }): Promise<void>;\n\n /**\n * Retrieves the current sort state of a column.\n */\n getSortState(options: {\n columnName: string;\n context: StrategyContext;\n }): Promise<'asc' | 'desc' | 'none'>;\n}\n\n/**\n * Debug configuration for development and troubleshooting\n */\nexport type DebugConfig = {\n /**\n * Slow down operations for debugging\n * - number: Apply same delay to all operations (ms)\n * - object: Granular delays per operation type\n */\n slow?: number | {\n pagination?: number;\n getCell?: number;\n findRow?: number;\n default?: number;\n };\n /**\n * Log level for debug output\n * - 'verbose': All logs (verbose, info, error)\n * - 'info': Info and error logs only\n * - 'error': Error logs only\n * - 'none': No logs\n */\n logLevel?: 'verbose' | 'info' | 'error' | 'none';\n};\n\nexport interface TableContext<T = any> {\n root: Locator;\n config: FinalTableConfig<T>;\n page: Page;\n resolve: (selector: Selector, parent: Locator | Page) => Locator;\n /** Resolves a column name to its header cell locator. Available after table is initialized. */\n getHeaderCell?: (columnName: string) => Promise<Locator>;\n /** Returns all column names in order. Available after table is initialized. */\n getHeaders?: () => Promise<string[]>;\n /** Scrolls the table horizontally to bring the given column's header into view. */\n scrollToColumn?: (columnName: string) => Promise<void>;\n}\n\nexport interface PaginationPrimitives {\n /** Classic \"Next Page\" or \"Scroll Down\" */\n goNext?: (context: TableContext) => Promise<boolean>;\n\n /** Classic \"Previous Page\" or \"Scroll Up\" */\n goPrevious?: (context: TableContext) => Promise<boolean>;\n\n /** Bulk skip forward multiple pages at once. Returns number of pages skipped. */\n goNextBulk?: (context: TableContext) => Promise<boolean | number>;\n\n /** Bulk skip backward multiple pages at once. Returns number of pages skipped. */\n goPreviousBulk?: (context: TableContext) => Promise<boolean | number>;\n\n /** Jump to first page / scroll to top */\n goToFirst?: (context: TableContext) => Promise<boolean>;\n\n /** Jump to last page / scroll to bottom */\n goToLast?: (context: TableContext) => Promise<boolean>;\n\n /**\n * Fetch the total number of pages currently available.\n * Can be used to optimize pagination paths (e.g. jumping to last page and going backwards).\n */\n getTotalPages?: (context: TableContext) => Promise<number | null>;\n\n /**\n * Jump to specific page index (0-indexed).\n * Can be full-range (e.g. page number input: any page works) or windowed (e.g. only visible links 6\u201314).\n * Return false when the page is not reachable in the current UI; the library will step toward the target (goNextBulk/goNext or goPreviousBulk/goPrevious) and retry goToPage until it succeeds.\n */\n goToPage?: (pageIndex: number, context: TableContext) => Promise<boolean>;\n\n /** How many pages one goNextBulk() advances. Used by navigation path planner for optimal bringIntoView. */\n nextBulkPages?: number;\n\n /** How many pages one goPreviousBulk() goes back. Used by navigation path planner for optimal bringIntoView. */\n previousBulkPages?: number;\n\n /**\n * Called once during init() to sync the library's page counter with the actual DOM state.\n * Use when a table may open on a page other than the first (e.g. a deep-linked URL that\n * lands on page 5). Returns a 0-indexed page number.\n * @example\n * detectCurrentPage: async (root) => {\n * const text = await root.locator('[aria-current=\"page\"]').textContent();\n * return parseInt(text ?? '1') - 1;\n * }\n */\n detectCurrentPage?: (root: import('@playwright/test').Locator) => number | Promise<number>;\n}\n\nexport type PaginationStrategy = PaginationPrimitives;\n\nexport type DedupeStrategy = (row: SmartRow) => string | number | Promise<string | number>;\n\n\n\nexport type FillStrategy = (options: {\n row: SmartRow;\n columnName: string;\n value: any;\n index: number;\n page: Page;\n rootLocator: Locator;\n config: FinalTableConfig<any>;\n table: TableResult; // The parent table instance\n fillOptions?: FillOptions;\n}) => Promise<void>;\n\nexport interface ColumnOverride<TValue = any> {\n /** \n * How to extract the value from the cell.\n * `context` provides access to the parent row, permitting multi-cell logic or bypassing the default cell locator.\n */\n read?: (cell: Locator) => Promise<TValue> | TValue;\n\n /** \n * How to fill the cell with a new value. (Replaces smartFill default logic)\n * Provides the current value (via `read`) if a `write` wants to check state first.\n */\n write?: (params: {\n cell: Locator;\n targetValue: TValue;\n currentValue?: TValue;\n row: SmartRow<any>;\n }) => Promise<void>;\n}\n\nexport type { HeaderStrategy } from './strategies/headers';\n\n/**\n * Strategy to resolve column names (string or regex) to their index.\n */\nexport type { ColumnResolutionStrategy } from './strategies/resolution';\n\n/**\n * Strategy to filter rows based on criteria. Applied when using getRow/findRow/findRows with filters.\n * The default engine handles string, RegExp, number, and function (cell) => Locator filters.\n */\nexport interface FilterStrategy {\n apply(options: {\n rows: Locator;\n filter: { column: string, value: FilterValue };\n colIndex: number;\n tableContext: TableContext;\n }): Locator;\n}\n\n/**\n * Strategy to check if the table or rows are loading. Used after pagination/sort to wait for content.\n * E.g. isHeaderLoading for init stability; isTableLoading after sort/pagination.\n */\nexport interface LoadingStrategy {\n isTableLoading?: (context: TableContext) => Promise<boolean>;\n isRowLoading?: (row: SmartRow) => Promise<boolean>;\n isHeaderLoading?: (context: TableContext) => Promise<boolean>;\n}\n\n/**\n * Organized container for all table interaction strategies.\n */\nexport interface TableStrategies {\n /** Strategy for discovering/scanning headers */\n header?: HeaderStrategy;\n /** Primitive navigation functions (goUp, goDown, goLeft, goRight, goHome) */\n navigation?: NavigationPrimitives;\n\n /** Strategy for filling form inputs */\n fill?: FillStrategy;\n /** Strategy for paginating through data */\n pagination?: PaginationStrategy;\n /** Strategy for sorting columns */\n sorting?: SortingStrategy;\n /** Strategy for deduplicating rows during iteration/scrolling */\n dedupe?: DedupeStrategy;\n /** Function to get a cell locator */\n getCellLocator?: GetCellLocatorFn;\n /** Function to get the currently active/focused cell */\n getActiveCell?: GetActiveCellFn;\n /**\n * Strategy for filtering rows. If present, FilterEngine will delegate filter application\n * to this pluggable strategy.\n */\n filter?: FilterStrategy;\n /**\n * Hook called before each cell value is read in toJSON and columnOverrides.read.\n * Fires for both the default innerText extraction and custom read mappers.\n * Useful for scrolling off-screen columns into view in horizontally virtualized tables.\n */\n beforeCellRead?: BeforeCellReadFn;\n /**\n * Strategy for detecting loading states. Use this for table-, row-, and header-level readiness.\n * E.g. after sort/pagination, the engine uses loading.isTableLoading when present.\n */\n loading?: LoadingStrategy;\n\n /**\n * Viewport oracle strategies for 2D virtualized tables (e.g. MUI DataGrid, AG Grid,\n * Braintrust-style grids where both rows and columns are virtualized simultaneously).\n *\n * When present, the cell-reading engine uses these to jump directly to the target\n * row/column and to detect the 2D scroll hazard (scrolling to reveal a column can\n * knock rows out of the vertical viewport, and vice versa).\n *\n * Completely optional and additive \u2014 existing `navigation` primitives remain the fallback.\n */\n viewport?: ViewportStrategy;\n}\n\n\nexport interface TableConfig<T = any> {\n /** Selector for the table headers */\n headerSelector?: string | ((root: Locator) => Locator);\n /** Selector for the table rows */\n rowSelector?: string;\n /** Selector for the cells within a row */\n cellSelector?: string | ((row: Locator) => Locator);\n /** Number of pages to scan for verification */\n maxPages?: number;\n /**\n * Default concurrency strategy for iteration methods.\n * Can be overridden by the options passed to forEach, map, or filter.\n */\n concurrency?: RowIterationMode;\n /** Hook to rename columns dynamically */\n headerTransformer?: (args: { text: string, index: number, locator: Locator, seenHeaders: Set<string> }) => string | Promise<string>;\n /** Automatically scroll to table on init */\n autoScroll?: boolean;\n /** Debug options for development and troubleshooting */\n debug?: DebugConfig;\n /** Reset hook */\n onReset?: (context: TableContext) => Promise<void>;\n /** All interaction strategies */\n strategies?: TableStrategies;\n\n /**\n * Unified interface for reading and writing data to specific columns.\n * Overrides both default extraction (toJSON) and filling (smartFill) logic.\n */\n columnOverrides?: Partial<Record<keyof T, ColumnOverride<T[keyof T]>>>;\n}\n\nexport interface FinalTableConfig<T = any> extends TableConfig<T> {\n headerSelector: string | ((root: Locator) => Locator);\n rowSelector: string;\n cellSelector: string | ((row: Locator) => Locator);\n maxPages: number;\n autoScroll: boolean;\n concurrency?: RowIterationMode;\n debug?: TableConfig['debug'];\n headerTransformer: (args: { text: string, index: number, locator: Locator, seenHeaders: Set<string> }) => string | Promise<string>;\n onReset: (context: TableContext) => Promise<void>;\n strategies: TableStrategies;\n}\n\n\nexport interface FillOptions {\n /**\n * Custom input mappers for specific columns.\n * Maps column names to functions that return the input locator for that cell.\n */\n inputMappers?: Record<string, (cell: Locator) => Locator>;\n}\n\n\n\n/** Callback context passed to forEach, map, and filter. */\nexport type RowIterationContext<T = any> = {\n row: SmartRow<T>;\n /** 0-based iteration counter \u2014 the order this row was visited, not its DOM position or grid identity. @deprecated Use `index` instead. `rowIndex` will be removed in v7.0.0. */\n rowIndex: number;\n /** 0-based iteration counter \u2014 the order this row was visited, not its DOM position or grid identity. */\n index: number;\n stop: () => void;\n};\n\n/** Concurrency modes for row iteration. */\nexport type RowIterationMode = 'parallel' | 'sequential' | 'synchronized';\n\n/** Shared options for forEach, map, and filter. */\nexport type RowIterationOptions = {\n /** Maximum number of pages to iterate. Defaults to config.maxPages. */\n maxPages?: number;\n /**\n * Concurrency strategy for iteration.\n * - 'parallel': Full parallel execution of both navigation and actions.\n * - 'synchronized': Parallel navigation (lock-step) with serial actions.\n * - 'sequential': Strictly serial one-at-a-time execution. No parallel navigation.\n * @default 'parallel' (for map), 'sequential' (for forEach/filter)\n */\n concurrency?: RowIterationMode;\n /**\n * Deduplication strategy. Use when rows may repeat across iterations\n * (e.g. infinite scroll tables). Returns a unique key per row.\n */\n dedupe?: DedupeStrategy;\n /**\n * When true, use goNextBulk (if present) to advance pages during iteration.\n * @default false \u2014 uses goNext for one-page-at-a-time advancement\n */\n useBulkPagination?: boolean;\n};\n\nexport interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number; index: number }> {\n /**\n * Represents the current page index of the table's DOM.\n * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.\n */\n currentPageIndex: number;\n\n /**\n * Initializes the table by resolving headers. Must be called before using sync methods.\n * @param options Optional timeout for header resolution (default: 3000ms)\n */\n init(options?: { timeout?: number }): Promise<TableResult>;\n\n /**\n * SYNC: Checks if the table has been initialized.\n * @returns true if init() has been called and completed, false otherwise\n */\n isInitialized(): boolean;\n\n getHeaders: () => Promise<string[]>;\n getHeaderCell: (columnName: string) => Promise<Locator>;\n\n /**\n * Finds a row by filters on the current page only. Returns immediately (sync).\n * Throws error if table is not initialized.\n * @note The returned SmartRow may have `rowIndex` as 0 when the match is not the first row.\n * Use getRowByIndex(index) when you need a known index (e.g. for bringIntoView()).\n */\n getRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean }\n ) => SmartRow;\n\n /**\n * Gets a row by 0-based index on the current page.\n * Throws error if table is not initialized.\n * @param index 0-based row index\n */\n getRowByIndex: (\n index: number\n ) => SmartRow;\n\n /**\n * ASYNC: Searches for a single row across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRow>;\n\n /**\n * ASYNC: Searches for all matching rows across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match (omit or pass {} for all rows)\n * @param options - Search options including exact match and max pages\n */\n findRows: (\n filters?: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number, useBulkPagination?: boolean }\n ) => Promise<SmartRowArray<T>>;\n\n /**\n * Navigates to a specific column using the configured CellNavigationStrategy.\n */\n scrollToColumn: (columnName: string) => Promise<void>;\n\n /**\n * Counts the number of rows currently on the page.\n * Does not paginate.\n */\n countRows: () => Promise<number>;\n\n /**\n * Iterates over rows and extracts the value of a single column.\n * More efficient than map + toJSON for single-column extraction.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;\n\n /**\n * Iterates over rows and extracts the value of a single column as strings.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;\n\n\n /**\n * Resets the table state (clears cache, flags) and invokes the onReset strategy.\n */\n reset: () => Promise<void>;\n\n /**\n * Revalidates the table's structure (headers, columns) without resetting pagination or state.\n * Useful when columns change visibility or order dynamically.\n */\n revalidate: () => Promise<void>;\n\n /**\n * Iterates every row across all pages, calling the callback for side effects.\n * Execution is sequential by default (safe for interactions like clicking/filling).\n * Call `stop()` in the callback to end iteration early.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * await table.forEach(async ({ row, stop }) => {\n * if (await row.getCell('Status').innerText() === 'Done') stop();\n * await row.getCell('Checkbox').click();\n * });\n */\n forEach(\n callback: (ctx: RowIterationContext<T>) => void | Promise<void>,\n options?: RowIterationOptions\n ): Promise<void>;\n\n /**\n * Transforms every row across all pages into a value. Returns a flat array.\n * Execution is parallel within each page by default (safe for reads).\n * Call `stop()` to halt after the current page finishes.\n *\n * > **\u26A0\uFE0F UI Interactions:** `map` defaults to `concurrency: 'parallel'`. If your callback opens popovers,\n * > fills inputs, or otherwise mutates UI state, pass `concurrency: 'sequential'` (or `'synchronized'`\n * > when navigation must stay lock-step) to avoid overlapping interactions.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * // Data extraction \u2014 parallel is safe\n * const emails = await table.map(({ row }) => row.getCell('Email').innerText());\n *\n * @example\n * // UI interactions \u2014 use sequential (or synchronized) concurrency\n * const assignees = await table.map(async ({ row }) => {\n * await row.getCell('Assignee').locator('button').click();\n * const name = await page.locator('.popover .name').innerText();\n * await page.keyboard.press('Escape');\n * return name;\n * }, { concurrency: 'sequential' });\n */\n map<R>(\n callback: (ctx: RowIterationContext<T>) => R | Promise<R>,\n options?: RowIterationOptions\n ): Promise<R[]>;\n\n /**\n * Filters rows across all pages by an async predicate. Returns a SmartRowArray.\n * Rows are returned as-is \u2014 call `bringIntoView()` on each if needed.\n * Execution is sequential by default.\n *\n * @param predicate - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * const active = await table.filter(async ({ row }) =>\n * await row.getCell('Status').innerText() === 'Active'\n * );\n */\n filter(\n predicate: (ctx: RowIterationContext<T>) => boolean | Promise<boolean>,\n options?: RowIterationOptions\n ): Promise<SmartRowArray<T>>;\n\n /**\n * Provides access to sorting actions and assertions.\n */\n sorting: {\n /**\n * Applies the configured sorting strategy to the specified column.\n * @param columnName The name of the column to sort.\n * @param direction The direction to sort ('asc' or 'desc').\n */\n apply(columnName: string, direction: 'asc' | 'desc'): Promise<void>;\n /**\n * Gets the current sort state of a column using the configured sorting strategy.\n * @param columnName The name of the column to check.\n * @returns A promise that resolves to 'asc', 'desc', or 'none'.\n */\n getState(columnName: string): Promise<'asc' | 'desc' | 'none'>;\n };\n\n /**\n * Generate an AI-friendly configuration prompt for debugging.\n * Outputs table HTML and TypeScript definitions to help AI assistants generate config.\n * Automatically throws an Error containing the prompt.\n */\n generateConfig: () => Promise<void>;\n\n /**\n * @deprecated Use `generateConfig()` instead. Will be removed in v7.0.0.\n */\n generateConfigPrompt: () => Promise<void>;\n}\n";
6
+ export declare const TYPE_CONTEXT = "\n/**\n * Flexible selector type - can be a CSS string, function returning a Locator, or Locator itself.\n * @example\n * // String selector\n * rowSelector: 'tbody tr'\n * \n * // Function selector\n * headerSelector: (root) => root.locator('[role=\"columnheader\"]')\n */\nexport type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);\n\n/**\n * Value used to filter rows.\n * - string/number/RegExp: filter by text content of the cell.\n * - function: filter by custom locator logic within the cell.\n * @example\n * // Text filter\n * { Name: 'John' }\n * \n * // Custom locator filter (e.g. checkbox is checked)\n * { Status: (cell) => cell.locator('input:checked') }\n */\nexport type FilterValue = string | RegExp | number | ((cell: Locator) => Locator);\n\n/**\n * Function to get a cell locator given row, column info.\n * Replaces the old cellResolver.\n */\nexport type GetCellLocatorFn = (args: {\n row: Locator;\n /** The root locator passed to useTable(). Useful for re-querying stale row locators. */\n root: Locator;\n columnName: string;\n columnIndex: number;\n rowIndex?: number;\n page: Page;\n config: FinalTableConfig<any>;\n}) => Locator;\n\n/**\n * Hook called before each cell value is read in toJSON (and columnOverrides.read).\n * 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 /** 0-based page index \u2014 which page this row was collected from. */\n pageIndex: number;\n stop: () => void;\n};\n\n/** Concurrency modes for row iteration. */\nexport type RowIterationMode = 'parallel' | 'sequential' | 'synchronized';\n\n/** Shared options for forEach, map, and filter. */\nexport type RowIterationOptions = {\n /** Maximum number of pages to iterate. Defaults to config.maxPages. */\n maxPages?: number;\n /**\n * Concurrency strategy for iteration.\n * - 'parallel': Full parallel execution of both navigation and actions.\n * - 'synchronized': Parallel navigation (lock-step) with serial actions.\n * - 'sequential': Strictly serial one-at-a-time execution. No parallel navigation.\n * @default 'parallel' (for map), 'sequential' (for forEach/filter)\n */\n concurrency?: RowIterationMode;\n /**\n * Deduplication strategy. Use when rows may repeat across iterations\n * (e.g. infinite scroll tables). Returns a unique key per row.\n */\n dedupe?: DedupeStrategy;\n /**\n * When true, use goNextBulk (if present) to advance pages during iteration.\n * @default false \u2014 uses goNext for one-page-at-a-time advancement\n */\n useBulkPagination?: boolean;\n};\n\nexport interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number; index: number; pageIndex: number }> {\n /**\n * Represents the current page index of the table's DOM.\n * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.\n */\n currentPageIndex: number;\n\n /**\n * Initializes the table by resolving headers. Must be called before using sync methods.\n * @param options Optional timeout for header resolution (default: 3000ms)\n */\n init(options?: { timeout?: number }): Promise<TableResult<T>>;\n\n /**\n * SYNC: Checks if the table has been initialized.\n * @returns true if init() has been called and completed, false otherwise\n */\n isInitialized(): boolean;\n\n getHeaders: () => Promise<string[]>;\n getHeaderCell: (columnName: string) => Promise<Locator>;\n\n /**\n * Finds a row by filters on the current page only. Returns immediately (sync).\n * Throws error if table is not initialized.\n * @note The returned SmartRow may have `rowIndex` as 0 when the match is not the first row.\n * Use getRowByIndex(index) when you need a known index (e.g. for bringIntoView()).\n */\n getRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean }\n ) => SmartRow<T>;\n\n /**\n * Gets a row by 0-based index on the current page.\n * Throws error if table is not initialized.\n * @param index 0-based row index\n */\n getRowByIndex: (\n index: number\n ) => SmartRow<T>;\n\n /**\n * ASYNC: Searches for a single row across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRow<T>>;\n\n /**\n * ASYNC: Searches for all matching rows across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match (omit or pass {} for all rows)\n * @param options - Search options including exact match and max pages\n */\n findRows: (\n filters?: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number, useBulkPagination?: boolean }\n ) => Promise<SmartRowArray<T>>;\n\n /**\n * Navigates to a specific column using the configured CellNavigationStrategy.\n */\n scrollToColumn: (columnName: string) => Promise<void>;\n\n /**\n * Counts the number of rows currently on the page.\n * Does not paginate.\n */\n countRows: () => Promise<number>;\n\n /**\n * Iterates over rows and extracts the value of a single column.\n * More efficient than map + toJSON for single-column extraction.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n mapColumn<R = string>(columnName: string, options?: RowIterationOptions): Promise<R[]>;\n\n /**\n * Iterates over rows and extracts the value of a single column as strings.\n * @param columnName - The name of the column to extract\n * @param options - Iteration options\n */\n getColumnValues(columnName: string, options?: RowIterationOptions): Promise<string[]>;\n\n\n /**\n * Resets the table state (clears cache, flags) and invokes the onReset strategy.\n */\n reset: () => Promise<void>;\n\n /**\n * Revalidates the table's structure (headers, columns) without resetting pagination or state.\n * Useful when columns change visibility or order dynamically.\n */\n revalidate: () => Promise<void>;\n\n /**\n * Iterates every row across all pages, calling the callback for side effects.\n * Execution is sequential by default (safe for interactions like clicking/filling).\n * Call `stop()` in the callback to end iteration early.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * await table.forEach(async ({ row, stop }) => {\n * if (await row.getCell('Status').innerText() === 'Done') stop();\n * await row.getCell('Checkbox').click();\n * });\n */\n forEach(\n callback: (ctx: RowIterationContext<T>) => void | Promise<void>,\n options?: RowIterationOptions\n ): Promise<void>;\n\n /**\n * Transforms every row across all pages into a value. Returns a flat array.\n * Execution is parallel within each page by default (safe for reads).\n * Call `stop()` to halt after the current page finishes.\n *\n * > **\u26A0\uFE0F UI Interactions:** `map` defaults to `concurrency: 'parallel'`. If your callback opens popovers,\n * > fills inputs, or otherwise mutates UI state, pass `concurrency: 'sequential'` (or `'synchronized'`\n * > when navigation must stay lock-step) to avoid overlapping interactions.\n *\n * @param callback - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * // Data extraction \u2014 parallel is safe\n * const emails = await table.map(({ row }) => row.getCell('Email').innerText());\n *\n * @example\n * // UI interactions \u2014 use sequential (or synchronized) concurrency\n * const assignees = await table.map(async ({ row }) => {\n * await row.getCell('Assignee').locator('button').click();\n * const name = await page.locator('.popover .name').innerText();\n * await page.keyboard.press('Escape');\n * return name;\n * }, { concurrency: 'sequential' });\n */\n map<R>(\n callback: (ctx: RowIterationContext<T>) => R | Promise<R>,\n options?: RowIterationOptions\n ): Promise<R[]>;\n\n /**\n * Filters rows across all pages by an async predicate. Returns a SmartRowArray.\n * Rows are returned as-is \u2014 call `bringIntoView()` on each if needed.\n * Execution is sequential by default.\n *\n * @param predicate - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * const active = await table.filter(async ({ row }) =>\n * await row.getCell('Status').innerText() === 'Active'\n * );\n */\n filter(\n predicate: (ctx: RowIterationContext<T>) => boolean | Promise<boolean>,\n options?: RowIterationOptions\n ): Promise<SmartRowArray<T>>;\n\n /**\n * Provides access to sorting actions and assertions.\n */\n sorting: {\n /**\n * Applies the configured sorting strategy to the specified column.\n * @param columnName The name of the column to sort.\n * @param direction The direction to sort ('asc' or 'desc').\n */\n apply(columnName: string, direction: 'asc' | 'desc'): Promise<void>;\n /**\n * Gets the current sort state of a column using the configured sorting strategy.\n * @param columnName The name of the column to check.\n * @returns A promise that resolves to 'asc', 'desc', or 'none'.\n */\n getState(columnName: string): Promise<'asc' | 'desc' | 'none'>;\n };\n\n /**\n * Generate an AI-friendly configuration prompt for debugging.\n * Outputs table HTML and TypeScript definitions to help AI assistants generate config.\n * Automatically throws an Error containing the prompt.\n */\n generateConfig: () => Promise<void>;\n\n /**\n * @deprecated Use `generateConfig()` instead. Will be removed in v7.0.0.\n */\n generateConfigPrompt: () => Promise<void>;\n}\n";
@@ -559,6 +559,8 @@ export type RowIterationContext<T = any> = {
559
559
  rowIndex: number;
560
560
  /** 0-based iteration counter — the order this row was visited, not its DOM position or grid identity. */
561
561
  index: number;
562
+ /** 0-based page index — which page this row was collected from. */
563
+ pageIndex: number;
562
564
  stop: () => void;
563
565
  };
564
566
 
@@ -589,7 +591,7 @@ export type RowIterationOptions = {
589
591
  useBulkPagination?: boolean;
590
592
  };
591
593
 
592
- export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number; index: number }> {
594
+ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number; index: number; pageIndex: number }> {
593
595
  /**
594
596
  * Represents the current page index of the table's DOM.
595
597
  * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.
@@ -600,7 +602,7 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
600
602
  * Initializes the table by resolving headers. Must be called before using sync methods.
601
603
  * @param options Optional timeout for header resolution (default: 3000ms)
602
604
  */
603
- init(options?: { timeout?: number }): Promise<TableResult>;
605
+ init(options?: { timeout?: number }): Promise<TableResult<T>>;
604
606
 
605
607
  /**
606
608
  * SYNC: Checks if the table has been initialized.
@@ -620,7 +622,7 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
620
622
  getRow: (
621
623
  filters: Record<string, FilterValue>,
622
624
  options?: { exact?: boolean }
623
- ) => SmartRow;
625
+ ) => SmartRow<T>;
624
626
 
625
627
  /**
626
628
  * Gets a row by 0-based index on the current page.
@@ -629,7 +631,7 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
629
631
  */
630
632
  getRowByIndex: (
631
633
  index: number
632
- ) => SmartRow;
634
+ ) => SmartRow<T>;
633
635
 
634
636
  /**
635
637
  * ASYNC: Searches for a single row across pages using pagination.
@@ -640,7 +642,7 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
640
642
  findRow: (
641
643
  filters: Record<string, FilterValue>,
642
644
  options?: { exact?: boolean, maxPages?: number }
643
- ) => Promise<SmartRow>;
645
+ ) => Promise<SmartRow<T>>;
644
646
 
645
647
  /**
646
648
  * ASYNC: Searches for all matching rows across pages using pagination.
package/dist/types.d.ts CHANGED
@@ -516,6 +516,8 @@ export type RowIterationContext<T = any> = {
516
516
  rowIndex: number;
517
517
  /** 0-based iteration counter — the order this row was visited, not its DOM position or grid identity. */
518
518
  index: number;
519
+ /** 0-based page index — which page this row was collected from. */
520
+ pageIndex: number;
519
521
  stop: () => void;
520
522
  };
521
523
  /** Concurrency modes for row iteration. */
@@ -547,6 +549,7 @@ export interface TableResult<T = any> extends AsyncIterable<{
547
549
  row: SmartRow<T>;
548
550
  rowIndex: number;
549
551
  index: number;
552
+ pageIndex: number;
550
553
  }> {
551
554
  /**
552
555
  * Represents the current page index of the table's DOM.
@@ -559,7 +562,7 @@ export interface TableResult<T = any> extends AsyncIterable<{
559
562
  */
560
563
  init(options?: {
561
564
  timeout?: number;
562
- }): Promise<TableResult>;
565
+ }): Promise<TableResult<T>>;
563
566
  /**
564
567
  * SYNC: Checks if the table has been initialized.
565
568
  * @returns true if init() has been called and completed, false otherwise
@@ -575,13 +578,13 @@ export interface TableResult<T = any> extends AsyncIterable<{
575
578
  */
576
579
  getRow: (filters: Record<string, FilterValue>, options?: {
577
580
  exact?: boolean;
578
- }) => SmartRow;
581
+ }) => SmartRow<T>;
579
582
  /**
580
583
  * Gets a row by 0-based index on the current page.
581
584
  * Throws error if table is not initialized.
582
585
  * @param index 0-based row index
583
586
  */
584
- getRowByIndex: (index: number) => SmartRow;
587
+ getRowByIndex: (index: number) => SmartRow<T>;
585
588
  /**
586
589
  * ASYNC: Searches for a single row across pages using pagination.
587
590
  * Auto-initializes the table if not already initialized.
@@ -591,7 +594,7 @@ export interface TableResult<T = any> extends AsyncIterable<{
591
594
  findRow: (filters: Record<string, FilterValue>, options?: {
592
595
  exact?: boolean;
593
596
  maxPages?: number;
594
- }) => Promise<SmartRow>;
597
+ }) => Promise<SmartRow<T>>;
595
598
  /**
596
599
  * ASYNC: Searches for all matching rows across pages using pagination.
597
600
  * Auto-initializes the table if not already initialized.
package/dist/useTable.js CHANGED
@@ -196,6 +196,7 @@ const useTable = (rootLocator, configOptions = {}) => {
196
196
  if (pagesJumped > 0) {
197
197
  tableState.currentPageIndex += pagesJumped;
198
198
  log(`_advancePage: ${primitive} advanced ${pagesJumped} page(s) — now at page ${tableState.currentPageIndex}`);
199
+ await (0, debugUtils_1.debugDelay)(config, 'pagination');
199
200
  }
200
201
  else {
201
202
  log(`_advancePage: ${primitive} returned false — end of data`);
@@ -261,10 +262,35 @@ const useTable = (rootLocator, configOptions = {}) => {
261
262
  return resolve(config.headerSelector, rootLocator).nth(idx);
262
263
  },
263
264
  countRows: async () => {
264
- log("countRows: counting rows in current viewport");
265
265
  await _autoInit();
266
- const allRows = resolve(config.rowSelector, rootLocator);
267
- return allRows.count();
266
+ const pag = config.strategies.pagination;
267
+ const hasPagination = config.maxPages > 1 && !!((pag === null || pag === void 0 ? void 0 : pag.goNext) || (pag === null || pag === void 0 ? void 0 : pag.goNextBulk));
268
+ if (!hasPagination) {
269
+ log("countRows: counting rows in current viewport (no pagination)");
270
+ return resolve(config.rowSelector, rootLocator).count();
271
+ }
272
+ log(`countRows: paginating up to ${config.maxPages} page(s)`);
273
+ const tracker = new elementTracker_1.ElementTracker('countRows');
274
+ let total = 0;
275
+ let pagesScanned = 1;
276
+ try {
277
+ while (true) {
278
+ const newIndices = await tracker.getUnseenIndices(resolve(config.rowSelector, rootLocator));
279
+ total += newIndices.length;
280
+ log(`countRows: page ${pagesScanned} — ${newIndices.length} row(s) (running total: ${total})`);
281
+ if (pagesScanned >= config.maxPages)
282
+ break;
283
+ if (!await _advancePage(false))
284
+ break;
285
+ pagesScanned++;
286
+ }
287
+ }
288
+ finally {
289
+ await tracker.cleanup(rootLocator.page());
290
+ }
291
+ log(`countRows: ${total} total row(s) across ${pagesScanned} page(s) — resetting`);
292
+ await result.reset();
293
+ return total;
268
294
  },
269
295
  mapColumn: async (columnName, options = {}) => {
270
296
  log(`mapColumn: column="${columnName}" options=${safeStringify(options)}`);
@@ -393,6 +419,7 @@ const useTable = (rootLocator, configOptions = {}) => {
393
419
  const effectiveMaxPages = config.maxPages;
394
420
  const tracker = new elementTracker_1.ElementTracker('iterator');
395
421
  const useBulk = false; // iterator has no options; default goNext
422
+ log(`iterator: starting (maxPages=${effectiveMaxPages})`);
396
423
  try {
397
424
  let rowIndex = 0;
398
425
  let pagesScanned = 1;
@@ -402,7 +429,7 @@ const useTable = (rootLocator, configOptions = {}) => {
402
429
  const pageRows = yield __await(rowLocators.all());
403
430
  const barrier = new navigationBarrier_1.NavigationBarrier(newIndices.length);
404
431
  for (const idx of newIndices) {
405
- yield yield __await({ row: _makeSmart(pageRows[idx], map, rowIndex, pagesScanned - 1, barrier), index: rowIndex, rowIndex });
432
+ yield yield __await({ row: _makeSmart(pageRows[idx], map, rowIndex, tableState.currentPageIndex, barrier), index: rowIndex, rowIndex, pageIndex: tableState.currentPageIndex });
406
433
  rowIndex++;
407
434
  }
408
435
  if (pagesScanned >= effectiveMaxPages)
@@ -429,6 +456,7 @@ const useTable = (rootLocator, configOptions = {}) => {
429
456
  createSmartRowArray: smartRowArray_1.createSmartRowArray,
430
457
  config,
431
458
  getPage: () => rootLocator.page(),
459
+ getCurrentPageIndex: () => tableState.currentPageIndex,
432
460
  }, callback, options);
433
461
  },
434
462
  map: async (callback, options = {}) => {
@@ -442,6 +470,7 @@ const useTable = (rootLocator, configOptions = {}) => {
442
470
  createSmartRowArray: smartRowArray_1.createSmartRowArray,
443
471
  config,
444
472
  getPage: () => rootLocator.page(),
473
+ getCurrentPageIndex: () => tableState.currentPageIndex,
445
474
  }, callback, options);
446
475
  },
447
476
  filter: async (predicate, options = {}) => {
@@ -455,6 +484,7 @@ const useTable = (rootLocator, configOptions = {}) => {
455
484
  createSmartRowArray: smartRowArray_1.createSmartRowArray,
456
485
  config,
457
486
  getPage: () => rootLocator.page(),
487
+ getCurrentPageIndex: () => tableState.currentPageIndex,
458
488
  }, predicate, options);
459
489
  },
460
490
  generateConfig: async () => {
@@ -7,6 +7,8 @@ export declare class NavigationBarrier {
7
7
  private finishedCount;
8
8
  private buckets;
9
9
  constructor(total: number);
10
+ /** True when more than one row shares this barrier (scrollToRow would evict peers). */
11
+ isParallel(): boolean;
10
12
  /**
11
13
  * Synchronize all active rows at a specific column index.
12
14
  * The last row to arrive will trigger the `moveAction`.
@@ -12,6 +12,10 @@ class NavigationBarrier {
12
12
  this.buckets = new Map();
13
13
  this.total = total;
14
14
  }
15
+ /** True when more than one row shares this barrier (scrollToRow would evict peers). */
16
+ isParallel() {
17
+ return this.total > 1;
18
+ }
15
19
  /**
16
20
  * Synchronize all active rows at a specific column index.
17
21
  * The last row to arrive will trigger the `moveAction`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rickcedwhat/playwright-smart-table",
3
- "version": "6.12.0",
3
+ "version": "6.13.0",
4
4
  "description": "Smart, column-aware table interactions for Playwright",
5
5
  "author": "Cedrick Catalan",
6
6
  "license": "MIT",
@@ -90,15 +90,12 @@
90
90
  "@vitest/coverage-v8": "^3.2.4",
91
91
  "@vitest/ui": "^3.2.4",
92
92
  "happy-dom": "^20.8.3",
93
- "@commitlint/cli": "^19.7.1",
94
- "@commitlint/config-conventional": "^19.7.1",
93
+ "@commitlint/cli": "^21.0.0",
94
+ "@commitlint/config-conventional": "^21.0.0",
95
95
  "husky": "^9.1.7",
96
96
  "typescript": "^6.0.2",
97
97
  "vitepress": "^1.6.4",
98
98
  "vitest": "^3.2.4"
99
99
  },
100
- "dependencies": {
101
- "@scarf/scarf": "^1.4.0"
102
- },
103
100
  "packageManager": "pnpm@10.33.2"
104
101
  }
@@ -1,14 +0,0 @@
1
- import { StrategyContext } from '../../types';
2
- /**
3
- * Primitive navigation functions for Glide Data Grid.
4
- * These define HOW to move, not WHEN to move.
5
- * The orchestration logic lives in _navigateToCell.
6
- */
7
- export declare const glideGoUp: (context: StrategyContext) => Promise<void>;
8
- export declare const glideGoDown: (context: StrategyContext) => Promise<void>;
9
- export declare const glideGoLeft: (context: StrategyContext) => Promise<void>;
10
- export declare const glideGoRight: (context: StrategyContext) => Promise<void>;
11
- /** Coarse `scrollLeft` toward `columnIndex`; `goLeft`/`goRight` correct the remainder. */
12
- export declare const glideSeekColumnIndex: (context: StrategyContext, columnIndex: number) => Promise<void>;
13
- /** `scrollLeft = 0` so low `aria-colindex` cells exist again (see smartRow for optional `Home`). */
14
- export declare const glideSnapFirstColumnIntoView: (context: StrategyContext) => Promise<void>;
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.glideSnapFirstColumnIntoView = exports.glideSeekColumnIndex = exports.glideGoRight = exports.glideGoLeft = exports.glideGoDown = exports.glideGoUp = void 0;
4
- /**
5
- * Primitive navigation functions for Glide Data Grid.
6
- * These define HOW to move, not WHEN to move.
7
- * The orchestration logic lives in _navigateToCell.
8
- */
9
- const glideGoUp = async (context) => {
10
- await context.page.keyboard.press('ArrowUp');
11
- };
12
- exports.glideGoUp = glideGoUp;
13
- const glideGoDown = async (context) => {
14
- await context.page.keyboard.press('ArrowDown');
15
- };
16
- exports.glideGoDown = glideGoDown;
17
- // Horizontal: use page `.dvn-scroller` (canvas root is not its ancestor). Virtualized rows expose
18
- // a small window of `td[aria-colindex]` that shifts with scrollLeft.
19
- const nudgePageScroller = async (page, delta) => {
20
- const scroller = page.locator('.dvn-scroller').first();
21
- await scroller.evaluate((el, d) => {
22
- el.scrollLeft += d;
23
- }, delta);
24
- };
25
- const glideGoLeft = async (context) => {
26
- await nudgePageScroller(context.page, -400);
27
- };
28
- exports.glideGoLeft = glideGoLeft;
29
- const glideGoRight = async (context) => {
30
- await nudgePageScroller(context.page, 400);
31
- };
32
- exports.glideGoRight = glideGoRight;
33
- /** Coarse `scrollLeft` toward `columnIndex`; `goLeft`/`goRight` correct the remainder. */
34
- const glideSeekColumnIndex = async (context, columnIndex) => {
35
- const { page } = context;
36
- const scroller = page.locator('.dvn-scroller').first();
37
- await scroller.evaluate((el, colIdx) => {
38
- const max = Math.max(0, el.scrollWidth - el.clientWidth);
39
- const ratio = Math.min(1, Math.max(0, (colIdx + 0.5) / 64));
40
- el.scrollLeft = Math.floor(ratio * max);
41
- }, columnIndex);
42
- await page.waitForTimeout(100);
43
- };
44
- exports.glideSeekColumnIndex = glideSeekColumnIndex;
45
- /** `scrollLeft = 0` so low `aria-colindex` cells exist again (see smartRow for optional `Home`). */
46
- const glideSnapFirstColumnIntoView = async (context) => {
47
- const { page } = context;
48
- await page.locator('.dvn-scroller').first().evaluate((el) => {
49
- el.scrollLeft = 0;
50
- });
51
- await page.waitForTimeout(150);
52
- };
53
- exports.glideSnapFirstColumnIntoView = glideSnapFirstColumnIntoView;