@cerios/playwright-table 1.1.1 → 2.0.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.mjs CHANGED
@@ -1,5 +1,24 @@
1
- // src/playwright-table.ts
2
- import { expect as expect2 } from "@playwright/test";
1
+ // src/polling.ts
2
+ async function pollTable(fn, options) {
3
+ var _a, _b;
4
+ if (!options) {
5
+ options = {};
6
+ }
7
+ const timeout = (_a = options.timeout) != null ? _a : 3e4;
8
+ const interval = (_b = options.interval) != null ? _b : 100;
9
+ const startTime = Date.now();
10
+ let lastError;
11
+ while (Date.now() - startTime < timeout) {
12
+ try {
13
+ await fn();
14
+ return;
15
+ } catch (err) {
16
+ lastError = err;
17
+ await new Promise((resolve) => setTimeout(resolve, interval));
18
+ }
19
+ }
20
+ throw lastError || new Error("Playwright Tables: Polling timeout reached");
21
+ }
3
22
 
4
23
  // src/cell-content-type.ts
5
24
  var CellContentType = /* @__PURE__ */ ((CellContentType2) => {
@@ -10,43 +29,127 @@ var CellContentType = /* @__PURE__ */ ((CellContentType2) => {
10
29
 
11
30
  // src/table-utils.ts
12
31
  var TableUtils = class {
32
+ constructor() {
33
+ }
34
+ /**
35
+ * Extracts text content from a table cell.
36
+ * @param cell - The Playwright locator for the cell.
37
+ * @param cellContentType - The type of content to extract (InnerText or TextContent).
38
+ * @returns The trimmed text content of the cell, or empty string if no content.
39
+ * @throws Error if the cell locator doesn't exist in the DOM.
40
+ */
13
41
  static async getCellContent(cell, cellContentType) {
14
- const content = cellContentType === "innerText" /* InnerText */ ? await cell.innerText() : await cell.textContent();
15
- return (content == null ? void 0 : content.trim()) || "";
42
+ try {
43
+ const count = await cell.count();
44
+ if (count === 0) {
45
+ throw new Error("Cell locator does not exist in the DOM");
46
+ }
47
+ const content = cellContentType === "innerText" /* InnerText */ ? await cell.innerText() : await cell.textContent();
48
+ return (content == null ? void 0 : content.trim()) || "";
49
+ } catch (error) {
50
+ const locatorDescription = this.getLocatorDescription(cell);
51
+ throw new Error(
52
+ `Failed to get cell content.
53
+ Locator: ${locatorDescription}
54
+ Content type: ${cellContentType}
55
+ Error: ${error instanceof Error ? error.message : String(error)}`
56
+ );
57
+ }
16
58
  }
59
+ /**
60
+ * Parses rowspan and colspan attributes from a table cell.
61
+ * Fetches both attributes in parallel for optimal performance.
62
+ * @param cell - The Playwright locator for the cell.
63
+ * @returns Object containing rowspan and colspan values (defaults to 1 if not present).
64
+ * @throws Error if attributes contain invalid values (non-numeric or less than 1).
65
+ */
17
66
  static async parseSpanAttributes(cell) {
18
- return {
19
- rowspan: parseInt(await cell.getAttribute("rowspan") || "1", 10),
20
- colspan: parseInt(await cell.getAttribute("colspan") || "1", 10)
21
- };
67
+ try {
68
+ const [rowspanAttr, colspanAttr] = await Promise.all([
69
+ cell.getAttribute("rowspan"),
70
+ cell.getAttribute("colspan")
71
+ ]);
72
+ const rowspan = parseInt(rowspanAttr || "1", 10);
73
+ const colspan = parseInt(colspanAttr || "1", 10);
74
+ if (isNaN(rowspan) || rowspan < 1) {
75
+ throw new Error(`Invalid rowspan attribute: "${rowspanAttr}". Expected positive integer.`);
76
+ }
77
+ if (isNaN(colspan) || colspan < 1) {
78
+ throw new Error(`Invalid colspan attribute: "${colspanAttr}". Expected positive integer.`);
79
+ }
80
+ return { rowspan, colspan };
81
+ } catch (error) {
82
+ const locatorDescription = this.getLocatorDescription(cell);
83
+ throw new Error(
84
+ `Failed to parse span attributes.
85
+ Locator: ${locatorDescription}
86
+ Error: ${error instanceof Error ? error.message : String(error)}`
87
+ );
88
+ }
22
89
  }
23
- static castContent(value) {
24
- const trimmedValue = value.trim();
25
- if (trimmedValue === "") return "";
26
- const lowerValue = trimmedValue.toLowerCase();
27
- if (lowerValue === "true") return true;
28
- if (lowerValue === "false") return false;
29
- const num = Number(trimmedValue);
30
- return isNaN(num) ? trimmedValue : num;
90
+ /**
91
+ * Extracts a human-readable locator description from a Playwright Locator.
92
+ * This captures Playwright's internal selector chain for better error messages.
93
+ * @param locator - The Playwright locator to describe.
94
+ * @returns A string representation of the locator's selector chain.
95
+ */
96
+ static getLocatorDescription(locator) {
97
+ const locatorString = locator.toString();
98
+ return locatorString;
31
99
  }
32
100
  };
33
101
 
34
102
  // src/table-body.ts
35
103
  var TableBody = class {
104
+ constructor() {
105
+ }
106
+ /**
107
+ * Extracts body rows from a table with proper handling of rowspan and colspan.
108
+ *
109
+ * @param rowLocator - The Playwright locator for body rows.
110
+ * @param columnsSelector - CSS selector for locating columns within rows (e.g., "td").
111
+ * @param bodyRowsOptions - Optional configuration for cell content extraction.
112
+ * @param bodyRowsOptions.cellContentType - The type of content to extract (InnerText or TextContent).
113
+ * @returns Promise resolving to an array of processed body rows.
114
+ * @throws Error if columnsSelector is empty or if row processing fails.
115
+ *
116
+ * @example
117
+ * const rows = await TableBody.getRows(
118
+ * page.locator('tbody tr'),
119
+ * 'td',
120
+ * { cellContentType: CellContentType.TextContent }
121
+ * );
122
+ */
36
123
  static async getRows(rowLocator, columnsSelector, bodyRowsOptions) {
124
+ if (!columnsSelector || columnsSelector.trim() === "") {
125
+ throw new Error("columnsSelector cannot be empty");
126
+ }
127
+ const locatorDescription = rowLocator.toString();
37
128
  const rows = [];
38
129
  const rowsCount = await rowLocator.count();
130
+ if (rowsCount === 0) {
131
+ return rows;
132
+ }
39
133
  const spannedCells = {};
40
134
  for (let rowIndex = 0; rowIndex < rowsCount; rowIndex++) {
41
- const row = rowLocator.nth(rowIndex);
42
- const columns = await this.extractColumns(
43
- row,
44
- columnsSelector,
45
- rowIndex,
46
- spannedCells,
47
- bodyRowsOptions == null ? void 0 : bodyRowsOptions.cellContentType
48
- );
49
- rows.push(columns);
135
+ try {
136
+ const row = rowLocator.nth(rowIndex);
137
+ const columns = await this.extractColumns(
138
+ row,
139
+ columnsSelector,
140
+ rowIndex,
141
+ spannedCells,
142
+ bodyRowsOptions == null ? void 0 : bodyRowsOptions.cellContentType
143
+ );
144
+ rows.push(columns);
145
+ } catch (error) {
146
+ throw new Error(
147
+ `Failed to process body row at index ${rowIndex}.
148
+ Body row locator: ${locatorDescription}
149
+ Columns selector: "${columnsSelector}"
150
+ Error: ${error instanceof Error ? error.message : String(error)}`
151
+ );
152
+ }
50
153
  }
51
154
  return rows;
52
155
  }
@@ -54,36 +157,77 @@ var TableBody = class {
54
157
  const columns = [];
55
158
  const columnLocators = row.locator(columnsSelector);
56
159
  const columnCount = await columnLocators.count();
160
+ if (columnCount === 0) {
161
+ this.applySpannedCells(spannedCells, rowIndex, columns);
162
+ return columns;
163
+ }
164
+ const cellDataPromises = [];
57
165
  for (let colIndex = 0; colIndex < columnCount; colIndex++) {
58
- await this.processColumn(
59
- columnLocators.nth(colIndex),
60
- colIndex,
61
- columns,
62
- rowIndex,
63
- spannedCells,
64
- cellContentType
65
- );
166
+ cellDataPromises.push(this.fetchCellData(columnLocators.nth(colIndex), cellContentType));
167
+ }
168
+ const cellDataArray = await Promise.all(cellDataPromises);
169
+ const spannedPositions = /* @__PURE__ */ new Set();
170
+ if (spannedCells[rowIndex]) {
171
+ spannedCells[rowIndex].forEach((_, colIndex) => {
172
+ if (spannedCells[rowIndex][colIndex] !== void 0) {
173
+ spannedPositions.add(colIndex);
174
+ }
175
+ });
176
+ }
177
+ let actualColIndex = 0;
178
+ for (let domCellIndex = 0; domCellIndex < columnCount; domCellIndex++) {
179
+ while (spannedPositions.has(actualColIndex)) {
180
+ actualColIndex++;
181
+ }
182
+ const cellData = cellDataArray[domCellIndex];
183
+ this.processCellData(cellData, actualColIndex, columns, rowIndex, spannedCells);
184
+ actualColIndex += cellData.colspan;
66
185
  }
67
186
  this.applySpannedCells(spannedCells, rowIndex, columns);
68
187
  return columns;
69
188
  }
70
- static async processColumn(column, colIndex, columns, rowIndex, spannedCells, cellContentType = "innerText" /* InnerText */) {
71
- const content = await TableUtils.getCellContent(column, cellContentType);
72
- const castedContent = TableUtils.castContent(content);
73
- const { rowspan, colspan } = await TableUtils.parseSpanAttributes(column);
189
+ /**
190
+ * Fetches cell content and span attributes in parallel.
191
+ * This method performs DOM operations that can be parallelized across multiple cells.
192
+ */
193
+ static async fetchCellData(column, cellContentType = "innerText" /* InnerText */) {
194
+ const [content, spanAttributes] = await Promise.all([
195
+ TableUtils.getCellContent(column, cellContentType),
196
+ TableUtils.parseSpanAttributes(column)
197
+ ]);
198
+ return {
199
+ content,
200
+ rowspan: spanAttributes.rowspan,
201
+ colspan: spanAttributes.colspan
202
+ };
203
+ }
204
+ /**
205
+ * Processes pre-fetched cell data and applies it to the columns array.
206
+ * This method is purely computational and doesn't perform any DOM operations.
207
+ */
208
+ static processCellData(cellData, colIndex, columns, rowIndex, spannedCells) {
209
+ const { content, rowspan, colspan } = cellData;
210
+ if (colIndex < 0) {
211
+ throw new Error(`Invalid column index: ${colIndex}. Must be non-negative.`);
212
+ }
213
+ if (rowIndex < 0) {
214
+ throw new Error(`Invalid row index: ${rowIndex}. Must be non-negative.`);
215
+ }
74
216
  for (let span = 0; span < colspan; span++) {
75
- columns[colIndex + span] = castedContent;
217
+ columns[colIndex + span] = content;
76
218
  }
77
219
  if (rowspan > 1) {
78
- this.storeSpannedCells(rowIndex, colIndex, rowspan, castedContent, spannedCells);
220
+ this.storeSpannedCells(rowIndex, colIndex, rowspan, colspan, content, spannedCells);
79
221
  }
80
222
  }
81
- static storeSpannedCells(rowIndex, colIndex, rowspan, content, spannedCells) {
82
- for (let span = 1; span < rowspan; span++) {
83
- if (!spannedCells[rowIndex + span]) {
84
- spannedCells[rowIndex + span] = [];
223
+ static storeSpannedCells(rowIndex, colIndex, rowspan, colspan, content, spannedCells) {
224
+ for (let rowSpan = 1; rowSpan < rowspan; rowSpan++) {
225
+ if (!spannedCells[rowIndex + rowSpan]) {
226
+ spannedCells[rowIndex + rowSpan] = [];
227
+ }
228
+ for (let colSpan = 0; colSpan < colspan; colSpan++) {
229
+ spannedCells[rowIndex + rowSpan][colIndex + colSpan] = content;
85
230
  }
86
- spannedCells[rowIndex + span][colIndex] = content;
87
231
  }
88
232
  }
89
233
  static applySpannedCells(spannedCells, rowIndex, columns) {
@@ -99,14 +243,48 @@ var TableBody = class {
99
243
 
100
244
  // src/table-header.ts
101
245
  var TableHeader = class {
246
+ constructor() {
247
+ }
248
+ /**
249
+ * Extracts header rows from a table with optional processing for colspan, rowspan, and duplicates.
250
+ *
251
+ * @param headerRowLocator - The Playwright locator for header rows.
252
+ * @param columnsSelector - CSS selector for locating header columns (e.g., "th").
253
+ * @param headerRowOptions - Optional configuration for header processing.
254
+ * @returns Promise resolving to an array of processed header rows.
255
+ * @throws Error if columnsSelector is empty or if no header rows are found.
256
+ *
257
+ * @example
258
+ * const headers = await TableHeader.getRows(
259
+ * page.locator('thead tr'),
260
+ * 'th',
261
+ * { duplicateSuffix: true, colspan: { enabled: true } }
262
+ * );
263
+ */
102
264
  static async getRows(headerRowLocator, columnsSelector, headerRowOptions) {
265
+ if (!columnsSelector || columnsSelector.trim() === "") {
266
+ throw new Error("columnsSelector cannot be empty");
267
+ }
268
+ const locatorDescription = headerRowLocator.toString();
103
269
  const options = this.getDefaultOptions(headerRowOptions);
104
270
  const rows = await headerRowLocator.all();
105
271
  const headerRows = [];
272
+ if (rows.length === 0) {
273
+ return headerRows;
274
+ }
106
275
  const rowSpans = /* @__PURE__ */ new Map();
107
- for (const row of rows) {
108
- const headerRow = await this.processRow(row, columnsSelector, rowSpans, options);
109
- headerRows.push(headerRow);
276
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
277
+ try {
278
+ const headerRow = await this.processRow(rows[rowIndex], columnsSelector, rowSpans, options);
279
+ headerRows.push(headerRow);
280
+ } catch (error) {
281
+ throw new Error(
282
+ `Failed to process header row at index ${rowIndex}.
283
+ Header row locator: ${locatorDescription}
284
+ Columns selector: "${columnsSelector}"
285
+ Error: ${error instanceof Error ? error.message : String(error)}`
286
+ );
287
+ }
110
288
  }
111
289
  this.applyColspanOptions(headerRows, options);
112
290
  this.applyDuplicateSuffix(headerRows, options);
@@ -127,24 +305,53 @@ var TableHeader = class {
127
305
  static async processRow(row, columnsSelector, rowSpans, options) {
128
306
  const headerRow = [];
129
307
  const cells = await row.locator(columnsSelector).all();
308
+ if (cells.length === 0) {
309
+ return headerRow;
310
+ }
311
+ const cellDataArray = await Promise.all(cells.map((cell) => this.fetchHeaderCellData(cell, options.cellContentType)));
130
312
  let columnIndex = 0;
131
- for (const cell of cells) {
132
- columnIndex = await this.processCell(cell, headerRow, rowSpans, columnIndex, options);
313
+ for (let i = 0; i < cellDataArray.length; i++) {
314
+ columnIndex = this.processHeaderCellData(
315
+ cellDataArray[i],
316
+ headerRow,
317
+ rowSpans,
318
+ columnIndex,
319
+ options.emptyCellReplacement
320
+ );
133
321
  }
134
322
  this.addRemainingRowSpans(headerRow, rowSpans, columnIndex);
135
323
  return headerRow;
136
324
  }
137
- static async processCell(cell, headerRow, rowSpans, columnIndex, options) {
325
+ /**
326
+ * Fetches header cell content and span attributes in parallel.
327
+ * This method performs DOM operations that can be parallelized across multiple cells.
328
+ */
329
+ static async fetchHeaderCellData(cell, cellContentType) {
330
+ const [text, spanAttributes] = await Promise.all([
331
+ TableUtils.getCellContent(cell, cellContentType),
332
+ TableUtils.parseSpanAttributes(cell)
333
+ ]);
334
+ return {
335
+ text,
336
+ rowspan: spanAttributes.rowspan,
337
+ colspan: spanAttributes.colspan
338
+ };
339
+ }
340
+ /**
341
+ * Processes pre-fetched header cell data and applies it to the header row.
342
+ * This method is purely computational and doesn't perform any DOM operations.
343
+ */
344
+ static processHeaderCellData(cellData, headerRow, rowSpans, columnIndex, emptyCellReplacement) {
138
345
  while (rowSpans.has(columnIndex)) {
139
346
  headerRow.push(rowSpans.get(columnIndex));
140
347
  rowSpans.delete(columnIndex);
141
348
  columnIndex++;
142
349
  }
143
- let text = await TableUtils.getCellContent(cell, options.cellContentType);
144
- if (!text && options.emptyCellReplacement) {
145
- text = "{{Empty}}";
350
+ let text = cellData.text;
351
+ if (!text && emptyCellReplacement) {
352
+ text = this.EMPTY_CELL_PLACEHOLDER;
146
353
  }
147
- const { colspan, rowspan } = await TableUtils.parseSpanAttributes(cell);
354
+ const { colspan, rowspan } = cellData;
148
355
  headerRow.push(text);
149
356
  this.handleColspan(headerRow, text, colspan);
150
357
  this.handleRowspan(rowSpans, text, columnIndex, colspan, rowspan);
@@ -152,7 +359,7 @@ var TableHeader = class {
152
359
  }
153
360
  static handleColspan(headerRow, text, colspan) {
154
361
  for (let i = 1; i < colspan; i++) {
155
- headerRow.push(`${text}__C${i}`);
362
+ headerRow.push(`${text}${this.COLSPAN_SUFFIX_PREFIX}${i}`);
156
363
  }
157
364
  }
158
365
  static handleRowspan(rowSpans, text, columnIndex, colspan, rowspan) {
@@ -178,20 +385,15 @@ var TableHeader = class {
178
385
  }
179
386
  }
180
387
  static removeColspanCells(headerRows) {
181
- for (const headerRow of headerRows) {
182
- for (let i = 0; i < headerRow.length; i++) {
183
- if (/__C\d/.test(headerRow[i])) {
184
- headerRow.splice(i, 1);
185
- i--;
186
- }
187
- }
388
+ for (let i = 0; i < headerRows.length; i++) {
389
+ headerRows[i] = headerRows[i].filter((cell) => !this.COLSPAN_PATTERN.test(cell));
188
390
  }
189
391
  }
190
392
  static removeColspanSuffix(headerRows) {
191
393
  for (const headerRow of headerRows) {
192
394
  for (let i = 0; i < headerRow.length; i++) {
193
- if (/__C\d/.test(headerRow[i])) {
194
- headerRow[i] = headerRow[i].replace(/__C\d/, "");
395
+ if (this.COLSPAN_PATTERN.test(headerRow[i])) {
396
+ headerRow[i] = headerRow[i].replace(this.COLSPAN_PATTERN, "");
195
397
  }
196
398
  }
197
399
  }
@@ -202,10 +404,10 @@ var TableHeader = class {
202
404
  const headerCountMap = /* @__PURE__ */ new Map();
203
405
  for (let i = 0; i < headerRow.length; i++) {
204
406
  const header = headerRow[i];
205
- if (headerCountMap.has(header)) {
206
- const count = headerCountMap.get(header);
207
- headerRow[i] = `${header}__D${count}`;
208
- headerCountMap.set(header, count + 1);
407
+ const currentCount = headerCountMap.get(header);
408
+ if (currentCount !== void 0) {
409
+ headerRow[i] = `${header}${this.DUPLICATE_SUFFIX_PREFIX}${currentCount}`;
410
+ headerCountMap.set(header, currentCount + 1);
209
411
  } else {
210
412
  headerCountMap.set(header, 1);
211
413
  }
@@ -213,125 +415,193 @@ var TableHeader = class {
213
415
  }
214
416
  }
215
417
  };
216
-
217
- // src/table-wait.ts
218
- import { expect } from "@playwright/test";
219
- var TableWait = class {
220
- static async waitForRows(rowLocator, cellSelector, rowKind, options) {
221
- const validateCellsWithContent = async () => {
222
- const cells = await rowLocator.locator(cellSelector).all();
223
- const cellsWithContent = (await Promise.all(
224
- cells.map(async (cell) => {
225
- const content = await cell.textContent();
226
- return content !== null && content.trim() !== "" ? cell : null;
227
- })
228
- )).filter((cell) => cell !== null);
229
- expect(cellsWithContent.length, `No ${rowKind} cells with content found`).toBeGreaterThan(0);
230
- };
231
- const validateRowAmount = (rows2, expectedAmount) => {
232
- expect(rows2.length, `Expected ${expectedAmount} ${rowKind} rows, but found ${rows2.length}`).toBe(expectedAmount);
233
- };
234
- const validateCellCount = async (rows2, expectedCount) => {
235
- const rowsWithMatchingCells = (await Promise.all(
236
- rows2.map(async (row) => {
237
- const cellCount = await row.locator(cellSelector).count();
238
- return cellCount === expectedCount ? row : null;
239
- })
240
- )).filter((row) => row !== null);
241
- expect(
242
- rowsWithMatchingCells.length,
243
- `Expected amount of ${expectedCount} ${rowKind} cells for row not found`
244
- ).toBeGreaterThan(0);
245
- };
246
- const validateCellContentCount = async (rows2, expectedContentCount) => {
247
- const rowsWithMatchingContent = (await Promise.all(
248
- rows2.map(async (row) => {
249
- const cells = await row.locator(cellSelector).all();
250
- const cellsWithContent = (await Promise.all(
251
- cells.map(async (cell) => {
252
- const content = await cell.textContent();
253
- return content !== null && content.trim() !== "" ? cell : null;
254
- })
255
- )).filter((cell) => cell !== null);
256
- return cellsWithContent.length === expectedContentCount ? row : null;
257
- })
258
- )).filter((row) => row !== null);
259
- expect(
260
- rowsWithMatchingContent.length,
261
- `Expected amount of ${expectedContentCount} ${rowKind} cells with content for row not found`
262
- ).toBeGreaterThan(0);
263
- };
264
- const rows = await rowLocator.all();
265
- if (options == null ? void 0 : options.row) {
266
- if (options.row.amount) {
267
- validateRowAmount(rows, options.row.amount);
268
- } else {
269
- expect(rows.length, `No ${rowKind} rows found`).toBeGreaterThan(0);
270
- }
271
- if (options.row.cell) {
272
- if (options.row.cell.totalCount) {
273
- await validateCellCount(rows, options.row.cell.totalCount);
274
- }
275
- if (options.row.cell.contentCount) {
276
- await validateCellContentCount(rows, options.row.cell.contentCount);
277
- } else {
278
- await validateCellsWithContent();
279
- }
280
- } else {
281
- await validateCellsWithContent();
282
- }
283
- } else {
284
- await validateCellsWithContent();
285
- }
286
- }
287
- };
418
+ TableHeader.EMPTY_CELL_PLACEHOLDER = "{{Empty}}";
419
+ TableHeader.COLSPAN_SUFFIX_PREFIX = "__C";
420
+ TableHeader.DUPLICATE_SUFFIX_PREFIX = "__D";
421
+ TableHeader.COLSPAN_PATTERN = /__C\d+/;
288
422
 
289
423
  // src/playwright-table.ts
290
424
  var PlaywrightTable = class {
425
+ /**
426
+ * Creates an instance of the table handler with customizable selectors for headers and rows.
427
+ *
428
+ * @param _tableLocator - The Playwright `Locator` pointing to the root table element.
429
+ * @param _options - Optional configuration for customizing header and row selectors.
430
+ * @param _options.header - Options for header row and columns.
431
+ * @param _options.header.setMainHeaderRow - (Optional) Index of the main header row if multiple header rows exist.
432
+ * @param _options.header.rowSelector - (Optional) CSS selector for locating header rows. Defaults to `"thead>tr"`.
433
+ * @param _options.header.columnSelector - (Optional) CSS selector for locating header columns. Defaults to `"th"`.
434
+ * @param _options.row - Options for body rows and columns.
435
+ * @param _options.row.rowSelector - (Optional) CSS selector for locating body rows. Defaults to `"tbody>tr"`.
436
+ * @param _options.row.columnSelector - (Optional) CSS selector for locating body columns. Defaults to `"td"`.
437
+ *
438
+ * @example
439
+ * const table = new PlaywrightTable(
440
+ * page.locator('table.my-table'),
441
+ * {
442
+ * header: {
443
+ * rowSelector: 'thead tr.header',
444
+ * columnSelector: 'th.header-cell'
445
+ * },
446
+ * row: {
447
+ * rowSelector: 'tbody tr.data-row',
448
+ * columnSelector: 'td.data-cell'
449
+ * }
450
+ * }
451
+ * );
452
+ */
291
453
  constructor(_tableLocator, _options) {
292
454
  this._tableLocator = _tableLocator;
293
455
  this._options = _options;
294
- this._headers = [];
295
- this._rows = [];
296
456
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
297
457
  this._headerRowLocator = this._tableLocator.locator((_c = (_b = (_a = this._options) == null ? void 0 : _a.header) == null ? void 0 : _b.rowSelector) != null ? _c : "thead>tr");
298
458
  this._headerColumnSelector = (_f = (_e = (_d = this._options) == null ? void 0 : _d.header) == null ? void 0 : _e.columnSelector) != null ? _f : "th";
299
459
  this._bodyRowLocator = this._tableLocator.locator((_i = (_h = (_g = this._options) == null ? void 0 : _g.row) == null ? void 0 : _h.rowSelector) != null ? _i : "tbody>tr");
300
460
  this._bodyRowColumnSelector = (_l = (_k = (_j = this._options) == null ? void 0 : _j.row) == null ? void 0 : _k.columnSelector) != null ? _l : "td";
301
461
  }
462
+ /**
463
+ * Retrieves all header rows of the table.
464
+ * @param options - Optional parameters for header row parsing configuration.
465
+ * @returns A promise that resolves to an array of header rows.
466
+ * @throws Error if no header rows found after table loads.
467
+ *
468
+ * @example
469
+ * // Get headers with colspan enabled
470
+ * const headers = await table.getHeaderRows({
471
+ * colspan: { enabled: true, suffix: true },
472
+ * duplicateSuffix: true
473
+ * });
474
+ *
475
+ * @see {@link getMainHeaderRow} for getting only the main header row
476
+ * @see {@link HeaderRowOptions} for all available configuration options
477
+ */
302
478
  async getHeaderRows(options) {
303
- await this.load(options);
304
- return this._headers;
479
+ const table = await this.getTable({
480
+ headerRowOptions: options
481
+ });
482
+ return table.headerRows;
305
483
  }
484
+ /**
485
+ * Retrieves the main header row of the table.
486
+ * By default, uses the last header row if multiple exist. Can be customized via constructor.
487
+ * @param options - Optional parameters for header row parsing configuration.
488
+ * @returns A promise that resolves to the main header row.
489
+ * @throws Error if no header rows available.
490
+ * @throws Error if setMainHeaderRow index is out of bounds (negative or >= header row count).
491
+ *
492
+ * @example
493
+ * // Get main header with custom index set in constructor
494
+ * const table = new PlaywrightTable(page.locator('table'), {
495
+ * header: { setMainHeaderRow: 0 } // Use first row as main header
496
+ * });
497
+ * const mainHeader = await table.getMainHeaderRow();
498
+ *
499
+ * @see {@link getHeaderRows} for getting all header rows
500
+ */
306
501
  async getMainHeaderRow(options) {
307
- var _a, _b;
308
- const headerRows = await this.getHeaderRows(options);
309
- const headers = ((_b = (_a = this._options) == null ? void 0 : _a.header) == null ? void 0 : _b.setMainHeaderRow) ? headerRows[this._options.header.setMainHeaderRow] : headerRows[this._headers.length - 1];
310
- return headers;
502
+ const table = await this.getTable({
503
+ headerRowOptions: options
504
+ });
505
+ return this.mainHeaderRow(table.headerRows);
311
506
  }
507
+ /**
508
+ * Retrieves all body rows of the table.
509
+ * @param options - Optional configuration for body row parsing.
510
+ * @param options.cellContentType - Content extraction type. See {@link CellContentType}. Defaults to InnerText.
511
+ * @returns A promise that resolves to an array of body rows.
512
+ * @throws Error if no body rows found after table loads.
513
+ *
514
+ * @example
515
+ * // Get body rows with TextContent (includes hidden elements)
516
+ * const rows = await table.getBodyRows({
517
+ * cellContentType: CellContentType.TextContent
518
+ * });
519
+ *
520
+ * @example
521
+ * // Get body rows with default InnerText
522
+ * const rows = await table.getBodyRows();
523
+ */
312
524
  async getBodyRows(options) {
313
- await this.load({ ...options, headerRowOptions: { colspan: { enabled: true } } });
314
- return this._rows;
525
+ const table = await this.getTable({
526
+ bodyRowOptions: options,
527
+ headerRowOptions: {
528
+ colspan: { enabled: true }
529
+ }
530
+ });
531
+ return table.bodyRows;
315
532
  }
533
+ /**
534
+ * Retrieves a specific cell locator in the body of the table by row and column index.
535
+ * @param rowNumber - The row number (0-based index).
536
+ * @param headerPosition - The column/header position (0-based index).
537
+ * @returns A Playwright Locator for the specified cell.
538
+ *
539
+ * @example
540
+ * // Get cell at row 1, column 2
541
+ * const cellLocator = table.getBodyCellLocator(1, 2);
542
+ * await expect(cellLocator).toHaveText('Expected Text');
543
+ *
544
+ * @example
545
+ * // Get first cell in first row
546
+ * const firstCell = table.getBodyCellLocator(0, 0);
547
+ * await firstCell.click();
548
+ *
549
+ * @see {@link getBodyCellLocatorByRowConditions} for finding cells by content matching
550
+ * @see {@link getAllBodyCellLocatorsByHeaderIndex} for getting all cells in a column
551
+ * @see {@link getAllBodyCellLocatorsByHeaderName} for getting all cells under a header
552
+ */
316
553
  getBodyCellLocator(rowNumber, headerPosition) {
317
554
  return this._bodyRowLocator.nth(rowNumber).locator(this._bodyRowColumnSelector).nth(headerPosition);
318
555
  }
556
+ /**
557
+ * Retrieves a cell locator in the body of the table based on row conditions and a target header.
558
+ * Finds the first row where all conditions match, then returns the cell in the target column.
559
+ * @param conditions - An object where keys are header names and values are expected cell contents, or a single [header, value] tuple.
560
+ * @param targetHeader - The header name of the column containing the cell to retrieve.
561
+ * @param options - Optional table loading options. See {@link TableOptions}.
562
+ * @returns A promise that resolves to a Playwright Locator for the matching cell.
563
+ * @throws Error if no row matches all specified conditions.
564
+ * @throws Error if any condition header or target header is not found in the table.
565
+ *
566
+ * @example
567
+ * // Find cell with multiple conditions
568
+ * const emailLocator = await table.getBodyCellLocatorByRowConditions(
569
+ * { "First name": "John", "Status": "Active" },
570
+ * "Email"
571
+ * );
572
+ * await expect(emailLocator).toContainText('@example.com');
573
+ *
574
+ * @example
575
+ * // Find cell with single condition using tuple syntax
576
+ * const actionCell = await table.getBodyCellLocatorByRowConditions(
577
+ * ["Username", "john.doe"],
578
+ * "Actions"
579
+ * );
580
+ * await actionCell.locator('button').click();
581
+ *
582
+ * @example
583
+ * // Find cell with single condition using object syntax
584
+ * const statusCell = await table.getBodyCellLocatorByRowConditions(
585
+ * { "Username": "john.doe" },
586
+ * "Status"
587
+ * );
588
+ *
589
+ * @see {@link getBodyCellLocator} for getting cells by direct index
590
+ * @see {@link getAllBodyCellLocatorsByHeaderName} for getting all cells in a column
591
+ */
319
592
  async getBodyCellLocatorByRowConditions(conditions, targetHeader, options) {
320
- await this.load(options);
321
- const headers = await this.getMainHeaderRow();
322
- const targetHeaderIndex = headers.indexOf(targetHeader);
323
- if (targetHeaderIndex === -1) {
324
- throw new Error(`Header "${targetHeader}" not found.`);
325
- }
326
- for (let rowIndex = 0; rowIndex < this._rows.length; rowIndex++) {
327
- const row = this._rows[rowIndex];
593
+ var _a;
594
+ const table = await this.getTable(options);
595
+ const mainHeader = this.mainHeaderRow(table.headerRows);
596
+ const targetHeaderIndex = this.getHeaderIndex(targetHeader, mainHeader);
597
+ const conditionsObj = Array.isArray(conditions) ? { [conditions[0]]: conditions[1] } : conditions;
598
+ for (let rowIndex = 0; rowIndex < table.bodyRows.length; rowIndex++) {
599
+ const row = table.bodyRows[rowIndex];
328
600
  let matches = true;
329
- for (const [header, value] of Object.entries(conditions)) {
330
- const headerIndex = headers.indexOf(header);
331
- if (headerIndex === -1) {
332
- throw new Error(`Header "${header}" not found.`);
333
- }
334
- if (row[headerIndex] !== value) {
601
+ for (const [header, value] of Object.entries(conditionsObj)) {
602
+ const headerIndex = this.getHeaderIndex(header, mainHeader);
603
+ const cellValue = (_a = row[headerIndex]) != null ? _a : "";
604
+ if (cellValue !== value) {
335
605
  matches = false;
336
606
  break;
337
607
  }
@@ -340,42 +610,123 @@ var PlaywrightTable = class {
340
610
  return this.getBodyCellLocator(rowIndex, targetHeaderIndex);
341
611
  }
342
612
  }
343
- throw new Error(`No row found matching conditions: ${JSON.stringify(conditions)}`);
613
+ throw new Error(
614
+ `No row found matching conditions: ${JSON.stringify(conditionsObj)}
615
+ Target header: "${targetHeader}"
616
+ Searched ${table.bodyRows.length} rows
617
+ Body row locator: ${this._bodyRowLocator.toString()}`
618
+ );
344
619
  }
620
+ /**
621
+ * Retrieves all cell locators in the body of the table for a specific header name.
622
+ * Returns locators for every cell in the column identified by the header.
623
+ * @param header - The header name identifying the column.
624
+ * @param options - Optional table loading options. See {@link TableOptions}.
625
+ * @returns A promise that resolves to an array of Playwright Locators for all cells in the column.
626
+ * @throws Error if the header is not found in the table.
627
+ *
628
+ * @example
629
+ * // Get all cells in the "Status" column
630
+ * const statusCells = await table.getAllBodyCellLocatorsByHeaderName("Status");
631
+ * for (const cell of statusCells) {
632
+ * await expect(cell).toHaveText(/Active|Inactive/);
633
+ * }
634
+ *
635
+ * @example
636
+ * // Get text from all cells in "Name" column
637
+ * const nameCells = await table.getAllBodyCellLocatorsByHeaderName("Name");
638
+ * const names = await Promise.all(nameCells.map(cell => cell.textContent()));
639
+ *
640
+ * @see {@link getAllBodyCellLocatorsByHeaderIndex} for getting cells by column index
641
+ * @see {@link getBodyCellLocatorByRowConditions} for finding specific cells by content
642
+ */
345
643
  async getAllBodyCellLocatorsByHeaderName(header, options) {
346
- await this.load(options);
347
- const headers = await this.getMainHeaderRow();
348
- const headerIndex = headers.indexOf(header);
349
- if (headerIndex === -1) {
350
- throw new Error(`Header "${header}" not found.`);
351
- }
644
+ const table = await this.getTable(options);
645
+ const headers = this.mainHeaderRow(table.headerRows);
646
+ const headerIndex = this.getHeaderIndex(header, headers);
352
647
  const locators = [];
353
- for (let rowIndex = 0; rowIndex < this._rows.length; rowIndex++) {
648
+ for (let rowIndex = 0; rowIndex < table.bodyRows.length; rowIndex++) {
354
649
  const cellLocator = this.getBodyCellLocator(rowIndex, headerIndex);
355
650
  locators.push(cellLocator);
356
651
  }
357
652
  return locators;
358
653
  }
359
- async getAllBodyCellLocatorsByHeaderIndex(headerIndex) {
360
- await this.load();
654
+ /**
655
+ * Retrieves all cell locators in the body of the table for a specific header index.
656
+ * Returns locators for every cell in the column at the specified position.
657
+ * @param headerIndex - The header/column index (0-based).
658
+ * @param options - Optional table loading options. See {@link TableOptions}.
659
+ * @returns A promise that resolves to an array of Playwright Locators for all cells in the column.
660
+ * @throws Error if the header index is out of bounds (negative or >= column count).
661
+ *
662
+ * @example
663
+ * // Get all cells in the third column (index 2)
664
+ * const thirdColumnCells = await table.getAllBodyCellLocatorsByHeaderIndex(2);
665
+ * for (const cell of thirdColumnCells) {
666
+ * await expect(cell).toBeVisible();
667
+ * }
668
+ *
669
+ * @example
670
+ * // Get all cells in first column
671
+ * const firstColumnCells = await table.getAllBodyCellLocatorsByHeaderIndex(0);
672
+ * const values = await Promise.all(firstColumnCells.map(c => c.textContent()));
673
+ *
674
+ * @see {@link getAllBodyCellLocatorsByHeaderName} for getting cells by header name
675
+ * @see {@link getBodyCellLocator} for getting a specific cell by row and column index
676
+ */
677
+ async getAllBodyCellLocatorsByHeaderIndex(headerIndex, options) {
678
+ const table = await this.getTable(options);
679
+ const columnCount = this.mainHeaderRow(table.headerRows).length;
680
+ if (headerIndex < 0 || headerIndex >= columnCount) {
681
+ throw new Error(
682
+ `Header index ${headerIndex} out of bounds. Table has ${columnCount} columns.
683
+ Header row locator: ${this._headerRowLocator.toString()}`
684
+ );
685
+ }
361
686
  const locators = [];
362
- for (let rowIndex = 0; rowIndex < this._rows.length; rowIndex++) {
687
+ for (let rowIndex = 0; rowIndex < table.bodyRows.length; rowIndex++) {
363
688
  const cellLocator = this.getBodyCellLocator(rowIndex, headerIndex);
364
689
  locators.push(cellLocator);
365
690
  }
366
691
  return locators;
367
692
  }
693
+ /**
694
+ * Converts the table data into a JSON array where each object represents a row.
695
+ * Keys are header names, values are cell contents.
696
+ * @param options - Optional table loading options. See {@link TableOptions}.
697
+ * @returns A promise that resolves to an array of objects representing table rows.
698
+ * @throws Error if no header rows or body rows found.
699
+ *
700
+ * @example
701
+ * // Convert table to JSON with default options
702
+ * const data = await table.getJson();
703
+ * // Result: [{"Name": "John", "Age": "30"}, {"Name": "Jane", "Age": "25"}]
704
+ *
705
+ * @example
706
+ * // Convert with colspan enabled and duplicate suffix
707
+ * const data = await table.getJson({
708
+ * headerRowOptions: {
709
+ * colspan: { enabled: true, suffix: true },
710
+ * duplicateSuffix: true,
711
+ * emptyCellReplacement: true
712
+ * }
713
+ * });
714
+ */
368
715
  async getJson(options) {
369
- const headers = await this.getMainHeaderRow({
370
- timeout: options == null ? void 0 : options.timeout,
371
- duplicateSuffix: true,
716
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
717
+ const table = await this.getTable({
718
+ bodyRowOptions: options == null ? void 0 : options.bodyRowOptions,
372
719
  headerRowOptions: {
373
- colspan: { enabled: true, suffix: true },
374
- duplicateSuffix: true,
375
- emptyCellReplacement: true
720
+ colspan: {
721
+ enabled: (_c = (_b = (_a = options == null ? void 0 : options.headerRowOptions) == null ? void 0 : _a.colspan) == null ? void 0 : _b.enabled) != null ? _c : true,
722
+ suffix: (_f = (_e = (_d = options == null ? void 0 : options.headerRowOptions) == null ? void 0 : _d.colspan) == null ? void 0 : _e.suffix) != null ? _f : true
723
+ },
724
+ duplicateSuffix: (_h = (_g = options == null ? void 0 : options.headerRowOptions) == null ? void 0 : _g.duplicateSuffix) != null ? _h : true,
725
+ emptyCellReplacement: (_j = (_i = options == null ? void 0 : options.headerRowOptions) == null ? void 0 : _i.emptyCellReplacement) != null ? _j : true
376
726
  }
377
727
  });
378
- return this._rows.map((row) => {
728
+ const headers = this.mainHeaderRow(table.headerRows);
729
+ return table.bodyRows.map((row) => {
379
730
  const rowObj = {};
380
731
  headers.forEach((header, index) => {
381
732
  rowObj[header] = row[index] || "";
@@ -383,31 +734,290 @@ var PlaywrightTable = class {
383
734
  return rowObj;
384
735
  });
385
736
  }
386
- async waitForHeaderRows(options) {
387
- await expect2(
388
- async () => await TableWait.waitForRows(this._headerRowLocator, this._headerColumnSelector, "header" /* Header */, options)
389
- ).toPass({
390
- timeout: options == null ? void 0 : options.timeout
391
- });
737
+ /**
738
+ * Waits for the table body to be empty (no body rows).
739
+ * @param options - Polling options (timeout, interval, retries).
740
+ * @returns A promise that resolves when table body is empty.
741
+ * @throws Error if table is not empty within timeout period.
742
+ *
743
+ * @example
744
+ * // Wait for table to clear after delete operation
745
+ * await table.waitForEmpty({ timeout: 5000 });
746
+ *
747
+ * @see {@link waitForNonEmpty} for waiting until table has data
748
+ *
749
+ * @remarks
750
+ * **Alternative:** Consider using Playwright's `expect.poll` for more flexibility:
751
+ * ```ts
752
+ * await expect.poll(async () => (await table.getBodyRows()).length).toBe(0);
753
+ * ```
754
+ */
755
+ async waitForEmpty(options) {
756
+ await pollTable(async () => {
757
+ const rows = await this._bodyRowLocator.all();
758
+ if (rows.length > 0) {
759
+ throw new Error(
760
+ `Expected table to be empty, but found ${rows.length} body rows.
761
+ Body row locator: ${this._bodyRowLocator.toString()}`
762
+ );
763
+ }
764
+ }, options);
392
765
  }
393
- async waitForBodyRows(options) {
394
- await expect2(
395
- async () => await TableWait.waitForRows(this._bodyRowLocator, this._bodyRowColumnSelector, "body" /* Body */, options)
396
- ).toPass({
397
- timeout: options == null ? void 0 : options.timeout
766
+ /**
767
+ * Waits for the table body to be non-empty (at least one body row with content).
768
+ * A row is considered valid if it has at least one cell containing text.
769
+ * @param options - Polling options (timeout, interval, retries).
770
+ * @returns A promise that resolves when table has at least one body row with content.
771
+ * @throws Error if table remains empty or has no rows with content within timeout period.
772
+ *
773
+ * @example
774
+ * // Wait for table to populate after search
775
+ * await table.waitForNonEmpty({ timeout: 5000 });
776
+ *
777
+ * @see {@link waitForEmpty} for waiting until table is cleared
778
+ *
779
+ * @remarks
780
+ * **Alternative:** Consider using Playwright's `expect.poll` for more flexibility:
781
+ * ```ts
782
+ * await expect.poll(async () => (await table.getBodyRows()).length).toBeGreaterThan(0);
783
+ * ```
784
+ */
785
+ async waitForNonEmpty(options) {
786
+ await pollTable(async () => {
787
+ const rows = await this._bodyRowLocator.all();
788
+ if (rows.length === 0) {
789
+ throw new Error(
790
+ `Expected table to be non-empty, but found 0 body rows.
791
+ Body row locator: ${this._bodyRowLocator.toString()}`
792
+ );
793
+ }
794
+ let hasRowWithContent = false;
795
+ for (const row of rows) {
796
+ const cells = await row.locator(this._bodyRowColumnSelector).all();
797
+ for (const cell of cells) {
798
+ const content = await cell.innerText();
799
+ if (content.trim().length > 0) {
800
+ hasRowWithContent = true;
801
+ break;
802
+ }
803
+ }
804
+ if (hasRowWithContent) break;
805
+ }
806
+ if (!hasRowWithContent) {
807
+ throw new Error(
808
+ `Expected table to have at least one row with content, but all ${rows.length} rows are empty.
809
+ Body row locator: ${this._bodyRowLocator.toString()}`
810
+ );
811
+ }
812
+ }, options);
813
+ }
814
+ /**
815
+ * Waits for the table body to have exactly N rows.
816
+ * @param count - The exact number of body rows expected.
817
+ * @param options - Polling options (timeout, interval, retries).
818
+ * @returns A promise that resolves when the table has exactly the specified number of rows.
819
+ * @throws Error if row count doesn't match within timeout period.
820
+ *
821
+ * @example
822
+ * // Wait for exactly 10 rows after pagination
823
+ * await table.waitForExactRowCount(10, { timeout: 5000 });
824
+ *
825
+ * @example
826
+ * // Verify table has exactly 0 rows (alternative to waitForEmpty)
827
+ * await table.waitForExactRowCount(0);
828
+ *
829
+ * @see {@link getRowCount} for getting current row counts
830
+ *
831
+ * @remarks
832
+ * **Alternative:** Consider using Playwright's `expect.poll` for more flexibility:
833
+ * ```ts
834
+ * await expect.poll(async () => (await table.getBodyRows()).length).toBe(10);
835
+ * ```
836
+ */
837
+ async waitForExactRowCount(count, options) {
838
+ if (count < 0 || !Number.isInteger(count)) {
839
+ throw new Error(`Row count must be a non-negative integer, got: ${count}`);
840
+ }
841
+ await pollTable(async () => {
842
+ const rows = await this._bodyRowLocator.all();
843
+ if (rows.length !== count) {
844
+ throw new Error(
845
+ `Expected exactly ${count} rows, but found ${rows.length}.
846
+ Body row locator: ${this._bodyRowLocator.toString()}`
847
+ );
848
+ }
849
+ }, options);
850
+ }
851
+ /**
852
+ * Gets the count of header and body rows in the table.
853
+ * Lightweight method that doesn't fetch cell data, only counts rows.
854
+ * @returns A promise that resolves to an object with header and body row counts.
855
+ *
856
+ * @example
857
+ * // Get current row counts
858
+ * const counts = await table.getRowCount();
859
+ * console.log(`Headers: ${counts.header}, Body: ${counts.body}`);
860
+ *
861
+ * @example
862
+ * // Assert specific row count
863
+ * const { body } = await table.getRowCount();
864
+ * expect(body).toBe(10);
865
+ */
866
+ async getRowCount() {
867
+ const [headerRows, bodyRows] = await Promise.all([this._headerRowLocator.all(), this._bodyRowLocator.all()]);
868
+ return {
869
+ header: headerRows.length,
870
+ body: bodyRows.length
871
+ };
872
+ }
873
+ /**
874
+ * Gets all distinct (unique) values from a specific column.
875
+ * Returns a sorted array of unique string values, excluding empty values.
876
+ * @param headerName - The header name of the column to extract distinct values from.
877
+ * @param options - Optional table loading options. See {@link TableOptions}.
878
+ * @returns A promise that resolves to a sorted array of distinct values.
879
+ * @throws Error if the specified header is not found in the table.
880
+ *
881
+ * @example
882
+ * // Get all unique status values
883
+ * const statuses = await table.getDistinctColumnValues("Status");
884
+ * // Result: ["Active", "Inactive", "Pending"]
885
+ *
886
+ * @example
887
+ * // Get distinct countries for filtering
888
+ * const countries = await table.getDistinctColumnValues("Country");
889
+ * console.log(`Available countries: ${countries.join(", ")}`);
890
+ *
891
+ * @example
892
+ * // Verify expected values exist
893
+ * const roles = await table.getDistinctColumnValues("Role");
894
+ * expect(roles).toContain("Admin");
895
+ * expect(roles).toHaveLength(3);
896
+ *
897
+ * @see {@link getAllBodyCellLocatorsByHeaderName} for getting all cell locators in a column
898
+ * @see {@link getJson} for getting full table data
899
+ */
900
+ async getDistinctColumnValues(headerName, options) {
901
+ var _a;
902
+ const table = await this.getTable(options);
903
+ const mainHeader = this.mainHeaderRow(table.headerRows);
904
+ const headerIndex = this.getHeaderIndex(headerName, mainHeader);
905
+ const values = /* @__PURE__ */ new Set();
906
+ for (const row of table.bodyRows) {
907
+ const value = String((_a = row[headerIndex]) != null ? _a : "").trim();
908
+ if (value) values.add(value);
909
+ }
910
+ return Array.from(values).sort();
911
+ }
912
+ /**
913
+ * Finds the index of the first body row matching the specified conditions.
914
+ * Returns -1 if no matching row is found.
915
+ * @param conditions - Record of header names and expected cell values to match.
916
+ * @param options - Optional table loading options. See {@link TableOptions}.
917
+ * @returns A promise that resolves to the 0-based index of the first matching row, or -1 if not found.
918
+ * @throws Error if specified headers don't exist in the table.
919
+ *
920
+ * @example
921
+ * // Find index of row where Status is "Active"
922
+ * const index = await table.findRowIndex({ Status: "Active" });
923
+ * if (index >= 0) {
924
+ * console.log(`Found at row ${index}`);
925
+ * }
926
+ *
927
+ * @example
928
+ * // Find row and interact with it
929
+ * const rowIndex = await table.findRowIndex({ Username: "john.doe" });
930
+ * if (rowIndex >= 0) {
931
+ * const cell = table.getBodyCellLocator(rowIndex, 0);
932
+ * await cell.click();
933
+ * }
934
+ *
935
+ * @see {@link getBodyCellLocatorByRowConditions} for getting cell locators from matching rows
936
+ * @see {@link waitForRowByConditions} for waiting until matching row appears
937
+ */
938
+ async findRowIndex(conditions, options) {
939
+ var _a;
940
+ const table = await this.getTable({
941
+ headerRowOptions: { colspan: { enabled: true }, ...options == null ? void 0 : options.headerRowOptions },
942
+ bodyRowOptions: options == null ? void 0 : options.bodyRowOptions
398
943
  });
944
+ const mainHeader = this.mainHeaderRow(table.headerRows);
945
+ const headerIndices = /* @__PURE__ */ new Map();
946
+ for (const header of Object.keys(conditions)) {
947
+ headerIndices.set(header, this.getHeaderIndex(header, mainHeader));
948
+ }
949
+ for (let rowIndex = 0; rowIndex < table.bodyRows.length; rowIndex++) {
950
+ const row = table.bodyRows[rowIndex];
951
+ let rowMatches = true;
952
+ for (const [header, expectedValue] of Object.entries(conditions)) {
953
+ const headerIndex = headerIndices.get(header);
954
+ const cellValue = String((_a = row[headerIndex]) != null ? _a : "");
955
+ if (cellValue !== expectedValue) {
956
+ rowMatches = false;
957
+ break;
958
+ }
959
+ }
960
+ if (rowMatches) {
961
+ return rowIndex;
962
+ }
963
+ }
964
+ return -1;
399
965
  }
400
- async load(options) {
401
- await expect2(async () => {
402
- await TableWait.waitForRows(this._headerRowLocator, this._headerColumnSelector, "header" /* Header */);
403
- await TableWait.waitForRows(this._bodyRowLocator, this._bodyRowColumnSelector, "body" /* Body */);
404
- }).toPass({ timeout: options == null ? void 0 : options.timeout });
405
- this._headers = await TableHeader.getRows(
406
- this._headerRowLocator,
407
- this._headerColumnSelector,
408
- options == null ? void 0 : options.headerRowOptions
409
- );
410
- this._rows = await TableBody.getRows(this._bodyRowLocator, this._bodyRowColumnSelector);
966
+ async getTable(options) {
967
+ const [headerRows, bodyRows] = await Promise.all([
968
+ TableHeader.getRows(this._headerRowLocator, this._headerColumnSelector, options == null ? void 0 : options.headerRowOptions),
969
+ TableBody.getRows(this._bodyRowLocator, this._bodyRowColumnSelector, options == null ? void 0 : options.bodyRowOptions)
970
+ ]);
971
+ if (headerRows.length === 0) {
972
+ throw new Error(
973
+ `No header rows found, is table loaded completely?
974
+ Header row locator: ${this._headerRowLocator.toString()}
975
+ Table locator: ${this._tableLocator.toString()}`
976
+ );
977
+ }
978
+ if (bodyRows.length === 0) {
979
+ throw new Error(
980
+ `No body rows found, is table loaded completely?
981
+ Body row locator: ${this._bodyRowLocator.toString()}
982
+ Table locator: ${this._tableLocator.toString()}`
983
+ );
984
+ }
985
+ return { headerRows, bodyRows };
986
+ }
987
+ mainHeaderRow(headers) {
988
+ var _a, _b, _c;
989
+ if (headers.length === 0) {
990
+ throw new Error(
991
+ `No header rows available. Ensure table has been loaded.
992
+ Header row locator: ${this._headerRowLocator.toString()}`
993
+ );
994
+ }
995
+ const headerIndex = (_c = (_b = (_a = this._options) == null ? void 0 : _a.header) == null ? void 0 : _b.setMainHeaderRow) != null ? _c : headers.length - 1;
996
+ if (headerIndex < 0 || headerIndex >= headers.length) {
997
+ throw new Error(
998
+ `Header row index ${headerIndex} out of bounds. Table has ${headers.length} header rows.
999
+ Header row locator: ${this._headerRowLocator.toString()}`
1000
+ );
1001
+ }
1002
+ return headers[headerIndex];
1003
+ }
1004
+ /**
1005
+ * Gets the index of a header in the main header row, throwing an error if not found.
1006
+ * @param header - The header name to find.
1007
+ * @param mainHeader - The main header row to search in.
1008
+ * @returns The 0-based index of the header.
1009
+ * @throws Error if the header is not found.
1010
+ */
1011
+ getHeaderIndex(header, mainHeader) {
1012
+ const index = mainHeader.indexOf(header);
1013
+ if (index === -1) {
1014
+ throw new Error(
1015
+ `Header "${header}" not found.
1016
+ Available headers: [${mainHeader.join(", ")}]
1017
+ Header row locator: ${this._headerRowLocator.toString()}`
1018
+ );
1019
+ }
1020
+ return index;
411
1021
  }
412
1022
  };
413
1023
  export {