vomebook commited on
Commit ·
eea3bcf
1
Parent(s): 5675f95
Keep filter drafts from interrupting search position restoration
Browse filesFiles changed (16)
- static/app.js+81-181
- static/search/input/application/controller.js+122-18
- static/search/positions/application/restoration.js+76-10
- tests/search/browser/test_paging_recovery.py+1-1
- tests/search/browser/test_position_controls.py+15-5
- tests/search/browser/test_position_window.py+6-6
- tests/search/browser/test_recent_search_pages.py+5-5
- tests/search/browser/test_search_positions.py+3-3
- tests/search/paging/result_window_contracts.mjs+1-1
- tests/search/reader-navigation/routing_contracts.mjs+35-15
- tests/search/reader-navigation/test_search_history_races.mjs+56-26
- tests/search/session/restoration_contracts.mjs+128-68
- tests/search/ui/virtual_results_contracts.mjs+1-1
- tests/support/classic_search_modules.js+1-1
- typings/reader-globals.d.ts+13-1
- typings/search-restoration.d.ts+22-12
116 unmodified lines117118119120121122123113 unmodified lines23723823924024124224324424524624724824925025120 unmodified lines2722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023038 unmodified lines31231331431531631731831917 unmodified lines3373383393403413423437 unmodified lines35135235335435535635774 unmodified lines4324334344354364374384 unmodified lines44344444544644744844921 unmodified lines47147247347447547647747847948048148248348448548648748848949049149249349423 unmodified lines5185195205215225235246 unmodified lines53153253353453553653716 unmodified lines5545555565575585595605615625635645655665675685695705715725735745755765775785795805813 unmodified lines58558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262385 unmodified lines70971071171271371471571671771821 unmodified lines74074174274374474574664 unmodified lines811812813814815816817818103 unmodified lines9229239249259269279286 unmodified lines93593693793893994094194294394446 unmodified lines991992993994995996997296 unmodified lines12941295129612971298129913001 unmodified line1302130313041305130613071308361 unmodified lines167016711672167316741675167616771678476 unmodified lines21552156215721582159216021612162216321642165216666 unmodified lines223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262111 unmodified lines2374237523762377237823792380238111 unmodified lines23932394239523962397239823992400240120 unmodified lines2422242324242425242624272428242933 unmodified lines2463246424652466246724682469197 unmodified lines266726682669267026712672267384 unmodified lines2758275927602761276227632764276527665 unmodified lines2772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928105 unmodified lines2816281728182819282028212822282328242825188 unmodified lines30143015301630173018301930203021194 unmodified lines3216321732183219322032213222529 unmodified lines3752375337543755375637573758116 unmodified lineslet filterSearchTimer = null;/** @type {ReturnType<typeof setTimeout> | null} */let sizeFilterTimer = null;const FILTER_SEARCH_DEBOUNCE_MS = 200;let routeRenderId = 0;// A path-only route change bumps routeRenderId for the browser, but must not// orphan an unfinished filter render or its batched folder-tree tasks.113 unmodified lines});/** @type {VoiceOfMLSearchAppDisplayedView | null} */let displayedSearchView = null;/** @type {SearchPositionRestoreTask | null} */let positionRestore = null;/** @type {VoiceOfMLSearchAppWindow | null} */let resultWindow = null;/** @type {SearchPosition | null} */let returnPositionTarget = null;/** @type {{key: string, last: number, distance: number, until: number} | null} */let positionControlScroll = null;let positionEntryId = 0;let backToTopPending = false;function getReturnPositionTarget(key = getSearchViewKey()) {20 unmodified linesfunction updateSearchPositionControls() {if (!getReturnPositionTarget()) setReturnPositionTarget();if (DOM.returnToPositionBtn) DOM.returnToPositionBtn.hidden = !returnPositionTarget || !!positionRestore;if (DOM.backToTopBtn) DOM.backToTopBtn.hidden = backToTopPending || !STATE.results.length || getResultScrollTop() <= 0;if (DOM.positionRestoreStatus) DOM.positionRestoreStatus.hidden = !positionRestore;}/** @param {boolean} [preserveDrafts] */function cancelPendingSearchControls(preserveDrafts = false) {if (preserveDrafts) return;searchInputController.cancelTimer();if (filterSearchTimer !== null) clearTimeout(filterSearchTimer);if (sizeFilterTimer !== null) clearTimeout(sizeFilterTimer);filterSearchTimer = null;sizeFilterTimer = null;}/** @param {{fromStart: boolean, restorePosition: boolean}} options */function prepareSearchPositionNavigation({ fromStart, restorePosition }) {// First-page fallback and retries belong to the current view, not to the// newer input draft. Explicit query/filter commits cancel their own debounce.cancelPendingSearchControls(!fromStart);// The URL is the handoff contract for Reader navigation and session restore.// Publish the current controls before any async result work starts.syncStateToURL(true);// A deliberate trip to the top captures the currently displayed position.// During restoration (or when already at the top), retain the existing target.if (fromStart && !positionRestore && getResultScrollTop() > 0) setReturnPositionTarget();saveSearchViewSnapshot();const key = getSearchViewKey();if (fromStart) saveSearchPosition();8 unmodified linesfunction returnToSavedPosition() {const position = getReturnPositionTarget();if (position) return tryRestoreSearchPosition(position.key, { position });return false;}function backToSearchTop() {17 unmodified linesconst top = getResultScrollTop();if (Date.now() <= progress.until) progress.distance += Math.abs(top - progress.last);progress.last = top;if (!positionRestore && progress.distance > Math.max(1200, DOM.resultsContainer.clientHeight * 2)) {setReturnPositionTarget();updateSearchPositionControls();}7 unmodified linesconst index = Math.min(STATE.total - 1, requested - 1);const key = getSearchViewKey();setReturnPositionTarget();if (!positionRestore && !resultWindow?.invalid && STATE.results[index]) setResultScrollTop(getVirtualOffset(index));else tryRestoreSearchPosition(key, { viewport: null, position: {version: 1, key, index, offset: 0, anchorId: "",loadedPage: Math.floor(index / STATE.pageSize) + 1, savedAt: Date.now()74 unmodified lineswindow.pending.set(page, request);try {const entry = await request;if (!resultWindowCurrent(window) || !positionRestore?.preview || VSCROLL.isDraggingThumb) return;if (!entry) { (window.missingPages ||= new Set()).add(page); return; }const start = (page - 1) * window.query.pageSize;if (start + entry.results.length > STATE.results.length) return;4 unmodified linesSTATE.results[index] = record; window.count++; VSCROLL.templateCache.delete(index);});window.pages.add(page);(positionRestore.cachedPages ||= new Map()).set(page, entry);VSCROLL.measuredWindowKey = ""; VSCROLL.renderStart = -1; VSCROLL.renderEnd = -1;renderVisible(); updateLoadInfo();} finally {21 unmodified linesreturn VoiceOfMLPositionPolicy.validViewport(viewport, position, getResultStableId);}/** @param {SearchPositionViewport | null} viewport @param {SearchPosition} position @param {SearchPositionRestoreTask} task */function showSavedSearchViewport(viewport, position, task) {if (!validSearchViewport(viewport, position)) return;const size = JSON.parse(position.key).pageSize;const results = new Array(Math.min(viewport.total, position.loadedPage * size));for (const [index, record] of viewport.records) if (Number.isInteger(index) && index >= 0 && index < results.length) results[index] = record;const snapshot = { version: SEARCH_VIEW_SNAPSHOT_VERSION, key: position.key, results, total: viewport.total,loadedPage: position.loadedPage, pageCache: {}, hasMore: results.length < viewport.total,window: { preview: true, generation: viewport.generation, pages: [], count: Object.keys(results).length }, estimatedHeight: viewport.estimatedHeight,heightCache: viewport.records.map(([, record, height]) => /** @type {SearchSnapshotHeightEntry} */ ([getResultStableId(record), {height, measurementKey: viewport.measurementKey}])),scroll: {index: position.index, offset: position.offset, viewKey: position.key}, savedAt: Date.now() };task.preview = true;resultSnapshots.put(position.key, snapshot);restoreSearchViewSnapshot(position.key, true, { preserveRestore: true });resultSnapshots.remove(position.key);showPositionRestoreStatus("已恢复上次画面,正在核对结果…");}/** @param {unknown} value @returns {value is SearchPosition} */function validSearchPosition(value) {return VoiceOfMLPositionPolicy.validPosition(value);23 unmodified linesconst view = displayedSearchView;const target = view && getReturnPositionTarget(view.key);if (target) return target;if (!view || positionRestore || readerHost.overlay || !view.results.length || !VSCROLL.heights.length) return null;if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return positionPersistence.getPosition(view.key) || null;const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);if (!view.results[index]) return positionPersistence.getPosition(view.key) || null;6 unmodified linesfunction setupSearchPositionSaving() {DOM.resultsContainer.addEventListener("scroll", () => {if (positionRestore || STATE.isLoading || displayedSearchView?.key !== getSearchViewKey()) return;positionPersistence.scheduleSave(saveSearchPosition);}, { passive: true });// Query and route handlers save explicitly; capture only filters before mutation.16 unmodified linesupdateLoadInfo();}function cancelPositionRestore() {cancelSnapshotClone();positionEntryId++;const previousWindow = resultWindow;const previousRestore = positionRestore;resultWindow = null;positionRestore = null;updateResultWindowStatus();if (previousRestore) {STATE.isLoading = false;showPositionRestoreStatus("");}previousWindow?.controller.abort();previousRestore?.controller.abort();}const positionRestoration = VoiceOfMLPositionRestoration.create({validatePage: (data, page, size, expected) => validatePositionWindowPage(data, page, size, expected),isCurrent: task => positionRestore === task && task.key === getSearchViewKey(),readViewport: key => readSearchViewport(key),fetchPage: (query, page, signal, anchorId) => fetchPositionPageWithRecovery(query, page, signal, anchorId),showPreview: (viewport, position, task) => showSavedSearchViewport(viewport, position, task),isDragging: () => VSCROLL.isDraggingThumb,capturePreviewAnchor: () => {if (readerHost.overlay) return null;3 unmodified lines},stableId: record => getResultStableId(record),estimatedHeight: () => VSCROLL.estimatedHeight,release: () => { positionRestore = null; showPositionRestoreStatus(""); },applyPreview: snapshot => applyValidatedSearchViewport(snapshot),snapshots: resultSnapshots,// Completing a position restore does not own query input typed while it was loading.restoreSnapshot: key => restoreSearchViewSnapshot(key, true, { preserveQueryDraft: true }),completed: () => resetPositionControlScroll(),failed: message => { STATE.isLoading = false; showPositionRestoreStatus(message, true); },notify: message => showToast(message)});/** @param {string} key @param {{position?: SearchPosition | null; viewport?: SearchPositionViewport | null}} [options] */function tryRestoreSearchPosition(key, options = {}) {const previous = positionRestore?.key === key && positionRestore.failed && !options.position ? positionRestore : null;const position = options.position || previous?.position || positionPersistence.getPosition(key);if (!validSearchPosition(position)) return false;searchIntentId++;if (!options.position && positionRestore?.key === key && !positionRestore.failed) return true;if (!cancelActiveSearch()) return false;const owner = searchId;cancelPositionRestore();if (owner !== searchId) return false;setReturnPositionTarget();const task = VoiceOfMLPositionRestoration.createTask({ key, position, previous });positionRestore = task;STATE.isLoading = true;resetPagingRecovery();showPositionRestoreStatus("正在恢复上次位置…");void positionRestoration.run(task, options.viewport);return true;}/** @param {SearchResultSnapshot} snapshot */function applyValidatedSearchViewport(snapshot) {const anchor = snapshot.scroll;const previous = STATE.results;// Preview selections belong to records, not to slots replaced by validation.85 unmodified linesfunction resumeResultRecovery() {if (document.hidden || !navigator.onLine || readerHost.overlay) return;if (positionRestore?.failed && isRecoverableSearchError(positionRestore.error)) {tryRestoreSearchPosition(positionRestore.key);return;}if (!resultWindow || resultWindow.invalid) return;const start = Math.floor(findVirtualIndex(getResultScrollTop()) / STATE.pageSize);const end = Math.floor(findVirtualIndex(getResultScrollTop() + DOM.resultsContainer.clientHeight) / STATE.pageSize) + 2;21 unmodified lines/** @param {number} page @param {boolean} [prefetch] */async function loadResultWindowPage(page, prefetch = false) {const window = resultWindow;if (!window || positionRestore || !resultWindowCurrent(window) || window.pages.has(page) || page < 1 || page > Math.ceil(window.total / window.query.pageSize)) return false;try {const data = await requestResultWindowPage(window, page, prefetch);if (!data || !resultWindowCurrent(window) || window.invalid || window.pages.has(page)) return false;64 unmodified linesif (!resultWindow || VSCROLL.isDraggingThumb) return;const activeWindow = resultWindow;const size = activeWindow.query.pageSize;if (positionRestore) {if (positionRestore.preview) for (let page = Math.floor(start / size) + 1; page <= Math.ceil(end / size); page++) loadCachedPreviewPage(resultWindow, page);return;}const scrollTop = getResultScrollTop();103 unmodified lines}// Browsing from the top must not overwrite the snapshot offered by Return.if (getReturnPositionTarget(key)) return resultSnapshots.snapshots.get(key) || null;if (!DOM.resultsContainer || !view || positionRestore || key !== view.key || view.loadedPage < 1) return null;const position = saveSearchPosition();return resultSnapshots.save(view, position, {revision: measuredHeightRevision, measurementKey: getHeightMeasurementKey(),6 unmodified linesconst snapshot = resultSnapshots.snapshots.get(key);VSCROLL.heightCache = new Map(snapshot?.heightCache || []);}function cancelSnapshotClone() {resultSnapshots.cancelClone();}/** @param {SearchSnapshotCloneTask} task @param {number} start @param {number} end @param {boolean} [deferHeights] */function materializeSnapshotRange(task, start, end, deferHeights = false) {resultSnapshots.materializeRange(task, start, end, deferHeights);46 unmodified linesconst owner = searchId;if (!preserveRestore) cancelPositionRestore();if (owner !== searchId) return false;if (!preserveRestore) cancelPendingSearchControls(preserveQueryDraft);STATE.results = resultSnapshots.restoreResults(snapshot, key, STATE.pageSize, restoreScroll, preserveRestore);STATE.total = snapshot.total;STATE.page = STATE._loadedPage = snapshot.loadedPage;296 unmodified linesconst owner = searchId;cancelPositionRestore();if (owner !== searchId || intent !== searchIntentId) return false;const key = getSearchViewKey(), entry = positionEntryId;prepareReturnPosition(key);if (resultSnapshots.snapshots.has(key)) {setReturnPositionTarget();1 unmodified line}const position = getReturnPositionTarget(key);const viewport = position ? await readSearchViewport(key) : null;if (intent !== searchIntentId || entry !== positionEntryId || key !== getSearchViewKey()) return false;if (validSearchViewport(viewport, position)) return tryRestoreSearchPosition(key, {position, viewport});return searchWithInitialFallbackFresh(intent);}361 unmodified lines// Reader host owns overlay and return-position state. Effects resolve live host hooks.const readerReturnPosition = VoiceOfMLReaderReturn.create({readView: () => ({ hasContainer: !!DOM.resultsContainer, containerHeight: DOM.resultsContainer?.clientHeight || 0,resultCount: STATE.results.length, total: STATE.total, loading: STATE.isLoading, loadedPage: STATE._loadedPage,positionRestore: positionRestore && { preview: positionRestore.preview, key: positionRestore.key }, routeRevision: routeRenderId }),hasResult: index => !!STATE.results[index], getViewKey: () => getSearchViewKey(),getTop: () => getResultScrollTop(), setTop: top => setResultScrollTop(top),ensureHeights: () => ensureHeightTree(), findIndex: top => findVirtualIndex(top),476 unmodified lines}syncURLToState(false);const sameSearchView = previousSearchKey === getSearchViewKey();const directoryOnly = sameSearchView && STATE.mode === "repo" && previousPath !== STATE.browserPath;if (directoryOnly && searchComposing) searchInputController.invalidateVisit();if (!directoryOnly && !searchComposing && !initialSearchDraft) setSearchInputValue(STATE.query);if (!sameSearchView) {if (routeInitialized) searchInputController.invalidateVisit();cancelPendingSearchControls();readerReturnPosition.invalidate();if (!cancelActiveSearch()) return;}66 unmodified linesDOM.sortSelect.value = projected.sort;STATE.filterExtensions = projected.filterExtensions === null ? loadStoredExtensionFilters() : projected.filterExtensions;if (projected.filterExtensions !== null) saveStoredExtensionFilters();const minSize = params.get("min_size");if (minSize) {var parsed = parseSizeStr(minSize);STATE.filterMinSize = parsed;var disp = bytesToDisplay(parsed);DOM.filterMinSize.value = disp.value;DOM.filterMinUnit.value = disp.unit;} else {STATE.filterMinSize = null;DOM.filterMinSize.value = "";DOM.filterMinUnit.value = "MB";}const maxSize = params.get("max_size");if (maxSize) {var parsedMx = parseSizeStr(maxSize);STATE.filterMaxSize = parsedMx;var dispMx = bytesToDisplay(parsedMx);DOM.filterMaxSize.value = dispMx.value;DOM.filterMaxUnit.value = dispMx.unit;} else {STATE.filterMaxSize = null;DOM.filterMaxSize.value = "";DOM.filterMaxUnit.value = "MB";}STATE.searchFolders = projected.searchFolders;DOM.searchFoldersToggle.checked = STATE.searchFolders;STATE.filterFolderSelfs = projected.filterFolderSelfs;111 unmodified linesreturn;}// Another search can preempt the size debounce: include its visible input.applyPendingSizeFilters();cancelPendingSearchControls();saveSearchViewSnapshot();if (updateInput) setSearchInputValue(query);STATE.query = query;11 unmodified linesfunction prepareReaderSearch() {if (readerHost.overlay || location.pathname + location.search !== appliedSearchRoute) return;if (searchTimer !== null && !searchComposing) {searchInputController.cancelTimer();submitSearchQuery(DOM.searchInput.value.trim(), { record: true, refreshHistory: true });}if (sizeFilterTimer !== null || filterSearchTimer !== null) {doFilterSearch();20 unmodified linessyncInput: syncSearchInputState,canSubmit: () => !readerHost.overlay && location.pathname + location.search === appliedSearchRoute,submit: query => { submitSearchQuery(query, { record: true, refreshHistory: true }); },onState: state => {searchTimer = state.timer;searchComposing = state.composing;initialSearchDraft = state.dirty;}33 unmodified lines}function renderResults(animate = false) {if (!positionRestore && STATE._loadedPage >= 1) rememberDisplayedSearchView();activateSearchView();redrawResults(animate);}197 unmodified linesif (!resultWindow) throw new TypeError("Result window is missing");return resultWindow.total;},cloning: () => !!resultSnapshots.cloneTask, restoring: () => !!positionRestore,loadedPage: () => STATE._loadedPage, pendingEntrance: () => pendingResultEntrance,consumeEntrance: () => { pendingResultEntrance = false; },recordMeasurement: () => { measuredHeightRevision++; },84 unmodified lines/** @param {boolean} clearResults */function prepareFilterChange(clearResults) {// Merge completed query drafts too; a filter click must not discard typing.const query = searchTimer !== null && !searchComposing ? DOM.searchInput.value.trim() : null;applyPendingSizeFilters();cancelPendingSearchControls();saveSearchViewSnapshot();if (query !== null && Array.from(query).length <= 256) STATE.query = query;STATE.page = 1;5 unmodified linesreturn doSearch(false, false, true);}/** @param {HTMLInputElement} input @param {HTMLSelectElement} unitSelect */function sizeInputToBytes(input, unitSelect) {const value = parseFloat(input.value);if (isNaN(value) || value < 0) return null;/** @type {Record<string, number>} */const factors = { B: 1, KB: 1024, MB: 1048576, GB: 1073741824 };const factor = factors[unitSelect.value] || 1;return Math.round(value * factor);}function applyPendingSizeFilters() {if (sizeFilterTimer === null) return;clearTimeout(sizeFilterTimer);sizeFilterTimer = null;STATE.filterMinSize = sizeInputToBytes(DOM.filterMinSize, DOM.filterMinUnit);STATE.filterMaxSize = sizeInputToBytes(DOM.filterMaxSize, DOM.filterMaxUnit);}function setupSizeFilterControls() {const schedule = () => {if (sizeFilterTimer !== null) clearTimeout(sizeFilterTimer);sizeFilterTimer = setTimeout(() => {applyPendingSizeFilters();doFilterSearch(true);}, 500);};[DOM.filterMinSize, DOM.filterMaxSize].forEach(input => input.addEventListener("input", schedule));// A unit alone does not change the search. Leave any pending edit to// either bound on its existing debounce deadline.DOM.filterMinUnit.addEventListener("change", () => { if (DOM.filterMinSize.value !== "") schedule(); });DOM.filterMaxUnit.addEventListener("change", () => { if (DOM.filterMaxSize.value !== "") schedule(); });}function scheduleFilterSearch(clearResults = false) {searchIntentId++;prepareFilterChange(clearResults);5 unmodified linesSTATE.isLoading = true;setSearchVisualLoading(true);syncStateToURL(true);filterSearchTimer = setTimeout(() => {filterSearchTimer = null;doFilterSearch();}, FILTER_SEARCH_DEBOUNCE_MS);}function updateCurrentResultPosition() {188 unmodified linesconst owner = searchId;if (!append && prepareSearchPositionNavigation({ fromStart, restorePosition })) return;if (owner !== searchId) return;if (filterSearchTimer !== null) clearTimeout(filterSearchTimer);filterSearchTimer = null;if (!append) {if (!recoveringFirstPage) resetPagingRecovery();STATE.page = 1;194 unmodified linesreturn {generation: searchRequestId, loadedPage: STATE._loadedPage, page: STATE.page,resultCount: STATE.results.length, hasMore: STATE.hasMore, loading: STATE.isLoading,suspended: !!resultSnapshots.cloneTask || !!positionRestore || (STATE._loadedPage? !ownsDisplayedSearchResults(): searchTimer !== null || filterSearchTimer !== null || sizeFilterTimer !== null || searchComposing),inactive: document.hidden || !!readerHost.overlay, dragging: VSCROLL.isDraggingThumb,529 unmodified linesDOM.randomBookBtn.addEventListener('click', randomBook);if (DOM.randomTxtBtn) DOM.randomTxtBtn.addEventListener('click', randomTxt);DOM.emptyRandomBtn.addEventListener('click', randomTxt);setupSizeFilterControls();setupExtensionBulkSelection();if (DOM.folderToggleAll) DOM.folderToggleAll.addEventListener("click", () =>setAllFoldersCollapsed(DOM.folderToggleAll.getAttribute("aria-expanded") === "true"));116 unmodified lines117118119120121122113 unmodified lines23623723823924024124224324424524624720 unmodified lines2682692702712722732742752762772782792802812822832842852862872888 unmodified lines29729829930030130230330430530617 unmodified lines3243253263273283293307 unmodified lines33833934034134234334474 unmodified lines4194204214224234244254 unmodified lines43043143243343443543621 unmodified lines45845946046146246323 unmodified lines4874884894904914924936 unmodified lines50050150250350450550616 unmodified lines5235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535543 unmodified lines55855956056156256356456556656756856957057157257357457557685 unmodified lines66266366466566666766821 unmodified lines69069169269369469569664 unmodified lines761762763764765766767768769103 unmodified lines8738748758768778788796 unmodified lines88688788888989089146 unmodified lines938939940941942943944296 unmodified lines12411242124312441245124612471 unmodified line1249125012511252125312541255361 unmodified lines161716181619162016211622162316241625162616271628476 unmodified lines210521062107210821092110211121122113211421152116211766 unmodified lines21842185218621872188218921902191111 unmodified lines2303230423052306230723082309231011 unmodified lines232223232324232523262327232823292330233120 unmodified lines235223532354235523562357235823592360236123622363236423652366236733 unmodified lines2401240224032404240524062407197 unmodified lines260526062607260826092610261184 unmodified lines2696269726982699270027012702270327045 unmodified lines2710271127122713271427155 unmodified lines2721272227232724272527262727188 unmodified lines2916291729182919292029212922194 unmodified lines3117311831193120312131223123529 unmodified lines365336543655365636573658116 unmodified lineslet filterSearchTimer = null;/** @type {ReturnType<typeof setTimeout> | null} */let sizeFilterTimer = null;let routeRenderId = 0;// A path-only route change bumps routeRenderId for the browser, but must not// orphan an unfinished filter render or its batched folder-tree tasks.113 unmodified lines});/** @type {VoiceOfMLSearchAppDisplayedView | null} */let displayedSearchView = null;/** @type {VoiceOfMLSearchAppWindow | null} */let resultWindow = null;/** @type {SearchPosition | null} */let returnPositionTarget = null;/** @type {{key: string, last: number, distance: number, until: number} | null} */let positionControlScroll = null;let backToTopPending = false;function getReturnPositionTarget(key = getSearchViewKey()) {20 unmodified linesfunction updateSearchPositionControls() {if (!getReturnPositionTarget()) setReturnPositionTarget();if (DOM.returnToPositionBtn) DOM.returnToPositionBtn.hidden = !returnPositionTarget || !!positionRestoration.current;if (DOM.backToTopBtn) DOM.backToTopBtn.hidden = backToTopPending || !STATE.results.length || getResultScrollTop() <= 0;if (DOM.positionRestoreStatus) DOM.positionRestoreStatus.hidden = !positionRestoration.current;}/** @param {{fromStart: boolean, restorePosition: boolean}} options */function prepareSearchPositionNavigation({ fromStart, restorePosition }) {// First-page fallback and retries do not own newer query or size drafts.if (fromStart) searchInputController.cancelPending();// The URL is the handoff contract for Reader navigation and session restore.// Publish the current controls before any async result work starts.syncStateToURL(true);// A deliberate trip to the top captures the currently displayed position.// During restoration (or when already at the top), retain the existing target.if (fromStart && !positionRestoration.current && getResultScrollTop() > 0) setReturnPositionTarget();saveSearchViewSnapshot();const key = getSearchViewKey();if (fromStart) saveSearchPosition();8 unmodified linesfunction returnToSavedPosition() {const position = getReturnPositionTarget();if (!position) return false;// A queued filter must not restart the search while Return is waiting for I/O.searchInputController.cancelPending(true);return tryRestoreSearchPosition(position.key, { position });}function backToSearchTop() {17 unmodified linesconst top = getResultScrollTop();if (Date.now() <= progress.until) progress.distance += Math.abs(top - progress.last);progress.last = top;if (!positionRestoration.current && progress.distance > Math.max(1200, DOM.resultsContainer.clientHeight * 2)) {setReturnPositionTarget();updateSearchPositionControls();}7 unmodified linesconst index = Math.min(STATE.total - 1, requested - 1);const key = getSearchViewKey();setReturnPositionTarget();if (!positionRestoration.current && !resultWindow?.invalid && STATE.results[index]) setResultScrollTop(getVirtualOffset(index));else tryRestoreSearchPosition(key, { viewport: null, position: {version: 1, key, index, offset: 0, anchorId: "",loadedPage: Math.floor(index / STATE.pageSize) + 1, savedAt: Date.now()74 unmodified lineswindow.pending.set(page, request);try {const entry = await request;if (!resultWindowCurrent(window) || !positionRestoration.current?.preview || VSCROLL.isDraggingThumb) return;if (!entry) { (window.missingPages ||= new Set()).add(page); return; }const start = (page - 1) * window.query.pageSize;if (start + entry.results.length > STATE.results.length) return;4 unmodified linesSTATE.results[index] = record; window.count++; VSCROLL.templateCache.delete(index);});window.pages.add(page);positionRestoration.rememberPreviewPage(page, entry);VSCROLL.measuredWindowKey = ""; VSCROLL.renderStart = -1; VSCROLL.renderEnd = -1;renderVisible(); updateLoadInfo();} finally {21 unmodified linesreturn VoiceOfMLPositionPolicy.validViewport(viewport, position, getResultStableId);}/** @param {unknown} value @returns {value is SearchPosition} */function validSearchPosition(value) {return VoiceOfMLPositionPolicy.validPosition(value);23 unmodified linesconst view = displayedSearchView;const target = view && getReturnPositionTarget(view.key);if (target) return target;if (!view || positionRestoration.current || readerHost.overlay || !view.results.length || !VSCROLL.heights.length) return null;if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return positionPersistence.getPosition(view.key) || null;const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);if (!view.results[index]) return positionPersistence.getPosition(view.key) || null;6 unmodified linesfunction setupSearchPositionSaving() {DOM.resultsContainer.addEventListener("scroll", () => {if (positionRestoration.current || STATE.isLoading || displayedSearchView?.key !== getSearchViewKey()) return;positionPersistence.scheduleSave(saveSearchPosition);}, { passive: true });// Query and route handlers save explicitly; capture only filters before mutation.16 unmodified linesupdateLoadInfo();}const positionRestoration = VoiceOfMLPositionRestoration.create({currentKey: () => getSearchViewKey(),getPosition: key => positionPersistence.getPosition(key),noteSearchIntent: () => { searchIntentId++; },retireSearch: () => {if (!cancelActiveSearch()) return null;const owner = searchId;return () => owner === searchId;},detachWindow: () => {const controller = resultWindow?.controller;resultWindow = null;updateResultWindowStatus();return controller;},status: (phase, message) => {if (phase === "started") {setReturnPositionTarget();STATE.isLoading = true;resetPagingRecovery();} else if (phase === "cancelled" || phase === "failed") STATE.isLoading = false;showPositionRestoreStatus(message, phase === "failed");},validatePage: (data, page, size, expected) => validatePositionWindowPage(data, page, size, expected),readViewport: key => readSearchViewport(key),fetchPage: (query, page, signal, anchorId) => fetchPositionPageWithRecovery(query, page, signal, anchorId),isDragging: () => VSCROLL.isDraggingThumb,capturePreviewAnchor: () => {if (readerHost.overlay) return null;3 unmodified lines},stableId: record => getResultStableId(record),estimatedHeight: () => VSCROLL.estimatedHeight,applyPreview: snapshot => applyValidatedSearchViewport(snapshot),snapshots: resultSnapshots,// Completing a position restore does not own query input typed while it was loading.restoreSnapshot: (key, preview) => restoreSearchViewSnapshot(key, true,preview ? { preserveRestore: true } : { preserveQueryDraft: true }),completed: () => resetPositionControlScroll(),notify: message => showToast(message)});const { cancel: cancelPositionRestore, start: tryRestoreSearchPosition } = positionRestoration;/** @param {SearchResultSnapshot} snapshot */function applyValidatedSearchViewport(snapshot) {searchInputController.cancelPending(true);const anchor = snapshot.scroll;const previous = STATE.results;// Preview selections belong to records, not to slots replaced by validation.85 unmodified linesfunction resumeResultRecovery() {if (document.hidden || !navigator.onLine || readerHost.overlay) return;if (positionRestoration.resume()) return;if (!resultWindow || resultWindow.invalid) return;const start = Math.floor(findVirtualIndex(getResultScrollTop()) / STATE.pageSize);const end = Math.floor(findVirtualIndex(getResultScrollTop() + DOM.resultsContainer.clientHeight) / STATE.pageSize) + 2;21 unmodified lines/** @param {number} page @param {boolean} [prefetch] */async function loadResultWindowPage(page, prefetch = false) {const window = resultWindow;if (!window || positionRestoration.current || !resultWindowCurrent(window) || window.pages.has(page) || page < 1 || page > Math.ceil(window.total / window.query.pageSize)) return false;try {const data = await requestResultWindowPage(window, page, prefetch);if (!data || !resultWindowCurrent(window) || window.invalid || window.pages.has(page)) return false;64 unmodified linesif (!resultWindow || VSCROLL.isDraggingThumb) return;const activeWindow = resultWindow;const size = activeWindow.query.pageSize;const restore = positionRestoration.current;if (restore) {if (restore.preview) for (let page = Math.floor(start / size) + 1; page <= Math.ceil(end / size); page++) loadCachedPreviewPage(resultWindow, page);return;}const scrollTop = getResultScrollTop();103 unmodified lines}// Browsing from the top must not overwrite the snapshot offered by Return.if (getReturnPositionTarget(key)) return resultSnapshots.snapshots.get(key) || null;if (!DOM.resultsContainer || !view || positionRestoration.current || key !== view.key || view.loadedPage < 1) return null;const position = saveSearchPosition();return resultSnapshots.save(view, position, {revision: measuredHeightRevision, measurementKey: getHeightMeasurementKey(),6 unmodified linesconst snapshot = resultSnapshots.snapshots.get(key);VSCROLL.heightCache = new Map(snapshot?.heightCache || []);}/** @param {SearchSnapshotCloneTask} task @param {number} start @param {number} end @param {boolean} [deferHeights] */function materializeSnapshotRange(task, start, end, deferHeights = false) {resultSnapshots.materializeRange(task, start, end, deferHeights);46 unmodified linesconst owner = searchId;if (!preserveRestore) cancelPositionRestore();if (owner !== searchId) return false;if (!preserveRestore) searchInputController.cancelPending(preserveQueryDraft);STATE.results = resultSnapshots.restoreResults(snapshot, key, STATE.pageSize, restoreScroll, preserveRestore);STATE.total = snapshot.total;STATE.page = STATE._loadedPage = snapshot.loadedPage;296 unmodified linesconst owner = searchId;cancelPositionRestore();if (owner !== searchId || intent !== searchIntentId) return false;const key = getSearchViewKey(), entry = positionRestoration.entry;prepareReturnPosition(key);if (resultSnapshots.snapshots.has(key)) {setReturnPositionTarget();1 unmodified line}const position = getReturnPositionTarget(key);const viewport = position ? await readSearchViewport(key) : null;if (intent !== searchIntentId || entry !== positionRestoration.entry || key !== getSearchViewKey()) return false;if (validSearchViewport(viewport, position)) return tryRestoreSearchPosition(key, {position, viewport});return searchWithInitialFallbackFresh(intent);}361 unmodified lines// Reader host owns overlay and return-position state. Effects resolve live host hooks.const readerReturnPosition = VoiceOfMLReaderReturn.create({readView: () => {const restore = positionRestoration.current;return { hasContainer: !!DOM.resultsContainer, containerHeight: DOM.resultsContainer?.clientHeight || 0,resultCount: STATE.results.length, total: STATE.total, loading: STATE.isLoading, loadedPage: STATE._loadedPage,positionRestore: restore && { preview: restore.preview, key: restore.key }, routeRevision: routeRenderId };},hasResult: index => !!STATE.results[index], getViewKey: () => getSearchViewKey(),getTop: () => getResultScrollTop(), setTop: top => setResultScrollTop(top),ensureHeights: () => ensureHeightTree(), findIndex: top => findVirtualIndex(top),476 unmodified lines}syncURLToState(false);const sameSearchView = previousSearchKey === getSearchViewKey();searchInputController.syncSize(sameSearchView);const directoryOnly = sameSearchView && STATE.mode === "repo" && previousPath !== STATE.browserPath;if (directoryOnly && searchComposing) searchInputController.invalidateVisit();if (!directoryOnly && !searchComposing && !initialSearchDraft) setSearchInputValue(STATE.query);if (!sameSearchView) {if (routeInitialized) searchInputController.invalidateVisit();searchInputController.cancelPending();readerReturnPosition.invalidate();if (!cancelActiveSearch()) return;}66 unmodified linesDOM.sortSelect.value = projected.sort;STATE.filterExtensions = projected.filterExtensions === null ? loadStoredExtensionFilters() : projected.filterExtensions;if (projected.filterExtensions !== null) saveStoredExtensionFilters();STATE.filterMinSize = parseSizeStr(params.get("min_size"));STATE.filterMaxSize = parseSizeStr(params.get("max_size"));STATE.searchFolders = projected.searchFolders;DOM.searchFoldersToggle.checked = STATE.searchFolders;STATE.filterFolderSelfs = projected.filterFolderSelfs;111 unmodified linesreturn;}// Another search can preempt the size debounce: include its visible input.searchInputController.flushSize();searchInputController.cancelPending();saveSearchViewSnapshot();if (updateInput) setSearchInputValue(query);STATE.query = query;11 unmodified linesfunction prepareReaderSearch() {if (readerHost.overlay || location.pathname + location.search !== appliedSearchRoute) return;const query = searchInputController.pendingQuery();if (query !== null) {searchInputController.cancelTimer();submitSearchQuery(query, { record: true, refreshHistory: true });}if (sizeFilterTimer !== null || filterSearchTimer !== null) {doFilterSearch();20 unmodified linessyncInput: syncSearchInputState,canSubmit: () => !readerHost.overlay && location.pathname + location.search === appliedSearchRoute,submit: query => { submitSearchQuery(query, { record: true, refreshHistory: true }); },filterSearch: clearResults => doFilterSearch(clearResults),size: {min: DOM.filterMinSize, max: DOM.filterMaxSize, minUnit: DOM.filterMinUnit, maxUnit: DOM.filterMaxUnit,read: () => [STATE.filterMinSize, STATE.filterMaxSize], format: bytesToDisplay,commit: (min, max) => { STATE.filterMinSize = min; STATE.filterMaxSize = max; }},onState: state => {searchTimer = state.timer;filterSearchTimer = state.filterTimer;sizeFilterTimer = state.sizeTimer;searchComposing = state.composing;initialSearchDraft = state.dirty;}33 unmodified lines}function renderResults(animate = false) {if (!positionRestoration.current && STATE._loadedPage >= 1) rememberDisplayedSearchView();activateSearchView();redrawResults(animate);}197 unmodified linesif (!resultWindow) throw new TypeError("Result window is missing");return resultWindow.total;},cloning: () => !!resultSnapshots.cloneTask, restoring: () => !!positionRestoration.current,loadedPage: () => STATE._loadedPage, pendingEntrance: () => pendingResultEntrance,consumeEntrance: () => { pendingResultEntrance = false; },recordMeasurement: () => { measuredHeightRevision++; },84 unmodified lines/** @param {boolean} clearResults */function prepareFilterChange(clearResults) {// Merge completed query drafts too; a filter click must not discard typing.const query = searchInputController.pendingQuery();searchInputController.flushSize();searchInputController.cancelPending();saveSearchViewSnapshot();if (query !== null && Array.from(query).length <= 256) STATE.query = query;STATE.page = 1;5 unmodified linesreturn doSearch(false, false, true);}function scheduleFilterSearch(clearResults = false) {searchIntentId++;prepareFilterChange(clearResults);5 unmodified linesSTATE.isLoading = true;setSearchVisualLoading(true);syncStateToURL(true);searchInputController.scheduleFilter();}function updateCurrentResultPosition() {188 unmodified linesconst owner = searchId;if (!append && prepareSearchPositionNavigation({ fromStart, restorePosition })) return;if (owner !== searchId) return;searchInputController.cancelFilter();if (!append) {if (!recoveringFirstPage) resetPagingRecovery();STATE.page = 1;194 unmodified linesreturn {generation: searchRequestId, loadedPage: STATE._loadedPage, page: STATE.page,resultCount: STATE.results.length, hasMore: STATE.hasMore, loading: STATE.isLoading,suspended: !!resultSnapshots.cloneTask || !!positionRestoration.current || (STATE._loadedPage? !ownsDisplayedSearchResults(): searchTimer !== null || filterSearchTimer !== null || sizeFilterTimer !== null || searchComposing),inactive: document.hidden || !!readerHost.overlay, dragging: VSCROLL.isDraggingThumb,529 unmodified linesDOM.randomBookBtn.addEventListener('click', randomBook);if (DOM.randomTxtBtn) DOM.randomTxtBtn.addEventListener('click', randomTxt);DOM.emptyRandomBtn.addEventListener('click', randomTxt);setupExtensionBulkSelection();if (DOM.folderToggleAll) DOM.folderToggleAll.addEventListener("click", () =>setAllFoldersCollapsed(DOM.folderToggleAll.getAttribute("aria-expanded") === "true"));
12345678910111213141516171819202122239 unmodified lines333435363738394041424344454647484930 unmodified lines80818283848521 unmodified lines107108109110111112113114115116117118119120121122123// Owns the input listeners, startup handoff, IME visit and debounce lifetime.(function () {/** @param {VoiceOfMLInputDependencies} deps @returns {VoiceOfMLInputController} */function create(deps) {const { input, navigation, ownership, clock } = deps;/** @type {VoiceOfMLInputState & {generation: number, owner: VoiceOfMLInputDraftOwner | null}} */const state = { timer: null, composing: false, generation: 0, ready: false, dirty: false, owner: null };let composition = ownership.visit(0, null);let mounted = false, disposed = false, timerGeneration = 0;const navigationEvents = ["popstate", "hashchange", "pagehide"];// Each notification is detached and contains only host presentation state.const publish = () => deps.onState({ timer: state.timer, composing: state.composing, dirty: state.dirty, ready: state.ready });function cancelTimer() {const token = ++timerGeneration;if (state.timer !== null) clock.clearTimeout(state.timer);state.timer = null;publish();return token;}function invalidateVisit() { state.generation++; cancelTimer(); }function captureDraft(renew = false) {if (disposed || state.ready) return;9 unmodified linesif (disposed || state.composing || !state.ready || !deps.canSubmit()) return;const token = cancelTimer();// Publication may synchronously cancel, replace or dispose this operation.if (disposed || token !== timerGeneration || state.composing || !state.ready) return;const owner = ownership.visit(state.generation, null);state.timer = clock.setTimeout(() => {// A cancelled callback must neither submit nor clear its replacement timer.if (disposed || token !== timerGeneration) return;state.timer = null;publish();if (disposed || token !== timerGeneration || state.composing || !deps.canSubmit() ||!ownership.visitIsCurrent(owner, state.generation, null)) return;deps.submit(input.value.trim());}, 100);publish();}/** @param {Event} event */30 unmodified linesinput.addEventListener("input", onInput);input.addEventListener("compositionstart", onStart);input.addEventListener("compositionend", onEnd);// The inline producer remains active until these listeners are installed.const early = input._earlySearchInput;if (early) {21 unmodified linesif (disposed) return;disposed = true;cancelDraft();invalidateVisit();removeNavigationListeners();input.removeEventListener("input", onInput);input.removeEventListener("compositionstart", onStart);input.removeEventListener("compositionend", onEnd);state.composing = false;state.dirty = false;state.owner = null;publish();}return { mount, dispose, debounce, cancelTimer, invalidateVisit, captureDraft, cancelDraft, draftIsCurrent, finishStartup };}globalThis.VoiceOfMLSearchInput = { create };})();1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191209 unmodified lines13013113213313413513613713813914014114214330 unmodified lines17417517617717817918018118218321 unmodified lines205206207208209210211212213214215216217218219220221222223224225226227// Owns search-control drafts and the lifetimes of their delayed commits.(function () {/** @param {VoiceOfMLInputDependencies['clock']} clock */function debounceSlot(clock) {/** @type {number | null} */let timer = null;let generation = 0;function cancel() {const token = ++generation;if (timer !== null) clock.clearTimeout(timer);timer = null;return token;}/** @param {number} token */const isCurrent = token => token === generation;/** @param {number} token @param {number} delay @param {() => void} run */function schedule(token, delay, run) {if (!isCurrent(token)) return;timer = clock.setTimeout(() => {if (!isCurrent(token) || timer === null) return;timer = null;run();}, delay);}return { get timer() { return timer; }, cancel, isCurrent, schedule };}/** @param {string} value @param {string} unit */function sizeInputToBytes(value, unit) {const number = parseFloat(value);if (isNaN(number) || number < 0) return null;const factors = /** @type {Record<string, number>} */ ({ B: 1, KB: 1024, MB: 1048576, GB: 1073741824 });return Math.round(number * (factors[unit] || 1));}/** @param {VoiceOfMLInputDependencies} deps @returns {VoiceOfMLInputController} */function create(deps) {const { input, navigation, ownership, clock, size } = deps;const query = debounceSlot(clock), filters = debounceSlot(clock), sizeEdit = debounceSlot(clock);/** @type {Pick<VoiceOfMLInputState, 'composing' | 'ready' | 'dirty'> & {generation: number, owner: VoiceOfMLInputDraftOwner | null}} */const state = { composing: false, generation: 0, ready: false, dirty: false, owner: null };let composition = ownership.visit(0, null);let mounted = false, disposed = false;const navigationEvents = ["popstate", "hashchange", "pagehide"];// Each notification is detached and contains only host presentation state.const publish = () => deps.onState({ timer: query.timer, filterTimer: filters.timer, sizeTimer: sizeEdit.timer,composing: state.composing, dirty: state.dirty, ready: state.ready });function cancelTimer() {const token = query.cancel();publish();return token;}function pendingQuery() {return query.timer !== null && !state.composing ? input.value.trim() : null;}function applySize() {size.commit(sizeInputToBytes(size.min.value, size.minUnit.value), sizeInputToBytes(size.max.value, size.maxUnit.value));}function flushSize() {if (sizeEdit.timer === null) return;sizeEdit.cancel();applySize();publish();}/** @param {boolean} [preserveDraft] */function syncSize(preserveDraft = false) {if (preserveDraft && sizeEdit.timer !== null) return;const [min, max] = size.read();const lower = size.format(min), upper = size.format(max);size.min.value = lower.value;size.minUnit.value = lower.unit;size.max.value = upper.value;size.maxUnit.value = upper.unit;}/** @param {boolean} [preserveQuery] */function cancelPending(preserveQuery = false) {filters.cancel();if (sizeEdit.timer !== null) {sizeEdit.cancel();// A discarded bound must not be picked up when the other bound is edited.syncSize();}if (preserveQuery) publish();else cancelTimer();}function cancelFilter() {filters.cancel();publish();}function scheduleFilter() {if (disposed) return;const token = filters.cancel();filters.schedule(token, 200, () => {publish();// Committed filters must settle even if a Reader overlay now covers the results.if (filters.isCurrent(token)) deps.filterSearch();});publish();}function scheduleSize() {if (disposed) return;const token = sizeEdit.cancel();sizeEdit.schedule(token, 500, () => {publish();if (!sizeEdit.isCurrent(token)) return;applySize();deps.filterSearch(true);});publish();}// A unit with an empty bound must not postpone an edit to the other bound.const changeMinUnit = () => { if (size.min.value !== "") scheduleSize(); };const changeMaxUnit = () => { if (size.max.value !== "") scheduleSize(); };function invalidateVisit() { state.generation++; cancelTimer(); }function captureDraft(renew = false) {if (disposed || state.ready) return;9 unmodified linesif (disposed || state.composing || !state.ready || !deps.canSubmit()) return;const token = cancelTimer();// Publication may synchronously cancel, replace or dispose this operation.if (disposed || !query.isCurrent(token) || state.composing || !state.ready) return;const owner = ownership.visit(state.generation, null);query.schedule(token, 100, () => {publish();if (disposed || !query.isCurrent(token) || state.composing || !deps.canSubmit() ||!ownership.visitIsCurrent(owner, state.generation, null)) return;deps.submit(input.value.trim());});publish();}/** @param {Event} event */30 unmodified linesinput.addEventListener("input", onInput);input.addEventListener("compositionstart", onStart);input.addEventListener("compositionend", onEnd);size.min.addEventListener("input", scheduleSize);size.max.addEventListener("input", scheduleSize);size.minUnit.addEventListener("change", changeMinUnit);size.maxUnit.addEventListener("change", changeMaxUnit);// The inline producer remains active until these listeners are installed.const early = input._earlySearchInput;if (early) {21 unmodified linesif (disposed) return;disposed = true;cancelDraft();state.generation++;cancelPending();removeNavigationListeners();input.removeEventListener("input", onInput);input.removeEventListener("compositionstart", onStart);input.removeEventListener("compositionend", onEnd);size.min.removeEventListener("input", scheduleSize);size.max.removeEventListener("input", scheduleSize);size.minUnit.removeEventListener("change", changeMinUnit);size.maxUnit.removeEventListener("change", changeMaxUnit);state.composing = false;state.dirty = false;state.owner = null;publish();}return { mount, dispose, debounce, cancelTimer, invalidateVisit, captureDraft, cancelDraft, draftIsCurrent, finishStartup,pendingQuery, flushSize, syncSize, cancelPending, scheduleFilter, cancelFilter };}globalThis.VoiceOfMLSearchInput = { create };})();
123455 unmodified lines1112131415161718192021222324252653 unmodified lines80818283848586878889909192933 unmodified lines979899100101102103104105106107// Coordinates asynchronous restoration. The host retains synchronous search// cancellation/publication because abort listeners can reenter navigation.(function () {/** @param {SearchPositionRestoreInput} input */function createTask({ key, position, previous }) {5 unmodified lines/** @param {SearchPositionRestorationHost} host */function create(host) {/** @param {SearchPositionRestoreTask} task @param {SearchPositionViewport | null | undefined} viewport */async function run(task, viewport) {const { key, controller } = task;let position = task.position;const current = () => host.isCurrent(task) && !controller.signal.aborted;try {const query = JSON.parse(key);if (viewport === undefined) viewport = await host.readViewport(key);if (!current()) return;host.showPreview(viewport, position, task);while (current()) {const lookup = task.lookup || await host.fetchPage(query, 1, controller.signal, position.anchorId);if (!current()) return;53 unmodified linesestimatedHeight: host.estimatedHeight(), heightCache: [], heightRecords: [],scroll: { index: geometry ? Math.min(geometry.index, Math.max(0, total - 1)) : found < 0 ? index : found,offset: total ? geometry?.offset ?? position.offset : 0, viewKey: key }, savedAt: Date.now() };host.release();if (task.preview && (geometry || found === position.index)) host.applyPreview(snapshot);else {host.snapshots.putRestored(key, snapshot);host.restoreSnapshot(key);}host.completed();host.snapshots.trim();if (!geometry && found < 0 && position.anchorId) host.notify("搜索结果已变化,已恢复到原位置附近");return;}3 unmodified linestask.failed = true;task.error = err;if (err.message === "RESTORE_PAGE_CHANGED") { task.lookup = null; task.ready.clear(); }host.failed(err.message === "RESTORE_PAGE_CHANGED"? "搜索数据已更新,请重试恢复" : "暂时无法加载原位置附近的结果");}}return { run };}globalThis.VoiceOfMLPositionRestoration = { createTask, create };})();123455 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909153 unmodified lines1451461471481491501511521531541551561571581593 unmodified lines163164165166167168169170171172173// Owns the restore task and its preview-to-validated transition. The host// renders snapshots and detaches the displayed pagination window on cancellation.(function () {/** @param {SearchPositionRestoreInput} input */function createTask({ key, position, previous }) {5 unmodified lines/** @param {SearchPositionRestorationHost} host */function create(host) {const { snapshots } = host;/** @type {SearchPositionRestoreTask | null} */let active = null;let entry = 0;function cancel() {snapshots.cancelClone();entry++;const previous = active;active = null;const windowController = host.detachWindow();if (previous) host.status("cancelled", "");// Both owners and their UI are cleared before abort listeners can reenter.windowController?.abort();previous?.controller.abort();}/** @param {string} key @param {SearchPositionRestoreOptions} [options] */function start(key, options = {}) {const same = active?.key === key ? active : null;const previous = same?.failed && !options.position ? same : null;const position = options.position || previous?.position || host.getPosition(key);if (!globalThis.VoiceOfMLPositionPolicy.validPosition(position)) return false;host.noteSearchIntent();if (!options.position && same && !same.failed) return true;const stillOwnsSearch = host.retireSearch();if (!stillOwnsSearch) return false;cancel();if (!stillOwnsSearch()) return false;const task = createTask({ key, position, previous });active = task;host.status("started", "正在恢复上次位置…");void run(task, options.viewport);return true;}function resume() {if (!active?.failed || !globalThis.VoiceOfMLSearchRecovery.isRecoverable(active.error)) return false;start(active.key);return true;}/** @param {number} page @param {SearchRecentPage} data */function rememberPreviewPage(page, data) {if (active?.preview) (active.cachedPages ||= new Map()).set(page, data);}/** @param {SearchPositionViewport | null} viewport @param {SearchPosition} position @param {SearchPositionRestoreTask} task */function showPreview(viewport, position, task) {if (!globalThis.VoiceOfMLPositionPolicy.validViewport(viewport, position, host.stableId)) return;const size = JSON.parse(position.key).pageSize;const results = new Array(Math.min(viewport.total, position.loadedPage * size));for (const [index, record] of viewport.records) if (Number.isInteger(index) && index >= 0 && index < results.length) results[index] = record;const snapshot = { version: globalThis.VoiceOfMLSnapshotPolicy.VERSION, key: position.key, results, total: viewport.total,loadedPage: position.loadedPage, pageCache: {}, hasMore: results.length < viewport.total,window: { preview: true, generation: viewport.generation, pages: [], count: Object.keys(results).length }, estimatedHeight: viewport.estimatedHeight,heightCache: viewport.records.map(([, record, height]) => /** @type {SearchSnapshotHeightEntry} */ ([host.stableId(record), {height, measurementKey: viewport.measurementKey}])),scroll: {index: position.index, offset: position.offset, viewKey: position.key}, savedAt: Date.now() };task.preview = true;snapshots.put(position.key, snapshot);host.restoreSnapshot(position.key, true);snapshots.remove(position.key);host.status("preview", "已恢复上次画面,正在核对结果…");}/** @param {SearchPositionRestoreTask} task @param {SearchPositionViewport | null | undefined} viewport */async function run(task, viewport) {const { key, controller } = task;let position = task.position;const current = () => active === task && key === host.currentKey() && !controller.signal.aborted;try {const query = JSON.parse(key);if (viewport === undefined) viewport = await host.readViewport(key);if (!current()) return;showPreview(viewport, position, task);while (current()) {const lookup = task.lookup || await host.fetchPage(query, 1, controller.signal, position.anchorId);if (!current()) return;53 unmodified linesestimatedHeight: host.estimatedHeight(), heightCache: [], heightRecords: [],scroll: { index: geometry ? Math.min(geometry.index, Math.max(0, total - 1)) : found < 0 ? index : found,offset: total ? geometry?.offset ?? position.offset : 0, viewKey: key }, savedAt: Date.now() };active = null;host.status("finished", "");if (task.preview && (geometry || found === position.index)) host.applyPreview(snapshot);else {snapshots.putRestored(key, snapshot);host.restoreSnapshot(key);}host.completed();snapshots.trim();if (!geometry && found < 0 && position.anchorId) host.notify("搜索结果已变化,已恢复到原位置附近");return;}3 unmodified linestask.failed = true;task.error = err;if (err.message === "RESTORE_PAGE_CHANGED") { task.lookup = null; task.ready.clear(); }host.status("failed", err.message === "RESTORE_PAGE_CHANGED"? "搜索数据已更新,请重试恢复" : "暂时无法加载原位置附近的结果");}}return { get current() { return active; }, get entry() { return entry; }, start, cancel, resume, rememberPreviewPage };}globalThis.VoiceOfMLPositionRestoration = { create };})();
363 unmodified lines364365366367368369370363 unmodified lines}''')self.page.wait_for_function("STATE._loadedPage === 1 && !STATE.isLoading && searchPageMetadata.get(STATE.results[0])?.generation === 'A'")self.page.evaluate("currentGeneration='B'; cancelSearchPrefetch(); STATE.page=2; doSearch(true)")self.page.wait_for_function("!positionRestore && resultWindow?.generation === 'B' && !STATE.isLoading")names = self.page.evaluate('STATE.results.filter(Boolean).map(r => r.File)')self.assertGreaterEqual(len(names), 200)self.assertEqual(names, ['paging-' + str(i) for i in range(-1, len(names) - 1)])363 unmodified lines364365366367368369370363 unmodified lines}''')self.page.wait_for_function("STATE._loadedPage === 1 && !STATE.isLoading && searchPageMetadata.get(STATE.results[0])?.generation === 'A'")self.page.evaluate("currentGeneration='B'; cancelSearchPrefetch(); STATE.page=2; doSearch(true)")self.page.wait_for_function("!positionRestoration.current && resultWindow?.generation === 'B' && !STATE.isLoading")names = self.page.evaluate('STATE.results.filter(Boolean).map(r => r.File)')self.assertGreaterEqual(len(names), 200)self.assertEqual(names, ['paging-' + str(i) for i in range(-1, len(names) - 1)])
42 unmodified lines4344454647484945 unmodified lines9596979899100101227 unmodified lines32933033133233333433528 unmodified lines3643653663673683693704 unmodified lines37537637737837938038138238338422 unmodified lines40740840941041141241342 unmodified linesself.assertEqual(errors, [])def wait_position(self, index):self.page.wait_for_function('i=>!positionRestore && !STATE.isLoading && findVirtualIndex(getResultScrollTop())===i && !!STATE.results[i]', arg=index)def jump(self, number, key='Enter'):self.page.locator('#edit-result-position').click()45 unmodified linesself.page.set_viewport_size({'width':390,'height':844})self.page.evaluate('STATE.isMobile=true;applyMobileMode();failPosition=true')self.jump(95001)self.page.wait_for_function('positionRestore?.failed')self.assertTrue(self.page.locator('#load-info .result-position-actions #retry-position-btn').is_visible())self.assertTrue(self.page.locator('#cancel-position-btn').is_hidden())self.assertEqual(self.page.locator('#results-container').evaluate('e=>getComputedStyle(e).visibility'),'visible')227 unmodified linesself.wait_position(0)self.page.locator('#sort-select').select_option('name')self.page.wait_for_function('!STATE.isLoading && !positionRestore')second = click_top_immediately()self.assertEqual(second['before'], [False, False])self.assertEqual(second['after'], [True, False])28 unmodified linesself.page.wait_for_timeout(250)self.assertEqual(self.page.evaluate('positionCalls'),[1])self.page.locator('#search-input').fill('paging-latest')self.page.wait_for_function('STATE.query==="paging-latest" && !STATE.isLoading && !positionRestore')self.page.evaluate('blockPosition=false;releasePosition()')self.page.wait_for_timeout(100)self.wait_position(0)4 unmodified linesself.page.locator('#restart-position-btn').click()self.wait_position(0)self.page.evaluate('''()=>{DOM.filterMinSize.value='7';DOM.filterMinSize.dispatchEvent(new Event('input',{bubbles:true}));DOM.returnToPositionBtn.click();}''')self.wait_position(95000)self.page.wait_for_timeout(600)self.wait_position(95000)22 unmodified lines};})''')self.page.reload(wait_until='domcontentloaded')self.page.wait_for_function('positionRestore?.preview && !!window.releaseValidation')self.assertEqual(self.page.evaluate('findVirtualIndex(getResultScrollTop())'),95000)self.assertEqual(self.page.locator('#results-container').evaluate('e=>getComputedStyle(e).visibility'),'visible')42 unmodified lines4344454647484945 unmodified lines9596979899100101227 unmodified lines32933033133233333433528 unmodified lines3643653663673683693704 unmodified lines37537637737837938038138238338438538638738838939039139239339422 unmodified lines41741841942042142242342 unmodified linesself.assertEqual(errors, [])def wait_position(self, index):self.page.wait_for_function('i=>!positionRestoration.current && !STATE.isLoading && findVirtualIndex(getResultScrollTop())===i && !!STATE.results[i]', arg=index)def jump(self, number, key='Enter'):self.page.locator('#edit-result-position').click()45 unmodified linesself.page.set_viewport_size({'width':390,'height':844})self.page.evaluate('STATE.isMobile=true;applyMobileMode();failPosition=true')self.jump(95001)self.page.wait_for_function('positionRestoration.current?.failed')self.assertTrue(self.page.locator('#load-info .result-position-actions #retry-position-btn').is_visible())self.assertTrue(self.page.locator('#cancel-position-btn').is_hidden())self.assertEqual(self.page.locator('#results-container').evaluate('e=>getComputedStyle(e).visibility'),'visible')227 unmodified linesself.wait_position(0)self.page.locator('#sort-select').select_option('name')self.page.wait_for_function('!STATE.isLoading && !positionRestoration.current')second = click_top_immediately()self.assertEqual(second['before'], [False, False])self.assertEqual(second['after'], [True, False])28 unmodified linesself.page.wait_for_timeout(250)self.assertEqual(self.page.evaluate('positionCalls'),[1])self.page.locator('#search-input').fill('paging-latest')self.page.wait_for_function('STATE.query==="paging-latest" && !STATE.isLoading && !positionRestoration.current')self.page.evaluate('blockPosition=false;releasePosition()')self.page.wait_for_timeout(100)self.wait_position(0)4 unmodified linesself.page.locator('#restart-position-btn').click()self.wait_position(0)self.page.evaluate('''()=>{readSearchViewport=async()=>null;blockPosition=true;positionCalls=[];DOM.filterMinSize.value='7';DOM.filterMinSize.dispatchEvent(new Event('input',{bubbles:true}));DOM.returnToPositionBtn.click();window.explicitReturn=positionRestoration.current;}''')self.page.wait_for_function('!!window.releasePosition')self.assertIsNone(self.page.evaluate('sizeFilterTimer'))self.assertEqual(self.page.locator('#filter-min-size').input_value(), '')self.page.wait_for_timeout(550)self.assertTrue(self.page.evaluate('positionRestoration.current === explicitReturn'))self.assertEqual(self.page.evaluate('positionCalls'), [1])self.page.evaluate('blockPosition=false;releasePosition()')self.wait_position(95000)self.page.wait_for_timeout(600)self.wait_position(95000)22 unmodified lines};})''')self.page.reload(wait_until='domcontentloaded')self.page.wait_for_function('positionRestoration.current?.preview && !!window.releaseValidation')self.assertEqual(self.page.evaluate('findVirtualIndex(getResultScrollTop())'),95000)self.assertEqual(self.page.locator('#results-container').evaluate('e=>getComputedStyle(e).visibility'),'visible')
51 unmodified lines52535455565758229 unmodified lines28828929029129229329480 unmodified lines37537637737837938038145 unmodified lines42742842943043143243366 unmodified lines5005015025035045055062 unmodified lines50951051151251351451551 unmodified linesself.assertEqual(errors, [])def wait_anchor(self, index, offset=11):self.page.wait_for_function('''({index,offset})=>!positionRestore && !!resultWindow &&findVirtualIndex(getResultScrollTop())===index && !!STATE.results[index] &&Math.abs(getResultScrollTop()-getVirtualOffset(index)-offset)<2''', arg={'index':index,'offset':offset})229 unmodified linesself.page.wait_for_function('!STATE.isLoading')self.assertEqual(self.page.evaluate('positionPersistence.positions.get(originalWindowKey).index'), 49850)self.page.evaluate("windowCalls=[];STATE.query='paging-original';doSearch(false,false,true)")self.assertTrue(self.page.evaluate("!!positionRestore || resultWindow?.generation === 'two'"),'Returning must validate the invalid window instead of silently restoring generation one')self.wait_anchor(35050)self.assertIn(1, self.page.evaluate('windowCalls'))80 unmodified lines}''')def assert_cached_viewport(self, offset=11):self.page.wait_for_function('positionRestore?.preview && !!window.releaseWindow')self.assertTrue(self.page.evaluate('''offset => {const box=DOM.resultsContainer.getBoundingClientRect();return findVirtualIndex(getResultScrollTop())===49850 &&45 unmodified linesneighbor.check()self.assertEqual(self.page.evaluate('getSelectedFiles().map(file=>file.filename)'),['paging-49850.txt', 'paging-49851.txt'])self.assertTrue(self.page.evaluate('!!positionRestore.preview'))self.page.evaluate('releaseWindow()')self.wait_anchor(49850)self.assertEqual(self.page.evaluate('resultWindow.generation'), 'two')66 unmodified lines!(box.left<count.right && box.right>count.left && box.top<count.bottom && box.bottom>count.top));}'''))self.page.locator('#restart-position-btn').click()self.page.wait_for_function('!positionRestore && !STATE.isLoading && !resultWindow')def test_saved_viewport_is_bounded_and_not_used_for_another_anchor(self):self.persist_viewport()2 unmodified linesself.page.wait_for_function('!STATE.isLoading')self.page.evaluate("resultSnapshots.snapshots.clear();positionPersistence.positions.get(originalWindowKey).anchorId='different';windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")self.page.wait_for_function('!!window.releaseWindow')self.assertFalse(self.page.evaluate('!!positionRestore.preview'))self.page.evaluate('releaseWindow()')self.wait_anchor(49850)51 unmodified lines52535455565758229 unmodified lines28828929029129229329480 unmodified lines37537637737837938038145 unmodified lines42742842943043143243366 unmodified lines5005015025035045055062 unmodified lines50951051151251351451551 unmodified linesself.assertEqual(errors, [])def wait_anchor(self, index, offset=11):self.page.wait_for_function('''({index,offset})=>!positionRestoration.current && !!resultWindow &&findVirtualIndex(getResultScrollTop())===index && !!STATE.results[index] &&Math.abs(getResultScrollTop()-getVirtualOffset(index)-offset)<2''', arg={'index':index,'offset':offset})229 unmodified linesself.page.wait_for_function('!STATE.isLoading')self.assertEqual(self.page.evaluate('positionPersistence.positions.get(originalWindowKey).index'), 49850)self.page.evaluate("windowCalls=[];STATE.query='paging-original';doSearch(false,false,true)")self.assertTrue(self.page.evaluate("!!positionRestoration.current || resultWindow?.generation === 'two'"),'Returning must validate the invalid window instead of silently restoring generation one')self.wait_anchor(35050)self.assertIn(1, self.page.evaluate('windowCalls'))80 unmodified lines}''')def assert_cached_viewport(self, offset=11):self.page.wait_for_function('positionRestoration.current?.preview && !!window.releaseWindow')self.assertTrue(self.page.evaluate('''offset => {const box=DOM.resultsContainer.getBoundingClientRect();return findVirtualIndex(getResultScrollTop())===49850 &&45 unmodified linesneighbor.check()self.assertEqual(self.page.evaluate('getSelectedFiles().map(file=>file.filename)'),['paging-49850.txt', 'paging-49851.txt'])self.assertTrue(self.page.evaluate('!!positionRestoration.current.preview'))self.page.evaluate('releaseWindow()')self.wait_anchor(49850)self.assertEqual(self.page.evaluate('resultWindow.generation'), 'two')66 unmodified lines!(box.left<count.right && box.right>count.left && box.top<count.bottom && box.bottom>count.top));}'''))self.page.locator('#restart-position-btn').click()self.page.wait_for_function('!positionRestoration.current && !STATE.isLoading && !resultWindow')def test_saved_viewport_is_bounded_and_not_used_for_another_anchor(self):self.persist_viewport()2 unmodified linesself.page.wait_for_function('!STATE.isLoading')self.page.evaluate("resultSnapshots.snapshots.clear();positionPersistence.positions.get(originalWindowKey).anchorId='different';windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")self.page.wait_for_function('!!window.releaseWindow')self.assertFalse(self.page.evaluate('!!positionRestoration.current.preview'))self.page.evaluate('releaseWindow()')self.wait_anchor(49850)
51 unmodified lines5253545556575859606156 unmodified lines11811912012112212312429 unmodified lines15415515615715815916028 unmodified lines18919019119219319419551 unmodified linesself.page.evaluate("STATE.query='paging-other';doSearch()")self.page.wait_for_function('!STATE.isLoading')self.page.evaluate("resultSnapshots.snapshots.clear();positionPersistence.viewports.clear();positionPersistence.recentPages.clear();windowCalls=[];windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")self.page.wait_for_function('positionRestore?.preview && !!window.releaseWindow')def wait_cached(self, index):self.page.wait_for_function('''index=>!!positionRestore?.preview && !!STATE.results[index] &&findVirtualIndex(getResultScrollTop())===index &&Math.abs(getResultScrollTop()-getVirtualOffset(index)-11)<2''', arg=index)56 unmodified lines# Hold the demanded page as well, so we check the handoff while the row is still a hole.self.page.evaluate('windowStall=751;releaseWindow()')self.page.wait_for_function('!positionRestore')anchor = self.page.evaluate('''index=>({index:findVirtualIndex(getResultScrollTop()),offset:getResultScrollTop()-getVirtualOffset(index),loaded:!!STATE.results[index],generation:resultWindow.generation})''', index)29 unmodified linesself.assertFalse(self.page.evaluate('!!STATE.results[25050]'),'A corrupt disk record must not enter the preview')self.page.evaluate('windowStall=0;releaseWindow()')self.page.wait_for_function('!positionRestore')self.fixture.jump(25050)self.fixture.wait_anchor(25050)self.assertIn(251, self.page.evaluate('windowCalls'))28 unmodified lines};});''')self.page.reload(wait_until='domcontentloaded')self.page.wait_for_function('positionRestore?.preview && !!window.releaseWindow')for index in [25050,35050,49850,35050,25050]:self.fixture.jump(index)self.wait_cached(index)51 unmodified lines5253545556575859606156 unmodified lines11811912012112212312429 unmodified lines15415515615715815916028 unmodified lines18919019119219319419551 unmodified linesself.page.evaluate("STATE.query='paging-other';doSearch()")self.page.wait_for_function('!STATE.isLoading')self.page.evaluate("resultSnapshots.snapshots.clear();positionPersistence.viewports.clear();positionPersistence.recentPages.clear();windowCalls=[];windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")self.page.wait_for_function('positionRestoration.current?.preview && !!window.releaseWindow')def wait_cached(self, index):self.page.wait_for_function('''index=>!!positionRestoration.current?.preview && !!STATE.results[index] &&findVirtualIndex(getResultScrollTop())===index &&Math.abs(getResultScrollTop()-getVirtualOffset(index)-11)<2''', arg=index)56 unmodified lines# Hold the demanded page as well, so we check the handoff while the row is still a hole.self.page.evaluate('windowStall=751;releaseWindow()')self.page.wait_for_function('!positionRestoration.current')anchor = self.page.evaluate('''index=>({index:findVirtualIndex(getResultScrollTop()),offset:getResultScrollTop()-getVirtualOffset(index),loaded:!!STATE.results[index],generation:resultWindow.generation})''', index)29 unmodified linesself.assertFalse(self.page.evaluate('!!STATE.results[25050]'),'A corrupt disk record must not enter the preview')self.page.evaluate('windowStall=0;releaseWindow()')self.page.wait_for_function('!positionRestoration.current')self.fixture.jump(25050)self.fixture.wait_anchor(25050)self.assertIn(251, self.page.evaluate('windowCalls'))28 unmodified lines};});''')self.page.reload(wait_until='domcontentloaded')self.page.wait_for_function('positionRestoration.current?.preview && !!window.releaseWindow')for index in [25050,35050,49850,35050,25050]:self.fixture.jump(index)self.wait_cached(index)
32 unmodified lines3334353637383938 unmodified lines78798081828384141 unmodified lines22622722822923023123232 unmodified linesself.fixture.tearDown()def assert_position(self):self.page.wait_for_function("!positionRestore && !STATE.isLoading && STATE.query==='paging-original'")self.page.wait_for_function('''saved => {const index=findVirtualIndex(DOM.resultsContainer.scrollTop);return getResultStableId(STATE.results[index])===saved.anchorId &&38 unmodified lines# Accept either position restoration or a fresh search, but never a blank# startup or an unhandled rejection. Surface errors without a long timeout.self.page.wait_for_function('''() => window.viewportReloadErrors?.length ||(STATE.query==='paging-original' && !STATE.isLoading && !positionRestore &&STATE.results.some(record=>record?.File==='paging-125'||record?.File==='paging-0'))''')self.assertEqual(self.page.evaluate('window.viewportReloadErrors'), [])self.assertEqual(self.fixture.errors, [])141 unmodified lines}''')self.page.wait_for_function('!!window.releaseRestore')self.page.evaluate("STATE.query='paging-latest'; doSearch(); releaseRestore()")self.page.wait_for_function("STATE.query==='paging-latest' && !STATE.isLoading && !positionRestore")self.assertEqual(self.page.evaluate('displayedSearchView.key'), self.page.evaluate('getSearchViewKey()'))self.assertEqual(self.page.evaluate('positionPersistence.positions.get(' + repr(self.saved['key']) + ').anchorId'), self.saved['anchorId'])self.assertEqual(self.fixture.errors, [])32 unmodified lines3334353637383938 unmodified lines78798081828384141 unmodified lines22622722822923023123232 unmodified linesself.fixture.tearDown()def assert_position(self):self.page.wait_for_function("!positionRestoration.current && !STATE.isLoading && STATE.query==='paging-original'")self.page.wait_for_function('''saved => {const index=findVirtualIndex(DOM.resultsContainer.scrollTop);return getResultStableId(STATE.results[index])===saved.anchorId &&38 unmodified lines# Accept either position restoration or a fresh search, but never a blank# startup or an unhandled rejection. Surface errors without a long timeout.self.page.wait_for_function('''() => window.viewportReloadErrors?.length ||(STATE.query==='paging-original' && !STATE.isLoading && !positionRestoration.current &&STATE.results.some(record=>record?.File==='paging-125'||record?.File==='paging-0'))''')self.assertEqual(self.page.evaluate('window.viewportReloadErrors'), [])self.assertEqual(self.fixture.errors, [])141 unmodified lines}''')self.page.wait_for_function('!!window.releaseRestore')self.page.evaluate("STATE.query='paging-latest'; doSearch(); releaseRestore()")self.page.wait_for_function("STATE.query==='paging-latest' && !STATE.isLoading && !positionRestoration.current")self.assertEqual(self.page.evaluate('displayedSearchView.key'), self.page.evaluate('getSearchViewKey()'))self.assertEqual(self.page.evaluate('positionPersistence.positions.get(' + repr(self.saved['key']) + ').anchorId'), self.saved['anchorId'])self.assertEqual(self.fixture.errors, [])
111 unmodified lines112113114115116117118111 unmodified linesconst window = {key: 'query', total: 1000, query: {pageSize: 1}, controller: new AbortController(), pages: new Set(), failures: new Map()};let error = new Error('temporary'), renders = 0, statuses = 0;const cache = new Map([['old-page', {}]]), stale = new Map([['query', {}]]);const c = fixture(['loadResultWindowPage'], {resultWindow: window, positionRestore: null,searchResponseStore: {cache}, resultSnapshots: {remove: key => stale.delete(key)}, STATE: {_pageCache: {1:[{}]} },resultWindowCurrent: () => true, requestResultWindowPage: async () => {throw error;},updateResultWindowStatus() {statuses++;}, scheduleVirtualRender() {renders++;},111 unmodified lines112113114115116117118111 unmodified linesconst window = {key: 'query', total: 1000, query: {pageSize: 1}, controller: new AbortController(), pages: new Set(), failures: new Map()};let error = new Error('temporary'), renders = 0, statuses = 0;const cache = new Map([['old-page', {}]]), stale = new Map([['query', {}]]);const c = fixture(['loadResultWindowPage'], {resultWindow: window, positionRestoration: {current: null},searchResponseStore: {cache}, resultSnapshots: {remove: key => stale.delete(key)}, STATE: {_pageCache: {1:[{}]} },resultWindowCurrent: () => true, requestResultWindowPage: async () => {throw error;},updateResultWindowStatus() {statuses++;}, scheduleVirtualRender() {renders++;},
33 unmodified lines34353637383940110 unmodified lines15115215315415515615715815916016116216316416516616716816917017117217317417517633 unmodified linessetSidebarExpanded(value){dom.leftSidebar.classList.toggle('expanded-wide',value);},getSearchViewKey:()=>JSON.stringify([state.mode,state.repo,state.query,state.filterExtensions,state.filterFolderSelfs,state.filterFolderSubtrees]),saveSearchViewSnapshot:()=>events.push(['snapshot',state.query]),prepareRouteTransitionResults(){},searchInputController:{invalidateVisit:()=>events.push(['intent'])},cancelPendingSearchControls:()=>events.push(['controls']),readerReturnPosition:{invalidate:()=>events.push(['reader'])},cancelActiveSearch:()=>{events.push(['cancel']);return true;},cancelPositionRestore:()=>events.push(['position']),renderBrowser:(path,id)=>events.push(['browser',path,id]),retainFilterRenderingForRoute:id=>events.push(['retain',id]),searchWithInitialFallback:()=>events.push(['search']),110 unmodified linesif (source === current) {test('size controls preserve the exact restored minimum when editing only the maximum', () => {const f = fixture('Test?min_size=1500B&max_size=1MB');vm.runInContext(fs.readFileSync('static/search/results/presentation/size-format.js', 'utf8'), f.c);let pending;Object.assign(f.c, {sizeFilterTimer: null, setTimeout(fn) { pending = fn; return 1; }, clearTimeout() {},doFilterSearch: () => f.c.syncStateToURL(),});for (const field of ['filterMinSize', 'filterMaxSize', 'filterMinUnit', 'filterMaxUnit']) {f.dom[field].addEventListener = (type, fn) => { f.dom[field][type] = fn; };}for (const name of ['sizeInputToBytes', 'applyPendingSizeFilters', 'setupSizeFilterControls']) {const match = source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));assert.ok(match, name); vm.runInContext(match[0], f.c);}f.c.router.apply();assert.equal(f.state.filterMinSize, 1500);assert.deepEqual([f.dom.filterMinSize.value, f.dom.filterMinUnit.value], ['1500', 'B']);assert.deepEqual([f.dom.filterMaxSize.value, f.dom.filterMaxUnit.value], ['1', 'MB']);f.c.setupSizeFilterControls();f.dom.filterMaxSize.value = '2'; f.dom.filterMaxSize.input(); pending();assert.deepEqual([f.state.filterMinSize, f.state.filterMaxSize], [1500, 2097152]);const params = new URLSearchParams(pages ? f.location.hash.split('?')[1] : f.location.search);assert.equal(f.c.parseSizeStr(params.get('min_size')), 1500);33 unmodified lines3435363738394041110 unmodified lines15215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519633 unmodified linessetSidebarExpanded(value){dom.leftSidebar.classList.toggle('expanded-wide',value);},getSearchViewKey:()=>JSON.stringify([state.mode,state.repo,state.query,state.filterExtensions,state.filterFolderSelfs,state.filterFolderSubtrees]),saveSearchViewSnapshot:()=>events.push(['snapshot',state.query]),prepareRouteTransitionResults(){},searchInputController:{invalidateVisit:()=>events.push(['intent']), cancelPending:()=>events.push(['controls']), syncSize(){}},cancelPendingSearchControls:()=>events.push(['controls']), // pre-extraction baselinereaderReturnPosition:{invalidate:()=>events.push(['reader'])},cancelActiveSearch:()=>{events.push(['cancel']);return true;},cancelPositionRestore:()=>events.push(['position']),renderBrowser:(path,id)=>events.push(['browser',path,id]),retainFilterRenderingForRoute:id=>events.push(['retain',id]),searchWithInitialFallback:()=>events.push(['search']),110 unmodified linesif (source === current) {test('size controls preserve the exact restored minimum when editing only the maximum', () => {const f = fixture('Test?ext=txt&min_size=1500B&max_size=1MB');vm.runInContext(fs.readFileSync('static/search/results/presentation/size-format.js', 'utf8'), f.c);for (const path of ['domain/ownership.js', 'application/controller.js'])vm.runInContext(fs.readFileSync('static/search/input/' + path, 'utf8'), f.c);const timers = new Map();let next = 0, controlState, filterRuns = 0;for (const name of ['searchInput', 'filterMinSize', 'filterMaxSize', 'filterMinUnit', 'filterMaxUnit'])f.dom[name] = Object.assign(new EventTarget(), {value: ''});const controller = f.c.VoiceOfMLSearchInput.create({input: f.dom.searchInput, navigation: new EventTarget(),ownership: f.c.VoiceOfMLSearchInputOwnership,clock: {setTimeout(fn, ms) {timers.set(++next, {fn, ms}); return next;}, clearTimeout(id) {timers.delete(id);}},canSubmit: () => !f.c.readerHost.overlay, onState: state => {controlState = state;},filterSearch: () => {filterRuns++; f.c.syncStateToURL();},size: {min: f.dom.filterMinSize, max: f.dom.filterMaxSize, minUnit: f.dom.filterMinUnit, maxUnit: f.dom.filterMaxUnit,read: () => [f.state.filterMinSize, f.state.filterMaxSize], format: f.c.bytesToDisplay,commit: (min, max) => {f.state.filterMinSize = min; f.state.filterMaxSize = max;}}});f.c.searchInputController = controller;controller.mount();f.c.router.apply();assert.equal(f.state.filterMinSize, 1500);assert.deepEqual([f.dom.filterMinSize.value, f.dom.filterMinUnit.value], ['1500', 'B']);assert.deepEqual([f.dom.filterMaxSize.value, f.dom.filterMaxUnit.value], ['1', 'MB']);f.dom.filterMaxSize.value = '2'; f.dom.filterMaxSize.dispatchEvent(new Event('input'));const pendingSize = controlState.sizeTimer;controller.scheduleFilter();const pendingFilter = controlState.filterTimer;f.c.router.apply(true);assert.equal(f.dom.filterMaxSize.value, '2');assert.equal(controlState.sizeTimer, pendingSize);assert.equal(controlState.filterTimer, pendingFilter);assert.equal(timers.get(pendingSize).ms, 500);assert.equal(timers.get(pendingFilter).ms, 200);f.c.readerHost.overlay = {};timers.get(pendingFilter).fn();assert.equal(controlState.filterTimer, null);assert.equal(filterRuns, 1, 'Reader blocks query input but not a committed filter search');f.c.readerHost.overlay = null;timers.get(pendingSize).fn();assert.deepEqual([f.state.filterMinSize, f.state.filterMaxSize], [1500, 2097152]);const params = new URLSearchParams(pages ? f.location.hash.split('?')[1] : f.location.search);assert.equal(f.c.parseSizeStr(params.get('min_size')), 1500);
101 unmodified lines1021031041051061071 unmodified line10911011111211311411511611711811984 unmodified lines2042052062072082092102112122132142152162172182192202212222232242253 unmodified lines229230231232233234235236237238239240186 unmodified lines42742842943043143243332 unmodified lines46646746846947047147247347417 unmodified lines492493494495496497498499500501502503101 unmodified linesassert.equal(f.timers.size,0);assert.equal(entry.listeners.size,0);});function inputFixture({submit = () => {}, schedule = () => {}, early} = {}) {const context = vm.createContext({});for (const file of ['domain/ownership.js', 'application/controller.js'])1 unmodified lineconst input = new EventTarget(), navigation = new EventTarget(), callbacks = new Map(), cancelled = [];input.value = 'old draft';if (early) input._earlySearchInput = early;const c = {input, navigation, callbacks, cancelled, href: 'https://example.test/A', entry: 'entry-A', key: 'A', syncs: 0};let next = 0;c.controller = context.VoiceOfMLSearchInput.create({input, navigation,ownership: context.VoiceOfMLSearchInputOwnership,clock: {setTimeout(fn, delay) { assert.equal(delay, 100); callbacks.set(++next, fn); schedule(); return next; },clearTimeout(id) { cancelled.push(id); }},getHref: () => c.href, getEntryKey: () => c.entry, getViewKey: () => c.key,syncInput: () => c.syncs++, canSubmit: () => !c.readerOpen, submit, onState: state => {84 unmodified linesassert.equal(group.signal.aborted, false);});test('position abort reentry retains the replacement window and restoration', () => {const old = new AbortController(), newer = {controller: new AbortController()};const c = fixture(['cancelPositionRestore'], {positionEntryId: 0,resultWindow: {controller: old}, positionRestore: {controller: new AbortController()},STATE: {isLoading: true}, cancelSnapshotClone() {}, updateResultWindowStatus() {}, showPositionRestoreStatus() {}});old.signal.addEventListener('abort', () => { c.resultWindow = newer; c.positionRestore = newer; });c.cancelPositionRestore();assert.equal(c.resultWindow, newer);assert.equal(c.positionRestore, newer);assert.equal(newer.controller.signal.aborted, false);});test('filter change incorporates the pending completed query before cancelling debounce', () => {const c = fixture(['prepareFilterChange'], {searchTimer: 1, searchComposing: false,DOM: {searchInput: {value: ' current draft '}}, STATE: {query: 'old', page: 3, results: [1]},applyPendingSizeFilters() {}, cancelPendingSearchControls() { c.searchTimer = null; },saveSearchViewSnapshot() { assert.equal(c.STATE.query, 'old'); }});c.prepareFilterChange(true);assert.equal(c.STATE.query, 'current draft');3 unmodified linestest('filter change preserves composing and overlong drafts without submitting them', () => {for (const [composing, value] of [[true, 'composition'], [false, 'x'.repeat(257)]]) {const c = fixture(['prepareFilterChange'], {searchTimer: 1, searchComposing: composing,DOM: {searchInput: {value}}, STATE: {query: 'old'}, applyPendingSizeFilters() {},cancelPendingSearchControls() {}, saveSearchViewSnapshot() {}});c.prepareFilterChange(false);assert.equal(c.STATE.query, 'old');assert.equal(c.DOM.searchInput.value, value);}});186 unmodified linesconst queries = [], snapshots = [];const c = inputFixture({submit: query => queries.push(query)});c.onState = state => {assert.deepEqual(Object.keys(state).sort(), ['composing', 'dirty', 'ready', 'timer']);snapshots.push(state);};c.controller.captureDraft();32 unmodified lineslet callback;navigation.setTimeout = fn => { callback = fn; return 42; };navigation.clearTimeout = () => {};const c = fixture(['setupSearchInput', 'initialSearchDraftIsCurrent', 'finishInitialSearchInput', 'cancelPendingSearchControls'], {VoiceOfMLSearchInput: modules.VoiceOfMLSearchInput, VoiceOfMLSearchInputOwnership: modules.VoiceOfMLSearchInputOwnership,DOM: {searchInput: input}, window: navigation, location: new URL('https://example.test/A'),readerHost: {overlay:null}, appliedSearchRoute: '/A',routeInitialized: true, getSearchViewKey: () => 'A', syncSearchInputState() {}, clearTimeout() {},filterSearchTimer: null, sizeFilterTimer: null,17 unmodified linesassert.equal(c.searchComposing, true);input.dispatchEvent(new Event('compositionend'));assert.equal(c.searchComposing, false);c.cancelPendingSearchControls();callback();assert.equal(c.searchTimer, null);assert.equal(queries.length, 1);});test('input dependency order, source shell, build resources and SW agree without delaying inline capture', async () => {const precache = await installSourcePrecachePaths('/static/');const paths = ['search/input/domain/ownership.js', 'search/input/application/controller.js'];101 unmodified lines1021031041051061071081091 unmodified line11111211311411511611711811912012112212312412512684 unmodified lines2112122132142152162172182192202212222233 unmodified lines227228229230231232233234235236237238239240241242186 unmodified lines42943043143243343443532 unmodified lines46846947047147247347447547647747817 unmodified lines496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533101 unmodified linesassert.equal(f.timers.size,0);assert.equal(entry.listeners.size,0);});const sizeControl = value => Object.assign(new EventTarget(), {value});function inputFixture({submit = () => {}, schedule = () => {}, early} = {}) {const context = vm.createContext({});for (const file of ['domain/ownership.js', 'application/controller.js'])1 unmodified lineconst input = new EventTarget(), navigation = new EventTarget(), callbacks = new Map(), cancelled = [];input.value = 'old draft';if (early) input._earlySearchInput = early;const c = {input, navigation, callbacks, cancelled, href: 'https://example.test/A', entry: 'entry-A', key: 'A', syncs: 0,deadlines: new Map(), bounds: [null, null], filterSearches: []};c.size = {min: sizeControl(''), max: sizeControl(''), minUnit: sizeControl('MB'), maxUnit: sizeControl('MB'),read: () => c.bounds, commit: (...bounds) => { c.bounds = bounds; },format: bytes => ({value: bytes === null ? '' : String(bytes), unit: bytes === null ? 'MB' : 'B'})};let next = 0;c.controller = context.VoiceOfMLSearchInput.create({input, navigation, size: c.size,ownership: context.VoiceOfMLSearchInputOwnership,filterSearch: clear => c.filterSearches.push(clear),clock: {setTimeout(fn, delay) { callbacks.set(++next, fn); c.deadlines.set(next, delay); schedule(); return next; },clearTimeout(id) { cancelled.push(id); }},getHref: () => c.href, getEntryKey: () => c.entry, getViewKey: () => c.key,syncInput: () => c.syncs++, canSubmit: () => !c.readerOpen, submit, onState: state => {84 unmodified linesassert.equal(group.signal.aborted, false);});test('filter change incorporates the pending completed query before cancelling debounce', () => {const i = inputFixture();i.controller.finishStartup(true);i.input.value = ' current draft ';i.emit('input');const c = fixture(['prepareFilterChange'], {searchInputController: i.controller,STATE: {query: 'old', page: 3, results: [1]},saveSearchViewSnapshot() { assert.equal(c.STATE.query, 'old'); }});c.prepareFilterChange(true);assert.equal(c.STATE.query, 'current draft');3 unmodified linestest('filter change preserves composing and overlong drafts without submitting them', () => {for (const [composing, value] of [[true, 'composition'], [false, 'x'.repeat(257)]]) {const i = inputFixture();i.controller.finishStartup(true);if (composing) i.emit('compositionstart');i.input.value = value;i.emit('input');const c = fixture(['prepareFilterChange'], {searchInputController: i.controller,STATE: {query: 'old'}, saveSearchViewSnapshot() {}});c.prepareFilterChange(false);assert.equal(c.STATE.query, 'old');assert.equal(i.input.value, value);}});186 unmodified linesconst queries = [], snapshots = [];const c = inputFixture({submit: query => queries.push(query)});c.onState = state => {assert.deepEqual(Object.keys(state).sort(), ['composing', 'dirty', 'filterTimer', 'ready', 'sizeTimer', 'timer']);snapshots.push(state);};c.controller.captureDraft();32 unmodified lineslet callback;navigation.setTimeout = fn => { callback = fn; return 42; };navigation.clearTimeout = () => {};const c = fixture(['setupSearchInput', 'initialSearchDraftIsCurrent', 'finishInitialSearchInput'], {VoiceOfMLSearchInput: modules.VoiceOfMLSearchInput, VoiceOfMLSearchInputOwnership: modules.VoiceOfMLSearchInputOwnership,DOM: {searchInput: input, filterMinSize: sizeControl(''), filterMaxSize: sizeControl(''),filterMinUnit: sizeControl('MB'), filterMaxUnit: sizeControl('MB')},window: navigation, location: new URL('https://example.test/A'), bytesToDisplay() {},readerHost: {overlay:null}, appliedSearchRoute: '/A',routeInitialized: true, getSearchViewKey: () => 'A', syncSearchInputState() {}, clearTimeout() {},filterSearchTimer: null, sizeFilterTimer: null,17 unmodified linesassert.equal(c.searchComposing, true);input.dispatchEvent(new Event('compositionend'));assert.equal(c.searchComposing, false);c.searchInputController.cancelPending();callback();assert.equal(c.searchTimer, null);assert.equal(queries.length, 1);});test('restore retires both filter slots without rescheduling the query or consuming a discarded bound', () => {const queries = [], c = inputFixture({submit: query => queries.push(query)});c.controller.finishStartup(true);c.emit('input');c.controller.scheduleFilter();c.size.min.value = '7';c.size.min.dispatchEvent(new Event('input'));const {timer, filterTimer, sizeTimer} = c.state;assert.deepEqual([timer, filterTimer, sizeTimer].map(id => c.deadlines.get(id)), [100, 200, 500]);c.controller.cancelPending(true);assert.deepEqual([c.state.timer, c.state.filterTimer, c.state.sizeTimer], [timer, null, null]);assert.equal(c.size.min.value, '');c.size.max.value = '2';c.size.max.dispatchEvent(new Event('input'));const replacement = c.state.sizeTimer;c.callbacks.get(filterTimer)();c.callbacks.get(sizeTimer)();assert.equal(c.state.sizeTimer, replacement);assert.deepEqual(c.filterSearches, []);c.callbacks.get(timer)();assert.deepEqual(queries, ['old draft']);c.callbacks.get(replacement)();assert.deepEqual(c.bounds, [null, 2097152]);assert.deepEqual(c.filterSearches, [true]);});test('input dependency order, source shell, build resources and SW agree without delaying inline capture', async () => {const precache = await installSourcePrecachePaths('/static/');const paths = ['search/input/domain/ownership.js', 'search/input/application/controller.js'];
5 unmodified lines6789101112131415162 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525354552 unmodified lines585960616263647 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031 unmodified line1051061071081091101111121131141151161171181191201211221231241251261271281 unmodified line1301311321331341351361371381391401411421431441456 unmodified lines1521531541551561571581591601611621631641651 unmodified line1671681691701711721731741 unmodified line1761771781791801811823 unmodified lines1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182195 unmodified linesconst source = fs.readFileSync('static/app.js', 'utf8');const key = JSON.stringify({pageSize: 2});const position = {version: 1, key, index: 4, offset: 7, anchorId: 'r4', loadedPage: 3, savedAt: 1};const page = (number, generation = 'A', total = 12) => ({page: number, page_size: 2, total, generation,results: Array.from({length: Math.min(2, Math.max(0, total - (number - 1) * 2))}, (_, i) => ({id: 'r' + ((number - 1) * 2 + i)}))});const deferred = () => {let resolve, reject; const promise = new Promise((yes, no) => {resolve = yes; reject = no;}); return {promise, resolve, reject};};const flush = async () => {for (let i = 0; i < 16; i++) await Promise.resolve();};// Run the real host composition as well as the coordinator. All geometry stays// behind the same ports as production; tests can replace the live page hook.2 unmodified linesconst c = vm.createContext({AbortController, TextEncoder: class extends TextEncoder {encode(value) {encoded.push(value); return super.encode(value);}}, setTimeout(fn, ms) {assert.equal(ms, 30); timers.push(fn);},positionRestore: null, positionEntryId: 0, resultWindow: null, searchIntentId: 0, searchId: 0,STATE: {isLoading: false, results: []}, VSCROLL: {isDraggingThumb: false, estimatedHeight: 40},readerHost: {overlay: null}, getSearchViewKey: () => key,positionPersistence: {getPosition: () => position}, validSearchPosition: () => true,cancelPendingSearchControls() {events.push('controls');}, cancelActiveSearch() {events.push('active'); return true;},cancelSnapshotClone() {events.push('clone');}, updateResultWindowStatus() {events.push('window');},setReturnPositionTarget() {events.push('target');}, resetPagingRecovery() {events.push('paging');},showPositionRestoreStatus(message, retry) {events.push(['status', message, retry]);},readSearchViewport: async () => null,fetchPositionPageWithRecovery: async (query, number, signal, anchorId) => {calls.push({query, number, signal, anchorId}); return {...page(number), ...(anchorId ? {anchor_index: 4} : {})};},showSavedSearchViewport(viewport, saved, task) {events.push('preview'); if (viewport) task.preview = true;},captureReaderReturnScroll: () => ({index: 4, offset: 7}), getResultStableId: record => record?.id || '',applyValidatedSearchViewport(snapshot) {events.push('apply'); c.snapshot = snapshot; c.STATE.isLoading = false;},restoreSearchViewSnapshot(k) {events.push('restore'); c.snapshot = store.snapshots.get(k); c.STATE.isLoading = false;},resetPositionControlScroll() {events.push('reset-controls');}, showToast(message) {events.push(['toast', message]);}});installClassicSearchModules(process.cwd(), c);const store = c.VoiceOfMLResultSnapshots.create({});c.resultSnapshots = {putRestored(k, snapshot) {store.putRestored(k, snapshot); events.push('put');},trim() {store.trim(); events.push('trim');}};c.validatePositionWindowPage = (...args) => c.VoiceOfMLSearchWindowPage.validate(...args);vm.runInContext(source.match(/^const positionRestoration = VoiceOfMLPositionRestoration.create\(\{[^]*?^\}\);/m)[0], c);for (const name of ['tryRestoreSearchPosition', 'cancelPositionRestore'])vm.runInContext(source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'))[0], c);const make = (previous, saved = position) => c.VoiceOfMLPositionRestoration.createTask({key, position: saved, previous});const run = (task, viewport = null) => {c.positionRestore = task; return vm.runInContext('positionRestoration', c).run(task, viewport);};return {c, calls, events, encoded, timers, make, run};}test('authoritative restore trims the exact sparse budget without serializing the holes', async () => {2 unmodified linestotal: 50_000, generation: '版本', anchor_index: ${index}, results: [0, 1].map(offset => ({id: 'r' + ((page - 1) * 2 + offset), File: '书📚', Folder: ['路径']}))})`, f.c);await f.run(f.make(null, {...position, index, anchorId: 'r' + index, loadedPage: 25_000}));const {bytes, ...envelope} = f.c.snapshot;assert.equal(bytes, new TextEncoder().encode(JSON.stringify(envelope)).length + 256);assert.equal(envelope.results.length, 50_000);7 unmodified linestest('restoration retries retain lookup and partial-neighbor buffer identity without duplicate rendering', async () => {const f = fixture(), original = f.c.fetchPositionPageWithRecovery;f.c.fetchPositionPageWithRecovery = (...args) => args[1] === 3 ? Promise.reject(new Error('offline')) : original(...args);const first = f.make(); await f.run(first);assert.equal(first.failed, true); assert.deepEqual([...first.ready.keys()], [1, 2, 4]);assert.equal(f.c.snapshot, undefined); assert.equal(f.events.includes('restore'), false);const retry = f.make(first);assert.equal(retry.ready, first.ready); assert.equal(retry.lookup, first.lookup);f.calls.length = 0; f.c.fetchPositionPageWithRecovery = original;await f.run(retry);assert.deepEqual(f.calls.map(call => call.number), [3]);assert.equal(f.c.snapshot.scroll.index, 4); assert.equal(f.c.snapshot.scroll.offset, 7);assert.equal(f.events.filter(event => event === 'restore').length, 1);assert.equal(f.events.includes('apply'), false); assert.equal(f.c.positionRestore, null);});test('generation mismatch clears the shared retry buffer and restarts lookup through the live validation hook', async () => {const f = fixture(), original = f.c.fetchPositionPageWithRecovery;const first = f.make(); first.ready.set(2, page(2));const buffer = first.ready;f.c.fetchPositionPageWithRecovery = (...args) => args[1] === 3 ? Promise.resolve(page(3, 'B')) : original(...args);let validations = 0;f.c.validatePositionWindowPage = (...args) => {validations++; f.c.VoiceOfMLSearchWindowPage.validate(...args);};await f.run(first);assert.ok(validations >= 2); assert.equal(first.error.message, 'RESTORE_PAGE_CHANGED');assert.equal(first.ready, buffer); assert.equal(buffer.size, 0); assert.equal(first.lookup, null); assert.equal(f.c.snapshot, undefined);f.calls.length = 0; f.c.fetchPositionPageWithRecovery = original;const retry = f.make(first); assert.equal(retry.ready, buffer);await f.run(retry); assert.deepEqual(f.calls.map(call => call.number), [1, 2, 3, 4]);});test('stale viewport, lookup and neighbor completions cannot publish or mark a newer task failed', async () => {1 unmodified lineconst f = fixture(), gate = deferred(), original = f.c.fetchPositionPageWithRecovery;if (stage === 'viewport') f.c.readSearchViewport = () => gate.promise;else f.c.fetchPositionPageWithRecovery = (...args) => (stage === 'lookup' ? args[1] === 1 : args[1] === 3) ? gate.promise : original(...args);const first = f.make(); f.c.positionRestore = first;const running = vm.runInContext('positionRestoration', f.c).run(first, stage === 'viewport' ? undefined : null);await flush(); const newer = f.make(); f.c.positionRestore = newer; f.c.STATE.isLoading = true;if (rejection) gate.reject(new Error('late')); else gate.resolve(stage === 'viewport' ? null : page(stage === 'lookup' ? 1 : 3));await running;assert.equal(f.c.positionRestore, newer); assert.equal(f.c.STATE.isLoading, true);assert.equal(first.failed, undefined); assert.equal(newer.failed, undefined); assert.equal(f.c.snapshot, undefined);}});test('preview waits for drag release, accepts only matching cached pages and applies once', async () => {const f = fixture(), task = f.make();f.c.STATE.results[4] = {id: 'r4'}; f.c.VSCROLL.isDraggingThumb = true;f.c.captureReaderReturnScroll = () => ({index: 4, offset: 19});task.cachedPages = new Map([[5, page(5)], [6, page(6, 'old')]]);const running = f.run(task, {}); await flush();assert.equal(f.timers.length, 1); assert.equal(f.c.snapshot, undefined);f.c.VSCROLL.isDraggingThumb = false; f.timers.shift()(); await running;assert.equal(task.ready.has(5), true); assert.equal(task.ready.has(6), false);assert.equal(f.c.snapshot.scroll.offset, 19); assert.equal(f.c.snapshot.results[8].id, 'r8');assert.equal(f.events.filter(event => event === 'apply').length, 1);1 unmodified line});test('abort during drag wait leaves the task and snapshot untouched', async () => {const f = fixture(), task = f.make(); f.c.VSCROLL.isDraggingThumb = true;const running = f.run(task, {}); await flush(); task.controller.abort(); f.timers.shift()(); await running;assert.equal(f.c.snapshot, undefined); assert.equal(task.failed, undefined); assert.equal(f.c.positionRestore, task);});test('moving preview anchor outside ready pages restarts lookup without replacing the shared map', async () => {const f = fixture(), task = f.make(), buffer = task.ready, original = f.c.fetchPositionPageWithRecovery;f.c.STATE.results[10] = {id: 'r10'}; f.c.captureReaderReturnScroll = () => ({index: 10, offset: 23});f.c.fetchPositionPageWithRecovery = async (...args) => ({...await original(...args), ...(args[3] ? {anchor_index: args[3] === 'r10' ? 10 : 4} : {})});await f.run(task, {});assert.equal(task.ready, buffer); assert.deepEqual(f.calls.filter(call => call.anchorId).map(call => call.anchorId), ['r4', 'r10']);assert.deepEqual([...buffer.keys()], [1, 5, 6]); assert.equal(f.c.snapshot.scroll.index, 10);assert.equal(f.c.snapshot.scroll.offset, 23); assert.equal(task.position.anchorId, 'r10');6 unmodified linesf.c.captureReaderReturnScroll = () => ({index:10, offset:23});let fail = true;f.c.fetchPositionPageWithRecovery = async (...args) => {if (fail && args[1] === 6) throw new Error('temporarily unavailable');return {...await original(...args), ...(args[3] === 'r10' ? {anchor_index:10} : {})};};const first = f.make(); await f.run(first, {});assert.ok(first.failed); assert.equal(first.position.anchorId, 'r10');fail = false; f.calls.length = 0;const retry = f.make(first, first.position);await f.run(retry, {});assert.deepEqual(f.calls.map(call => call.number), [6]);assert.equal(f.c.snapshot.scroll.index, 10); assert.equal(f.c.snapshot.scroll.offset, 23);});1 unmodified linetest('Reader overlay retains the saved anchor and missing anchor uses the nearby snapshot path', async () => {const f = fixture(); f.c.readerHost.overlay = {};f.c.captureReaderReturnScroll = () => {throw new Error('Reader must retain the saved anchor');};await f.run(f.make(), {}); assert.equal(f.c.snapshot.scroll.index, 4); assert.equal(f.events.includes('apply'), true);const missing = fixture(); await missing.run(missing.make(null, {...position, anchorId: 'gone'}), {});assert.equal(missing.c.snapshot.scroll.index, 4); assert.equal(missing.events.includes('restore'), true);assert.equal(missing.events.includes('apply'), false); assert.equal(missing.events.filter(event => event[0] === 'toast').length, 1);});1 unmodified linetest('preview keeps a user-moved hole instead of a vanished saved anchor', async () => {const f = fixture();f.c.captureReaderReturnScroll = () => ({index: 11, offset: 17});await f.run(f.make(null, {...position, anchorId: 'gone'}), {});assert.equal(f.c.snapshot.scroll.index, 11);assert.equal(f.c.snapshot.scroll.offset, 17);assert.equal(f.events.includes('apply'), true);3 unmodified linestest('synchronous prologue retains ordering, duplicate handling and abort reentry ownership', () => {const f = fixture();const active = f.make(); f.c.positionRestore = active;assert.equal(f.c.tryRestoreSearchPosition(key), true); assert.deepEqual(f.events, []);assert.equal(f.c.searchIntentId, 1);f.events.length = 0;const newer = f.make();active.controller.signal.addEventListener('abort', () => {f.c.searchId++; f.c.positionRestore = newer; f.c.STATE.isLoading = true;});assert.equal(f.c.tryRestoreSearchPosition(key, {position}), false);assert.deepEqual(f.events.slice(0, 3), ['active', 'clone', 'window']);assert.equal(f.c.positionEntryId, 1); assert.equal(f.c.positionRestore, newer);assert.equal(f.c.STATE.isLoading, true); assert.equal(f.events.includes('target'), false);});test('active-search abort reentry exits before restoration cancellation', () => {const f = fixture(), active = f.make(); f.c.positionRestore = active;f.c.cancelActiveSearch = () => false;assert.equal(f.c.tryRestoreSearchPosition(key, {position}), false);assert.equal(f.c.positionEntryId, 0); assert.equal(active.controller.signal.aborted, false);});test('site-specific backend pin and completion reset remain unchanged', async () => {const f = fixture(); const pages = source.includes('backend: options.backend');const task = f.c.VoiceOfMLPositionRestoration.createTask({key, position, backend: 'local'});await f.run(task);assert.equal(f.calls[0].query.resultBackend, pages ? 'local' : undefined);assert.equal(Object.hasOwn(f.c.snapshot, 'resultBackend'), pages);assert.equal(f.c.snapshot.resultBackend, pages ? 'local' : undefined);assert.equal(f.events.includes('reset-controls'), !pages);const previous = f.c.VoiceOfMLPositionRestoration.createTask({key, position, backend: 'api'});const retry = f.c.VoiceOfMLPositionRestoration.createTask({key, position, previous});assert.equal(retry.backend, pages ? 'api' : undefined);});5 unmodified lines67891011121314151617182 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869702 unmodified lines737475767778797 unmodified lines878889909192939495969798991001011021031041051061071081091101111121131141151161171 unmodified line1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481 unmodified line1501511521531541551561571581591601611621631641656 unmodified lines1721731741751761771781791801811821831841851 unmodified line1871881891901911921931941951961 unmodified line1981992002012022032042053 unmodified lines2092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782795 unmodified linesconst source = fs.readFileSync('static/app.js', 'utf8');const key = JSON.stringify({pageSize: 2});const position = {version: 1, key, index: 4, offset: 7, anchorId: 'r4', loadedPage: 3, savedAt: Date.now()};const preview = (saved = position) => ({key, savedAt: Date.now(), total: 12, generation: 'A',estimatedHeight: 40, measurementKey: 'layout', records: [[saved.index, {File: 'saved', id: saved.anchorId}, 40]]});const page = (number, generation = 'A', total = 12) => ({page: number, page_size: 2, total, generation,results: Array.from({length: Math.min(2, Math.max(0, total - (number - 1) * 2))}, (_, i) => ({id: 'r' + ((number - 1) * 2 + i)}))});const deferred = () => {let resolve, reject; const promise = new Promise((yes, no) => {resolve = yes; reject = no;}); return {promise, resolve, reject};};const flush = () => new Promise(resolve => setImmediate(resolve));// Run the real host composition as well as the coordinator. All geometry stays// behind the same ports as production; tests can replace the live page hook.2 unmodified linesconst c = vm.createContext({AbortController, TextEncoder: class extends TextEncoder {encode(value) {encoded.push(value); return super.encode(value);}}, setTimeout(fn, ms) {assert.equal(ms, 30); timers.push(fn);},resultWindow: null, searchIntentId: 0, searchId: 0,STATE: {isLoading: false, results: []}, VSCROLL: {isDraggingThumb: false, estimatedHeight: 40},readerHost: {overlay: null}, getSearchViewKey: () => key,positionPersistence: {getPosition: () => position},cancelActiveSearch() {events.push('active'); c.searchId++; return true;},updateResultWindowStatus() {events.push('window');},setReturnPositionTarget() {events.push('target');}, resetPagingRecovery() {events.push('paging');},showPositionRestoreStatus(message, retry) {events.push(['status', message, retry]);},readSearchViewport: async () => null,fetchPositionPageWithRecovery: async (query, number, signal, anchorId) => {calls.push({query, number, signal, anchorId}); return {...page(number), ...(anchorId ? {anchor_index: 4} : {})};},captureReaderReturnScroll: () => ({index: 4, offset: 7}), getResultStableId: record => record?.id || '',applyValidatedSearchViewport(snapshot) {events.push('apply'); c.snapshot = snapshot; c.STATE.isLoading = false;},restoreSearchViewSnapshot(k, scroll, options) {assert.equal(scroll, true);if (options.preserveRestore) {assert.equal(restoration.current.preview, true);events.push('preview'); c.preview = store.snapshots.get(k);} else {assert.equal(restoration.current, null);assert.equal(options.preserveQueryDraft, true);events.push('restore'); c.snapshot = store.snapshots.get(k);}c.STATE.isLoading = false;},resetPositionControlScroll() {events.push('reset-controls');}, showToast(message) {events.push(['toast', message]);}});installClassicSearchModules(process.cwd(), c);const store = c.VoiceOfMLResultSnapshots.create({});c.resultSnapshots = {...store,cancelClone() {store.cancelClone(); events.push('clone');},putRestored(k, snapshot) {store.putRestored(k, snapshot); events.push('put');},trim() {store.trim(); events.push('trim');}};c.validatePositionWindowPage = (...args) => c.VoiceOfMLSearchWindowPage.validate(...args);vm.runInContext(source.match(/^const positionRestoration = VoiceOfMLPositionRestoration.create\(\{[^]*?^\}\);/m)[0], c);const restoration = vm.runInContext('positionRestoration', c);vm.runInContext(source.match(/^const \{ cancel: cancelPositionRestore, start: tryRestoreSearchPosition \} = positionRestoration;$/m)[0], c);const start = (options = {viewport: null}) => {assert.equal(restoration.start(key, options), true);return restoration.current;};return {c, calls, events, encoded, timers, restoration, start, store};}test('authoritative restore trims the exact sparse budget without serializing the holes', async () => {2 unmodified linestotal: 50_000, generation: '版本', anchor_index: ${index}, results: [0, 1].map(offset => ({id: 'r' + ((page - 1) * 2 + offset), File: '书📚', Folder: ['路径']}))})`, f.c);f.start({viewport: null, position: {...position, index, anchorId: 'r' + index, loadedPage: 25_000}}); await flush();const {bytes, ...envelope} = f.c.snapshot;assert.equal(bytes, new TextEncoder().encode(JSON.stringify(envelope)).length + 256);assert.equal(envelope.results.length, 50_000);7 unmodified linestest('restoration retries retain lookup and partial-neighbor buffer identity without duplicate rendering', async () => {const f = fixture(), original = f.c.fetchPositionPageWithRecovery;f.c.fetchPositionPageWithRecovery = (...args) => args[1] === 3 ? Promise.reject(new Error('offline')) : original(...args);const first = f.start(); await flush();assert.equal(first.failed, true); assert.deepEqual([...first.ready.keys()], [1, 2, 4]);assert.equal(f.c.snapshot, undefined); assert.equal(f.events.includes('restore'), false);f.calls.length = 0; f.c.fetchPositionPageWithRecovery = original;const retry = f.start();assert.equal(retry.ready, first.ready); assert.equal(retry.lookup, first.lookup);await flush();assert.deepEqual(f.calls.map(call => call.number), [3]);assert.equal(f.c.snapshot.scroll.index, 4); assert.equal(f.c.snapshot.scroll.offset, 7);assert.equal(f.events.filter(event => event === 'restore').length, 1);assert.equal(f.events.includes('apply'), false); assert.equal(f.restoration.current, null);});test('generation mismatch clears the shared retry buffer and restarts lookup through the live validation hook', async () => {const f = fixture(), original = f.c.fetchPositionPageWithRecovery;f.c.fetchPositionPageWithRecovery = (...args) => args[1] === 3 ? Promise.resolve(page(3, 'B')) : original(...args);let validations = 0;f.c.validatePositionWindowPage = (...args) => {validations++; f.c.VoiceOfMLSearchWindowPage.validate(...args);};const first = f.start(), buffer = first.ready; buffer.set(2, page(2));await flush();assert.ok(validations >= 2); assert.equal(first.error.message, 'RESTORE_PAGE_CHANGED');assert.equal(first.ready, buffer); assert.equal(buffer.size, 0); assert.equal(first.lookup, null); assert.equal(f.c.snapshot, undefined);f.calls.length = 0; f.c.fetchPositionPageWithRecovery = original;const retry = f.start(); assert.equal(retry.ready, buffer);await flush(); assert.deepEqual(f.calls.map(call => call.number), [1, 2, 3, 4]);});test('stale viewport, lookup and neighbor completions cannot publish or mark a newer task failed', async () => {1 unmodified lineconst f = fixture(), gate = deferred(), original = f.c.fetchPositionPageWithRecovery;if (stage === 'viewport') f.c.readSearchViewport = () => gate.promise;else f.c.fetchPositionPageWithRecovery = (...args) => (stage === 'lookup' ? args[1] === 1 : args[1] === 3) ? gate.promise : original(...args);const first = f.start({viewport: stage === 'viewport' ? undefined : null});await flush();f.c.readSearchViewport = () => deferred().promise;const newer = f.start({position});if (rejection) gate.reject(new Error('late')); else gate.resolve(stage === 'viewport' ? null : page(stage === 'lookup' ? 1 : 3));await flush();assert.equal(first.controller.signal.aborted, true);assert.equal(f.restoration.current, newer); assert.equal(f.c.STATE.isLoading, true);assert.equal(first.failed, undefined); assert.equal(newer.failed, undefined); assert.equal(f.c.snapshot, undefined);}});test('preview waits for drag release, accepts only matching cached pages and applies once', async () => {const f = fixture();f.c.STATE.results[4] = {id: 'r4'}; f.c.VSCROLL.isDraggingThumb = true;f.c.captureReaderReturnScroll = () => ({index: 4, offset: 19});const task = f.start({viewport: preview()});f.restoration.rememberPreviewPage(5, page(5));f.restoration.rememberPreviewPage(6, page(6, 'old'));await flush();assert.equal(f.timers.length, 1); assert.equal(f.c.snapshot, undefined);assert.equal(f.c.preview.window.preview, true); assert.equal(Object.hasOwn(f.c.preview, 'resultBackend'), false);assert.equal(f.c.preview.results[4].id, 'r4'); assert.equal(f.store.snapshots.has(key), false);f.c.VSCROLL.isDraggingThumb = false; f.timers.shift()(); await flush();assert.equal(task.ready.has(5), true); assert.equal(task.ready.has(6), false);assert.equal(f.c.snapshot.scroll.offset, 19); assert.equal(f.c.snapshot.results[8].id, 'r8');assert.equal(f.events.filter(event => event === 'apply').length, 1);1 unmodified line});test('abort during drag wait leaves the task and snapshot untouched', async () => {const f = fixture(); f.c.VSCROLL.isDraggingThumb = true;const task = f.start({viewport: preview()}); await flush(); task.controller.abort(); f.timers.shift()(); await flush();assert.equal(f.c.snapshot, undefined); assert.equal(task.failed, undefined); assert.equal(f.restoration.current, task);});test('moving preview anchor outside ready pages restarts lookup without replacing the shared map', async () => {const f = fixture(), original = f.c.fetchPositionPageWithRecovery;f.c.STATE.results[10] = {id: 'r10'}; f.c.captureReaderReturnScroll = () => ({index: 10, offset: 23});f.c.fetchPositionPageWithRecovery = async (...args) => ({...await original(...args), ...(args[3] ? {anchor_index: args[3] === 'r10' ? 10 : 4} : {})});const task = f.start({viewport: preview()}), buffer = task.ready; await flush();assert.equal(task.ready, buffer); assert.deepEqual(f.calls.filter(call => call.anchorId).map(call => call.anchorId), ['r4', 'r10']);assert.deepEqual([...buffer.keys()], [1, 5, 6]); assert.equal(f.c.snapshot.scroll.index, 10);assert.equal(f.c.snapshot.scroll.offset, 23); assert.equal(task.position.anchorId, 'r10');6 unmodified linesf.c.captureReaderReturnScroll = () => ({index:10, offset:23});let fail = true;f.c.fetchPositionPageWithRecovery = async (...args) => {if (fail && args[1] === 6) throw new Error('offline');return {...await original(...args), ...(args[3] === 'r10' ? {anchor_index:10} : {})};};const first = f.start({viewport: preview()}); await flush();assert.ok(first.failed); assert.equal(first.position.anchorId, 'r10');fail = false; f.calls.length = 0;f.c.readSearchViewport = async () => preview(first.position);assert.equal(f.restoration.resume(), true); await flush();assert.deepEqual(f.calls.map(call => call.number), [6]);assert.equal(f.c.snapshot.scroll.index, 10); assert.equal(f.c.snapshot.scroll.offset, 23);});1 unmodified linetest('Reader overlay retains the saved anchor and missing anchor uses the nearby snapshot path', async () => {const f = fixture(); f.c.readerHost.overlay = {};f.c.captureReaderReturnScroll = () => {throw new Error('Reader must retain the saved anchor');};f.start({viewport: preview()}); await flush();assert.equal(f.c.snapshot.scroll.index, 4); assert.equal(f.events.includes('apply'), true);const missing = fixture(), saved = {...position, anchorId: 'gone'};missing.start({position: saved, viewport: preview(saved)}); await flush();assert.equal(missing.c.snapshot.scroll.index, 4); assert.equal(missing.events.includes('restore'), true);assert.equal(missing.events.includes('apply'), false); assert.equal(missing.events.filter(event => event[0] === 'toast').length, 1);});1 unmodified linetest('preview keeps a user-moved hole instead of a vanished saved anchor', async () => {const f = fixture();f.c.captureReaderReturnScroll = () => ({index: 11, offset: 17});const saved = {...position, anchorId: 'gone'};f.start({position: saved, viewport: preview(saved)}); await flush();assert.equal(f.c.snapshot.scroll.index, 11);assert.equal(f.c.snapshot.scroll.offset, 17);assert.equal(f.events.includes('apply'), true);3 unmodified linestest('synchronous prologue retains ordering, duplicate handling and abort reentry ownership', () => {const f = fixture();f.c.readSearchViewport = () => deferred().promise;const active = f.start({}), entry = f.restoration.entry;f.events.length = 0;assert.equal(f.restoration.start(key), true); assert.deepEqual(f.events, []);assert.equal(f.c.searchIntentId, 2); assert.equal(f.restoration.entry, entry);let newer;active.controller.signal.addEventListener('abort', () => {newer = f.start({position});});assert.equal(f.restoration.start(key, {position}), false);assert.deepEqual(f.events.slice(0, 3), ['active', 'clone', 'window']);assert.equal(f.restoration.entry, entry + 2); assert.equal(f.restoration.current, newer);assert.equal(f.c.STATE.isLoading, true); assert.equal(f.events.filter(event => event === 'target').length, 1);});test('active-search abort reentry exits before restoration cancellation', () => {const f = fixture(), active = f.start(), entry = f.restoration.entry;f.c.cancelActiveSearch = () => false;assert.equal(f.restoration.start(key, {position}), false);assert.equal(f.restoration.entry, entry); assert.equal(active.controller.signal.aborted, false);assert.equal(f.restoration.current, active);});test('window abort sees both owners cleared and retains the replacement window and restore', () => {const f = fixture();f.c.readSearchViewport = () => deferred().promise;const active = f.start({}), old = new AbortController(), replacement = {controller: new AbortController()};f.c.resultWindow = {controller: old};let newer, observed;old.signal.addEventListener('abort', () => {observed = [f.c.resultWindow, f.restoration.current, f.c.STATE.isLoading, active.controller.signal.aborted];newer = f.start({position});f.c.resultWindow = replacement;});f.restoration.cancel();assert.deepEqual(observed, [null, null, false, false]);assert.equal(active.controller.signal.aborted, true);assert.equal(f.c.resultWindow, replacement);assert.equal(f.restoration.current, newer);assert.equal(replacement.controller.signal.aborted, false);assert.equal(newer.controller.signal.aborted, false);});test('cancelling the position entry alone invalidates an initial viewport read', async () => {const f = fixture(), gate = deferred();vm.runInContext(source.match(/^async function searchWithInitialFallback\([^]*?^}/m)[0], f.c);let reads = 0, validations = 0, fallback = 0;Object.assign(f.c, {saveSearchViewSnapshot() {}, prepareReturnPosition() {}, getReturnPositionTarget: () => position,validSearchViewport() {validations++; return true;}, searchWithInitialFallbackFresh() {fallback++;},readSearchViewport() {reads++; return gate.promise;}});const pending = f.c.searchWithInitialFallback();assert.equal(reads, 1); assert.equal(f.restoration.current, null);const intent = f.c.searchIntentId, owner = f.c.searchId, entry = f.restoration.entry;f.restoration.cancel();assert.equal(f.restoration.entry, entry + 1);assert.equal(f.c.getSearchViewKey(), key);assert.equal(f.c.searchIntentId, intent); assert.equal(f.c.searchId, owner);gate.resolve(preview());assert.equal(await pending, false);assert.equal(validations, 0); assert.equal(fallback, 0); assert.equal(f.restoration.current, null);});test('Space restores without pinning a backend and resets control scroll after publication', async () => {const f = fixture();f.start(); await flush();assert.ok(f.calls.every(({query}) => !Object.hasOwn(query, 'resultBackend')));assert.equal(Object.hasOwn(f.c.snapshot, 'resultBackend'), false);assert.deepEqual(f.events.filter(event => ['restore', 'reset-controls', 'trim'].includes(event)),['restore', 'reset-controls', 'trim']);});
48 unmodified lines4950515253545548 unmodified linesconst STATE = {results: Array.from({length: count}, (_, index) => ({File: 'row-' + index})), total: count, _loadedPage: 1};const c = vm.createContext({STATE, DOM: {resultsList: list, resultsContainer: container, multiSelectToggle: {checked: false}},document, performance: {now: () => clock += 16}, resultWindow: null, resultSnapshots: {cloneTask: null},positionRestore: null, pendingResultEntrance: false, measuredHeightRevision: 0, keyboardResultIndex: -1,resultRowRecords: records, virtualResults: undefined,requestAnimationFrame(fn) { const id = ++serial; frames.set(id, fn); return id; },cancelAnimationFrame(id) { frames.delete(id); events.push(['cancel', id]); },48 unmodified lines4950515253545548 unmodified linesconst STATE = {results: Array.from({length: count}, (_, index) => ({File: 'row-' + index})), total: count, _loadedPage: 1};const c = vm.createContext({STATE, DOM: {resultsList: list, resultsContainer: container, multiSelectToggle: {checked: false}},document, performance: {now: () => clock += 16}, resultWindow: null, resultSnapshots: {cloneTask: null},positionRestoration: {current: null}, pendingResultEntrance: false, measuredHeightRevision: 0, keyboardResultIndex: -1,resultRowRecords: records, virtualResults: undefined,requestAnimationFrame(fn) { const id = ++serial; frames.set(id, fn); return id; },cancelAnimationFrame(id) { frames.delete(id); events.push(['cancel', id]); },
21 unmodified lines2223242526272821 unmodified lines"static/search/requests/infrastructure/response-cache.js", "static/search/requests/application/response-store.js","static/search/catalog/domain/sidebar-payload.js", "static/search/catalog/application/client.js","static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js","static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];const sources = new Map();const installed = new WeakMap();21 unmodified lines2223242526272821 unmodified lines"static/search/requests/infrastructure/response-cache.js", "static/search/requests/application/response-store.js","static/search/catalog/domain/sidebar-payload.js", "static/search/catalog/application/client.js","static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js","static/search/results/domain/recovery.js", "static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];const sources = new Map();const installed = new WeakMap();
179 unmodified lines1801811821831841851864 unmodified lines191192193194195196197198199200179 unmodified linesinterface VoiceOfMLInputDraftOwner {href: string; key: string | undefined; cancelled: boolean}interface VoiceOfMLInputVisitOwner {generation: number; viewKey: string | null}interface VoiceOfMLInputState {timer: number | null; composing: boolean; dirty: boolean; ready: boolean;}interface VoiceOfMLInputElement extends EventTarget {value: string;4 unmodified linesclock: {setTimeout(callback: () => void, delay: number): number; clearTimeout(timer: number): void};getHref(): string; getEntryKey(): string | undefined; getViewKey(): string | null;syncInput(): void; canSubmit(): boolean; submit(query: string): void; onState(state: Readonly<VoiceOfMLInputState>): void;}interface VoiceOfMLInputController {mount(): void; dispose(): void; debounce(): void; cancelTimer(): void; invalidateVisit(): void;captureDraft(renew?: boolean): void; cancelDraft(): void; draftIsCurrent(): boolean; finishStartup(current: boolean): void;}declare var VoiceOfMLSearchInputOwnership: {draft(href: string, key: string | undefined): VoiceOfMLInputDraftOwner;179 unmodified lines1801811821831841851861871881891901911921931944 unmodified lines199200201202203204205206207208209210211212179 unmodified linesinterface VoiceOfMLInputDraftOwner {href: string; key: string | undefined; cancelled: boolean}interface VoiceOfMLInputVisitOwner {generation: number; viewKey: string | null}interface VoiceOfMLInputState {timer: number | null; filterTimer: number | null; sizeTimer: number | null;composing: boolean; dirty: boolean; ready: boolean;}interface VoiceOfMLSizeControls {min: VoiceOfMLInputElement; max: VoiceOfMLInputElement;minUnit: VoiceOfMLInputElement; maxUnit: VoiceOfMLInputElement;read(): [number | null, number | null];format(bytes: number | null): {value: string; unit: string};commit(min: number | null, max: number | null): void;}interface VoiceOfMLInputElement extends EventTarget {value: string;4 unmodified linesclock: {setTimeout(callback: () => void, delay: number): number; clearTimeout(timer: number): void};getHref(): string; getEntryKey(): string | undefined; getViewKey(): string | null;syncInput(): void; canSubmit(): boolean; submit(query: string): void; onState(state: Readonly<VoiceOfMLInputState>): void;filterSearch(clearResults?: boolean): void;size: VoiceOfMLSizeControls;}interface VoiceOfMLInputController {mount(): void; dispose(): void; debounce(): void; cancelTimer(): void; invalidateVisit(): void;captureDraft(renew?: boolean): void; cancelDraft(): void; draftIsCurrent(): boolean; finishStartup(current: boolean): void;pendingQuery(): string | null; flushSize(): void; syncSize(preserveDraft?: boolean): void;cancelPending(preserveQuery?: boolean): void; scheduleFilter(): void; cancelFilter(): void;}declare var VoiceOfMLSearchInputOwnership: {draft(href: string, key: string | undefined): VoiceOfMLInputDraftOwner;
2 unmodified lines345678910111213141516171819202122232425262728293031323334352 unmodified lines}interface SearchPositionRestoreTask {key: string; controller: AbortController; position: SearchPosition;backend?: string | undefined;lookup?: SearchPositionRestorePage | null | undefined;ready: Map<number, SearchPositionRestorePage>;preview?: boolean; cachedPages?: Map<number, SearchPositionRestorePage>;failed?: boolean; error?: Error;}interface SearchPositionRestoreInput {key: string; position: SearchPosition; previous?: SearchPositionRestoreTask | null | undefined;backend?: string | undefined;}interface SearchPositionRestorationHost {isCurrent(task: SearchPositionRestoreTask): boolean;readViewport(key: string): Promise<SearchPositionViewport | null>;fetchPage(query: VoiceOfMLSearchViewProjection & {resultBackend?: string}, page: number, signal: AbortSignal, anchorId?: string): Promise<SearchPositionRestorePage>;validatePage: typeof VoiceOfMLSearchWindowPage.validate;showPreview(viewport: SearchPositionViewport | null, position: SearchPosition, task: SearchPositionRestoreTask): void;isDragging(): boolean;capturePreviewAnchor(): Readonly<{index: number; offset: number; anchorId: string}> | null;stableId(record: unknown): string; estimatedHeight(): number;release(): void; applyPreview(snapshot: SearchResultSnapshot): void;snapshots: Pick<SearchSnapshotStore, 'putRestored' | 'trim'>;restoreSnapshot(key: string): void; completed(): void;failed(message: string): void; notify(message: string): void;}declare var VoiceOfMLPositionRestoration: {createTask(input: SearchPositionRestoreInput): SearchPositionRestoreTask;create(host: SearchPositionRestorationHost): {run(task: SearchPositionRestoreTask, viewport?: SearchPositionViewport | null): Promise<void>;};};2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344452 unmodified lines}interface SearchPositionRestoreTask {key: string; controller: AbortController; position: SearchPosition;lookup?: SearchPositionRestorePage | null | undefined;ready: Map<number, SearchPositionRestorePage>;preview?: boolean; cachedPages?: Map<number, SearchRecentPage>;failed?: boolean; error?: Error;}interface SearchPositionRestoreOptions {position?: SearchPosition | null;viewport?: SearchPositionViewport | null | undefined;}interface SearchPositionRestoreInput {key: string; position: SearchPosition; previous: SearchPositionRestoreTask | null;}interface SearchPositionRestorationHost {currentKey(): string;getPosition(key: string): SearchPosition | undefined;noteSearchIntent(): void;retireSearch(): (() => boolean) | null;detachWindow(): AbortController | undefined;status(phase: 'started' | 'cancelled' | 'preview' | 'finished' | 'failed', message: string): void;readViewport(key: string): Promise<SearchPositionViewport | null>;fetchPage(query: VoiceOfMLSearchViewProjection & {resultBackend?: string}, page: number, signal: AbortSignal, anchorId?: string): Promise<SearchPositionRestorePage>;validatePage: typeof VoiceOfMLSearchWindowPage.validate;isDragging(): boolean;capturePreviewAnchor(): Readonly<{index: number; offset: number; anchorId: string}> | null;stableId(record: unknown): string; estimatedHeight(): number;applyPreview(snapshot: SearchResultSnapshot): void;snapshots: Pick<SearchSnapshotStore, 'cancelClone' | 'put' | 'remove' | 'putRestored' | 'trim'>;restoreSnapshot(key: string, preview?: boolean): void;completed(): void; notify(message: string): void;}declare var VoiceOfMLPositionRestoration: {create(host: SearchPositionRestorationHost): {readonly current: Readonly<SearchPositionRestoreTask> | null;readonly entry: number;start(key: string, options?: SearchPositionRestoreOptions): boolean;cancel(): void;resume(): boolean;rememberPreviewPage(page: number, data: SearchRecentPage): void;};};
static/app.js+81-181
static/search/input/application/controller.js+122-18
static/search/positions/application/restoration.js+76-10
tests/search/browser/test_paging_recovery.py+1-1
tests/search/browser/test_position_controls.py+15-5
tests/search/browser/test_position_window.py+6-6
tests/search/browser/test_recent_search_pages.py+5-5
tests/search/browser/test_search_positions.py+3-3
tests/search/paging/result_window_contracts.mjs+1-1
tests/search/reader-navigation/routing_contracts.mjs+35-15
tests/search/reader-navigation/test_search_history_races.mjs+56-26
tests/search/session/restoration_contracts.mjs+128-68
tests/search/ui/virtual_results_contracts.mjs+1-1
tests/support/classic_search_modules.js+1-1
typings/reader-globals.d.ts+13-1
typings/search-restoration.d.ts+22-12