@file-viewer/renderer-spreadsheet 3.0.1 → 3.0.3

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.
@@ -13,6 +13,7 @@ interface TableConfigOptions {
13
13
  resizableColumns?: boolean;
14
14
  resizableRows?: boolean;
15
15
  copySelection?: (params: SpreadsheetCopyParams) => void;
16
+ searchCell?: (row: number, col: number) => 'active' | 'match' | undefined;
16
17
  sheetDefaults: SheetDefaults;
17
18
  virtualState: VirtualSheetState;
18
19
  zoomScale?: number;
@@ -32,7 +33,8 @@ export declare const buildColumns: (ws: SheetModel) => {
32
33
  dataKeys: string[];
33
34
  };
34
35
  export declare const getDisplayColumns: (columns: Column[], zoomScale?: number) => Column[];
36
+ export declare const getSearchColumnLeft: (columns: Column[], key: string) => number | undefined;
35
37
  export declare const createTextLayer: (documentRef: Document, value: unknown, style: CellStyleCache, padding: number) => HTMLSpanElement;
36
38
  export declare const normalizeCellStyle: (meta: SheetCellMetadata | undefined) => CellStyleCache | undefined;
37
- export declare const createTableConfig: ({ hostHeight, darkMode, resizableColumns, resizableRows, copySelection, sheetDefaults, virtualState, zoomScale }: TableConfigOptions) => ConfigType;
39
+ export declare const createTableConfig: ({ hostHeight, darkMode, resizableColumns, resizableRows, copySelection, searchCell, sheetDefaults, virtualState, zoomScale }: TableConfigOptions) => ConfigType;
38
40
  export {};
@@ -353,6 +353,28 @@ export const getDisplayColumns = (columns, zoomScale = 1) => {
353
353
  }
354
354
  return columns.map(column => scaleColumn(column, normalizedScale));
355
355
  };
356
+ export const getSearchColumnLeft = (columns, key) => {
357
+ let left = 0;
358
+ const visit = (list) => {
359
+ var _a;
360
+ for (const column of list) {
361
+ if (column.hide)
362
+ continue;
363
+ if ((_a = column.children) === null || _a === void 0 ? void 0 : _a.length) {
364
+ const childLeft = visit(column.children);
365
+ if (childLeft !== undefined)
366
+ return childLeft;
367
+ }
368
+ else {
369
+ if (`${column.key}` === key)
370
+ return left;
371
+ left += Number(column.width) || 0;
372
+ }
373
+ }
374
+ return undefined;
375
+ };
376
+ return visit(columns);
377
+ };
356
378
  const toBorderWidth = (value) => {
357
379
  if (typeof value === 'number' && Number.isFinite(value)) {
358
380
  return Math.max(value, 0);
@@ -883,7 +905,7 @@ export const normalizeCellStyle = (meta) => {
883
905
  }
884
906
  return nextStyle;
885
907
  };
886
- export const createTableConfig = ({ hostHeight, darkMode = false, resizableColumns = false, resizableRows = false, copySelection, sheetDefaults, virtualState, zoomScale = 1 }) => {
908
+ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColumns = false, resizableRows = false, copySelection, searchCell, sheetDefaults, virtualState, zoomScale = 1 }) => {
887
909
  const normalizedScale = normalizeZoomScale(zoomScale);
888
910
  const scaledPadding = scaleNumber(CELL_PADDING, normalizedScale);
889
911
  const scaledHeaderHeight = scaleNumber(HEADER_HEIGHT, normalizedScale);
@@ -920,7 +942,9 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
920
942
  if (getRowState(currentRow) !== RowState.Loaded) {
921
943
  return loadingStyle;
922
944
  }
923
- return scaleCellStyle(virtualState.cellCache.get(getCellCacheKey(rowIndex, colIndex, column)), normalizedScale);
945
+ const style = scaleCellStyle(virtualState.cellCache.get(getCellCacheKey(rowIndex, colIndex, column)), normalizedScale);
946
+ const match = searchCell === null || searchCell === void 0 ? void 0 : searchCell(rowIndex, getDataColumnIndex(column, colIndex));
947
+ return match ? { ...style, backgroundColor: match === 'active' ? '#ffbf47' : '#fff1a8', color: '#202124' } : style;
924
948
  };
