@rickcedwhat/playwright-smart-table 6.5.0 → 6.6.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/typeContext.d.ts +1 -1
- package/dist/typeContext.js +73 -1
- package/dist/types.d.ts +62 -1
- package/dist/useTable.js +230 -0
- package/package.json +1 -1
package/dist/typeContext.d.ts
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* This file is generated by scripts/embed-types.js
|
|
4
4
|
* It contains the raw text of types.ts to provide context for LLM prompts.
|
|
5
5
|
*/
|
|
6
|
-
export declare const TYPE_CONTEXT = "\n/**\n * Flexible selector type - can be a CSS string, function returning a Locator, or Locator itself.\n * @example\n * // String selector\n * rowSelector: 'tbody tr'\n * \n * // Function selector\n * rowSelector: (root) => root.locator('[role=\"row\"]')\n */\nexport type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);\n\n/**\n * Value used to filter rows.\n * - string/number/RegExp: filter by text content of the cell.\n * - function: filter by custom locator logic within the cell.\n * @example\n * // Text filter\n * { Name: 'John' }\n * \n * // Custom locator filter (e.g. checkbox is checked)\n * { Status: (cell) => cell.locator('input:checked') }\n */\nexport type FilterValue = string | RegExp | number | ((cell: Locator) => Locator);\n\n/**\n * Function to get a cell locator given row, column info.\n * Replaces the old cellResolver.\n */\nexport type GetCellLocatorFn = (args: {\n row: Locator;\n columnName: string;\n columnIndex: number;\n rowIndex?: number;\n page: Page;\n}) => Locator;\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/**\n * SmartRow - A Playwright Locator with table-aware methods.\n * \n * Extends all standard Locator methods (click, isVisible, etc.) with table-specific functionality.\n * \n * @example\n * const row = table.getRow({ Name: 'John Doe' });\n * await row.click(); // Standard Locator method\n * const email = row.getCell('Email'); // Table-aware method\n * const data = await row.toJSON(); // Extract all row data\n * await row.smartFill({ Name: 'Jane', Status: 'Active' }); // Fill form fields\n */\nexport type SmartRow<T = any> = Locator & {\n /** Optional row index (0-based) if known */\n rowIndex?: number;\n\n /** Optional page index this row was found on (0-based) */\n tablePageIndex?: number;\n\n /** Reference to the parent TableResult */\n table: TableResult<T>;\n\n /**\n * Get a cell locator by column name.\n * @param column - Column name (case-sensitive)\n * @returns Locator for the cell\n * @example\n * const emailCell = row.getCell('Email');\n * await expect(emailCell).toHaveText('john@example.com');\n */\n getCell(column: string): Locator;\n\n /**\n * Extract all cell data as a key-value object.\n * @param options - Optional configuration\n * @param options.columns - Specific columns to extract (extracts all if not specified)\n * @returns Promise resolving to row data\n * @example\n * const data = await row.toJSON();\n * // { Name: 'John', Email: 'john@example.com', ... }\n * \n * const partial = await row.toJSON({ columns: ['Name', 'Email'] });\n * // { Name: 'John', Email: 'john@example.com' }\n */\n toJSON(options?: { columns?: string[] }): Promise<T>;\n\n /**\n * Scrolls/paginates to bring this row into view.\n * Only works if rowIndex is known (e.g., from getRowByIndex).\n * @throws Error if rowIndex is unknown\n */\n bringIntoView(): Promise<void>;\n\n /**\n * Intelligently fills form fields in the row.\n * Automatically detects input types (text, select, checkbox, contenteditable).\n * \n * @param data - Column-value pairs to fill\n * @param options - Optional configuration\n * @param options.inputMappers - Custom input selectors per column\n * @example\n * // Auto-detection\n * await row.smartFill({ Name: 'John', Status: 'Active', Subscribe: true });\n * \n * // Custom input mappers\n * await row.smartFill(\n * { Name: 'John' },\n * { inputMappers: { Name: (cell) => cell.locator('.custom-input') } }\n * );\n */\n smartFill: (data: Partial<T> | Record<string, any>, options?: FillOptions) => Promise<void>;\n};\n\nexport type StrategyContext = TableContext & { rowLocator?: Locator; rowIndex?: number };\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}\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 /** Jump to first page / scroll to top */\n goToFirst?: (context: TableContext) => Promise<boolean>;\n\n /** Jump to specific page index (0-indexed) */\n goToPage?: (pageIndex: number, context: TableContext) => Promise<boolean>;\n}\n\nexport type PaginationStrategy = ((context: TableContext) => Promise<boolean>) | 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. (Replaces dataMapper logic)\n */\n read?: (cell: Locator) => Promise<TValue> | TValue;\n\n /** \n * How to fill the cell with a new value. (Replaces smartFill default logic)\n * Provides the current value (via `read`) if a `write` wants to check state first.\n */\n write?: (params: {\n cell: Locator;\n targetValue: TValue;\n currentValue?: TValue;\n row: SmartRow<any>;\n }) => Promise<void>;\n}\n\nexport type { HeaderStrategy } from './strategies/headers';\n\n/**\n * Strategy to resolve column names (string or regex) to their index.\n */\nexport type { ColumnResolutionStrategy } from './strategies/resolution';\n\n/**\n * Strategy to filter rows based on criteria.\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.\n */\nexport interface LoadingStrategy {\n isTableLoading?: (context: TableContext) => Promise<boolean>;\n isRowLoading?: (row: SmartRow) => Promise<boolean>;\n isHeaderLoading?: (context: TableContext) => Promise<boolean>;\n}\n\n/**\n * Organized container for all table interaction strategies.\n */\nexport interface TableStrategies {\n /** Strategy for discovering/scanning headers */\n header?: HeaderStrategy;\n /** Primitive navigation functions (goUp, goDown, goLeft, goRight, goHome) */\n navigation?: NavigationPrimitives;\n\n /** Strategy for filling form inputs */\n fill?: FillStrategy;\n /** Strategy for paginating through data */\n pagination?: PaginationStrategy;\n /** Strategy for sorting columns */\n sorting?: SortingStrategy;\n /** Strategy for deduplicating rows during iteration/scrolling */\n dedupe?: DedupeStrategy;\n /** Function to get a cell locator */\n getCellLocator?: GetCellLocatorFn;\n /** Function to get the currently active/focused cell */\n getActiveCell?: GetActiveCellFn;\n /** Custom helper to check if a table is fully loaded/ready */\n isTableLoaded?: (args: TableContext) => Promise<boolean>;\n /** Custom helper to check if a row is fully loaded/ready */\n isRowLoaded?: (args: { row: Locator, index: number }) => Promise<boolean>;\n /** Custom helper to check if a cell is fully loaded/ready (e.g. for editing) */\n isCellLoaded?: (args: { cell: Locator, column: string, row: Locator }) => Promise<boolean>;\n /** Strategy for detecting loading states */\n loading?: LoadingStrategy;\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;\n /** Number of pages to scan for verification */\n maxPages?: number;\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 * @deprecated Use `columnOverrides` instead. `dataMapper` will be removed in v7.0.0.\n * Custom data mappers for specific columns.\n * Allows extracting complex data types (boolean, number) instead of just string.\n */\n dataMapper?: Partial<Record<keyof T, (cell: Locator) => Promise<T[keyof T]> | T[keyof T]>>;\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;\n maxPages: number;\n autoScroll: boolean;\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 * Options for generateConfigPrompt\n */\nexport interface PromptOptions {\n /**\n * Output Strategy:\n * - 'error': Throws an error with the prompt (useful for platforms that capture error output cleanly).\n * - 'console': Standard console logs (Default).\n */\n output?: 'console' | 'error';\n /**\n * Include TypeScript type definitions in the prompt\n * @default true\n */\n includeTypes?: boolean;\n}\n\nexport interface TableResult<T = any> {\n /**\n * Represents the current page index of the table's DOM.\n * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.\n */\n currentPageIndex: number;\n\n /**\n * Initializes the table by resolving headers. Must be called before using sync methods.\n * @param options Optional timeout for header resolution (default: 3000ms)\n */\n init(options?: { timeout?: number }): Promise<TableResult>;\n\n /**\n * SYNC: Checks if the table has been initialized.\n * @returns true if init() has been called and completed, false otherwise\n */\n isInitialized(): boolean;\n\n getHeaders: () => Promise<string[]>;\n getHeaderCell: (columnName: string) => Promise<Locator>;\n\n /**\n * Finds a row by filters on the current page only. Returns immediately (sync).\n * Throws error if table is not initialized.\n */\n getRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean }\n ) => SmartRow;\n\n /**\n * Gets a row by 1-based index on the current page.\n * Throws error if table is not initialized.\n * @param index 1-based row index\n * @param options Optional settings including bringIntoView\n */\n getRowByIndex: (\n index: number,\n options?: { bringIntoView?: boolean }\n ) => SmartRow;\n\n /**\n * ASYNC: Searches for a single row across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRow>;\n\n /**\n * ASYNC: Searches for all matching rows across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRows: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRowArray<T>>;\n\n /**\n * Navigates to a specific column using the configured CellNavigationStrategy.\n */\n scrollToColumn: (columnName: string) => Promise<void>;\n\n\n\n /**\n * Resets the table state (clears cache, flags) and invokes the onReset strategy.\n */\n reset: () => Promise<void>;\n\n /**\n * Revalidates the table's structure (headers, columns) without resetting pagination or state.\n * Useful when columns change visibility or order dynamically.\n */\n revalidate: () => Promise<void>;\n\n /**\n * Scans a specific column across all pages and returns the values.\n */\n getColumnValues: <V = string>(column: string, options?: { mapper?: (cell: Locator) => Promise<V> | V, maxPages?: number }) => Promise<V[]>;\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 * Iterates through paginated table data, calling the callback for each iteration.\n * Callback return values are automatically appended to allData, which is returned.\n */\n iterateThroughTable: <T = any>(\n callback: (context: {\n index: number;\n isFirst: boolean;\n isLast: boolean;\n rows: SmartRowArray;\n allData: T[];\n table: RestrictedTableResult;\n batchInfo?: {\n startIndex: number;\n endIndex: number;\n size: number;\n };\n\n }) => T | T[] | Promise<T | T[]>,\n options?: {\n pagination?: PaginationStrategy;\n dedupeStrategy?: DedupeStrategy;\n maxIterations?: number;\n batchSize?: number;\n getIsFirst?: (context: { index: number }) => boolean;\n getIsLast?: (context: { index: number, paginationResult: boolean }) => boolean;\n beforeFirst?: (context: { index: number, rows: SmartRowArray, allData: any[] }) => void | Promise<void>;\n afterLast?: (context: { index: number, rows: SmartRowArray, allData: any[] }) => void | Promise<void>;\n /**\n * If true, flattens array results from callback into the main data array.\n * If false (default), pushes the return value as-is (preserves batching/arrays).\n */\n autoFlatten?: boolean;\n }\n ) => Promise<T[]>;\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 */\n generateConfigPrompt: (options?: PromptOptions) => Promise<void>;\n}\n\n/**\n * Restricted table result that excludes methods that shouldn't be called during iteration.\n */\nexport type RestrictedTableResult<T = any> = Omit<TableResult<T>, 'searchForRow' | 'iterateThroughTable' | 'reset'>;\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 * rowSelector: (root) => root.locator('[role=\"row\"]')\n */\nexport type Selector = string | ((root: Locator | Page) => Locator) | ((root: Locator) => Locator);\n\n/**\n * Value used to filter rows.\n * - string/number/RegExp: filter by text content of the cell.\n * - function: filter by custom locator logic within the cell.\n * @example\n * // Text filter\n * { Name: 'John' }\n * \n * // Custom locator filter (e.g. checkbox is checked)\n * { Status: (cell) => cell.locator('input:checked') }\n */\nexport type FilterValue = string | RegExp | number | ((cell: Locator) => Locator);\n\n/**\n * Function to get a cell locator given row, column info.\n * Replaces the old cellResolver.\n */\nexport type GetCellLocatorFn = (args: {\n row: Locator;\n columnName: string;\n columnIndex: number;\n rowIndex?: number;\n page: Page;\n}) => Locator;\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/**\n * SmartRow - A Playwright Locator with table-aware methods.\n * \n * Extends all standard Locator methods (click, isVisible, etc.) with table-specific functionality.\n * \n * @example\n * const row = table.getRow({ Name: 'John Doe' });\n * await row.click(); // Standard Locator method\n * const email = row.getCell('Email'); // Table-aware method\n * const data = await row.toJSON(); // Extract all row data\n * await row.smartFill({ Name: 'Jane', Status: 'Active' }); // Fill form fields\n */\nexport type SmartRow<T = any> = Locator & {\n /** Optional row index (0-based) if known */\n rowIndex?: number;\n\n /** Optional page index this row was found on (0-based) */\n tablePageIndex?: number;\n\n /** Reference to the parent TableResult */\n table: TableResult<T>;\n\n /**\n * Get a cell locator by column name.\n * @param column - Column name (case-sensitive)\n * @returns Locator for the cell\n * @example\n * const emailCell = row.getCell('Email');\n * await expect(emailCell).toHaveText('john@example.com');\n */\n getCell(column: string): Locator;\n\n /**\n * Extract all cell data as a key-value object.\n * @param options - Optional configuration\n * @param options.columns - Specific columns to extract (extracts all if not specified)\n * @returns Promise resolving to row data\n * @example\n * const data = await row.toJSON();\n * // { Name: 'John', Email: 'john@example.com', ... }\n * \n * const partial = await row.toJSON({ columns: ['Name', 'Email'] });\n * // { Name: 'John', Email: 'john@example.com' }\n */\n toJSON(options?: { columns?: string[] }): Promise<T>;\n\n /**\n * Scrolls/paginates to bring this row into view.\n * Only works if rowIndex is known (e.g., from getRowByIndex).\n * @throws Error if rowIndex is unknown\n */\n bringIntoView(): Promise<void>;\n\n /**\n * Intelligently fills form fields in the row.\n * Automatically detects input types (text, select, checkbox, contenteditable).\n * \n * @param data - Column-value pairs to fill\n * @param options - Optional configuration\n * @param options.inputMappers - Custom input selectors per column\n * @example\n * // Auto-detection\n * await row.smartFill({ Name: 'John', Status: 'Active', Subscribe: true });\n * \n * // Custom input mappers\n * await row.smartFill(\n * { Name: 'John' },\n * { inputMappers: { Name: (cell) => cell.locator('.custom-input') } }\n * );\n */\n smartFill: (data: Partial<T> | Record<string, any>, options?: FillOptions) => Promise<void>;\n};\n\nexport type StrategyContext = TableContext & { rowLocator?: Locator; rowIndex?: number };\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}\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 /** Jump to first page / scroll to top */\n goToFirst?: (context: TableContext) => Promise<boolean>;\n\n /** Jump to specific page index (0-indexed) */\n goToPage?: (pageIndex: number, context: TableContext) => Promise<boolean>;\n}\n\nexport type PaginationStrategy = ((context: TableContext) => Promise<boolean>) | 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. (Replaces dataMapper logic)\n */\n read?: (cell: Locator) => Promise<TValue> | TValue;\n\n /** \n * How to fill the cell with a new value. (Replaces smartFill default logic)\n * Provides the current value (via `read`) if a `write` wants to check state first.\n */\n write?: (params: {\n cell: Locator;\n targetValue: TValue;\n currentValue?: TValue;\n row: SmartRow<any>;\n }) => Promise<void>;\n}\n\nexport type { HeaderStrategy } from './strategies/headers';\n\n/**\n * Strategy to resolve column names (string or regex) to their index.\n */\nexport type { ColumnResolutionStrategy } from './strategies/resolution';\n\n/**\n * Strategy to filter rows based on criteria.\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.\n */\nexport interface LoadingStrategy {\n isTableLoading?: (context: TableContext) => Promise<boolean>;\n isRowLoading?: (row: SmartRow) => Promise<boolean>;\n isHeaderLoading?: (context: TableContext) => Promise<boolean>;\n}\n\n/**\n * Organized container for all table interaction strategies.\n */\nexport interface TableStrategies {\n /** Strategy for discovering/scanning headers */\n header?: HeaderStrategy;\n /** Primitive navigation functions (goUp, goDown, goLeft, goRight, goHome) */\n navigation?: NavigationPrimitives;\n\n /** Strategy for filling form inputs */\n fill?: FillStrategy;\n /** Strategy for paginating through data */\n pagination?: PaginationStrategy;\n /** Strategy for sorting columns */\n sorting?: SortingStrategy;\n /** Strategy for deduplicating rows during iteration/scrolling */\n dedupe?: DedupeStrategy;\n /** Function to get a cell locator */\n getCellLocator?: GetCellLocatorFn;\n /** Function to get the currently active/focused cell */\n getActiveCell?: GetActiveCellFn;\n /** Custom helper to check if a table is fully loaded/ready */\n isTableLoaded?: (args: TableContext) => Promise<boolean>;\n /** Custom helper to check if a row is fully loaded/ready */\n isRowLoaded?: (args: { row: Locator, index: number }) => Promise<boolean>;\n /** Custom helper to check if a cell is fully loaded/ready (e.g. for editing) */\n isCellLoaded?: (args: { cell: Locator, column: string, row: Locator }) => Promise<boolean>;\n /** Strategy for detecting loading states */\n loading?: LoadingStrategy;\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;\n /** Number of pages to scan for verification */\n maxPages?: number;\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 * @deprecated Use `columnOverrides` instead. `dataMapper` will be removed in v7.0.0.\n * Custom data mappers for specific columns.\n * Allows extracting complex data types (boolean, number) instead of just string.\n */\n dataMapper?: Partial<Record<keyof T, (cell: Locator) => Promise<T[keyof T]> | T[keyof T]>>;\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;\n maxPages: number;\n autoScroll: boolean;\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 * Options for generateConfigPrompt\n */\nexport interface PromptOptions {\n /**\n * Output Strategy:\n * - 'error': Throws an error with the prompt (useful for platforms that capture error output cleanly).\n * - 'console': Standard console logs (Default).\n */\n output?: 'console' | 'error';\n /**\n * Include TypeScript type definitions in the prompt\n * @default true\n */\n includeTypes?: boolean;\n}\n\n/** Callback context passed to forEach, map, and filter. */\nexport type RowIterationContext<T = any> = {\n row: SmartRow<T>;\n rowIndex: number;\n stop: () => void;\n};\n\n/** 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 * Whether to process rows within a page concurrently.\n * @default false for forEach/filter, true for map\n */\n parallel?: boolean;\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\nexport interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number }> {\n /**\n * Represents the current page index of the table's DOM.\n * Starts at 0. Automatically maintained by the library during pagination and bringIntoView.\n */\n currentPageIndex: number;\n\n /**\n * Initializes the table by resolving headers. Must be called before using sync methods.\n * @param options Optional timeout for header resolution (default: 3000ms)\n */\n init(options?: { timeout?: number }): Promise<TableResult>;\n\n /**\n * SYNC: Checks if the table has been initialized.\n * @returns true if init() has been called and completed, false otherwise\n */\n isInitialized(): boolean;\n\n getHeaders: () => Promise<string[]>;\n getHeaderCell: (columnName: string) => Promise<Locator>;\n\n /**\n * Finds a row by filters on the current page only. Returns immediately (sync).\n * Throws error if table is not initialized.\n */\n getRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean }\n ) => SmartRow;\n\n /**\n * Gets a row by 1-based index on the current page.\n * Throws error if table is not initialized.\n * @param index 1-based row index\n * @param options Optional settings including bringIntoView\n */\n getRowByIndex: (\n index: number,\n options?: { bringIntoView?: boolean }\n ) => SmartRow;\n\n /**\n * ASYNC: Searches for a single row across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRow: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRow>;\n\n /**\n * ASYNC: Searches for all matching rows across pages using pagination.\n * Auto-initializes the table if not already initialized.\n * @param filters - The filter criteria to match\n * @param options - Search options including exact match and max pages\n */\n findRows: (\n filters: Record<string, FilterValue>,\n options?: { exact?: boolean, maxPages?: number }\n ) => Promise<SmartRowArray<T>>;\n\n /**\n * Navigates to a specific column using the configured CellNavigationStrategy.\n */\n scrollToColumn: (columnName: string) => Promise<void>;\n\n\n\n /**\n * Resets the table state (clears cache, flags) and invokes the onReset strategy.\n */\n reset: () => Promise<void>;\n\n /**\n * Revalidates the table's structure (headers, columns) without resetting pagination or state.\n * Useful when columns change visibility or order dynamically.\n */\n revalidate: () => Promise<void>;\n\n /**\n * Iterates every row across all pages, calling the callback for side effects.\n * Execution is sequential by default (safe for interactions like clicking/filling).\n * Call `stop()` in the callback to end iteration early.\n *\n * @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 * @example\n * const emails = await table.map(({ row }) => row.getCell('Email').innerText());\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 * @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 * Scans a specific column across all pages and returns the values.\n * @deprecated Use `table.map(({ row }) => row.getCell(column).innerText())` instead.\n * Will be removed in v7.0.0.\n */\n getColumnValues: <V = string>(column: string, options?: { mapper?: (cell: Locator) => Promise<V> | V, maxPages?: number }) => Promise<V[]>;\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 * Iterates through paginated table data, calling the callback for each iteration.\n * Callback return values are automatically appended to allData, which is returned.\n * @deprecated Use `forEach`, `map`, or `filter` instead for cleaner cross-page iteration.\n * Only use this for advanced scenarios (batchSize, beforeFirst/afterLast hooks).\n * Will be removed in v7.0.0.\n */\n iterateThroughTable: <T = any>(\n callback: (context: {\n index: number;\n isFirst: boolean;\n isLast: boolean;\n rows: SmartRowArray;\n allData: T[];\n table: RestrictedTableResult;\n batchInfo?: {\n startIndex: number;\n endIndex: number;\n size: number;\n };\n\n }) => T | T[] | Promise<T | T[]>,\n options?: {\n pagination?: PaginationStrategy;\n dedupeStrategy?: DedupeStrategy;\n maxIterations?: number;\n batchSize?: number;\n getIsFirst?: (context: { index: number }) => boolean;\n getIsLast?: (context: { index: number, paginationResult: boolean }) => boolean;\n beforeFirst?: (context: { index: number, rows: SmartRowArray, allData: any[] }) => void | Promise<void>;\n afterLast?: (context: { index: number, rows: SmartRowArray, allData: any[] }) => void | Promise<void>;\n /**\n * If true, flattens array results from callback into the main data array.\n * If false (default), pushes the return value as-is (preserves batching/arrays).\n */\n autoFlatten?: boolean;\n }\n ) => Promise<T[]>;\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 */\n generateConfigPrompt: (options?: PromptOptions) => Promise<void>;\n}\n\n/**\n * Restricted table result that excludes methods that shouldn't be called during iteration.\n */\nexport type RestrictedTableResult<T = any> = Omit<TableResult<T>, 'searchForRow' | 'iterateThroughTable' | 'reset'>;\n";
|
package/dist/typeContext.js
CHANGED
|
@@ -365,7 +365,30 @@ export interface PromptOptions {
|
|
|
365
365
|
includeTypes?: boolean;
|
|
366
366
|
}
|
|
367
367
|
|
|
368
|
-
|
|
368
|
+
/** Callback context passed to forEach, map, and filter. */
|
|
369
|
+
export type RowIterationContext<T = any> = {
|
|
370
|
+
row: SmartRow<T>;
|
|
371
|
+
rowIndex: number;
|
|
372
|
+
stop: () => void;
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
/** Shared options for forEach, map, and filter. */
|
|
376
|
+
export type RowIterationOptions = {
|
|
377
|
+
/** Maximum number of pages to iterate. Defaults to config.maxPages. */
|
|
378
|
+
maxPages?: number;
|
|
379
|
+
/**
|
|
380
|
+
* Whether to process rows within a page concurrently.
|
|
381
|
+
* @default false for forEach/filter, true for map
|
|
382
|
+
*/
|
|
383
|
+
parallel?: boolean;
|
|
384
|
+
/**
|
|
385
|
+
* Deduplication strategy. Use when rows may repeat across iterations
|
|
386
|
+
* (e.g. infinite scroll tables). Returns a unique key per row.
|
|
387
|
+
*/
|
|
388
|
+
dedupe?: DedupeStrategy;
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
export interface TableResult<T = any> extends AsyncIterable<{ row: SmartRow<T>; rowIndex: number }> {
|
|
369
392
|
/**
|
|
370
393
|
* Represents the current page index of the table's DOM.
|
|
371
394
|
* Starts at 0. Automatically maintained by the library during pagination and bringIntoView.
|
|
@@ -447,8 +470,54 @@ export interface TableResult<T = any> {
|
|
|
447
470
|
*/
|
|
448
471
|
revalidate: () => Promise<void>;
|
|
449
472
|
|
|
473
|
+
/**
|
|
474
|
+
* Iterates every row across all pages, calling the callback for side effects.
|
|
475
|
+
* Execution is sequential by default (safe for interactions like clicking/filling).
|
|
476
|
+
* Call \`stop()\` in the callback to end iteration early.
|
|
477
|
+
*
|
|
478
|
+
* @example
|
|
479
|
+
* await table.forEach(async ({ row, stop }) => {
|
|
480
|
+
* if (await row.getCell('Status').innerText() === 'Done') stop();
|
|
481
|
+
* await row.getCell('Checkbox').click();
|
|
482
|
+
* });
|
|
483
|
+
*/
|
|
484
|
+
forEach(
|
|
485
|
+
callback: (ctx: RowIterationContext<T>) => void | Promise<void>,
|
|
486
|
+
options?: RowIterationOptions
|
|
487
|
+
): Promise<void>;
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Transforms every row across all pages into a value. Returns a flat array.
|
|
491
|
+
* Execution is parallel within each page by default (safe for reads).
|
|
492
|
+
* Call \`stop()\` to halt after the current page finishes.
|
|
493
|
+
*
|
|
494
|
+
* @example
|
|
495
|
+
* const emails = await table.map(({ row }) => row.getCell('Email').innerText());
|
|
496
|
+
*/
|
|
497
|
+
map<R>(
|
|
498
|
+
callback: (ctx: RowIterationContext<T>) => R | Promise<R>,
|
|
499
|
+
options?: RowIterationOptions
|
|
500
|
+
): Promise<R[]>;
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Filters rows across all pages by an async predicate. Returns a SmartRowArray.
|
|
504
|
+
* Rows are returned as-is — call \`bringIntoView()\` on each if needed.
|
|
505
|
+
* Execution is sequential by default.
|
|
506
|
+
*
|
|
507
|
+
* @example
|
|
508
|
+
* const active = await table.filter(async ({ row }) =>
|
|
509
|
+
* await row.getCell('Status').innerText() === 'Active'
|
|
510
|
+
* );
|
|
511
|
+
*/
|
|
512
|
+
filter(
|
|
513
|
+
predicate: (ctx: RowIterationContext<T>) => boolean | Promise<boolean>,
|
|
514
|
+
options?: RowIterationOptions
|
|
515
|
+
): Promise<SmartRowArray<T>>;
|
|
516
|
+
|
|
450
517
|
/**
|
|
451
518
|
* Scans a specific column across all pages and returns the values.
|
|
519
|
+
* @deprecated Use \`table.map(({ row }) => row.getCell(column).innerText())\` instead.
|
|
520
|
+
* Will be removed in v7.0.0.
|
|
452
521
|
*/
|
|
453
522
|
getColumnValues: <V = string>(column: string, options?: { mapper?: (cell: Locator) => Promise<V> | V, maxPages?: number }) => Promise<V[]>;
|
|
454
523
|
|
|
@@ -473,6 +542,9 @@ export interface TableResult<T = any> {
|
|
|
473
542
|
/**
|
|
474
543
|
* Iterates through paginated table data, calling the callback for each iteration.
|
|
475
544
|
* Callback return values are automatically appended to allData, which is returned.
|
|
545
|
+
* @deprecated Use \`forEach\`, \`map\`, or \`filter\` instead for cleaner cross-page iteration.
|
|
546
|
+
* Only use this for advanced scenarios (batchSize, beforeFirst/afterLast hooks).
|
|
547
|
+
* Will be removed in v7.0.0.
|
|
476
548
|
*/
|
|
477
549
|
iterateThroughTable: <T = any>(
|
|
478
550
|
callback: (context: {
|
package/dist/types.d.ts
CHANGED
|
@@ -344,7 +344,31 @@ export interface PromptOptions {
|
|
|
344
344
|
*/
|
|
345
345
|
includeTypes?: boolean;
|
|
346
346
|
}
|
|
347
|
-
|
|
347
|
+
/** Callback context passed to forEach, map, and filter. */
|
|
348
|
+
export type RowIterationContext<T = any> = {
|
|
349
|
+
row: SmartRow<T>;
|
|
350
|
+
rowIndex: number;
|
|
351
|
+
stop: () => void;
|
|
352
|
+
};
|
|
353
|
+
/** Shared options for forEach, map, and filter. */
|
|
354
|
+
export type RowIterationOptions = {
|
|
355
|
+
/** Maximum number of pages to iterate. Defaults to config.maxPages. */
|
|
356
|
+
maxPages?: number;
|
|
357
|
+
/**
|
|
358
|
+
* Whether to process rows within a page concurrently.
|
|
359
|
+
* @default false for forEach/filter, true for map
|
|
360
|
+
*/
|
|
361
|
+
parallel?: boolean;
|
|
362
|
+
/**
|
|
363
|
+
* Deduplication strategy. Use when rows may repeat across iterations
|
|
364
|
+
* (e.g. infinite scroll tables). Returns a unique key per row.
|
|
365
|
+
*/
|
|
366
|
+
dedupe?: DedupeStrategy;
|
|
367
|
+
};
|
|
368
|
+
export interface TableResult<T = any> extends AsyncIterable<{
|
|
369
|
+
row: SmartRow<T>;
|
|
370
|
+
rowIndex: number;
|
|
371
|
+
}> {
|
|
348
372
|
/**
|
|
349
373
|
* Represents the current page index of the table's DOM.
|
|
350
374
|
* Starts at 0. Automatically maintained by the library during pagination and bringIntoView.
|
|
@@ -413,8 +437,42 @@ export interface TableResult<T = any> {
|
|
|
413
437
|
* Useful when columns change visibility or order dynamically.
|
|
414
438
|
*/
|
|
415
439
|
revalidate: () => Promise<void>;
|
|
440
|
+
/**
|
|
441
|
+
* Iterates every row across all pages, calling the callback for side effects.
|
|
442
|
+
* Execution is sequential by default (safe for interactions like clicking/filling).
|
|
443
|
+
* Call `stop()` in the callback to end iteration early.
|
|
444
|
+
*
|
|
445
|
+
* @example
|
|
446
|
+
* await table.forEach(async ({ row, stop }) => {
|
|
447
|
+
* if (await row.getCell('Status').innerText() === 'Done') stop();
|
|
448
|
+
* await row.getCell('Checkbox').click();
|
|
449
|
+
* });
|
|
450
|
+
*/
|
|
451
|
+
forEach(callback: (ctx: RowIterationContext<T>) => void | Promise<void>, options?: RowIterationOptions): Promise<void>;
|
|
452
|
+
/**
|
|
453
|
+
* Transforms every row across all pages into a value. Returns a flat array.
|
|
454
|
+
* Execution is parallel within each page by default (safe for reads).
|
|
455
|
+
* Call `stop()` to halt after the current page finishes.
|
|
456
|
+
*
|
|
457
|
+
* @example
|
|
458
|
+
* const emails = await table.map(({ row }) => row.getCell('Email').innerText());
|
|
459
|
+
*/
|
|
460
|
+
map<R>(callback: (ctx: RowIterationContext<T>) => R | Promise<R>, options?: RowIterationOptions): Promise<R[]>;
|
|
461
|
+
/**
|
|
462
|
+
* Filters rows across all pages by an async predicate. Returns a SmartRowArray.
|
|
463
|
+
* Rows are returned as-is — call `bringIntoView()` on each if needed.
|
|
464
|
+
* Execution is sequential by default.
|
|
465
|
+
*
|
|
466
|
+
* @example
|
|
467
|
+
* const active = await table.filter(async ({ row }) =>
|
|
468
|
+
* await row.getCell('Status').innerText() === 'Active'
|
|
469
|
+
* );
|
|
470
|
+
*/
|
|
471
|
+
filter(predicate: (ctx: RowIterationContext<T>) => boolean | Promise<boolean>, options?: RowIterationOptions): Promise<SmartRowArray<T>>;
|
|
416
472
|
/**
|
|
417
473
|
* Scans a specific column across all pages and returns the values.
|
|
474
|
+
* @deprecated Use `table.map(({ row }) => row.getCell(column).innerText())` instead.
|
|
475
|
+
* Will be removed in v7.0.0.
|
|
418
476
|
*/
|
|
419
477
|
getColumnValues: <V = string>(column: string, options?: {
|
|
420
478
|
mapper?: (cell: Locator) => Promise<V> | V;
|
|
@@ -440,6 +498,9 @@ export interface TableResult<T = any> {
|
|
|
440
498
|
/**
|
|
441
499
|
* Iterates through paginated table data, calling the callback for each iteration.
|
|
442
500
|
* Callback return values are automatically appended to allData, which is returned.
|
|
501
|
+
* @deprecated Use `forEach`, `map`, or `filter` instead for cleaner cross-page iteration.
|
|
502
|
+
* Only use this for advanced scenarios (batchSize, beforeFirst/afterLast hooks).
|
|
503
|
+
* Will be removed in v7.0.0.
|
|
443
504
|
*/
|
|
444
505
|
iterateThroughTable: <T = any>(callback: (context: {
|
|
445
506
|
index: number;
|
package/dist/useTable.js
CHANGED
|
@@ -8,6 +8,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
|
+
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
|
|
12
|
+
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
|
|
13
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
14
|
+
var g = generator.apply(thisArg, _arguments || []), i, q = [];
|
|
15
|
+
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
|
|
16
|
+
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
|
|
17
|
+
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
|
|
18
|
+
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
|
|
19
|
+
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
|
|
20
|
+
function fulfill(value) { resume("next", value); }
|
|
21
|
+
function reject(value) { resume("throw", value); }
|
|
22
|
+
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
|
|
23
|
+
};
|
|
11
24
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
25
|
exports.useTable = void 0;
|
|
13
26
|
const minimalConfigContext_1 = require("./minimalConfigContext");
|
|
@@ -250,6 +263,219 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
250
263
|
return config.strategies.sorting.getSortState({ columnName, context });
|
|
251
264
|
})
|
|
252
265
|
},
|
|
266
|
+
// ─── Shared async row iterator ───────────────────────────────────────────
|
|
267
|
+
[Symbol.asyncIterator]() {
|
|
268
|
+
return __asyncGenerator(this, arguments, function* _a() {
|
|
269
|
+
var _b;
|
|
270
|
+
yield __await(_ensureInitialized());
|
|
271
|
+
const map = tableMapper.getMapSync();
|
|
272
|
+
const effectiveMaxPages = config.maxPages;
|
|
273
|
+
let rowIndex = 0;
|
|
274
|
+
let pagesScanned = 1;
|
|
275
|
+
while (true) {
|
|
276
|
+
const pageRows = yield __await(resolve(config.rowSelector, rootLocator).all());
|
|
277
|
+
for (const rowLocator of pageRows) {
|
|
278
|
+
yield yield __await({ row: _makeSmart(rowLocator, map, rowIndex), rowIndex });
|
|
279
|
+
rowIndex++;
|
|
280
|
+
}
|
|
281
|
+
if (pagesScanned >= effectiveMaxPages)
|
|
282
|
+
break;
|
|
283
|
+
const context = { root: rootLocator, config, page: rootLocator.page(), resolve };
|
|
284
|
+
let advanced;
|
|
285
|
+
if (typeof config.strategies.pagination === 'function') {
|
|
286
|
+
advanced = !!(yield __await(config.strategies.pagination(context)));
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
advanced = !!(((_b = config.strategies.pagination) === null || _b === void 0 ? void 0 : _b.goNext) && (yield __await(config.strategies.pagination.goNext(context))));
|
|
290
|
+
}
|
|
291
|
+
if (!advanced)
|
|
292
|
+
break;
|
|
293
|
+
tableState.currentPageIndex++;
|
|
294
|
+
pagesScanned++;
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
},
|
|
298
|
+
// ─── Private row-iteration engine ────────────────────────────────────────
|
|
299
|
+
forEach: (callback_1, ...args_1) => __awaiter(void 0, [callback_1, ...args_1], void 0, function* (callback, options = {}) {
|
|
300
|
+
var _a, _b, _c;
|
|
301
|
+
yield _ensureInitialized();
|
|
302
|
+
const map = tableMapper.getMapSync();
|
|
303
|
+
const effectiveMaxPages = (_a = options.maxPages) !== null && _a !== void 0 ? _a : config.maxPages;
|
|
304
|
+
const dedupeKeys = options.dedupe ? new Set() : null;
|
|
305
|
+
const parallel = (_b = options.parallel) !== null && _b !== void 0 ? _b : false;
|
|
306
|
+
let rowIndex = 0;
|
|
307
|
+
let stopped = false;
|
|
308
|
+
let pagesScanned = 1;
|
|
309
|
+
const stop = () => { stopped = true; };
|
|
310
|
+
while (!stopped) {
|
|
311
|
+
const pageRows = yield resolve(config.rowSelector, rootLocator).all();
|
|
312
|
+
const smartRows = pageRows.map((r, i) => _makeSmart(r, map, rowIndex + i));
|
|
313
|
+
if (parallel) {
|
|
314
|
+
yield Promise.all(smartRows.map((row) => __awaiter(void 0, void 0, void 0, function* () {
|
|
315
|
+
if (stopped)
|
|
316
|
+
return;
|
|
317
|
+
if (dedupeKeys) {
|
|
318
|
+
const key = yield options.dedupe(row);
|
|
319
|
+
if (dedupeKeys.has(key))
|
|
320
|
+
return;
|
|
321
|
+
dedupeKeys.add(key);
|
|
322
|
+
}
|
|
323
|
+
yield callback({ row, rowIndex: row.rowIndex, stop });
|
|
324
|
+
})));
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
for (const row of smartRows) {
|
|
328
|
+
if (stopped)
|
|
329
|
+
break;
|
|
330
|
+
if (dedupeKeys) {
|
|
331
|
+
const key = yield options.dedupe(row);
|
|
332
|
+
if (dedupeKeys.has(key))
|
|
333
|
+
continue;
|
|
334
|
+
dedupeKeys.add(key);
|
|
335
|
+
}
|
|
336
|
+
yield callback({ row, rowIndex: row.rowIndex, stop });
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
rowIndex += smartRows.length;
|
|
340
|
+
if (stopped || pagesScanned >= effectiveMaxPages)
|
|
341
|
+
break;
|
|
342
|
+
const context = { root: rootLocator, config, page: rootLocator.page(), resolve };
|
|
343
|
+
let advanced;
|
|
344
|
+
if (typeof config.strategies.pagination === 'function') {
|
|
345
|
+
advanced = !!(yield config.strategies.pagination(context));
|
|
346
|
+
}
|
|
347
|
+
else {
|
|
348
|
+
advanced = !!(((_c = config.strategies.pagination) === null || _c === void 0 ? void 0 : _c.goNext) && (yield config.strategies.pagination.goNext(context)));
|
|
349
|
+
}
|
|
350
|
+
if (!advanced)
|
|
351
|
+
break;
|
|
352
|
+
tableState.currentPageIndex++;
|
|
353
|
+
pagesScanned++;
|
|
354
|
+
}
|
|
355
|
+
}),
|
|
356
|
+
map: (callback_1, ...args_1) => __awaiter(void 0, [callback_1, ...args_1], void 0, function* (callback, options = {}) {
|
|
357
|
+
var _a, _b, _c;
|
|
358
|
+
yield _ensureInitialized();
|
|
359
|
+
const map = tableMapper.getMapSync();
|
|
360
|
+
const effectiveMaxPages = (_a = options.maxPages) !== null && _a !== void 0 ? _a : config.maxPages;
|
|
361
|
+
const dedupeKeys = options.dedupe ? new Set() : null;
|
|
362
|
+
const parallel = (_b = options.parallel) !== null && _b !== void 0 ? _b : true;
|
|
363
|
+
const results = [];
|
|
364
|
+
let rowIndex = 0;
|
|
365
|
+
let stopped = false;
|
|
366
|
+
let pagesScanned = 1;
|
|
367
|
+
const stop = () => { stopped = true; };
|
|
368
|
+
while (!stopped) {
|
|
369
|
+
const pageRows = yield resolve(config.rowSelector, rootLocator).all();
|
|
370
|
+
const smartRows = pageRows.map((r, i) => _makeSmart(r, map, rowIndex + i));
|
|
371
|
+
if (parallel) {
|
|
372
|
+
const SKIP = Symbol('skip');
|
|
373
|
+
const pageResults = yield Promise.all(smartRows.map((row) => __awaiter(void 0, void 0, void 0, function* () {
|
|
374
|
+
if (dedupeKeys) {
|
|
375
|
+
const key = yield options.dedupe(row);
|
|
376
|
+
if (dedupeKeys.has(key))
|
|
377
|
+
return SKIP;
|
|
378
|
+
dedupeKeys.add(key);
|
|
379
|
+
}
|
|
380
|
+
return callback({ row, rowIndex: row.rowIndex, stop });
|
|
381
|
+
})));
|
|
382
|
+
for (const r of pageResults) {
|
|
383
|
+
if (r !== SKIP)
|
|
384
|
+
results.push(r);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
else {
|
|
388
|
+
for (const row of smartRows) {
|
|
389
|
+
if (stopped)
|
|
390
|
+
break;
|
|
391
|
+
if (dedupeKeys) {
|
|
392
|
+
const key = yield options.dedupe(row);
|
|
393
|
+
if (dedupeKeys.has(key))
|
|
394
|
+
continue;
|
|
395
|
+
dedupeKeys.add(key);
|
|
396
|
+
}
|
|
397
|
+
results.push(yield callback({ row, rowIndex: row.rowIndex, stop }));
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
rowIndex += smartRows.length;
|
|
401
|
+
if (stopped || pagesScanned >= effectiveMaxPages)
|
|
402
|
+
break;
|
|
403
|
+
const context = { root: rootLocator, config, page: rootLocator.page(), resolve };
|
|
404
|
+
let advanced;
|
|
405
|
+
if (typeof config.strategies.pagination === 'function') {
|
|
406
|
+
advanced = !!(yield config.strategies.pagination(context));
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
advanced = !!(((_c = config.strategies.pagination) === null || _c === void 0 ? void 0 : _c.goNext) && (yield config.strategies.pagination.goNext(context)));
|
|
410
|
+
}
|
|
411
|
+
if (!advanced)
|
|
412
|
+
break;
|
|
413
|
+
tableState.currentPageIndex++;
|
|
414
|
+
pagesScanned++;
|
|
415
|
+
}
|
|
416
|
+
return results;
|
|
417
|
+
}),
|
|
418
|
+
filter: (predicate_1, ...args_1) => __awaiter(void 0, [predicate_1, ...args_1], void 0, function* (predicate, options = {}) {
|
|
419
|
+
var _a, _b, _c;
|
|
420
|
+
yield _ensureInitialized();
|
|
421
|
+
const map = tableMapper.getMapSync();
|
|
422
|
+
const effectiveMaxPages = (_a = options.maxPages) !== null && _a !== void 0 ? _a : config.maxPages;
|
|
423
|
+
const dedupeKeys = options.dedupe ? new Set() : null;
|
|
424
|
+
const parallel = (_b = options.parallel) !== null && _b !== void 0 ? _b : false;
|
|
425
|
+
const matched = [];
|
|
426
|
+
let rowIndex = 0;
|
|
427
|
+
let stopped = false;
|
|
428
|
+
let pagesScanned = 1;
|
|
429
|
+
const stop = () => { stopped = true; };
|
|
430
|
+
while (!stopped) {
|
|
431
|
+
const pageRows = yield resolve(config.rowSelector, rootLocator).all();
|
|
432
|
+
const smartRows = pageRows.map((r, i) => _makeSmart(r, map, rowIndex + i, pagesScanned - 1));
|
|
433
|
+
if (parallel) {
|
|
434
|
+
const flags = yield Promise.all(smartRows.map((row) => __awaiter(void 0, void 0, void 0, function* () {
|
|
435
|
+
if (dedupeKeys) {
|
|
436
|
+
const key = yield options.dedupe(row);
|
|
437
|
+
if (dedupeKeys.has(key))
|
|
438
|
+
return false;
|
|
439
|
+
dedupeKeys.add(key);
|
|
440
|
+
}
|
|
441
|
+
return predicate({ row, rowIndex: row.rowIndex, stop });
|
|
442
|
+
})));
|
|
443
|
+
smartRows.forEach((row, i) => { if (flags[i])
|
|
444
|
+
matched.push(row); });
|
|
445
|
+
}
|
|
446
|
+
else {
|
|
447
|
+
for (const row of smartRows) {
|
|
448
|
+
if (stopped)
|
|
449
|
+
break;
|
|
450
|
+
if (dedupeKeys) {
|
|
451
|
+
const key = yield options.dedupe(row);
|
|
452
|
+
if (dedupeKeys.has(key))
|
|
453
|
+
continue;
|
|
454
|
+
dedupeKeys.add(key);
|
|
455
|
+
}
|
|
456
|
+
if (yield predicate({ row, rowIndex: row.rowIndex, stop })) {
|
|
457
|
+
matched.push(row);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
rowIndex += smartRows.length;
|
|
462
|
+
if (stopped || pagesScanned >= effectiveMaxPages)
|
|
463
|
+
break;
|
|
464
|
+
const context = { root: rootLocator, config, page: rootLocator.page(), resolve };
|
|
465
|
+
let advanced;
|
|
466
|
+
if (typeof config.strategies.pagination === 'function') {
|
|
467
|
+
advanced = !!(yield config.strategies.pagination(context));
|
|
468
|
+
}
|
|
469
|
+
else {
|
|
470
|
+
advanced = !!(((_c = config.strategies.pagination) === null || _c === void 0 ? void 0 : _c.goNext) && (yield config.strategies.pagination.goNext(context)));
|
|
471
|
+
}
|
|
472
|
+
if (!advanced)
|
|
473
|
+
break;
|
|
474
|
+
tableState.currentPageIndex++;
|
|
475
|
+
pagesScanned++;
|
|
476
|
+
}
|
|
477
|
+
return (0, smartRowArray_1.createSmartRowArray)(matched);
|
|
478
|
+
}),
|
|
253
479
|
iterateThroughTable: (callback, options) => __awaiter(void 0, void 0, void 0, function* () {
|
|
254
480
|
var _a, _b, _c, _d, _e, _f, _g;
|
|
255
481
|
yield _ensureInitialized();
|
|
@@ -275,6 +501,10 @@ const useTable = (rootLocator, configOptions = {}) => {
|
|
|
275
501
|
scrollToColumn: result.scrollToColumn,
|
|
276
502
|
revalidate: result.revalidate,
|
|
277
503
|
generateConfigPrompt: result.generateConfigPrompt,
|
|
504
|
+
forEach: result.forEach,
|
|
505
|
+
map: result.map,
|
|
506
|
+
filter: result.filter,
|
|
507
|
+
[Symbol.asyncIterator]: result[Symbol.asyncIterator].bind(result),
|
|
278
508
|
};
|
|
279
509
|
const getIsFirst = (_b = options === null || options === void 0 ? void 0 : options.getIsFirst) !== null && _b !== void 0 ? _b : (({ index }) => index === 0);
|
|
280
510
|
const getIsLast = (_c = options === null || options === void 0 ? void 0 : options.getIsLast) !== null && _c !== void 0 ? _c : (() => false);
|