vomebook commited on
Commit
eea3bcf
·
1 Parent(s): 5675f95

Keep filter drafts from interrupting search position restoration

Browse files
static/app.js CHANGED
@@ -117,7 +117,6 @@ let searchIntentId = 0;
117
  let filterSearchTimer = null;
118
  /** @type {ReturnType<typeof setTimeout> | null} */
119
  let sizeFilterTimer = null;
120
- const FILTER_SEARCH_DEBOUNCE_MS = 200;
121
  let routeRenderId = 0;
122
  // A path-only route change bumps routeRenderId for the browser, but must not
123
  // orphan an unfinished filter render or its batched folder-tree tasks.
@@ -237,15 +236,12 @@ const positionPersistence = VoiceOfMLSearchPositions.create({
237
  });
238
  /** @type {VoiceOfMLSearchAppDisplayedView | null} */
239
  let displayedSearchView = null;
240
- /** @type {SearchPositionRestoreTask | null} */
241
- let positionRestore = null;
242
  /** @type {VoiceOfMLSearchAppWindow | null} */
243
  let resultWindow = null;
244
  /** @type {SearchPosition | null} */
245
  let returnPositionTarget = null;
246
  /** @type {{key: string, last: number, distance: number, until: number} | null} */
247
  let positionControlScroll = null;
248
- let positionEntryId = 0;
249
  let backToTopPending = false;
250
 
