@rickcedwhat/playwright-smart-table 6.16.0 → 6.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -1
- package/dist/packageVersion.d.ts +1 -1
- package/dist/packageVersion.js +1 -1
- package/dist/presets/index.d.ts +2 -1
- package/dist/presets/index.js +3 -1
- package/dist/presets/mui.d.ts +23 -7
- package/dist/presets/mui.js +349 -272
- package/dist/presets/rdg.d.ts +20 -13
- package/dist/presets/rdg.js +5 -5
- package/dist/typeContext.d.ts +1 -1
- package/dist/typeContext.js +25 -0
- package/dist/types.d.ts +21 -0
- package/dist/useTable.js +10 -0
- package/dist/utils/mergeTableConfig.d.ts +22 -0
- package/dist/utils/mergeTableConfig.js +60 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.Plugins = exports.presets = exports.Strategies = exports.useTable = exports.PLAYWRIGHT_SMART_TABLE_VERSION = void 0;
|
|
36
|
+
exports.mergeTableConfig = exports.Plugins = exports.presets = exports.Strategies = exports.useTable = exports.PLAYWRIGHT_SMART_TABLE_VERSION = void 0;
|
|
37
37
|
var packageVersion_1 = require("./packageVersion");
|
|
38
38
|
Object.defineProperty(exports, "PLAYWRIGHT_SMART_TABLE_VERSION", { enumerable: true, get: function () { return packageVersion_1.PLAYWRIGHT_SMART_TABLE_VERSION; } });
|
|
39
39
|
var useTable_1 = require("./useTable");
|
|
@@ -45,3 +45,5 @@ exports.presets = __importStar(require("./presets"));
|
|
|
45
45
|
/** @deprecated Use `presets` instead. Plugins will be removed in v7.0.0. */
|
|
46
46
|
var plugins_1 = require("./plugins");
|
|
47
47
|
Object.defineProperty(exports, "Plugins", { enumerable: true, get: function () { return plugins_1.Plugins; } });
|
|
48
|
+
var mergeTableConfig_1 = require("./utils/mergeTableConfig");
|
|
49
|
+
Object.defineProperty(exports, "mergeTableConfig", { enumerable: true, get: function () { return mergeTableConfig_1.mergeTableConfig; } });
|
package/dist/packageVersion.d.ts
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Generated by scripts/embed-version.mjs from package.json
|
|
4
4
|
*/
|
|
5
5
|
/** Semver of this package. Use in logs or diagnostics to confirm the installed build. */
|
|
6
|
-
export declare const PLAYWRIGHT_SMART_TABLE_VERSION: "6.
|
|
6
|
+
export declare const PLAYWRIGHT_SMART_TABLE_VERSION: "6.17.0";
|
package/dist/packageVersion.js
CHANGED
|
@@ -6,4 +6,4 @@ exports.PLAYWRIGHT_SMART_TABLE_VERSION = void 0;
|
|
|
6
6
|
* Generated by scripts/embed-version.mjs from package.json
|
|
7
7
|
*/
|
|
8
8
|
/** Semver of this package. Use in logs or diagnostics to confirm the installed build. */
|
|
9
|
-
exports.PLAYWRIGHT_SMART_TABLE_VERSION = "6.
|
|
9
|
+
exports.PLAYWRIGHT_SMART_TABLE_VERSION = "6.17.0";
|
package/dist/presets/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export { muiTable, muiDataGrid } from './mui';
|
|
1
|
+
export { muiTable, muiDataGrid, createMuiTable, createMuiDataGrid } from './mui';
|
|
2
|
+
export type { MuiButtonLabels } from './mui';
|
|
2
3
|
export { RDG as rdg, RDG2D as rdg2D } from './rdg';
|
|
3
4
|
export { Glide as glide, createGlide, createGlideViewport } from './glide';
|
|
4
5
|
export type { GlideOptions, GlideViewportOptions } from './glide';
|
package/dist/presets/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createGlideViewport = exports.createGlide = exports.glide = exports.rdg2D = exports.rdg = exports.muiDataGrid = exports.muiTable = void 0;
|
|
3
|
+
exports.createGlideViewport = exports.createGlide = exports.glide = exports.rdg2D = exports.rdg = exports.createMuiDataGrid = exports.createMuiTable = 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; } });
|
|
7
|
+
Object.defineProperty(exports, "createMuiTable", { enumerable: true, get: function () { return mui_1.createMuiTable; } });
|
|
8
|
+
Object.defineProperty(exports, "createMuiDataGrid", { enumerable: true, get: function () { return mui_1.createMuiDataGrid; } });
|
|
7
9
|
var rdg_1 = require("./rdg");
|
|
8
10
|
Object.defineProperty(exports, "rdg", { enumerable: true, get: function () { return rdg_1.RDG; } });
|
|
9
11
|
Object.defineProperty(exports, "rdg2D", { enumerable: true, get: function () { return rdg_1.RDG2D; } });
|
package/dist/presets/mui.d.ts
CHANGED
|
@@ -1,16 +1,28 @@
|
|
|
1
1
|
import { TableConfig } from '../types';
|
|
2
|
+
/** Aria-labels for MUI pagination buttons. Override for non-English locales. */
|
|
3
|
+
export interface MuiButtonLabels {
|
|
4
|
+
nextPage?: string;
|
|
5
|
+
previousPage?: string;
|
|
6
|
+
firstPage?: string;
|
|
7
|
+
}
|
|
2
8
|
/**
|
|
3
|
-
*
|
|
9
|
+
* Creates a preset configuration for the standard Material UI `<Table />` component.
|
|
4
10
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
11
|
+
* @param opts.buttonLabels - Override aria-labels for pagination buttons (use for non-English locales).
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* // French locale
|
|
15
|
+
* const table = useTable(loc, createMuiTable({ buttonLabels: { nextPage: 'Page suivante', previousPage: 'Page précédente' } }));
|
|
10
16
|
*/
|
|
17
|
+
export declare function createMuiTable(opts?: {
|
|
18
|
+
buttonLabels?: MuiButtonLabels;
|
|
19
|
+
}): Partial<TableConfig>;
|
|
20
|
+
/** Default preset for MUI `<Table />`. For non-English locales use `createMuiTable({ buttonLabels })`. */
|
|
11
21
|
export declare const muiTable: Partial<TableConfig>;
|
|
12
22
|
/**
|
|
13
|
-
*
|
|
23
|
+
* Creates a preset configuration for the MUI DataGrid component (@mui/x-data-grid).
|
|
24
|
+
*
|
|
25
|
+
* @param opts.buttonLabels - Override aria-labels for pagination buttons (use for non-English locales).
|
|
14
26
|
*
|
|
15
27
|
* Handles:
|
|
16
28
|
* - Selectors for `.MuiDataGrid-row`, `.MuiDataGrid-cell`, and `.MuiDataGrid-columnHeader`.
|
|
@@ -19,4 +31,8 @@ export declare const muiTable: Partial<TableConfig>;
|
|
|
19
31
|
* - Vertical Virtualization deduplication using `data-rowindex`.
|
|
20
32
|
* - Horizontal Virtualization support via `aria-colindex`.
|
|
21
33
|
*/
|
|
34
|
+
export declare function createMuiDataGrid(opts?: {
|
|
35
|
+
buttonLabels?: MuiButtonLabels;
|
|
36
|
+
}): Partial<TableConfig>;
|
|
37
|
+
/** Default preset for MUI DataGrid. For non-English locales use `createMuiDataGrid({ buttonLabels })`. */
|
|
22
38
|
export declare const muiDataGrid: Partial<TableConfig>;
|
package/dist/presets/mui.js
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.muiDataGrid = exports.muiTable = void 0;
|
|
4
|
+
exports.createMuiTable = createMuiTable;
|
|
5
|
+
exports.createMuiDataGrid = createMuiDataGrid;
|
|
4
6
|
const debugUtils_1 = require("../utils/debugUtils");
|
|
7
|
+
const DEFAULT_LABELS = {
|
|
8
|
+
nextPage: 'Go to next page',
|
|
9
|
+
previousPage: 'Go to previous page',
|
|
10
|
+
firstPage: 'Go to first page',
|
|
11
|
+
};
|
|
5
12
|
/**
|
|
6
13
|
* Safely wait for MUI pagination to stabilize.
|
|
7
14
|
* Polls for displayed row text changes and waits for loading overlays to disappear.
|
|
@@ -45,120 +52,136 @@ async function getPaginationRoot(context) {
|
|
|
45
52
|
return context.root.locator('xpath=following::div[contains(@class, "MuiTablePagination-root")][1]').first();
|
|
46
53
|
}
|
|
47
54
|
/**
|
|
48
|
-
*
|
|
55
|
+
* Creates a preset configuration for the standard Material UI `<Table />` component.
|
|
49
56
|
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
57
|
+
* @param opts.buttonLabels - Override aria-labels for pagination buttons (use for non-English locales).
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* // French locale
|
|
61
|
+
* const table = useTable(loc, createMuiTable({ buttonLabels: { nextPage: 'Page suivante', previousPage: 'Page précédente' } }));
|
|
55
62
|
*/
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
await nextBtn.click({ force: true });
|
|
72
|
-
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
73
|
-
return true;
|
|
74
|
-
},
|
|
75
|
-
goPrevious: async (context) => {
|
|
76
|
-
const root = await getPaginationRoot(context);
|
|
77
|
-
const prevBtn = root.locator('button[aria-label="Go to previous page"]');
|
|
78
|
-
if (await prevBtn.count() === 0 || await prevBtn.isDisabled())
|
|
79
|
-
return false;
|
|
80
|
-
const displayedRows = root.locator('.MuiTablePagination-displayedRows');
|
|
81
|
-
const oldText = await displayedRows.innerText().catch(() => '');
|
|
82
|
-
await prevBtn.click({ force: true });
|
|
83
|
-
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
84
|
-
return true;
|
|
85
|
-
},
|
|
86
|
-
goToFirst: async (context) => {
|
|
87
|
-
const root = await getPaginationRoot(context);
|
|
88
|
-
const prevBtn = root.locator('button[aria-label="Go to previous page"]');
|
|
89
|
-
const displayedRows = root.locator('.MuiTablePagination-displayedRows');
|
|
90
|
-
let clicked = false;
|
|
91
|
-
let noProgressCount = 0;
|
|
92
|
-
const NO_PROGRESS_LIMIT = 3;
|
|
93
|
-
while (await prevBtn.count() > 0 && !(await prevBtn.isDisabled())) {
|
|
63
|
+
function createMuiTable(opts) {
|
|
64
|
+
const labels = Object.assign(Object.assign({}, DEFAULT_LABELS), opts === null || opts === void 0 ? void 0 : opts.buttonLabels);
|
|
65
|
+
return {
|
|
66
|
+
rowSelector: 'tbody tr, tbody .MuiTableRow-root',
|
|
67
|
+
cellSelector: 'td, th, .MuiTableCell-body',
|
|
68
|
+
headerSelector: 'thead th, .MuiTableCell-head',
|
|
69
|
+
headerTransformer: ({ text }) => text.replace(/\bsorted\s+(?:ascending|descending)\b/i, '').trim(),
|
|
70
|
+
strategies: {
|
|
71
|
+
pagination: {
|
|
72
|
+
goNext: async (context) => {
|
|
73
|
+
const root = await getPaginationRoot(context);
|
|
74
|
+
const nextBtn = root.getByRole('button', { name: labels.nextPage, exact: true });
|
|
75
|
+
if (await nextBtn.count() === 0 || await nextBtn.isDisabled())
|
|
76
|
+
return false;
|
|
77
|
+
const displayedRows = root.locator('.MuiTablePagination-displayedRows');
|
|
94
78
|
const oldText = await displayedRows.innerText().catch(() => '');
|
|
95
|
-
|
|
79
|
+
// Force click ignores cookie banners obscuring the footer
|
|
80
|
+
await nextBtn.click({ force: true });
|
|
96
81
|
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
82
|
+
return true;
|
|
83
|
+
},
|
|
84
|
+
goPrevious: async (context) => {
|
|
85
|
+
const root = await getPaginationRoot(context);
|
|
86
|
+
const prevBtn = root.getByRole('button', { name: labels.previousPage, exact: true });
|
|
87
|
+
if (await prevBtn.count() === 0 || await prevBtn.isDisabled())
|
|
88
|
+
return false;
|
|
89
|
+
const displayedRows = root.locator('.MuiTablePagination-displayedRows');
|
|
90
|
+
const oldText = await displayedRows.innerText().catch(() => '');
|
|
91
|
+
await prevBtn.click({ force: true });
|
|
92
|
+
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
93
|
+
return true;
|
|
94
|
+
},
|
|
95
|
+
goToFirst: async (context) => {
|
|
96
|
+
const root = await getPaginationRoot(context);
|
|
97
|
+
const displayedRows = root.locator('.MuiTablePagination-displayedRows');
|
|
98
|
+
// MUI TablePagination optionally renders a "first page" button (showFirstButton prop)
|
|
99
|
+
const firstBtn = root.getByRole('button', { name: labels.firstPage, exact: true });
|
|
100
|
+
if (await firstBtn.count() > 0 && !(await firstBtn.isDisabled())) {
|
|
101
|
+
const oldText = await displayedRows.innerText().catch(() => '');
|
|
102
|
+
await firstBtn.click({ force: true });
|
|
103
|
+
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
104
|
+
return true;
|
|
105
105
|
}
|
|
106
|
-
|
|
107
|
-
|
|
106
|
+
// Fall back to stepping backward one page at a time
|
|
107
|
+
const prevBtn = root.getByRole('button', { name: labels.previousPage, exact: true });
|
|
108
|
+
let clicked = false;
|
|
109
|
+
let noProgressCount = 0;
|
|
110
|
+
const NO_PROGRESS_LIMIT = 3;
|
|
111
|
+
while (await prevBtn.count() > 0 && !(await prevBtn.isDisabled())) {
|
|
112
|
+
const oldText = await displayedRows.innerText().catch(() => '');
|
|
113
|
+
await prevBtn.click({ force: true });
|
|
114
|
+
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
115
|
+
clicked = true;
|
|
116
|
+
const newText = await displayedRows.innerText().catch(() => '');
|
|
117
|
+
if (newText === oldText) {
|
|
118
|
+
noProgressCount++;
|
|
119
|
+
if (noProgressCount >= NO_PROGRESS_LIMIT) {
|
|
120
|
+
(0, debugUtils_1.logDebug)(context.config, 'error', `goToFirst: no pagination progress after ${NO_PROGRESS_LIMIT} consecutive clicks — aborting to avoid infinite loop`);
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
noProgressCount = 0;
|
|
126
|
+
}
|
|
108
127
|
}
|
|
128
|
+
return clicked;
|
|
109
129
|
}
|
|
110
|
-
return clicked;
|
|
111
|
-
}
|
|
112
|
-
},
|
|
113
|
-
sorting: {
|
|
114
|
-
getSortState: async ({ columnName, context }) => {
|
|
115
|
-
if (!context.getHeaderCell)
|
|
116
|
-
return 'none';
|
|
117
|
-
const header = await context.getHeaderCell(columnName);
|
|
118
|
-
const sortLabel = header.locator('.MuiTableSortLabel-root').first();
|
|
119
|
-
if (!(await sortLabel.isVisible().catch(() => false)))
|
|
120
|
-
return 'none';
|
|
121
|
-
const className = await sortLabel.getAttribute('class') || '';
|
|
122
|
-
if (className.includes('directionAsc'))
|
|
123
|
-
return 'asc';
|
|
124
|
-
if (className.includes('directionDesc'))
|
|
125
|
-
return 'desc';
|
|
126
|
-
// Often, if the label is active but lacks explicit direction classes, MUI defaults to ascending
|
|
127
|
-
if (className.includes('active'))
|
|
128
|
-
return 'asc';
|
|
129
|
-
return 'none';
|
|
130
130
|
},
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
131
|
+
sorting: {
|
|
132
|
+
getSortState: async ({ columnName, context }) => {
|
|
133
|
+
if (!context.getHeaderCell)
|
|
134
|
+
return 'none';
|
|
135
|
+
const header = await context.getHeaderCell(columnName);
|
|
136
|
+
const sortLabel = header.locator('.MuiTableSortLabel-root').first();
|
|
137
|
+
if (!(await sortLabel.isVisible().catch(() => false)))
|
|
138
|
+
return 'none';
|
|
139
|
+
const className = await sortLabel.getAttribute('class') || '';
|
|
140
|
+
if (className.includes('directionAsc'))
|
|
141
|
+
return 'asc';
|
|
142
|
+
if (className.includes('directionDesc'))
|
|
143
|
+
return 'desc';
|
|
144
|
+
// Often, if the label is active but lacks explicit direction classes, MUI defaults to ascending
|
|
145
|
+
if (className.includes('active'))
|
|
146
|
+
return 'asc';
|
|
147
|
+
return 'none';
|
|
148
|
+
},
|
|
149
|
+
doSort: async ({ columnName, direction, context }) => {
|
|
150
|
+
var _a, _b;
|
|
151
|
+
if (!context.getHeaderCell)
|
|
152
|
+
return;
|
|
153
|
+
const header = await context.getHeaderCell(columnName);
|
|
154
|
+
const sortLabel = header.locator('.MuiTableSortLabel-root').first();
|
|
155
|
+
const target = await sortLabel.isVisible().catch(() => false) ? sortLabel : header;
|
|
156
|
+
let current = await ((_a = context.config.strategies.sorting) === null || _a === void 0 ? void 0 : _a.getSortState({ columnName, context })) || 'none';
|
|
157
|
+
let attempts = 0;
|
|
158
|
+
// Click until the state matches the target direction, max 3 times (none -> asc -> desc)
|
|
159
|
+
while (current !== direction && attempts < 3) {
|
|
160
|
+
await target.click();
|
|
161
|
+
await context.page.waitForTimeout(100);
|
|
162
|
+
current = await ((_b = context.config.strategies.sorting) === null || _b === void 0 ? void 0 : _b.getSortState({ columnName, context })) || 'none';
|
|
163
|
+
attempts++;
|
|
164
|
+
}
|
|
146
165
|
}
|
|
166
|
+
},
|
|
167
|
+
dedupe: async (row) => {
|
|
168
|
+
// MUI virtualized tables attach data-index to rows
|
|
169
|
+
const dataIndex = await row.getAttribute('data-index');
|
|
170
|
+
if (dataIndex !== null)
|
|
171
|
+
return dataIndex;
|
|
172
|
+
// Unvirtualized tables don't recycle nodes, but if they do duplicate, fallback to first cell's text
|
|
173
|
+
const text = await row.locator('td, th').first().innerText().catch(() => '');
|
|
174
|
+
return text || String(Math.random());
|
|
147
175
|
}
|
|
148
|
-
},
|
|
149
|
-
dedupe: async (row) => {
|
|
150
|
-
// MUI virtualized tables attach data-index to rows
|
|
151
|
-
const dataIndex = await row.getAttribute('data-index');
|
|
152
|
-
if (dataIndex !== null)
|
|
153
|
-
return dataIndex;
|
|
154
|
-
// Unvirtualized tables don't recycle nodes, but if they do duplicate, fallback to first cell's text
|
|
155
|
-
const text = await row.locator('td, th').first().innerText().catch(() => '');
|
|
156
|
-
return text || String(Math.random());
|
|
157
176
|
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/** Default preset for MUI `<Table />`. For non-English locales use `createMuiTable({ buttonLabels })`. */
|
|
180
|
+
exports.muiTable = createMuiTable();
|
|
160
181
|
/**
|
|
161
|
-
*
|
|
182
|
+
* Creates a preset configuration for the MUI DataGrid component (@mui/x-data-grid).
|
|
183
|
+
*
|
|
184
|
+
* @param opts.buttonLabels - Override aria-labels for pagination buttons (use for non-English locales).
|
|
162
185
|
*
|
|
163
186
|
* Handles:
|
|
164
187
|
* - Selectors for `.MuiDataGrid-row`, `.MuiDataGrid-cell`, and `.MuiDataGrid-columnHeader`.
|
|
@@ -167,184 +190,238 @@ exports.muiTable = {
|
|
|
167
190
|
* - Vertical Virtualization deduplication using `data-rowindex`.
|
|
168
191
|
* - Horizontal Virtualization support via `aria-colindex`.
|
|
169
192
|
*/
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
193
|
+
function createMuiDataGrid(opts) {
|
|
194
|
+
const labels = Object.assign(Object.assign({}, DEFAULT_LABELS), opts === null || opts === void 0 ? void 0 : opts.buttonLabels);
|
|
195
|
+
return {
|
|
196
|
+
rowSelector: '.MuiDataGrid-row',
|
|
197
|
+
cellSelector: '.MuiDataGrid-cell',
|
|
198
|
+
headerSelector: '.MuiDataGrid-columnHeader',
|
|
199
|
+
strategies: {
|
|
200
|
+
pagination: {
|
|
201
|
+
goNext: async (context) => {
|
|
202
|
+
const footer = context.root.locator('.MuiDataGrid-footerContainer');
|
|
203
|
+
const nextBtn = footer.getByRole('button', { name: labels.nextPage, exact: true });
|
|
204
|
+
try {
|
|
205
|
+
await nextBtn.waitFor({ state: 'visible', timeout: 2000 });
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
if (await nextBtn.isDisabled())
|
|
211
|
+
return false;
|
|
212
|
+
const displayedRows = footer.locator('.MuiTablePagination-displayedRows');
|
|
213
|
+
const oldText = await displayedRows.innerText().catch(() => '');
|
|
214
|
+
await nextBtn.scrollIntoViewIfNeeded().catch(() => { });
|
|
215
|
+
await nextBtn.click({ force: true });
|
|
216
|
+
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
217
|
+
return true;
|
|
218
|
+
},
|
|
219
|
+
goPrevious: async (context) => {
|
|
220
|
+
const footer = context.root.locator('.MuiDataGrid-footerContainer');
|
|
221
|
+
const prevBtn = footer.getByRole('button', { name: labels.previousPage, exact: true });
|
|
222
|
+
try {
|
|
223
|
+
await prevBtn.waitFor({ state: 'visible', timeout: 2000 });
|
|
224
|
+
}
|
|
225
|
+
catch (e) {
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
if (await prevBtn.isDisabled())
|
|
229
|
+
return false;
|
|
230
|
+
const displayedRows = footer.locator('.MuiTablePagination-displayedRows');
|
|
231
|
+
const oldText = await displayedRows.innerText().catch(() => '');
|
|
232
|
+
await prevBtn.scrollIntoViewIfNeeded().catch(() => { });
|
|
233
|
+
await prevBtn.click({ force: true });
|
|
234
|
+
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
235
|
+
return true;
|
|
236
|
+
},
|
|
237
|
+
goToFirst: async (context) => {
|
|
238
|
+
const footer = context.root.locator('.MuiDataGrid-footerContainer');
|
|
239
|
+
const displayedRows = footer.locator('.MuiTablePagination-displayedRows');
|
|
240
|
+
const firstBtn = footer.getByRole('button', { name: labels.firstPage, exact: true });
|
|
241
|
+
try {
|
|
242
|
+
await firstBtn.waitFor({ state: 'visible', timeout: 1000 });
|
|
243
|
+
if (!(await firstBtn.isDisabled())) {
|
|
244
|
+
const oldText = await displayedRows.innerText().catch(() => '');
|
|
245
|
+
await firstBtn.scrollIntoViewIfNeeded().catch(() => { });
|
|
246
|
+
await firstBtn.click({ force: true });
|
|
247
|
+
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
catch (_a) {
|
|
252
|
+
// first-page button not present; fall back to stepping backward
|
|
253
|
+
}
|
|
254
|
+
const prevBtn = footer.getByRole('button', { name: labels.previousPage, exact: true });
|
|
255
|
+
let clicked = false;
|
|
256
|
+
let noProgressCount = 0;
|
|
257
|
+
const NO_PROGRESS_LIMIT = 3;
|
|
258
|
+
while (true) {
|
|
259
|
+
try {
|
|
260
|
+
await prevBtn.waitFor({ state: 'visible', timeout: 2000 });
|
|
261
|
+
}
|
|
262
|
+
catch (_b) {
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
if (await prevBtn.isDisabled())
|
|
266
|
+
break;
|
|
267
|
+
const oldText = await displayedRows.innerText().catch(() => '');
|
|
268
|
+
await prevBtn.scrollIntoViewIfNeeded().catch(() => { });
|
|
269
|
+
await prevBtn.click({ force: true });
|
|
270
|
+
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
271
|
+
clicked = true;
|
|
272
|
+
const newText = await displayedRows.innerText().catch(() => '');
|
|
273
|
+
if (newText === oldText) {
|
|
274
|
+
noProgressCount++;
|
|
275
|
+
if (noProgressCount >= NO_PROGRESS_LIMIT) {
|
|
276
|
+
(0, debugUtils_1.logDebug)(context.config, 'error', `goToFirst: no pagination progress after ${NO_PROGRESS_LIMIT} consecutive clicks — aborting to avoid infinite loop`);
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
noProgressCount = 0;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return clicked;
|
|
184
285
|
}
|
|
185
|
-
if (await nextBtn.isDisabled())
|
|
186
|
-
return false;
|
|
187
|
-
const displayedRows = footer.locator('.MuiTablePagination-displayedRows');
|
|
188
|
-
const oldText = await displayedRows.innerText().catch(() => '');
|
|
189
|
-
await nextBtn.scrollIntoViewIfNeeded().catch(() => { });
|
|
190
|
-
await nextBtn.click({ force: true });
|
|
191
|
-
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
192
|
-
return true;
|
|
193
286
|
},
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
await
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
return false;
|
|
205
|
-
const displayedRows = footer.locator('.MuiTablePagination-displayedRows');
|
|
206
|
-
const oldText = await displayedRows.innerText().catch(() => '');
|
|
207
|
-
await prevBtn.scrollIntoViewIfNeeded().catch(() => { });
|
|
208
|
-
await prevBtn.click({ force: true });
|
|
209
|
-
await waitForMuiPaginationStabilization(context, displayedRows, oldText);
|
|
210
|
-
return true;
|
|
211
|
-
}
|
|
212
|
-
},
|
|
213
|
-
sorting: {
|
|
214
|
-
getSortState: async ({ columnName, context }) => {
|
|
215
|
-
if (!context.getHeaderCell)
|
|
287
|
+
sorting: {
|
|
288
|
+
getSortState: async ({ columnName, context }) => {
|
|
289
|
+
if (!context.getHeaderCell)
|
|
290
|
+
return 'none';
|
|
291
|
+
const header = await context.getHeaderCell(columnName);
|
|
292
|
+
const sortAttr = await header.getAttribute('aria-sort');
|
|
293
|
+
if (sortAttr === 'ascending')
|
|
294
|
+
return 'asc';
|
|
295
|
+
if (sortAttr === 'descending')
|
|
296
|
+
return 'desc';
|
|
216
297
|
return 'none';
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
await
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
298
|
+
},
|
|
299
|
+
doSort: async ({ columnName, direction, context }) => {
|
|
300
|
+
var _a, _b;
|
|
301
|
+
if (!context.getHeaderCell)
|
|
302
|
+
return;
|
|
303
|
+
const header = await context.getHeaderCell(columnName);
|
|
304
|
+
let current = await ((_a = context.config.strategies.sorting) === null || _a === void 0 ? void 0 : _a.getSortState({ columnName, context })) || 'none';
|
|
305
|
+
let attempts = 0;
|
|
306
|
+
while (current !== direction && attempts < 3) {
|
|
307
|
+
const clickTarget = header.locator('.MuiDataGrid-columnHeaderTitleContainer').first();
|
|
308
|
+
if (await clickTarget.isVisible()) {
|
|
309
|
+
await clickTarget.click({ force: true });
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
await header.click({ force: true });
|
|
313
|
+
}
|
|
314
|
+
// Wait for stabilization (using DataGrid specific overlay check inside helper)
|
|
315
|
+
const displayedRows = context.root.locator('.MuiTablePagination-displayedRows');
|
|
316
|
+
const text = await displayedRows.innerText().catch(() => '');
|
|
317
|
+
await waitForMuiPaginationStabilization(context, displayedRows, text);
|
|
318
|
+
current = await ((_b = context.config.strategies.sorting) === null || _b === void 0 ? void 0 : _b.getSortState({ columnName, context })) || 'none';
|
|
319
|
+
attempts++;
|
|
239
320
|
}
|
|
240
|
-
// Wait for stabilization (using DataGrid specific overlay check inside helper)
|
|
241
|
-
const displayedRows = context.root.locator('.MuiTablePagination-displayedRows');
|
|
242
|
-
const text = await displayedRows.innerText().catch(() => '');
|
|
243
|
-
await waitForMuiPaginationStabilization(context, displayedRows, text);
|
|
244
|
-
current = await ((_b = context.config.strategies.sorting) === null || _b === void 0 ? void 0 : _b.getSortState({ columnName, context })) || 'none';
|
|
245
|
-
attempts++;
|
|
246
321
|
}
|
|
247
|
-
}
|
|
248
|
-
},
|
|
249
|
-
dedupe: async (row) => {
|
|
250
|
-
var _a;
|
|
251
|
-
// DataGrid uses data-rowindex for its own virtualization management
|
|
252
|
-
return (_a = (await row.getAttribute('data-rowindex').catch(() => null))) !== null && _a !== void 0 ? _a : '';
|
|
253
|
-
},
|
|
254
|
-
getCellLocator: ({ row, columnIndex }) => {
|
|
255
|
-
// Horizontal virtualization uses aria-colindex (1-indexed)
|
|
256
|
-
return row.locator(`[aria-colindex="${columnIndex + 1}"]`);
|
|
257
|
-
},
|
|
258
|
-
// MUI DataGrid virtualizes rows vertically (always) and columns horizontally (when
|
|
259
|
-
// columnBuffer is configured). The virtualScroller is a descendant of root, so
|
|
260
|
-
// scroll methods use querySelector rather than closest().
|
|
261
|
-
viewport: {
|
|
262
|
-
getVisibleRowRange: async ({ root, config }) => {
|
|
263
|
-
const rowSel = config.rowSelector;
|
|
264
|
-
return root.evaluate((el, rowSel) => {
|
|
265
|
-
const indices = Array.from(el.querySelectorAll(rowSel))
|
|
266
|
-
.map(r => Number(r.getAttribute('data-rowindex')))
|
|
267
|
-
.filter(n => !isNaN(n));
|
|
268
|
-
if (!indices.length)
|
|
269
|
-
return { first: 0, last: 0 };
|
|
270
|
-
return { first: Math.min(...indices), last: Math.max(...indices) };
|
|
271
|
-
}, rowSel);
|
|
272
322
|
},
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
return
|
|
277
|
-
const firstRow = el.querySelector(rowSel);
|
|
278
|
-
if (!firstRow)
|
|
279
|
-
return { first: 0, last: 0 };
|
|
280
|
-
const indices = Array.from(firstRow.querySelectorAll(cellSel))
|
|
281
|
-
.map(c => Number(c.getAttribute('aria-colindex')) - 1)
|
|
282
|
-
.filter(n => !isNaN(n));
|
|
283
|
-
if (!indices.length)
|
|
284
|
-
return { first: 0, last: 0 };
|
|
285
|
-
return { first: Math.min(...indices), last: Math.max(...indices) };
|
|
286
|
-
}, { rowSel, cellSel });
|
|
323
|
+
dedupe: async (row) => {
|
|
324
|
+
var _a;
|
|
325
|
+
// DataGrid uses data-rowindex for its own virtualization management
|
|
326
|
+
return (_a = (await row.getAttribute('data-rowindex').catch(() => null))) !== null && _a !== void 0 ? _a : '';
|
|
287
327
|
},
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
const scroller = el.querySelector('.MuiDataGrid-virtualScroller');
|
|
292
|
-
if (!scroller)
|
|
293
|
-
return;
|
|
294
|
-
const row = el.querySelector(`${rowSel}[data-rowindex="${idx}"]`);
|
|
295
|
-
if (row) {
|
|
296
|
-
row.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
const visibleRows = Array.from(el.querySelectorAll(rowSel));
|
|
300
|
-
const heights = visibleRows
|
|
301
|
-
.map(visibleRow => visibleRow.getBoundingClientRect().height)
|
|
302
|
-
.filter(height => height > 0);
|
|
303
|
-
const estimatedHeight = heights.length
|
|
304
|
-
? heights.reduce((sum, height) => sum + height, 0) / heights.length
|
|
305
|
-
: 52;
|
|
306
|
-
scroller.scrollTop = Math.max(0, idx * estimatedHeight - 20);
|
|
307
|
-
}, { rowSel, idx: rowIndex });
|
|
308
|
-
await root.locator(`${rowSel}[data-rowindex="${rowIndex}"]`)
|
|
309
|
-
.waitFor({ state: 'attached', timeout: 3000 });
|
|
328
|
+
getCellLocator: ({ row, columnIndex }) => {
|
|
329
|
+
// Horizontal virtualization uses aria-colindex (1-indexed)
|
|
330
|
+
return row.locator(`[aria-colindex="${columnIndex + 1}"]`);
|
|
310
331
|
},
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
332
|
+
// MUI DataGrid virtualizes rows vertically (always) and columns horizontally (when
|
|
333
|
+
// columnBuffer is configured). The virtualScroller is a descendant of root, so
|
|
334
|
+
// scroll methods use querySelector rather than closest().
|
|
335
|
+
viewport: {
|
|
336
|
+
getVisibleRowRange: async ({ root, config }) => {
|
|
337
|
+
const rowSel = config.rowSelector;
|
|
338
|
+
return root.evaluate((el, rowSel) => {
|
|
339
|
+
const indices = Array.from(el.querySelectorAll(rowSel))
|
|
340
|
+
.map(r => Number(r.getAttribute('data-rowindex')))
|
|
341
|
+
.filter(n => !isNaN(n));
|
|
342
|
+
if (!indices.length)
|
|
343
|
+
return { first: 0, last: 0 };
|
|
344
|
+
return { first: Math.min(...indices), last: Math.max(...indices) };
|
|
345
|
+
}, rowSel);
|
|
346
|
+
},
|
|
347
|
+
getVisibleColumnRange: async ({ root, config }) => {
|
|
348
|
+
const rowSel = config.rowSelector;
|
|
349
|
+
const cellSel = typeof config.cellSelector === 'string' ? config.cellSelector : '[aria-colindex]';
|
|
350
|
+
return root.evaluate((el, { rowSel, cellSel }) => {
|
|
351
|
+
const firstRow = el.querySelector(rowSel);
|
|
352
|
+
if (!firstRow)
|
|
353
|
+
return { first: 0, last: 0 };
|
|
354
|
+
const indices = Array.from(firstRow.querySelectorAll(cellSel))
|
|
355
|
+
.map(c => Number(c.getAttribute('aria-colindex')) - 1)
|
|
356
|
+
.filter(n => !isNaN(n));
|
|
357
|
+
if (!indices.length)
|
|
358
|
+
return { first: 0, last: 0 };
|
|
359
|
+
return { first: Math.min(...indices), last: Math.max(...indices) };
|
|
360
|
+
}, { rowSel, cellSel });
|
|
361
|
+
},
|
|
362
|
+
scrollToRow: async ({ root, config }, rowIndex) => {
|
|
363
|
+
const rowSel = config.rowSelector;
|
|
364
|
+
await root.evaluate((el, { rowSel, idx }) => {
|
|
365
|
+
const scroller = el.querySelector('.MuiDataGrid-virtualScroller');
|
|
366
|
+
if (!scroller)
|
|
367
|
+
return;
|
|
368
|
+
const row = el.querySelector(`${rowSel}[data-rowindex="${idx}"]`);
|
|
369
|
+
if (row) {
|
|
370
|
+
row.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
const visibleRows = Array.from(el.querySelectorAll(rowSel));
|
|
374
|
+
const heights = visibleRows
|
|
375
|
+
.map(visibleRow => visibleRow.getBoundingClientRect().height)
|
|
376
|
+
.filter(height => height > 0);
|
|
377
|
+
const estimatedHeight = heights.length
|
|
378
|
+
? heights.reduce((sum, height) => sum + height, 0) / heights.length
|
|
379
|
+
: 52;
|
|
380
|
+
scroller.scrollTop = Math.max(0, idx * estimatedHeight - 20);
|
|
381
|
+
}, { rowSel, idx: rowIndex });
|
|
382
|
+
await root.locator(`${rowSel}[data-rowindex="${rowIndex}"]`)
|
|
383
|
+
.waitFor({ state: 'attached', timeout: 3000 });
|
|
384
|
+
},
|
|
385
|
+
scrollToColumn: async ({ root, config }, colIndex) => {
|
|
386
|
+
const headerSel = typeof config.headerSelector === 'string' ? config.headerSelector : null;
|
|
387
|
+
await root.evaluate((el, { headerSel, idx }) => {
|
|
388
|
+
// virtualScroller is a descendant — querySelector, not closest
|
|
389
|
+
const scroller = el.querySelector('.MuiDataGrid-virtualScroller');
|
|
390
|
+
if (!scroller || !headerSel)
|
|
391
|
+
return;
|
|
392
|
+
const headers = Array.from(el.querySelectorAll(headerSel));
|
|
393
|
+
const target = headers[idx];
|
|
394
|
+
if (!target) {
|
|
395
|
+
const widths = headers
|
|
396
|
+
.map(header => header.getBoundingClientRect().width)
|
|
397
|
+
.filter(width => width > 0);
|
|
398
|
+
const estimatedWidth = widths.length
|
|
399
|
+
? widths.reduce((sum, width) => sum + width, 0) / widths.length
|
|
400
|
+
: 100;
|
|
401
|
+
scroller.scrollLeft = Math.max(0, idx * estimatedWidth - 20);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
const cRect = scroller.getBoundingClientRect();
|
|
405
|
+
const tRect = target.getBoundingClientRect();
|
|
406
|
+
if (tRect.left < cRect.left) {
|
|
407
|
+
scroller.scrollLeft -= (cRect.left - tRect.left) + 20;
|
|
408
|
+
}
|
|
409
|
+
else if (tRect.right > cRect.right) {
|
|
410
|
+
scroller.scrollLeft += (tRect.right - cRect.right) + 20;
|
|
411
|
+
}
|
|
412
|
+
}, { headerSel, idx: colIndex });
|
|
413
|
+
await root.locator(`${config.rowSelector} [aria-colindex="${colIndex + 1}"]`)
|
|
414
|
+
.first()
|
|
415
|
+
.waitFor({ state: 'attached', timeout: 3000 });
|
|
416
|
+
},
|
|
342
417
|
},
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
418
|
+
loading: {
|
|
419
|
+
isTableLoading: async (context) => {
|
|
420
|
+
return await context.root.locator('.MuiDataGrid-overlay').isVisible().catch(() => false);
|
|
421
|
+
}
|
|
347
422
|
}
|
|
348
423
|
}
|
|
349
|
-
}
|
|
350
|
-
}
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
/** Default preset for MUI DataGrid. For non-English locales use `createMuiDataGrid({ buttonLabels })`. */
|
|
427
|
+
exports.muiDataGrid = createMuiDataGrid();
|
package/dist/presets/rdg.d.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Locator } from '@playwright/test';
|
|
2
|
+
import { TableContext, TableConfig, ViewportStrategy, StrategyContext } from '../types';
|
|
2
3
|
/** Full strategies for React Data Grid. Use when you want to supply your own selectors: strategies: Plugins.RDG.Strategies */
|
|
3
4
|
export declare const RDGStrategies: {
|
|
4
5
|
header: (context: TableContext) => Promise<string[]>;
|
|
5
|
-
getCellLocator: ({ row, columnIndex }:
|
|
6
|
+
getCellLocator: ({ row, columnIndex }: {
|
|
7
|
+
row: Locator;
|
|
8
|
+
columnIndex: number;
|
|
9
|
+
}) => Locator;
|
|
6
10
|
navigation: {
|
|
7
|
-
goRight: ({ root
|
|
8
|
-
goLeft: ({ root
|
|
9
|
-
goDown: ({ root
|
|
10
|
-
goUp: ({ root
|
|
11
|
-
goHome: ({ root
|
|
11
|
+
goRight: ({ root }: StrategyContext) => Promise<void>;
|
|
12
|
+
goLeft: ({ root }: StrategyContext) => Promise<void>;
|
|
13
|
+
goDown: ({ root }: StrategyContext) => Promise<void>;
|
|
14
|
+
goUp: ({ root }: StrategyContext) => Promise<void>;
|
|
15
|
+
goHome: ({ root }: StrategyContext) => Promise<void>;
|
|
12
16
|
};
|
|
13
17
|
pagination: import("..").PaginationPrimitives;
|
|
14
18
|
};
|
|
@@ -18,13 +22,16 @@ export declare const RDG: Partial<TableConfig> & {
|
|
|
18
22
|
export declare const RDG2DStrategies: {
|
|
19
23
|
viewport: ViewportStrategy;
|
|
20
24
|
header: (context: TableContext) => Promise<string[]>;
|
|
21
|
-
getCellLocator: ({ row, columnIndex }:
|
|
25
|
+
getCellLocator: ({ row, columnIndex }: {
|
|
26
|
+
row: Locator;
|
|
27
|
+
columnIndex: number;
|
|
28
|
+
}) => Locator;
|
|
22
29
|
navigation: {
|
|
23
|
-
goRight: ({ root
|
|
24
|
-
goLeft: ({ root
|
|
25
|
-
goDown: ({ root
|
|
26
|
-
goUp: ({ root
|
|
27
|
-
goHome: ({ root
|
|
30
|
+
goRight: ({ root }: StrategyContext) => Promise<void>;
|
|
31
|
+
goLeft: ({ root }: StrategyContext) => Promise<void>;
|
|
32
|
+
goDown: ({ root }: StrategyContext) => Promise<void>;
|
|
33
|
+
goUp: ({ root }: StrategyContext) => Promise<void>;
|
|
34
|
+
goHome: ({ root }: StrategyContext) => Promise<void>;
|
|
28
35
|
};
|
|
29
36
|
pagination: import("..").PaginationPrimitives;
|
|
30
37
|
};
|
package/dist/presets/rdg.js
CHANGED
|
@@ -54,35 +54,35 @@ const rdgPaginationStrategy = pagination_1.PaginationStrategies.infiniteScroll({
|
|
|
54
54
|
stabilization: stabilization_1.StabilizationStrategies.contentChanged({ timeout: 5000 })
|
|
55
55
|
});
|
|
56
56
|
const rdgNavigation = {
|
|
57
|
-
goRight: async ({ root
|
|
57
|
+
goRight: async ({ root }) => {
|
|
58
58
|
await root.evaluate((el) => {
|
|
59
59
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
60
60
|
if (grid)
|
|
61
61
|
grid.scrollLeft += 150;
|
|
62
62
|
});
|
|
63
63
|
},
|
|
64
|
-
goLeft: async ({ root
|
|
64
|
+
goLeft: async ({ root }) => {
|
|
65
65
|
await root.evaluate((el) => {
|
|
66
66
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
67
67
|
if (grid)
|
|
68
68
|
grid.scrollLeft -= 150;
|
|
69
69
|
});
|
|
70
70
|
},
|
|
71
|
-
goDown: async ({ root
|
|
71
|
+
goDown: async ({ root }) => {
|
|
72
72
|
await root.evaluate((el) => {
|
|
73
73
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
74
74
|
if (grid)
|
|
75
75
|
grid.scrollTop += 35;
|
|
76
76
|
});
|
|
77
77
|
},
|
|
78
|
-
goUp: async ({ root
|
|
78
|
+
goUp: async ({ root }) => {
|
|
79
79
|
await root.evaluate((el) => {
|
|
80
80
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
81
81
|
if (grid)
|
|
82
82
|
grid.scrollTop -= 35;
|
|
83
83
|
});
|
|
84
84
|
},
|
|
85
|
-
goHome: async ({ root
|
|
85
|
+
goHome: async ({ root }) => {
|
|
86
86
|
await root.evaluate((el) => {
|
|
87
87
|
const grid = el.querySelector('[role="grid"]') || el.closest('[role="grid"]') || el;
|
|
88
88
|
if (grid) {
|
package/dist/typeContext.d.ts
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* This file is generated by scripts/embed-types.mjs
|
|
4
4
|
* It contains the raw text of types.ts to provide context for LLM prompts.
|
|
5
5
|
*/
|
|
6
|
-
export declare const TYPE_CONTEXT = "\n/**\n * Flexible selector type - can be a CSS string, function returning a Locator, or Locator itself.\n * @example\n * // String selector\n * rowSelector: 'tbody tr'\n * \n * // Function selector\n * headerSelector: (root) => root.locator('[role=\"columnheader\"]')\n */\nexport type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);\n\n/**\n * Value used to filter rows.\n * - string/number/RegExp: filter by text content of the cell.\n * - function: filter by custom locator logic within the cell.\n * @example\n * // Text filter\n * { Name: 'John' }\n * \n * // Custom locator filter (e.g. checkbox is checked)\n * { Status: (cell) => cell.locator('input:checked') }\n */\nexport type FilterValue = string | RegExp | number | ((cell: Locator) => Locator);\n\n/**\n * Function to get a cell locator given row, column info.\n * Replaces the old cellResolver.\n */\nexport type GetCellLocatorFn = (args: {\n row: Locator;\n /** The root locator passed to useTable(). Useful for re-querying stale row locators. */\n root: Locator;\n columnName: string;\n columnIndex: number;\n rowIndex?: number;\n page: Page;\n config: FinalTableConfig<any>;\n}) => Locator;\n\n/**\n * Hook called before each cell value is read in `toJSON` (and `columnOverrides.read`).\n *\n * Use this to scroll off-screen columns into view in **horizontally** virtualized tables,\n * wait for lazy-rendered content (popovers, tooltips, async cell renderers), or perform\n * any other pre-read setup that doesn't involve Y-axis scrolling.\n *\n * ---\n *\n * **\u26A0\uFE0F Y-scroll footgun \u2014 do NOT call `scrollIntoViewIfNeeded()` on row-virtualized grids.**\n *\n * `scrollIntoViewIfNeeded` adjusts *both* scroll axes. On grids that recycle DOM nodes\n * based on the Y position (MUI DataGrid, AG Grid, react-window, etc.) calling it will\n * shift the viewport vertically, unmounting the row you are currently reading and\n * silently returning stale or empty cell values for the remainder of the row.\n *\n * Safe uses:\n * - Column-only (X-axis) virtualization where rows are always in the DOM.\n * - Calling `scrollIntoViewIfNeeded` on the **header cell** only, when that header is\n * guaranteed not to trigger a Y-scroll (e.g. sticky header grids).\n *\n * For grids with **both** row and column virtualization, use the `viewport` strategy\n * instead \u2014 it drives explicit `scrollToRow` / `scrollToColumn` calls and is aware of\n * the virtualization lifecycle.\n *\n * @example\n * // Safe: column-only horizontal virtualization (rows always in DOM)\n * strategies: {\n * beforeCellRead: async ({ columnName, getHeaderCell }) => {\n * const header = await getHeaderCell(columnName);\n * await header.scrollIntoViewIfNeeded(); // only scrolls X \u2014 rows stay mounted\n * }\n * }\n *\n * @example\n * // Safe: wait for a lazy-rendered popover/tooltip before reading its text\n * strategies: {\n * beforeCellRead: async ({ cell }) => {\n * await cell.hover();\n * await cell.page().waitForSelector('.cell-tooltip', { state: 'visible' });\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 */\n// fallow-ignore-next-line unused-type\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 * How long (ms) to wait for a loading row to resolve before applying onRowLoadingTimeout.\n * When not set, loading rows are immediately skipped (backward-compatible behavior).\n */\n rowLoadingTimeout?: number;\n\n /**\n * What to do when a row is still loading after rowLoadingTimeout ms.\n * - 'skip': drop the row from results (matches legacy skip behavior)\n * - 'read-as-is': include the row even though it's still loading (default)\n * - 'throw': throw an error with row index and timeout info\n * Defaults to 'read-as-is' when rowLoadingTimeout is set.\n */\n onRowLoadingTimeout?: 'skip' | 'read-as-is' | 'throw';\n\n /**\n * Predicate called before reading each cell. Return true if the cell is still loading.\n * When cellLoadingTimeout is also set, the engine waits up to that many ms for the\n * cell to resolve before applying onCellLoadingTimeout.\n */\n isCellLoading?: (cell: import('@playwright/test').Locator, columnName: string, row: SmartRow) => Promise<boolean>;\n\n /**\n * How long (ms) to wait for a loading cell to resolve before applying onCellLoadingTimeout.\n * When not set and isCellLoading returns true, the cell is read as-is immediately.\n */\n cellLoadingTimeout?: number;\n\n /**\n * What to do when a cell is still loading after cellLoadingTimeout ms.\n * - 'skip': use empty string for this cell value\n * - 'read-as-is': read the cell content even though it's still loading (default)\n * - 'throw': throw an error with column name, row index and timeout info\n * - callback: called with (cell, columnName, row); its return value becomes the cell's string value\n * Defaults to 'read-as-is' when cellLoadingTimeout is set.\n */\n onCellLoadingTimeout?:\n | 'skip'\n | 'read-as-is'\n | 'throw'\n | ((cell: import('@playwright/test').Locator, columnName: string, row: SmartRow) => Promise<string>);\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";
|
|
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 *\n * Use this to scroll off-screen columns into view in **horizontally** virtualized tables,\n * wait for lazy-rendered content (popovers, tooltips, async cell renderers), or perform\n * any other pre-read setup that doesn't involve Y-axis scrolling.\n *\n * ---\n *\n * **\u26A0\uFE0F Y-scroll footgun \u2014 do NOT call `scrollIntoViewIfNeeded()` on row-virtualized grids.**\n *\n * `scrollIntoViewIfNeeded` adjusts *both* scroll axes. On grids that recycle DOM nodes\n * based on the Y position (MUI DataGrid, AG Grid, react-window, etc.) calling it will\n * shift the viewport vertically, unmounting the row you are currently reading and\n * silently returning stale or empty cell values for the remainder of the row.\n *\n * Safe uses:\n * - Column-only (X-axis) virtualization where rows are always in the DOM.\n * - Calling `scrollIntoViewIfNeeded` on the **header cell** only, when that header is\n * guaranteed not to trigger a Y-scroll (e.g. sticky header grids).\n *\n * For grids with **both** row and column virtualization, use the `viewport` strategy\n * instead \u2014 it drives explicit `scrollToRow` / `scrollToColumn` calls and is aware of\n * the virtualization lifecycle.\n *\n * @example\n * // Safe: column-only horizontal virtualization (rows always in DOM)\n * strategies: {\n * beforeCellRead: async ({ columnName, getHeaderCell }) => {\n * const header = await getHeaderCell(columnName);\n * await header.scrollIntoViewIfNeeded(); // only scrolls X \u2014 rows stay mounted\n * }\n * }\n *\n * @example\n * // Safe: wait for a lazy-rendered popover/tooltip before reading its text\n * strategies: {\n * beforeCellRead: async ({ cell }) => {\n * await cell.hover();\n * await cell.page().waitForSelector('.cell-tooltip', { state: 'visible' });\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 */\n// fallow-ignore-next-line unused-type\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 * How long (ms) to wait for a loading row to resolve before applying onRowLoadingTimeout.\n * When not set, loading rows are immediately skipped (backward-compatible behavior).\n */\n rowLoadingTimeout?: number;\n\n /**\n * What to do when a row is still loading after rowLoadingTimeout ms.\n * - 'skip': drop the row from results (matches legacy skip behavior)\n * - 'read-as-is': include the row even though it's still loading (default)\n * - 'throw': throw an error with row index and timeout info\n * Defaults to 'read-as-is' when rowLoadingTimeout is set.\n */\n onRowLoadingTimeout?: 'skip' | 'read-as-is' | 'throw';\n\n /**\n * Predicate called before reading each cell. Return true if the cell is still loading.\n * When cellLoadingTimeout is also set, the engine waits up to that many ms for the\n * cell to resolve before applying onCellLoadingTimeout.\n */\n isCellLoading?: (cell: import('@playwright/test').Locator, columnName: string, row: SmartRow) => Promise<boolean>;\n\n /**\n * How long (ms) to wait for a loading cell to resolve before applying onCellLoadingTimeout.\n * When not set and isCellLoading returns true, the cell is read as-is immediately.\n */\n cellLoadingTimeout?: number;\n\n /**\n * What to do when a cell is still loading after cellLoadingTimeout ms.\n * - 'skip': use empty string for this cell value\n * - 'read-as-is': read the cell content even though it's still loading (default)\n * - 'throw': throw an error with column name, row index and timeout info\n * - callback: called with (cell, columnName, row); its return value becomes the cell's string value\n * Defaults to 'read-as-is' when cellLoadingTimeout is set.\n */\n onCellLoadingTimeout?:\n | 'skip'\n | 'read-as-is'\n | 'throw'\n | ((cell: import('@playwright/test').Locator, columnName: string, row: SmartRow) => Promise<string>);\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 * Shorthand for `map()` + `reset()`. Iterates every row across all pages, applies the\n * callback (defaults to `row.toJSON()`), then resets the table back to page 1 \u2014 even if\n * the callback throws.\n *\n * @param callback - Optional map function. Defaults to `({ row }) => row.toJSON()`.\n * @param options - Same options as `map()`.\n *\n * @example\n * // Zero-arg: returns toJSON() for every row\n * const rows = await table.toArray();\n *\n * @example\n * // Custom callback\n * const names = await table.toArray(({ row }) => row.getCell('Name').innerText());\n *\n * @example\n * // With options\n * const rows = await table.toArray(({ row }) => row.toJSON(), { concurrency: 'parallel' });\n */\n toArray<R = Record<string, unknown>>(\n callback?: (ctx: RowIterationContext<T>) => R | Promise<R>,\n options?: RowIterationOptions\n ): Promise<R[]>;\n\n /**\n * Filters rows across all pages by an async predicate. Returns a SmartRowArray.\n * Rows are returned as-is \u2014 call `bringIntoView()` on each if needed.\n * Execution is sequential by default.\n *\n * @param predicate - Function receiving { row, rowIndex, stop }\n * @param options - maxPages, concurrency, dedupe, useBulkPagination\n *\n * @example\n * const active = await table.filter(async ({ row }) =>\n * await row.getCell('Status').innerText() === 'Active'\n * );\n */\n filter(\n predicate: (ctx: RowIterationContext<T>) => boolean | Promise<boolean>,\n options?: RowIterationOptions\n ): Promise<SmartRowArray<T>>;\n\n /**\n * Provides access to sorting actions and assertions.\n */\n sorting: {\n /**\n * Applies the configured sorting strategy to the specified column.\n * @param columnName The name of the column to sort.\n * @param direction The direction to sort ('asc' or 'desc').\n */\n apply(columnName: string, direction: 'asc' | 'desc'): Promise<void>;\n /**\n * Gets the current sort state of a column using the configured sorting strategy.\n * @param columnName The name of the column to check.\n * @returns A promise that resolves to 'asc', 'desc', or 'none'.\n */\n getState(columnName: string): Promise<'asc' | 'desc' | 'none'>;\n };\n\n /**\n * Generate an AI-friendly configuration prompt for debugging.\n * Outputs table HTML and TypeScript definitions to help AI assistants generate config.\n * Automatically throws an Error containing the prompt.\n */\n generateConfig: () => Promise<void>;\n\n /**\n * @deprecated Use `generateConfig()` instead. Will be removed in v7.0.0.\n */\n generateConfigPrompt: () => Promise<void>;\n}\n";
|
package/dist/typeContext.js
CHANGED
|
@@ -814,6 +814,31 @@ export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>;
|
|
|
814
814
|
options?: RowIterationOptions
|
|
815
815
|
): Promise<R[]>;
|
|
816
816
|
|
|
817
|
+
/**
|
|
818
|
+
* Shorthand for \`map()\` + \`reset()\`. Iterates every row across all pages, applies the
|
|
819
|
+
* callback (defaults to \`row.toJSON()\`), then resets the table back to page 1 — even if
|
|
820
|
+
* the callback throws.
|
|
821
|
+
*
|
|
822
|
+
* @param callback - Optional map function. Defaults to \`({ row }) => row.toJSON()\`.
|
|
823
|
+
* @param options - Same options as \`map()\`.
|
|
824
|
+
*
|
|
825
|
+
* @example
|
|
826
|
+
* // Zero-arg: returns toJSON() for every row
|
|
827
|
+
* const rows = await table.toArray();
|
|
828
|
+
*
|
|
829
|
+
* @example
|
|
830
|
+
* // Custom callback
|
|
831
|
+
* const names = await table.toArray(({ row }) => row.getCell('Name').innerText());
|
|
832
|
+
*
|
|
833
|
+
* @example
|
|
834
|
+
* // With options
|
|
835
|
+
* const rows = await table.toArray(({ row }) => row.toJSON(), { concurrency: 'parallel' });
|
|
836
|
+
*/
|
|
837
|
+
toArray<R = Record<string, unknown>>(
|
|
838
|
+
callback?: (ctx: RowIterationContext<T>) => R | Promise<R>,
|
|
839
|
+
options?: RowIterationOptions
|
|
840
|
+
): Promise<R[]>;
|
|
841
|
+
|
|
817
842
|
/**
|
|
818
843
|
* Filters rows across all pages by an async predicate. Returns a SmartRowArray.
|
|
819
844
|
* Rows are returned as-is — call \`bringIntoView()\` on each if needed.
|
package/dist/types.d.ts
CHANGED
|
@@ -740,6 +740,27 @@ export interface TableResult<T = any> extends AsyncIterable<{
|
|
|
740
740
|
* }, { concurrency: 'sequential' });
|
|
741
741
|
*/
|
|
742
742
|
map<R>(callback: (ctx: RowIterationContext<T>) => R | Promise<R>, options?: RowIterationOptions): Promise<R[]>;
|
|
743
|
+
/**
|
|
744
|
+
* Shorthand for `map()` + `reset()`. Iterates every row across all pages, applies the
|
|
745
|
+
* callback (defaults to `row.toJSON()`), then resets the table back to page 1 — even if
|
|
746
|
+
* the callback throws.
|
|
747
|
+
*
|
|
748
|
+
* @param callback - Optional map function. Defaults to `({ row }) => row.toJSON()`.
|
|
749
|
+
* @param options - Same options as `map()`.
|
|
750
|
+
*
|
|
751
|
+
* @example
|
|
752
|
+
* // Zero-arg: returns toJSON() for every row
|
|
753
|
+
* const rows = await table.toArray();
|
|
754
|
+
*
|
|
755
|
+
* @example
|
|
756
|
+
* // Custom callback
|
|
757
|
+
* const names = await table.toArray(({ row }) => row.getCell('Name').innerText());
|
|
758
|
+
*
|
|
759
|
+
* @example
|
|
760
|
+
* // With options
|
|
761
|
+
* const rows = await table.toArray(({ row }) => row.toJSON(), { concurrency: 'parallel' });
|
|
762
|
+
*/
|
|
763
|
+
toArray<R = Record<string, unknown>>(callback?: (ctx: RowIterationContext<T>) => R | Promise<R>, options?: RowIterationOptions): Promise<R[]>;
|
|
743
764
|
/**
|
|
744
765
|
* Filters rows across all pages by an async predicate. Returns a SmartRowArray.
|
|
745
766
|
* Rows are returned as-is — call `bringIntoView()` on each if needed.
|
package/dist/useTable.js
CHANGED
|
@@ -469,6 +469,16 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
469
469
|
getCurrentPageIndex: () => tableState.currentPageIndex,
|
|
470
470
|
}, callback, options);
|
|
471
471
|
},
|
|
472
|
+
toArray: async (callback, options = {}) => {
|
|
473
|
+
log(`toArray: options=${safeStringify(options)}`);
|
|
474
|
+
const cb = callback !== null && callback !== void 0 ? callback : (({ row }) => row.toJSON());
|
|
475
|
+
try {
|
|
476
|
+
return await result.map(cb, options);
|
|
477
|
+
}
|
|
478
|
+
finally {
|
|
479
|
+
await result.reset();
|
|
480
|
+
}
|
|
481
|
+
},
|
|
472
482
|
filter: async (predicate, options = {}) => {
|
|
473
483
|
log(`filter: options=${safeStringify(options)}`);
|
|
474
484
|
await _autoInit();
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { TableConfig } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Deep-merges two `TableConfig` objects.
|
|
4
|
+
*
|
|
5
|
+
* Merge semantics:
|
|
6
|
+
* - Top-level keys (`rowSelector`, `maxPages`, etc.): overrides win — same as `{ ...base, ...overrides }`.
|
|
7
|
+
* - `strategies`: each sub-key is merged independently. Object-valued strategies (`loading`,
|
|
8
|
+
* `viewport`, `pagination`) are merged key-by-key so that neither side silently wipes the
|
|
9
|
+
* other's settings. Function-valued strategies (`header`, `dedupe`, `getCellLocator`, etc.)
|
|
10
|
+
* are replaced in full by the override value (a function cannot be meaningfully object-spread).
|
|
11
|
+
* - `columnOverrides`: merged key-by-key (each column entry merged independently).
|
|
12
|
+
* - Everything else: overrides win (shallow merge).
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const config = mergeTableConfig(baseConfig, {
|
|
16
|
+
* maxPages: 20,
|
|
17
|
+
* strategies: {
|
|
18
|
+
* loading: { isTableLoading: myLoadingFn },
|
|
19
|
+
* },
|
|
20
|
+
* });
|
|
21
|
+
*/
|
|
22
|
+
export declare function mergeTableConfig<T = any>(base: TableConfig<T>, overrides: TableConfig<T>): TableConfig<T>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mergeTableConfig = mergeTableConfig;
|
|
4
|
+
/**
|
|
5
|
+
* Deep-merges two `TableConfig` objects.
|
|
6
|
+
*
|
|
7
|
+
* Merge semantics:
|
|
8
|
+
* - Top-level keys (`rowSelector`, `maxPages`, etc.): overrides win — same as `{ ...base, ...overrides }`.
|
|
9
|
+
* - `strategies`: each sub-key is merged independently. Object-valued strategies (`loading`,
|
|
10
|
+
* `viewport`, `pagination`) are merged key-by-key so that neither side silently wipes the
|
|
11
|
+
* other's settings. Function-valued strategies (`header`, `dedupe`, `getCellLocator`, etc.)
|
|
12
|
+
* are replaced in full by the override value (a function cannot be meaningfully object-spread).
|
|
13
|
+
* - `columnOverrides`: merged key-by-key (each column entry merged independently).
|
|
14
|
+
* - Everything else: overrides win (shallow merge).
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* const config = mergeTableConfig(baseConfig, {
|
|
18
|
+
* maxPages: 20,
|
|
19
|
+
* strategies: {
|
|
20
|
+
* loading: { isTableLoading: myLoadingFn },
|
|
21
|
+
* },
|
|
22
|
+
* });
|
|
23
|
+
*/
|
|
24
|
+
function mergeTableConfig(base, overrides) {
|
|
25
|
+
var _a, _b, _c, _d;
|
|
26
|
+
const result = Object.assign(Object.assign({}, base), overrides);
|
|
27
|
+
// Deep-merge strategies one level down
|
|
28
|
+
if (base.strategies || overrides.strategies) {
|
|
29
|
+
result.strategies = Object.assign(Object.assign({}, base.strategies), overrides.strategies);
|
|
30
|
+
// For strategy sub-keys that are plain objects on *both* sides, merge key-by-key
|
|
31
|
+
// so that e.g. base.strategies.loading and overrides.strategies.loading are combined.
|
|
32
|
+
// Function values (pagination, header, dedupe, getCellLocator, etc.) are replaced, not merged.
|
|
33
|
+
const strategyKeys = new Set([
|
|
34
|
+
...Object.keys((_a = base.strategies) !== null && _a !== void 0 ? _a : {}),
|
|
35
|
+
...Object.keys((_b = overrides.strategies) !== null && _b !== void 0 ? _b : {}),
|
|
36
|
+
]);
|
|
37
|
+
for (const key of strategyKeys) {
|
|
38
|
+
const baseVal = (_c = base.strategies) === null || _c === void 0 ? void 0 : _c[key];
|
|
39
|
+
const overrideVal = (_d = overrides.strategies) === null || _d === void 0 ? void 0 : _d[key];
|
|
40
|
+
if (baseVal !== undefined &&
|
|
41
|
+
overrideVal !== undefined &&
|
|
42
|
+
typeof baseVal === 'object' &&
|
|
43
|
+
typeof overrideVal === 'object' &&
|
|
44
|
+
!Array.isArray(baseVal) &&
|
|
45
|
+
!Array.isArray(overrideVal) &&
|
|
46
|
+
typeof baseVal !== 'function' &&
|
|
47
|
+
typeof overrideVal !== 'function') {
|
|
48
|
+
// The spread result can't be expressed as the union of all strategy types;
|
|
49
|
+
// the runtime object-check above guarantees safety.
|
|
50
|
+
result.strategies[key] =
|
|
51
|
+
Object.assign(Object.assign({}, baseVal), overrideVal);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Deep-merge columnOverrides one level down (each column entry merged independently)
|
|
56
|
+
if (base.columnOverrides || overrides.columnOverrides) {
|
|
57
|
+
result.columnOverrides = Object.assign(Object.assign({}, base.columnOverrides), overrides.columnOverrides);
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
}
|