fix(sheets): extend Ctrl+F beyond the loaded window on streamed workbooks (#131)

This commit is contained in:
ANIRUDDHA ADAK
2026-08-24 07:20:10 +08:00
committed by GitHub
parent 6d9b6812dd
commit afc6711d9c
7 changed files with 1195 additions and 2 deletions
+2
View File
@@ -35,6 +35,7 @@
"@univerjs/core": "^0.25.1",
"@univerjs/data-validation": "^0.25.1",
"@univerjs/engine-render": "^0.25.1",
"@univerjs/find-replace": "^0.25.1",
"@univerjs/preset-sheets-conditional-formatting": "^0.25.1",
"@univerjs/preset-sheets-core": "^0.25.1",
"@univerjs/preset-sheets-data-validation": "^0.25.1",
@@ -50,6 +51,7 @@
"jszip": "^3.10.1",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"rxjs": "^7.8.2",
"zod": "^4.3.6"
},
"devDependencies": {
+5
View File
@@ -145,6 +145,7 @@ import {
} from '../domain/chart-visual'
import { InMemoryWorkbookAdapter } from '../domain/in-memory-workbook'
import { cfRuleUnsaveableReason, iconSetSaveable } from '../gateway/xlsx-cf'
import { installLazyFindBridge } from './lazy-find'
import type { ApplyOutcome, ChangePlan } from '../domain/workbook.types'
import { createElectronTransport } from './ai/transport'
import { MAX_READ_RANGE_CELLS, type ActiveSheetInfo, type SheetsSkillDeps } from './ai/tools'
@@ -1475,6 +1476,9 @@ export function App(): React.JSX.Element {
// Rule-management panels show what each rule actually does: list options /
// source range, CF formula text, ⚠ on #REF! dead rules.
const ruleDetailDisposable = installRuleDetail(runtime)
// Ctrl+F covers every row of a streamed workbook, not just the loaded
// window: the bridge pages the underlying file for out-of-window hits.
const lazyFindDisposable = installLazyFindBridge({ runtime, lazyWorkbookRef, setMessage })
const scrollDisposable = runtime.univerAPI.addEvent(
runtime.univerAPI.Event.Scroll,
(params) => {
@@ -2328,6 +2332,7 @@ export function App(): React.JSX.Element {
copyMaterializeDisposable.dispose()
dataValidationArrowDisposable.dispose()
ruleDetailDisposable()
lazyFindDisposable.dispose()
scrollDisposable.dispose()
zoomDisposable.dispose()
editStartDisposable.dispose()
@@ -20,9 +20,9 @@ import type { WorkbookReadContext } from './workbook-readers'
export const ERROR_VALUE_RE = /^#(?:REF!|DIV\/0!|VALUE!|NAME\?|N\/A|NUM!|NULL!|SPILL!|CALC!)$/
/** Total cells (by scanned extent) one find_cells call may cover. */
const MAX_SCAN_CELLS = 400_000
export const MAX_SCAN_CELLS = 400_000
/** Row batches sized to stay under the sidecar's per-read cell budget. */
const FILE_READ_BATCH_CELLS = 18_000
export const FILE_READ_BATCH_CELLS = 18_000
type Matcher = (value: CellScalar | undefined, formula: string | undefined) => boolean
@@ -374,6 +374,7 @@ export const appStrings = defineStrings({
appZoom: '缩放 {percent}%。',
appTopRowFrozen: '已冻结首行——⌘S 保存。',
appFirstColFrozen: '已冻结首列——⌘S 保存。',
appFindScanTruncated: '大工作表:搜索提前停止(已扫描 {cells} 个单元格),结果可能不完整。',
appReplaceNeedsFullLoad: '替换需要完整加载模式——请改用查找。',
appGridlinesHiddenSave: '网格线已隐藏——⌘S 保存。',
appGridlinesShownSave: '网格线已显示——⌘S 保存。',
@@ -1652,6 +1653,8 @@ export const appStrings = defineStrings({
appZoom: 'Zoom {percent}%.',
appTopRowFrozen: 'Top row frozen — saves with ⌘S.',
appFirstColFrozen: 'First column frozen — saves with ⌘S.',
appFindScanTruncated:
'Large sheet: search stopped after {cells} cells — results may be incomplete.',
appReplaceNeedsFullLoad: 'Replace needs the fully-loaded mode — use Find instead.',
appGridlinesHiddenSave: 'Gridlines hidden — saves with ⌘S.',
appGridlinesShownSave: 'Gridlines shown — saves with ⌘S.',
@@ -2973,6 +2976,8 @@ export const appStrings = defineStrings({
appZoom: 'ズーム {percent}%。',
appTopRowFrozen: '先頭行を固定しました — ⌘S で保存します。',
appFirstColFrozen: '先頭列を固定しました — ⌘S で保存します。',
appFindScanTruncated:
'大きなシート: {cells} セルで検索を中断しました。結果が不完全な場合があります。',
appReplaceNeedsFullLoad: '置換には完全読み込みモードが必要です — 検索をご利用ください。',
appGridlinesHiddenSave: '目盛線を非表示にしました — ⌘S で保存します。',
appGridlinesShownSave: '目盛線を表示しました — ⌘S で保存します。',
@@ -4301,6 +4306,8 @@ export const appStrings = defineStrings({
appZoom: '확대/축소 {percent}%.',
appTopRowFrozen: '첫 행을 고정했습니다 — ⌘S로 저장합니다.',
appFirstColFrozen: '첫 열을 고정했습니다 — ⌘S로 저장합니다.',
appFindScanTruncated:
'큰 시트: {cells}개 셀에서 검색을 중단했습니다. 결과가 불완전할 수 있습니다.',
appReplaceNeedsFullLoad: '바꾸기에는 전체 로드 모드가 필요합니다 — 대신 찾기를 사용하십시오.',
appGridlinesHiddenSave: '눈금선을 숨겼습니다 — ⌘S로 저장합니다.',
appGridlinesShownSave: '눈금선을 표시했습니다 — ⌘S로 저장합니다.',
@@ -5654,6 +5661,8 @@ export const appStrings = defineStrings({
appZoom: 'Zoom {percent} %.',
appTopRowFrozen: 'Ligne supérieure figée — enregistrez avec ⌘S.',
appFirstColFrozen: 'Première colonne figée — enregistrez avec ⌘S.',
appFindScanTruncated:
'Grande feuille : recherche interrompue après {cells} cellules — les résultats peuvent être incomplets.',
appReplaceNeedsFullLoad:
'Le remplacement nécessite le mode de chargement complet — utilisez plutôt Rechercher.',
appGridlinesHiddenSave: 'Quadrillage masqué — enregistrez avec ⌘S.',
@@ -7001,6 +7010,8 @@ export const appStrings = defineStrings({
appZoom: 'Zoom {percent} %.',
appTopRowFrozen: 'Oberste Zeile fixiert — mit ⌘S speichern.',
appFirstColFrozen: 'Erste Spalte fixiert — mit ⌘S speichern.',
appFindScanTruncated:
'Großes Blatt: Suche nach {cells} Zellen abgebrochen – Ergebnisse können unvollständig sein.',
appReplaceNeedsFullLoad:
'Ersetzen erfordert den Volllademodus — verwenden Sie stattdessen Suchen.',
appGridlinesHiddenSave: 'Gitternetzlinien ausgeblendet — mit ⌘S speichern.',
@@ -8342,6 +8353,8 @@ export const appStrings = defineStrings({
appZoom: 'Zoom {percent} %.',
appTopRowFrozen: 'Fila superior inmovilizada — guarde con ⌘S.',
appFirstColFrozen: 'Primera columna inmovilizada — guarde con ⌘S.',
appFindScanTruncated:
'Hoja grande: la búsqueda se detuvo tras {cells} celdas; los resultados pueden estar incompletos.',
appReplaceNeedsFullLoad:
'Reemplazar requiere el modo de carga completa — use Buscar en su lugar.',
appGridlinesHiddenSave: 'Líneas de cuadrícula ocultas — guarde con ⌘S.',
@@ -9633,6 +9646,7 @@ export const appStrings = defineStrings({
appZoom: 'ย่อ/ขยาย {percent}%',
appTopRowFrozen: 'ตรึงแถวบนสุดแล้ว — บันทึกด้วย ⌘S',
appFirstColFrozen: 'ตรึงคอลัมน์แรกแล้ว — บันทึกด้วย ⌘S',
appFindScanTruncated: 'ชีตขนาดใหญ่: หยุดการค้นหาหลังจาก {cells} เซลล์ ผลลัพธ์อาจไม่ครบถ้วน',
appReplaceNeedsFullLoad: 'การแทนที่ต้องใช้โหมดโหลดเต็ม — ใช้ค้นหาแทน',
appGridlinesHiddenSave: 'ซ่อนเส้นตารางแล้ว — บันทึกด้วย ⌘S',
appGridlinesShownSave: 'แสดงเส้นตารางแล้ว — บันทึกด้วย ⌘S',
@@ -10914,6 +10928,8 @@ export const appStrings = defineStrings({
appZoom: 'Zoom {percent}%.',
appTopRowFrozen: 'Baris atas dibekukan — simpan dengan ⌘S.',
appFirstColFrozen: 'Kolom pertama dibekukan — simpan dengan ⌘S.',
appFindScanTruncated:
'Lembar besar: pencarian berhenti setelah {cells} sel — hasil mungkin tidak lengkap.',
appReplaceNeedsFullLoad:
'Mengganti memerlukan mode muat penuh — gunakan Temukan sebagai gantinya.',
appGridlinesHiddenSave: 'Garis kisi disembunyikan — simpan dengan ⌘S.',
@@ -12228,6 +12244,8 @@ export const appStrings = defineStrings({
appZoom: 'Масштаб {percent}%.',
appTopRowFrozen: 'Верхняя строка закреплена — сохраните с помощью ⌘S.',
appFirstColFrozen: 'Первый столбец закреплён — сохраните с помощью ⌘S.',
appFindScanTruncated:
'Большой лист: поиск остановлен после {cells} ячеек — результаты могут быть неполными.',
appReplaceNeedsFullLoad: 'Замена требует режима полной загрузки — используйте поиск.',
appGridlinesHiddenSave: 'Сетка скрыта — сохраните с помощью ⌘S.',
appGridlinesShownSave: 'Сетка показана — сохраните с помощью ⌘S.',
@@ -13514,6 +13532,7 @@ export const appStrings = defineStrings({
appZoom: 'التكبير/التصغير {percent}%.',
appTopRowFrozen: 'جُمّد الصف العلوي — احفظ بـ ⌘S.',
appFirstColFrozen: 'جُمّد العمود الأول — احفظ بـ ⌘S.',
appFindScanTruncated: 'ورقة كبيرة: توقف البحث بعد {cells} خلية — قد تكون النتائج غير مكتملة.',
appReplaceNeedsFullLoad: 'يتطلب الاستبدال وضع التحميل الكامل — استخدم البحث بدلاً منه.',
appGridlinesHiddenSave: 'أُخفيت خطوط الشبكة — احفظ بـ ⌘S.',
appGridlinesShownSave: 'أُظهرت خطوط الشبكة — احفظ بـ ⌘S.',
@@ -14822,6 +14841,8 @@ export const appStrings = defineStrings({
appZoom: 'Zoom {percent}%.',
appTopRowFrozen: 'Primeira linha congelada — salve com ⌘S.',
appFirstColFrozen: 'Primeira coluna congelada — salve com ⌘S.',
appFindScanTruncated:
'Planilha grande: a pesquisa parou após {cells} células — os resultados podem estar incompletos.',
appReplaceNeedsFullLoad: 'Substituir requer o modo de carregamento completo — use Localizar.',
appGridlinesHiddenSave: 'Linhas de grade ocultas — salve com ⌘S.',
appGridlinesShownSave: 'Linhas de grade exibidas — salve com ⌘S.',
@@ -16151,6 +16172,8 @@ export const appStrings = defineStrings({
appZoom: 'Zoom {percent}%.',
appTopRowFrozen: 'Riga superiore bloccata — salva con ⌘S.',
appFirstColFrozen: 'Prima colonna bloccata — salva con ⌘S.',
appFindScanTruncated:
'Foglio di grandi dimensioni: ricerca interrotta dopo {cells} celle; i risultati potrebbero essere incompleti.',
appReplaceNeedsFullLoad: 'Sostituisci richiede la modalità a caricamento completo — usa Trova.',
appGridlinesHiddenSave: 'Griglia nascosta — salva con ⌘S.',
appGridlinesShownSave: 'Griglia visualizzata — salva con ⌘S.',
@@ -17475,6 +17498,8 @@ export const appStrings = defineStrings({
appZoom: 'Powiększenie {percent}%.',
appTopRowFrozen: 'Zablokowano górny wiersz — zapisz za pomocą ⌘S.',
appFirstColFrozen: 'Zablokowano pierwszą kolumnę — zapisz za pomocą ⌘S.',
appFindScanTruncated:
'Duży arkusz: wyszukiwanie zatrzymane po {cells} komórkach — wyniki mogą być niepełne.',
appReplaceNeedsFullLoad: 'Zamienianie wymaga trybu pełnego ładowania — użyj funkcji Znajdź.',
appGridlinesHiddenSave: 'Linie siatki ukryte — zapisz za pomocą ⌘S.',
appGridlinesShownSave: 'Linie siatki pokazane — zapisz za pomocą ⌘S.',
@@ -18807,6 +18832,8 @@ export const appStrings = defineStrings({
appZoom: 'Zoomen {percent}%.',
appTopRowFrozen: 'Bovenste rij geblokkeerd — sla op met ⌘S.',
appFirstColFrozen: 'Eerste kolom geblokkeerd — sla op met ⌘S.',
appFindScanTruncated:
'Groot werkblad: zoeken gestopt na {cells} cellen — resultaten kunnen onvolledig zijn.',
appReplaceNeedsFullLoad: 'Vervangen vereist de volledig geladen modus — gebruik Zoeken.',
appGridlinesHiddenSave: 'Rasterlijnen verborgen — sla op met ⌘S.',
appGridlinesShownSave: 'Rasterlijnen weergegeven — sla op met ⌘S.',
@@ -20116,6 +20143,8 @@ export const appStrings = defineStrings({
appZoom: 'Zum {percent}%.',
appTopRowFrozen: 'Baris teratas dibekukan — simpan dengan ⌘S.',
appFirstColFrozen: 'Lajur pertama dibekukan — simpan dengan ⌘S.',
appFindScanTruncated:
'Helaian besar: carian berhenti selepas {cells} sel — hasil mungkin tidak lengkap.',
appReplaceNeedsFullLoad: 'Ganti memerlukan mod muat penuh — gunakan Cari.',
appGridlinesHiddenSave: 'Garis grid disembunyikan — simpan dengan ⌘S.',
appGridlinesShownSave: 'Garis grid ditunjukkan — simpan dengan ⌘S.',
@@ -21381,6 +21410,8 @@ export const appStrings = defineStrings({
appZoom: 'זום {percent}%.',
appTopRowFrozen: 'השורה העליונה הוקפאה — שמור עם ⌘S.',
appFirstColFrozen: 'העמודה הראשונה הוקפאה — שמור עם ⌘S.',
appFindScanTruncated:
'גיליון גדול: החיפוש הופסק לאחר {cells} תאים — ייתכן שהתוצאות אינן מלאות.',
appReplaceNeedsFullLoad: 'החלפה דורשת מצב טעינה מלאה — השתמש בחיפוש במקום.',
appGridlinesHiddenSave: 'קווי הרשת הוסתרו — שמור עם ⌘S.',
appGridlinesShownSave: 'קווי הרשת מוצגים — שמור עם ⌘S.',
@@ -22661,6 +22692,7 @@ export const appStrings = defineStrings({
appZoom: 'ज़ूम {percent}%।',
appTopRowFrozen: 'शीर्ष पंक्ति फ़्रीज़ की गई — ⌘S से सहेजें।',
appFirstColFrozen: 'पहला स्तंभ फ़्रीज़ किया गया — ⌘S से सहेजें।',
appFindScanTruncated: 'बड़ी शीट: {cells} सेल के बाद खोज रुक गई — परिणाम अधूरे हो सकते हैं।',
appReplaceNeedsFullLoad: 'बदलने के लिए पूर्ण-लोड मोड चाहिए — इसके बजाय ढूँढें का उपयोग करें।',
appGridlinesHiddenSave: 'ग्रिडलाइन छिपाई गईं — ⌘S से सहेजें।',
appGridlinesShownSave: 'ग्रिडलाइन दिखाई गईं — ⌘S से सहेजें।',
@@ -23904,6 +23936,7 @@ export const appStrings = defineStrings({
appZoom: '縮放 {percent}%。',
appTopRowFrozen: '已凍結頂端列——⌘S 儲存。',
appFirstColFrozen: '已凍結首欄——⌘S 儲存。',
appFindScanTruncated: '大工作表:搜尋提前停止(已掃描 {cells} 個儲存格),結果可能不完整。',
appReplaceNeedsFullLoad: '取代需要完整載入模式——請改用尋找。',
appGridlinesHiddenSave: '格線已隱藏——⌘S 儲存。',
appGridlinesShownSave: '格線已顯示——⌘S 儲存。',
+682
View File
@@ -0,0 +1,682 @@
/**
* Full-sheet Find coverage for streamed (lazy) workbooks.
*
* Univer's Find dialog searches the in-memory cell matrix, but a streamed
* workbook only holds rows that were already scrolled into view, so matches
* in never-visited rows are invisible and users conclude the data does not
* exist (issue #113). This module wraps the built-in sheets find provider:
* the inner model keeps handling everything inside the loaded window, while
* the wrapper extends the session with out-of-window matches paged from the
* underlying file via readSheetRangeMapped (journal edits included) — the
* same approach the AI-side find takes. Focusing an out-of-window match
* activates its sheet, starts loading its range, scrolls to it, and selects
* it, so the grid shows real data instead of an empty jump.
*/
import type { IRange } from '@univerjs/core'
import {
FindBy,
FindModel,
IFindReplaceService,
type IFindMatch,
type IFindMoveParams,
type IFindQuery,
type IFindReplaceProvider,
type IReplaceAllResult,
} from '@univerjs/find-replace'
import { Subject, type Subscription } from 'rxjs'
import { FILE_READ_BATCH_CELLS, MAX_SCAN_CELLS } from './ai/workbook-search'
import { t } from './i18n/locale'
import { netAxisDelta } from './view-transform'
import type { LazyWorkbookState, UniverRuntime } from './univer-state'
import { ensureLazyRangeLoaded, readSheetRangeMapped } from './univer-sync'
/** Same match shape the built-in sheets provider produces (ISheetCellMatch). */
export interface LazyCellMatch extends IFindMatch {
isFormula: boolean
replaceable?: boolean
/// Extra bookkeeping the wrapper needs to focus/replace the hit; ignored
/// by Univer's composite model.
range: { subUnitId: string; range: IRange }
matchedText?: string | null
}
export interface LazyCellTexts {
/** Display/computed value stringified like Univer's extractPureValue. */
value: string | null
formula: string | undefined
}
type LazyCellTest = (cell: LazyCellTexts) => boolean
/** Whether a find session needs the file-backed extension for this workbook. */
export function planLazyFind(state: LazyWorkbookState | null): 'inactive' | 'extend' {
if (!state || state.flags.preloadComplete) return 'inactive'
return 'extend'
}
/// Stringifies a scalar like Univer's extractPureValue: numbers become their
/// decimal text, booleans become "1"/"0".
export function scalarToText(value: unknown): string | null {
if (value === null || value === undefined) return null
if (typeof value === 'number') return `${value}`
if (typeof value === 'boolean') return value ? '1' : '0'
return String(value)
}
/// Mirrors Univer's matchCellData/hitCell semantics for file-backed cells:
/// substring vs whole-cell (spaces trimmed, line breaks kept), case
/// sensitivity, and formula-vs-value look-in.
export function buildLazyCellTest(query: IFindQuery): LazyCellTest | null {
const needleRaw = query.findString
if (!needleRaw) return null
const caseSensitive = query.caseSensitive === true
// The built-in model lowercases the needle once up front (its parsed
// query); do the same here so both models agree on what a hit is.
const needle = caseSensitive ? needleRaw : needleRaw.toLowerCase()
const matches = (text: string | null | undefined): boolean => {
if (text === null || text === undefined) return false
const haystack = caseSensitive ? text : text.toLowerCase()
if (query.matchesTheWholeCell) {
const trimmed = haystack.replace(/^ +/g, '').replace(/ +$/g, '')
return trimmed === needle
}
return haystack.includes(needle)
}
return ({ value, formula }) => {
if (formula && query.findBy === FindBy.FORMULA) return matches(formula)
return matches(value)
}
}
function insideRange(range: IRange | undefined, row: number, column: number): boolean {
if (!range) return false
return (
row >= range.startRow &&
row <= range.endRow &&
column >= range.startColumn &&
column <= range.endColumn
)
}
/** True when the loaded window covers the coordinate — the inner model owns it. */
export function coveredByWindow(
state: LazyWorkbookState,
sheetId: string,
row: number,
column: number,
): boolean {
return insideRange(state.loadedRanges.get(sheetId), row, column)
}
function matchKey(match: LazyCellMatch): string {
return `${match.range.subUnitId}|${match.range.range.startRow}|${match.range.range.startColumn}`
}
/** Dedupes inner-model matches against the extension's; inner entries win. */
export function mergeFindMatches(primary: IFindMatch[], extra: LazyCellMatch[]): IFindMatch[] {
if (extra.length === 0) return primary
const seen = new Set(primary.map((match) => matchKey(match as LazyCellMatch)))
const merged = [...primary]
for (const match of extra) {
const key = matchKey(match)
if (seen.has(key)) continue
seen.add(key)
merged.push(match)
}
return merged
}
interface ScanCell {
readonly row: number
readonly column: number
readonly value: string | number | boolean | null
readonly formula: string | undefined
}
/** Journal edits of one sheet that sit outside the loaded window. */
export function collectJournalMatches(
state: LazyWorkbookState,
sheetId: string,
test: LazyCellTest,
): ScanCell[] {
const found: ScanCell[] = []
const journal = state.editJournal.cells.get(sheetId)
for (const entry of journal?.values() ?? []) {
if (!entry.hasValue) continue
if (coveredByWindow(state, sheetId, entry.row, entry.column)) continue
if (!test({ value: scalarToText(entry.value), formula: entry.formula })) continue
found.push({ row: entry.row, column: entry.column, value: entry.value, formula: entry.formula })
}
return found
}
/** Coordinates whose file cell is shadowed by a journal edit this session. */
export function journalShadowKeys(state: LazyWorkbookState, sheetId: string): Set<string> {
const shadowed = new Set<string>()
const journal = state.editJournal.cells.get(sheetId)
for (const entry of journal?.values() ?? []) shadowed.add(`${entry.row}:${entry.column}`)
return shadowed
}
/** Row-major/column-major ordering across sheets, following the query direction. */
export function extraComparator(
sheetOrder: ReadonlyMap<string, number>,
columnDirection: boolean,
): (a: ScanCell & { sheetId: string }, b: ScanCell & { sheetId: string }) => number {
return (a, b) => {
const sheetDelta = (sheetOrder.get(a.sheetId) ?? 0) - (sheetOrder.get(b.sheetId) ?? 0)
if (sheetDelta !== 0) return sheetDelta
return columnDirection
? a.column - b.column || a.row - b.row
: a.row - b.row || a.column - b.column
}
}
function makeCellMatch(
unitId: string,
sheetId: string,
cell: ScanCell,
findByFormula: boolean,
): LazyCellMatch {
const isFormula = Boolean(cell.formula)
return {
provider: 'sheets-find-replace-provider',
unitId,
isFormula,
// Formula hits are only replaced when searching formulas (mirrors the
// built-in model); plain cells behave exactly like in-memory ones.
replaceable: isFormula ? findByFormula : cell.value !== null && cell.value !== undefined,
matchedText: (findByFormula && isFormula ? cell.formula : scalarToText(cell.value)) ?? null,
range: {
subUnitId: sheetId,
range: {
startRow: cell.row,
endRow: cell.row,
startColumn: cell.column,
endColumn: cell.column,
},
},
}
}
export interface LazyFindBridgeDeps {
runtime: UniverRuntime
lazyWorkbookRef: { current: LazyWorkbookState | null }
setMessage: (message: string) => void
}
interface InnerFindModel extends FindModel {
readonly unitId: string
focusSelection(): void
}
/**
* Replaces the registered sheets find provider with a wrapper while the app
* lives. Non-streamed workbooks flow straight through; streamed ones get the
* extended model. Nothing is restored on dispose: the whole runtime dies
* with the component that installed the bridge.
*/
export function installLazyFindBridge(deps: LazyFindBridgeDeps): { dispose(): void } {
const service = deps.runtime.univer.__getInjector().get(IFindReplaceService)
const providers = service.getProviders()
let generation = 0
const wrapper: IFindReplaceProvider = {
async find(query: IFindQuery) {
generation += 1
const liveGeneration = generation
// Adopt whichever built-in providers exist now — the sheets controller
// registers one per workbook, while this wrapper survives across
// workbooks for the lifetime of the renderer.
const models: FindModel[] = []
for (const builtin of [...providers]) {
if (builtin === wrapper) continue
models.push(...(await builtin.find(query)))
}
const state = deps.lazyWorkbookRef.current
if (!state || planLazyFind(state) !== 'extend' || models.length === 0) return models
return models.map(
(model) =>
new LazyExtendedFindModel(
model as InnerFindModel,
state,
query,
deps,
() => generation === liveGeneration,
),
)
},
terminate() {
generation += 1
for (const builtin of [...providers]) {
if (builtin !== wrapper) builtin.terminate()
}
},
}
const registration = service.registerFindReplaceProvider(wrapper)
return {
dispose() {
generation += 1
registration.dispose()
},
}
}
/**
* A FindModel combining the built-in in-window session with out-of-window
* hits paged from the underlying file. The inner model keeps navigating and
* highlighting everything it can see; this wrapper only steps in when the
* inner session runs out, and hands focus back once the jumped-to region is
* materialized in the grid (the inner model re-runs on mutations and takes
* over navigation there).
*/
export class LazyExtendedFindModel extends FindModel {
readonly unitId: string
readonly matchesUpdate$ = new Subject<IFindMatch[]>()
readonly activelyChangingMatch$ = new Subject<LazyCellMatch>()
private readonly state: LazyWorkbookState
private readonly query: IFindQuery
private readonly deps: LazyFindBridgeDeps
private readonly isLiveGeneration: () => boolean
private alive = true
private truncated = false
private extras: LazyCellMatch[] = []
private lastFocusedExtra: LazyCellMatch | null = null
private readonly forwardSub: Subscription
constructor(
private readonly inner: InnerFindModel,
state: LazyWorkbookState,
query: IFindQuery,
deps: LazyFindBridgeDeps,
isLiveGeneration: () => boolean,
) {
super()
this.state = state
this.query = query
this.deps = deps
this.isLiveGeneration = isLiveGeneration
this.unitId = inner.unitId
// The inner model refreshes itself when grid mutations stream regions in
// or evict them; forward those moments so the dialog count stays right.
this.forwardSub = inner.matchesUpdate$.subscribe(() => this.emitMerged())
void this.runScan()
}
override dispose(): void {
this.alive = false
this.forwardSub.unsubscribe()
this.matchesUpdate$.complete()
this.activelyChangingMatch$.complete()
super.dispose()
}
getMatches(): IFindMatch[] {
return mergeFindMatches(this.innerMatches(), this.currentExtras())
}
moveToNextMatch(params?: IFindMoveParams): LazyCellMatch | null {
const candidate = this.innerNeighbor('next', params)
if (candidate) {
if (!params?.noFocus) this.safeInnerFocus()
return candidate as LazyCellMatch
}
const target = this.neighborExtra('next', params)
if (!target) return null
if (!params?.noFocus) this.focusExtra(target)
return target
}
moveToPreviousMatch(params?: IFindMoveParams): LazyCellMatch | null {
const candidate = this.innerNeighbor('previous', params)
if (candidate) {
if (!params?.noFocus) this.safeInnerFocus()
return candidate as LazyCellMatch
}
const target = this.neighborExtra('previous', params)
if (!target) return null
if (!params?.noFocus) this.focusExtra(target)
return target
}
async replace(replaceString: string): Promise<boolean> {
try {
if (await this.inner.replace(replaceString)) return true
} catch {
/* no inner current match — fall through to the extension's */
}
const extra = this.lastFocusedExtra
if (!extra || extra.replaceable !== true) return false
return this.writeExtraReplacement(extra, replaceString)
}
async replaceAll(replaceString: string): Promise<IReplaceAllResult> {
let success = 0
let failure = 0
try {
const result = await this.inner.replaceAll(replaceString)
success += result.success
failure += result.failure
} catch {
/* the inner session may already be gone; still report the extension's */
}
for (const extra of this.currentExtras()) {
if (extra.replaceable !== true) {
failure += 1
continue
}
if (await this.writeExtraReplacement(extra, replaceString)) success += 1
else failure += 1
}
return { success, failure }
}
focusSelection(): void {
if (this.lastFocusedExtra) {
this.focusExtra(this.lastFocusedExtra)
return
}
this.safeInnerFocus()
}
private safeInnerFocus(): void {
try {
this.inner.focusSelection()
} catch {
/* closed workbook */
}
}
private innerNeighbor(
direction: 'next' | 'previous',
params?: IFindMoveParams,
): IFindMatch | null {
try {
return direction === 'next'
? this.inner.moveToNextMatch({ ...params, noFocus: true })
: this.inner.moveToPreviousMatch({ ...params, noFocus: true })
} catch {
return null
}
}
private innerMatches(): IFindMatch[] {
try {
return this.inner.getMatches()
} catch {
return []
}
}
/** Extras that are still outside the (evolving) loaded window. */
private currentExtras(): LazyCellMatch[] {
return this.extras.filter(
(match) =>
!coveredByWindow(
this.state,
match.range.subUnitId,
match.range.range.startRow,
match.range.range.startColumn,
),
)
}
/**
* Steps into the extension's territory: the first out-of-window hit after
* (or before) the current selection, looping like the built-in model.
*/
private neighborExtra(
direction: 'next' | 'previous',
params?: IFindMoveParams,
): LazyCellMatch | null {
const candidates = this.currentExtras()
if (candidates.length === 0) return null
const order = this.sheetOrderIndex()
const positionOf = (match: LazyCellMatch): [number, number, number] => {
const bounds = match.range.range
return [
order.get(match.range.subUnitId) ?? Number.MAX_SAFE_INTEGER,
direction === 'next' ? bounds.startRow : -bounds.startRow,
direction === 'next' ? bounds.startColumn : -bounds.startColumn,
]
}
const reference = this.referencePosition(order)
if (!reference) {
return direction === 'next' ? candidates[0]! : candidates[candidates.length - 1]!
}
const referencePosition_: [number, number, number] =
direction === 'next'
? [reference.sheetIndex, reference.row, reference.column]
: [reference.sheetIndex, -reference.row, -reference.column]
const ordered = [...candidates].sort((a, b) => compareTriples(positionOf(a), positionOf(b)))
const neighbor =
ordered.find((match) => compareTriples(positionOf(match), referencePosition_) > 0) ?? null
if (neighbor) return neighbor
if (params?.loop === false) return null
return direction === 'next' ? ordered[0]! : ordered[ordered.length - 1]!
}
private sheetOrderIndex(): Map<string, number> {
try {
const sheets = this.deps.runtime.univerAPI.getActiveWorkbook()?.getSheets() ?? []
return new Map(sheets.map((sheet, index) => [sheet.getSheetId(), index] as const))
} catch {
return new Map()
}
}
private referencePosition(
order: ReadonlyMap<string, number>,
): { sheetIndex: number; row: number; column: number } | null {
try {
const workbook = this.deps.runtime.univerAPI.getActiveWorkbook()
const range = workbook?.getActiveRange()
const activeSheet = workbook?.getActiveSheet()
if (!workbook || !range || !activeSheet) return null
return {
sheetIndex: order.get(activeSheet.getSheetId()) ?? Number.MAX_SAFE_INTEGER,
row: range.getRow(),
column: range.getColumn(),
}
} catch {
return this.lastFocusedExtra
? {
sheetIndex: order.get(this.lastFocusedExtra.range.subUnitId) ?? Number.MAX_SAFE_INTEGER,
row: this.lastFocusedExtra.range.range.startRow,
column: this.lastFocusedExtra.range.range.startColumn,
}
: null
}
}
/** Activate the sheet, load the region, scroll to it, and select the cell. */
private focusExtra(match: LazyCellMatch): void {
this.lastFocusedExtra = match
try {
const workbook = this.deps.runtime.univerAPI.getActiveWorkbook()
if (!workbook) return
const worksheet = workbook.getSheetBySheetId(match.range.subUnitId)
if (!worksheet) return
if (worksheet.getSheetId() !== workbook.getActiveSheet()?.getSheetId()) {
workbook.setActiveSheet(worksheet)
}
const bounds = match.range.range
// Best-effort streaming: the scroll below also triggers the regular
// viewport load; this makes sure the exact hit lands even when the
// visible window math picks a different anchor.
void ensureLazyRangeLoaded(
this.deps.runtime,
this.deps.lazyWorkbookRef,
worksheet,
{
startRow: bounds.startRow,
endRow: bounds.endRow,
startColumn: bounds.startColumn,
endColumn: bounds.endColumn,
},
this.deps.setMessage,
)
worksheet.scrollToCell(bounds.startRow, bounds.startColumn)
worksheet.getRange(bounds.startRow, bounds.startColumn, 1, 1).activate()
this.emitMerged()
this.activelyChangingMatch$.next(match)
} catch {
/* closed workbook mid-jump */
}
}
/** Writes the replacement straight onto the cell; the journal carries it. */
private async writeExtraReplacement(
match: LazyCellMatch,
replaceString: string,
): Promise<boolean> {
try {
const workbook = this.deps.runtime.univerAPI.getActiveWorkbook()
const worksheet = workbook?.getSheetBySheetId(match.range.subUnitId)
if (!worksheet) return false
const bounds = match.range.range
const target = worksheet.getRange(bounds.startRow, bounds.startColumn, 1, 1)
if (match.isFormula) {
target.setValues([
[{ f: replaceAllOccurrences(match.matchedText ?? '', this.query, replaceString) }],
])
} else {
target.setValues([
[{ v: replaceAllOccurrences(match.matchedText ?? '', this.query, replaceString) }],
])
}
return true
} catch {
return false
}
}
private emitMerged(): void {
if (!this.alive) return
this.matchesUpdate$.next(this.getMatches())
}
/** Pages the underlying file for out-of-window hits, emitting as it goes. */
private async runScan(): Promise<void> {
const workbook = this.deps.runtime.univerAPI.getActiveWorkbook()
if (!workbook) return
const test = buildLazyCellTest(this.query)
if (!test) return
const unitId = this.unitId
const sheets = workbook.getSheets()
const targets =
this.query.findScope === 'unit'
? sheets
: sheets.filter((sheet) => sheet.getSheetId() === workbook.getActiveSheet()?.getSheetId())
const sheetOrder = new Map(sheets.map((sheet, index) => [sheet.getSheetId(), index] as const))
const comparator = extraComparator(sheetOrder, this.query.findDirection === 'column')
const collected: (ScanCell & { sheetId: string })[] = []
for (const worksheet of targets) {
const sheetId = worksheet.getSheetId()
// Session edits first — they shadow file cells at the same coordinates.
for (const cell of collectJournalMatches(this.state, sheetId, test)) {
collected.push({ ...cell, sheetId })
}
const meta = this.state.file.sheets.find((candidate) => candidate.id === sheetId)
// Sheets added this session live entirely in the journal.
if (!meta || meta.rowCount <= 0 || meta.columnCount <= 0) {
this.refreshExtras(collected, comparator, unitId)
this.emitMerged()
continue
}
const ops = this.state.editJournal.structuralOps.get(sheetId) ?? []
const screenRows = Math.max(meta.rowCount + netAxisDelta(ops, 'row'), 0)
const screenColumns = Math.max(meta.columnCount + netAxisDelta(ops, 'column'), 0)
if (screenRows <= 0 || screenColumns <= 0) continue
const shadowed = journalShadowKeys(this.state, sheetId)
const batchRows = Math.max(1, Math.floor(FILE_READ_BATCH_CELLS / screenColumns))
for (let startRow = 0; startRow < screenRows; startRow += batchRows) {
if (!this.alive || !this.isLiveGeneration()) return
if (this.truncated) break
if (collected.length >= MAX_SCAN_CELLS) {
this.truncated = true
break
}
const endRow = Math.min(startRow + batchRows - 1, screenRows - 1)
let mapped
try {
mapped = await readSheetRangeMapped(
this.state,
sheetId,
{ startRow, endRow, startColumn: 0, endColumn: screenColumns - 1 },
meta,
)
} catch {
this.truncated = true
break
}
if (!mapped) continue
if (
!mapped.raw.indexingComplete &&
(mapped.indexedThroughScreen === null || mapped.indexedThroughScreen < endRow)
) {
this.truncated = true
}
for (const cell of mapped.screen.cells) {
if (shadowed.has(`${cell.row}:${cell.column}`)) continue
if (coveredByWindow(this.state, sheetId, cell.row, cell.column)) continue
if (!test({ value: scalarToText(cell.value), formula: cell.formula })) continue
collected.push({
row: cell.row,
column: cell.column,
value: cell.value,
formula: cell.formula,
sheetId,
})
}
this.refreshExtras(collected, comparator, unitId)
this.emitMerged()
}
if (this.truncated) break
}
this.refreshExtras(collected, comparator, unitId)
if (this.truncated && this.alive && this.isLiveGeneration()) {
this.deps.setMessage(t('appFindScanTruncated', { cells: MAX_SCAN_CELLS.toLocaleString() }))
}
this.emitMerged()
}
private refreshExtras(
collected: (ScanCell & { sheetId: string })[],
comparator: (a: ScanCell & { sheetId: string }, b: ScanCell & { sheetId: string }) => number,
unitId: string,
): void {
const findByFormula = this.query.findBy === FindBy.FORMULA
this.extras = [...collected]
.sort(comparator)
.map((cell) => makeCellMatch(unitId, cell.sheetId, cell, findByFormula))
}
}
/// Substring replacement honoring the query's case sensitivity, replacing
/// every occurrence like Excel's Replace All.
function replaceAllOccurrences(text: string, query: IFindQuery, replaceString: string): string {
const needle = query.caseSensitive === true ? query.findString : query.findString.toLowerCase()
if (!needle) return text
const haystack = query.caseSensitive === true ? text : text.toLowerCase()
let result = ''
let cursor = 0
for (;;) {
const index = haystack.indexOf(needle, cursor)
if (index < 0) {
result += text.slice(cursor)
break
}
result += text.slice(cursor, index) + replaceString
cursor = index + needle.length
}
return result
}
function compareTriples(a: [number, number, number], b: [number, number, number]): number {
return a[0] - b[0] || a[1] - b[1] || a[2] - b[2]
}
+469
View File
@@ -0,0 +1,469 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { IRange } from '@univerjs/core'
import { FindModel, type IFindMatch } from '@univerjs/find-replace'
import { Subject } from 'rxjs'
import {
buildLazyCellTest,
collectJournalMatches,
coveredByWindow,
extraComparator,
installLazyFindBridge,
mergeFindMatches,
planLazyFind,
scalarToText,
type LazyCellMatch,
} from '../src/renderer/lazy-find'
import { ensureLazyRangeLoaded, readSheetRangeMapped } from '../src/renderer/univer-sync'
import type { LazyWorkbookState } from '../src/renderer/univer-state'
vi.mock('../src/renderer/univer-sync', () => ({
readSheetRangeMapped: vi.fn(),
ensureLazyRangeLoaded: vi.fn().mockResolvedValue(true),
}))
vi.mock('../src/renderer/i18n/locale', () => ({
t: (key: string, params?: Record<string, string>) =>
`${key}${params ? ` ${JSON.stringify(params)}` : ''}`,
}))
const mockRead = vi.mocked(readSheetRangeMapped)
const mockEnsure = vi.mocked(ensureLazyRangeLoaded)
describe('planLazyFind', () => {
it('is inactive without a streamed workbook', () => {
expect(planLazyFind(null)).toBe('inactive')
})
it('is inactive once preloading completed', () => {
expect(planLazyFind(state({ preloadComplete: true }))).toBe('inactive')
})
it('extends the search while rows are still streaming', () => {
expect(planLazyFind(state({ preloadComplete: false }))).toBe('extend')
})
})
describe('scalarToText', () => {
it('stringifies like Univer does', () => {
expect(scalarToText(120)).toBe('120')
expect(scalarToText(true)).toBe('1')
expect(scalarToText(false)).toBe('0')
expect(scalarToText('txt')).toBe('txt')
expect(scalarToText(null)).toBeNull()
expect(scalarToText(undefined)).toBeNull()
})
})
describe('buildLazyCellTest', () => {
it('matches substrings case-insensitively by default', () => {
const test = buildLazyCellTest(query({ findString: 'Total' }))
expect(test?.({ value: 'grand TOTAL', formula: undefined })).toBe(true)
expect(test?.({ value: 'other', formula: undefined })).toBe(false)
})
it('honors case sensitivity', () => {
const test = buildLazyCellTest(query({ findString: 'Total', caseSensitive: true }))
expect(test?.({ value: 'grand total', formula: undefined })).toBe(false)
expect(test?.({ value: 'grand Total', formula: undefined })).toBe(true)
})
it('trims spaces (not line breaks) for whole-cell matches', () => {
const test = buildLazyCellTest(query({ findString: 'total', matchesTheWholeCell: true }))
expect(test?.({ value: ' total ', formula: undefined })).toBe(true)
// Line breaks are kept, mirroring Univer's trimLeadingTrailingWhitespace.
expect(test?.({ value: 'total\n', formula: undefined })).toBe(false)
expect(test?.({ value: 'grand total', formula: undefined })).toBe(false)
})
it('looks at formulas only when searching formulas', () => {
const formulaQuery = query({ findString: 'a2*2', findBy: 'formula' })
expect(formulaQuery.findBy).toBe('formula')
const test = buildLazyCellTest(formulaQuery)
expect(test?.({ value: '240', formula: '=A2*2' })).toBe(true)
expect(test?.({ value: '240', formula: undefined })).toBe(false)
const valueTest = buildLazyCellTest(query({ findString: '240', findBy: 'value' }))
expect(valueTest?.({ value: '240', formula: '=A2*2' })).toBe(true)
})
it('rejects an empty needle', () => {
expect(buildLazyCellTest(query({ findString: '' }))).toBeNull()
})
})
describe('mergeFindMatches', () => {
const inner = match('s1', 5, 1)
const extraSame = match('s1', 5, 1)
const extraFar = match('s1', 900, 0)
it('keeps inner entries and appends unseen extras', () => {
const merged = mergeFindMatches([inner], [extraSame, extraFar])
expect(merged).toHaveLength(2)
expect(merged[0]).toBe(inner)
expect(merged[1]).toBe(extraFar)
})
it('returns primary untouched without extras', () => {
const merged = mergeFindMatches([inner], [])
expect(merged).toEqual([inner])
})
})
describe('coveredByWindow', () => {
it('checks the sheet loaded range', () => {
const lazyState = state({})
expect(coveredByWindow(lazyState, 's1', 5, 5)).toBe(true)
expect(coveredByWindow(lazyState, 's1', 50, 0)).toBe(false)
expect(coveredByWindow(lazyState, 'ghost', 0, 0)).toBe(false)
})
})
describe('collectJournalMatches', () => {
it('skips loaded-window edits and cleared cells', () => {
const lazyState = state({
journalCells: new Map([
[
's1',
new Map([
['0', { row: 5, column: 0, value: 'inside hit', hasValue: true }],
['1', { row: 900, column: 0, value: 'outside hit', hasValue: true }],
['2', { row: 901, column: 0, value: null, hasValue: false }],
]),
],
]),
})
const found = collectJournalMatches(
lazyState,
's1',
buildLazyCellTest(query({ findString: 'hit' }))!,
)
expect(found.map((cell) => cell.value)).toEqual(['outside hit'])
})
it('tests formulas of journaled cells', () => {
const lazyState = state({
journalCells: new Map([
[
's1',
new Map([
['0', { row: 20, column: 2, value: null, formula: '=Sum(A1:A9)', hasValue: true }],
]),
],
]),
})
const found = collectJournalMatches(
lazyState,
's1',
buildLazyCellTest(query({ findString: 'sum(', findBy: 'formula' }))!,
)
expect(found).toHaveLength(1)
expect(found[0]?.formula).toBe('=Sum(A1:A9)')
})
})
describe('extraComparator', () => {
const order = new Map([
['s1', 0],
['s2', 1],
])
const cell = (sheetId: string, row: number, column: number) => ({
sheetId,
row,
column,
value: null,
formula: undefined,
})
it('orders row-major across sheets', () => {
const compare = extraComparator(order, false)
expect(compare(cell('s1', 1, 9), cell('s2', 0, 0))).toBeLessThan(0)
expect(compare(cell('s1', 2, 0), cell('s1', 1, 5))).toBeGreaterThan(0)
expect(compare(cell('s1', 1, 2), cell('s1', 1, 2))).toBe(0)
})
it('orders column-major when requested', () => {
const compare = extraComparator(order, true)
expect(compare(cell('s1', 9, 1), cell('s1', 0, 2))).toBeLessThan(0)
})
})
type FakeOverrides = {
preloadComplete?: boolean
journalCells?: LazyWorkbookState['editJournal']['cells']
}
function state(overrides: FakeOverrides): LazyWorkbookState {
return {
file: {
sessionId: 'session-1',
sheets: [{ id: 's1', name: 'Sheet1', rowCount: 1000, columnCount: 8 }],
},
generation: 1,
loadedRanges: new Map<string, IRange>([
['s1', { startRow: 0, endRow: 9, startColumn: 0, endColumn: 9 }],
]),
loadingKeys: new Map(),
retryTimers: new Map(),
appliedMerges: new Map(),
appliedRowKeys: new Map(),
sheetProtections: new Map(),
sheetPageBreaks: new Map(),
sheetProtectedRanges: new Map(),
uninstalledDefinedNames: new Set(),
appliedCfSheets: new Set(),
appliedFilterSheets: new Set(),
appliedDvSheets: new Set(),
decorationsPendingSheets: new Set(),
hyperlinkTargets: new Map(),
frozenStripKeys: new Map(),
filterOrigins: new Map(),
showFormulaSheets: new Set(),
formulaMode: false,
editJournal: {
cells: overrides.journalCells ?? new Map(),
structuralOps: new Map(),
},
flags: { preloadComplete: overrides.preloadComplete ?? false },
closure: { status: 'idle', pinned: new Map() },
formulaText: new Map(),
cachedFormulaValues: new Map(),
pivotDefinitions: new Map(),
outline: new Map(),
recalc: {
timer: null,
generation: 0,
failures: 0,
formulaCells: new Map(),
overlay: new Map(),
},
} as unknown as LazyWorkbookState
}
function query(overrides: Record<string, unknown> = {}): ReturnType<typeof buildQuery> {
return buildQuery(overrides)
}
function buildQuery(overrides: Record<string, unknown>) {
return {
findString: 'needle',
caseSensitive: false,
findBy: 'value',
findDirection: 'row',
findScope: 'subunit',
matchesTheWholeCell: false,
replaceRevealed: false,
...overrides,
} as Parameters<typeof buildLazyCellTest>[0]
}
function match(sheetId: string, row: number, column: number): LazyCellMatch {
return {
provider: 'sheets-find-replace-provider',
unitId: 'workbook-1',
isFormula: false,
range: {
subUnitId: sheetId,
range: { startRow: row, endRow: row, startColumn: column, endColumn: column },
},
}
}
class FakeInnerModel extends FindModel {
readonly unitId = 'workbook-1'
readonly matchesUpdate$ = new Subject<IFindMatch[]>()
readonly activelyChangingMatch$ = new Subject<LazyCellMatch>()
constructor(private readonly matches: IFindMatch[]) {
super()
}
getMatches(): IFindMatch[] {
return this.matches
}
moveToNextMatch(): IFindMatch | null {
return this.matches[0] ?? null
}
moveToPreviousMatch(): IFindMatch | null {
return this.matches[this.matches.length - 1] ?? null
}
replace(_replaceString: string): Promise<boolean> {
return Promise.resolve(false)
}
async replaceAll(): Promise<{ success: number; failure: number }> {
return { success: this.matches.length, failure: 0 }
}
focusSelection(): void {}
}
function facade(lazyState: LazyWorkbookState | null) {
const setValues = vi.fn()
const worksheet = {
getSheetId: () => 's1',
getSheetName: () => 'Sheet1',
scrollToCell: vi.fn(),
getRange: vi.fn(() => ({ activate: vi.fn(), setValues })),
}
const workbook = {
getId: () => 'workbook-1',
getSheets: () => [worksheet],
getActiveSheet: () => worksheet,
getSheetBySheetId: (sheetId: string) => (sheetId === 's1' ? worksheet : null),
getActiveRange: () => ({ getRow: () => 0, getColumn: () => 0 }),
setActiveSheet: vi.fn(),
}
const providers = new Set<unknown>()
const registrations: { provider: unknown; dispose: () => void }[] = []
const service = {
getProviders: () => providers,
registerFindReplaceProvider: (provider: unknown) => {
const registration = {
provider,
dispose: () => {
providers.delete(registration.provider)
},
}
providers.add(provider)
registrations.push(registration)
return registration
},
}
const runtime = {
univerAPI: { getActiveWorkbook: () => workbook },
univer: { __getInjector: () => ({ get: () => service }) },
}
return {
runtime: runtime as unknown as Parameters<typeof installLazyFindBridge>[0]['runtime'],
lazyWorkbookRef: { current: lazyState },
setMessage: vi.fn(),
worksheet,
workbook,
setValues,
providers,
service,
registrations,
}
}
async function settle(model: { getMatches(): unknown[] }): Promise<void> {
await vi.waitFor(() => {
expect(mockRead).toHaveBeenCalled()
expect(model.getMatches().length).toBeGreaterThan(0)
})
}
type MappedResult = Awaited<ReturnType<typeof readSheetRangeMapped>>
function mapped(
cells: {
row: number
column: number
value: string | number | boolean | null
formula?: string
}[],
): MappedResult {
return {
raw: { indexingComplete: true },
indexedThroughScreen: 999,
fileEndRow: 999,
screen: { cells, rows: [], merges: [], hyperlinks: [] },
} as unknown as MappedResult
}
describe('installLazyFindBridge', () => {
beforeEach(() => {
mockRead.mockReset()
mockEnsure.mockReset()
mockEnsure.mockResolvedValue(true)
})
it('passes through when no streamed workbook is open', async () => {
const harness = facade(null)
const inner = new FakeInnerModel([match('s1', 1, 1)])
const builtin = { find: vi.fn().mockResolvedValue([inner]), terminate: vi.fn() }
harness.providers.add(builtin)
const bridge = installLazyFindBridge(harness)
const models = await harnessLookup(harness)(query())
expect(models).toHaveLength(1)
expect(models[0]).toBe(inner)
bridge.dispose()
// The wrapper left, the built-in stayed registered.
expect([...harness.providers]).toContain(builtin)
})
it('extends the session with out-of-window hits and focuses them', async () => {
const harness = facade(state({}))
const inner = new FakeInnerModel([])
const builtin = { find: vi.fn().mockResolvedValue([inner]), terminate: vi.fn() }
harness.providers.add(builtin)
const bridge = installLazyFindBridge(harness)
mockRead.mockResolvedValue(
mapped([
{ row: 500, column: 3, value: 'deep needle' },
{ row: 5, column: 3, value: 'window needle' },
]),
)
const models = await harnessLookup(harness)(query())
expect(models).toHaveLength(1)
const model = models[0]!
await settle(model)
const matches = model.getMatches()
// The in-window file hit belongs to the (empty) inner list; only the deep one is added.
expect(matches).toHaveLength(1)
expect((matches[0] as LazyCellMatch).range.range.startRow).toBe(500)
const focused = model.moveToNextMatch()
expect(focused).not.toBeNull()
expect(harness.worksheet.scrollToCell).toHaveBeenCalledWith(500, 3)
expect(mockEnsure).toHaveBeenCalled()
bridge.dispose()
})
it('dedupes hits the inner model also reports', async () => {
const harness = facade(state({}))
const inner = new FakeInnerModel([match('s1', 500, 3)])
const builtin = { find: vi.fn().mockResolvedValue([inner]), terminate: vi.fn() }
harness.providers.add(builtin)
const bridge = installLazyFindBridge(harness)
mockRead.mockResolvedValue(mapped([{ row: 500, column: 3, value: 'same needle' }]))
const models = await harnessLookup(harness)(query())
const model = models[0]!
await settle(model)
expect(model.getMatches()).toHaveLength(1)
bridge.dispose()
})
it('reports truncated scans through the status message', async () => {
const harness = facade(state({}))
const inner = new FakeInnerModel([])
const builtin = { find: vi.fn().mockResolvedValue([inner]), terminate: vi.fn() }
harness.providers.add(builtin)
const bridge = installLazyFindBridge(harness)
mockRead.mockRejectedValue(new Error('sidecar gone'))
const models = await harnessLookup(harness)(query())
const model = models[0]!
await vi.waitFor(() => expect(harness.setMessage).toHaveBeenCalled())
expect(model.getMatches()).toHaveLength(0)
bridge.dispose()
})
})
/** Runs a find through the provider the bridge registered (last registration). */
function harnessLookup(harness: ReturnType<typeof facade>): (q: unknown) => Promise<FindModel[]> {
const registration = harness.registrations[harness.registrations.length - 1]!
const wrapper = registration.provider as { find: (q: unknown) => Promise<FindModel[]> }
expect(typeof wrapper.find).toBe('function')
return (q) => wrapper.find(q)
}
+2
View File
@@ -396,6 +396,7 @@
"@univerjs/core": "^0.25.1",
"@univerjs/data-validation": "^0.25.1",
"@univerjs/engine-render": "^0.25.1",
"@univerjs/find-replace": "^0.25.1",
"@univerjs/preset-sheets-conditional-formatting": "^0.25.1",
"@univerjs/preset-sheets-core": "^0.25.1",
"@univerjs/preset-sheets-data-validation": "^0.25.1",
@@ -411,6 +412,7 @@
"jszip": "^3.10.1",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"rxjs": "^7.8.2",
"zod": "^4.3.6"
},
"devDependencies": {