251
  function getReturnPositionTarget(key = getSearchViewKey()) {
@@ -272,32 +268,21 @@ function prepareReturnPosition(key, updateControls = true) {
272
 
273
  function updateSearchPositionControls() {
274
  if (!getReturnPositionTarget()) setReturnPositionTarget();
275
- if (DOM.returnToPositionBtn) DOM.returnToPositionBtn.hidden = !returnPositionTarget || !!positionRestore;
276
  if (DOM.backToTopBtn) DOM.backToTopBtn.hidden = backToTopPending || !STATE.results.length || getResultScrollTop() <= 0;
277
- if (DOM.positionRestoreStatus) DOM.positionRestoreStatus.hidden = !positionRestore;
278
- }
279
-
280
- /** @param {boolean} [preserveDrafts] */
281
- function cancelPendingSearchControls(preserveDrafts = false) {
282
- if (preserveDrafts) return;
283
- searchInputController.cancelTimer();
284
- if (filterSearchTimer !== null) clearTimeout(filterSearchTimer);
285
- if (sizeFilterTimer !== null) clearTimeout(sizeFilterTimer);
286
- filterSearchTimer = null;
287
- sizeFilterTimer = null;
288
  }
289
 
290
  /** @param {{fromStart: boolean, restorePosition: boolean}} options */
291
  function prepareSearchPositionNavigation({ fromStart, restorePosition }) {
292
- // First-page fallback and retries belong to the current view, not to the
293
- // newer input draft. Explicit query/filter commits cancel their own debounce.
294
- cancelPendingSearchControls(!fromStart);
295
  // The URL is the handoff contract for Reader navigation and session restore.
296
  // Publish the current controls before any async result work starts.
297
  syncStateToURL(true);
298
  // A deliberate trip to the top captures the currently displayed position.
299
  // During restoration (or when already at the top), retain the existing target.
300
- if (fromStart && !positionRestore && getResultScrollTop() > 0) setReturnPositionTarget();
301
  saveSearchViewSnapshot();
302
  const key = getSearchViewKey();
303
  if (fromStart) saveSearchPosition();
@@ -312,8 +297,10 @@ function prepareSearchPositionNavigation({ fromStart, restorePosition }) {
312
 
313
  function returnToSavedPosition() {
314
  const position = getReturnPositionTarget();
315
- if (position) return tryRestoreSearchPosition(position.key, { position });
316
- return false;
 
 
317
  }
318
 
319
  function backToSearchTop() {
@@ -337,7 +324,7 @@ function updateReturnPositionOnScroll() {
337
  const top = getResultScrollTop();
338
  if (Date.now() <= progress.until) progress.distance += Math.abs(top - progress.last);
339
  progress.last = top;
340
- if (!positionRestore && progress.distance > Math.max(1200, DOM.resultsContainer.clientHeight * 2)) {
341
  setReturnPositionTarget();
342
  updateSearchPositionControls();
343
  }
@@ -351,7 +338,7 @@ function jumpToSearchResult(value) {
351
  const index = Math.min(STATE.total - 1, requested - 1);
352
  const key = getSearchViewKey();
353
  setReturnPositionTarget();
354
- if (!positionRestore && !resultWindow?.invalid && STATE.results[index]) setResultScrollTop(getVirtualOffset(index));
355
  else tryRestoreSearchPosition(key, { viewport: null, position: {
356
  version: 1, key, index, offset: 0, anchorId: "",
357
  loadedPage: Math.floor(index / STATE.pageSize) + 1, savedAt: Date.now()
@@ -432,7 +419,7 @@ async function loadCachedPreviewPage(window, page) {
432
  window.pending.set(page, request);
433
  try {
434
  const entry = await request;
435
- if (!resultWindowCurrent(window) || !positionRestore?.preview || VSCROLL.isDraggingThumb) return;
436
  if (!entry) { (window.missingPages ||= new Set()).add(page); return; }
437
  const start = (page - 1) * window.query.pageSize;
438
  if (start + entry.results.length > STATE.results.length) return;
@@ -443,7 +430,7 @@ async function loadCachedPreviewPage(window, page) {
443
  STATE.results[index] = record; window.count++; VSCROLL.templateCache.delete(index);
444
  });
445
  window.pages.add(page);
446
- (positionRestore.cachedPages ||= new Map()).set(page, entry);
447
  VSCROLL.measuredWindowKey = ""; VSCROLL.renderStart = -1; VSCROLL.renderEnd = -1;
448
  renderVisible(); updateLoadInfo();
449
  } finally {
@@ -471,24 +458,6 @@ function validSearchViewport(viewport, position) {
471
  return VoiceOfMLPositionPolicy.validViewport(viewport, position, getResultStableId);
472
  }
473
 
474
- /** @param {SearchPositionViewport | null} viewport @param {SearchPosition} position @param {SearchPositionRestoreTask} task */
475
- function showSavedSearchViewport(viewport, position, task) {
476
- if (!validSearchViewport(viewport, position)) return;
477
- const size = JSON.parse(position.key).pageSize;
478
- const results = new Array(Math.min(viewport.total, position.loadedPage * size));
479
- for (const [index, record] of viewport.records) if (Number.isInteger(index) && index >= 0 && index < results.length) results[index] = record;
480
- const snapshot = { version: SEARCH_VIEW_SNAPSHOT_VERSION, key: position.key, results, total: viewport.total,
481
- loadedPage: position.loadedPage, pageCache: {}, hasMore: results.length < viewport.total,
482
- window: { preview: true, generation: viewport.generation, pages: [], count: Object.keys(results).length }, estimatedHeight: viewport.estimatedHeight,
483
- heightCache: viewport.records.map(([, record, height]) => /** @type {SearchSnapshotHeightEntry} */ ([getResultStableId(record), {height, measurementKey: viewport.measurementKey}])),
484
- scroll: {index: position.index, offset: position.offset, viewKey: position.key}, savedAt: Date.now() };
485
- task.preview = true;
486
- resultSnapshots.put(position.key, snapshot);
487
- restoreSearchViewSnapshot(position.key, true, { preserveRestore: true });
488
- resultSnapshots.remove(position.key);
489
- showPositionRestoreStatus("已恢复上次画面,正在核对结果…");
490
- }
491
-
492
  /** @param {unknown} value @returns {value is SearchPosition} */
493
  function validSearchPosition(value) {
494
  return VoiceOfMLPositionPolicy.validPosition(value);
@@ -518,7 +487,7 @@ function saveSearchPosition() {
518
  const view = displayedSearchView;
519
  const target = view && getReturnPositionTarget(view.key);
520
  if (target) return target;
521
- if (!view || positionRestore || readerHost.overlay || !view.results.length || !VSCROLL.heights.length) return null;
522
  if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return positionPersistence.getPosition(view.key) || null;
523
  const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);
524
  if (!view.results[index]) return positionPersistence.getPosition(view.key) || null;
@@ -531,7 +500,7 @@ function saveSearchPosition() {
531
 
532
  function setupSearchPositionSaving() {
533
  DOM.resultsContainer.addEventListener("scroll", () => {
534
- if (positionRestore || STATE.isLoading || displayedSearchView?.key !== getSearchViewKey()) return;
535
  positionPersistence.scheduleSave(saveSearchPosition);
536
  }, { passive: true });
537
  // Query and route handlers save explicitly; capture only filters before mutation.
@@ -554,28 +523,32 @@ function showPositionRestoreStatus(message, retry = false) {
554
  updateLoadInfo();
555
  }
556
 
557
- function cancelPositionRestore() {
558
- cancelSnapshotClone();
559
- positionEntryId++;
560
- const previousWindow = resultWindow;
561
- const previousRestore = positionRestore;
562
- resultWindow = null;
563
- positionRestore = null;
564
- updateResultWindowStatus();
565
- if (previousRestore) {
566
- STATE.isLoading = false;
567
- showPositionRestoreStatus("");
568
- }
569
- previousWindow?.controller.abort();
570
- previousRestore?.controller.abort();
571
- }
572
-
573
  const positionRestoration = VoiceOfMLPositionRestoration.create({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  validatePage: (data, page, size, expected) => validatePositionWindowPage(data, page, size, expected),
575
- isCurrent: task => positionRestore === task && task.key === getSearchViewKey(),
576
  readViewport: key => readSearchViewport(key),
577
  fetchPage: (query, page, signal, anchorId) => fetchPositionPageWithRecovery(query, page, signal, anchorId),
578
- showPreview: (viewport, position, task) => showSavedSearchViewport(viewport, position, task),
579
  isDragging: () => VSCROLL.isDraggingThumb,
580
  capturePreviewAnchor: () => {
581
  if (readerHost.overlay) return null;
@@ -585,39 +558,19 @@ const positionRestoration = VoiceOfMLPositionRestoration.create({
585
  },
586
  stableId: record => getResultStableId(record),
587
  estimatedHeight: () => VSCROLL.estimatedHeight,
588
- release: () => { positionRestore = null; showPositionRestoreStatus(""); },
589
  applyPreview: snapshot => applyValidatedSearchViewport(snapshot),
590
  snapshots: resultSnapshots,
591
  // Completing a position restore does not own query input typed while it was loading.
592
- restoreSnapshot: key => restoreSearchViewSnapshot(key, true, { preserveQueryDraft: true }),
 
593
  completed: () => resetPositionControlScroll(),
594
- failed: message => { STATE.isLoading = false; showPositionRestoreStatus(message, true); },
595
  notify: message => showToast(message)
596
  });
597
-
598
- /** @param {string} key @param {{position?: SearchPosition | null; viewport?: SearchPositionViewport | null}} [options] */
599
- function tryRestoreSearchPosition(key, options = {}) {
600
- const previous = positionRestore?.key === key && positionRestore.failed && !options.position ? positionRestore : null;
601
- const position = options.position || previous?.position || positionPersistence.getPosition(key);
602
- if (!validSearchPosition(position)) return false;
603
- searchIntentId++;
604
- if (!options.position && positionRestore?.key === key && !positionRestore.failed) return true;
605
- if (!cancelActiveSearch()) return false;
606
- const owner = searchId;
607
- cancelPositionRestore();
608
- if (owner !== searchId) return false;
609
- setReturnPositionTarget();
610
- const task = VoiceOfMLPositionRestoration.createTask({ key, position, previous });
611
- positionRestore = task;
612
- STATE.isLoading = true;
613
- resetPagingRecovery();
614
- showPositionRestoreStatus("正在恢复上次位置…");
615
- void positionRestoration.run(task, options.viewport);
616
- return true;
617
- }
618
 
619
  /** @param {SearchResultSnapshot} snapshot */
620
  function applyValidatedSearchViewport(snapshot) {
 
621
  const anchor = snapshot.scroll;
622
  const previous = STATE.results;
623
  // Preview selections belong to records, not to slots replaced by validation.
@@ -709,10 +662,7 @@ async function fetchPositionPageWithRecovery(query, page, signal, anchorId, dema
709
 
710
  function resumeResultRecovery() {
711
  if (document.hidden || !navigator.onLine || readerHost.overlay) return;
712
- if (positionRestore?.failed && isRecoverableSearchError(positionRestore.error)) {
713
- tryRestoreSearchPosition(positionRestore.key);
714
- return;
715
- }
716
  if (!resultWindow || resultWindow.invalid) return;
717
  const start = Math.floor(findVirtualIndex(getResultScrollTop()) / STATE.pageSize);
718
  const end = Math.floor(findVirtualIndex(getResultScrollTop() + DOM.resultsContainer.clientHeight) / STATE.pageSize) + 2;
@@ -740,7 +690,7 @@ function requestResultWindowPage(window, page, prefetch = false) {
740
  /** @param {number} page @param {boolean} [prefetch] */
741
  async function loadResultWindowPage(page, prefetch = false) {
742
  const window = resultWindow;
743
- if (!window || positionRestore || !resultWindowCurrent(window) || window.pages.has(page) || page < 1 || page > Math.ceil(window.total / window.query.pageSize)) return false;
744
  try {
745
  const data = await requestResultWindowPage(window, page, prefetch);
746
  if (!data || !resultWindowCurrent(window) || window.invalid || window.pages.has(page)) return false;
@@ -811,8 +761,9 @@ function ensureResultWindowPages(start, end) {
811
  if (!resultWindow || VSCROLL.isDraggingThumb) return;
812
  const activeWindow = resultWindow;
813
  const size = activeWindow.query.pageSize;
814
- if (positionRestore) {
815
- if (positionRestore.preview) for (let page = Math.floor(start / size) + 1; page <= Math.ceil(end / size); page++) loadCachedPreviewPage(resultWindow, page);
 
816
  return;
817
  }
818
  const scrollTop = getResultScrollTop();
@@ -922,7 +873,7 @@ function saveSearchViewSnapshot(key = displayedSearchView?.key) {
922
  }
923
  // Browsing from the top must not overwrite the snapshot offered by Return.
924
  if (getReturnPositionTarget(key)) return resultSnapshots.snapshots.get(key) || null;
925
- if (!DOM.resultsContainer || !view || positionRestore || key !== view.key || view.loadedPage < 1) return null;
926
  const position = saveSearchPosition();
927
  return resultSnapshots.save(view, position, {
928
  revision: measuredHeightRevision, measurementKey: getHeightMeasurementKey(),
@@ -935,10 +886,6 @@ function activateSearchView(key = getSearchViewKey()) {
935
  const snapshot = resultSnapshots.snapshots.get(key);
936
  VSCROLL.heightCache = new Map(snapshot?.heightCache || []);
937
  }
938
- function cancelSnapshotClone() {
939
- resultSnapshots.cancelClone();
940
- }
941
-
942
  /** @param {SearchSnapshotCloneTask} task @param {number} start @param {number} end @param {boolean} [deferHeights] */
943
  function materializeSnapshotRange(task, start, end, deferHeights = false) {
944
  resultSnapshots.materializeRange(task, start, end, deferHeights);
@@ -991,7 +938,7 @@ function restoreSearchViewSnapshot(key, restoreScroll = true, { preserveRestore
991
  const owner = searchId;
992
  if (!preserveRestore) cancelPositionRestore();
993
  if (owner !== searchId) return false;
994
- if (!preserveRestore) cancelPendingSearchControls(preserveQueryDraft);
995
  STATE.results = resultSnapshots.restoreResults(snapshot, key, STATE.pageSize, restoreScroll, preserveRestore);
996
  STATE.total = snapshot.total;
997
  STATE.page = STATE._loadedPage = snapshot.loadedPage;
@@ -1294,7 +1241,7 @@ async function searchWithInitialFallback() {
1294
  const owner = searchId;
1295
  cancelPositionRestore();
1296
  if (owner !== searchId || intent !== searchIntentId) return false;
1297
- const key = getSearchViewKey(), entry = positionEntryId;
1298
  prepareReturnPosition(key);
1299
  if (resultSnapshots.snapshots.has(key)) {
1300
  setReturnPositionTarget();
@@ -1302,7 +1249,7 @@ async function searchWithInitialFallback() {
1302
  }
1303
  const position = getReturnPositionTarget(key);
1304
  const viewport = position ? await readSearchViewport(key) : null;
1305
- if (intent !== searchIntentId || entry !== positionEntryId || key !== getSearchViewKey()) return false;
1306
  if (validSearchViewport(viewport, position)) return tryRestoreSearchPosition(key, {position, viewport});
1307
  return searchWithInitialFallbackFresh(intent);
1308
  }
@@ -1670,9 +1617,12 @@ function getReaderLink(rec, returnUrl = location.href, cacheMetadata = true) {
1670
 
1671
  // Reader host owns overlay and return-position state. Effects resolve live host hooks.
1672
  const readerReturnPosition = VoiceOfMLReaderReturn.create({
1673
- readView: () => ({ hasContainer: !!DOM.resultsContainer, containerHeight: DOM.resultsContainer?.clientHeight || 0,
1674
- resultCount: STATE.results.length, total: STATE.total, loading: STATE.isLoading, loadedPage: STATE._loadedPage,
1675
- positionRestore: positionRestore && { preview: positionRestore.preview, key: positionRestore.key }, routeRevision: routeRenderId }),
 
 
 
1676
  hasResult: index => !!STATE.results[index], getViewKey: () => getSearchViewKey(),
1677
  getTop: () => getResultScrollTop(), setTop: top => setResultScrollTop(top),
1678
  ensureHeights: () => ensureHeightTree(), findIndex: top => findVirtualIndex(top),
@@ -2155,12 +2105,13 @@ const ROUTER = {
2155
  }
2156
  syncURLToState(false);
2157
  const sameSearchView = previousSearchKey === getSearchViewKey();
 
2158
  const directoryOnly = sameSearchView && STATE.mode === "repo" && previousPath !== STATE.browserPath;
2159
  if (directoryOnly && searchComposing) searchInputController.invalidateVisit();
2160
  if (!directoryOnly && !searchComposing && !initialSearchDraft) setSearchInputValue(STATE.query);
2161
  if (!sameSearchView) {
2162
  if (routeInitialized) searchInputController.invalidateVisit();
2163
- cancelPendingSearchControls();
2164
  readerReturnPosition.invalidate();
2165
  if (!cancelActiveSearch()) return;
2166
  }
@@ -2233,30 +2184,8 @@ function syncURLToState(updateInput = true) {
2233
  DOM.sortSelect.value = projected.sort;
2234
  STATE.filterExtensions = projected.filterExtensions === null ? loadStoredExtensionFilters() : projected.filterExtensions;
2235
  if (projected.filterExtensions !== null) saveStoredExtensionFilters();
2236
- const minSize = params.get("min_size");
2237
- if (minSize) {
2238
- var parsed = parseSizeStr(minSize);
2239
- STATE.filterMinSize = parsed;
2240
- var disp = bytesToDisplay(parsed);
2241
- DOM.filterMinSize.value = disp.value;
2242
- DOM.filterMinUnit.value = disp.unit;
2243
- } else {
2244
- STATE.filterMinSize = null;
2245
- DOM.filterMinSize.value = "";
2246
- DOM.filterMinUnit.value = "MB";
2247
- }
2248
- const maxSize = params.get("max_size");
2249
- if (maxSize) {
2250
- var parsedMx = parseSizeStr(maxSize);
2251
- STATE.filterMaxSize = parsedMx;
2252
- var dispMx = bytesToDisplay(parsedMx);
2253
- DOM.filterMaxSize.value = dispMx.value;
2254
- DOM.filterMaxUnit.value = dispMx.unit;
2255
- } else {
2256
- STATE.filterMaxSize = null;
2257
- DOM.filterMaxSize.value = "";
2258
- DOM.filterMaxUnit.value = "MB";
2259
- }
2260
  STATE.searchFolders = projected.searchFolders;
2261
  DOM.searchFoldersToggle.checked = STATE.searchFolders;
2262
  STATE.filterFolderSelfs = projected.filterFolderSelfs;
@@ -2374,8 +2303,8 @@ function submitSearchQuery(query, { restore = false, record = false, refreshHist
2374
  return;
2375
  }
2376
  // Another search can preempt the size debounce: include its visible input.
2377
- applyPendingSizeFilters();
2378
- cancelPendingSearchControls();
2379
  saveSearchViewSnapshot();
2380
  if (updateInput) setSearchInputValue(query);
2381
  STATE.query = query;
@@ -2393,9 +2322,10 @@ function submitSearchQuery(query, { restore = false, record = false, refreshHist
2393
 
2394
  function prepareReaderSearch() {
2395
  if (readerHost.overlay || location.pathname + location.search !== appliedSearchRoute) return;
2396
- if (searchTimer !== null && !searchComposing) {
 
2397
  searchInputController.cancelTimer();
2398
- submitSearchQuery(DOM.searchInput.value.trim(), { record: true, refreshHistory: true });
2399
  }
2400
  if (sizeFilterTimer !== null || filterSearchTimer !== null) {
2401
  doFilterSearch();
@@ -2422,8 +2352,16 @@ function setupSearchInput() {
2422
  syncInput: syncSearchInputState,
2423
  canSubmit: () => !readerHost.overlay && location.pathname + location.search === appliedSearchRoute,
2424
  submit: query => { submitSearchQuery(query, { record: true, refreshHistory: true }); },
 
 
 
 
 
 
2425
  onState: state => {
2426
  searchTimer = state.timer;
 
 
2427
  searchComposing = state.composing;
2428
  initialSearchDraft = state.dirty;
2429
  }
@@ -2463,7 +2401,7 @@ function clearResultsSkeleton() {
2463
  }
2464
 
2465
  function renderResults(animate = false) {
2466
- if (!positionRestore && STATE._loadedPage >= 1) rememberDisplayedSearchView();
2467
  activateSearchView();
2468
  redrawResults(animate);
2469
  }
@@ -2667,7 +2605,7 @@ function getVirtualResults() {
2667
  if (!resultWindow) throw new TypeError("Result window is missing");
2668
  return resultWindow.total;
2669
  },
2670
- cloning: () => !!resultSnapshots.cloneTask, restoring: () => !!positionRestore,
2671
  loadedPage: () => STATE._loadedPage, pendingEntrance: () => pendingResultEntrance,
2672
  consumeEntrance: () => { pendingResultEntrance = false; },
2673
  recordMeasurement: () => { measuredHeightRevision++; },
@@ -2758,9 +2696,9 @@ function setSearchVisualLoading(loading) {
2758
  /** @param {boolean} clearResults */
2759
  function prepareFilterChange(clearResults) {
2760
  // Merge completed query drafts too; a filter click must not discard typing.
2761
- const query = searchTimer !== null && !searchComposing ? DOM.searchInput.value.trim() : null;
2762
- applyPendingSizeFilters();
2763
- cancelPendingSearchControls();
2764
  saveSearchViewSnapshot();
2765
  if (query !== null && Array.from(query).length <= 256) STATE.query = query;
2766
  STATE.page = 1;
@@ -2772,39 +2710,6 @@ function doFilterSearch(clearResults = false) {
2772
  return doSearch(false, false, true);
2773
  }
2774
 
2775
- /** @param {HTMLInputElement} input @param {HTMLSelectElement} unitSelect */
2776
- function sizeInputToBytes(input, unitSelect) {
2777
- const value = parseFloat(input.value);
2778
- if (isNaN(value) || value < 0) return null;
2779
- /** @type {Record<string, number>} */
2780
- const factors = { B: 1, KB: 1024, MB: 1048576, GB: 1073741824 };
2781
- const factor = factors[unitSelect.value] || 1;
2782
- return Math.round(value * factor);
2783
- }
2784
-
2785
- function applyPendingSizeFilters() {
2786
- if (sizeFilterTimer === null) return;
2787
- clearTimeout(sizeFilterTimer);
2788
- sizeFilterTimer = null;
2789
- STATE.filterMinSize = sizeInputToBytes(DOM.filterMinSize, DOM.filterMinUnit);
2790
- STATE.filterMaxSize = sizeInputToBytes(DOM.filterMaxSize, DOM.filterMaxUnit);
2791
- }
2792
-
2793
- function setupSizeFilterControls() {
2794
- const schedule = () => {
2795
- if (sizeFilterTimer !== null) clearTimeout(sizeFilterTimer);
2796
- sizeFilterTimer = setTimeout(() => {
2797
- applyPendingSizeFilters();
2798
- doFilterSearch(true);
2799
- }, 500);
2800
- };
2801
- [DOM.filterMinSize, DOM.filterMaxSize].forEach(input => input.addEventListener("input", schedule));
2802
- // A unit alone does not change the search. Leave any pending edit to
2803
- // either bound on its existing debounce deadline.
2804
- DOM.filterMinUnit.addEventListener("change", () => { if (DOM.filterMinSize.value !== "") schedule(); });
2805
- DOM.filterMaxUnit.addEventListener("change", () => { if (DOM.filterMaxSize.value !== "") schedule(); });
2806
- }
2807
-
2808
  function scheduleFilterSearch(clearResults = false) {
2809
  searchIntentId++;
2810
  prepareFilterChange(clearResults);
@@ -2816,10 +2721,7 @@ function scheduleFilterSearch(clearResults = false) {
2816
  STATE.isLoading = true;
2817
  setSearchVisualLoading(true);
2818
  syncStateToURL(true);
2819
- filterSearchTimer = setTimeout(() => {
2820
- filterSearchTimer = null;
2821
- doFilterSearch();
2822
- }, FILTER_SEARCH_DEBOUNCE_MS);
2823
  }
2824
 
2825
  function updateCurrentResultPosition() {
@@ -3014,8 +2916,7 @@ async function doSearch(append = false, fromStart = false, restorePosition = fal
3014
  const owner = searchId;
3015
  if (!append && prepareSearchPositionNavigation({ fromStart, restorePosition })) return;
3016
  if (owner !== searchId) return;
3017
- if (filterSearchTimer !== null) clearTimeout(filterSearchTimer);
3018
- filterSearchTimer = null;
3019
  if (!append) {
3020
  if (!recoveringFirstPage) resetPagingRecovery();
3021
  STATE.page = 1;
@@ -3216,7 +3117,7 @@ function readPagingView() {
3216
  return {
3217
  generation: searchRequestId, loadedPage: STATE._loadedPage, page: STATE.page,
3218
  resultCount: STATE.results.length, hasMore: STATE.hasMore, loading: STATE.isLoading,
3219
- suspended: !!resultSnapshots.cloneTask || !!positionRestore || (STATE._loadedPage
3220
  ? !ownsDisplayedSearchResults()
3221
  : searchTimer !== null || filterSearchTimer !== null || sizeFilterTimer !== null || searchComposing),
3222
  inactive: document.hidden || !!readerHost.overlay, dragging: VSCROLL.isDraggingThumb,
@@ -3752,7 +3653,6 @@ async function init() {
3752
  DOM.randomBookBtn.addEventListener('click', randomBook);
3753
  if (DOM.randomTxtBtn) DOM.randomTxtBtn.addEventListener('click', randomTxt);
3754
  DOM.emptyRandomBtn.addEventListener('click', randomTxt);
3755
- setupSizeFilterControls();
3756
  setupExtensionBulkSelection();
3757
  if (DOM.folderToggleAll) DOM.folderToggleAll.addEventListener("click", () =>
3758
  setAllFoldersCollapsed(DOM.folderToggleAll.getAttribute("aria-expanded") === "true"));
 
117
  let filterSearchTimer = null;
118
  /** @type {ReturnType<typeof setTimeout> | null} */
119
  let sizeFilterTimer = null;
 
120
  let routeRenderId = 0;
121
  // A path-only route change bumps routeRenderId for the browser, but must not
122
  // orphan an unfinished filter render or its batched folder-tree tasks.
 
236
  });
237
  /** @type {VoiceOfMLSearchAppDisplayedView | null} */
238
  let displayedSearchView = null;
 
 
239
  /** @type {VoiceOfMLSearchAppWindow | null} */
240
  let resultWindow = null;
241
  /** @type {SearchPosition | null} */
242
  let returnPositionTarget = null;
243
  /** @type {{key: string, last: number, distance: number, until: number} | null} */
244
  let positionControlScroll = null;
 
245
  let backToTopPending = false;
246
 
247
  function getReturnPositionTarget(key = getSearchViewKey()) {
 
268
 
269
  function updateSearchPositionControls() {
270
  if (!getReturnPositionTarget()) setReturnPositionTarget();
271
+ if (DOM.returnToPositionBtn) DOM.returnToPositionBtn.hidden = !returnPositionTarget || !!positionRestoration.current;
272
  if (DOM.backToTopBtn) DOM.backToTopBtn.hidden = backToTopPending || !STATE.results.length || getResultScrollTop() <= 0;
273
+ if (DOM.positionRestoreStatus) DOM.positionRestoreStatus.hidden = !positionRestoration.current;
 
 
 
 
 
 
 
 
 
 
274
  }
275
 
276
  /** @param {{fromStart: boolean, restorePosition: boolean}} options */
277
  function prepareSearchPositionNavigation({ fromStart, restorePosition }) {
278
+ // First-page fallback and retries do not own newer query or size drafts.
279
+ if (fromStart) searchInputController.cancelPending();
 
280
  // The URL is the handoff contract for Reader navigation and session restore.
281
  // Publish the current controls before any async result work starts.
282
  syncStateToURL(true);
283
  // A deliberate trip to the top captures the currently displayed position.
284
  // During restoration (or when already at the top), retain the existing target.
285
+ if (fromStart && !positionRestoration.current && getResultScrollTop() > 0) setReturnPositionTarget();
286
  saveSearchViewSnapshot();
287
  const key = getSearchViewKey();
288
  if (fromStart) saveSearchPosition();
 
297
 
298
  function returnToSavedPosition() {
299
  const position = getReturnPositionTarget();
300
+ if (!position) return false;
301
+ // A queued filter must not restart the search while Return is waiting for I/O.
302
+ searchInputController.cancelPending(true);
303
+ return tryRestoreSearchPosition(position.key, { position });
304
  }
305
 
306
  function backToSearchTop() {
 
324
  const top = getResultScrollTop();
325
  if (Date.now() <= progress.until) progress.distance += Math.abs(top - progress.last);
326
  progress.last = top;
327
+ if (!positionRestoration.current && progress.distance > Math.max(1200, DOM.resultsContainer.clientHeight * 2)) {
328
  setReturnPositionTarget();
329
  updateSearchPositionControls();
330
  }
 
338
  const index = Math.min(STATE.total - 1, requested - 1);
339
  const key = getSearchViewKey();
340
  setReturnPositionTarget();
341
+ if (!positionRestoration.current && !resultWindow?.invalid && STATE.results[index]) setResultScrollTop(getVirtualOffset(index));
342
  else tryRestoreSearchPosition(key, { viewport: null, position: {
343
  version: 1, key, index, offset: 0, anchorId: "",
344
  loadedPage: Math.floor(index / STATE.pageSize) + 1, savedAt: Date.now()
 
419
  window.pending.set(page, request);
420
  try {
421
  const entry = await request;
422
+ if (!resultWindowCurrent(window) || !positionRestoration.current?.preview || VSCROLL.isDraggingThumb) return;
423
  if (!entry) { (window.missingPages ||= new Set()).add(page); return; }
424
  const start = (page - 1) * window.query.pageSize;
425
  if (start + entry.results.length > STATE.results.length) return;
 
430
  STATE.results[index] = record; window.count++; VSCROLL.templateCache.delete(index);
431
  });
432
  window.pages.add(page);
433
+ positionRestoration.rememberPreviewPage(page, entry);
434
  VSCROLL.measuredWindowKey = ""; VSCROLL.renderStart = -1; VSCROLL.renderEnd = -1;
435
  renderVisible(); updateLoadInfo();
436
  } finally {
 
458
  return VoiceOfMLPositionPolicy.validViewport(viewport, position, getResultStableId);
459
  }
460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  /** @param {unknown} value @returns {value is SearchPosition} */
462
  function validSearchPosition(value) {
463
  return VoiceOfMLPositionPolicy.validPosition(value);
 
487
  const view = displayedSearchView;
488
  const target = view && getReturnPositionTarget(view.key);
489
  if (target) return target;
490
+ if (!view || positionRestoration.current || readerHost.overlay || !view.results.length || !VSCROLL.heights.length) return null;
491
  if (STATE.results !== view.results || (STATE.isLoading && view.key !== getSearchViewKey())) return positionPersistence.getPosition(view.key) || null;
492
  const index = Math.min(findVirtualIndex(getResultScrollTop()), view.results.length - 1);
493
  if (!view.results[index]) return positionPersistence.getPosition(view.key) || null;
 
500
 
501
  function setupSearchPositionSaving() {
502
  DOM.resultsContainer.addEventListener("scroll", () => {
503
+ if (positionRestoration.current || STATE.isLoading || displayedSearchView?.key !== getSearchViewKey()) return;
504
  positionPersistence.scheduleSave(saveSearchPosition);
505
  }, { passive: true });
506
  // Query and route handlers save explicitly; capture only filters before mutation.
 
523
  updateLoadInfo();
524
  }
525
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
  const positionRestoration = VoiceOfMLPositionRestoration.create({
527
+ currentKey: () => getSearchViewKey(),
528
+ getPosition: key => positionPersistence.getPosition(key),
529
+ noteSearchIntent: () => { searchIntentId++; },
530
+ retireSearch: () => {
531
+ if (!cancelActiveSearch()) return null;
532
+ const owner = searchId;
533
+ return () => owner === searchId;
534
+ },
535
+ detachWindow: () => {
536
+ const controller = resultWindow?.controller;
537
+ resultWindow = null;
538
+ updateResultWindowStatus();
539
+ return controller;
540
+ },
541
+ status: (phase, message) => {
542
+ if (phase === "started") {
543
+ setReturnPositionTarget();
544
+ STATE.isLoading = true;
545
+ resetPagingRecovery();
546
+ } else if (phase === "cancelled" || phase === "failed") STATE.isLoading = false;
547
+ showPositionRestoreStatus(message, phase === "failed");
548
+ },
549
  validatePage: (data, page, size, expected) => validatePositionWindowPage(data, page, size, expected),
 
550
  readViewport: key => readSearchViewport(key),
551
  fetchPage: (query, page, signal, anchorId) => fetchPositionPageWithRecovery(query, page, signal, anchorId),
 
552
  isDragging: () => VSCROLL.isDraggingThumb,
553
  capturePreviewAnchor: () => {
554
  if (readerHost.overlay) return null;
 
558
  },
559
  stableId: record => getResultStableId(record),
560
  estimatedHeight: () => VSCROLL.estimatedHeight,
 
561
  applyPreview: snapshot => applyValidatedSearchViewport(snapshot),
562
  snapshots: resultSnapshots,
563
  // Completing a position restore does not own query input typed while it was loading.
564
+ restoreSnapshot: (key, preview) => restoreSearchViewSnapshot(key, true,
565
+ preview ? { preserveRestore: true } : { preserveQueryDraft: true }),
566
  completed: () => resetPositionControlScroll(),
 
567
  notify: message => showToast(message)
568
  });
569
+ const { cancel: cancelPositionRestore, start: tryRestoreSearchPosition } = positionRestoration;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570
 
571
  /** @param {SearchResultSnapshot} snapshot */
572
  function applyValidatedSearchViewport(snapshot) {
573
+ searchInputController.cancelPending(true);
574
  const anchor = snapshot.scroll;
575
  const previous = STATE.results;
576
  // Preview selections belong to records, not to slots replaced by validation.
 
662
 
663
  function resumeResultRecovery() {
664
  if (document.hidden || !navigator.onLine || readerHost.overlay) return;
665
+ if (positionRestoration.resume()) return;
 
 
 
666
  if (!resultWindow || resultWindow.invalid) return;
667
  const start = Math.floor(findVirtualIndex(getResultScrollTop()) / STATE.pageSize);
668
  const end = Math.floor(findVirtualIndex(getResultScrollTop() + DOM.resultsContainer.clientHeight) / STATE.pageSize) + 2;
 
690
  /** @param {number} page @param {boolean} [prefetch] */
691
  async function loadResultWindowPage(page, prefetch = false) {
692
  const window = resultWindow;
693
+ if (!window || positionRestoration.current || !resultWindowCurrent(window) || window.pages.has(page) || page < 1 || page > Math.ceil(window.total / window.query.pageSize)) return false;
694
  try {
695
  const data = await requestResultWindowPage(window, page, prefetch);
696
  if (!data || !resultWindowCurrent(window) || window.invalid || window.pages.has(page)) return false;
 
761
  if (!resultWindow || VSCROLL.isDraggingThumb) return;
762
  const activeWindow = resultWindow;
763
  const size = activeWindow.query.pageSize;
764
+ const restore = positionRestoration.current;
765
+ if (restore) {
766
+ if (restore.preview) for (let page = Math.floor(start / size) + 1; page <= Math.ceil(end / size); page++) loadCachedPreviewPage(resultWindow, page);
767
  return;
768
  }
769
  const scrollTop = getResultScrollTop();
 
873
  }
874
  // Browsing from the top must not overwrite the snapshot offered by Return.
875
  if (getReturnPositionTarget(key)) return resultSnapshots.snapshots.get(key) || null;
876
+ if (!DOM.resultsContainer || !view || positionRestoration.current || key !== view.key || view.loadedPage < 1) return null;
877
  const position = saveSearchPosition();
878
  return resultSnapshots.save(view, position, {
879
  revision: measuredHeightRevision, measurementKey: getHeightMeasurementKey(),
 
886
  const snapshot = resultSnapshots.snapshots.get(key);
887
  VSCROLL.heightCache = new Map(snapshot?.heightCache || []);
888
  }
 
 
 
 
889
  /** @param {SearchSnapshotCloneTask} task @param {number} start @param {number} end @param {boolean} [deferHeights] */
890
  function materializeSnapshotRange(task, start, end, deferHeights = false) {
891
  resultSnapshots.materializeRange(task, start, end, deferHeights);
 
938
  const owner = searchId;
939
  if (!preserveRestore) cancelPositionRestore();
940
  if (owner !== searchId) return false;
941
+ if (!preserveRestore) searchInputController.cancelPending(preserveQueryDraft);
942
  STATE.results = resultSnapshots.restoreResults(snapshot, key, STATE.pageSize, restoreScroll, preserveRestore);
943
  STATE.total = snapshot.total;
944
  STATE.page = STATE._loadedPage = snapshot.loadedPage;
 
1241
  const owner = searchId;
1242
  cancelPositionRestore();
1243
  if (owner !== searchId || intent !== searchIntentId) return false;
1244
+ const key = getSearchViewKey(), entry = positionRestoration.entry;
1245
  prepareReturnPosition(key);
1246
  if (resultSnapshots.snapshots.has(key)) {
1247
  setReturnPositionTarget();
 
1249
  }
1250
  const position = getReturnPositionTarget(key);
1251
  const viewport = position ? await readSearchViewport(key) : null;
1252
+ if (intent !== searchIntentId || entry !== positionRestoration.entry || key !== getSearchViewKey()) return false;
1253
  if (validSearchViewport(viewport, position)) return tryRestoreSearchPosition(key, {position, viewport});
1254
  return searchWithInitialFallbackFresh(intent);
1255
  }
 
1617
 
1618
  // Reader host owns overlay and return-position state. Effects resolve live host hooks.
1619
  const readerReturnPosition = VoiceOfMLReaderReturn.create({
1620
+ readView: () => {
1621
+ const restore = positionRestoration.current;
1622
+ return { hasContainer: !!DOM.resultsContainer, containerHeight: DOM.resultsContainer?.clientHeight || 0,
1623
+ resultCount: STATE.results.length, total: STATE.total, loading: STATE.isLoading, loadedPage: STATE._loadedPage,
1624
+ positionRestore: restore && { preview: restore.preview, key: restore.key }, routeRevision: routeRenderId };
1625
+ },
1626
  hasResult: index => !!STATE.results[index], getViewKey: () => getSearchViewKey(),
1627
  getTop: () => getResultScrollTop(), setTop: top => setResultScrollTop(top),
1628
  ensureHeights: () => ensureHeightTree(), findIndex: top => findVirtualIndex(top),
 
2105
  }
2106
  syncURLToState(false);
2107
  const sameSearchView = previousSearchKey === getSearchViewKey();
2108
+ searchInputController.syncSize(sameSearchView);
2109
  const directoryOnly = sameSearchView && STATE.mode === "repo" && previousPath !== STATE.browserPath;
2110
  if (directoryOnly && searchComposing) searchInputController.invalidateVisit();
2111
  if (!directoryOnly && !searchComposing && !initialSearchDraft) setSearchInputValue(STATE.query);
2112
  if (!sameSearchView) {
2113
  if (routeInitialized) searchInputController.invalidateVisit();
2114
+ searchInputController.cancelPending();
2115
  readerReturnPosition.invalidate();
2116
  if (!cancelActiveSearch()) return;
2117
  }
 
2184
  DOM.sortSelect.value = projected.sort;
2185
  STATE.filterExtensions = projected.filterExtensions === null ? loadStoredExtensionFilters() : projected.filterExtensions;
2186
  if (projected.filterExtensions !== null) saveStoredExtensionFilters();
2187
+ STATE.filterMinSize = parseSizeStr(params.get("min_size"));
2188
+ STATE.filterMaxSize = parseSizeStr(params.get("max_size"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2189
  STATE.searchFolders = projected.searchFolders;
2190
  DOM.searchFoldersToggle.checked = STATE.searchFolders;
2191
  STATE.filterFolderSelfs = projected.filterFolderSelfs;
 
2303
  return;
2304
  }
2305
  // Another search can preempt the size debounce: include its visible input.
2306
+ searchInputController.flushSize();
2307
+ searchInputController.cancelPending();
2308
  saveSearchViewSnapshot();
2309
  if (updateInput) setSearchInputValue(query);
2310
  STATE.query = query;
 
2322
 
2323
  function prepareReaderSearch() {
2324
  if (readerHost.overlay || location.pathname + location.search !== appliedSearchRoute) return;
2325
+ const query = searchInputController.pendingQuery();
2326
+ if (query !== null) {
2327
  searchInputController.cancelTimer();
2328
+ submitSearchQuery(query, { record: true, refreshHistory: true });
2329
  }
2330
  if (sizeFilterTimer !== null || filterSearchTimer !== null) {
2331
  doFilterSearch();
 
2352
  syncInput: syncSearchInputState,
2353
  canSubmit: () => !readerHost.overlay && location.pathname + location.search === appliedSearchRoute,
2354
  submit: query => { submitSearchQuery(query, { record: true, refreshHistory: true }); },
2355
+ filterSearch: clearResults => doFilterSearch(clearResults),
2356
+ size: {
2357
+ min: DOM.filterMinSize, max: DOM.filterMaxSize, minUnit: DOM.filterMinUnit, maxUnit: DOM.filterMaxUnit,
2358
+ read: () => [STATE.filterMinSize, STATE.filterMaxSize], format: bytesToDisplay,
2359
+ commit: (min, max) => { STATE.filterMinSize = min; STATE.filterMaxSize = max; }
2360
+ },
2361
  onState: state => {
2362
  searchTimer = state.timer;
2363
+ filterSearchTimer = state.filterTimer;
2364
+ sizeFilterTimer = state.sizeTimer;
2365
  searchComposing = state.composing;
2366
  initialSearchDraft = state.dirty;
2367
  }
 
2401
  }
2402
 
2403
  function renderResults(animate = false) {
2404
+ if (!positionRestoration.current && STATE._loadedPage >= 1) rememberDisplayedSearchView();
2405
  activateSearchView();
2406
  redrawResults(animate);
2407
  }
 
2605
  if (!resultWindow) throw new TypeError("Result window is missing");
2606
  return resultWindow.total;
2607
  },
2608
+ cloning: () => !!resultSnapshots.cloneTask, restoring: () => !!positionRestoration.current,
2609
  loadedPage: () => STATE._loadedPage, pendingEntrance: () => pendingResultEntrance,
2610
  consumeEntrance: () => { pendingResultEntrance = false; },
2611
  recordMeasurement: () => { measuredHeightRevision++; },
 
2696
  /** @param {boolean} clearResults */
2697
  function prepareFilterChange(clearResults) {
2698
  // Merge completed query drafts too; a filter click must not discard typing.
2699
+ const query = searchInputController.pendingQuery();
2700
+ searchInputController.flushSize();
2701
+ searchInputController.cancelPending();
2702
  saveSearchViewSnapshot();
2703
  if (query !== null && Array.from(query).length <= 256) STATE.query = query;
2704
  STATE.page = 1;
 
2710
  return doSearch(false, false, true);
2711
  }
2712
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2713
  function scheduleFilterSearch(clearResults = false) {
2714
  searchIntentId++;
2715
  prepareFilterChange(clearResults);
 
2721
  STATE.isLoading = true;
2722
  setSearchVisualLoading(true);
2723
  syncStateToURL(true);
2724
+ searchInputController.scheduleFilter();
 
 
 
2725
  }
2726
 
2727
  function updateCurrentResultPosition() {
 
2916
  const owner = searchId;
2917
  if (!append && prepareSearchPositionNavigation({ fromStart, restorePosition })) return;
2918
  if (owner !== searchId) return;
2919
+ searchInputController.cancelFilter();
 
2920
  if (!append) {
2921
  if (!recoveringFirstPage) resetPagingRecovery();
2922
  STATE.page = 1;
 
3117
  return {
3118
  generation: searchRequestId, loadedPage: STATE._loadedPage, page: STATE.page,
3119
  resultCount: STATE.results.length, hasMore: STATE.hasMore, loading: STATE.isLoading,
3120
+ suspended: !!resultSnapshots.cloneTask || !!positionRestoration.current || (STATE._loadedPage
3121
  ? !ownsDisplayedSearchResults()
3122
  : searchTimer !== null || filterSearchTimer !== null || sizeFilterTimer !== null || searchComposing),
3123
  inactive: document.hidden || !!readerHost.overlay, dragging: VSCROLL.isDraggingThumb,
 
3653
  DOM.randomBookBtn.addEventListener('click', randomBook);
3654
  if (DOM.randomTxtBtn) DOM.randomTxtBtn.addEventListener('click', randomTxt);
3655
  DOM.emptyRandomBtn.addEventListener('click', randomTxt);
 
3656
  setupExtensionBulkSelection();
3657
  if (DOM.folderToggleAll) DOM.folderToggleAll.addEventListener("click", () =>
3658
  setAllFoldersCollapsed(DOM.folderToggleAll.getAttribute("aria-expanded") === "true"));
static/search/input/application/controller.js CHANGED
@@ -1,23 +1,120 @@
1
- // Owns the input listeners, startup handoff, IME visit and debounce lifetime.
2
  (function () {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  /** @param {VoiceOfMLInputDependencies} deps @returns {VoiceOfMLInputController} */
4
  function create(deps) {
5
- const { input, navigation, ownership, clock } = deps;
6
- /** @type {VoiceOfMLInputState & {generation: number, owner: VoiceOfMLInputDraftOwner | null}} */
7
- const state = { timer: null, composing: false, generation: 0, ready: false, dirty: false, owner: null };
 
8
  let composition = ownership.visit(0, null);
9
- let mounted = false, disposed = false, timerGeneration = 0;
10
  const navigationEvents = ["popstate", "hashchange", "pagehide"];
11
  // Each notification is detached and contains only host presentation state.
12
- const publish = () => deps.onState({ timer: state.timer, composing: state.composing, dirty: state.dirty, ready: state.ready });
 
13
 
14
  function cancelTimer() {
15
- const token = ++timerGeneration;
16
- if (state.timer !== null) clock.clearTimeout(state.timer);
17
- state.timer = null;
18
  publish();
19
  return token;
20
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  function invalidateVisit() { state.generation++; cancelTimer(); }
22
  function captureDraft(renew = false) {
23
  if (disposed || state.ready) return;
@@ -33,17 +130,14 @@
33
  if (disposed || state.composing || !state.ready || !deps.canSubmit()) return;
34
  const token = cancelTimer();
35
  // Publication may synchronously cancel, replace or dispose this operation.
36
- if (disposed || token !== timerGeneration || state.composing || !state.ready) return;
37
  const owner = ownership.visit(state.generation, null);
38
- state.timer = clock.setTimeout(() => {
39
- // A cancelled callback must neither submit nor clear its replacement timer.
40
- if (disposed || token !== timerGeneration) return;
41
- state.timer = null;
42
  publish();
43
- if (disposed || token !== timerGeneration || state.composing || !deps.canSubmit() ||
44
  !ownership.visitIsCurrent(owner, state.generation, null)) return;
45
  deps.submit(input.value.trim());
46
- }, 100);
47
  publish();
48
  }
49
  /** @param {Event} event */
@@ -80,6 +174,10 @@
80
  input.addEventListener("input", onInput);
81
  input.addEventListener("compositionstart", onStart);
82
  input.addEventListener("compositionend", onEnd);
 
 
 
 
83
  // The inline producer remains active until these listeners are installed.
84
  const early = input._earlySearchInput;
85
  if (early) {
@@ -107,17 +205,23 @@
107
  if (disposed) return;
108
  disposed = true;
109
  cancelDraft();
110
- invalidateVisit();
 
111
  removeNavigationListeners();
112
  input.removeEventListener("input", onInput);
113
  input.removeEventListener("compositionstart", onStart);
114
  input.removeEventListener("compositionend", onEnd);
 
 
 
 
115
  state.composing = false;
116
  state.dirty = false;
117
  state.owner = null;
118
  publish();
119
  }
120
- return { mount, dispose, debounce, cancelTimer, invalidateVisit, captureDraft, cancelDraft, draftIsCurrent, finishStartup };
 
121
  }
122
  globalThis.VoiceOfMLSearchInput = { create };
123
  })();
 
1
+ // Owns search-control drafts and the lifetimes of their delayed commits.
2
  (function () {
3
+ /** @param {VoiceOfMLInputDependencies['clock']} clock */
4
+ function debounceSlot(clock) {
5
+ /** @type {number | null} */
6
+ let timer = null;
7
+ let generation = 0;
8
+ function cancel() {
9
+ const token = ++generation;
10
+ if (timer !== null) clock.clearTimeout(timer);
11
+ timer = null;
12
+ return token;
13
+ }
14
+ /** @param {number} token */
15
+ const isCurrent = token => token === generation;
16
+ /** @param {number} token @param {number} delay @param {() => void} run */
17
+ function schedule(token, delay, run) {
18
+ if (!isCurrent(token)) return;
19
+ timer = clock.setTimeout(() => {
20
+ if (!isCurrent(token) || timer === null) return;
21
+ timer = null;
22
+ run();
23
+ }, delay);
24
+ }
25
+ return { get timer() { return timer; }, cancel, isCurrent, schedule };
26
+ }
27
+
28
+ /** @param {string} value @param {string} unit */
29
+ function sizeInputToBytes(value, unit) {
30
+ const number = parseFloat(value);
31
+ if (isNaN(number) || number < 0) return null;
32
+ const factors = /** @type {Record<string, number>} */ ({ B: 1, KB: 1024, MB: 1048576, GB: 1073741824 });
33
+ return Math.round(number * (factors[unit] || 1));
34
+ }
35
+
36
  /** @param {VoiceOfMLInputDependencies} deps @returns {VoiceOfMLInputController} */
37
  function create(deps) {
38
+ const { input, navigation, ownership, clock, size } = deps;
39
+ const query = debounceSlot(clock), filters = debounceSlot(clock), sizeEdit = debounceSlot(clock);
40
+ /** @type {Pick<VoiceOfMLInputState, 'composing' | 'ready' | 'dirty'> & {generation: number, owner: VoiceOfMLInputDraftOwner | null}} */
41
+ const state = { composing: false, generation: 0, ready: false, dirty: false, owner: null };
42
  let composition = ownership.visit(0, null);
43
+ let mounted = false, disposed = false;
44
  const navigationEvents = ["popstate", "hashchange", "pagehide"];
45
  // Each notification is detached and contains only host presentation state.
46
+ const publish = () => deps.onState({ timer: query.timer, filterTimer: filters.timer, sizeTimer: sizeEdit.timer,
47
+ composing: state.composing, dirty: state.dirty, ready: state.ready });
48
 
49
  function cancelTimer() {
50
+ const token = query.cancel();
 
 
51
  publish();
52
  return token;
53
  }
54
+
55
+ function pendingQuery() {
56
+ return query.timer !== null && !state.composing ? input.value.trim() : null;
57
+ }
58
+
59
+ function applySize() {
60
+ size.commit(sizeInputToBytes(size.min.value, size.minUnit.value), sizeInputToBytes(size.max.value, size.maxUnit.value));
61
+ }
62
+ function flushSize() {
63
+ if (sizeEdit.timer === null) return;
64
+ sizeEdit.cancel();
65
+ applySize();
66
+ publish();
67
+ }
68
+ /** @param {boolean} [preserveDraft] */
69
+ function syncSize(preserveDraft = false) {
70
+ if (preserveDraft && sizeEdit.timer !== null) return;
71
+ const [min, max] = size.read();
72
+ const lower = size.format(min), upper = size.format(max);
73
+ size.min.value = lower.value;
74
+ size.minUnit.value = lower.unit;
75
+ size.max.value = upper.value;
76
+ size.maxUnit.value = upper.unit;
77
+ }
78
+ /** @param {boolean} [preserveQuery] */
79
+ function cancelPending(preserveQuery = false) {
80
+ filters.cancel();
81
+ if (sizeEdit.timer !== null) {
82
+ sizeEdit.cancel();
83
+ // A discarded bound must not be picked up when the other bound is edited.
84
+ syncSize();
85
+ }
86
+ if (preserveQuery) publish();
87
+ else cancelTimer();
88
+ }
89
+ function cancelFilter() {
90
+ filters.cancel();
91
+ publish();
92
+ }
93
+ function scheduleFilter() {
94
+ if (disposed) return;
95
+ const token = filters.cancel();
96
+ filters.schedule(token, 200, () => {
97
+ publish();
98
+ // Committed filters must settle even if a Reader overlay now covers the results.
99
+ if (filters.isCurrent(token)) deps.filterSearch();
100
+ });
101
+ publish();
102
+ }
103
+ function scheduleSize() {
104
+ if (disposed) return;
105
+ const token = sizeEdit.cancel();
106
+ sizeEdit.schedule(token, 500, () => {
107
+ publish();
108
+ if (!sizeEdit.isCurrent(token)) return;
109
+ applySize();
110
+ deps.filterSearch(true);
111
+ });
112
+ publish();
113
+ }
114
+ // A unit with an empty bound must not postpone an edit to the other bound.
115
+ const changeMinUnit = () => { if (size.min.value !== "") scheduleSize(); };
116
+ const changeMaxUnit = () => { if (size.max.value !== "") scheduleSize(); };
117
+
118
  function invalidateVisit() { state.generation++; cancelTimer(); }
119
  function captureDraft(renew = false) {
120
  if (disposed || state.ready) return;
 
130
  if (disposed || state.composing || !state.ready || !deps.canSubmit()) return;
131
  const token = cancelTimer();
132
  // Publication may synchronously cancel, replace or dispose this operation.
133
+ if (disposed || !query.isCurrent(token) || state.composing || !state.ready) return;
134
  const owner = ownership.visit(state.generation, null);
135
+ query.schedule(token, 100, () => {
 
 
 
136
  publish();
137
+ if (disposed || !query.isCurrent(token) || state.composing || !deps.canSubmit() ||
138
  !ownership.visitIsCurrent(owner, state.generation, null)) return;
139
  deps.submit(input.value.trim());
140
+ });
141
  publish();
142
  }
143
  /** @param {Event} event */
 
174
  input.addEventListener("input", onInput);
175
  input.addEventListener("compositionstart", onStart);
176
  input.addEventListener("compositionend", onEnd);
177
+ size.min.addEventListener("input", scheduleSize);
178
+ size.max.addEventListener("input", scheduleSize);
179
+ size.minUnit.addEventListener("change", changeMinUnit);
180
+ size.maxUnit.addEventListener("change", changeMaxUnit);
181
  // The inline producer remains active until these listeners are installed.
182
  const early = input._earlySearchInput;
183
  if (early) {
 
205
  if (disposed) return;
206
  disposed = true;
207
  cancelDraft();
208
+ state.generation++;
209
+ cancelPending();
210
  removeNavigationListeners();
211
  input.removeEventListener("input", onInput);
212
  input.removeEventListener("compositionstart", onStart);
213
  input.removeEventListener("compositionend", onEnd);
214
+ size.min.removeEventListener("input", scheduleSize);
215
+ size.max.removeEventListener("input", scheduleSize);
216
+ size.minUnit.removeEventListener("change", changeMinUnit);
217
+ size.maxUnit.removeEventListener("change", changeMaxUnit);
218
  state.composing = false;
219
  state.dirty = false;
220
  state.owner = null;
221
  publish();
222
  }
223
+ return { mount, dispose, debounce, cancelTimer, invalidateVisit, captureDraft, cancelDraft, draftIsCurrent, finishStartup,
224
+ pendingQuery, flushSize, syncSize, cancelPending, scheduleFilter, cancelFilter };
225
  }
226
  globalThis.VoiceOfMLSearchInput = { create };
227
  })();
static/search/positions/application/restoration.js CHANGED
@@ -1,5 +1,5 @@
1
- // Coordinates asynchronous restoration. The host retains synchronous search
2
- // cancellation/publication because abort listeners can reenter navigation.
3
  (function () {
4
  /** @param {SearchPositionRestoreInput} input */
5
  function createTask({ key, position, previous }) {
@@ -11,16 +11,81 @@
11
 
12
  /** @param {SearchPositionRestorationHost} host */
13
  function create(host) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  /** @param {SearchPositionRestoreTask} task @param {SearchPositionViewport | null | undefined} viewport */
15
  async function run(task, viewport) {
16
  const { key, controller } = task;
17
  let position = task.position;
18
- const current = () => host.isCurrent(task) && !controller.signal.aborted;
19
  try {
20
  const query = JSON.parse(key);
21
  if (viewport === undefined) viewport = await host.readViewport(key);
22
  if (!current()) return;
23
- host.showPreview(viewport, position, task);
24
  while (current()) {
25
  const lookup = task.lookup || await host.fetchPage(query, 1, controller.signal, position.anchorId);
26
  if (!current()) return;
@@ -80,14 +145,15 @@
80
  estimatedHeight: host.estimatedHeight(), heightCache: [], heightRecords: [],
81
  scroll: { index: geometry ? Math.min(geometry.index, Math.max(0, total - 1)) : found < 0 ? index : found,
82
  offset: total ? geometry?.offset ?? position.offset : 0, viewKey: key }, savedAt: Date.now() };
83
- host.release();
 
84
  if (task.preview && (geometry || found === position.index)) host.applyPreview(snapshot);
85
  else {
86
- host.snapshots.putRestored(key, snapshot);
87
  host.restoreSnapshot(key);
88
  }
89
  host.completed();
90
- host.snapshots.trim();
91
  if (!geometry && found < 0 && position.anchorId) host.notify("搜索结果已变化,已恢复到原位置附近");
92
  return;
93
  }
@@ -97,11 +163,11 @@
97
  task.failed = true;
98
  task.error = err;
99
  if (err.message === "RESTORE_PAGE_CHANGED") { task.lookup = null; task.ready.clear(); }
100
- host.failed(err.message === "RESTORE_PAGE_CHANGED"
101
  ? "搜索数据已更新,请重试恢复" : "暂时无法加载原位置附近的结果");
102
  }
103
  }
104
- return { run };
105
  }
106
- globalThis.VoiceOfMLPositionRestoration = { createTask, create };
107
  })();
 
1
+ // Owns the restore task and its preview-to-validated transition. The host
2
+ // renders snapshots and detaches the displayed pagination window on cancellation.
3
  (function () {
4
  /** @param {SearchPositionRestoreInput} input */
5
  function createTask({ key, position, previous }) {
 
11
 
12
  /** @param {SearchPositionRestorationHost} host */
13
  function create(host) {
14
+ const { snapshots } = host;
15
+ /** @type {SearchPositionRestoreTask | null} */
16
+ let active = null;
17
+ let entry = 0;
18
+
19
+ function cancel() {
20
+ snapshots.cancelClone();
21
+ entry++;
22
+ const previous = active;
23
+ active = null;
24
+ const windowController = host.detachWindow();
25
+ if (previous) host.status("cancelled", "");
26
+ // Both owners and their UI are cleared before abort listeners can reenter.
27
+ windowController?.abort();
28
+ previous?.controller.abort();
29
+ }
30
+
31
+ /** @param {string} key @param {SearchPositionRestoreOptions} [options] */
32
+ function start(key, options = {}) {
33
+ const same = active?.key === key ? active : null;
34
+ const previous = same?.failed && !options.position ? same : null;
35
+ const position = options.position || previous?.position || host.getPosition(key);
36
+ if (!globalThis.VoiceOfMLPositionPolicy.validPosition(position)) return false;
37
+ host.noteSearchIntent();
38
+ if (!options.position && same && !same.failed) return true;
39
+ const stillOwnsSearch = host.retireSearch();
40
+ if (!stillOwnsSearch) return false;
41
+ cancel();
42
+ if (!stillOwnsSearch()) return false;
43
+ const task = createTask({ key, position, previous });
44
+ active = task;
45
+ host.status("started", "正在恢复上次位置…");
46
+ void run(task, options.viewport);
47
+ return true;
48
+ }
49
+
50
+ function resume() {
51
+ if (!active?.failed || !globalThis.VoiceOfMLSearchRecovery.isRecoverable(active.error)) return false;
52
+ start(active.key);
53
+ return true;
54
+ }
55
+
56
+ /** @param {number} page @param {SearchRecentPage} data */
57
+ function rememberPreviewPage(page, data) {
58
+ if (active?.preview) (active.cachedPages ||= new Map()).set(page, data);
59
+ }
60
+
61
+ /** @param {SearchPositionViewport | null} viewport @param {SearchPosition} position @param {SearchPositionRestoreTask} task */
62
+ function showPreview(viewport, position, task) {
63
+ if (!globalThis.VoiceOfMLPositionPolicy.validViewport(viewport, position, host.stableId)) return;
64
+ const size = JSON.parse(position.key).pageSize;
65
+ const results = new Array(Math.min(viewport.total, position.loadedPage * size));
66
+ for (const [index, record] of viewport.records) if (Number.isInteger(index) && index >= 0 && index < results.length) results[index] = record;
67
+ const snapshot = { version: globalThis.VoiceOfMLSnapshotPolicy.VERSION, key: position.key, results, total: viewport.total,
68
+ loadedPage: position.loadedPage, pageCache: {}, hasMore: results.length < viewport.total,
69
+ window: { preview: true, generation: viewport.generation, pages: [], count: Object.keys(results).length }, estimatedHeight: viewport.estimatedHeight,
70
+ heightCache: viewport.records.map(([, record, height]) => /** @type {SearchSnapshotHeightEntry} */ ([host.stableId(record), {height, measurementKey: viewport.measurementKey}])),
71
+ scroll: {index: position.index, offset: position.offset, viewKey: position.key}, savedAt: Date.now() };
72
+ task.preview = true;
73
+ snapshots.put(position.key, snapshot);
74
+ host.restoreSnapshot(position.key, true);
75
+ snapshots.remove(position.key);
76
+ host.status("preview", "已恢复上次画面,正在核对结果…");
77
+ }
78
+
79
  /** @param {SearchPositionRestoreTask} task @param {SearchPositionViewport | null | undefined} viewport */
80
  async function run(task, viewport) {
81
  const { key, controller } = task;
82
  let position = task.position;
83
+ const current = () => active === task && key === host.currentKey() && !controller.signal.aborted;
84
  try {
85
  const query = JSON.parse(key);
86
  if (viewport === undefined) viewport = await host.readViewport(key);
87
  if (!current()) return;
88
+ showPreview(viewport, position, task);
89
  while (current()) {
90
  const lookup = task.lookup || await host.fetchPage(query, 1, controller.signal, position.anchorId);
91
  if (!current()) return;
 
145
  estimatedHeight: host.estimatedHeight(), heightCache: [], heightRecords: [],
146
  scroll: { index: geometry ? Math.min(geometry.index, Math.max(0, total - 1)) : found < 0 ? index : found,
147
  offset: total ? geometry?.offset ?? position.offset : 0, viewKey: key }, savedAt: Date.now() };
148
+ active = null;
149
+ host.status("finished", "");
150
  if (task.preview && (geometry || found === position.index)) host.applyPreview(snapshot);
151
  else {
152
+ snapshots.putRestored(key, snapshot);
153
  host.restoreSnapshot(key);
154
  }
155
  host.completed();
156
+ snapshots.trim();
157
  if (!geometry && found < 0 && position.anchorId) host.notify("搜索结果已变化,已恢复到原位置附近");
158
  return;
159
  }
 
163
  task.failed = true;
164
  task.error = err;
165
  if (err.message === "RESTORE_PAGE_CHANGED") { task.lookup = null; task.ready.clear(); }
166
+ host.status("failed", err.message === "RESTORE_PAGE_CHANGED"
167
  ? "搜索数据已更新,请重试恢复" : "暂时无法加载原位置附近的结果");
168
  }
169
  }
170
+ return { get current() { return active; }, get entry() { return entry; }, start, cancel, resume, rememberPreviewPage };
171
  }
172
+ globalThis.VoiceOfMLPositionRestoration = { create };
173
  })();
tests/search/browser/test_paging_recovery.py CHANGED
@@ -364,7 +364,7 @@ class PagingRecoveryTests(unittest.TestCase):
364
  }''')
365
  self.page.wait_for_function("STATE._loadedPage === 1 && !STATE.isLoading && searchPageMetadata.get(STATE.results[0])?.generation === 'A'")
366
  self.page.evaluate("currentGeneration='B'; cancelSearchPrefetch(); STATE.page=2; doSearch(true)")
367
- self.page.wait_for_function("!positionRestore && resultWindow?.generation === 'B' && !STATE.isLoading")
368
  names = self.page.evaluate('STATE.results.filter(Boolean).map(r => r.File)')
369
  self.assertGreaterEqual(len(names), 200)
370
  self.assertEqual(names, ['paging-' + str(i) for i in range(-1, len(names) - 1)])
 
364
  }''')
365
  self.page.wait_for_function("STATE._loadedPage === 1 && !STATE.isLoading && searchPageMetadata.get(STATE.results[0])?.generation === 'A'")
366
  self.page.evaluate("currentGeneration='B'; cancelSearchPrefetch(); STATE.page=2; doSearch(true)")
367
+ self.page.wait_for_function("!positionRestoration.current && resultWindow?.generation === 'B' && !STATE.isLoading")
368
  names = self.page.evaluate('STATE.results.filter(Boolean).map(r => r.File)')
369
  self.assertGreaterEqual(len(names), 200)
370
  self.assertEqual(names, ['paging-' + str(i) for i in range(-1, len(names) - 1)])
tests/search/browser/test_position_controls.py CHANGED
@@ -43,7 +43,7 @@ class PositionControlTests(unittest.TestCase):
43
  self.assertEqual(errors, [])
44
 
45
  def wait_position(self, index):
46
- self.page.wait_for_function('i=>!positionRestore && !STATE.isLoading && findVirtualIndex(getResultScrollTop())===i && !!STATE.results[i]', arg=index)
47
 
48
  def jump(self, number, key='Enter'):
49
  self.page.locator('#edit-result-position').click()
@@ -95,7 +95,7 @@ class PositionControlTests(unittest.TestCase):
95
  self.page.set_viewport_size({'width':390,'height':844})
96
  self.page.evaluate('STATE.isMobile=true;applyMobileMode();failPosition=true')
97
  self.jump(95001)
98
- self.page.wait_for_function('positionRestore?.failed')
99
  self.assertTrue(self.page.locator('#load-info .result-position-actions #retry-position-btn').is_visible())
100
  self.assertTrue(self.page.locator('#cancel-position-btn').is_hidden())
101
  self.assertEqual(self.page.locator('#results-container').evaluate('e=>getComputedStyle(e).visibility'),'visible')
@@ -329,7 +329,7 @@ class PositionControlTests(unittest.TestCase):
329
  self.wait_position(0)
330
 
331
  self.page.locator('#sort-select').select_option('name')
332
- self.page.wait_for_function('!STATE.isLoading && !positionRestore')
333
  second = click_top_immediately()
334
  self.assertEqual(second['before'], [False, False])
335
  self.assertEqual(second['after'], [True, False])
@@ -364,7 +364,7 @@ class PositionControlTests(unittest.TestCase):
364
  self.page.wait_for_timeout(250)
365
  self.assertEqual(self.page.evaluate('positionCalls'),[1])
366
  self.page.locator('#search-input').fill('paging-latest')
367
- self.page.wait_for_function('STATE.query==="paging-latest" && !STATE.isLoading && !positionRestore')
368
  self.page.evaluate('blockPosition=false;releasePosition()')
369
  self.page.wait_for_timeout(100)
370
  self.wait_position(0)
@@ -375,10 +375,20 @@ class PositionControlTests(unittest.TestCase):
375
  self.page.locator('#restart-position-btn').click()
376
  self.wait_position(0)
377
  self.page.evaluate('''()=>{
 
 
378
  DOM.filterMinSize.value='7';
379
  DOM.filterMinSize.dispatchEvent(new Event('input',{bubbles:true}));
380
  DOM.returnToPositionBtn.click();
 
381
  }''')
 
 
 
 
 
 
 
382
  self.wait_position(95000)
383
  self.page.wait_for_timeout(600)
384
  self.wait_position(95000)
@@ -407,7 +417,7 @@ class PositionControlTests(unittest.TestCase):
407
  };
408
  })''')
409
  self.page.reload(wait_until='domcontentloaded')
410
- self.page.wait_for_function('positionRestore?.preview && !!window.releaseValidation')
411
  self.assertEqual(self.page.evaluate('findVirtualIndex(getResultScrollTop())'),95000)
412
  self.assertEqual(self.page.locator('#results-container').evaluate('e=>getComputedStyle(e).visibility'),'visible')
413
 
 
43
  self.assertEqual(errors, [])
44
 
45
  def wait_position(self, index):
46
+ self.page.wait_for_function('i=>!positionRestoration.current && !STATE.isLoading && findVirtualIndex(getResultScrollTop())===i && !!STATE.results[i]', arg=index)
47
 
48
  def jump(self, number, key='Enter'):
49
  self.page.locator('#edit-result-position').click()
 
95
  self.page.set_viewport_size({'width':390,'height':844})
96
  self.page.evaluate('STATE.isMobile=true;applyMobileMode();failPosition=true')
97
  self.jump(95001)
98
+ self.page.wait_for_function('positionRestoration.current?.failed')
99
  self.assertTrue(self.page.locator('#load-info .result-position-actions #retry-position-btn').is_visible())
100
  self.assertTrue(self.page.locator('#cancel-position-btn').is_hidden())
101
  self.assertEqual(self.page.locator('#results-container').evaluate('e=>getComputedStyle(e).visibility'),'visible')
 
329
  self.wait_position(0)
330
 
331
  self.page.locator('#sort-select').select_option('name')
332
+ self.page.wait_for_function('!STATE.isLoading && !positionRestoration.current')
333
  second = click_top_immediately()
334
  self.assertEqual(second['before'], [False, False])
335
  self.assertEqual(second['after'], [True, False])
 
364
  self.page.wait_for_timeout(250)
365
  self.assertEqual(self.page.evaluate('positionCalls'),[1])
366
  self.page.locator('#search-input').fill('paging-latest')
367
+ self.page.wait_for_function('STATE.query==="paging-latest" && !STATE.isLoading && !positionRestoration.current')
368
  self.page.evaluate('blockPosition=false;releasePosition()')
369
  self.page.wait_for_timeout(100)
370
  self.wait_position(0)
 
375
  self.page.locator('#restart-position-btn').click()
376
  self.wait_position(0)
377
  self.page.evaluate('''()=>{
378
+ readSearchViewport=async()=>null;
379
+ blockPosition=true;positionCalls=[];
380
  DOM.filterMinSize.value='7';
381
  DOM.filterMinSize.dispatchEvent(new Event('input',{bubbles:true}));
382
  DOM.returnToPositionBtn.click();
383
+ window.explicitReturn=positionRestoration.current;
384
  }''')
385
+ self.page.wait_for_function('!!window.releasePosition')
386
+ self.assertIsNone(self.page.evaluate('sizeFilterTimer'))
387
+ self.assertEqual(self.page.locator('#filter-min-size').input_value(), '')
388
+ self.page.wait_for_timeout(550)
389
+ self.assertTrue(self.page.evaluate('positionRestoration.current === explicitReturn'))
390
+ self.assertEqual(self.page.evaluate('positionCalls'), [1])
391
+ self.page.evaluate('blockPosition=false;releasePosition()')
392
  self.wait_position(95000)
393
  self.page.wait_for_timeout(600)
394
  self.wait_position(95000)
 
417
  };
418
  })''')
419
  self.page.reload(wait_until='domcontentloaded')
420
+ self.page.wait_for_function('positionRestoration.current?.preview && !!window.releaseValidation')
421
  self.assertEqual(self.page.evaluate('findVirtualIndex(getResultScrollTop())'),95000)
422
  self.assertEqual(self.page.locator('#results-container').evaluate('e=>getComputedStyle(e).visibility'),'visible')
423
 
tests/search/browser/test_position_window.py CHANGED
@@ -52,7 +52,7 @@ class PositionWindowTests(unittest.TestCase):
52
  self.assertEqual(errors, [])
53
 
54
  def wait_anchor(self, index, offset=11):
55
- self.page.wait_for_function('''({index,offset})=>!positionRestore && !!resultWindow &&
56
  findVirtualIndex(getResultScrollTop())===index && !!STATE.results[index] &&
57
  Math.abs(getResultScrollTop()-getVirtualOffset(index)-offset)<2''', arg={'index':index,'offset':offset})
58
 
@@ -288,7 +288,7 @@ class PositionWindowTests(unittest.TestCase):
288
  self.page.wait_for_function('!STATE.isLoading')
289
  self.assertEqual(self.page.evaluate('positionPersistence.positions.get(originalWindowKey).index'), 49850)
290
  self.page.evaluate("windowCalls=[];STATE.query='paging-original';doSearch(false,false,true)")
291
- self.assertTrue(self.page.evaluate("!!positionRestore || resultWindow?.generation === 'two'"),
292
  'Returning must validate the invalid window instead of silently restoring generation one')
293
  self.wait_anchor(35050)
294
  self.assertIn(1, self.page.evaluate('windowCalls'))
@@ -375,7 +375,7 @@ class PositionWindowTests(unittest.TestCase):
375
  }''')
376
 
377
  def assert_cached_viewport(self, offset=11):
378
- self.page.wait_for_function('positionRestore?.preview && !!window.releaseWindow')
379
  self.assertTrue(self.page.evaluate('''offset => {
380
  const box=DOM.resultsContainer.getBoundingClientRect();
381
  return findVirtualIndex(getResultScrollTop())===49850 &&
@@ -427,7 +427,7 @@ class PositionWindowTests(unittest.TestCase):
427
  neighbor.check()
428
  self.assertEqual(self.page.evaluate('getSelectedFiles().map(file=>file.filename)'),
429
  ['paging-49850.txt', 'paging-49851.txt'])
430
- self.assertTrue(self.page.evaluate('!!positionRestore.preview'))
431
  self.page.evaluate('releaseWindow()')
432
  self.wait_anchor(49850)
433
  self.assertEqual(self.page.evaluate('resultWindow.generation'), 'two')
@@ -500,7 +500,7 @@ class PositionWindowTests(unittest.TestCase):
500
  !(box.left<count.right && box.right>count.left && box.top<count.bottom && box.bottom>count.top));
501
  }'''))
502
  self.page.locator('#restart-position-btn').click()
503
- self.page.wait_for_function('!positionRestore && !STATE.isLoading && !resultWindow')
504
 
505
  def test_saved_viewport_is_bounded_and_not_used_for_another_anchor(self):
506
  self.persist_viewport()
@@ -509,7 +509,7 @@ class PositionWindowTests(unittest.TestCase):
509
  self.page.wait_for_function('!STATE.isLoading')
510
  self.page.evaluate("resultSnapshots.snapshots.clear();positionPersistence.positions.get(originalWindowKey).anchorId='different';windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")
511
  self.page.wait_for_function('!!window.releaseWindow')
512
- self.assertFalse(self.page.evaluate('!!positionRestore.preview'))
513
  self.page.evaluate('releaseWindow()')
514
  self.wait_anchor(49850)
515
 
 
52
  self.assertEqual(errors, [])
53
 
54
  def wait_anchor(self, index, offset=11):
55
+ self.page.wait_for_function('''({index,offset})=>!positionRestoration.current && !!resultWindow &&
56
  findVirtualIndex(getResultScrollTop())===index && !!STATE.results[index] &&
57
  Math.abs(getResultScrollTop()-getVirtualOffset(index)-offset)<2''', arg={'index':index,'offset':offset})
58
 
 
288
  self.page.wait_for_function('!STATE.isLoading')
289
  self.assertEqual(self.page.evaluate('positionPersistence.positions.get(originalWindowKey).index'), 49850)
290
  self.page.evaluate("windowCalls=[];STATE.query='paging-original';doSearch(false,false,true)")
291
+ self.assertTrue(self.page.evaluate("!!positionRestoration.current || resultWindow?.generation === 'two'"),
292
  'Returning must validate the invalid window instead of silently restoring generation one')
293
  self.wait_anchor(35050)
294
  self.assertIn(1, self.page.evaluate('windowCalls'))
 
375
  }''')
376
 
377
  def assert_cached_viewport(self, offset=11):
378
+ self.page.wait_for_function('positionRestoration.current?.preview && !!window.releaseWindow')
379
  self.assertTrue(self.page.evaluate('''offset => {
380
  const box=DOM.resultsContainer.getBoundingClientRect();
381
  return findVirtualIndex(getResultScrollTop())===49850 &&
 
427
  neighbor.check()
428
  self.assertEqual(self.page.evaluate('getSelectedFiles().map(file=>file.filename)'),
429
  ['paging-49850.txt', 'paging-49851.txt'])
430
+ self.assertTrue(self.page.evaluate('!!positionRestoration.current.preview'))
431
  self.page.evaluate('releaseWindow()')
432
  self.wait_anchor(49850)
433
  self.assertEqual(self.page.evaluate('resultWindow.generation'), 'two')
 
500
  !(box.left<count.right && box.right>count.left && box.top<count.bottom && box.bottom>count.top));
501
  }'''))
502
  self.page.locator('#restart-position-btn').click()
503
+ self.page.wait_for_function('!positionRestoration.current && !STATE.isLoading && !resultWindow')
504
 
505
  def test_saved_viewport_is_bounded_and_not_used_for_another_anchor(self):
506
  self.persist_viewport()
 
509
  self.page.wait_for_function('!STATE.isLoading')
510
  self.page.evaluate("resultSnapshots.snapshots.clear();positionPersistence.positions.get(originalWindowKey).anchorId='different';windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")
511
  self.page.wait_for_function('!!window.releaseWindow')
512
+ self.assertFalse(self.page.evaluate('!!positionRestoration.current.preview'))
513
  self.page.evaluate('releaseWindow()')
514
  self.wait_anchor(49850)
515
 
tests/search/browser/test_recent_search_pages.py CHANGED
@@ -52,10 +52,10 @@ class RecentSearchPageTests(unittest.TestCase):
52
  self.page.evaluate("STATE.query='paging-other';doSearch()")
53
  self.page.wait_for_function('!STATE.isLoading')
54
  self.page.evaluate("resultSnapshots.snapshots.clear();positionPersistence.viewports.clear();positionPersistence.recentPages.clear();windowCalls=[];windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")
55
- self.page.wait_for_function('positionRestore?.preview && !!window.releaseWindow')
56
 
57
  def wait_cached(self, index):
58
- self.page.wait_for_function('''index=>!!positionRestore?.preview && !!STATE.results[index] &&
59
  findVirtualIndex(getResultScrollTop())===index &&
60
  Math.abs(getResultScrollTop()-getVirtualOffset(index)-11)<2''', arg=index)
61
 
@@ -118,7 +118,7 @@ class RecentSearchPageTests(unittest.TestCase):
118
 
119
  # Hold the demanded page as well, so we check the handoff while the row is still a hole.
120
  self.page.evaluate('windowStall=751;releaseWindow()')
121
- self.page.wait_for_function('!positionRestore')
122
  anchor = self.page.evaluate('''index=>({index:findVirtualIndex(getResultScrollTop()),
123
  offset:getResultScrollTop()-getVirtualOffset(index),loaded:!!STATE.results[index],
124
  generation:resultWindow.generation})''', index)
@@ -154,7 +154,7 @@ class RecentSearchPageTests(unittest.TestCase):
154
  self.assertFalse(self.page.evaluate('!!STATE.results[25050]'),
155
  'A corrupt disk record must not enter the preview')
156
  self.page.evaluate('windowStall=0;releaseWindow()')
157
- self.page.wait_for_function('!positionRestore')
158
  self.fixture.jump(25050)
159
  self.fixture.wait_anchor(25050)
160
  self.assertIn(251, self.page.evaluate('windowCalls'))
@@ -189,7 +189,7 @@ class RecentSearchPageTests(unittest.TestCase):
189
  };
190
  });''')
191
  self.page.reload(wait_until='domcontentloaded')
192
- self.page.wait_for_function('positionRestore?.preview && !!window.releaseWindow')
193
  for index in [25050,35050,49850,35050,25050]:
194
  self.fixture.jump(index)
195
  self.wait_cached(index)
 
52
  self.page.evaluate("STATE.query='paging-other';doSearch()")
53
  self.page.wait_for_function('!STATE.isLoading')
54
  self.page.evaluate("resultSnapshots.snapshots.clear();positionPersistence.viewports.clear();positionPersistence.recentPages.clear();windowCalls=[];windowStall=1;STATE.query='paging-original';doSearch(false,false,true)")
55
+ self.page.wait_for_function('positionRestoration.current?.preview && !!window.releaseWindow')
56
 
57
  def wait_cached(self, index):
58
+ self.page.wait_for_function('''index=>!!positionRestoration.current?.preview && !!STATE.results[index] &&
59
  findVirtualIndex(getResultScrollTop())===index &&
60
  Math.abs(getResultScrollTop()-getVirtualOffset(index)-11)<2''', arg=index)
61
 
 
118
 
119
  # Hold the demanded page as well, so we check the handoff while the row is still a hole.
120
  self.page.evaluate('windowStall=751;releaseWindow()')
121
+ self.page.wait_for_function('!positionRestoration.current')
122
  anchor = self.page.evaluate('''index=>({index:findVirtualIndex(getResultScrollTop()),
123
  offset:getResultScrollTop()-getVirtualOffset(index),loaded:!!STATE.results[index],
124
  generation:resultWindow.generation})''', index)
 
154
  self.assertFalse(self.page.evaluate('!!STATE.results[25050]'),
155
  'A corrupt disk record must not enter the preview')
156
  self.page.evaluate('windowStall=0;releaseWindow()')
157
+ self.page.wait_for_function('!positionRestoration.current')
158
  self.fixture.jump(25050)
159
  self.fixture.wait_anchor(25050)
160
  self.assertIn(251, self.page.evaluate('windowCalls'))
 
189
  };
190
  });''')
191
  self.page.reload(wait_until='domcontentloaded')
192
+ self.page.wait_for_function('positionRestoration.current?.preview && !!window.releaseWindow')
193
  for index in [25050,35050,49850,35050,25050]:
194
  self.fixture.jump(index)
195
  self.wait_cached(index)
tests/search/browser/test_search_positions.py CHANGED
@@ -33,7 +33,7 @@ class SearchPositionTests(unittest.TestCase):
33
  self.fixture.tearDown()
34
 
35
  def assert_position(self):
36
- self.page.wait_for_function("!positionRestore && !STATE.isLoading && STATE.query==='paging-original'")
37
  self.page.wait_for_function('''saved => {
38
  const index=findVirtualIndex(DOM.resultsContainer.scrollTop);
39
  return getResultStableId(STATE.results[index])===saved.anchorId &&
@@ -78,7 +78,7 @@ class SearchPositionTests(unittest.TestCase):
78
  # Accept either position restoration or a fresh search, but never a blank
79
  # startup or an unhandled rejection. Surface errors without a long timeout.
80
  self.page.wait_for_function('''() => window.viewportReloadErrors?.length ||
81
- (STATE.query==='paging-original' && !STATE.isLoading && !positionRestore &&
82
  STATE.results.some(record=>record?.File==='paging-125'||record?.File==='paging-0'))''')
83
  self.assertEqual(self.page.evaluate('window.viewportReloadErrors'), [])
84
  self.assertEqual(self.fixture.errors, [])
@@ -226,7 +226,7 @@ class SearchPositionTests(unittest.TestCase):
226
  }''')
227
  self.page.wait_for_function('!!window.releaseRestore')
228
  self.page.evaluate("STATE.query='paging-latest'; doSearch(); releaseRestore()")
229
- self.page.wait_for_function("STATE.query==='paging-latest' && !STATE.isLoading && !positionRestore")
230
  self.assertEqual(self.page.evaluate('displayedSearchView.key'), self.page.evaluate('getSearchViewKey()'))
231
  self.assertEqual(self.page.evaluate('positionPersistence.positions.get(' + repr(self.saved['key']) + ').anchorId'), self.saved['anchorId'])
232
  self.assertEqual(self.fixture.errors, [])
 
33
  self.fixture.tearDown()
34
 
35
  def assert_position(self):
36
+ self.page.wait_for_function("!positionRestoration.current && !STATE.isLoading && STATE.query==='paging-original'")
37
  self.page.wait_for_function('''saved => {
38
  const index=findVirtualIndex(DOM.resultsContainer.scrollTop);
39
  return getResultStableId(STATE.results[index])===saved.anchorId &&
 
78
  # Accept either position restoration or a fresh search, but never a blank
79
  # startup or an unhandled rejection. Surface errors without a long timeout.
80
  self.page.wait_for_function('''() => window.viewportReloadErrors?.length ||
81
+ (STATE.query==='paging-original' && !STATE.isLoading && !positionRestoration.current &&
82
  STATE.results.some(record=>record?.File==='paging-125'||record?.File==='paging-0'))''')
83
  self.assertEqual(self.page.evaluate('window.viewportReloadErrors'), [])
84
  self.assertEqual(self.fixture.errors, [])
 
226
  }''')
227
  self.page.wait_for_function('!!window.releaseRestore')
228
  self.page.evaluate("STATE.query='paging-latest'; doSearch(); releaseRestore()")
229
+ self.page.wait_for_function("STATE.query==='paging-latest' && !STATE.isLoading && !positionRestoration.current")
230
  self.assertEqual(self.page.evaluate('displayedSearchView.key'), self.page.evaluate('getSearchViewKey()'))
231
  self.assertEqual(self.page.evaluate('positionPersistence.positions.get(' + repr(self.saved['key']) + ').anchorId'), self.saved['anchorId'])
232
  self.assertEqual(self.fixture.errors, [])
tests/search/paging/result_window_contracts.mjs CHANGED
@@ -112,7 +112,7 @@ test('host keeps prefetch failures bounded and generation changes invalidate eve
112
  const window = {key: 'query', total: 1000, query: {pageSize: 1}, controller: new AbortController(), pages: new Set(), failures: new Map()};
113
  let error = new Error('temporary'), renders = 0, statuses = 0;
114
  const cache = new Map([['old-page', {}]]), stale = new Map([['query', {}]]);
115
- const c = fixture(['loadResultWindowPage'], {resultWindow: window, positionRestore: null,
116
  searchResponseStore: {cache}, resultSnapshots: {remove: key => stale.delete(key)}, STATE: {_pageCache: {1:[{}]} },
117
  resultWindowCurrent: () => true, requestResultWindowPage: async () => {throw error;},
118
  updateResultWindowStatus() {statuses++;}, scheduleVirtualRender() {renders++;},
 
112
  const window = {key: 'query', total: 1000, query: {pageSize: 1}, controller: new AbortController(), pages: new Set(), failures: new Map()};
113
  let error = new Error('temporary'), renders = 0, statuses = 0;
114
  const cache = new Map([['old-page', {}]]), stale = new Map([['query', {}]]);
115
+ const c = fixture(['loadResultWindowPage'], {resultWindow: window, positionRestoration: {current: null},
116
  searchResponseStore: {cache}, resultSnapshots: {remove: key => stale.delete(key)}, STATE: {_pageCache: {1:[{}]} },
117
  resultWindowCurrent: () => true, requestResultWindowPage: async () => {throw error;},
118
  updateResultWindowStatus() {statuses++;}, scheduleVirtualRender() {renders++;},
tests/search/reader-navigation/routing_contracts.mjs CHANGED
@@ -34,7 +34,8 @@ function fixture(route = '', overrides = {}) {
34
  setSidebarExpanded(value){dom.leftSidebar.classList.toggle('expanded-wide',value);},
35
  getSearchViewKey:()=>JSON.stringify([state.mode,state.repo,state.query,state.filterExtensions,state.filterFolderSelfs,state.filterFolderSubtrees]),
36
  saveSearchViewSnapshot:()=>events.push(['snapshot',state.query]),prepareRouteTransitionResults(){},
37
- searchInputController:{invalidateVisit:()=>events.push(['intent'])},cancelPendingSearchControls:()=>events.push(['controls']),
 
38
  readerReturnPosition:{invalidate:()=>events.push(['reader'])},cancelActiveSearch:()=>{events.push(['cancel']);return true;},
39
  cancelPositionRestore:()=>events.push(['position']),renderBrowser:(path,id)=>events.push(['browser',path,id]),
40
  retainFilterRenderingForRoute:id=>events.push(['retain',id]),searchWithInitialFallback:()=>events.push(['search']),
@@ -151,26 +152,45 @@ test('same-view path-only navigation retains active work and geometry; changed v
151
 
152
  if (source === current) {
153
  test('size controls preserve the exact restored minimum when editing only the maximum', () => {
154
- const f = fixture('Test?min_size=1500B&max_size=1MB');
155
  vm.runInContext(fs.readFileSync('static/search/results/presentation/size-format.js', 'utf8'), f.c);
156
- let pending;
157
- Object.assign(f.c, {
158
- sizeFilterTimer: null, setTimeout(fn) { pending = fn; return 1; }, clearTimeout() {},
159
- doFilterSearch: () => f.c.syncStateToURL(),
 
 
 
 
 
 
 
 
 
 
160
  });
161
- for (const field of ['filterMinSize', 'filterMaxSize', 'filterMinUnit', 'filterMaxUnit']) {
162
- f.dom[field].addEventListener = (type, fn) => { f.dom[field][type] = fn; };
163
- }
164
- for (const name of ['sizeInputToBytes', 'applyPendingSizeFilters', 'setupSizeFilterControls']) {
165
- const match = source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));
166
- assert.ok(match, name); vm.runInContext(match[0], f.c);
167
- }
168
  f.c.router.apply();
169
  assert.equal(f.state.filterMinSize, 1500);
170
  assert.deepEqual([f.dom.filterMinSize.value, f.dom.filterMinUnit.value], ['1500', 'B']);
171
  assert.deepEqual([f.dom.filterMaxSize.value, f.dom.filterMaxUnit.value], ['1', 'MB']);
172
- f.c.setupSizeFilterControls();
173
- f.dom.filterMaxSize.value = '2'; f.dom.filterMaxSize.input(); pending();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  assert.deepEqual([f.state.filterMinSize, f.state.filterMaxSize], [1500, 2097152]);
175
  const params = new URLSearchParams(pages ? f.location.hash.split('?')[1] : f.location.search);
176
  assert.equal(f.c.parseSizeStr(params.get('min_size')), 1500);
 
34
  setSidebarExpanded(value){dom.leftSidebar.classList.toggle('expanded-wide',value);},
35
  getSearchViewKey:()=>JSON.stringify([state.mode,state.repo,state.query,state.filterExtensions,state.filterFolderSelfs,state.filterFolderSubtrees]),
36
  saveSearchViewSnapshot:()=>events.push(['snapshot',state.query]),prepareRouteTransitionResults(){},
37
+ searchInputController:{invalidateVisit:()=>events.push(['intent']), cancelPending:()=>events.push(['controls']), syncSize(){}},
38
+ cancelPendingSearchControls:()=>events.push(['controls']), // pre-extraction baseline
39
  readerReturnPosition:{invalidate:()=>events.push(['reader'])},cancelActiveSearch:()=>{events.push(['cancel']);return true;},
40
  cancelPositionRestore:()=>events.push(['position']),renderBrowser:(path,id)=>events.push(['browser',path,id]),
41
  retainFilterRenderingForRoute:id=>events.push(['retain',id]),searchWithInitialFallback:()=>events.push(['search']),
 
152
 
153
  if (source === current) {
154
  test('size controls preserve the exact restored minimum when editing only the maximum', () => {
155
+ const f = fixture('Test?ext=txt&min_size=1500B&max_size=1MB');
156
  vm.runInContext(fs.readFileSync('static/search/results/presentation/size-format.js', 'utf8'), f.c);
157
+ for (const path of ['domain/ownership.js', 'application/controller.js'])
158
+ vm.runInContext(fs.readFileSync('static/search/input/' + path, 'utf8'), f.c);
159
+ const timers = new Map();
160
+ let next = 0, controlState, filterRuns = 0;
161
+ for (const name of ['searchInput', 'filterMinSize', 'filterMaxSize', 'filterMinUnit', 'filterMaxUnit'])
162
+ f.dom[name] = Object.assign(new EventTarget(), {value: ''});
163
+ const controller = f.c.VoiceOfMLSearchInput.create({input: f.dom.searchInput, navigation: new EventTarget(),
164
+ ownership: f.c.VoiceOfMLSearchInputOwnership,
165
+ clock: {setTimeout(fn, ms) {timers.set(++next, {fn, ms}); return next;}, clearTimeout(id) {timers.delete(id);}},
166
+ canSubmit: () => !f.c.readerHost.overlay, onState: state => {controlState = state;},
167
+ filterSearch: () => {filterRuns++; f.c.syncStateToURL();},
168
+ size: {min: f.dom.filterMinSize, max: f.dom.filterMaxSize, minUnit: f.dom.filterMinUnit, maxUnit: f.dom.filterMaxUnit,
169
+ read: () => [f.state.filterMinSize, f.state.filterMaxSize], format: f.c.bytesToDisplay,
170
+ commit: (min, max) => {f.state.filterMinSize = min; f.state.filterMaxSize = max;}}
171
  });
172
+ f.c.searchInputController = controller;
173
+ controller.mount();
 
 
 
 
 
174
  f.c.router.apply();
175
  assert.equal(f.state.filterMinSize, 1500);
176
  assert.deepEqual([f.dom.filterMinSize.value, f.dom.filterMinUnit.value], ['1500', 'B']);
177
  assert.deepEqual([f.dom.filterMaxSize.value, f.dom.filterMaxUnit.value], ['1', 'MB']);
178
+ f.dom.filterMaxSize.value = '2'; f.dom.filterMaxSize.dispatchEvent(new Event('input'));
179
+ const pendingSize = controlState.sizeTimer;
180
+ controller.scheduleFilter();
181
+ const pendingFilter = controlState.filterTimer;
182
+ f.c.router.apply(true);
183
+ assert.equal(f.dom.filterMaxSize.value, '2');
184
+ assert.equal(controlState.sizeTimer, pendingSize);
185
+ assert.equal(controlState.filterTimer, pendingFilter);
186
+ assert.equal(timers.get(pendingSize).ms, 500);
187
+ assert.equal(timers.get(pendingFilter).ms, 200);
188
+ f.c.readerHost.overlay = {};
189
+ timers.get(pendingFilter).fn();
190
+ assert.equal(controlState.filterTimer, null);
191
+ assert.equal(filterRuns, 1, 'Reader blocks query input but not a committed filter search');
192
+ f.c.readerHost.overlay = null;
193
+ timers.get(pendingSize).fn();
194
  assert.deepEqual([f.state.filterMinSize, f.state.filterMaxSize], [1500, 2097152]);
195
  const params = new URLSearchParams(pages ? f.location.hash.split('?')[1] : f.location.search);
196
  assert.equal(f.c.parseSizeStr(params.get('min_size')), 1500);
tests/search/reader-navigation/test_search_history_races.mjs CHANGED
@@ -102,6 +102,8 @@ test('resume retains joined ownership and ignores the previous connection body',
102
  assert.equal(f.timers.size,0);assert.equal(entry.listeners.size,0);
103
  });
104
 
 
 
105
  function inputFixture({submit = () => {}, schedule = () => {}, early} = {}) {
106
  const context = vm.createContext({});
107
  for (const file of ['domain/ownership.js', 'application/controller.js'])
@@ -109,11 +111,16 @@ function inputFixture({submit = () => {}, schedule = () => {}, early} = {}) {
109
  const input = new EventTarget(), navigation = new EventTarget(), callbacks = new Map(), cancelled = [];
110
  input.value = 'old draft';
111
  if (early) input._earlySearchInput = early;
112
- const c = {input, navigation, callbacks, cancelled, href: 'https://example.test/A', entry: 'entry-A', key: 'A', syncs: 0};
 
 
 
 
113
  let next = 0;
114
- c.controller = context.VoiceOfMLSearchInput.create({input, navigation,
115
  ownership: context.VoiceOfMLSearchInputOwnership,
116
- clock: {setTimeout(fn, delay) { assert.equal(delay, 100); callbacks.set(++next, fn); schedule(); return next; },
 
117
  clearTimeout(id) { cancelled.push(id); }},
118
  getHref: () => c.href, getEntryKey: () => c.entry, getViewKey: () => c.key,
119
  syncInput: () => c.syncs++, canSubmit: () => !c.readerOpen, submit, onState: state => {
@@ -204,22 +211,13 @@ test('online first page prefetch starts page two immediately and path-only reuse
204
  assert.equal(group.signal.aborted, false);
205
  });
206
 
207
- test('position abort reentry retains the replacement window and restoration', () => {
208
- const old = new AbortController(), newer = {controller: new AbortController()};
209
- const c = fixture(['cancelPositionRestore'], {positionEntryId: 0,
210
- resultWindow: {controller: old}, positionRestore: {controller: new AbortController()},
211
- STATE: {isLoading: true}, cancelSnapshotClone() {}, updateResultWindowStatus() {}, showPositionRestoreStatus() {}});
212
- old.signal.addEventListener('abort', () => { c.resultWindow = newer; c.positionRestore = newer; });
213
- c.cancelPositionRestore();
214
- assert.equal(c.resultWindow, newer);
215
- assert.equal(c.positionRestore, newer);
216
- assert.equal(newer.controller.signal.aborted, false);
217
- });
218
-
219
  test('filter change incorporates the pending completed query before cancelling debounce', () => {
220
- const c = fixture(['prepareFilterChange'], {searchTimer: 1, searchComposing: false,
221
- DOM: {searchInput: {value: ' current draft '}}, STATE: {query: 'old', page: 3, results: [1]},
222
- applyPendingSizeFilters() {}, cancelPendingSearchControls() { c.searchTimer = null; },
 
 
 
223
  saveSearchViewSnapshot() { assert.equal(c.STATE.query, 'old'); }});
224
  c.prepareFilterChange(true);
225
  assert.equal(c.STATE.query, 'current draft');
@@ -229,12 +227,16 @@ test('filter change incorporates the pending completed query before cancelling d
229
 
230
  test('filter change preserves composing and overlong drafts without submitting them', () => {
231
  for (const [composing, value] of [[true, 'composition'], [false, 'x'.repeat(257)]]) {
232
- const c = fixture(['prepareFilterChange'], {searchTimer: 1, searchComposing: composing,
233
- DOM: {searchInput: {value}}, STATE: {query: 'old'}, applyPendingSizeFilters() {},
234
- cancelPendingSearchControls() {}, saveSearchViewSnapshot() {}});
 
 
 
 
235
  c.prepareFilterChange(false);
236
  assert.equal(c.STATE.query, 'old');
237
- assert.equal(c.DOM.searchInput.value, value);
238
  }
239
  });
240
 
@@ -427,7 +429,7 @@ test('published state is a detached narrow projection without mutable ownership'
427
  const queries = [], snapshots = [];
428
  const c = inputFixture({submit: query => queries.push(query)});
429
  c.onState = state => {
430
- assert.deepEqual(Object.keys(state).sort(), ['composing', 'dirty', 'ready', 'timer']);
431
  snapshots.push(state);
432
  };
433
  c.controller.captureDraft();
@@ -466,9 +468,11 @@ test('app adapter waits for startup and delegates submit with history options',
466
  let callback;
467
  navigation.setTimeout = fn => { callback = fn; return 42; };
468
  navigation.clearTimeout = () => {};
469
- const c = fixture(['setupSearchInput', 'initialSearchDraftIsCurrent', 'finishInitialSearchInput', 'cancelPendingSearchControls'], {
470
  VoiceOfMLSearchInput: modules.VoiceOfMLSearchInput, VoiceOfMLSearchInputOwnership: modules.VoiceOfMLSearchInputOwnership,
471
- DOM: {searchInput: input}, window: navigation, location: new URL('https://example.test/A'),
 
 
472
  readerHost: {overlay:null}, appliedSearchRoute: '/A',
473
  routeInitialized: true, getSearchViewKey: () => 'A', syncSearchInputState() {}, clearTimeout() {},
474
  filterSearchTimer: null, sizeFilterTimer: null,
@@ -492,12 +496,38 @@ test('app adapter waits for startup and delegates submit with history options',
492
  assert.equal(c.searchComposing, true);
493
  input.dispatchEvent(new Event('compositionend'));
494
  assert.equal(c.searchComposing, false);
495
- c.cancelPendingSearchControls();
496
  callback();
497
  assert.equal(c.searchTimer, null);
498
  assert.equal(queries.length, 1);
499
  });
500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501
  test('input dependency order, source shell, build resources and SW agree without delaying inline capture', async () => {
502
  const precache = await installSourcePrecachePaths('/static/');
503
  const paths = ['search/input/domain/ownership.js', 'search/input/application/controller.js'];
 
102
  assert.equal(f.timers.size,0);assert.equal(entry.listeners.size,0);
103
  });
104
 
105
+ const sizeControl = value => Object.assign(new EventTarget(), {value});
106
+
107
  function inputFixture({submit = () => {}, schedule = () => {}, early} = {}) {
108
  const context = vm.createContext({});
109
  for (const file of ['domain/ownership.js', 'application/controller.js'])
 
111
  const input = new EventTarget(), navigation = new EventTarget(), callbacks = new Map(), cancelled = [];
112
  input.value = 'old draft';
113
  if (early) input._earlySearchInput = early;
114
+ const c = {input, navigation, callbacks, cancelled, href: 'https://example.test/A', entry: 'entry-A', key: 'A', syncs: 0,
115
+ deadlines: new Map(), bounds: [null, null], filterSearches: []};
116
+ c.size = {min: sizeControl(''), max: sizeControl(''), minUnit: sizeControl('MB'), maxUnit: sizeControl('MB'),
117
+ read: () => c.bounds, commit: (...bounds) => { c.bounds = bounds; },
118
+ format: bytes => ({value: bytes === null ? '' : String(bytes), unit: bytes === null ? 'MB' : 'B'})};
119
  let next = 0;
120
+ c.controller = context.VoiceOfMLSearchInput.create({input, navigation, size: c.size,
121
  ownership: context.VoiceOfMLSearchInputOwnership,
122
+ filterSearch: clear => c.filterSearches.push(clear),
123
+ clock: {setTimeout(fn, delay) { callbacks.set(++next, fn); c.deadlines.set(next, delay); schedule(); return next; },
124
  clearTimeout(id) { cancelled.push(id); }},
125
  getHref: () => c.href, getEntryKey: () => c.entry, getViewKey: () => c.key,
126
  syncInput: () => c.syncs++, canSubmit: () => !c.readerOpen, submit, onState: state => {
 
211
  assert.equal(group.signal.aborted, false);
212
  });
213
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  test('filter change incorporates the pending completed query before cancelling debounce', () => {
215
+ const i = inputFixture();
216
+ i.controller.finishStartup(true);
217
+ i.input.value = ' current draft ';
218
+ i.emit('input');
219
+ const c = fixture(['prepareFilterChange'], {searchInputController: i.controller,
220
+ STATE: {query: 'old', page: 3, results: [1]},
221
  saveSearchViewSnapshot() { assert.equal(c.STATE.query, 'old'); }});
222
  c.prepareFilterChange(true);
223
  assert.equal(c.STATE.query, 'current draft');
 
227
 
228
  test('filter change preserves composing and overlong drafts without submitting them', () => {
229
  for (const [composing, value] of [[true, 'composition'], [false, 'x'.repeat(257)]]) {
230
+ const i = inputFixture();
231
+ i.controller.finishStartup(true);
232
+ if (composing) i.emit('compositionstart');
233
+ i.input.value = value;
234
+ i.emit('input');
235
+ const c = fixture(['prepareFilterChange'], {searchInputController: i.controller,
236
+ STATE: {query: 'old'}, saveSearchViewSnapshot() {}});
237
  c.prepareFilterChange(false);
238
  assert.equal(c.STATE.query, 'old');
239
+ assert.equal(i.input.value, value);
240
  }
241
  });
242
 
 
429
  const queries = [], snapshots = [];
430
  const c = inputFixture({submit: query => queries.push(query)});
431
  c.onState = state => {
432
+ assert.deepEqual(Object.keys(state).sort(), ['composing', 'dirty', 'filterTimer', 'ready', 'sizeTimer', 'timer']);
433
  snapshots.push(state);
434
  };
435
  c.controller.captureDraft();
 
468
  let callback;
469
  navigation.setTimeout = fn => { callback = fn; return 42; };
470
  navigation.clearTimeout = () => {};
471
+ const c = fixture(['setupSearchInput', 'initialSearchDraftIsCurrent', 'finishInitialSearchInput'], {
472
  VoiceOfMLSearchInput: modules.VoiceOfMLSearchInput, VoiceOfMLSearchInputOwnership: modules.VoiceOfMLSearchInputOwnership,
473
+ DOM: {searchInput: input, filterMinSize: sizeControl(''), filterMaxSize: sizeControl(''),
474
+ filterMinUnit: sizeControl('MB'), filterMaxUnit: sizeControl('MB')},
475
+ window: navigation, location: new URL('https://example.test/A'), bytesToDisplay() {},
476
  readerHost: {overlay:null}, appliedSearchRoute: '/A',
477
  routeInitialized: true, getSearchViewKey: () => 'A', syncSearchInputState() {}, clearTimeout() {},
478
  filterSearchTimer: null, sizeFilterTimer: null,
 
496
  assert.equal(c.searchComposing, true);
497
  input.dispatchEvent(new Event('compositionend'));
498
  assert.equal(c.searchComposing, false);
499
+ c.searchInputController.cancelPending();
500
  callback();
501
  assert.equal(c.searchTimer, null);
502
  assert.equal(queries.length, 1);
503
  });
504
 
505
+ test('restore retires both filter slots without rescheduling the query or consuming a discarded bound', () => {
506
+ const queries = [], c = inputFixture({submit: query => queries.push(query)});
507
+ c.controller.finishStartup(true);
508
+ c.emit('input');
509
+ c.controller.scheduleFilter();
510
+ c.size.min.value = '7';
511
+ c.size.min.dispatchEvent(new Event('input'));
512
+ const {timer, filterTimer, sizeTimer} = c.state;
513
+ assert.deepEqual([timer, filterTimer, sizeTimer].map(id => c.deadlines.get(id)), [100, 200, 500]);
514
+ c.controller.cancelPending(true);
515
+ assert.deepEqual([c.state.timer, c.state.filterTimer, c.state.sizeTimer], [timer, null, null]);
516
+ assert.equal(c.size.min.value, '');
517
+ c.size.max.value = '2';
518
+ c.size.max.dispatchEvent(new Event('input'));
519
+ const replacement = c.state.sizeTimer;
520
+ c.callbacks.get(filterTimer)();
521
+ c.callbacks.get(sizeTimer)();
522
+ assert.equal(c.state.sizeTimer, replacement);
523
+ assert.deepEqual(c.filterSearches, []);
524
+ c.callbacks.get(timer)();
525
+ assert.deepEqual(queries, ['old draft']);
526
+ c.callbacks.get(replacement)();
527
+ assert.deepEqual(c.bounds, [null, 2097152]);
528
+ assert.deepEqual(c.filterSearches, [true]);
529
+ });
530
+
531
  test('input dependency order, source shell, build resources and SW agree without delaying inline capture', async () => {
532
  const precache = await installSourcePrecachePaths('/static/');
533
  const paths = ['search/input/domain/ownership.js', 'search/input/application/controller.js'];
tests/search/session/restoration_contracts.mjs CHANGED
@@ -6,11 +6,13 @@ import {installClassicSearchModules} from '../../support/classic_search_modules.
6
 
7
  const source = fs.readFileSync('static/app.js', 'utf8');
8
  const key = JSON.stringify({pageSize: 2});
9
- const position = {version: 1, key, index: 4, offset: 7, anchorId: 'r4', loadedPage: 3, savedAt: 1};
 
 
10
  const page = (number, generation = 'A', total = 12) => ({page: number, page_size: 2, total, generation,
11
  results: Array.from({length: Math.min(2, Math.max(0, total - (number - 1) * 2))}, (_, i) => ({id: 'r' + ((number - 1) * 2 + i)}))});
12
  const deferred = () => {let resolve, reject; const promise = new Promise((yes, no) => {resolve = yes; reject = no;}); return {promise, resolve, reject};};
13
- const flush = async () => {for (let i = 0; i < 16; i++) await Promise.resolve();};
14
 
15
  // Run the real host composition as well as the coordinator. All geometry stays
16
  // behind the same ports as production; tests can replace the live page hook.
@@ -19,37 +21,50 @@ function fixture() {
19
  const c = vm.createContext({AbortController, TextEncoder: class extends TextEncoder {
20
  encode(value) {encoded.push(value); return super.encode(value);}
21
  }, setTimeout(fn, ms) {assert.equal(ms, 30); timers.push(fn);},
22
- positionRestore: null, positionEntryId: 0, resultWindow: null, searchIntentId: 0, searchId: 0,
23
  STATE: {isLoading: false, results: []}, VSCROLL: {isDraggingThumb: false, estimatedHeight: 40},
24
  readerHost: {overlay: null}, getSearchViewKey: () => key,
25
- positionPersistence: {getPosition: () => position}, validSearchPosition: () => true,
26
- cancelPendingSearchControls() {events.push('controls');}, cancelActiveSearch() {events.push('active'); return true;},
27
- cancelSnapshotClone() {events.push('clone');}, updateResultWindowStatus() {events.push('window');},
28
  setReturnPositionTarget() {events.push('target');}, resetPagingRecovery() {events.push('paging');},
29
  showPositionRestoreStatus(message, retry) {events.push(['status', message, retry]);},
30
  readSearchViewport: async () => null,
31
  fetchPositionPageWithRecovery: async (query, number, signal, anchorId) => {
32
  calls.push({query, number, signal, anchorId}); return {...page(number), ...(anchorId ? {anchor_index: 4} : {})};
33
  },
34
- showSavedSearchViewport(viewport, saved, task) {events.push('preview'); if (viewport) task.preview = true;},
35
  captureReaderReturnScroll: () => ({index: 4, offset: 7}), getResultStableId: record => record?.id || '',
36
  applyValidatedSearchViewport(snapshot) {events.push('apply'); c.snapshot = snapshot; c.STATE.isLoading = false;},
37
- restoreSearchViewSnapshot(k) {events.push('restore'); c.snapshot = store.snapshots.get(k); c.STATE.isLoading = false;},
 
 
 
 
 
 
 
 
 
 
 
38
  resetPositionControlScroll() {events.push('reset-controls');}, showToast(message) {events.push(['toast', message]);}
39
  });
40
  installClassicSearchModules(process.cwd(), c);
41
  const store = c.VoiceOfMLResultSnapshots.create({});
42
- c.resultSnapshots = {
 
43
  putRestored(k, snapshot) {store.putRestored(k, snapshot); events.push('put');},
44
  trim() {store.trim(); events.push('trim');}
45
  };
46
  c.validatePositionWindowPage = (...args) => c.VoiceOfMLSearchWindowPage.validate(...args);
47
  vm.runInContext(source.match(/^const positionRestoration = VoiceOfMLPositionRestoration.create\(\{[^]*?^\}\);/m)[0], c);
48
- for (const name of ['tryRestoreSearchPosition', 'cancelPositionRestore'])
49
- vm.runInContext(source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'))[0], c);
50
- const make = (previous, saved = position) => c.VoiceOfMLPositionRestoration.createTask({key, position: saved, previous});
51
- const run = (task, viewport = null) => {c.positionRestore = task; return vm.runInContext('positionRestoration', c).run(task, viewport);};
52
- return {c, calls, events, encoded, timers, make, run};
 
 
53
  }
54
 
55
  test('authoritative restore trims the exact sparse budget without serializing the holes', async () => {
@@ -58,7 +73,7 @@ test('authoritative restore trims the exact sparse budget without serializing th
58
  total: 50_000, generation: '版本', anchor_index: ${index}, results: [0, 1].map(offset => ({
59
  id: 'r' + ((page - 1) * 2 + offset), File: '书📚', Folder: ['路径']
60
  }))})`, f.c);
61
- await f.run(f.make(null, {...position, index, anchorId: 'r' + index, loadedPage: 25_000}));
62
  const {bytes, ...envelope} = f.c.snapshot;
63
  assert.equal(bytes, new TextEncoder().encode(JSON.stringify(envelope)).length + 256);
64
  assert.equal(envelope.results.length, 50_000);
@@ -72,32 +87,31 @@ test('authoritative restore trims the exact sparse budget without serializing th
72
  test('restoration retries retain lookup and partial-neighbor buffer identity without duplicate rendering', async () => {
73
  const f = fixture(), original = f.c.fetchPositionPageWithRecovery;
74
  f.c.fetchPositionPageWithRecovery = (...args) => args[1] === 3 ? Promise.reject(new Error('offline')) : original(...args);
75
- const first = f.make(); await f.run(first);
76
  assert.equal(first.failed, true); assert.deepEqual([...first.ready.keys()], [1, 2, 4]);
77
  assert.equal(f.c.snapshot, undefined); assert.equal(f.events.includes('restore'), false);
78
- const retry = f.make(first);
79
- assert.equal(retry.ready, first.ready); assert.equal(retry.lookup, first.lookup);
80
  f.calls.length = 0; f.c.fetchPositionPageWithRecovery = original;
81
- await f.run(retry);
 
 
82
  assert.deepEqual(f.calls.map(call => call.number), [3]);
83
  assert.equal(f.c.snapshot.scroll.index, 4); assert.equal(f.c.snapshot.scroll.offset, 7);
84
  assert.equal(f.events.filter(event => event === 'restore').length, 1);
85
- assert.equal(f.events.includes('apply'), false); assert.equal(f.c.positionRestore, null);
86
  });
87
 
88
  test('generation mismatch clears the shared retry buffer and restarts lookup through the live validation hook', async () => {
89
  const f = fixture(), original = f.c.fetchPositionPageWithRecovery;
90
- const first = f.make(); first.ready.set(2, page(2));
91
- const buffer = first.ready;
92
  f.c.fetchPositionPageWithRecovery = (...args) => args[1] === 3 ? Promise.resolve(page(3, 'B')) : original(...args);
93
  let validations = 0;
94
  f.c.validatePositionWindowPage = (...args) => {validations++; f.c.VoiceOfMLSearchWindowPage.validate(...args);};
95
- await f.run(first);
 
96
  assert.ok(validations >= 2); assert.equal(first.error.message, 'RESTORE_PAGE_CHANGED');
97
  assert.equal(first.ready, buffer); assert.equal(buffer.size, 0); assert.equal(first.lookup, null); assert.equal(f.c.snapshot, undefined);
98
  f.calls.length = 0; f.c.fetchPositionPageWithRecovery = original;
99
- const retry = f.make(first); assert.equal(retry.ready, buffer);
100
- await f.run(retry); assert.deepEqual(f.calls.map(call => call.number), [1, 2, 3, 4]);
101
  });
102
 
103
  test('stale viewport, lookup and neighbor completions cannot publish or mark a newer task failed', async () => {
@@ -105,24 +119,30 @@ test('stale viewport, lookup and neighbor completions cannot publish or mark a n
105
  const f = fixture(), gate = deferred(), original = f.c.fetchPositionPageWithRecovery;
106
  if (stage === 'viewport') f.c.readSearchViewport = () => gate.promise;
107
  else f.c.fetchPositionPageWithRecovery = (...args) => (stage === 'lookup' ? args[1] === 1 : args[1] === 3) ? gate.promise : original(...args);
108
- const first = f.make(); f.c.positionRestore = first;
109
- const running = vm.runInContext('positionRestoration', f.c).run(first, stage === 'viewport' ? undefined : null);
110
- await flush(); const newer = f.make(); f.c.positionRestore = newer; f.c.STATE.isLoading = true;
 
111
  if (rejection) gate.reject(new Error('late')); else gate.resolve(stage === 'viewport' ? null : page(stage === 'lookup' ? 1 : 3));
112
- await running;
113
- assert.equal(f.c.positionRestore, newer); assert.equal(f.c.STATE.isLoading, true);
 
114
  assert.equal(first.failed, undefined); assert.equal(newer.failed, undefined); assert.equal(f.c.snapshot, undefined);
115
  }
116
  });
117
 
118
  test('preview waits for drag release, accepts only matching cached pages and applies once', async () => {
119
- const f = fixture(), task = f.make();
120
  f.c.STATE.results[4] = {id: 'r4'}; f.c.VSCROLL.isDraggingThumb = true;
121
  f.c.captureReaderReturnScroll = () => ({index: 4, offset: 19});
122
- task.cachedPages = new Map([[5, page(5)], [6, page(6, 'old')]]);
123
- const running = f.run(task, {}); await flush();
 
 
124
  assert.equal(f.timers.length, 1); assert.equal(f.c.snapshot, undefined);
125
- f.c.VSCROLL.isDraggingThumb = false; f.timers.shift()(); await running;
 
 
126
  assert.equal(task.ready.has(5), true); assert.equal(task.ready.has(6), false);
127
  assert.equal(f.c.snapshot.scroll.offset, 19); assert.equal(f.c.snapshot.results[8].id, 'r8');
128
  assert.equal(f.events.filter(event => event === 'apply').length, 1);
@@ -130,16 +150,16 @@ test('preview waits for drag release, accepts only matching cached pages and app
130
  });
131
 
132
  test('abort during drag wait leaves the task and snapshot untouched', async () => {
133
- const f = fixture(), task = f.make(); f.c.VSCROLL.isDraggingThumb = true;
134
- const running = f.run(task, {}); await flush(); task.controller.abort(); f.timers.shift()(); await running;
135
- assert.equal(f.c.snapshot, undefined); assert.equal(task.failed, undefined); assert.equal(f.c.positionRestore, task);
136
  });
137
 
138
  test('moving preview anchor outside ready pages restarts lookup without replacing the shared map', async () => {
139
- const f = fixture(), task = f.make(), buffer = task.ready, original = f.c.fetchPositionPageWithRecovery;
140
  f.c.STATE.results[10] = {id: 'r10'}; f.c.captureReaderReturnScroll = () => ({index: 10, offset: 23});
141
  f.c.fetchPositionPageWithRecovery = async (...args) => ({...await original(...args), ...(args[3] ? {anchor_index: args[3] === 'r10' ? 10 : 4} : {})});
142
- await f.run(task, {});
143
  assert.equal(task.ready, buffer); assert.deepEqual(f.calls.filter(call => call.anchorId).map(call => call.anchorId), ['r4', 'r10']);
144
  assert.deepEqual([...buffer.keys()], [1, 5, 6]); assert.equal(f.c.snapshot.scroll.index, 10);
145
  assert.equal(f.c.snapshot.scroll.offset, 23); assert.equal(task.position.anchorId, 'r10');
@@ -152,14 +172,14 @@ test('a failed neighbor retry preserves the moved anchor and its offset', async
152
  f.c.captureReaderReturnScroll = () => ({index:10, offset:23});
153
  let fail = true;
154
  f.c.fetchPositionPageWithRecovery = async (...args) => {
155
- if (fail && args[1] === 6) throw new Error('temporarily unavailable');
156
  return {...await original(...args), ...(args[3] === 'r10' ? {anchor_index:10} : {})};
157
  };
158
- const first = f.make(); await f.run(first, {});
159
  assert.ok(first.failed); assert.equal(first.position.anchorId, 'r10');
160
  fail = false; f.calls.length = 0;
161
- const retry = f.make(first, first.position);
162
- await f.run(retry, {});
163
  assert.deepEqual(f.calls.map(call => call.number), [6]);
164
  assert.equal(f.c.snapshot.scroll.index, 10); assert.equal(f.c.snapshot.scroll.offset, 23);
165
  });
@@ -167,8 +187,10 @@ test('a failed neighbor retry preserves the moved anchor and its offset', async
167
  test('Reader overlay retains the saved anchor and missing anchor uses the nearby snapshot path', async () => {
168
  const f = fixture(); f.c.readerHost.overlay = {};
169
  f.c.captureReaderReturnScroll = () => {throw new Error('Reader must retain the saved anchor');};
170
- await f.run(f.make(), {}); assert.equal(f.c.snapshot.scroll.index, 4); assert.equal(f.events.includes('apply'), true);
171
- const missing = fixture(); await missing.run(missing.make(null, {...position, anchorId: 'gone'}), {});
 
 
172
  assert.equal(missing.c.snapshot.scroll.index, 4); assert.equal(missing.events.includes('restore'), true);
173
  assert.equal(missing.events.includes('apply'), false); assert.equal(missing.events.filter(event => event[0] === 'toast').length, 1);
174
  });
@@ -176,7 +198,8 @@ test('Reader overlay retains the saved anchor and missing anchor uses the nearby
176
  test('preview keeps a user-moved hole instead of a vanished saved anchor', async () => {
177
  const f = fixture();
178
  f.c.captureReaderReturnScroll = () => ({index: 11, offset: 17});
179
- await f.run(f.make(null, {...position, anchorId: 'gone'}), {});
 
180
  assert.equal(f.c.snapshot.scroll.index, 11);
181
  assert.equal(f.c.snapshot.scroll.offset, 17);
182
  assert.equal(f.events.includes('apply'), true);
@@ -186,34 +209,71 @@ test('preview keeps a user-moved hole instead of a vanished saved anchor', async
186
 
187
  test('synchronous prologue retains ordering, duplicate handling and abort reentry ownership', () => {
188
  const f = fixture();
189
- const active = f.make(); f.c.positionRestore = active;
190
- assert.equal(f.c.tryRestoreSearchPosition(key), true); assert.deepEqual(f.events, []);
191
- assert.equal(f.c.searchIntentId, 1);
192
  f.events.length = 0;
193
- const newer = f.make();
194
- active.controller.signal.addEventListener('abort', () => {f.c.searchId++; f.c.positionRestore = newer; f.c.STATE.isLoading = true;});
195
- assert.equal(f.c.tryRestoreSearchPosition(key, {position}), false);
 
 
196
  assert.deepEqual(f.events.slice(0, 3), ['active', 'clone', 'window']);
197
- assert.equal(f.c.positionEntryId, 1); assert.equal(f.c.positionRestore, newer);
198
- assert.equal(f.c.STATE.isLoading, true); assert.equal(f.events.includes('target'), false);
199
  });
200
 
201
  test('active-search abort reentry exits before restoration cancellation', () => {
202
- const f = fixture(), active = f.make(); f.c.positionRestore = active;
203
  f.c.cancelActiveSearch = () => false;
204
- assert.equal(f.c.tryRestoreSearchPosition(key, {position}), false);
205
- assert.equal(f.c.positionEntryId, 0); assert.equal(active.controller.signal.aborted, false);
 
206
  });
207
 
208
- test('site-specific backend pin and completion reset remain unchanged', async () => {
209
- const f = fixture(); const pages = source.includes('backend: options.backend');
210
- const task = f.c.VoiceOfMLPositionRestoration.createTask({key, position, backend: 'local'});
211
- await f.run(task);
212
- assert.equal(f.calls[0].query.resultBackend, pages ? 'local' : undefined);
213
- assert.equal(Object.hasOwn(f.c.snapshot, 'resultBackend'), pages);
214
- assert.equal(f.c.snapshot.resultBackend, pages ? 'local' : undefined);
215
- assert.equal(f.events.includes('reset-controls'), !pages);
216
- const previous = f.c.VoiceOfMLPositionRestoration.createTask({key, position, backend: 'api'});
217
- const retry = f.c.VoiceOfMLPositionRestoration.createTask({key, position, previous});
218
- assert.equal(retry.backend, pages ? 'api' : undefined);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  });
 
6
 
7
  const source = fs.readFileSync('static/app.js', 'utf8');
8
  const key = JSON.stringify({pageSize: 2});
9
+ const position = {version: 1, key, index: 4, offset: 7, anchorId: 'r4', loadedPage: 3, savedAt: Date.now()};
10
+ const preview = (saved = position) => ({key, savedAt: Date.now(), total: 12, generation: 'A',
11
+ estimatedHeight: 40, measurementKey: 'layout', records: [[saved.index, {File: 'saved', id: saved.anchorId}, 40]]});
12
  const page = (number, generation = 'A', total = 12) => ({page: number, page_size: 2, total, generation,
13
  results: Array.from({length: Math.min(2, Math.max(0, total - (number - 1) * 2))}, (_, i) => ({id: 'r' + ((number - 1) * 2 + i)}))});
14
  const deferred = () => {let resolve, reject; const promise = new Promise((yes, no) => {resolve = yes; reject = no;}); return {promise, resolve, reject};};
15
+ const flush = () => new Promise(resolve => setImmediate(resolve));
16
 
17
  // Run the real host composition as well as the coordinator. All geometry stays
18
  // behind the same ports as production; tests can replace the live page hook.
 
21
  const c = vm.createContext({AbortController, TextEncoder: class extends TextEncoder {
22
  encode(value) {encoded.push(value); return super.encode(value);}
23
  }, setTimeout(fn, ms) {assert.equal(ms, 30); timers.push(fn);},
24
+ resultWindow: null, searchIntentId: 0, searchId: 0,
25
  STATE: {isLoading: false, results: []}, VSCROLL: {isDraggingThumb: false, estimatedHeight: 40},
26
  readerHost: {overlay: null}, getSearchViewKey: () => key,
27
+ positionPersistence: {getPosition: () => position},
28
+ cancelActiveSearch() {events.push('active'); c.searchId++; return true;},
29
+ updateResultWindowStatus() {events.push('window');},
30
  setReturnPositionTarget() {events.push('target');}, resetPagingRecovery() {events.push('paging');},
31
  showPositionRestoreStatus(message, retry) {events.push(['status', message, retry]);},
32
  readSearchViewport: async () => null,
33
  fetchPositionPageWithRecovery: async (query, number, signal, anchorId) => {
34
  calls.push({query, number, signal, anchorId}); return {...page(number), ...(anchorId ? {anchor_index: 4} : {})};
35
  },
 
36
  captureReaderReturnScroll: () => ({index: 4, offset: 7}), getResultStableId: record => record?.id || '',
37
  applyValidatedSearchViewport(snapshot) {events.push('apply'); c.snapshot = snapshot; c.STATE.isLoading = false;},
38
+ restoreSearchViewSnapshot(k, scroll, options) {
39
+ assert.equal(scroll, true);
40
+ if (options.preserveRestore) {
41
+ assert.equal(restoration.current.preview, true);
42
+ events.push('preview'); c.preview = store.snapshots.get(k);
43
+ } else {
44
+ assert.equal(restoration.current, null);
45
+ assert.equal(options.preserveQueryDraft, true);
46
+ events.push('restore'); c.snapshot = store.snapshots.get(k);
47
+ }
48
+ c.STATE.isLoading = false;
49
+ },
50
  resetPositionControlScroll() {events.push('reset-controls');}, showToast(message) {events.push(['toast', message]);}
51
  });
52
  installClassicSearchModules(process.cwd(), c);
53
  const store = c.VoiceOfMLResultSnapshots.create({});
54
+ c.resultSnapshots = {...store,
55
+ cancelClone() {store.cancelClone(); events.push('clone');},
56
  putRestored(k, snapshot) {store.putRestored(k, snapshot); events.push('put');},
57
  trim() {store.trim(); events.push('trim');}
58
  };
59
  c.validatePositionWindowPage = (...args) => c.VoiceOfMLSearchWindowPage.validate(...args);
60
  vm.runInContext(source.match(/^const positionRestoration = VoiceOfMLPositionRestoration.create\(\{[^]*?^\}\);/m)[0], c);
61
+ const restoration = vm.runInContext('positionRestoration', c);
62
+ vm.runInContext(source.match(/^const \{ cancel: cancelPositionRestore, start: tryRestoreSearchPosition \} = positionRestoration;$/m)[0], c);
63
+ const start = (options = {viewport: null}) => {
64
+ assert.equal(restoration.start(key, options), true);
65
+ return restoration.current;
66
+ };
67
+ return {c, calls, events, encoded, timers, restoration, start, store};
68
  }
69
 
70
  test('authoritative restore trims the exact sparse budget without serializing the holes', async () => {
 
73
  total: 50_000, generation: '版本', anchor_index: ${index}, results: [0, 1].map(offset => ({
74
  id: 'r' + ((page - 1) * 2 + offset), File: '书📚', Folder: ['路径']
75
  }))})`, f.c);
76
+ f.start({viewport: null, position: {...position, index, anchorId: 'r' + index, loadedPage: 25_000}}); await flush();
77
  const {bytes, ...envelope} = f.c.snapshot;
78
  assert.equal(bytes, new TextEncoder().encode(JSON.stringify(envelope)).length + 256);
79
  assert.equal(envelope.results.length, 50_000);
 
87
  test('restoration retries retain lookup and partial-neighbor buffer identity without duplicate rendering', async () => {
88
  const f = fixture(), original = f.c.fetchPositionPageWithRecovery;
89
  f.c.fetchPositionPageWithRecovery = (...args) => args[1] === 3 ? Promise.reject(new Error('offline')) : original(...args);
90
+ const first = f.start(); await flush();
91
  assert.equal(first.failed, true); assert.deepEqual([...first.ready.keys()], [1, 2, 4]);
92
  assert.equal(f.c.snapshot, undefined); assert.equal(f.events.includes('restore'), false);
 
 
93
  f.calls.length = 0; f.c.fetchPositionPageWithRecovery = original;
94
+ const retry = f.start();
95
+ assert.equal(retry.ready, first.ready); assert.equal(retry.lookup, first.lookup);
96
+ await flush();
97
  assert.deepEqual(f.calls.map(call => call.number), [3]);
98
  assert.equal(f.c.snapshot.scroll.index, 4); assert.equal(f.c.snapshot.scroll.offset, 7);
99
  assert.equal(f.events.filter(event => event === 'restore').length, 1);
100
+ assert.equal(f.events.includes('apply'), false); assert.equal(f.restoration.current, null);
101
  });
102
 
103
  test('generation mismatch clears the shared retry buffer and restarts lookup through the live validation hook', async () => {
104
  const f = fixture(), original = f.c.fetchPositionPageWithRecovery;
 
 
105
  f.c.fetchPositionPageWithRecovery = (...args) => args[1] === 3 ? Promise.resolve(page(3, 'B')) : original(...args);
106
  let validations = 0;
107
  f.c.validatePositionWindowPage = (...args) => {validations++; f.c.VoiceOfMLSearchWindowPage.validate(...args);};
108
+ const first = f.start(), buffer = first.ready; buffer.set(2, page(2));
109
+ await flush();
110
  assert.ok(validations >= 2); assert.equal(first.error.message, 'RESTORE_PAGE_CHANGED');
111
  assert.equal(first.ready, buffer); assert.equal(buffer.size, 0); assert.equal(first.lookup, null); assert.equal(f.c.snapshot, undefined);
112
  f.calls.length = 0; f.c.fetchPositionPageWithRecovery = original;
113
+ const retry = f.start(); assert.equal(retry.ready, buffer);
114
+ await flush(); assert.deepEqual(f.calls.map(call => call.number), [1, 2, 3, 4]);
115
  });
116
 
117
  test('stale viewport, lookup and neighbor completions cannot publish or mark a newer task failed', async () => {
 
119
  const f = fixture(), gate = deferred(), original = f.c.fetchPositionPageWithRecovery;
120
  if (stage === 'viewport') f.c.readSearchViewport = () => gate.promise;
121
  else f.c.fetchPositionPageWithRecovery = (...args) => (stage === 'lookup' ? args[1] === 1 : args[1] === 3) ? gate.promise : original(...args);
122
+ const first = f.start({viewport: stage === 'viewport' ? undefined : null});
123
+ await flush();
124
+ f.c.readSearchViewport = () => deferred().promise;
125
+ const newer = f.start({position});
126
  if (rejection) gate.reject(new Error('late')); else gate.resolve(stage === 'viewport' ? null : page(stage === 'lookup' ? 1 : 3));
127
+ await flush();
128
+ assert.equal(first.controller.signal.aborted, true);
129
+ assert.equal(f.restoration.current, newer); assert.equal(f.c.STATE.isLoading, true);
130
  assert.equal(first.failed, undefined); assert.equal(newer.failed, undefined); assert.equal(f.c.snapshot, undefined);
131
  }
132
  });
133
 
134
  test('preview waits for drag release, accepts only matching cached pages and applies once', async () => {
135
+ const f = fixture();
136
  f.c.STATE.results[4] = {id: 'r4'}; f.c.VSCROLL.isDraggingThumb = true;
137
  f.c.captureReaderReturnScroll = () => ({index: 4, offset: 19});
138
+ const task = f.start({viewport: preview()});
139
+ f.restoration.rememberPreviewPage(5, page(5));
140
+ f.restoration.rememberPreviewPage(6, page(6, 'old'));
141
+ await flush();
142
  assert.equal(f.timers.length, 1); assert.equal(f.c.snapshot, undefined);
143
+ assert.equal(f.c.preview.window.preview, true); assert.equal(Object.hasOwn(f.c.preview, 'resultBackend'), false);
144
+ assert.equal(f.c.preview.results[4].id, 'r4'); assert.equal(f.store.snapshots.has(key), false);
145
+ f.c.VSCROLL.isDraggingThumb = false; f.timers.shift()(); await flush();
146
  assert.equal(task.ready.has(5), true); assert.equal(task.ready.has(6), false);
147
  assert.equal(f.c.snapshot.scroll.offset, 19); assert.equal(f.c.snapshot.results[8].id, 'r8');
148
  assert.equal(f.events.filter(event => event === 'apply').length, 1);
 
150
  });
151
 
152
  test('abort during drag wait leaves the task and snapshot untouched', async () => {
153
+ const f = fixture(); f.c.VSCROLL.isDraggingThumb = true;
154
+ const task = f.start({viewport: preview()}); await flush(); task.controller.abort(); f.timers.shift()(); await flush();
155
+ assert.equal(f.c.snapshot, undefined); assert.equal(task.failed, undefined); assert.equal(f.restoration.current, task);
156
  });
157
 
158
  test('moving preview anchor outside ready pages restarts lookup without replacing the shared map', async () => {
159
+ const f = fixture(), original = f.c.fetchPositionPageWithRecovery;
160
  f.c.STATE.results[10] = {id: 'r10'}; f.c.captureReaderReturnScroll = () => ({index: 10, offset: 23});
161
  f.c.fetchPositionPageWithRecovery = async (...args) => ({...await original(...args), ...(args[3] ? {anchor_index: args[3] === 'r10' ? 10 : 4} : {})});
162
+ const task = f.start({viewport: preview()}), buffer = task.ready; await flush();
163
  assert.equal(task.ready, buffer); assert.deepEqual(f.calls.filter(call => call.anchorId).map(call => call.anchorId), ['r4', 'r10']);
164
  assert.deepEqual([...buffer.keys()], [1, 5, 6]); assert.equal(f.c.snapshot.scroll.index, 10);
165
  assert.equal(f.c.snapshot.scroll.offset, 23); assert.equal(task.position.anchorId, 'r10');
 
172
  f.c.captureReaderReturnScroll = () => ({index:10, offset:23});
173
  let fail = true;
174
  f.c.fetchPositionPageWithRecovery = async (...args) => {
175
+ if (fail && args[1] === 6) throw new Error('offline');
176
  return {...await original(...args), ...(args[3] === 'r10' ? {anchor_index:10} : {})};
177
  };
178
+ const first = f.start({viewport: preview()}); await flush();
179
  assert.ok(first.failed); assert.equal(first.position.anchorId, 'r10');
180
  fail = false; f.calls.length = 0;
181
+ f.c.readSearchViewport = async () => preview(first.position);
182
+ assert.equal(f.restoration.resume(), true); await flush();
183
  assert.deepEqual(f.calls.map(call => call.number), [6]);
184
  assert.equal(f.c.snapshot.scroll.index, 10); assert.equal(f.c.snapshot.scroll.offset, 23);
185
  });
 
187
  test('Reader overlay retains the saved anchor and missing anchor uses the nearby snapshot path', async () => {
188
  const f = fixture(); f.c.readerHost.overlay = {};
189
  f.c.captureReaderReturnScroll = () => {throw new Error('Reader must retain the saved anchor');};
190
+ f.start({viewport: preview()}); await flush();
191
+ assert.equal(f.c.snapshot.scroll.index, 4); assert.equal(f.events.includes('apply'), true);
192
+ const missing = fixture(), saved = {...position, anchorId: 'gone'};
193
+ missing.start({position: saved, viewport: preview(saved)}); await flush();
194
  assert.equal(missing.c.snapshot.scroll.index, 4); assert.equal(missing.events.includes('restore'), true);
195
  assert.equal(missing.events.includes('apply'), false); assert.equal(missing.events.filter(event => event[0] === 'toast').length, 1);
196
  });
 
198
  test('preview keeps a user-moved hole instead of a vanished saved anchor', async () => {
199
  const f = fixture();
200
  f.c.captureReaderReturnScroll = () => ({index: 11, offset: 17});
201
+ const saved = {...position, anchorId: 'gone'};
202
+ f.start({position: saved, viewport: preview(saved)}); await flush();
203
  assert.equal(f.c.snapshot.scroll.index, 11);
204
  assert.equal(f.c.snapshot.scroll.offset, 17);
205
  assert.equal(f.events.includes('apply'), true);
 
209
 
210
  test('synchronous prologue retains ordering, duplicate handling and abort reentry ownership', () => {
211
  const f = fixture();
212
+ f.c.readSearchViewport = () => deferred().promise;
213
+ const active = f.start({}), entry = f.restoration.entry;
 
214
  f.events.length = 0;
215
+ assert.equal(f.restoration.start(key), true); assert.deepEqual(f.events, []);
216
+ assert.equal(f.c.searchIntentId, 2); assert.equal(f.restoration.entry, entry);
217
+ let newer;
218
+ active.controller.signal.addEventListener('abort', () => {newer = f.start({position});});
219
+ assert.equal(f.restoration.start(key, {position}), false);
220
  assert.deepEqual(f.events.slice(0, 3), ['active', 'clone', 'window']);
221
+ assert.equal(f.restoration.entry, entry + 2); assert.equal(f.restoration.current, newer);
222
+ assert.equal(f.c.STATE.isLoading, true); assert.equal(f.events.filter(event => event === 'target').length, 1);
223
  });
224
 
225
  test('active-search abort reentry exits before restoration cancellation', () => {
226
+ const f = fixture(), active = f.start(), entry = f.restoration.entry;
227
  f.c.cancelActiveSearch = () => false;
228
+ assert.equal(f.restoration.start(key, {position}), false);
229
+ assert.equal(f.restoration.entry, entry); assert.equal(active.controller.signal.aborted, false);
230
+ assert.equal(f.restoration.current, active);
231
  });
232
 
233
+ test('window abort sees both owners cleared and retains the replacement window and restore', () => {
234
+ const f = fixture();
235
+ f.c.readSearchViewport = () => deferred().promise;
236
+ const active = f.start({}), old = new AbortController(), replacement = {controller: new AbortController()};
237
+ f.c.resultWindow = {controller: old};
238
+ let newer, observed;
239
+ old.signal.addEventListener('abort', () => {
240
+ observed = [f.c.resultWindow, f.restoration.current, f.c.STATE.isLoading, active.controller.signal.aborted];
241
+ newer = f.start({position});
242
+ f.c.resultWindow = replacement;
243
+ });
244
+ f.restoration.cancel();
245
+ assert.deepEqual(observed, [null, null, false, false]);
246
+ assert.equal(active.controller.signal.aborted, true);
247
+ assert.equal(f.c.resultWindow, replacement);
248
+ assert.equal(f.restoration.current, newer);
249
+ assert.equal(replacement.controller.signal.aborted, false);
250
+ assert.equal(newer.controller.signal.aborted, false);
251
+ });
252
+
253
+ test('cancelling the position entry alone invalidates an initial viewport read', async () => {
254
+ const f = fixture(), gate = deferred();
255
+ vm.runInContext(source.match(/^async function searchWithInitialFallback\([^]*?^}/m)[0], f.c);
256
+ let reads = 0, validations = 0, fallback = 0;
257
+ Object.assign(f.c, {saveSearchViewSnapshot() {}, prepareReturnPosition() {}, getReturnPositionTarget: () => position,
258
+ validSearchViewport() {validations++; return true;}, searchWithInitialFallbackFresh() {fallback++;},
259
+ readSearchViewport() {reads++; return gate.promise;}});
260
+ const pending = f.c.searchWithInitialFallback();
261
+ assert.equal(reads, 1); assert.equal(f.restoration.current, null);
262
+ const intent = f.c.searchIntentId, owner = f.c.searchId, entry = f.restoration.entry;
263
+ f.restoration.cancel();
264
+ assert.equal(f.restoration.entry, entry + 1);
265
+ assert.equal(f.c.getSearchViewKey(), key);
266
+ assert.equal(f.c.searchIntentId, intent); assert.equal(f.c.searchId, owner);
267
+ gate.resolve(preview());
268
+ assert.equal(await pending, false);
269
+ assert.equal(validations, 0); assert.equal(fallback, 0); assert.equal(f.restoration.current, null);
270
+ });
271
+
272
+ test('Space restores without pinning a backend and resets control scroll after publication', async () => {
273
+ const f = fixture();
274
+ f.start(); await flush();
275
+ assert.ok(f.calls.every(({query}) => !Object.hasOwn(query, 'resultBackend')));
276
+ assert.equal(Object.hasOwn(f.c.snapshot, 'resultBackend'), false);
277
+ assert.deepEqual(f.events.filter(event => ['restore', 'reset-controls', 'trim'].includes(event)),
278
+ ['restore', 'reset-controls', 'trim']);
279
  });
tests/search/ui/virtual_results_contracts.mjs CHANGED
@@ -49,7 +49,7 @@ function fixture(count = 100) {
49
  const STATE = {results: Array.from({length: count}, (_, index) => ({File: 'row-' + index})), total: count, _loadedPage: 1};
50
  const c = vm.createContext({STATE, DOM: {resultsList: list, resultsContainer: container, multiSelectToggle: {checked: false}},
51
  document, performance: {now: () => clock += 16}, resultWindow: null, resultSnapshots: {cloneTask: null},
52
- positionRestore: null, pendingResultEntrance: false, measuredHeightRevision: 0, keyboardResultIndex: -1,
53
  resultRowRecords: records, virtualResults: undefined,
54
  requestAnimationFrame(fn) { const id = ++serial; frames.set(id, fn); return id; },
55
  cancelAnimationFrame(id) { frames.delete(id); events.push(['cancel', id]); },
 
49
  const STATE = {results: Array.from({length: count}, (_, index) => ({File: 'row-' + index})), total: count, _loadedPage: 1};
50
  const c = vm.createContext({STATE, DOM: {resultsList: list, resultsContainer: container, multiSelectToggle: {checked: false}},
51
  document, performance: {now: () => clock += 16}, resultWindow: null, resultSnapshots: {cloneTask: null},
52
+ positionRestoration: {current: null}, pendingResultEntrance: false, measuredHeightRevision: 0, keyboardResultIndex: -1,
53
  resultRowRecords: records, virtualResults: undefined,
54
  requestAnimationFrame(fn) { const id = ++serial; frames.set(id, fn); return id; },
55
  cancelAnimationFrame(id) { frames.delete(id); events.push(['cancel', id]); },
tests/support/classic_search_modules.js CHANGED
@@ -22,7 +22,7 @@ const MODULES = ["static/search/execution/domain/policy.js", "static/search/exec
22
  "static/search/requests/infrastructure/response-cache.js", "static/search/requests/application/response-store.js",
23
  "static/search/catalog/domain/sidebar-payload.js", "static/search/catalog/application/client.js",
24
  "static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js",
25
- "static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];
26
  const sources = new Map();
27
  const installed = new WeakMap();
28
 
 
22
  "static/search/requests/infrastructure/response-cache.js", "static/search/requests/application/response-store.js",
23
  "static/search/catalog/domain/sidebar-payload.js", "static/search/catalog/application/client.js",
24
  "static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js",
25
+ "static/search/results/domain/recovery.js", "static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"];
26
  const sources = new Map();
27
  const installed = new WeakMap();
28
 
typings/reader-globals.d.ts CHANGED
@@ -180,7 +180,15 @@ declare var VoiceOfMLPagingStatus: {create(options: VoiceOfMLPagingStatusOptions
180
  interface VoiceOfMLInputDraftOwner {href: string; key: string | undefined; cancelled: boolean}
181
  interface VoiceOfMLInputVisitOwner {generation: number; viewKey: string | null}
182
  interface VoiceOfMLInputState {
183
- timer: number | null; composing: boolean; dirty: boolean; ready: boolean;
 
 
 
 
 
 
 
 
184
  }
185
  interface VoiceOfMLInputElement extends EventTarget {
186
  value: string;
@@ -191,10 +199,14 @@ interface VoiceOfMLInputDependencies {
191
  clock: {setTimeout(callback: () => void, delay: number): number; clearTimeout(timer: number): void};
192
  getHref(): string; getEntryKey(): string | undefined; getViewKey(): string | null;
193
  syncInput(): void; canSubmit(): boolean; submit(query: string): void; onState(state: Readonly<VoiceOfMLInputState>): void;
 
 
194
  }
195
  interface VoiceOfMLInputController {
196
  mount(): void; dispose(): void; debounce(): void; cancelTimer(): void; invalidateVisit(): void;
197
  captureDraft(renew?: boolean): void; cancelDraft(): void; draftIsCurrent(): boolean; finishStartup(current: boolean): void;
 
 
198
  }
199
  declare var VoiceOfMLSearchInputOwnership: {
200
  draft(href: string, key: string | undefined): VoiceOfMLInputDraftOwner;
 
180
  interface VoiceOfMLInputDraftOwner {href: string; key: string | undefined; cancelled: boolean}
181
  interface VoiceOfMLInputVisitOwner {generation: number; viewKey: string | null}
182
  interface VoiceOfMLInputState {
183
+ timer: number | null; filterTimer: number | null; sizeTimer: number | null;
184
+ composing: boolean; dirty: boolean; ready: boolean;
185
+ }
186
+ interface VoiceOfMLSizeControls {
187
+ min: VoiceOfMLInputElement; max: VoiceOfMLInputElement;
188
+ minUnit: VoiceOfMLInputElement; maxUnit: VoiceOfMLInputElement;
189
+ read(): [number | null, number | null];
190
+ format(bytes: number | null): {value: string; unit: string};
191
+ commit(min: number | null, max: number | null): void;
192
  }
193
  interface VoiceOfMLInputElement extends EventTarget {
194
  value: string;
 
199
  clock: {setTimeout(callback: () => void, delay: number): number; clearTimeout(timer: number): void};
200
  getHref(): string; getEntryKey(): string | undefined; getViewKey(): string | null;
201
  syncInput(): void; canSubmit(): boolean; submit(query: string): void; onState(state: Readonly<VoiceOfMLInputState>): void;
202
+ filterSearch(clearResults?: boolean): void;
203
+ size: VoiceOfMLSizeControls;
204
  }
205
  interface VoiceOfMLInputController {
206
  mount(): void; dispose(): void; debounce(): void; cancelTimer(): void; invalidateVisit(): void;
207
  captureDraft(renew?: boolean): void; cancelDraft(): void; draftIsCurrent(): boolean; finishStartup(current: boolean): void;
208
+ pendingQuery(): string | null; flushSize(): void; syncSize(preserveDraft?: boolean): void;
209
+ cancelPending(preserveQuery?: boolean): void; scheduleFilter(): void; cancelFilter(): void;
210
  }
211
  declare var VoiceOfMLSearchInputOwnership: {
212
  draft(href: string, key: string | undefined): VoiceOfMLInputDraftOwner;
typings/search-restoration.d.ts CHANGED
@@ -3,33 +3,43 @@ interface SearchPositionRestorePage extends VoiceOfMLSearchWindowPageData {
3
  }
4
  interface SearchPositionRestoreTask {
5
  key: string; controller: AbortController; position: SearchPosition;
6
- backend?: string | undefined;
7
  lookup?: SearchPositionRestorePage | null | undefined;
8
  ready: Map<number, SearchPositionRestorePage>;
9
- preview?: boolean; cachedPages?: Map<number, SearchPositionRestorePage>;
10
  failed?: boolean; error?: Error;
11
  }
 
 
 
 
12
  interface SearchPositionRestoreInput {
13
- key: string; position: SearchPosition; previous?: SearchPositionRestoreTask | null | undefined;
14
- backend?: string | undefined;
15
  }
16
  interface SearchPositionRestorationHost {
17
- isCurrent(task: SearchPositionRestoreTask): boolean;
 
 
 
 
 
18
  readViewport(key: string): Promise<SearchPositionViewport | null>;
19
  fetchPage(query: VoiceOfMLSearchViewProjection & {resultBackend?: string}, page: number, signal: AbortSignal, anchorId?: string): Promise<SearchPositionRestorePage>;
20
  validatePage: typeof VoiceOfMLSearchWindowPage.validate;
21
- showPreview(viewport: SearchPositionViewport | null, position: SearchPosition, task: SearchPositionRestoreTask): void;
22
  isDragging(): boolean;
23
  capturePreviewAnchor(): Readonly<{index: number; offset: number; anchorId: string}> | null;
24
  stableId(record: unknown): string; estimatedHeight(): number;
25
- release(): void; applyPreview(snapshot: SearchResultSnapshot): void;
26
- snapshots: Pick<SearchSnapshotStore, 'putRestored' | 'trim'>;
27
- restoreSnapshot(key: string): void; completed(): void;
28
- failed(message: string): void; notify(message: string): void;
29
  }
30
  declare var VoiceOfMLPositionRestoration: {
31
- createTask(input: SearchPositionRestoreInput): SearchPositionRestoreTask;
32
  create(host: SearchPositionRestorationHost): {
33
- run(task: SearchPositionRestoreTask, viewport?: SearchPositionViewport | null): Promise<void>;
 
 
 
 
 
34
  };
35
  };
 
3
  }
4
  interface SearchPositionRestoreTask {
5
  key: string; controller: AbortController; position: SearchPosition;
 
6
  lookup?: SearchPositionRestorePage | null | undefined;
7
  ready: Map<number, SearchPositionRestorePage>;
8
+ preview?: boolean; cachedPages?: Map<number, SearchRecentPage>;
9
  failed?: boolean; error?: Error;
10
  }
11
+ interface SearchPositionRestoreOptions {
12
+ position?: SearchPosition | null;
13
+ viewport?: SearchPositionViewport | null | undefined;
14
+ }
15
  interface SearchPositionRestoreInput {
16
+ key: string; position: SearchPosition; previous: SearchPositionRestoreTask | null;
 
17
  }
18
  interface SearchPositionRestorationHost {
19
+ currentKey(): string;
20
+ getPosition(key: string): SearchPosition | undefined;
21
+ noteSearchIntent(): void;
22
+ retireSearch(): (() => boolean) | null;
23
+ detachWindow(): AbortController | undefined;
24
+ status(phase: 'started' | 'cancelled' | 'preview' | 'finished' | 'failed', message: string): void;
25
  readViewport(key: string): Promise<SearchPositionViewport | null>;
26
  fetchPage(query: VoiceOfMLSearchViewProjection & {resultBackend?: string}, page: number, signal: AbortSignal, anchorId?: string): Promise<SearchPositionRestorePage>;
27
  validatePage: typeof VoiceOfMLSearchWindowPage.validate;
 
28
  isDragging(): boolean;
29
  capturePreviewAnchor(): Readonly<{index: number; offset: number; anchorId: string}> | null;
30
  stableId(record: unknown): string; estimatedHeight(): number;
31
+ applyPreview(snapshot: SearchResultSnapshot): void;
32
+ snapshots: Pick<SearchSnapshotStore, 'cancelClone' | 'put' | 'remove' | 'putRestored' | 'trim'>;
33
+ restoreSnapshot(key: string, preview?: boolean): void;
34
+ completed(): void; notify(message: string): void;
35
  }
36
  declare var VoiceOfMLPositionRestoration: {
 
37
  create(host: SearchPositionRestorationHost): {
38
+ readonly current: Readonly<SearchPositionRestoreTask> | null;
39
+ readonly entry: number;
40
+ start(key: string, options?: SearchPositionRestoreOptions): boolean;
41
+ cancel(): void;
42
+ resume(): boolean;
43
+ rememberPreviewPage(page: number, data: SearchRecentPage): void;
44
  };
45
  };