925
949
  const renderMethod = ({ row, rowIndex, colIndex, column, value }) => {
926
950
  const currentRow = row;
@@ -938,13 +962,16 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
938
962
  const mirror = !hasRenderableValue(value)
939
963
  ? getLeftOverflowMirror(virtualState, currentRow, rowIndex, dataColIndex, normalizedScale, measureDocument)
940
964
  : undefined;
941
- const renderText = shouldRenderTextInOverlay(style, column) || !!overflowLayout || !!mirror;
965
+ const match = searchCell === null || searchCell === void 0 ? void 0 : searchCell(rowIndex, dataColIndex);
966
+ const renderText = shouldRenderTextInOverlay(style, column) || !!overflowLayout || !!mirror || !!match;
942
967
  if (!hasBorder(style) && !renderText) {
943
968
  return undefined;
944
969
  }
945
970
  return ((cellEl) => {
946
971
  const baseStyle = {
947
972
  ...(style || {}),
973
+ font: (style === null || style === void 0 ? void 0 : style.font) || getBodyFont(normalizedScale),
974
+ color: match ? '#202124' : style === null || style === void 0 ? void 0 : style.color,
948
975
  horizontalAlign: (style === null || style === void 0 ? void 0 : style.horizontalAlign) || (column === null || column === void 0 ? void 0 : column.align),
949
976
  verticalAlign: (style === null || style === void 0 ? void 0 : style.verticalAlign) || (column === null || column === void 0 ? void 0 : column.verticalAlign)
950
977
  };
@@ -952,6 +979,18 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
952
979
  ? getCollapsedBorderStyle(virtualState, rowIndex, dataColIndex, baseStyle, normalizedScale)
953
980
  : baseStyle;
954
981
  renderCellOverlay(cellEl, collapsedStyle, (mirror === null || mirror === void 0 ? void 0 : mirror.style) || collapsedStyle, mirror ? mirror.value : value, renderText, (mirror === null || mirror === void 0 ? void 0 : mirror.overflowLayout) || overflowLayout, normalizedScale);
982
+ cellEl.style.boxShadow = match === 'active' ? 'inset 0 0 0 2px #9a5700' : '';
983
+ if (match) {
984
+ cellEl.dataset.spreadsheetSearch = match;
985
+ cellEl.dataset.spreadsheetRow = `${rowIndex}`;
986
+ cellEl.dataset.spreadsheetCol = `${dataColIndex}`;
987
+ cellEl.style.background = match === 'active' ? '#ffbf47' : '#fff1a8';
988
+ }
989
+ else {
990
+ delete cellEl.dataset.spreadsheetSearch;
991
+ delete cellEl.dataset.spreadsheetRow;
992
+ delete cellEl.dataset.spreadsheetCol;
993
+ }
955
994
  });
956
995
  };
957
996
  return {
@@ -1006,6 +1045,9 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
1006
1045
  RESIZE_ROW_LINE_COLOR: EXCEL_GREEN,
1007
1046
  RESIZE_ROW_MIN_HEIGHT: scaleNumber(RESIZABLE_ROW_MIN_HEIGHT, normalizedScale),
1008
1047
  ENABLE_KEYBOARD: true,
1048
+ // The table finder only indexes loaded rows and competes with the viewer's
1049
+ // workbook-wide search shortcut. Keep one search owner for all integrations.
1050
+ ENABLE_FINDER: false,
1009
1051
  ENABLE_COPY: true,
1010
1052
  BEFORE_COPY_METHOD: copySelection
1011
1053
  ? (params) => {
@@ -1038,7 +1080,7 @@ export const createTableConfig = ({ hostHeight, darkMode = false, resizableColum
1038
1080
  const mirror = !hasRenderableValue(value)
1039
1081
  ? getLeftOverflowMirror(virtualState, currentRow, rowIndex, dataColIndex, normalizedScale, measureDocument)
1040
1082
  : undefined;
1041
- if (shouldRenderTextInOverlay(style, column) || overflowLayout || mirror) {
1083
+ if (shouldRenderTextInOverlay(style, column) || overflowLayout || mirror || (searchCell === null || searchCell === void 0 ? void 0 : searchCell(rowIndex, dataColIndex))) {
1042
1084
  return '';
1043
1085
  }
1044
1086
  if (value === null || value === undefined) {
@@ -1,4 +1,4 @@
1
- import type { Range, WorkSheet } from 'styled-exceljs';
1
+ import type { CellObject, Range, WorkSheet } from 'styled-exceljs';
2
2
  import type { CellMerge, SheetChartDefinition, SheetCellImage, SheetCellMetadata, SheetColumn, SheetModel, SheetStructure, SheetWindow } from '../type.js';
3
3
  export declare const createAutoFitSampleRanges: (totalRowCount: number, totalColCount: number) => Range[];
4
4
  export declare const defaults: {
@@ -16,6 +16,7 @@ interface SheetSliceOptions {
16
16
  interface SheetObjectOptions {
17
17
  includeLayout?: boolean;
18
18
  }
19
+ export declare const formatCellValue: (cell?: CellObject) => string;
19
20
  export default class SheetJsModel implements SheetModel {
20
21
  private readonly _ws;
21
22
  private readonly _startRow;
@@ -61,7 +61,7 @@ export const defaults = {
61
61
  const cellKey = (row, col) => {
62
62
  return `${row}-${col}`;
63
63
  };
64
- const formatCellValue = (cell) => {
64
+ export const formatCellValue = (cell) => {
65
65
  if (!cell) {
66
66
  return '';
67
67
  }
@@ -30,6 +30,19 @@ export interface SpreadsheetWorkerResponse {
30
30
  type: string;
31
31
  payload?: Record<string, any>;
32
32
  }
33
+ export interface SpreadsheetSearchOptions {
34
+ caseSensitive?: boolean;
35
+ wholeWord?: boolean;
36
+ maxMatches?: number;
37
+ }
38
+ export interface SpreadsheetSearchMatch {
39
+ sheet: number;
40
+ sheetName: string;
41
+ row: number;
42
+ col: number;
43
+ text: string;
44
+ matchText: string;
45
+ }
33
46
  export declare const createSpreadsheetParserContext: () => SpreadsheetParserContext;
34
47
  interface WorksheetRangeLike extends WorksheetWithDrawings {
35
48
  '!ref'?: string;
@@ -51,5 +64,6 @@ export interface WorksheetDisplayBounds {
51
64
  export declare const getWorksheetDisplayBounds: (worksheet: WorksheetRangeLike | undefined, charts: SheetChartDefinition[] | undefined) => WorksheetDisplayBounds;
52
65
  export declare const parseSpreadsheetWorkbook: (context: SpreadsheetParserContext, data: ArrayBuffer, source?: SpreadsheetTextSource) => Promise<SpreadsheetWorkerResponse[]>;
53
66
  export declare const parseSpreadsheetSheet: (context: SpreadsheetParserContext, payload?: Record<string, any>) => SpreadsheetWorkerResponse[];
67
+ export declare const searchSpreadsheetWorkbook: (context: SpreadsheetParserContext, query: string, options?: SpreadsheetSearchOptions) => SpreadsheetSearchMatch[];
54
68
  export declare const handleSpreadsheetWorkerRequest: (context: SpreadsheetParserContext, request: SpreadsheetWorkerRequest) => SpreadsheetWorkerResponse[] | Promise<SpreadsheetWorkerResponse[]>;
55
69
  export {};
@@ -1,5 +1,5 @@
1
1
  import { read, utils } from 'styled-exceljs';
2
- import SheetJsModel from './SheetJsModel.js';
2
+ import SheetJsModel, { formatCellValue } from './SheetJsModel.js';
3
3
  import { parseSpreadsheetCharts } from './chartParser.js';
4
4
  import { prepareSpreadsheetReadInput, } from './textEncoding.js';
5
5
  import { parseSpreadsheetCellImages } from './richDataParser.js';
@@ -336,8 +336,104 @@ export const parseSpreadsheetSheet = (context, payload = {}) => {
336
336
  return [toErrorResponse(error, { sessionId, startRow })];
337
337
  }
338
338
  };
339
+ const escapeSearchRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
340
+ const createSpreadsheetSearchRegExp = (query, options) => {
341
+ const source = options.wholeWord
342
+ ? `\\b${escapeSearchRegExp(query)}\\b`
343
+ : escapeSearchRegExp(query);
344
+ return new RegExp(source, options.caseSensitive ? 'g' : 'gi');
345
+ };
346
+ const visitWorksheetCells = (worksheet, visit) => {
347
+ const candidate = worksheet;
348
+ const rows = Array.isArray(worksheet)
349
+ ? worksheet
350
+ : candidate['!data'];
351
+ if (rows) {
352
+ for (const rowKey of Object.keys(rows)) {
353
+ const row = rows[Number(rowKey)];
354
+ const rowIndex = Number(rowKey);
355
+ if (!Number.isInteger(rowIndex) || rowIndex < 0 || !Array.isArray(row)) {
356
+ continue;
357
+ }
358
+ for (const colKey of Object.keys(row)) {
359
+ const colIndex = Number(colKey);
360
+ const cell = row[colIndex];
361
+ if (!Number.isInteger(colIndex) || colIndex < 0 || !cell) {
362
+ continue;
363
+ }
364
+ if (!visit(cell, rowIndex, colIndex)) {
365
+ return false;
366
+ }
367
+ }
368
+ }
369
+ return true;
370
+ }
371
+ for (const key of Object.keys(worksheet)) {
372
+ if (key.startsWith('!') || !/^[A-Z]+[1-9][0-9]*$/i.test(key)) {
373
+ continue;
374
+ }
375
+ const cell = worksheet[key];
376
+ if (!cell) {
377
+ continue;
378
+ }
379
+ let position;
380
+ try {
381
+ position = utils.decode_cell(key);
382
+ }
383
+ catch {
384
+ continue;
385
+ }
386
+ if (!visit(cell, position.r, position.c)) {
387
+ return false;
388
+ }
389
+ }
390
+ return true;
391
+ };
392
+ export const searchSpreadsheetWorkbook = (context, query, options = {}) => {
393
+ var _a;
394
+ const normalizedQuery = query.replace(/\s+/g, ' ').trim();
395
+ if (!normalizedQuery || !((_a = context.workbook) === null || _a === void 0 ? void 0 : _a.Sheets)) {
396
+ return [];
397
+ }
398
+ const maxMatches = Math.max(1, Math.floor(options.maxMatches || 1000));
399
+ const expression = createSpreadsheetSearchRegExp(normalizedQuery, options);
400
+ const matches = [];
401
+ for (const sheet of context.sheets) {
402
+ const worksheet = context.workbook.Sheets[sheet.name];
403
+ if (!worksheet) {
404
+ continue;
405
+ }
406
+ const completed = visitWorksheetCells(worksheet, (cell, row, col) => {
407
+ const text = formatCellValue(cell);
408
+ if (!text) {
409
+ return true;
410
+ }
411
+ expression.lastIndex = 0;
412
+ let match;
413
+ while ((match = expression.exec(text)) && matches.length < maxMatches) {
414
+ if (!match[0]) {
415
+ expression.lastIndex += 1;
416
+ continue;
417
+ }
418
+ matches.push({
419
+ sheet: sheet.id,
420
+ sheetName: sheet.name,
421
+ row,
422
+ col,
423
+ text,
424
+ matchText: match[0],
425
+ });
426
+ }
427
+ return matches.length < maxMatches;
428
+ });
429
+ if (!completed || matches.length >= maxMatches) {
430
+ break;
431
+ }
432
+ }
433
+ return matches;
434
+ };
339
435
  export const handleSpreadsheetWorkerRequest = (context, request) => {
340
- var _a, _b, _c, _d;
436
+ var _a, _b, _c, _d, _e, _f, _g;
341
437
  switch (request.type) {
342
438
  case 'parseWorkbook':
343
439
  return parseSpreadsheetWorkbook(context, (_a = request.payload) === null || _a === void 0 ? void 0 : _a.workbook, {
@@ -347,6 +443,15 @@ export const handleSpreadsheetWorkerRequest = (context, request) => {
347
443
  });
348
444
  case 'parseSheet':
349
445
  return parseSpreadsheetSheet(context, request.payload);
446
+ case 'searchWorkbook':
447
+ return [{
448
+ type: 'searchWorkbook',
449
+ payload: {
450
+ requestId: (_e = request.payload) === null || _e === void 0 ? void 0 : _e.requestId,
451
+ query: ((_f = request.payload) === null || _f === void 0 ? void 0 : _f.query) || '',
452
+ matches: searchSpreadsheetWorkbook(context, ((_g = request.payload) === null || _g === void 0 ? void 0 : _g.query) || '', request.payload),
453
+ },
454
+ }];
350
455
  default:
351
456
  return [];
352
457
  }
@@ -1,8 +1,8 @@
1
- import { createFileViewerWorkerController, createFileViewerTranslator, createFileViewerZoomChangeEmitter as createZoomChangeEmitter, registerFileViewerZoomProvider, resolveFileViewerColorScheme, resolveFileViewerFitScale, resolveFileViewerRuntimeAssetBaseUrl, resolveFileViewerSpreadsheetWorkerUrl, unregisterFileViewerZoomProvider, } from '@file-viewer/core';
1
+ import { createFileViewerWorkerController, createFileViewerTranslator, createFileViewerZoomChangeEmitter as createZoomChangeEmitter, createEmptyFileViewerSearchState, registerFileViewerSearchProvider, registerFileViewerZoomProvider, resolveFileViewerColorScheme, resolveFileViewerFitScale, resolveFileViewerRuntimeAssetBaseUrl, resolveFileViewerSpreadsheetWorkerUrl, unregisterFileViewerSearchProvider, unregisterFileViewerZoomProvider, } from '@file-viewer/core';
2
2
  import { renderSpreadsheetChart } from './spreadsheet/chartRenderer.js';
3
3
  import { createSpreadsheetImageSourceResolver } from './spreadsheet/imageSource.js';
4
- import { buildRows, clampWindowStart, collectWindowStarts, createEmptyVirtualState, DEFAULT_SHEET_DEFAULTS, displayCellKey, getDataKey, INDEX_COLUMN_KEY, markWindowState, ROW_STATE_FIELD, RowState, WINDOW_SIZE, } from './spreadsheet/state.js';
5
- import { buildColumns, createTableConfig, detectIndexOffset, getDisplayColumns, getRowHeight, HEADER_HEIGHT, INDEX_COLUMN_WIDTH, normalizeCellStyle, normalizeRowHeight, RESIZABLE_COLUMN_MIN_WIDTH, RESIZABLE_ROW_MIN_HEIGHT, SPREADSHEET_MAX_ZOOM, SPREADSHEET_MIN_ZOOM, } from './spreadsheet/view.js';
4
+ import { buildRows, clampWindowStart, collectWindowStarts, createEmptyVirtualState, DEFAULT_SHEET_DEFAULTS, displayCellKey, getDataKey, getWindowStart, INDEX_COLUMN_KEY, markWindowState, ROW_STATE_FIELD, RowState, WINDOW_SIZE, } from './spreadsheet/state.js';
5
+ import { buildColumns, createTableConfig, detectIndexOffset, getDisplayColumns, getSearchColumnLeft, getRowHeight, HEADER_HEIGHT, INDEX_COLUMN_WIDTH, normalizeCellStyle, normalizeRowHeight, RESIZABLE_COLUMN_MIN_WIDTH, RESIZABLE_ROW_MIN_HEIGHT, SPREADSHEET_MAX_ZOOM, SPREADSHEET_MIN_ZOOM, } from './spreadsheet/view.js';
6
6
  const EXCEL_IMAGE_SCROLLBAR_GUARD = 18;
7
7
  const DEFAULT_SPREADSHEET_WORKER_AUTO_THRESHOLD = 1 * 1024 * 1024;
8
8
  const E_VIRT_TABLE_STYLE_MARKERS = [
@@ -556,6 +556,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
556
556
  root.className = 'excel-wrapper';
557
557
  root.dataset.fileViewerSpreadsheetRoot = 'true';
558
558
  root.dataset.spreadsheetTheme = darkMode ? 'dark' : 'light';
559
+ root.dataset.viewerSearchProvider = 'spreadsheet';
559
560
  root.dataset.viewerZoomProvider = 'xlsx';
560
561
  const loading = documentRef.createElement('div');
561
562
  loading.className = 'loading';
@@ -666,15 +667,83 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
666
667
  let imageLightboxPreviousFocus = null;
667
668
  let hasNotifiedFirstPaint = false;
668
669
  let hasAppliedDefaultInitialFit = false;
670
+ let searchState = createEmptyFileViewerSearchState();
671
+ let searchMatches = [];
672
+ let searchCells = new Set();
673
+ let searchOptions = {};
674
+ let searchRequestSequence = 0;
675
+ let latestSearchRequest = 0;
676
+ let pendingSearchJump = null;
677
+ let resolveWorkbookReady = null;
678
+ const workbookReady = new Promise(resolve => {
679
+ resolveWorkbookReady = resolve;
680
+ });
669
681
  const resizableColumns = ((_f = (_e = context === null || context === void 0 ? void 0 : context.options) === null || _e === void 0 ? void 0 : _e.spreadsheet) === null || _f === void 0 ? void 0 : _f.resizableColumns) === true;
670
682
  const resizableRows = ((_h = (_g = context === null || context === void 0 ? void 0 : context.options) === null || _g === void 0 ? void 0 : _g.spreadsheet) === null || _h === void 0 ? void 0 : _h.resizableRows) === true;
671
683
  const controller = createFileViewerWorkerController(createSpreadsheetWorkerFactory(target, buffer.byteLength, context), { logErrors: false });
684
+ const pendingSearchRequests = new Map();
672
685
  const getActiveSheet = () => sheets.find(sheet => sheet.id === sheetIndex);
673
686
  const getSheetTabs = () => {
674
687
  const visible = sheets.filter(sheet => !sheet.hidden);
675
688
  return visible.length ? visible : sheets;
676
689
  };
677
690
  const getActiveSheetId = () => { var _a; return sheetIndex !== null && sheetIndex !== void 0 ? sheetIndex : (_a = sheets[0]) === null || _a === void 0 ? void 0 : _a.id; };
691
+ const getColumnLabel = (column) => {
692
+ let value = Math.max(0, column) + 1;
693
+ let label = '';
694
+ while (value > 0) {
695
+ const remainder = (value - 1) % 26;
696
+ label = String.fromCharCode(65 + remainder) + label;
697
+ value = Math.floor((value - 1) / 26);
698
+ }
699
+ return label;
700
+ };
701
+ const createSpreadsheetSearchAnchor = (match, index) => ({
702
+ id: `spreadsheet-cell-${match.sheet}-${match.row}-${match.col}`,
703
+ index,
704
+ line: match.row + 1,
705
+ type: 'block',
706
+ label: `${match.sheetName}!${getColumnLabel(match.col)}${match.row + 1}`,
707
+ text: match.text,
708
+ top: match.row * sheetDefaults.rowHeight,
709
+ left: match.col * sheetDefaults.colWidth,
710
+ width: sheetDefaults.colWidth,
711
+ height: sheetDefaults.rowHeight,
712
+ spreadsheet: {
713
+ sheetId: match.sheet,
714
+ row: match.row,
715
+ col: match.col,
716
+ },
717
+ });
718
+ const setSearchState = (query, matches, currentIndex = matches.length ? 0 : -1) => {
719
+ const normalizedIndex = matches.length
720
+ ? ((currentIndex % matches.length) + matches.length) % matches.length
721
+ : -1;
722
+ searchMatches = matches;
723
+ searchCells = new Set(matches.map(match => {
724
+ var _a;
725
+ const cell = (_a = match.anchor) === null || _a === void 0 ? void 0 : _a.spreadsheet;
726
+ return cell ? `${cell.sheetId}:${cell.row}:${cell.col}` : '';
727
+ }));
728
+ searchState = {
729
+ query,
730
+ total: matches.length,
731
+ currentIndex: normalizedIndex,
732
+ current: normalizedIndex >= 0 ? matches[normalizedIndex] : null,
733
+ matches,
734
+ };
735
+ table === null || table === void 0 ? void 0 : table.draw();
736
+ return searchState;
737
+ };
738
+ const getSearchCell = (row, col) => {
739
+ var _a, _b;
740
+ if (!searchCells.has(`${getActiveSheetId()}:${row}:${col}`))
741
+ return undefined;
742
+ const current = (_b = (_a = searchState.current) === null || _a === void 0 ? void 0 : _a.anchor) === null || _b === void 0 ? void 0 : _b.spreadsheet;
743
+ return (current === null || current === void 0 ? void 0 : current.sheetId) === getActiveSheetId() && current.row === row && current.col === col
744
+ ? 'active'
745
+ : 'match';
746
+ };
678
747
  const getHostHeight = () => tableHost.clientHeight || 0;
679
748
  const showBlockingLoading = () => !errorMessage && !hasInitialWindow && (loadingState || sheetInitializing);
680
749
  const showStreamingLoading = () => !showBlockingLoading() &&
@@ -922,6 +991,17 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
922
991
  setLoading(true);
923
992
  controller.emit(type, payload);
924
993
  };
994
+ const requestWorkbookSearch = (query, options) => new Promise((resolve, reject) => {
995
+ const requestId = ++searchRequestSequence;
996
+ pendingSearchRequests.set(requestId, { resolve, reject });
997
+ controller.emit('searchWorkbook', {
998
+ requestId,
999
+ query,
1000
+ caseSensitive: options.caseSensitive === true,
1001
+ wholeWord: options.wholeWord === true,
1002
+ maxMatches: options.maxMatches,
1003
+ });
1004
+ });
925
1005
  const applyRowHeight = (row, baseHeight) => {
926
1006
  row.__baseHeight = baseHeight;
927
1007
  row._height = scaleRowHeight(baseHeight);
@@ -1101,6 +1181,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1101
1181
  resizableColumns,
1102
1182
  resizableRows,
1103
1183
  copySelection: copySpreadsheetSelection,
1184
+ searchCell: getSearchCell,
1104
1185
  sheetDefaults,
1105
1186
  virtualState,
1106
1187
  zoomScale: zoom,
@@ -1158,6 +1239,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1158
1239
  resizableColumns,
1159
1240
  resizableRows,
1160
1241
  copySelection: copySpreadsheetSelection,
1242
+ searchCell: getSearchCell,
1161
1243
  sheetDefaults,
1162
1244
  virtualState,
1163
1245
  zoomScale: zoom,
@@ -1179,6 +1261,7 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1179
1261
  resizableColumns,
1180
1262
  resizableRows,
1181
1263
  copySelection: copySpreadsheetSelection,
1264
+ searchCell: getSearchCell,
1182
1265
  sheetDefaults,
1183
1266
  virtualState,
1184
1267
  zoomScale: zoom,
@@ -1306,8 +1389,14 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1306
1389
  if (activeSheetId !== undefined) {
1307
1390
  sheetStateCache.set(activeSheetId, virtualState);
1308
1391
  }
1309
- clearTableResizableHeaderCache();
1310
- syncTableLayout();
1392
+ // e-virt-table writes its pixel-width cache after emitting the resize event.
1393
+ // Clear it after that write so our unscaled, per-sheet widths remain authoritative.
1394
+ queueMicrotask(() => {
1395
+ if (disposed || !table)
1396
+ return;
1397
+ clearTableResizableHeaderCache();
1398
+ syncTableLayout();
1399
+ });
1311
1400
  }
1312
1401
  function handleRowResizeChange(event) {
1313
1402
  if (!resizableRows || disposed) {
@@ -1540,6 +1629,8 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1540
1629
  if (isFirstWindow) {
1541
1630
  scheduleStableFirstPaintRefresh();
1542
1631
  }
1632
+ requestPendingSearchWindow();
1633
+ flushPendingSearchJump();
1543
1634
  const start = viewportRange.start || meta.startRow;
1544
1635
  const end = Math.max(viewportRange.end, meta.endRow - 1, meta.startRow);
1545
1636
  ensureViewportWindows(start, end);
@@ -1615,6 +1706,72 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1615
1706
  resetViewState();
1616
1707
  requestWindow(0, false);
1617
1708
  };
1709
+ const getSearchRowTop = (rowIndex) => {
1710
+ var _a;
1711
+ let top = scalePx(HEADER_HEIGHT);
1712
+ for (let index = 0; index < rowIndex; index += 1) {
1713
+ const height = (_a = virtualState.rowHeightCache.get(index)) !== null && _a !== void 0 ? _a : virtualState.defaults.rowHeight;
1714
+ top += scaleRowHeight(height);
1715
+ }
1716
+ return top;
1717
+ };
1718
+ function flushPendingSearchJump() {
1719
+ const pending = pendingSearchJump;
1720
+ if (!pending ||
1721
+ pending.sheetId !== getActiveSheetId() ||
1722
+ !virtualState.loadedWindows.has(getWindowStart(pending.row, virtualState.totalRows)) ||
1723
+ !table) {
1724
+ return;
1725
+ }
1726
+ requestAnimationFrame(() => {
1727
+ if (disposed || !table || pendingSearchJump !== pending || pending.sheetId !== getActiveSheetId()) {
1728
+ return;
1729
+ }
1730
+ pendingSearchJump = null;
1731
+ const targetTop = Math.max(0, getSearchRowTop(pending.row) - Math.max(0, (tableHost.clientHeight || 0) * 0.35));
1732
+ // The vendor's rendered header index can still be empty before its first
1733
+ // draw. Source column geometry is ready as soon as the window is loaded.
1734
+ const columnLeft = getSearchColumnLeft(getDisplayColumns(virtualState.columns, zoom), virtualState.dataKeys[pending.col] || getDataKey(pending.col));
1735
+ const targetLeft = columnLeft === undefined
1736
+ ? table.ctx.scrollX || 0
1737
+ : Math.max(0, columnLeft - tableHost.clientWidth / 2);
1738
+ table.scrollTo(targetLeft, targetTop);
1739
+ table.draw();
1740
+ syncImageViewport();
1741
+ scheduleViewportLoad();
1742
+ });
1743
+ }
1744
+ function requestPendingSearchWindow() {
1745
+ const pending = pendingSearchJump;
1746
+ if (!pending || pending.sheetId !== getActiveSheetId() || !virtualState.totalRows) {
1747
+ return;
1748
+ }
1749
+ const windowStart = getWindowStart(pending.row, virtualState.totalRows);
1750
+ if (virtualState.loadedWindows.has(windowStart)) {
1751
+ flushPendingSearchJump();
1752
+ return;
1753
+ }
1754
+ requestWindow(windowStart, false);
1755
+ }
1756
+ function jumpToSpreadsheetSearchMatch(match) {
1757
+ var _a, _b;
1758
+ const spreadsheet = (_a = match === null || match === void 0 ? void 0 : match.anchor) === null || _a === void 0 ? void 0 : _a.spreadsheet;
1759
+ pendingSearchJump = spreadsheet || null;
1760
+ if (!spreadsheet) {
1761
+ return;
1762
+ }
1763
+ if (spreadsheet.sheetId !== getActiveSheetId()) {
1764
+ cacheCurrentSheetState();
1765
+ sheetIndex = spreadsheet.sheetId;
1766
+ renderChrome();
1767
+ startSheetSession();
1768
+ scrollActiveSheetIntoView();
1769
+ const view = getTargetWindow(target);
1770
+ (_b = view === null || view === void 0 ? void 0 : view.queueMicrotask) === null || _b === void 0 ? void 0 : _b.call(view, requestPendingSearchWindow);
1771
+ return;
1772
+ }
1773
+ requestPendingSearchWindow();
1774
+ }
1618
1775
  function handleSheet(index) {
1619
1776
  if (sheetIndex === index) {
1620
1777
  scrollActiveSheetIntoView();
@@ -1626,6 +1783,68 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1626
1783
  startSheetSession();
1627
1784
  scrollActiveSheetIntoView();
1628
1785
  }
1786
+ controller.onWorkerEvent('searchWorkbook', ({ requestId, matches }) => {
1787
+ if (typeof requestId !== 'number') {
1788
+ return;
1789
+ }
1790
+ const pending = pendingSearchRequests.get(requestId);
1791
+ if (!pending) {
1792
+ return;
1793
+ }
1794
+ pendingSearchRequests.delete(requestId);
1795
+ pending.resolve(Array.isArray(matches) ? matches : []);
1796
+ });
1797
+ const searchProvider = {
1798
+ async search(query, options = {}) {
1799
+ const normalizedQuery = query.replace(/\s+/g, ' ').trim();
1800
+ searchOptions = options;
1801
+ const requestNumber = ++latestSearchRequest;
1802
+ if (!normalizedQuery) {
1803
+ pendingSearchJump = null;
1804
+ return setSearchState('', []);
1805
+ }
1806
+ await workbookReady;
1807
+ const matches = await requestWorkbookSearch(normalizedQuery, searchOptions);
1808
+ if (requestNumber !== latestSearchRequest || disposed) {
1809
+ return searchState;
1810
+ }
1811
+ const nextMatches = matches.map((match, index) => ({
1812
+ id: `spreadsheet-search-${match.sheet}-${match.row}-${match.col}-${index}`,
1813
+ index,
1814
+ text: match.matchText,
1815
+ anchor: createSpreadsheetSearchAnchor(match, index),
1816
+ line: match.row + 1,
1817
+ }));
1818
+ const nextState = setSearchState(normalizedQuery, nextMatches);
1819
+ jumpToSpreadsheetSearchMatch(nextState.current);
1820
+ return nextState;
1821
+ },
1822
+ next() {
1823
+ if (!searchMatches.length) {
1824
+ return searchState;
1825
+ }
1826
+ const nextState = setSearchState(searchState.query, searchMatches, searchState.currentIndex + 1);
1827
+ jumpToSpreadsheetSearchMatch(nextState.current);
1828
+ return nextState;
1829
+ },
1830
+ previous() {
1831
+ if (!searchMatches.length) {
1832
+ return searchState;
1833
+ }
1834
+ const nextState = setSearchState(searchState.query, searchMatches, searchState.currentIndex - 1);
1835
+ jumpToSpreadsheetSearchMatch(nextState.current);
1836
+ return nextState;
1837
+ },
1838
+ clear() {
1839
+ latestSearchRequest += 1;
1840
+ pendingSearchJump = null;
1841
+ return setSearchState('', []);
1842
+ },
1843
+ getState() {
1844
+ return searchState;
1845
+ },
1846
+ };
1847
+ registerFileViewerSearchProvider(root, searchProvider);
1629
1848
  const emitParseWorkbook = () => {
1630
1849
  var _a, _b;
1631
1850
  emitWorker('parseWorkbook', {
@@ -1637,6 +1856,8 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1637
1856
  };
1638
1857
  controller.onWorkerEvent('sheets', ({ sheets: list }) => {
1639
1858
  sheets = list;
1859
+ resolveWorkbookReady === null || resolveWorkbookReady === void 0 ? void 0 : resolveWorkbookReady();
1860
+ resolveWorkbookReady = null;
1640
1861
  const firstSheet = list.find((sheet) => !sheet.hidden) || list[0];
1641
1862
  if (firstSheet) {
1642
1863
  sheetIndex = firstSheet.id;
@@ -1656,6 +1877,8 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1656
1877
  applyVirtualWindow(ws);
1657
1878
  });
1658
1879
  controller.onWorkerEvent('parseError', ({ sessionId, startRow, message }) => {
1880
+ resolveWorkbookReady === null || resolveWorkbookReady === void 0 ? void 0 : resolveWorkbookReady();
1881
+ resolveWorkbookReady = null;
1659
1882
  if (sessionId && sessionId !== sheetSessionId) {
1660
1883
  return;
1661
1884
  }
@@ -1743,6 +1966,14 @@ const renderFileViewerSpreadsheet = async (buffer, target, type, context) => {
1743
1966
  clearScheduledLayoutRefresh();
1744
1967
  resizeObserver === null || resizeObserver === void 0 ? void 0 : resizeObserver.disconnect();
1745
1968
  resizeObserver = null;
1969
+ pendingSearchJump = null;
1970
+ pendingSearchRequests.forEach(({ reject }) => {
1971
+ reject(new Error('Spreadsheet renderer was unmounted before search completed.'));
1972
+ });
1973
+ pendingSearchRequests.clear();
1974
+ resolveWorkbookReady === null || resolveWorkbookReady === void 0 ? void 0 : resolveWorkbookReady();
1975
+ resolveWorkbookReady = null;
1976
+ unregisterFileViewerSearchProvider(root);
1746
1977
  unregisterFileViewerZoomProvider(root);
1747
1978
  controller.destroy();
1748
1979
  table === null || table === void 0 ? void 0 : table.destroy();