vomebook commited on
Commit ·
d101ec0
1
Parent(s): c77f9c7
Fix search and Reader history ownership and recovery
Browse files- scripts/search/check_reader_navigation_baseline.mjs +7 -3
- static/app.js +221 -64
- static/reader/core/reader-bindings.mjs +41 -4
- static/search/reader-navigation.js +49 -5
- static/search/search-session.js +140 -54
- tests/gates/ci-test-inventory.json +20 -0
- tests/gates/test_static_checks.py +14 -2
- tests/reader/browser/test_reader_host_history_races.py +378 -0
- tests/reader/browser/test_reader_navigation_host.py +96 -8
- tests/reader/browser/test_reader_reload_search_document.py +600 -0
- tests/reader/core/test_reader_regression.js +1 -1
- tests/search/browser/test_paging_recovery.py +8 -2
- tests/search/browser/test_session_transaction_browser.py +321 -0
- tests/search/reader-navigation/test_reader_navigation_baseline.mjs +173 -7
- tests/search/reader-navigation/test_search_history_races.mjs +201 -0
- tests/search/session/test_search_session_contract.js +378 -0
- typings/reader-globals.d.ts +1 -0
scripts/search/check_reader_navigation_baseline.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import {spawnSync} from 'node:child_process';
|
| 2 |
import {hasPassingTapContracts} from '../check_tap_contracts.mjs';
|
| 3 |
|
| 4 |
-
// Node 26/V8 scope: this
|
| 5 |
-
//
|
| 6 |
const minimum = [31.96, 81.82, 27.27];
|
| 7 |
const result = spawnSync(process.execPath, [
|
| 8 |
'--test', '--test-reporter=tap', '--experimental-test-coverage',
|
|
@@ -29,7 +29,11 @@ const required = [
|
|
| 29 |
'remember still updates history when storage fails and saved rejects malformed JSON',
|
| 30 |
'clear removes only the matching session and selected return token',
|
| 31 |
'messages are rejected when no reader iframe is active',
|
| 32 |
-
'pathname and search parameter prototype overrides retain their original effects'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
].map(name => ({name}));
|
| 34 |
if (result.status !== 0 || rows.length !== 1 || rows[0].some((value, index) => value < minimum[index]) ||
|
| 35 |
!hasPassingTapContracts(text, required)) {
|
|
|
|
| 1 |
import {spawnSync} from 'node:child_process';
|
| 2 |
import {hasPassingTapContracts} from '../check_tap_contracts.mjs';
|
| 3 |
|
| 4 |
+
// Node 26/V8 scope: this file under synthetic URL/session and shell contracts.
|
| 5 |
+
// Native browser traversal, rendering and speech still require browser tests.
|
| 6 |
const minimum = [31.96, 81.82, 27.27];
|
| 7 |
const result = spawnSync(process.execPath, [
|
| 8 |
'--test', '--test-reporter=tap', '--experimental-test-coverage',
|
|
|
|
| 29 |
'remember still updates history when storage fails and saved rejects malformed JSON',
|
| 30 |
'clear removes only the matching session and selected return token',
|
| 31 |
'messages are rejected when no reader iframe is active',
|
| 32 |
+
'pathname and search parameter prototype overrides retain their original effects',
|
| 33 |
+
'replacement revision preserves a Reader opened synchronously during disposal',
|
| 34 |
+
'ordinary replacement carries handoff and focus while releasing background ownership',
|
| 35 |
+
'close recovery validates both search routes without changing history or private handoff',
|
| 36 |
+
'recovery survives late shell load and records handoff only on native link activation'
|
| 37 |
].map(name => ({name}));
|
| 38 |
if (result.status !== 0 || rows.length !== 1 || rows[0].some((value, index) => value < minimum[index]) ||
|
| 39 |
!hasPassingTapContracts(text, required)) {
|
static/app.js
CHANGED
|
@@ -118,6 +118,14 @@ let filterRenderDone = 0;
|
|
| 118 |
let scrollLoadTimer = null;
|
| 119 |
let scrollRecoveryTimer = null;
|
| 120 |
let searchComposing = false;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
let keepalivePending = null;
|
| 122 |
let lastKeepaliveAt = 0;
|
| 123 |
const KEEPALIVE_INTERVAL_MS = 45 * 1000;
|
|
@@ -378,7 +386,9 @@ function prepareSearchPositionNavigation({ fromStart, restorePosition }) {
|
|
| 378 |
saveSearchViewSnapshot();
|
| 379 |
const key = getSearchViewKey();
|
| 380 |
if (fromStart) saveSearchPosition();
|
|
|
|
| 381 |
cancelPositionRestore();
|
|
|
|
| 382 |
prepareReturnPosition(key, !fromStart);
|
| 383 |
if (!restorePosition) return false;
|
| 384 |
setReturnPositionTarget();
|
|
@@ -821,14 +831,17 @@ function showPositionRestoreStatus(message, retry = false) {
|
|
| 821 |
function cancelPositionRestore() {
|
| 822 |
cancelSnapshotClone();
|
| 823 |
positionEntryId++;
|
| 824 |
-
|
|
|
|
| 825 |
resultWindow = null;
|
| 826 |
-
updateResultWindowStatus();
|
| 827 |
-
if (!positionRestore) return;
|
| 828 |
-
positionRestore.controller.abort();
|
| 829 |
positionRestore = null;
|
| 830 |
-
|
| 831 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 832 |
}
|
| 833 |
|
| 834 |
function tryRestoreSearchPosition(key, options = {}) {
|
|
@@ -837,11 +850,11 @@ function tryRestoreSearchPosition(key, options = {}) {
|
|
| 837 |
if (!validSearchPosition(position)) return false;
|
| 838 |
cancelPendingSearchControls();
|
| 839 |
if (!options.position && positionRestore?.key === key && !positionRestore.failed) return true;
|
|
|
|
|
|
|
| 840 |
cancelPositionRestore();
|
|
|
|
| 841 |
setReturnPositionTarget();
|
| 842 |
-
searchAbortController?.abort();
|
| 843 |
-
cancelSearchPrefetch();
|
| 844 |
-
searchRequestId++;
|
| 845 |
const controller = new AbortController();
|
| 846 |
const task = { key, controller, position: {...position}, lookup: previous?.lookup, ready: previous?.ready || new Map(), page: 0, results: [] };
|
| 847 |
positionRestore = task;
|
|
@@ -1443,12 +1456,11 @@ function startSnapshotClone() {
|
|
| 1443 |
function restoreSearchViewSnapshot(key, restoreScroll = true, preserveRestore = false) {
|
| 1444 |
const snapshot = searchViewSnapshots.get(key);
|
| 1445 |
if (!snapshot || snapshot.version !== SEARCH_VIEW_SNAPSHOT_VERSION || snapshot.loadedPage < 1) return restoreScroll && tryRestoreSearchPosition(key);
|
|
|
|
|
|
|
| 1446 |
if (!preserveRestore) cancelPositionRestore();
|
|
|
|
| 1447 |
cancelPendingSearchControls();
|
| 1448 |
-
if (searchAbortController) searchAbortController.abort();
|
| 1449 |
-
cancelSearchPrefetch();
|
| 1450 |
-
searchAbortController = new AbortController();
|
| 1451 |
-
searchRequestId++;
|
| 1452 |
const materialized = snapshot.window?.count ?? snapshot.results.length;
|
| 1453 |
STATE.results = materialized > 2000 && !preserveRestore
|
| 1454 |
? prepareSnapshotClone(snapshot, key, restoreScroll) : snapshot.results.map(cloneSearchResult);
|
|
@@ -1612,7 +1624,7 @@ function buildSearchApiBody(params = {}) {
|
|
| 1612 |
}
|
| 1613 |
if (params.min_size != null) body.min_size = params.min_size;
|
| 1614 |
if (params.max_size != null) body.max_size = params.max_size;
|
| 1615 |
-
body.sort = params.sort || DOM.sortSelect.value;
|
| 1616 |
if (params.search_folders === false) body.search_folders = false;
|
| 1617 |
if (params.exact) body.exact = true;
|
| 1618 |
return body;
|
|
@@ -1796,10 +1808,7 @@ function applyInitialSearchPayload(data) {
|
|
| 1796 |
if (!data || !Array.isArray(data.results) || !canUseInitialSearchPayload()) return false;
|
| 1797 |
if (STATE.mode === "repo" && data.repo !== STATE.repoFull) return false;
|
| 1798 |
if (STATE.mode === "global" && data.mode !== "global") return false;
|
| 1799 |
-
if (
|
| 1800 |
-
cancelSearchPrefetch();
|
| 1801 |
-
searchAbortController = new AbortController();
|
| 1802 |
-
searchRequestId++;
|
| 1803 |
STATE.total = data.total || 0;
|
| 1804 |
STATE.page = 1;
|
| 1805 |
STATE.results = data.results.slice();
|
|
@@ -1838,7 +1847,9 @@ function applyInitialSearchPayload(data) {
|
|
| 1838 |
|
| 1839 |
async function searchWithInitialFallback() {
|
| 1840 |
saveSearchViewSnapshot();
|
|
|
|
| 1841 |
cancelPositionRestore();
|
|
|
|
| 1842 |
const key = getSearchViewKey(), entry = positionEntryId;
|
| 1843 |
prepareReturnPosition(key);
|
| 1844 |
if (searchViewSnapshots.has(key)) {
|
|
@@ -2415,6 +2426,7 @@ const READER_RETURN_SEARCH_KEYS = Object.freeze([
|
|
| 2415 |
]);
|
| 2416 |
|
| 2417 |
let readerOverlay = null;
|
|
|
|
| 2418 |
let readerUiState = "base";
|
| 2419 |
let readerClosing = false;
|
| 2420 |
const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", {
|
|
@@ -2437,9 +2449,69 @@ function captureReaderReturnScroll() {
|
|
| 2437 |
index = findVirtualIndex(top);
|
| 2438 |
offset = top - getVirtualOffset(index);
|
| 2439 |
}
|
| 2440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2441 |
}
|
| 2442 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2443 |
const saved = readerReturnScrollState;
|
| 2444 |
if (!saved) return;
|
| 2445 |
if (saved.route && saved.route !== location.href) { readerReturnScrollState = null; return; }
|
|
@@ -2447,14 +2519,14 @@ function restoreReaderReturnScroll(windowRendered = false) {
|
|
| 2447 |
const generation = ++readerReturnRestoreGeneration;
|
| 2448 |
let attempts = 0;
|
| 2449 |
const restore = () => {
|
| 2450 |
-
if (generation !== readerReturnRestoreGeneration) return;
|
| 2451 |
if (!DOM.resultsContainer || !STATE.results.length) {
|
| 2452 |
if (++attempts < 20) requestAnimationFrame(restore);
|
| 2453 |
return;
|
| 2454 |
}
|
| 2455 |
ensureHeightTree();
|
| 2456 |
const index = Math.min(saved.index, STATE.results.length - 1);
|
| 2457 |
-
const target = Math.max(0, getVirtualOffset(index) + saved.offset);
|
| 2458 |
const max = Math.max(0, getVirtualTotalHeight() - DOM.resultsContainer.clientHeight);
|
| 2459 |
readerReturnRestoreActive = true;
|
| 2460 |
setResultScrollTop(Math.min(target, max));
|
|
@@ -2474,10 +2546,12 @@ function restoreReaderReturnScroll(windowRendered = false) {
|
|
| 2474 |
}
|
| 2475 |
function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {
|
| 2476 |
if (!readerOverlay) return false;
|
|
|
|
| 2477 |
readerClosing = false;
|
| 2478 |
readerUiState = "base";
|
| 2479 |
-
const returnFocus = readerNavigation.unmount();
|
| 2480 |
readerOverlay = null;
|
|
|
|
|
|
|
| 2481 |
if (restoreScroll) {
|
| 2482 |
const saved = readerReturnScrollState;
|
| 2483 |
const snapshot = readerReturnSnapshot;
|
|
@@ -2500,6 +2574,7 @@ function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {
|
|
| 2500 |
}
|
| 2501 |
|
| 2502 |
function openReaderOverlay(url, addHistory = true) {
|
|
|
|
| 2503 |
if (addHistory && !readerReturnScrollState) {
|
| 2504 |
readerReturnScrollState = captureReaderReturnScroll();
|
| 2505 |
readerReturnSnapshot = saveSearchViewSnapshot(readerReturnScrollState?.viewKey || getSearchViewKey());
|
|
@@ -2517,7 +2592,9 @@ function restoreReaderOverlay(state) {
|
|
| 2517 |
}
|
| 2518 |
try {
|
| 2519 |
const url = readerNavigation.parse(state.readerUrl);
|
|
|
|
| 2520 |
closeReaderOverlay(false, false);
|
|
|
|
| 2521 |
openReaderOverlay(url, false);
|
| 2522 |
} catch (_) {}
|
| 2523 |
}
|
|
@@ -2549,11 +2626,10 @@ function handleReaderMessage(event) {
|
|
| 2549 |
}
|
| 2550 |
const overlay = readerOverlay;
|
| 2551 |
history.back();
|
| 2552 |
-
//
|
| 2553 |
setTimeout(() => {
|
| 2554 |
if (!readerClosing || readerOverlay !== overlay) return;
|
| 2555 |
-
|
| 2556 |
-
history.replaceState(null, "", returnUrl);
|
| 2557 |
}, 1000);
|
| 2558 |
return;
|
| 2559 |
}
|
|
@@ -2881,6 +2957,11 @@ async function loadSidebarInitial(repo) {
|
|
| 2881 |
return pending;
|
| 2882 |
}
|
| 2883 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2884 |
function buildSearchURLParams() {
|
| 2885 |
const params = new URLSearchParams();
|
| 2886 |
if (STATE.query) params.set("q", STATE.query);
|
|
@@ -2971,15 +3052,14 @@ const ROUTER = {
|
|
| 2971 |
history.pushState(null, "", url);
|
| 2972 |
this.apply();
|
| 2973 |
},
|
| 2974 |
-
apply() {
|
| 2975 |
const route = this.parse();
|
| 2976 |
const prevMode = STATE.mode;
|
| 2977 |
const prevRepo = STATE.repo;
|
| 2978 |
const previousPath = STATE.browserPath;
|
| 2979 |
-
const previousSearchKey = routeInitialized
|
| 2980 |
const previousPage = STATE.page;
|
| 2981 |
saveSearchViewSnapshot();
|
| 2982 |
-
cancelPositionRestore();
|
| 2983 |
STATE.mode = route.mode;
|
| 2984 |
STATE.repo = route.repo;
|
| 2985 |
STATE.repoFull = route.repo ? `VoiceOfML/${route.repo}` : null;
|
|
@@ -2994,8 +3074,18 @@ const ROUTER = {
|
|
| 2994 |
STATE.folderTreeCollapsed = {};
|
| 2995 |
STATE.browserPath = "";
|
| 2996 |
API._extCache = null;
|
| 2997 |
-
syncURLToState();
|
| 2998 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2999 |
this.updateUI();
|
| 3000 |
updateRandomTxtVisibility();
|
| 3001 |
if (prevMode !== STATE.mode || prevRepo !== STATE.repo) {
|
|
@@ -3006,12 +3096,10 @@ const ROUTER = {
|
|
| 3006 |
syncStateToURL(true);
|
| 3007 |
}
|
| 3008 |
} else {
|
| 3009 |
-
syncURLToState();
|
| 3010 |
const routeId = ++routeRenderId;
|
| 3011 |
-
if (
|
| 3012 |
-
previousSearchKey === getSearchViewKey()) {
|
| 3013 |
STATE.page = previousPage;
|
| 3014 |
-
renderBrowser(STATE.browserPath || "", routeId);
|
| 3015 |
retainFilterRenderingForRoute(routeId);
|
| 3016 |
routeInitialized = true;
|
| 3017 |
persistSearchSession();
|
|
@@ -3071,7 +3159,7 @@ function syncStateToURL(replace = true) {
|
|
| 3071 |
const path = STATE.mode === "global" ? "/" : `/${STATE.repo}`;
|
| 3072 |
const url = qs ? `${path}?${qs}` : path;
|
| 3073 |
if (replace) {
|
| 3074 |
-
history.replaceState(
|
| 3075 |
} else {
|
| 3076 |
history.pushState(null, "", url);
|
| 3077 |
}
|
|
@@ -3085,10 +3173,10 @@ function syncURLToState() {
|
|
| 3085 |
STATE.query = Array.from(STATE.query).slice(0, 256).join("");
|
| 3086 |
showToast("搜索内容已限制为 256 个字符");
|
| 3087 |
}
|
| 3088 |
-
setSearchInputValue(STATE.query);
|
| 3089 |
STATE.filterRepos = params.getAll("repo").map(r => `VoiceOfML/${r}`);
|
| 3090 |
STATE.browserPath = params.get("path") || "";
|
| 3091 |
-
const sort = params.get("sort")
|
| 3092 |
DOM.sortSelect.value = sort;
|
| 3093 |
const extStr = params.get("ext");
|
| 3094 |
if (extStr !== null) {
|
|
@@ -3407,10 +3495,72 @@ function submitSearchQuery(query, { restore = false, record = false, refreshHist
|
|
| 3407 |
return result;
|
| 3408 |
}
|
| 3409 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3410 |
function debouncedSearch() {
|
| 3411 |
-
if (searchComposing) return;
|
| 3412 |
clearTimeout(searchTimer);
|
|
|
|
| 3413 |
searchTimer = setTimeout(() => {
|
|
|
|
|
|
|
| 3414 |
submitSearchQuery(DOM.searchInput.value.trim(), { record: true, refreshHistory: true });
|
| 3415 |
}, 100);
|
| 3416 |
}
|
|
@@ -4048,10 +4198,12 @@ function setSearchVisualLoading(loading) {
|
|
| 4048 |
}
|
| 4049 |
|
| 4050 |
function prepareFilterChange(clearResults) {
|
| 4051 |
-
// Merge
|
|
|
|
| 4052 |
applyPendingSizeFilters();
|
| 4053 |
cancelPendingSearchControls();
|
| 4054 |
saveSearchViewSnapshot();
|
|
|
|
| 4055 |
STATE.page = 1;
|
| 4056 |
if (clearResults) STATE.results = [];
|
| 4057 |
}
|
|
@@ -4090,12 +4242,11 @@ function setupSizeFilterControls() {
|
|
| 4090 |
|
| 4091 |
function scheduleFilterSearch(clearResults = false) {
|
| 4092 |
prepareFilterChange(clearResults);
|
|
|
|
|
|
|
| 4093 |
cancelPositionRestore();
|
|
|
|
| 4094 |
resetPagingRecovery();
|
| 4095 |
-
if (searchAbortController) searchAbortController.abort();
|
| 4096 |
-
cancelSearchPrefetch();
|
| 4097 |
-
searchRequestId++;
|
| 4098 |
-
searchId++;
|
| 4099 |
STATE.isLoading = true;
|
| 4100 |
setSearchVisualLoading(true);
|
| 4101 |
syncStateToURL(true);
|
|
@@ -4129,10 +4280,21 @@ function updateLoadInfo() {
|
|
| 4129 |
}
|
| 4130 |
|
| 4131 |
function cancelSearchPrefetch() {
|
| 4132 |
-
|
| 4133 |
-
searchPrefetchAbortController?.cacheWaits?.forEach(wait => wait.controller.abort());
|
| 4134 |
-
searchPrefetchAbortController?.abort();
|
| 4135 |
searchPrefetchAbortController = null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4136 |
}
|
| 4137 |
|
| 4138 |
function prefetchSearchPages(base, template) {
|
|
@@ -4271,10 +4433,13 @@ function consumeCachedAppendPage() {
|
|
| 4271 |
|
| 4272 |
async function doSearch(append = false, fromStart = false, restorePosition = false) {
|
| 4273 |
if (append && resultWindow) { loadResultWindowPage(STATE._loadedPage + 1); return; }
|
| 4274 |
-
if (!append && !fromStart) backToTopPending = false;
|
| 4275 |
-
if (!append && prepareSearchPositionNavigation({ fromStart, restorePosition })) return;
|
| 4276 |
const recoveringFirstPage = append && !STATE._loadedPage;
|
| 4277 |
if (recoveringFirstPage) append = false;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4278 |
clearTimeout(filterSearchTimer);
|
| 4279 |
filterSearchTimer = null;
|
| 4280 |
if (!append) {
|
|
@@ -4283,9 +4448,6 @@ async function doSearch(append = false, fromStart = false, restorePosition = fal
|
|
| 4283 |
selectedIndices = {};
|
| 4284 |
lastSelectedIndex = -1;
|
| 4285 |
if (DOM.multiSelectToggle && DOM.multiSelectToggle.checked) updateSelectionUI();
|
| 4286 |
-
if (searchAbortController) searchAbortController.abort();
|
| 4287 |
-
cancelSearchPrefetch();
|
| 4288 |
-
searchAbortController = new AbortController();
|
| 4289 |
STATE._pageCache = {};
|
| 4290 |
STATE._loadedPage = 0;
|
| 4291 |
STATE._pagingAppendScrollTop = null;
|
|
@@ -5688,6 +5850,7 @@ async function init() {
|
|
| 5688 |
if (document.visibilityState === "hidden") flushSidebarScroll();
|
| 5689 |
});
|
| 5690 |
syncSearchInputState();
|
|
|
|
| 5691 |
// Session and position databases are independent; start both without
|
| 5692 |
// serializing their I/O. Route handling still waits for both to settle.
|
| 5693 |
const positionsReady = initSearchPositions();
|
|
@@ -5705,17 +5868,6 @@ async function init() {
|
|
| 5705 |
else if (savedMobile === "desktop") STATE.isMobile = false;
|
| 5706 |
else STATE.isMobile = autoDetectMobile();
|
| 5707 |
applyMobileMode();
|
| 5708 |
-
DOM.searchInput.addEventListener("input", () => {
|
| 5709 |
-
syncSearchInputState();
|
| 5710 |
-
debouncedSearch();
|
| 5711 |
-
});
|
| 5712 |
-
DOM.searchInput.addEventListener("compositionstart", () => {
|
| 5713 |
-
searchComposing = true;
|
| 5714 |
-
});
|
| 5715 |
-
DOM.searchInput.addEventListener("compositionend", () => {
|
| 5716 |
-
searchComposing = false;
|
| 5717 |
-
debouncedSearch();
|
| 5718 |
-
});
|
| 5719 |
setupSearchHistory();
|
| 5720 |
DOM.historyToggle.addEventListener("change", () => {
|
| 5721 |
STATE.recordHistory = DOM.historyToggle.checked;
|
|
@@ -5875,8 +6027,10 @@ async function init() {
|
|
| 5875 |
restoreReaderOverlay(event.state);
|
| 5876 |
return;
|
| 5877 |
}
|
| 5878 |
-
|
| 5879 |
-
|
|
|
|
|
|
|
| 5880 |
});
|
| 5881 |
window.addEventListener("resize", () => {
|
| 5882 |
if (!readSearchPreference("mobileMode")) {
|
|
@@ -5902,7 +6056,10 @@ async function init() {
|
|
| 5902 |
window.addEventListener("pageshow", resumeResultRecovery);
|
| 5903 |
window.addEventListener("online", resumeResultRecovery);
|
| 5904 |
window.setInterval(() => warmConnection(), KEEPALIVE_INTERVAL_MS);
|
|
|
|
| 5905 |
ROUTER.apply();
|
|
|
|
|
|
|
| 5906 |
// Keep the first search paint independent of the multi-megabyte Reader sidecar.
|
| 5907 |
// API results already carry Reader fields; the sidecar is only enrichment for
|
| 5908 |
// local snapshots and directory browsing. Load it on the first real
|
|
|
|
| 118 |
let scrollLoadTimer = null;
|
| 119 |
let scrollRecoveryTimer = null;
|
| 120 |
let searchComposing = false;
|
| 121 |
+
let searchInputGeneration = 0;
|
| 122 |
+
let searchCompositionGeneration = 0;
|
| 123 |
+
/** @type {string | null} */
|
| 124 |
+
let searchCompositionViewKey = null;
|
| 125 |
+
let searchInputReady = false;
|
| 126 |
+
let initialSearchDraft = false;
|
| 127 |
+
/** @type {{href: string, key: string | undefined, cancelled: boolean} | null} */
|
| 128 |
+
let initialSearchDraftOwner = null;
|
| 129 |
let keepalivePending = null;
|
| 130 |
let lastKeepaliveAt = 0;
|
| 131 |
const KEEPALIVE_INTERVAL_MS = 45 * 1000;
|
|
|
|
| 386 |
saveSearchViewSnapshot();
|
| 387 |
const key = getSearchViewKey();
|
| 388 |
if (fromStart) saveSearchPosition();
|
| 389 |
+
const owner = searchId;
|
| 390 |
cancelPositionRestore();
|
| 391 |
+
if (owner !== searchId) return true;
|
| 392 |
prepareReturnPosition(key, !fromStart);
|
| 393 |
if (!restorePosition) return false;
|
| 394 |
setReturnPositionTarget();
|
|
|
|
| 831 |
function cancelPositionRestore() {
|
| 832 |
cancelSnapshotClone();
|
| 833 |
positionEntryId++;
|
| 834 |
+
const previousWindow = resultWindow;
|
| 835 |
+
const previousRestore = positionRestore;
|
| 836 |
resultWindow = null;
|
|
|
|
|
|
|
|
|
|
| 837 |
positionRestore = null;
|
| 838 |
+
updateResultWindowStatus();
|
| 839 |
+
if (previousRestore) {
|
| 840 |
+
STATE.isLoading = false;
|
| 841 |
+
showPositionRestoreStatus("");
|
| 842 |
+
}
|
| 843 |
+
previousWindow?.controller.abort();
|
| 844 |
+
previousRestore?.controller.abort();
|
| 845 |
}
|
| 846 |
|
| 847 |
function tryRestoreSearchPosition(key, options = {}) {
|
|
|
|
| 850 |
if (!validSearchPosition(position)) return false;
|
| 851 |
cancelPendingSearchControls();
|
| 852 |
if (!options.position && positionRestore?.key === key && !positionRestore.failed) return true;
|
| 853 |
+
if (!cancelActiveSearch()) return false;
|
| 854 |
+
const owner = searchId;
|
| 855 |
cancelPositionRestore();
|
| 856 |
+
if (owner !== searchId) return false;
|
| 857 |
setReturnPositionTarget();
|
|
|
|
|
|
|
|
|
|
| 858 |
const controller = new AbortController();
|
| 859 |
const task = { key, controller, position: {...position}, lookup: previous?.lookup, ready: previous?.ready || new Map(), page: 0, results: [] };
|
| 860 |
positionRestore = task;
|
|
|
|
| 1456 |
function restoreSearchViewSnapshot(key, restoreScroll = true, preserveRestore = false) {
|
| 1457 |
const snapshot = searchViewSnapshots.get(key);
|
| 1458 |
if (!snapshot || snapshot.version !== SEARCH_VIEW_SNAPSHOT_VERSION || snapshot.loadedPage < 1) return restoreScroll && tryRestoreSearchPosition(key);
|
| 1459 |
+
if (!cancelActiveSearch()) return false;
|
| 1460 |
+
const owner = searchId;
|
| 1461 |
if (!preserveRestore) cancelPositionRestore();
|
| 1462 |
+
if (owner !== searchId) return false;
|
| 1463 |
cancelPendingSearchControls();
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1464 |
const materialized = snapshot.window?.count ?? snapshot.results.length;
|
| 1465 |
STATE.results = materialized > 2000 && !preserveRestore
|
| 1466 |
? prepareSnapshotClone(snapshot, key, restoreScroll) : snapshot.results.map(cloneSearchResult);
|
|
|
|
| 1624 |
}
|
| 1625 |
if (params.min_size != null) body.min_size = params.min_size;
|
| 1626 |
if (params.max_size != null) body.max_size = params.max_size;
|
| 1627 |
+
body.sort = normalizeSearchSort(params.sort || DOM.sortSelect.value);
|
| 1628 |
if (params.search_folders === false) body.search_folders = false;
|
| 1629 |
if (params.exact) body.exact = true;
|
| 1630 |
return body;
|
|
|
|
| 1808 |
if (!data || !Array.isArray(data.results) || !canUseInitialSearchPayload()) return false;
|
| 1809 |
if (STATE.mode === "repo" && data.repo !== STATE.repoFull) return false;
|
| 1810 |
if (STATE.mode === "global" && data.mode !== "global") return false;
|
| 1811 |
+
if (!cancelActiveSearch()) return false;
|
|
|
|
|
|
|
|
|
|
| 1812 |
STATE.total = data.total || 0;
|
| 1813 |
STATE.page = 1;
|
| 1814 |
STATE.results = data.results.slice();
|
|
|
|
| 1847 |
|
| 1848 |
async function searchWithInitialFallback() {
|
| 1849 |
saveSearchViewSnapshot();
|
| 1850 |
+
const owner = searchId;
|
| 1851 |
cancelPositionRestore();
|
| 1852 |
+
if (owner !== searchId) return false;
|
| 1853 |
const key = getSearchViewKey(), entry = positionEntryId;
|
| 1854 |
prepareReturnPosition(key);
|
| 1855 |
if (searchViewSnapshots.has(key)) {
|
|
|
|
| 2426 |
]);
|
| 2427 |
|
| 2428 |
let readerOverlay = null;
|
| 2429 |
+
let readerOverlayRevision = 0;
|
| 2430 |
let readerUiState = "base";
|
| 2431 |
let readerClosing = false;
|
| 2432 |
const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", {
|
|
|
|
| 2449 |
index = findVirtualIndex(top);
|
| 2450 |
offset = top - getVirtualOffset(index);
|
| 2451 |
}
|
| 2452 |
+
const active = document.activeElement;
|
| 2453 |
+
const focus = active instanceof HTMLElement && active.id ? { id: active.id,
|
| 2454 |
+
start: active instanceof HTMLInputElement ? active.selectionStart : null,
|
| 2455 |
+
end: active instanceof HTMLInputElement ? active.selectionEnd : null,
|
| 2456 |
+
direction: active instanceof HTMLInputElement ? active.selectionDirection : null } : null;
|
| 2457 |
+
return { route: location.href, viewKey: getSearchViewKey(), top, index, offset, focus };
|
| 2458 |
+
}
|
| 2459 |
+
function readerSearchHandoffReady(saved) {
|
| 2460 |
+
// A preview has already restored usable rows and geometry while validation
|
| 2461 |
+
// may still be fetching adjacent pages. Keep that validation running.
|
| 2462 |
+
if (STATE.isLoading || !STATE._loadedPage || !STATE.results.length) return false;
|
| 2463 |
+
if (positionRestore && (!positionRestore.preview || positionRestore.key !== saved.viewKey)) return false;
|
| 2464 |
+
const index = Math.min(saved.index, Math.max(0, STATE.total - 1));
|
| 2465 |
+
return !!STATE.results[index];
|
| 2466 |
}
|
| 2467 |
+
|
| 2468 |
+
function restoreReaderSearchHandoff() {
|
| 2469 |
+
let saved;
|
| 2470 |
+
try {
|
| 2471 |
+
const handoff = JSON.parse(sessionStorage.getItem("reader-navigation-restore") || "null");
|
| 2472 |
+
sessionStorage.removeItem("reader-navigation-restore");
|
| 2473 |
+
if (!handoff || handoff.returnUrl !== location.href) return;
|
| 2474 |
+
const current = /** @type {{readerUrl?: string; returnScroll?: ReturnType<typeof captureReaderReturnScroll>} | null} */ (readerNavigation.saved());
|
| 2475 |
+
if (!current || current.readerUrl !== handoff.readerUrl) return;
|
| 2476 |
+
const url = readerNavigation.parse(handoff.readerUrl);
|
| 2477 |
+
const token = url.searchParams.get("nav");
|
| 2478 |
+
if (!token || sessionStorage.getItem("reader-return:" + token) !== location.href) return;
|
| 2479 |
+
saved = current.returnScroll;
|
| 2480 |
+
if (!saved || saved.route !== location.href || saved.viewKey !== getSearchViewKey() ||
|
| 2481 |
+
!Number.isInteger(saved.index) || saved.index < 0 || !Number.isFinite(saved.offset) || !Number.isFinite(saved.top)) return;
|
| 2482 |
+
} catch (_) { return; }
|
| 2483 |
+
const route = location.href;
|
| 2484 |
+
let cancelled = false;
|
| 2485 |
+
const cancel = () => { cancelled = true; cleanup(); };
|
| 2486 |
+
const cleanup = () => {
|
| 2487 |
+
for (const type of ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"])
|
| 2488 |
+
document.removeEventListener(type, cancel, true);
|
| 2489 |
+
};
|
| 2490 |
+
for (const type of ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"])
|
| 2491 |
+
document.addEventListener(type, cancel, true);
|
| 2492 |
+
const routeRevision = routeRenderId;
|
| 2493 |
+
const deadline = Date.now() + 30000;
|
| 2494 |
+
const restore = () => {
|
| 2495 |
+
if (cancelled || routeRevision !== routeRenderId || location.href !== route || saved.viewKey !== getSearchViewKey() || Date.now() > deadline) {
|
| 2496 |
+
cleanup(); return;
|
| 2497 |
+
}
|
| 2498 |
+
if (!readerSearchHandoffReady(saved)) { requestAnimationFrame(restore); return; }
|
| 2499 |
+
cleanup();
|
| 2500 |
+
readerReturnScrollState = saved;
|
| 2501 |
+
restoreReaderReturnScroll(false, true);
|
| 2502 |
+
const focus = saved.focus;
|
| 2503 |
+
const element = focus && document.getElementById(focus.id);
|
| 2504 |
+
if (!element || (document.activeElement !== document.body && document.activeElement !== element)) return;
|
| 2505 |
+
element.focus({ preventScroll: true });
|
| 2506 |
+
if (element instanceof HTMLInputElement && Number.isInteger(focus.start) && Number.isInteger(focus.end) &&
|
| 2507 |
+
["forward", "backward", "none"].includes(focus.direction)) {
|
| 2508 |
+
try { element.setSelectionRange(focus.start, focus.end, focus.direction); } catch (_) {}
|
| 2509 |
+
}
|
| 2510 |
+
};
|
| 2511 |
+
requestAnimationFrame(restore);
|
| 2512 |
+
}
|
| 2513 |
+
|
| 2514 |
+
function restoreReaderReturnScroll(windowRendered = false, restoreTop = false) {
|
| 2515 |
const saved = readerReturnScrollState;
|
| 2516 |
if (!saved) return;
|
| 2517 |
if (saved.route && saved.route !== location.href) { readerReturnScrollState = null; return; }
|
|
|
|
| 2519 |
const generation = ++readerReturnRestoreGeneration;
|
| 2520 |
let attempts = 0;
|
| 2521 |
const restore = () => {
|
| 2522 |
+
if (generation !== readerReturnRestoreGeneration || saved.viewKey !== getSearchViewKey() || saved.route !== location.href) return;
|
| 2523 |
if (!DOM.resultsContainer || !STATE.results.length) {
|
| 2524 |
if (++attempts < 20) requestAnimationFrame(restore);
|
| 2525 |
return;
|
| 2526 |
}
|
| 2527 |
ensureHeightTree();
|
| 2528 |
const index = Math.min(saved.index, STATE.results.length - 1);
|
| 2529 |
+
const target = Math.max(0, restoreTop ? saved.top : getVirtualOffset(index) + saved.offset);
|
| 2530 |
const max = Math.max(0, getVirtualTotalHeight() - DOM.resultsContainer.clientHeight);
|
| 2531 |
readerReturnRestoreActive = true;
|
| 2532 |
setResultScrollTop(Math.min(target, max));
|
|
|
|
| 2546 |
}
|
| 2547 |
function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {
|
| 2548 |
if (!readerOverlay) return false;
|
| 2549 |
+
readerOverlayRevision++;
|
| 2550 |
readerClosing = false;
|
| 2551 |
readerUiState = "base";
|
|
|
|
| 2552 |
readerOverlay = null;
|
| 2553 |
+
const returnFocus = readerNavigation.unmount();
|
| 2554 |
+
if (readerOverlay) return true;
|
| 2555 |
if (restoreScroll) {
|
| 2556 |
const saved = readerReturnScrollState;
|
| 2557 |
const snapshot = readerReturnSnapshot;
|
|
|
|
| 2574 |
}
|
| 2575 |
|
| 2576 |
function openReaderOverlay(url, addHistory = true) {
|
| 2577 |
+
readerOverlayRevision++;
|
| 2578 |
if (addHistory && !readerReturnScrollState) {
|
| 2579 |
readerReturnScrollState = captureReaderReturnScroll();
|
| 2580 |
readerReturnSnapshot = saveSearchViewSnapshot(readerReturnScrollState?.viewKey || getSearchViewKey());
|
|
|
|
| 2592 |
}
|
| 2593 |
try {
|
| 2594 |
const url = readerNavigation.parse(state.readerUrl);
|
| 2595 |
+
const revision = readerOverlayRevision + (readerOverlay ? 1 : 0);
|
| 2596 |
closeReaderOverlay(false, false);
|
| 2597 |
+
if (readerOverlayRevision !== revision) return;
|
| 2598 |
openReaderOverlay(url, false);
|
| 2599 |
} catch (_) {}
|
| 2600 |
}
|
|
|
|
| 2626 |
}
|
| 2627 |
const overlay = readerOverlay;
|
| 2628 |
history.back();
|
| 2629 |
+
// Back may still arrive: keep its Reader entry intact for Forward.
|
| 2630 |
setTimeout(() => {
|
| 2631 |
if (!readerClosing || readerOverlay !== overlay) return;
|
| 2632 |
+
readerNavigation.showCloseRecovery(returnUrl);
|
|
|
|
| 2633 |
}, 1000);
|
| 2634 |
return;
|
| 2635 |
}
|
|
|
|
| 2957 |
return pending;
|
| 2958 |
}
|
| 2959 |
|
| 2960 |
+
/** @param {unknown} value */
|
| 2961 |
+
function normalizeSearchSort(value) {
|
| 2962 |
+
return value === "name" || value === "size" ? value : "relevance";
|
| 2963 |
+
}
|
| 2964 |
+
|
| 2965 |
function buildSearchURLParams() {
|
| 2966 |
const params = new URLSearchParams();
|
| 2967 |
if (STATE.query) params.set("q", STATE.query);
|
|
|
|
| 3052 |
history.pushState(null, "", url);
|
| 3053 |
this.apply();
|
| 3054 |
},
|
| 3055 |
+
apply(preserveSameView = false) {
|
| 3056 |
const route = this.parse();
|
| 3057 |
const prevMode = STATE.mode;
|
| 3058 |
const prevRepo = STATE.repo;
|
| 3059 |
const previousPath = STATE.browserPath;
|
| 3060 |
+
const previousSearchKey = routeInitialized ? getSearchViewKey() : null;
|
| 3061 |
const previousPage = STATE.page;
|
| 3062 |
saveSearchViewSnapshot();
|
|
|
|
| 3063 |
STATE.mode = route.mode;
|
| 3064 |
STATE.repo = route.repo;
|
| 3065 |
STATE.repoFull = route.repo ? `VoiceOfML/${route.repo}` : null;
|
|
|
|
| 3074 |
STATE.folderTreeCollapsed = {};
|
| 3075 |
STATE.browserPath = "";
|
| 3076 |
API._extCache = null;
|
|
|
|
| 3077 |
}
|
| 3078 |
+
syncURLToState();
|
| 3079 |
+
const sameSearchView = previousSearchKey === getSearchViewKey();
|
| 3080 |
+
if (!sameSearchView) {
|
| 3081 |
+
if (routeInitialized) searchInputGeneration++;
|
| 3082 |
+
cancelPendingSearchControls();
|
| 3083 |
+
readerReturnRestoreGeneration++;
|
| 3084 |
+
if (!cancelActiveSearch()) return;
|
| 3085 |
+
}
|
| 3086 |
+
const owner = searchId;
|
| 3087 |
+
if (!sameSearchView || (!preserveSameView && previousPath === STATE.browserPath)) cancelPositionRestore();
|
| 3088 |
+
if (owner !== searchId) return;
|
| 3089 |
this.updateUI();
|
| 3090 |
updateRandomTxtVisibility();
|
| 3091 |
if (prevMode !== STATE.mode || prevRepo !== STATE.repo) {
|
|
|
|
| 3096 |
syncStateToURL(true);
|
| 3097 |
}
|
| 3098 |
} else {
|
|
|
|
| 3099 |
const routeId = ++routeRenderId;
|
| 3100 |
+
if (sameSearchView && (preserveSameView || (STATE.mode === "repo" && previousPath !== STATE.browserPath))) {
|
|
|
|
| 3101 |
STATE.page = previousPage;
|
| 3102 |
+
if (STATE.mode === "repo" && previousPath !== STATE.browserPath) renderBrowser(STATE.browserPath || "", routeId);
|
| 3103 |
retainFilterRenderingForRoute(routeId);
|
| 3104 |
routeInitialized = true;
|
| 3105 |
persistSearchSession();
|
|
|
|
| 3159 |
const path = STATE.mode === "global" ? "/" : `/${STATE.repo}`;
|
| 3160 |
const url = qs ? `${path}?${qs}` : path;
|
| 3161 |
if (replace) {
|
| 3162 |
+
history.replaceState(history.state, "", url);
|
| 3163 |
} else {
|
| 3164 |
history.pushState(null, "", url);
|
| 3165 |
}
|
|
|
|
| 3173 |
STATE.query = Array.from(STATE.query).slice(0, 256).join("");
|
| 3174 |
showToast("搜索内容已限制为 256 个字符");
|
| 3175 |
}
|
| 3176 |
+
if (!searchComposing && !initialSearchDraft) setSearchInputValue(STATE.query);
|
| 3177 |
STATE.filterRepos = params.getAll("repo").map(r => `VoiceOfML/${r}`);
|
| 3178 |
STATE.browserPath = params.get("path") || "";
|
| 3179 |
+
const sort = normalizeSearchSort(params.get("sort"));
|
| 3180 |
DOM.sortSelect.value = sort;
|
| 3181 |
const extStr = params.get("ext");
|
| 3182 |
if (extStr !== null) {
|
|
|
|
| 3495 |
return result;
|
| 3496 |
}
|
| 3497 |
|
| 3498 |
+
function currentSearchEntryKey() {
|
| 3499 |
+
return /** @type {Window & {navigation?: {currentEntry?: {key?: string} | null}}} */ (window).navigation?.currentEntry?.key;
|
| 3500 |
+
}
|
| 3501 |
+
|
| 3502 |
+
function captureInitialSearchDraft(renew = false) {
|
| 3503 |
+
if (searchInputReady) return;
|
| 3504 |
+
initialSearchDraft = true;
|
| 3505 |
+
if (renew || !initialSearchDraftOwner) initialSearchDraftOwner = {
|
| 3506 |
+
href: location.href, key: currentSearchEntryKey(), cancelled: false
|
| 3507 |
+
};
|
| 3508 |
+
}
|
| 3509 |
+
|
| 3510 |
+
function cancelInitialSearchDraft() {
|
| 3511 |
+
if (initialSearchDraftOwner) initialSearchDraftOwner.cancelled = true;
|
| 3512 |
+
}
|
| 3513 |
+
|
| 3514 |
+
function initialSearchDraftIsCurrent() {
|
| 3515 |
+
const owner = initialSearchDraftOwner;
|
| 3516 |
+
return !owner || (!owner.cancelled && owner.href === location.href &&
|
| 3517 |
+
(owner.key === undefined || owner.key === currentSearchEntryKey()));
|
| 3518 |
+
}
|
| 3519 |
+
|
| 3520 |
+
function finishInitialSearchInput(current) {
|
| 3521 |
+
for (const type of ["popstate", "hashchange", "pagehide"]) window.removeEventListener(type, cancelInitialSearchDraft, true);
|
| 3522 |
+
searchInputReady = true;
|
| 3523 |
+
if (!current) searchInputGeneration++;
|
| 3524 |
+
if (initialSearchDraft) {
|
| 3525 |
+
initialSearchDraft = false;
|
| 3526 |
+
if (current) debouncedSearch();
|
| 3527 |
+
}
|
| 3528 |
+
initialSearchDraftOwner = null;
|
| 3529 |
+
}
|
| 3530 |
+
|
| 3531 |
+
function setupSearchInput() {
|
| 3532 |
+
for (const type of ["popstate", "hashchange", "pagehide"]) window.addEventListener(type, cancelInitialSearchDraft, true);
|
| 3533 |
+
DOM.searchInput.addEventListener("input", event => {
|
| 3534 |
+
const compositionInput = event.isComposing || event.inputType === "insertCompositionText" || event.inputType === "insertFromComposition";
|
| 3535 |
+
captureInitialSearchDraft(!searchComposing && !compositionInput);
|
| 3536 |
+
syncSearchInputState();
|
| 3537 |
+
if (compositionInput) return;
|
| 3538 |
+
debouncedSearch();
|
| 3539 |
+
});
|
| 3540 |
+
DOM.searchInput.addEventListener("compositionstart", () => {
|
| 3541 |
+
captureInitialSearchDraft(true);
|
| 3542 |
+
clearTimeout(searchTimer);
|
| 3543 |
+
searchTimer = null;
|
| 3544 |
+
searchComposing = true;
|
| 3545 |
+
searchCompositionGeneration = searchInputGeneration;
|
| 3546 |
+
searchCompositionViewKey = routeInitialized ? getSearchViewKey() : null;
|
| 3547 |
+
});
|
| 3548 |
+
DOM.searchInput.addEventListener("compositionend", () => {
|
| 3549 |
+
searchComposing = false;
|
| 3550 |
+
// Keep the visible draft, but an old view's completion cannot submit in B.
|
| 3551 |
+
if (searchCompositionGeneration !== searchInputGeneration ||
|
| 3552 |
+
(searchCompositionViewKey !== null && searchCompositionViewKey !== getSearchViewKey())) return;
|
| 3553 |
+
debouncedSearch();
|
| 3554 |
+
});
|
| 3555 |
+
}
|
| 3556 |
+
|
| 3557 |
function debouncedSearch() {
|
| 3558 |
+
if (searchComposing || !searchInputReady) return;
|
| 3559 |
clearTimeout(searchTimer);
|
| 3560 |
+
const generation = searchInputGeneration;
|
| 3561 |
searchTimer = setTimeout(() => {
|
| 3562 |
+
searchTimer = null;
|
| 3563 |
+
if (searchComposing || generation !== searchInputGeneration) return;
|
| 3564 |
submitSearchQuery(DOM.searchInput.value.trim(), { record: true, refreshHistory: true });
|
| 3565 |
}, 100);
|
| 3566 |
}
|
|
|
|
| 4198 |
}
|
| 4199 |
|
| 4200 |
function prepareFilterChange(clearResults) {
|
| 4201 |
+
// Merge completed query drafts too; a filter click must not discard typing.
|
| 4202 |
+
const query = searchTimer !== null && !searchComposing ? DOM.searchInput.value.trim() : null;
|
| 4203 |
applyPendingSizeFilters();
|
| 4204 |
cancelPendingSearchControls();
|
| 4205 |
saveSearchViewSnapshot();
|
| 4206 |
+
if (query !== null && Array.from(query).length <= 256) STATE.query = query;
|
| 4207 |
STATE.page = 1;
|
| 4208 |
if (clearResults) STATE.results = [];
|
| 4209 |
}
|
|
|
|
| 4242 |
|
| 4243 |
function scheduleFilterSearch(clearResults = false) {
|
| 4244 |
prepareFilterChange(clearResults);
|
| 4245 |
+
if (!cancelActiveSearch()) return;
|
| 4246 |
+
const owner = searchId;
|
| 4247 |
cancelPositionRestore();
|
| 4248 |
+
if (owner !== searchId) return;
|
| 4249 |
resetPagingRecovery();
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4250 |
STATE.isLoading = true;
|
| 4251 |
setSearchVisualLoading(true);
|
| 4252 |
syncStateToURL(true);
|
|
|
|
| 4280 |
}
|
| 4281 |
|
| 4282 |
function cancelSearchPrefetch() {
|
| 4283 |
+
const previous = searchPrefetchAbortController;
|
|
|
|
|
|
|
| 4284 |
searchPrefetchAbortController = null;
|
| 4285 |
+
cancelPendingSearchCacheWrites();
|
| 4286 |
+
previous?.cacheWaits?.forEach(wait => wait.controller.abort());
|
| 4287 |
+
previous?.abort();
|
| 4288 |
+
}
|
| 4289 |
+
|
| 4290 |
+
function cancelActiveSearch() {
|
| 4291 |
+
const id = ++searchId;
|
| 4292 |
+
searchRequestId++;
|
| 4293 |
+
const previous = searchAbortController;
|
| 4294 |
+
searchAbortController = new AbortController();
|
| 4295 |
+
cancelSearchPrefetch();
|
| 4296 |
+
previous?.abort();
|
| 4297 |
+
return id === searchId;
|
| 4298 |
}
|
| 4299 |
|
| 4300 |
function prefetchSearchPages(base, template) {
|
|
|
|
| 4433 |
|
| 4434 |
async function doSearch(append = false, fromStart = false, restorePosition = false) {
|
| 4435 |
if (append && resultWindow) { loadResultWindowPage(STATE._loadedPage + 1); return; }
|
|
|
|
|
|
|
| 4436 |
const recoveringFirstPage = append && !STATE._loadedPage;
|
| 4437 |
if (recoveringFirstPage) append = false;
|
| 4438 |
+
if (!append && !fromStart) backToTopPending = false;
|
| 4439 |
+
if (!append && !cancelActiveSearch()) return;
|
| 4440 |
+
const owner = searchId;
|
| 4441 |
+
if (!append && prepareSearchPositionNavigation({ fromStart, restorePosition })) return;
|
| 4442 |
+
if (owner !== searchId) return;
|
| 4443 |
clearTimeout(filterSearchTimer);
|
| 4444 |
filterSearchTimer = null;
|
| 4445 |
if (!append) {
|
|
|
|
| 4448 |
selectedIndices = {};
|
| 4449 |
lastSelectedIndex = -1;
|
| 4450 |
if (DOM.multiSelectToggle && DOM.multiSelectToggle.checked) updateSelectionUI();
|
|
|
|
|
|
|
|
|
|
| 4451 |
STATE._pageCache = {};
|
| 4452 |
STATE._loadedPage = 0;
|
| 4453 |
STATE._pagingAppendScrollTop = null;
|
|
|
|
| 5850 |
if (document.visibilityState === "hidden") flushSidebarScroll();
|
| 5851 |
});
|
| 5852 |
syncSearchInputState();
|
| 5853 |
+
setupSearchInput();
|
| 5854 |
// Session and position databases are independent; start both without
|
| 5855 |
// serializing their I/O. Route handling still waits for both to settle.
|
| 5856 |
const positionsReady = initSearchPositions();
|
|
|
|
| 5868 |
else if (savedMobile === "desktop") STATE.isMobile = false;
|
| 5869 |
else STATE.isMobile = autoDetectMobile();
|
| 5870 |
applyMobileMode();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5871 |
setupSearchHistory();
|
| 5872 |
DOM.historyToggle.addEventListener("change", () => {
|
| 5873 |
STATE.recordHistory = DOM.historyToggle.checked;
|
|
|
|
| 6027 |
restoreReaderOverlay(event.state);
|
| 6028 |
return;
|
| 6029 |
}
|
| 6030 |
+
// Apply the destination and retire A before Reader disposal or async B restoration.
|
| 6031 |
+
const overlay = readerOverlay;
|
| 6032 |
+
ROUTER.apply(!!overlay);
|
| 6033 |
+
if (readerOverlay === overlay) closeReaderOverlay();
|
| 6034 |
});
|
| 6035 |
window.addEventListener("resize", () => {
|
| 6036 |
if (!readSearchPreference("mobileMode")) {
|
|
|
|
| 6056 |
window.addEventListener("pageshow", resumeResultRecovery);
|
| 6057 |
window.addEventListener("online", resumeResultRecovery);
|
| 6058 |
window.setInterval(() => warmConnection(), KEEPALIVE_INTERVAL_MS);
|
| 6059 |
+
const initialDraftCurrent = initialSearchDraftIsCurrent();
|
| 6060 |
ROUTER.apply();
|
| 6061 |
+
finishInitialSearchInput(initialDraftCurrent);
|
| 6062 |
+
restoreReaderSearchHandoff();
|
| 6063 |
// Keep the first search paint independent of the multi-megabyte Reader sidecar.
|
| 6064 |
// API results already carry Reader fields; the sidecar is only enrichment for
|
| 6065 |
// local snapshots and directory browsing. Load it on the first real
|
static/reader/core/reader-bindings.mjs
CHANGED
|
@@ -425,10 +425,47 @@ export function createReaderBindings(readerContext) {
|
|
| 425 |
}
|
| 426 |
|
| 427 |
function bindReaderUiHistory() {
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
}
|
| 433 |
|
| 434 |
function bindPanelBookmarkAndLifecycleControls() {
|
|
|
|
| 425 |
}
|
| 426 |
|
| 427 |
function bindReaderUiHistory() {
|
| 428 |
+
if (window !== window.top) return;
|
| 429 |
+
const readerUrl = location.href;
|
| 430 |
+
let loadingSearch = false;
|
| 431 |
+
const restoreSearchDocument = (event) => {
|
| 432 |
+
if (!event.isTrusted || loadingSearch || readerContext.readerLifecycle.disposed) return;
|
| 433 |
+
// Reloading an overlay URL creates a standalone Reader document which can
|
| 434 |
+
// still own the preceding same-document search entries. Back changes the
|
| 435 |
+
// URL/state first; load THAT document without another traversal or rewrite.
|
| 436 |
+
// Match the app's root / single-segment repository search routes.
|
| 437 |
+
// Asset, API and Reader documents must never trigger search restoration.
|
| 438 |
+
const parts = location.pathname.split("/").filter(Boolean);
|
| 439 |
+
if (parts.length > 1 || ["static", "api", "reader", "reader.html"].includes(parts[0])) return;
|
| 440 |
+
loadingSearch = true;
|
| 441 |
+
try {
|
| 442 |
+
sessionStorage.removeItem("reader-navigation-restore");
|
| 443 |
+
const saved = JSON.parse(sessionStorage.getItem("reader-navigation-current") || "null");
|
| 444 |
+
if (saved?.shareUrl === readerUrl && saved.readerUrl) {
|
| 445 |
+
const source = new URL(saved.readerUrl, location.origin);
|
| 446 |
+
const returnUrl = source.searchParams.get("return");
|
| 447 |
+
const token = source.searchParams.get("nav");
|
| 448 |
+
if (source.origin === location.origin && returnUrl === location.href && token &&
|
| 449 |
+
sessionStorage.getItem(`reader-return:${token}`) === returnUrl) {
|
| 450 |
+
// The host saves focus/scroll before mounting. The app consumes this
|
| 451 |
+
// handoff after loading results; it is not a history-entry identity.
|
| 452 |
+
sessionStorage.setItem("reader-navigation-restore", JSON.stringify({
|
| 453 |
+
readerUrl: saved.readerUrl, returnUrl
|
| 454 |
+
}));
|
| 455 |
+
}
|
| 456 |
+
}
|
| 457 |
+
} catch (_) {}
|
| 458 |
+
location.reload();
|
| 459 |
+
};
|
| 460 |
+
const resume = (event) => { if (event.persisted) loadingSearch = false; };
|
| 461 |
+
window.addEventListener("popstate", restoreSearchDocument);
|
| 462 |
+
window.addEventListener("pageshow", resume);
|
| 463 |
+
// A failed book load stops book work but leaves this document's error UI
|
| 464 |
+
// alive. Keep browser navigation until the document/runtime is disposed.
|
| 465 |
+
readerContext.readerRuntime.track(() => {
|
| 466 |
+
window.removeEventListener("popstate", restoreSearchDocument);
|
| 467 |
+
window.removeEventListener("pageshow", resume);
|
| 468 |
+
});
|
| 469 |
}
|
| 470 |
|
| 471 |
function bindPanelBookmarkAndLifecycleControls() {
|
static/search/reader-navigation.js
CHANGED
|
@@ -44,6 +44,7 @@
|
|
| 44 |
}
|
| 45 |
/** @type {HTMLIFrameElement | null} */
|
| 46 |
let frame = null;
|
|
|
|
| 47 |
/** @type {HTMLElement | null} */
|
| 48 |
let returnFocus = null;
|
| 49 |
/** @type {{element: Element; inert: boolean; ariaHidden: string | null}[]} */
|
|
@@ -276,6 +277,7 @@
|
|
| 276 |
}
|
| 277 |
/** @param {URL} url */
|
| 278 |
function mount(url) {
|
|
|
|
| 279 |
const key = bookKey(url.href);
|
| 280 |
if (parked && key && parked.key === key) {
|
| 281 |
// The same book: show the Reader that kept reading, at its reading position.
|
|
@@ -330,7 +332,7 @@
|
|
| 330 |
status.textContent = "正在打开阅读器...";
|
| 331 |
opening.append(back, status);
|
| 332 |
const reveal = () => {
|
| 333 |
-
if (frame !== next || !opening) return;
|
| 334 |
next.classList.remove("reader-overlay-pending");
|
| 335 |
opening?.remove();
|
| 336 |
opening = null;
|
|
@@ -359,9 +361,44 @@
|
|
| 359 |
shade(next);
|
| 360 |
return next;
|
| 361 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
function dismiss() {
|
| 363 |
-
// Visually return immediately;
|
| 364 |
-
// the actual close, including the stalled-history fallback.
|
| 365 |
titleDismissed = true;
|
| 366 |
restoreTitle();
|
| 367 |
for (const target of [frame, opening]) if (target) {
|
|
@@ -372,10 +409,12 @@
|
|
| 372 |
// `keepSpeech` parks a Reader that is reading aloud instead of disposing it.
|
| 373 |
function unmount(keepSpeech = true) {
|
| 374 |
if (!frame) return null;
|
|
|
|
| 375 |
titleDismissed = true;
|
| 376 |
restoreTitle();
|
| 377 |
-
|
| 378 |
-
|
|
|
|
| 379 |
frame = null;
|
| 380 |
opening?.remove();
|
| 381 |
opening = null;
|
|
@@ -389,6 +428,8 @@
|
|
| 389 |
document.body.classList.remove("reader-overlay-open");
|
| 390 |
const focus = returnFocus;
|
| 391 |
returnFocus = null;
|
|
|
|
|
|
|
| 392 |
return focus;
|
| 393 |
}
|
| 394 |
/** @param {string} raw @param {object} returnScroll @returns {HTMLIFrameElement | null} */
|
|
@@ -399,7 +440,9 @@
|
|
| 399 |
if (!next.searchParams.get(key) && current.searchParams.get(key))
|
| 400 |
next.searchParams.set(key, /** @type {string} */ (current.searchParams.get(key)));
|
| 401 |
remember(next, returnScroll, true);
|
|
|
|
| 402 |
const focus = unmount(bookKey(next.href) !== bookKey(current.href));
|
|
|
|
| 403 |
mount(next);
|
| 404 |
returnFocus = focus;
|
| 405 |
return frame;
|
|
@@ -474,6 +517,7 @@
|
|
| 474 |
remember,
|
| 475 |
mount,
|
| 476 |
dismiss,
|
|
|
|
| 477 |
unmount,
|
| 478 |
persistProgress,
|
| 479 |
replace,
|
|
|
|
| 44 |
}
|
| 45 |
/** @type {HTMLIFrameElement | null} */
|
| 46 |
let frame = null;
|
| 47 |
+
let revision = 0;
|
| 48 |
/** @type {HTMLElement | null} */
|
| 49 |
let returnFocus = null;
|
| 50 |
/** @type {{element: Element; inert: boolean; ariaHidden: string | null}[]} */
|
|
|
|
| 277 |
}
|
| 278 |
/** @param {URL} url */
|
| 279 |
function mount(url) {
|
| 280 |
+
revision++;
|
| 281 |
const key = bookKey(url.href);
|
| 282 |
if (parked && key && parked.key === key) {
|
| 283 |
// The same book: show the Reader that kept reading, at its reading position.
|
|
|
|
| 332 |
status.textContent = "正在打开阅读器...";
|
| 333 |
opening.append(back, status);
|
| 334 |
const reveal = () => {
|
| 335 |
+
if (frame !== next || !opening || titleDismissed) return;
|
| 336 |
next.classList.remove("reader-overlay-pending");
|
| 337 |
opening?.remove();
|
| 338 |
opening = null;
|
|
|
|
| 361 |
shade(next);
|
| 362 |
return next;
|
| 363 |
}
|
| 364 |
+
/** @param {string} raw */
|
| 365 |
+
function showCloseRecovery(raw) {
|
| 366 |
+
if (!frame || !titleDismissed) return;
|
| 367 |
+
const searchPath = readerPath.slice(0, -"static/reader.html".length) || "/";
|
| 368 |
+
let target = new URL(searchPath, location.origin);
|
| 369 |
+
try {
|
| 370 |
+
const candidate = new URL(raw, location.origin);
|
| 371 |
+
if (candidate.origin === location.origin && !candidate.username && !candidate.password &&
|
| 372 |
+
(searchPath === "/" ? candidate.pathname.split("/").filter(Boolean).length <= 1 : candidate.pathname === searchPath))
|
| 373 |
+
target = candidate;
|
| 374 |
+
} catch (_) {}
|
| 375 |
+
if (!opening) {
|
| 376 |
+
opening = document.createElement("div");
|
| 377 |
+
opening.className = "reader-overlay-opening";
|
| 378 |
+
document.body.append(opening);
|
| 379 |
+
}
|
| 380 |
+
const status = document.createElement("span");
|
| 381 |
+
status.setAttribute("role", "status");
|
| 382 |
+
status.textContent = "仍在等待返回搜索,可直接打开搜索页。";
|
| 383 |
+
const link = document.createElement("a");
|
| 384 |
+
link.textContent = "直接打开搜索页";
|
| 385 |
+
link.href = target.href;
|
| 386 |
+
link.addEventListener("click", () => {
|
| 387 |
+
// Native navigation is an explicit recovery choice, not cancellation
|
| 388 |
+
// of the outstanding Back. Reuse the validated focus/scroll handoff.
|
| 389 |
+
try {
|
| 390 |
+
sessionStorage.setItem("reader-navigation-restore", JSON.stringify({
|
| 391 |
+
readerUrl: frame?.src, returnUrl: target.href
|
| 392 |
+
}));
|
| 393 |
+
} catch (_) {}
|
| 394 |
+
});
|
| 395 |
+
opening.replaceChildren(status, link);
|
| 396 |
+
opening.style.removeProperty("opacity");
|
| 397 |
+
opening.style.removeProperty("pointer-events");
|
| 398 |
+
link.focus();
|
| 399 |
+
}
|
| 400 |
function dismiss() {
|
| 401 |
+
// Visually return immediately; popstate still owns the actual close.
|
|
|
|
| 402 |
titleDismissed = true;
|
| 403 |
restoreTitle();
|
| 404 |
for (const target of [frame, opening]) if (target) {
|
|
|
|
| 409 |
// `keepSpeech` parks a Reader that is reading aloud instead of disposing it.
|
| 410 |
function unmount(keepSpeech = true) {
|
| 411 |
if (!frame) return null;
|
| 412 |
+
revision++;
|
| 413 |
titleDismissed = true;
|
| 414 |
restoreTitle();
|
| 415 |
+
const target = frame;
|
| 416 |
+
const keep = keepSpeech && !target.classList.contains("reader-overlay-pending") && speech(target)?.active;
|
| 417 |
+
// Release ownership before lifecycle callbacks can synchronously reenter.
|
| 418 |
frame = null;
|
| 419 |
opening?.remove();
|
| 420 |
opening = null;
|
|
|
|
| 428 |
document.body.classList.remove("reader-overlay-open");
|
| 429 |
const focus = returnFocus;
|
| 430 |
returnFocus = null;
|
| 431 |
+
if (keep) park(target);
|
| 432 |
+
else dispose(target);
|
| 433 |
return focus;
|
| 434 |
}
|
| 435 |
/** @param {string} raw @param {object} returnScroll @returns {HTMLIFrameElement | null} */
|
|
|
|
| 440 |
if (!next.searchParams.get(key) && current.searchParams.get(key))
|
| 441 |
next.searchParams.set(key, /** @type {string} */ (current.searchParams.get(key)));
|
| 442 |
remember(next, returnScroll, true);
|
| 443 |
+
const expected = revision + 1;
|
| 444 |
const focus = unmount(bookKey(next.href) !== bookKey(current.href));
|
| 445 |
+
if (revision !== expected) return frame;
|
| 446 |
mount(next);
|
| 447 |
returnFocus = focus;
|
| 448 |
return frame;
|
|
|
|
| 517 |
remember,
|
| 518 |
mount,
|
| 519 |
dismiss,
|
| 520 |
+
showCloseRecovery,
|
| 521 |
unmount,
|
| 522 |
persistProgress,
|
| 523 |
replace,
|
static/search/search-session.js
CHANGED
|
@@ -4,11 +4,25 @@
|
|
| 4 |
const DB_NAME = "voiceofml-search-state";
|
| 5 |
const SESSION_TIMEOUT_MS = 1500;
|
| 6 |
|
| 7 |
-
/
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
let settled = false;
|
| 13 |
const timer = setTimeout(() => fail(new Error("IndexedDB open timed out")), SESSION_TIMEOUT_MS);
|
| 14 |
/** @param {unknown} error */
|
|
@@ -23,89 +37,161 @@
|
|
| 23 |
};
|
| 24 |
request.onsuccess = () => {
|
| 25 |
const db = request.result;
|
|
|
|
| 26 |
if (settled) { db.close(); return; }
|
| 27 |
settled = true;
|
| 28 |
clearTimeout(timer);
|
| 29 |
db.onversionchange = () => db.close();
|
| 30 |
resolve(db);
|
| 31 |
};
|
| 32 |
-
request.onerror = () => fail(request.error);
|
| 33 |
request.onblocked = () => fail(new Error("IndexedDB open blocked"));
|
| 34 |
});
|
|
|
|
| 35 |
}
|
| 36 |
|
| 37 |
-
/** @
|
| 38 |
-
function
|
| 39 |
-
return
|
| 40 |
-
let settled = false;
|
| 41 |
-
const timer = setTimeout(() => {
|
| 42 |
-
if (settled) return;
|
| 43 |
-
settled = true;
|
| 44 |
-
try { transaction.abort(); } catch (_) {}
|
| 45 |
-
reject(new Error("IndexedDB read timed out"));
|
| 46 |
-
}, SESSION_TIMEOUT_MS);
|
| 47 |
-
request.onsuccess = () => {
|
| 48 |
-
if (settled) return;
|
| 49 |
-
settled = true; clearTimeout(timer); resolve(request.result);
|
| 50 |
-
};
|
| 51 |
-
request.onerror = () => {
|
| 52 |
-
if (settled) return;
|
| 53 |
-
settled = true; clearTimeout(timer); reject(request.error);
|
| 54 |
-
};
|
| 55 |
-
});
|
| 56 |
}
|
| 57 |
|
| 58 |
-
/** @param {IDBTransaction} transaction
|
| 59 |
-
function
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
}
|
| 69 |
|
| 70 |
/** @param {{canPersist: () => boolean, canRestore: (target?: URL) => boolean}} options */
|
| 71 |
function createSearchSession({ canPersist, canRestore }) {
|
| 72 |
-
|
| 73 |
-
if (!canPersist()) return;
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
);
|
| 82 |
-
await waitForTransaction(transaction);
|
| 83 |
-
} catch (_) {
|
| 84 |
-
// Session persistence is best effort and must never block search.
|
| 85 |
-
} finally {
|
| 86 |
-
if (db) db.close();
|
| 87 |
-
}
|
| 88 |
}
|
| 89 |
|
| 90 |
async function restoreSearchSession() {
|
| 91 |
if (!canRestore()) return false;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
let db;
|
| 93 |
try {
|
|
|
|
| 94 |
db = await openSearchSessionDB();
|
| 95 |
const transaction = db.transaction("session", "readonly");
|
| 96 |
-
const
|
| 97 |
/** @type {unknown} */
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
if (!saved || typeof saved !== "object" || !("version" in saved) || saved.version !== 1 ||
|
| 100 |
!("url" in saved) || typeof saved.url !== "string") return false;
|
| 101 |
const target = new URL(saved.url);
|
| 102 |
// A user may have navigated while IndexedDB was opening or reading.
|
| 103 |
-
if (
|
| 104 |
-
|
|
|
|
|
|
|
| 105 |
return true;
|
| 106 |
} catch (_) {
|
| 107 |
return false;
|
| 108 |
} finally {
|
|
|
|
| 109 |
if (db) db.close();
|
| 110 |
}
|
| 111 |
}
|
|
|
|
| 4 |
const DB_NAME = "voiceofml-search-state";
|
| 5 |
const SESSION_TIMEOUT_MS = 1500;
|
| 6 |
|
| 7 |
+
// A deadline settles the caller, but only a native terminal event retires
|
| 8 |
+
// the operation. In particular, blocked opens cannot be cancelled.
|
| 9 |
+
function startSessionOpen() {
|
| 10 |
+
/** @type {() => void} */
|
| 11 |
+
let finish = () => {};
|
| 12 |
+
/** @type {Promise<void>} */
|
| 13 |
+
const finished = new Promise(resolve => { finish = resolve; });
|
| 14 |
+
/** @type {Promise<IDBDatabase>} */
|
| 15 |
+
const result = new Promise((resolve, reject) => {
|
| 16 |
+
/** @type {IDBOpenDBRequest} */
|
| 17 |
+
let request;
|
| 18 |
+
try {
|
| 19 |
+
if (!window.indexedDB) throw new Error("IndexedDB unavailable");
|
| 20 |
+
request = indexedDB.open(DB_NAME, 1);
|
| 21 |
+
} catch (error) {
|
| 22 |
+
finish();
|
| 23 |
+
reject(error);
|
| 24 |
+
return;
|
| 25 |
+
}
|
| 26 |
let settled = false;
|
| 27 |
const timer = setTimeout(() => fail(new Error("IndexedDB open timed out")), SESSION_TIMEOUT_MS);
|
| 28 |
/** @param {unknown} error */
|
|
|
|
| 37 |
};
|
| 38 |
request.onsuccess = () => {
|
| 39 |
const db = request.result;
|
| 40 |
+
finish();
|
| 41 |
if (settled) { db.close(); return; }
|
| 42 |
settled = true;
|
| 43 |
clearTimeout(timer);
|
| 44 |
db.onversionchange = () => db.close();
|
| 45 |
resolve(db);
|
| 46 |
};
|
| 47 |
+
request.onerror = () => { finish(); fail(request.error); };
|
| 48 |
request.onblocked = () => fail(new Error("IndexedDB open blocked"));
|
| 49 |
});
|
| 50 |
+
return { result, finished };
|
| 51 |
}
|
| 52 |
|
| 53 |
+
/** @returns {Promise<IDBDatabase>} */
|
| 54 |
+
function openSearchSessionDB() {
|
| 55 |
+
return startSessionOpen().result;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
}
|
| 57 |
|
| 58 |
+
/** @param {IDBTransaction} transaction */
|
| 59 |
+
function watchTransaction(transaction) {
|
| 60 |
+
/** @type {(success: boolean) => void} */
|
| 61 |
+
let settle = () => {};
|
| 62 |
+
/** @type {() => void} */
|
| 63 |
+
let finish = () => {};
|
| 64 |
+
/** @type {Promise<boolean>} */
|
| 65 |
+
const result = new Promise(resolve => { settle = resolve; });
|
| 66 |
+
/** @type {Promise<void>} */
|
| 67 |
+
const finished = new Promise(resolve => { finish = resolve; });
|
| 68 |
+
let failed = false;
|
| 69 |
+
function fail() {
|
| 70 |
+
if (failed) return;
|
| 71 |
+
failed = true;
|
| 72 |
+
clearTimeout(timer);
|
| 73 |
+
settle(false);
|
| 74 |
+
// abort() may throw or return before onabort. Neither releases a writer.
|
| 75 |
+
try { transaction.abort(); } catch (_) {}
|
| 76 |
+
}
|
| 77 |
+
const timer = setTimeout(fail, SESSION_TIMEOUT_MS);
|
| 78 |
+
transaction.onerror = fail;
|
| 79 |
+
transaction.onabort = () => { clearTimeout(timer); settle(false); finish(); };
|
| 80 |
+
transaction.oncomplete = () => { clearTimeout(timer); settle(!failed); finish(); };
|
| 81 |
+
return { result, finished, fail };
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/** @typedef {{version: number, url: string, updatedAt: number}} SessionSnapshot */
|
| 85 |
+
/** @typedef {{snapshot: SessionSnapshot, result: Promise<void>, settle: () => void}} SaveBatch */
|
| 86 |
+
// Shared by adapters in this document: one active operation and one latest
|
| 87 |
+
// pending snapshot, with a shared (bounded) wait for every pending caller.
|
| 88 |
+
/** @type {SaveBatch | null} */
|
| 89 |
+
let pendingSave = null;
|
| 90 |
+
let saving = false;
|
| 91 |
+
|
| 92 |
+
/** @param {SessionSnapshot} snapshot @returns {SaveBatch} */
|
| 93 |
+
function createSaveBatch(snapshot) {
|
| 94 |
+
/** @type {() => void} */
|
| 95 |
+
let settle = () => {};
|
| 96 |
+
/** @type {Promise<void>} */
|
| 97 |
+
const result = new Promise(resolve => {
|
| 98 |
+
const timer = setTimeout(resolve, SESSION_TIMEOUT_MS);
|
| 99 |
+
settle = () => { clearTimeout(timer); resolve(); };
|
| 100 |
});
|
| 101 |
+
return { snapshot, result, settle };
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
async function drainSaves() {
|
| 105 |
+
saving = true;
|
| 106 |
+
try {
|
| 107 |
+
while (pendingSave) {
|
| 108 |
+
const batch = pendingSave;
|
| 109 |
+
pendingSave = null;
|
| 110 |
+
const opening = startSessionOpen();
|
| 111 |
+
/** @type {IDBDatabase | undefined} */
|
| 112 |
+
let db;
|
| 113 |
+
/** @type {ReturnType<typeof watchTransaction> | undefined} */
|
| 114 |
+
let completion;
|
| 115 |
+
try {
|
| 116 |
+
db = await opening.result;
|
| 117 |
+
const transaction = db.transaction("session", "readwrite");
|
| 118 |
+
completion = watchTransaction(transaction);
|
| 119 |
+
try {
|
| 120 |
+
transaction.objectStore("session").put(batch.snapshot, "last-search");
|
| 121 |
+
} catch (_) {
|
| 122 |
+
completion.fail();
|
| 123 |
+
}
|
| 124 |
+
await completion.result;
|
| 125 |
+
} catch (_) {
|
| 126 |
+
// Persistence is best effort. A failed open/transaction must not
|
| 127 |
+
// leak a rejection into the search UI.
|
| 128 |
+
} finally {
|
| 129 |
+
if (db) db.close();
|
| 130 |
+
batch.settle();
|
| 131 |
+
}
|
| 132 |
+
// A permanently stalled native operation parks this single worker.
|
| 133 |
+
// New saves replace the one pending snapshot; no promise chain grows.
|
| 134 |
+
await opening.finished;
|
| 135 |
+
if (completion) await completion.finished;
|
| 136 |
+
}
|
| 137 |
+
} finally {
|
| 138 |
+
saving = false;
|
| 139 |
+
}
|
| 140 |
}
|
| 141 |
|
| 142 |
/** @param {{canPersist: () => boolean, canRestore: (target?: URL) => boolean}} options */
|
| 143 |
function createSearchSession({ canPersist, canRestore }) {
|
| 144 |
+
function persistSearchSession() {
|
| 145 |
+
if (!canPersist()) return Promise.resolve();
|
| 146 |
+
// Capture eligibility and the immutable value together, before any await.
|
| 147 |
+
const snapshot = { version: 1, url: location.href, updatedAt: Date.now() };
|
| 148 |
+
if (pendingSave) pendingSave.snapshot = snapshot;
|
| 149 |
+
else pendingSave = createSaveBatch(snapshot);
|
| 150 |
+
const result = pendingSave.result;
|
| 151 |
+
if (!saving) void drainSaves();
|
| 152 |
+
return result;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
}
|
| 154 |
|
| 155 |
async function restoreSearchSession() {
|
| 156 |
if (!canRestore()) return false;
|
| 157 |
+
const startingHref = location.href;
|
| 158 |
+
// Navigation entry identity is independent of classic history.state.
|
| 159 |
+
const navigation = /** @type {Window & {navigation?: {currentEntry?: {key?: string} | null}}} */ (window).navigation;
|
| 160 |
+
const startingKey = navigation?.currentEntry?.key;
|
| 161 |
+
let cancelled = false;
|
| 162 |
+
const cancel = () => { cancelled = true; };
|
| 163 |
+
const events = ["popstate", "hashchange", "pagehide", "input", "compositionstart", "compositionupdate", "compositionend"];
|
| 164 |
let db;
|
| 165 |
try {
|
| 166 |
+
for (const type of events) window.addEventListener(type, cancel, true);
|
| 167 |
db = await openSearchSessionDB();
|
| 168 |
const transaction = db.transaction("session", "readonly");
|
| 169 |
+
const completion = watchTransaction(transaction);
|
| 170 |
/** @type {unknown} */
|
| 171 |
+
let saved;
|
| 172 |
+
try {
|
| 173 |
+
const request = transaction.objectStore("session").get("last-search");
|
| 174 |
+
request.onsuccess = () => { saved = request.result; };
|
| 175 |
+
request.onerror = completion.fail;
|
| 176 |
+
} catch (_) {
|
| 177 |
+
completion.fail();
|
| 178 |
+
}
|
| 179 |
+
// Request success is provisional: an abort later in the same
|
| 180 |
+
// transaction must never publish a saved URL.
|
| 181 |
+
if (!await completion.result) return false;
|
| 182 |
if (!saved || typeof saved !== "object" || !("version" in saved) || saved.version !== 1 ||
|
| 183 |
!("url" in saved) || typeof saved.url !== "string") return false;
|
| 184 |
const target = new URL(saved.url);
|
| 185 |
// A user may have navigated while IndexedDB was opening or reading.
|
| 186 |
+
if (cancelled || location.href !== startingHref ||
|
| 187 |
+
(startingKey !== undefined && navigation?.currentEntry?.key !== startingKey) ||
|
| 188 |
+
!canRestore() || !canRestore(target)) return false;
|
| 189 |
+
history.replaceState(history.state, "", target.href);
|
| 190 |
return true;
|
| 191 |
} catch (_) {
|
| 192 |
return false;
|
| 193 |
} finally {
|
| 194 |
+
for (const type of events) window.removeEventListener(type, cancel, true);
|
| 195 |
if (db) db.close();
|
| 196 |
}
|
| 197 |
}
|
tests/gates/ci-test-inventory.json
CHANGED
|
@@ -933,6 +933,26 @@
|
|
| 933 |
"tests/service_worker/test_service_worker_pruning.js": {
|
| 934 |
"kind": "direct",
|
| 935 |
"source": "@reader-workflow"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 936 |
}
|
| 937 |
}
|
| 938 |
}
|
|
|
|
| 933 |
"tests/service_worker/test_service_worker_pruning.js": {
|
| 934 |
"kind": "direct",
|
| 935 |
"source": "@reader-workflow"
|
| 936 |
+
},
|
| 937 |
+
"tests/search/session/test_search_session_contract.js": {
|
| 938 |
+
"kind": "direct",
|
| 939 |
+
"source": "@reader-workflow"
|
| 940 |
+
},
|
| 941 |
+
"tests/search/reader-navigation/test_search_history_races.mjs": {
|
| 942 |
+
"kind": "direct",
|
| 943 |
+
"source": "@reader-workflow"
|
| 944 |
+
},
|
| 945 |
+
"tests/search/browser/test_session_transaction_browser.py": {
|
| 946 |
+
"kind": "direct",
|
| 947 |
+
"source": "@reader-workflow"
|
| 948 |
+
},
|
| 949 |
+
"tests/reader/browser/test_reader_reload_search_document.py": {
|
| 950 |
+
"kind": "direct",
|
| 951 |
+
"source": "@reader-workflow"
|
| 952 |
+
},
|
| 953 |
+
"tests/reader/browser/test_reader_host_history_races.py": {
|
| 954 |
+
"kind": "direct",
|
| 955 |
+
"source": "@reader-workflow"
|
| 956 |
}
|
| 957 |
}
|
| 958 |
}
|
tests/gates/test_static_checks.py
CHANGED
|
@@ -2142,9 +2142,19 @@ class StaticGateTests(unittest.TestCase):
|
|
| 2142 |
target.parent.mkdir(parents=True, exist_ok=True)
|
| 2143 |
shutil.copyfile(ROOT / path, target)
|
| 2144 |
check = ["node", paths[1]]
|
| 2145 |
-
self.assert_check(self.run_check(*check), True, "# pass
|
| 2146 |
test = self.root / paths[2]
|
| 2147 |
source = test.read_text()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2148 |
name = 'remember stores a private reader URL but exposes a sanitized history URL'
|
| 2149 |
anchor = "test('" + name + "'"
|
| 2150 |
self.assertEqual(source.count(anchor), 1)
|
|
@@ -2184,7 +2194,9 @@ class StaticGateTests(unittest.TestCase):
|
|
| 2184 |
gate.write_text(original.replace('const required = [', 'const duplicateRows = rows.concat(rows);\nconst required = [')
|
| 2185 |
.replace('rows.length !== 1', 'duplicateRows.length !== 1'))
|
| 2186 |
self.assert_check(self.run_check(*check), False, 'one source row above each minimum')
|
| 2187 |
-
|
|
|
|
|
|
|
| 2188 |
self.assertIn('[31.96, 81.82, 27.27]', original)
|
| 2189 |
gate.write_text(original.replace('[31.96, 81.82, 27.27]', thresholds))
|
| 2190 |
self.assert_check(self.run_check(*check), False, 'one source row above each minimum')
|
|
|
|
| 2142 |
target.parent.mkdir(parents=True, exist_ok=True)
|
| 2143 |
shutil.copyfile(ROOT / path, target)
|
| 2144 |
check = ["node", paths[1]]
|
| 2145 |
+
self.assert_check(self.run_check(*check), True, "# pass 15")
|
| 2146 |
test = self.root / paths[2]
|
| 2147 |
source = test.read_text()
|
| 2148 |
+
for new_name in (
|
| 2149 |
+
'replacement revision preserves a Reader opened synchronously during disposal',
|
| 2150 |
+
'ordinary replacement carries handoff and focus while releasing background ownership',
|
| 2151 |
+
'close recovery validates both search routes without changing history or private handoff',
|
| 2152 |
+
'recovery survives late shell load and records handoff only on native link activation',
|
| 2153 |
+
):
|
| 2154 |
+
new_anchor = "test('" + new_name + "'"
|
| 2155 |
+
self.assertEqual(source.count(new_anchor), 1)
|
| 2156 |
+
test.write_text(source.replace(new_anchor, "test('missing new contract'"))
|
| 2157 |
+
self.assert_check(self.run_check(*check), False, "all named baseline contracts")
|
| 2158 |
name = 'remember stores a private reader URL but exposes a sanitized history URL'
|
| 2159 |
anchor = "test('" + name + "'"
|
| 2160 |
self.assertEqual(source.count(anchor), 1)
|
|
|
|
| 2194 |
gate.write_text(original.replace('const required = [', 'const duplicateRows = rows.concat(rows);\nconst required = [')
|
| 2195 |
.replace('rows.length !== 1', 'duplicateRows.length !== 1'))
|
| 2196 |
self.assert_check(self.run_check(*check), False, 'one source row above each minimum')
|
| 2197 |
+
# Independent impossible thresholds keep these negative controls valid
|
| 2198 |
+
# when additional meaningful contracts improve actual coverage.
|
| 2199 |
+
for thresholds in ('[100.01, 81.82, 27.27]', '[31.96, 100.01, 27.27]', '[31.96, 81.82, 100.01]'):
|
| 2200 |
self.assertIn('[31.96, 81.82, 27.27]', original)
|
| 2201 |
gate.write_text(original.replace('[31.96, 81.82, 27.27]', thresholds))
|
| 2202 |
self.assert_check(self.run_check(*check), False, 'one source row above each minimum')
|
tests/reader/browser/test_reader_host_history_races.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Current search/Reader traversal and deterministic input ownership regressions."""
|
| 2 |
+
import unittest
|
| 3 |
+
from tests.search.browser import test_paging_recovery as paging
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ReaderHostHistoryRaceTests(unittest.TestCase):
|
| 7 |
+
@classmethod
|
| 8 |
+
def setUpClass(cls):
|
| 9 |
+
paging.PagingRecoveryTests.setUpClass()
|
| 10 |
+
|
| 11 |
+
@classmethod
|
| 12 |
+
def tearDownClass(cls):
|
| 13 |
+
paging.PagingRecoveryTests.tearDownClass()
|
| 14 |
+
|
| 15 |
+
def setUp(self):
|
| 16 |
+
self.fixture = paging.PagingRecoveryTests()
|
| 17 |
+
self.fixture.setUp()
|
| 18 |
+
self.page = self.fixture.page
|
| 19 |
+
self.page.route('**/static/reader.html?**', lambda route: route.fulfill(
|
| 20 |
+
content_type='text/html', body='<body>reader</body>'))
|
| 21 |
+
self.page.evaluate('''() => {
|
| 22 |
+
window.historySearchUrl = (query, extra = '') => location.pathname.startsWith('/search/')
|
| 23 |
+
? '/search/#/?q=' + query + '&local=0' + extra : '/?q=' + query + extra;
|
| 24 |
+
window.historyReaderUrl = () => location.pathname.startsWith('/search/')
|
| 25 |
+
? '/search/static/reader.html?ext=txt' : '/static/reader.html?ext=txt';
|
| 26 |
+
}''')
|
| 27 |
+
|
| 28 |
+
def tearDown(self):
|
| 29 |
+
errors = list(self.fixture.errors)
|
| 30 |
+
self.fixture.tearDown()
|
| 31 |
+
self.assertEqual(errors, [])
|
| 32 |
+
|
| 33 |
+
def test_product_automatically_saves_and_restores_search_session(self):
|
| 34 |
+
self.page.locator('#search-input').fill('paging-auto-session')
|
| 35 |
+
self.page.wait_for_function("STATE.query === 'paging-auto-session' && !STATE.isLoading && STATE._loadedPage === 1")
|
| 36 |
+
saved_url = self.page.url
|
| 37 |
+
self.page.wait_for_function('''expected => new Promise(resolve => {
|
| 38 |
+
const request = indexedDB.open('voiceofml-search-state', 1);
|
| 39 |
+
request.onerror = () => resolve(false);
|
| 40 |
+
request.onsuccess = () => {
|
| 41 |
+
const db = request.result;
|
| 42 |
+
const tx = db.transaction('session', 'readonly');
|
| 43 |
+
const read = tx.objectStore('session').get('last-search');
|
| 44 |
+
let saved;
|
| 45 |
+
read.onsuccess = () => { saved = read.result; };
|
| 46 |
+
tx.oncomplete = () => { db.close(); resolve(saved?.url === expected); };
|
| 47 |
+
tx.onabort = tx.onerror = () => { db.close(); resolve(false); };
|
| 48 |
+
};
|
| 49 |
+
})''', arg=saved_url)
|
| 50 |
+
bare = '/search/' if '/search/' in saved_url else '/'
|
| 51 |
+
self.page.goto(self.fixture.origin + bare, wait_until='domcontentloaded')
|
| 52 |
+
self.page.wait_for_function("STATE.query === 'paging-auto-session' && !STATE.isLoading && STATE._loadedPage === 1")
|
| 53 |
+
self.assertEqual(self.page.url, saved_url)
|
| 54 |
+
self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-auto-session')
|
| 55 |
+
self.assertGreater(self.page.locator('#results-list .result-item').count(), 0)
|
| 56 |
+
|
| 57 |
+
def test_go_minus_two_applies_destination_before_dispose_and_held_restoration(self):
|
| 58 |
+
self.page.evaluate('''() => {
|
| 59 |
+
history.replaceState({foreign:'B'}, '', historySearchUrl('paging-B', '&sort=size'));
|
| 60 |
+
ROUTER.apply();
|
| 61 |
+
}''')
|
| 62 |
+
self.page.wait_for_function("STATE.query === 'paging-B' && !STATE.isLoading && STATE._loadedPage === 1")
|
| 63 |
+
self.page.evaluate('''() => {
|
| 64 |
+
history.pushState({foreign:'A'}, '', historySearchUrl('paging-A', '&sort=name'));
|
| 65 |
+
ROUTER.apply();
|
| 66 |
+
}''')
|
| 67 |
+
self.page.wait_for_function("STATE.query === 'paging-A' && !STATE.isLoading && STATE._loadedPage === 1")
|
| 68 |
+
self.page.evaluate('''() => {
|
| 69 |
+
// Force B through asynchronous viewport restoration, while A still has
|
| 70 |
+
// a live prefetch consumer. No test-only session save is involved.
|
| 71 |
+
searchViewSnapshots.clear();
|
| 72 |
+
const oldRead = readSearchViewport;
|
| 73 |
+
readSearchViewport = key => JSON.parse(key).query === 'paging-B'
|
| 74 |
+
? new Promise(resolve => { window.releaseBViewport = () => resolve(null); }) : oldRead(key);
|
| 75 |
+
const oldTarget = getReturnPositionTarget;
|
| 76 |
+
getReturnPositionTarget = key => key && JSON.parse(key).query === 'paging-B'
|
| 77 |
+
? {version:1,key,index:1,offset:0,loadedPage:1,savedAt:Date.now()} : oldTarget(key);
|
| 78 |
+
DOM.searchInput.focus();
|
| 79 |
+
navigateToReader(historyReaderUrl());
|
| 80 |
+
window.oldSearchId = searchRequestId;
|
| 81 |
+
}''')
|
| 82 |
+
self.page.wait_for_function("readerOverlay && readerOverlay.contentDocument?.body?.textContent === 'reader'")
|
| 83 |
+
self.page.evaluate('''() => {
|
| 84 |
+
readerOverlay.contentWindow.addEventListener('voice-reader-dispose', () => {
|
| 85 |
+
window.atDispose = {query:STATE.query,sort:DOM.sortSelect.value,
|
| 86 |
+
retired:searchRequestId > oldSearchId,overlayReleased:readerOverlay === null};
|
| 87 |
+
// Reentrant close must be harmless.
|
| 88 |
+
closeReaderOverlay();
|
| 89 |
+
window.releaseStalePage();
|
| 90 |
+
});
|
| 91 |
+
history.go(-2);
|
| 92 |
+
}''')
|
| 93 |
+
self.page.wait_for_function('!!window.atDispose && typeof window.releaseBViewport === "function"')
|
| 94 |
+
self.assertEqual(self.page.evaluate('atDispose'), dict(query='paging-B', sort='size', retired=True, overlayReleased=True))
|
| 95 |
+
self.page.evaluate('releaseBViewport()')
|
| 96 |
+
self.page.wait_for_function("STATE.query === 'paging-B' && !STATE.isLoading && STATE._loadedPage === 1")
|
| 97 |
+
self.assertFalse(self.page.evaluate("STATE.results.some(r => r.File.startsWith('stale-'))"))
|
| 98 |
+
self.assertTrue(self.page.evaluate("document.activeElement === DOM.searchInput"))
|
| 99 |
+
self.assertIn('q=paging-B', self.page.url)
|
| 100 |
+
|
| 101 |
+
def test_same_view_route_keeps_pending_filter_debounce(self):
|
| 102 |
+
self.page.evaluate('''() => {
|
| 103 |
+
STATE.filterExtensions = ['txt'];
|
| 104 |
+
scheduleFilterSearch(true);
|
| 105 |
+
window.pendingFilter = filterSearchTimer;
|
| 106 |
+
ROUTER.apply(true);
|
| 107 |
+
window.filterPreserved = filterSearchTimer === pendingFilter && filterSearchTimer !== null;
|
| 108 |
+
}''')
|
| 109 |
+
self.assertTrue(self.page.evaluate('filterPreserved'))
|
| 110 |
+
self.page.wait_for_function('!STATE.isLoading && STATE._loadedPage === 1 && filterSearchTimer === null')
|
| 111 |
+
self.assertEqual(self.page.evaluate('STATE.filterExtensions'), ['txt'])
|
| 112 |
+
|
| 113 |
+
def test_replace_and_restore_yield_to_reader_opened_during_dispose(self):
|
| 114 |
+
for action in ('replace', 'restore'):
|
| 115 |
+
result = self.page.evaluate('''action => {
|
| 116 |
+
const path = new URL(historyReaderUrl(), location.origin).pathname;
|
| 117 |
+
navigateToReader(path + '?ext=txt&id=A');
|
| 118 |
+
const first = readerOverlay;
|
| 119 |
+
first.contentWindow.addEventListener('voice-reader-dispose', () => {
|
| 120 |
+
navigateToReader(path + '?ext=txt&id=C');
|
| 121 |
+
});
|
| 122 |
+
if (action === 'replace') handleReaderMessage({origin:location.origin,source:first.contentWindow,
|
| 123 |
+
data:{type:'voice-reader-open',url:path+'?ext=txt&id=B'}});
|
| 124 |
+
else restoreReaderOverlay({voiceReaderOverlay:true,readerUrl:path+'?ext=txt&id=B'});
|
| 125 |
+
const result = {id:new URL(readerOverlay.src).searchParams.get('id'),
|
| 126 |
+
connected:readerOverlay.isConnected,count:document.querySelectorAll('iframe.reader-overlay').length};
|
| 127 |
+
closeReaderOverlay(false,false);
|
| 128 |
+
history.replaceState(null,'',historySearchUrl('paging'));
|
| 129 |
+
return result;
|
| 130 |
+
}''', action)
|
| 131 |
+
self.assertEqual(result, dict(id='C', connected=True, count=1))
|
| 132 |
+
|
| 133 |
+
def test_dispose_reentry_mounts_new_reader_without_outer_cleanup(self):
|
| 134 |
+
result = self.page.evaluate('''() => {
|
| 135 |
+
const path = new URL(historyReaderUrl(), location.origin).pathname;
|
| 136 |
+
const nav = VoiceOfMLReaderNavigation.createNavigation(path);
|
| 137 |
+
const first = nav.mount(new URL(path + '?ext=txt&id=first', location.origin));
|
| 138 |
+
let second;
|
| 139 |
+
first.contentWindow.addEventListener('voice-reader-dispose', () => {
|
| 140 |
+
nav.unmount(false);
|
| 141 |
+
second = nav.mount(new URL(path + '?ext=txt&id=second', location.origin));
|
| 142 |
+
});
|
| 143 |
+
nav.unmount(false);
|
| 144 |
+
const result = {firstRemoved:!first.isConnected,secondConnected:second.isConnected,
|
| 145 |
+
accepted:nav.accepts({origin:location.origin,source:second.contentWindow}),
|
| 146 |
+
shaded:document.body.classList.contains('reader-overlay-open')};
|
| 147 |
+
nav.unmount(false);
|
| 148 |
+
return result;
|
| 149 |
+
}''')
|
| 150 |
+
self.assertTrue(all(result.values()), result)
|
| 151 |
+
|
| 152 |
+
def test_same_view_reader_back_retains_flight_scroll_and_focus(self):
|
| 153 |
+
self.page.evaluate('''() => {
|
| 154 |
+
DOM.searchInput.focus();
|
| 155 |
+
setResultScrollTop(900);
|
| 156 |
+
// Keep a live foreground subscriber to the held page-2 prefetch.
|
| 157 |
+
// Capture after this scroll's append request acquires its request ID.
|
| 158 |
+
STATE.page = 2; doSearch(true);
|
| 159 |
+
window.beforeReader = {top:getResultScrollTop(), request:searchRequestId, controller:searchAbortController};
|
| 160 |
+
navigateToReader(historyReaderUrl());
|
| 161 |
+
history.back();
|
| 162 |
+
}''')
|
| 163 |
+
self.page.wait_for_function('!readerOverlay')
|
| 164 |
+
self.assertTrue(self.page.evaluate('searchRequestId === beforeReader.request && searchAbortController === beforeReader.controller'))
|
| 165 |
+
self.assertTrue(self.page.evaluate('STATE.isLoading && STATE._pendingPage === 2 && !searchAbortController.signal.aborted'))
|
| 166 |
+
self.assertEqual(self.page.evaluate('pagingRequests.filter(page => page === 2).length'), 1)
|
| 167 |
+
self.assertTrue(self.page.evaluate('document.activeElement === DOM.searchInput'))
|
| 168 |
+
self.assertLessEqual(abs(self.page.evaluate('getResultScrollTop() - beforeReader.top')), 1)
|
| 169 |
+
|
| 170 |
+
def test_compositionstart_cancels_preexisting_debounce(self):
|
| 171 |
+
self.page.evaluate('''() => {
|
| 172 |
+
DOM.searchInput.value = 'paging-draft';
|
| 173 |
+
DOM.searchInput.dispatchEvent(new Event('input', {bubbles:true}));
|
| 174 |
+
DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart', {data:'中'}));
|
| 175 |
+
DOM.searchInput.value = 'paging-中';
|
| 176 |
+
}''')
|
| 177 |
+
self.page.wait_for_timeout(180)
|
| 178 |
+
self.assertEqual(self.page.evaluate('STATE.query'), 'paging')
|
| 179 |
+
self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend', {data:'中'}))")
|
| 180 |
+
self.page.wait_for_function("STATE.query === 'paging-中' && !STATE.isLoading")
|
| 181 |
+
|
| 182 |
+
def test_initial_storage_wait_preserves_draft_and_composition(self):
|
| 183 |
+
self.check_initial_storage_draft(False)
|
| 184 |
+
|
| 185 |
+
def test_initial_storage_navigation_keeps_old_draft_without_submitting_in_b(self):
|
| 186 |
+
self.check_initial_storage_draft(True)
|
| 187 |
+
|
| 188 |
+
def test_initial_storage_navigation_accepts_new_edit_and_composition_in_b(self):
|
| 189 |
+
self.check_initial_storage_draft(True, renew=True)
|
| 190 |
+
|
| 191 |
+
def check_initial_storage_draft(self, navigate, renew=False):
|
| 192 |
+
self.page.add_init_script('''(() => {
|
| 193 |
+
const open = indexedDB.open.bind(indexedDB);
|
| 194 |
+
window.releaseInitialStorage = [];
|
| 195 |
+
window.holdInitialStorage = true;
|
| 196 |
+
indexedDB.open = (...args) => {
|
| 197 |
+
const request = open(...args);
|
| 198 |
+
return new Proxy(request, {
|
| 199 |
+
get: (target, key) => target[key],
|
| 200 |
+
set(target, key, value) {
|
| 201 |
+
target[key] = key === 'onsuccess' ? event => {
|
| 202 |
+
if (window.holdInitialStorage) releaseInitialStorage.push(() => value(event));
|
| 203 |
+
else value(event);
|
| 204 |
+
} : value;
|
| 205 |
+
return true;
|
| 206 |
+
}
|
| 207 |
+
});
|
| 208 |
+
};
|
| 209 |
+
})();''')
|
| 210 |
+
for composing in (False, True):
|
| 211 |
+
with self.subTest(composing=composing):
|
| 212 |
+
self.page.reload(wait_until='domcontentloaded')
|
| 213 |
+
self.page.wait_for_function('window.releaseInitialStorage?.length > 0')
|
| 214 |
+
self.assertFalse(self.page.evaluate('routeInitialized'))
|
| 215 |
+
if navigate:
|
| 216 |
+
self.page.evaluate('''() => {
|
| 217 |
+
const original = location.href;
|
| 218 |
+
const target = location.pathname.startsWith('/search/')
|
| 219 |
+
? '/search/#/?q=paging-startup-B&local=0' : '/?q=paging-startup-B';
|
| 220 |
+
history.replaceState(null, '', target);
|
| 221 |
+
history.pushState(null, '', original);
|
| 222 |
+
}''')
|
| 223 |
+
self.page.evaluate('''composing => {
|
| 224 |
+
DOM.searchInput.focus();
|
| 225 |
+
if (composing) DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart'));
|
| 226 |
+
DOM.searchInput.value = composing ? 'paging-early-composing' : 'paging-early';
|
| 227 |
+
DOM.searchInput.setSelectionRange(3, 7);
|
| 228 |
+
DOM.searchInput.dispatchEvent(new InputEvent('input', {bubbles:true, isComposing:composing}));
|
| 229 |
+
window.initialRouteQuery = new URLSearchParams(location.search || location.hash.split('?')[1]).get('q');
|
| 230 |
+
}''', composing)
|
| 231 |
+
if navigate:
|
| 232 |
+
self.page.evaluate('''() => new Promise(resolve => {
|
| 233 |
+
window.addEventListener('popstate', resolve, {once:true});
|
| 234 |
+
history.back();
|
| 235 |
+
})''')
|
| 236 |
+
if renew:
|
| 237 |
+
self.page.evaluate('''composing => {
|
| 238 |
+
if (composing) {
|
| 239 |
+
DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'));
|
| 240 |
+
DOM.searchInput.dispatchEvent(new InputEvent('input', {
|
| 241 |
+
bubbles:true, inputType:'insertCompositionText'
|
| 242 |
+
}));
|
| 243 |
+
}
|
| 244 |
+
}''', composing)
|
| 245 |
+
self.assertFalse(self.page.evaluate('initialSearchDraftIsCurrent()'))
|
| 246 |
+
self.page.evaluate('''composing => {
|
| 247 |
+
if (composing) DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart'));
|
| 248 |
+
DOM.searchInput.value = composing ? 'paging-early-composing' : 'paging-early';
|
| 249 |
+
DOM.searchInput.setSelectionRange(3, 7);
|
| 250 |
+
DOM.searchInput.dispatchEvent(new InputEvent('input', {
|
| 251 |
+
bubbles:true, isComposing:composing,
|
| 252 |
+
inputType:composing ? 'insertCompositionText' : 'insertText'
|
| 253 |
+
}));
|
| 254 |
+
window.initialRouteQuery = 'paging-startup-B';
|
| 255 |
+
}''', composing)
|
| 256 |
+
self.assertTrue(self.page.evaluate('initialSearchDraftIsCurrent()'))
|
| 257 |
+
self.page.evaluate('''() => {
|
| 258 |
+
window.holdInitialStorage = false;
|
| 259 |
+
releaseInitialStorage.splice(0).forEach(release => release());
|
| 260 |
+
}''')
|
| 261 |
+
self.page.wait_for_function('routeInitialized')
|
| 262 |
+
if navigate and not renew:
|
| 263 |
+
self.page.wait_for_timeout(180)
|
| 264 |
+
self.assertEqual(self.page.evaluate('STATE.query'), 'paging-startup-B')
|
| 265 |
+
draft = 'paging-early-composing' if composing else 'paging-early'
|
| 266 |
+
self.assertEqual(self.page.locator('#search-input').input_value(), draft)
|
| 267 |
+
if composing:
|
| 268 |
+
self.assertTrue(self.page.evaluate('searchComposing'))
|
| 269 |
+
self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'))")
|
| 270 |
+
self.page.wait_for_timeout(180)
|
| 271 |
+
self.assertEqual(self.page.evaluate('STATE.query'), 'paging-startup-B')
|
| 272 |
+
self.page.locator('#search-input').fill('paging-new-startup-edit')
|
| 273 |
+
self.page.wait_for_function("STATE.query === 'paging-new-startup-edit' && !STATE.isLoading")
|
| 274 |
+
continue
|
| 275 |
+
if composing:
|
| 276 |
+
self.assertTrue(self.page.evaluate('searchComposing'))
|
| 277 |
+
self.assertEqual(self.page.evaluate('STATE.query'), self.page.evaluate('initialRouteQuery'))
|
| 278 |
+
self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-early-composing')
|
| 279 |
+
self.assertEqual(self.page.evaluate('[DOM.searchInput.selectionStart, DOM.searchInput.selectionEnd]'), [3, 7])
|
| 280 |
+
self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'))")
|
| 281 |
+
expected = 'paging-early-composing' if composing else 'paging-early'
|
| 282 |
+
self.page.wait_for_function('query => STATE.query === query && !STATE.isLoading', arg=expected)
|
| 283 |
+
self.assertEqual(self.page.locator('#search-input').input_value(), expected)
|
| 284 |
+
|
| 285 |
+
def test_long_composition_waits_for_real_completion(self):
|
| 286 |
+
self.page.evaluate('''() => {
|
| 287 |
+
DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart'));
|
| 288 |
+
DOM.searchInput.value = 'paging-long-composition';
|
| 289 |
+
DOM.searchInput.dispatchEvent(new InputEvent('input', {bubbles:true, isComposing:true}));
|
| 290 |
+
}''')
|
| 291 |
+
self.page.wait_for_timeout(5200)
|
| 292 |
+
self.assertEqual(self.page.evaluate('STATE.query'), 'paging')
|
| 293 |
+
self.assertTrue(self.page.evaluate('searchComposing'))
|
| 294 |
+
self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'))")
|
| 295 |
+
self.page.wait_for_function("STATE.query === 'paging-long-composition' && !STATE.isLoading")
|
| 296 |
+
|
| 297 |
+
def test_composition_from_previous_view_cannot_submit_but_new_input_can(self):
|
| 298 |
+
self.page.evaluate('''() => {
|
| 299 |
+
DOM.searchInput.focus();
|
| 300 |
+
DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart'));
|
| 301 |
+
DOM.searchInput.value = 'paging-composing-A';
|
| 302 |
+
history.pushState(null, '', historySearchUrl('paging-B'));
|
| 303 |
+
ROUTER.apply();
|
| 304 |
+
}''')
|
| 305 |
+
self.page.wait_for_function("STATE.query === 'paging-B' && !STATE.isLoading")
|
| 306 |
+
self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-composing-A')
|
| 307 |
+
self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'))")
|
| 308 |
+
self.page.wait_for_timeout(180)
|
| 309 |
+
self.assertEqual(self.page.evaluate('STATE.query'), 'paging-B')
|
| 310 |
+
input_type = self.page.evaluate('''() => {
|
| 311 |
+
// Use a recognized type: an unsupported constructor value can become
|
| 312 |
+
// an empty string, which is indistinguishable from ordinary input.
|
| 313 |
+
const tail = new InputEvent('input', {bubbles:true, inputType:'insertCompositionText'});
|
| 314 |
+
DOM.searchInput.dispatchEvent(tail);
|
| 315 |
+
return tail.inputType;
|
| 316 |
+
}''')
|
| 317 |
+
self.assertEqual(input_type, 'insertCompositionText')
|
| 318 |
+
self.page.wait_for_timeout(180)
|
| 319 |
+
self.assertEqual(self.page.evaluate('STATE.query'), 'paging-B')
|
| 320 |
+
self.page.locator('#search-input').press('Enter')
|
| 321 |
+
self.page.wait_for_function("STATE.query === 'paging-composing-A' && !STATE.isLoading")
|
| 322 |
+
self.page.locator('#search-input').fill('paging-deliberate-edit')
|
| 323 |
+
self.page.wait_for_function("STATE.query === 'paging-deliberate-edit' && !STATE.isLoading")
|
| 324 |
+
|
| 325 |
+
def test_query_debounce_is_retired_by_a_different_view(self):
|
| 326 |
+
self.page.evaluate('''() => {
|
| 327 |
+
DOM.searchInput.value = 'paging-obsolete-draft';
|
| 328 |
+
DOM.searchInput.dispatchEvent(new Event('input', {bubbles:true}));
|
| 329 |
+
history.pushState(null, '', historySearchUrl('paging-B'));
|
| 330 |
+
ROUTER.apply();
|
| 331 |
+
}''')
|
| 332 |
+
self.page.wait_for_timeout(180)
|
| 333 |
+
self.assertEqual(self.page.evaluate('STATE.query'), 'paging-B')
|
| 334 |
+
self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-B')
|
| 335 |
+
|
| 336 |
+
def test_pending_query_and_filter_are_submitted_together(self):
|
| 337 |
+
self.page.evaluate('''() => {
|
| 338 |
+
DOM.searchInput.value = 'paging-filter-draft';
|
| 339 |
+
DOM.searchInput.dispatchEvent(new Event('input', {bubbles:true}));
|
| 340 |
+
DOM.sortSelect.value = 'size';
|
| 341 |
+
DOM.sortSelect.dispatchEvent(new Event('change', {bubbles:true}));
|
| 342 |
+
}''')
|
| 343 |
+
self.page.wait_for_function("STATE.query === 'paging-filter-draft' && !STATE.isLoading")
|
| 344 |
+
self.assertEqual(self.page.evaluate('DOM.searchInput.value'), 'paging-filter-draft')
|
| 345 |
+
self.assertEqual(self.page.evaluate('DOM.sortSelect.value'), 'size')
|
| 346 |
+
self.assertIn('q=paging-filter-draft', self.page.url)
|
| 347 |
+
self.assertIn('sort=size', self.page.url)
|
| 348 |
+
|
| 349 |
+
def test_abort_reentry_new_query_owns_request_and_result(self):
|
| 350 |
+
self.page.evaluate('''() => {
|
| 351 |
+
searchAbortController.signal.addEventListener('abort', () => {
|
| 352 |
+
submitSearchQuery('paging-reentrant', {updateInput:true});
|
| 353 |
+
}, {once:true});
|
| 354 |
+
submitSearchQuery('paging-superseded', {updateInput:true});
|
| 355 |
+
}''')
|
| 356 |
+
self.page.wait_for_function("STATE.query === 'paging-reentrant' && !STATE.isLoading && STATE._loadedPage === 1")
|
| 357 |
+
self.assertEqual(self.page.evaluate('DOM.searchInput.value'), 'paging-reentrant')
|
| 358 |
+
self.assertIn('q=paging-reentrant', self.page.url)
|
| 359 |
+
self.assertTrue(self.page.evaluate('!searchAbortController.signal.aborted'))
|
| 360 |
+
|
| 361 |
+
def test_invalid_history_sort_uses_backend_whitelist(self):
|
| 362 |
+
self.page.evaluate('''() => {
|
| 363 |
+
const previous = window.fetch;
|
| 364 |
+
window.seenSort = [];
|
| 365 |
+
window.fetch = (input, options) => {
|
| 366 |
+
const body = JSON.parse(options?.body || '{}');
|
| 367 |
+
if (String(input).includes('/api/search') && body.q === 'paging-invalid-sort') {
|
| 368 |
+
window.seenSort.push(body.sort);
|
| 369 |
+
if (!['relevance','name','size'].includes(body.sort)) return Promise.resolve(new Response('{}',{status:422}));
|
| 370 |
+
}
|
| 371 |
+
return previous(input, options);
|
| 372 |
+
};
|
| 373 |
+
history.pushState(null, '', historySearchUrl('paging-invalid-sort', '&sort=invalid'));
|
| 374 |
+
ROUTER.apply();
|
| 375 |
+
}''')
|
| 376 |
+
self.page.wait_for_function("STATE.query === 'paging-invalid-sort' && !STATE.isLoading && STATE._loadedPage === 1")
|
| 377 |
+
self.assertEqual(self.page.evaluate('DOM.sortSelect.value'), 'relevance')
|
| 378 |
+
self.assertTrue(self.page.evaluate("seenSort.length > 0 && seenSort.every(sort => sort === 'relevance')"))
|
tests/reader/browser/test_reader_navigation_host.py
CHANGED
|
@@ -390,12 +390,25 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
|
|
| 390 |
def test_back_tap_recovers_when_history_traversal_never_arrives(self):
|
| 391 |
self.page.evaluate('navigateToReader("/static/reader.html?ext=txt")')
|
| 392 |
self.page.frame_locator('.reader-overlay').locator('body').wait_for()
|
|
|
|
| 393 |
self.page.evaluate("""() => {
|
| 394 |
-
|
|
|
|
| 395 |
handleReaderMessage({origin:location.origin,source:readerOverlay.contentWindow,data:{type:'voice-reader-close'}});
|
| 396 |
-
history.back = back;
|
| 397 |
}""")
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
self.assertFalse(self.page.evaluate('readerClosing'))
|
| 400 |
self.assertFalse(self.page.evaluate('!!history.state?.voiceReaderOverlay'))
|
| 401 |
self.page.evaluate('navigateToReader("/static/reader.html?ext=txt")')
|
|
@@ -456,12 +469,22 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
|
|
| 456 |
navigateToReader('/static/reader.html?ext=txt');
|
| 457 |
const button=document.querySelector('.reader-overlay-opening button');button?.click();return !!button;}''')
|
| 458 |
self.assertTrue(present)
|
| 459 |
-
self.page.
|
| 460 |
-
|
| 461 |
-
self.assertFalse(
|
| 462 |
-
self.
|
| 463 |
for route in held:
|
| 464 |
-
route.fulfill(content_type='text/html', body='<body>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
|
| 466 |
def test_closing_a_speech_reader_does_not_leave_the_reopened_frame_hidden(self):
|
| 467 |
self.page.evaluate('navigateToReader("/static/reader.html?id=speech-resume&ext=txt")')
|
|
@@ -829,3 +852,68 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
|
|
| 829 |
} finally {Storage.prototype.setItem=original;}
|
| 830 |
}''')
|
| 831 |
self.assertTrue(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
def test_back_tap_recovers_when_history_traversal_never_arrives(self):
|
| 391 |
self.page.evaluate('navigateToReader("/static/reader.html?ext=txt")')
|
| 392 |
self.page.frame_locator('.reader-overlay').locator('body').wait_for()
|
| 393 |
+
target = self.page.evaluate('new URL(readerOverlay.src).searchParams.get("return")')
|
| 394 |
self.page.evaluate("""() => {
|
| 395 |
+
window.__backCalls = 0;
|
| 396 |
+
history.back = () => { __backCalls++; };
|
| 397 |
handleReaderMessage({origin:location.origin,source:readerOverlay.contentWindow,data:{type:'voice-reader-close'}});
|
|
|
|
| 398 |
}""")
|
| 399 |
+
# Automatic replacement destroyed the Reader entry when Back was late.
|
| 400 |
+
# The stalled contract now requires a visible, usable explicit recovery.
|
| 401 |
+
recovery = self.page.get_by_role('link', name='直接打开搜索页')
|
| 402 |
+
recovery.wait_for(state='visible', timeout=3000)
|
| 403 |
+
self.assertEqual(recovery.get_attribute('href'), target)
|
| 404 |
+
self.assertFalse(recovery.evaluate('link => !!link.closest("[inert]")'))
|
| 405 |
+
self.assertEqual(self.page.evaluate('__backCalls'), 1)
|
| 406 |
+
self.assertTrue(self.page.evaluate('readerClosing && history.state.voiceReaderOverlay'))
|
| 407 |
+
with self.page.expect_navigation(wait_until='domcontentloaded'):
|
| 408 |
+
recovery.click()
|
| 409 |
+
self.assertEqual(self.page.url, target)
|
| 410 |
+
self.page.wait_for_function('STATE.results.length > 0 && !STATE.isLoading')
|
| 411 |
+
self.assertEqual(self.page.locator('.reader-overlay').count(), 0)
|
| 412 |
self.assertFalse(self.page.evaluate('readerClosing'))
|
| 413 |
self.assertFalse(self.page.evaluate('!!history.state?.voiceReaderOverlay'))
|
| 414 |
self.page.evaluate('navigateToReader("/static/reader.html?ext=txt")')
|
|
|
|
| 469 |
navigateToReader('/static/reader.html?ext=txt');
|
| 470 |
const button=document.querySelector('.reader-overlay-opening button');button?.click();return !!button;}''')
|
| 471 |
self.assertTrue(present)
|
| 472 |
+
recovery = self.page.get_by_role('link', name='直接打开搜索页')
|
| 473 |
+
recovery.wait_for(state='visible', timeout=3000)
|
| 474 |
+
self.assertFalse(recovery.evaluate('link => !!link.closest("[inert]")'))
|
| 475 |
+
self.assertTrue(held)
|
| 476 |
for route in held:
|
| 477 |
+
route.fulfill(content_type='text/html', body='<body>late reader shell</body>')
|
| 478 |
+
self.page.frame_locator('.reader-overlay').locator('body').wait_for()
|
| 479 |
+
self.page.frame_locator('.reader-overlay').locator('body').evaluate(
|
| 480 |
+
'() => window.parent.postMessage({type:"voice-reader-shell"},location.origin)')
|
| 481 |
+
self.assertTrue(recovery.is_visible(), 'late load must not dismiss the recovery shell')
|
| 482 |
+
with self.page.expect_navigation(wait_until='domcontentloaded'):
|
| 483 |
+
recovery.click()
|
| 484 |
+
self.page.wait_for_function('STATE.results.length > 0 && !STATE.isLoading')
|
| 485 |
+
self.assertEqual(self.page.locator('.reader-overlay-opening').count(), 0)
|
| 486 |
+
self.assertEqual(self.page.locator('.reader-overlay').count(), 0)
|
| 487 |
+
self.assertFalse(self.page.evaluate('readerClosing'))
|
| 488 |
|
| 489 |
def test_closing_a_speech_reader_does_not_leave_the_reopened_frame_hidden(self):
|
| 490 |
self.page.evaluate('navigateToReader("/static/reader.html?id=speech-resume&ext=txt")')
|
|
|
|
| 852 |
} finally {Storage.prototype.setItem=original;}
|
| 853 |
}''')
|
| 854 |
self.assertTrue(result)
|
| 855 |
+
|
| 856 |
+
def test_watchdog_late_back_preserves_reader_forward_and_foreign_state(self):
|
| 857 |
+
self.page.locator('#search-input').focus()
|
| 858 |
+
before = self.page.evaluate('''() => {
|
| 859 |
+
history.replaceState({...history.state, foreignSearch:{keep:1}}, '', location.href);
|
| 860 |
+
return {url:location.href, state:history.state, rows:STATE.results.map(getResultStableId)};
|
| 861 |
+
}''')
|
| 862 |
+
opened = self.page.evaluate('''() => {
|
| 863 |
+
const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src)
|
| 864 |
+
.pathname.replace('search/reader-navigation.js','reader.html');
|
| 865 |
+
navigateToReader(path+'?ext=txt&title=Delayed');
|
| 866 |
+
history.replaceState({...history.state, foreignReader:{keep:2}}, '', location.href);
|
| 867 |
+
return {url:location.href, state:history.state, length:history.length};
|
| 868 |
+
}''')
|
| 869 |
+
self.page.frame_locator('.reader-overlay').locator('body').wait_for()
|
| 870 |
+
self.page.evaluate('''() => {
|
| 871 |
+
const back=history.back.bind(history);
|
| 872 |
+
window.__releaseBack=()=>{history.back=back;back();};
|
| 873 |
+
window.__backCalls=0; window.__historyWrites=0;
|
| 874 |
+
history.back=()=>{__backCalls++;};
|
| 875 |
+
for (const name of ['pushState','replaceState']) {
|
| 876 |
+
const original=history[name].bind(history);
|
| 877 |
+
history[name]=(...args)=>{__historyWrites++;return original(...args);};
|
| 878 |
+
}
|
| 879 |
+
window.__returnSnapshot=readerReturnSnapshot;
|
| 880 |
+
handleReaderMessage({origin:location.origin,source:readerOverlay.contentWindow,data:{type:'voice-reader-close'}});
|
| 881 |
+
}''')
|
| 882 |
+
recovery = self.page.get_by_role('link', name='直接打开搜索页')
|
| 883 |
+
recovery.wait_for(state='visible', timeout=3000)
|
| 884 |
+
self.assertEqual(self.page.evaluate('({url:location.href,state:history.state,length:history.length})'), opened)
|
| 885 |
+
self.assertEqual(self.page.evaluate('[__backCalls,__historyWrites]'), [1, 0])
|
| 886 |
+
self.assertTrue(self.page.evaluate('readerClosing && readerReturnSnapshot === __returnSnapshot'))
|
| 887 |
+
# Release the sole requested traversal only after the watchdog has run.
|
| 888 |
+
self.page.evaluate('__releaseBack()')
|
| 889 |
+
self.page.locator('.reader-overlay').wait_for(state='detached')
|
| 890 |
+
self.assertEqual(self.page.url, before['url'])
|
| 891 |
+
self.assertEqual(self.page.evaluate('history.state'), before['state'])
|
| 892 |
+
self.assertEqual(self.page.evaluate('STATE.results.map(getResultStableId)'), before['rows'])
|
| 893 |
+
self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')
|
| 894 |
+
self.assertEqual(self.page.locator('.reader-overlay-opening').count(), 0)
|
| 895 |
+
self.page.evaluate('history.forward()')
|
| 896 |
+
self.page.frame_locator('.reader-overlay').locator('body').wait_for()
|
| 897 |
+
self.assertEqual(self.page.evaluate('({url:location.href,state:history.state,length:history.length})'), opened)
|
| 898 |
+
self.assertEqual(self.page.evaluate('readerOverlay.src'), opened['state']['readerUrl'])
|
| 899 |
+
self.assertFalse(self.page.evaluate('readerClosing'))
|
| 900 |
+
self.assertEqual(self.page.locator('.reader-overlay-opening a').count(), 0)
|
| 901 |
+
|
| 902 |
+
def test_watchdog_recovery_rejects_foreign_and_non_search_targets(self):
|
| 903 |
+
self.page.evaluate('''() => {
|
| 904 |
+
const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src)
|
| 905 |
+
.pathname.replace('search/reader-navigation.js','reader.html');
|
| 906 |
+
navigateToReader(path+'?ext=txt');
|
| 907 |
+
}''')
|
| 908 |
+
self.page.frame_locator('.reader-overlay').locator('body').wait_for()
|
| 909 |
+
self.page.evaluate('''() => {
|
| 910 |
+
history.back=()=>{};
|
| 911 |
+
handleReaderMessage({origin:location.origin,source:readerOverlay.contentWindow,data:{type:'voice-reader-close'}});
|
| 912 |
+
}''')
|
| 913 |
+
recovery = self.page.get_by_role('link', name='直接打开搜索页')
|
| 914 |
+
recovery.wait_for(state='visible', timeout=3000)
|
| 915 |
+
safe = self.page.evaluate('new URL(new URL(readerOverlay.src).pathname.startsWith("/search/")?"/search/":"/",location.origin).href')
|
| 916 |
+
for target in ('https://invalid.example/', 'javascript:alert(1)', '/static/reader.html', '/elsewhere/page', 'http://['):
|
| 917 |
+
self.page.evaluate('target => readerNavigation.showCloseRecovery(target)', target)
|
| 918 |
+
self.assertEqual(recovery.get_attribute('href'), safe)
|
| 919 |
+
self.assertFalse(recovery.evaluate('link => !!link.closest("[inert]")'))
|
tests/reader/browser/test_reader_reload_search_document.py
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real Reader reload -> Back -> search DOM, focus/scroll and Forward.
|
| 2 |
+
|
| 3 |
+
Serve the repository's actual documents/modules. Only search API data and the
|
| 4 |
+
text book are synthetic; no replacement Reader shell or extra search reload.
|
| 5 |
+
Both engines are required. Run through the task's namespace runner.
|
| 6 |
+
"""
|
| 7 |
+
import contextlib
|
| 8 |
+
import functools
|
| 9 |
+
import http.server
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
import unittest
|
| 14 |
+
from urllib.parse import urlencode, urlsplit
|
| 15 |
+
|
| 16 |
+
from playwright.sync_api import sync_playwright
|
| 17 |
+
from tests.search.browser.test_paging_recovery import FETCH_SCRIPT
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 21 |
+
PREFIX = "/search" if '/search/static/' in (ROOT / "static/reader.html").read_text() else ""
|
| 22 |
+
TEXT = "Reader history forward content.\n" * 80
|
| 23 |
+
SOURCE = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/history.txt"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@contextlib.contextmanager
|
| 27 |
+
def source_server():
|
| 28 |
+
control = {"failures": set(), "failed_requests": [], "failure_seen": threading.Event()}
|
| 29 |
+
|
| 30 |
+
class Handler(http.server.SimpleHTTPRequestHandler):
|
| 31 |
+
def translate_path(self, path):
|
| 32 |
+
clean = urlsplit(path).path
|
| 33 |
+
if PREFIX and clean.startswith(PREFIX + "/"):
|
| 34 |
+
clean = clean[len(PREFIX):]
|
| 35 |
+
# Production's SPA fallback serves known repository routes with
|
| 36 |
+
# the search shell; static/API paths keep their own handlers.
|
| 37 |
+
if (clean in ("/", "/index.html") or
|
| 38 |
+
clean.strip('/').split('/')[0] in ('Teachers', 'VOMEBOOK')):
|
| 39 |
+
clean = "/static/index.html"
|
| 40 |
+
elif clean in ('/sw.js', '/manifest.json') or clean.startswith('/icons/'):
|
| 41 |
+
clean = '/static' + clean
|
| 42 |
+
return super().translate_path(clean)
|
| 43 |
+
|
| 44 |
+
def do_GET(self):
|
| 45 |
+
path = urlsplit(self.path).path
|
| 46 |
+
if path in control['failures']:
|
| 47 |
+
control['failed_requests'].append(path)
|
| 48 |
+
control['failure_seen'].set()
|
| 49 |
+
self.send_error(503, 'Controlled cache fallback')
|
| 50 |
+
return
|
| 51 |
+
# SW install fetches bypass Playwright page routes. Supply only the
|
| 52 |
+
# synthetic corpus manifests/data; production SW/assets stay intact.
|
| 53 |
+
if path.startswith(PREFIX + '/data/') and path.endswith('.json'):
|
| 54 |
+
body, content_type = b'{}', 'application/json'
|
| 55 |
+
elif path.startswith(('/api/reader-content', '/api/reader-resource')):
|
| 56 |
+
body, content_type = TEXT.encode(), 'text/plain; charset=utf-8'
|
| 57 |
+
else:
|
| 58 |
+
return super().do_GET()
|
| 59 |
+
self.send_response(200)
|
| 60 |
+
self.send_header('Content-Type', content_type)
|
| 61 |
+
self.send_header('Content-Length', str(len(body)))
|
| 62 |
+
self.end_headers()
|
| 63 |
+
self.wfile.write(body)
|
| 64 |
+
|
| 65 |
+
def guess_type(self, path):
|
| 66 |
+
if path.endswith((".mjs", ".js")):
|
| 67 |
+
return "text/javascript"
|
| 68 |
+
return super().guess_type(path)
|
| 69 |
+
|
| 70 |
+
def log_message(self, *_args):
|
| 71 |
+
pass
|
| 72 |
+
|
| 73 |
+
server = http.server.ThreadingHTTPServer(
|
| 74 |
+
("127.0.0.1", 0), functools.partial(Handler, directory=str(ROOT)))
|
| 75 |
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
| 76 |
+
thread.start()
|
| 77 |
+
try:
|
| 78 |
+
yield f"http://127.0.0.1:{server.server_port}", control
|
| 79 |
+
finally:
|
| 80 |
+
server.shutdown()
|
| 81 |
+
server.server_close()
|
| 82 |
+
thread.join(timeout=5)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ReaderReloadSearchDocumentCases:
|
| 86 |
+
engine = None
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
def setUpClass(cls):
|
| 90 |
+
stack = contextlib.ExitStack()
|
| 91 |
+
cls.addClassCleanup(stack.close)
|
| 92 |
+
cls.origin, cls.server_control = stack.enter_context(source_server())
|
| 93 |
+
playwright = stack.enter_context(sync_playwright())
|
| 94 |
+
cls.browser = getattr(playwright, cls.engine).launch(
|
| 95 |
+
headless=True, **({"args": ["--no-sandbox"]} if cls.engine == "chromium" else {}))
|
| 96 |
+
stack.callback(cls.browser.close)
|
| 97 |
+
|
| 98 |
+
def setUp(self):
|
| 99 |
+
self.server_control['failures'].clear()
|
| 100 |
+
self.server_control['failed_requests'].clear()
|
| 101 |
+
self.server_control['failure_seen'].clear()
|
| 102 |
+
self.addCleanup(self.server_control['failures'].clear)
|
| 103 |
+
self.context = self.browser.new_context(
|
| 104 |
+
service_workers=('allow' if self._testMethodName ==
|
| 105 |
+
'test_controlled_worker_cache_fallback_preserves_reader_back' else 'block'),
|
| 106 |
+
viewport={"width": 1280, "height": 800})
|
| 107 |
+
self.addCleanup(self.context.close)
|
| 108 |
+
self.page = self.context.new_page()
|
| 109 |
+
self.page.set_default_timeout(5000)
|
| 110 |
+
self.page.set_default_navigation_timeout(5000)
|
| 111 |
+
self.page.add_init_script(FETCH_SCRIPT + """
|
| 112 |
+
// Hold a real app search consumer's response only on the return load.
|
| 113 |
+
// Keep the synthetic API payload unchanged and deliberately ignore abort.
|
| 114 |
+
if (window === window.top && sessionStorage.getItem('test-hold-return') &&
|
| 115 |
+
!location.pathname.endsWith('reader.html')) {
|
| 116 |
+
sessionStorage.removeItem('test-hold-return');
|
| 117 |
+
const fetchSearch = window.fetch;
|
| 118 |
+
window.fetch = (input, options) => {
|
| 119 |
+
let body = {};
|
| 120 |
+
try { body = JSON.parse(options?.body || '{}'); } catch (_) {}
|
| 121 |
+
const response = fetchSearch(input, options);
|
| 122 |
+
if (String(input).includes('/api/search') && body.q === 'paging' && body.page === 1) {
|
| 123 |
+
window.__returnHeld = true;
|
| 124 |
+
return new Promise(resolve => {
|
| 125 |
+
window.__releaseReturn = () => Promise.resolve(response).then(value => {
|
| 126 |
+
window.__returnReleased = true; resolve(value);
|
| 127 |
+
});
|
| 128 |
+
});
|
| 129 |
+
}
|
| 130 |
+
return response;
|
| 131 |
+
};
|
| 132 |
+
}
|
| 133 |
+
""")
|
| 134 |
+
# Observation only: capture the handoff before app startup consumes it,
|
| 135 |
+
# and record whether the traversal was a real browser popstate.
|
| 136 |
+
self.page.add_init_script("""(() => {
|
| 137 |
+
if (window !== window.top) return;
|
| 138 |
+
window.__arrivalHandoff = sessionStorage.getItem('reader-navigation-restore');
|
| 139 |
+
addEventListener('popstate', event => {
|
| 140 |
+
sessionStorage.setItem('test-reader-popstate', JSON.stringify({
|
| 141 |
+
trusted: event.isTrusted, url: location.href
|
| 142 |
+
}));
|
| 143 |
+
});
|
| 144 |
+
})();""")
|
| 145 |
+
self.page.route('**/api/**', lambda route: route.fulfill(
|
| 146 |
+
content_type='application/json',
|
| 147 |
+
body='[]' if route.request.url.endswith(('/repos', '/extensions')) else '{}'))
|
| 148 |
+
self.page.route('https://vomebook-hitokoto.hf.space/**', lambda route: route.fulfill(body='{}'))
|
| 149 |
+
for pattern in ('**/api/reader-content**', '**/api/reader-resource**', SOURCE):
|
| 150 |
+
self.page.route(pattern, lambda route: route.fulfill(
|
| 151 |
+
content_type='text/plain; charset=utf-8', body=TEXT,
|
| 152 |
+
headers={'Access-Control-Allow-Origin': '*'}))
|
| 153 |
+
self.page.goto(self.search_url('paging'), wait_until='domcontentloaded')
|
| 154 |
+
self.wait_search('paging')
|
| 155 |
+
|
| 156 |
+
def search_url(self, query):
|
| 157 |
+
route = '/search/#/?' if PREFIX else '/?'
|
| 158 |
+
return self.origin + route + urlencode({'q': query, **({'local': '0'} if PREFIX else {})})
|
| 159 |
+
|
| 160 |
+
def wait_search(self, query):
|
| 161 |
+
self.page.locator('#search-input').wait_for(state='visible')
|
| 162 |
+
self.page.wait_for_function('''query => typeof STATE !== 'undefined' &&
|
| 163 |
+
STATE.query === query && !STATE.isLoading && STATE.results.length >= 100''', arg=query)
|
| 164 |
+
self.assertEqual(self.page.locator('iframe.reader-overlay').count(), 0)
|
| 165 |
+
self.assertEqual(self.page.locator('.reader-text').count(), 0)
|
| 166 |
+
|
| 167 |
+
def open_and_reload(self):
|
| 168 |
+
target = PREFIX + '/static/reader.html?' + urlencode({
|
| 169 |
+
'ext': 'txt', 'url': SOURCE, 'title': 'History book'})
|
| 170 |
+
self.assertTrue(self.page.evaluate('target => navigateToReader(target)', target))
|
| 171 |
+
self.page.frame_locator('iframe.reader-overlay').locator('.reader-text').wait_for(state='visible')
|
| 172 |
+
reader_url = self.page.url
|
| 173 |
+
self.page.reload(wait_until='domcontentloaded') # The one user Reader reload.
|
| 174 |
+
self.page.locator('.reader-text').wait_for(state='visible')
|
| 175 |
+
self.assertIn('Reader history forward content.', self.page.locator('.reader-text').inner_text())
|
| 176 |
+
self.assertEqual(self.page.locator('iframe.reader-overlay').count(), 0)
|
| 177 |
+
return reader_url
|
| 178 |
+
|
| 179 |
+
def test_back_restores_search_focus_scroll_and_forward_book(self):
|
| 180 |
+
self.page.locator('#search-input').focus()
|
| 181 |
+
before = self.page.evaluate('''async () => {
|
| 182 |
+
history.replaceState({...history.state, foreign: {keep: 'search-entry'}}, '', location.href);
|
| 183 |
+
DOM.searchInput.setSelectionRange(1, 4, 'backward');
|
| 184 |
+
setResultScrollTop(520); renderVisible();
|
| 185 |
+
await new Promise(resolve => requestAnimationFrame(resolve));
|
| 186 |
+
return {url: location.href, top: getResultScrollTop(), length: history.length};
|
| 187 |
+
}''')
|
| 188 |
+
reader_url = self.open_and_reload()
|
| 189 |
+
self.assertEqual(self.page.evaluate('history.length'), before['length'] + 1)
|
| 190 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 191 |
+
# There is deliberately no page.reload() here: product popstate must load search.
|
| 192 |
+
self.wait_search('paging')
|
| 193 |
+
self.assertEqual(self.page.url, before['url'])
|
| 194 |
+
self.page.wait_for_function('''top => document.activeElement === DOM.searchInput &&
|
| 195 |
+
Math.abs(getResultScrollTop() - top) <= 2''', arg=before['top'])
|
| 196 |
+
self.assertEqual(self.page.evaluate('history.state.foreign'), {'keep': 'search-entry'})
|
| 197 |
+
self.assertEqual(self.page.evaluate('history.length'), before['length'] + 1)
|
| 198 |
+
self.assertEqual(self.page.evaluate('''[DOM.searchInput.selectionStart,
|
| 199 |
+
DOM.searchInput.selectionEnd, DOM.searchInput.selectionDirection]'''), [1, 4, 'backward'])
|
| 200 |
+
self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('test-reader-popstate'))"),
|
| 201 |
+
{'trusted': True, 'url': before['url']})
|
| 202 |
+
self.page.go_forward(wait_until='domcontentloaded')
|
| 203 |
+
self.assertEqual(self.page.url, reader_url)
|
| 204 |
+
# Depending on document reuse, Forward can restore the standalone Reader
|
| 205 |
+
# or the host overlay; both must render the actual book.
|
| 206 |
+
self.page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible')
|
| 207 |
+
content = (self.page.frame_locator('iframe.reader-overlay').locator('.reader-text')
|
| 208 |
+
if self.page.locator('iframe.reader-overlay').count() else self.page.locator('.reader-text'))
|
| 209 |
+
content.wait_for(state='visible')
|
| 210 |
+
self.assertIn('Reader history forward content.', content.inner_text())
|
| 211 |
+
self.assertEqual(self.page.evaluate('history.length'), before['length'] + 1)
|
| 212 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 213 |
+
self.wait_search('paging')
|
| 214 |
+
self.assertEqual(self.page.url, before['url'])
|
| 215 |
+
|
| 216 |
+
def test_back_then_forward_renders_book_without_consuming_forward_entry(self):
|
| 217 |
+
search_url = self.page.url
|
| 218 |
+
reader_url = self.open_and_reload()
|
| 219 |
+
length = self.page.evaluate('history.length')
|
| 220 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 221 |
+
self.wait_search('paging')
|
| 222 |
+
self.assertEqual(self.page.url, search_url)
|
| 223 |
+
self.page.go_forward(wait_until='domcontentloaded')
|
| 224 |
+
self.assertEqual(self.page.url, reader_url)
|
| 225 |
+
self.page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible')
|
| 226 |
+
content = (self.page.frame_locator('iframe.reader-overlay').locator('.reader-text')
|
| 227 |
+
if self.page.locator('iframe.reader-overlay').count() else self.page.locator('.reader-text'))
|
| 228 |
+
content.wait_for(state='visible')
|
| 229 |
+
self.assertIn('Reader history forward content.', content.inner_text())
|
| 230 |
+
self.assertEqual(self.page.evaluate('history.length'), length)
|
| 231 |
+
|
| 232 |
+
def test_repo_search_reload_back_restores_dom_query_repo_and_forward_book(self):
|
| 233 |
+
search_url = self.origin + '/Teachers?' + urlencode({'q': 'paging-repo'})
|
| 234 |
+
self.page.goto(search_url, wait_until='domcontentloaded')
|
| 235 |
+
self.wait_search('paging-repo')
|
| 236 |
+
self.assertEqual(self.page.evaluate('[STATE.mode, STATE.repo, STATE.repoFull]'),
|
| 237 |
+
['repo', 'Teachers', 'VoiceOfML/Teachers'])
|
| 238 |
+
reader_url = self.open_and_reload()
|
| 239 |
+
length = self.page.evaluate('history.length')
|
| 240 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 241 |
+
# Product popstate must load the repository's actual search document.
|
| 242 |
+
self.wait_search('paging-repo')
|
| 243 |
+
self.assertEqual(self.page.url, search_url)
|
| 244 |
+
self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-repo')
|
| 245 |
+
self.assertEqual(self.page.evaluate('[STATE.mode, STATE.repo, STATE.repoFull]'),
|
| 246 |
+
['repo', 'Teachers', 'VoiceOfML/Teachers'])
|
| 247 |
+
self.assertTrue(self.page.locator('.result-item').first.is_visible())
|
| 248 |
+
self.assertEqual(self.page.evaluate('JSON.parse(window.__arrivalHandoff).returnUrl'), search_url)
|
| 249 |
+
self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('test-reader-popstate'))"),
|
| 250 |
+
{'trusted': True, 'url': search_url})
|
| 251 |
+
self.assertEqual(self.page.evaluate('history.length'), length)
|
| 252 |
+
self.page.go_forward(wait_until='domcontentloaded')
|
| 253 |
+
self.assertEqual(self.page.url, reader_url)
|
| 254 |
+
self.page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible')
|
| 255 |
+
content = (self.page.frame_locator('iframe.reader-overlay').locator('.reader-text')
|
| 256 |
+
if self.page.locator('iframe.reader-overlay').count() else self.page.locator('.reader-text'))
|
| 257 |
+
content.wait_for(state='visible')
|
| 258 |
+
self.assertIn('Reader history forward content.', content.inner_text())
|
| 259 |
+
self.assertEqual(self.page.evaluate('history.length'), length)
|
| 260 |
+
|
| 261 |
+
def test_two_step_back_loads_arrived_query_without_old_return_handoff(self):
|
| 262 |
+
self.page.evaluate("history.replaceState({...history.state, foreign: 'older'}, '', location.href)")
|
| 263 |
+
older_url = self.page.url
|
| 264 |
+
# Search edits replace their current entry. Model a third-party-created
|
| 265 |
+
# entry explicitly so go(-2) really lands on the older search document.
|
| 266 |
+
self.page.evaluate("history.pushState({foreign: 'newer'}, '', location.href)")
|
| 267 |
+
self.page.locator('#search-input').fill('paging-next')
|
| 268 |
+
self.page.locator('#search-input').press('Enter')
|
| 269 |
+
self.wait_search('paging-next')
|
| 270 |
+
newer_url = self.page.url
|
| 271 |
+
self.assertNotEqual(older_url, newer_url)
|
| 272 |
+
self.open_and_reload()
|
| 273 |
+
length = self.page.evaluate('history.length')
|
| 274 |
+
self.page.evaluate('setTimeout(() => history.go(-2), 0)')
|
| 275 |
+
self.wait_search('paging')
|
| 276 |
+
self.assertEqual(self.page.url, older_url)
|
| 277 |
+
self.assertEqual(self.page.evaluate('history.state.foreign'), 'older')
|
| 278 |
+
self.assertIsNone(self.page.evaluate('window.__arrivalHandoff'))
|
| 279 |
+
self.assertEqual(self.page.evaluate('history.length'), length)
|
| 280 |
+
self.page.go_forward(wait_until='domcontentloaded')
|
| 281 |
+
self.wait_search('paging-next')
|
| 282 |
+
self.assertEqual(self.page.url, newer_url)
|
| 283 |
+
|
| 284 |
+
def test_missing_return_session_still_loads_actual_arrived_document(self):
|
| 285 |
+
expected_url = self.page.url
|
| 286 |
+
self.open_and_reload()
|
| 287 |
+
self.page.evaluate("sessionStorage.removeItem('reader-navigation-current')")
|
| 288 |
+
length = self.page.evaluate('history.length')
|
| 289 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 290 |
+
self.wait_search('paging')
|
| 291 |
+
self.assertEqual(self.page.url, expected_url)
|
| 292 |
+
self.assertIsNone(self.page.evaluate('window.__arrivalHandoff'))
|
| 293 |
+
self.assertEqual(self.page.evaluate('history.length'), length)
|
| 294 |
+
|
| 295 |
+
def test_failed_reader_reload_back_restores_search_document(self):
|
| 296 |
+
search_url = self.page.url
|
| 297 |
+
target = PREFIX + '/static/reader.html?' + urlencode({
|
| 298 |
+
'ext': 'txt', 'url': SOURCE, 'title': 'Failed history book'})
|
| 299 |
+
self.assertTrue(self.page.evaluate('target => navigateToReader(target)', target))
|
| 300 |
+
self.page.frame_locator('iframe.reader-overlay').locator('.reader-text').wait_for(state='visible')
|
| 301 |
+
length = self.page.evaluate('history.length')
|
| 302 |
+
# Fail the actual content transport on the user reload. Production
|
| 303 |
+
# fail() cancels book work but leaves the Reader error document alive.
|
| 304 |
+
for pattern in ('**/api/reader-content**', '**/api/reader-resource**', SOURCE):
|
| 305 |
+
self.page.route(pattern, lambda route: route.fulfill(
|
| 306 |
+
status=404, content_type='text/plain', body='Book unavailable',
|
| 307 |
+
headers={'Access-Control-Allow-Origin': '*'}))
|
| 308 |
+
self.page.reload(wait_until='domcontentloaded')
|
| 309 |
+
self.page.locator('.reader-error').wait_for(state='visible')
|
| 310 |
+
self.assertEqual(self.page.locator('iframe.reader-overlay').count(), 0)
|
| 311 |
+
self.assertEqual(self.page.locator('.reader-text').count(), 0)
|
| 312 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 313 |
+
# No fixture reload or direct fail() call: the error screen must keep
|
| 314 |
+
# its real popstate listener until the document/runtime is disposed.
|
| 315 |
+
self.page.locator('#search-input').wait_for(state='visible', timeout=5000)
|
| 316 |
+
self.wait_search('paging')
|
| 317 |
+
self.assertEqual(self.page.url, search_url)
|
| 318 |
+
self.assertEqual(self.page.locator('.reader-error').count(), 0)
|
| 319 |
+
self.assertEqual(self.page.evaluate('history.length'), length)
|
| 320 |
+
self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('test-reader-popstate'))"),
|
| 321 |
+
{'trusted': True, 'url': search_url})
|
| 322 |
+
|
| 323 |
+
def test_return_response_does_not_steal_new_user_focus(self):
|
| 324 |
+
self.page.locator('#search-input').focus()
|
| 325 |
+
# Stay at the top: scrolling saves a usable viewport preview, allowing
|
| 326 |
+
# restoration to finish before the held validation response arrives.
|
| 327 |
+
self.page.evaluate("DOM.searchInput.setSelectionRange(1, 4, 'backward')")
|
| 328 |
+
self.open_and_reload()
|
| 329 |
+
self.page.evaluate("sessionStorage.setItem('test-hold-return', '1')")
|
| 330 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 331 |
+
self.page.locator('#search-input').wait_for(state='visible')
|
| 332 |
+
self.page.wait_for_function('window.__returnHeld === true && STATE.isLoading')
|
| 333 |
+
self.assertIsNotNone(self.page.evaluate('window.__arrivalHandoff'))
|
| 334 |
+
# Move focus with real keyboard input while keeping the route/view
|
| 335 |
+
# unchanged: route invalidation must not hide a focus cancellation bug.
|
| 336 |
+
search = self.page.locator('#search-input')
|
| 337 |
+
search.click()
|
| 338 |
+
search.press('Tab')
|
| 339 |
+
self.assertEqual(self.page.evaluate('document.activeElement.id'), 'settings-btn')
|
| 340 |
+
expected_url = self.page.url
|
| 341 |
+
self.page.evaluate('window.__releaseReturn()')
|
| 342 |
+
self.page.wait_for_function('window.__returnReleased === true')
|
| 343 |
+
self.wait_search('paging')
|
| 344 |
+
self.page.evaluate('''() => new Promise(resolve =>
|
| 345 |
+
requestAnimationFrame(() => requestAnimationFrame(resolve)))''')
|
| 346 |
+
self.assertEqual(search.input_value(), 'paging')
|
| 347 |
+
self.assertEqual(self.page.url, expected_url)
|
| 348 |
+
self.assertEqual(self.page.evaluate('STATE.query'), 'paging')
|
| 349 |
+
self.assertEqual(self.page.evaluate('document.activeElement.id'), 'settings-btn')
|
| 350 |
+
self.assertEqual(self.page.locator('iframe.reader-overlay').count(), 0)
|
| 351 |
+
|
| 352 |
+
def test_controlled_worker_cache_fallback_preserves_reader_back(self):
|
| 353 |
+
self.page.wait_for_function('navigator.serviceWorker.controller !== null')
|
| 354 |
+
controller = self.page.evaluate('navigator.serviceWorker.controller.scriptURL')
|
| 355 |
+
self.assertEqual(controller, self.origin + PREFIX + '/sw.js')
|
| 356 |
+
search_url = self.page.url
|
| 357 |
+
self.page.locator('#search-input').click()
|
| 358 |
+
search_length = self.page.evaluate('history.length')
|
| 359 |
+
cdp = self.context.new_cdp_session(self.page) if self.engine == 'chromium' else None
|
| 360 |
+
target = PREFIX + '/static/reader.html?' + urlencode({
|
| 361 |
+
'ext': 'txt', 'url': SOURCE, 'title': 'Cached history book'})
|
| 362 |
+
self.assertTrue(self.page.evaluate('target => navigateToReader(target)', target))
|
| 363 |
+
self.page.frame_locator('iframe.reader-overlay').locator('.reader-text').wait_for(state='visible')
|
| 364 |
+
reader_url = self.page.url
|
| 365 |
+
# Chromium's renderer can report a stale history.length after the SW
|
| 366 |
+
# controlled iframe opens. Inspect real entries, then verify standalone
|
| 367 |
+
# length and traversal; never accept an extra entry from Reader reload.
|
| 368 |
+
entries_before = cdp.send('Page.getNavigationHistory') if cdp else None
|
| 369 |
+
if entries_before:
|
| 370 |
+
self.assertEqual(len(entries_before['entries']), search_length + 1)
|
| 371 |
+
self.assertEqual(entries_before['entries'][-2]['url'], search_url)
|
| 372 |
+
self.assertEqual(entries_before['entries'][-1]['url'], reader_url)
|
| 373 |
+
shell = PREFIX + '/static/reader.html'
|
| 374 |
+
self.page.wait_for_function('''async shell => {
|
| 375 |
+
const cached = await caches.match(shell);
|
| 376 |
+
return !!cached && cached.ok && (await cached.text()).includes('reader.js');
|
| 377 |
+
}''', arg=shell)
|
| 378 |
+
self.server_control['failures'].add(shell)
|
| 379 |
+
responses = []
|
| 380 |
+
self.page.on('response', lambda response: responses.append(response)
|
| 381 |
+
if urlsplit(response.url).path == shell else None)
|
| 382 |
+
self.page.reload(wait_until='domcontentloaded')
|
| 383 |
+
self.page.locator('.reader-text').wait_for(state='visible')
|
| 384 |
+
length = self.page.evaluate('history.length')
|
| 385 |
+
self.assertEqual(length, search_length + 1)
|
| 386 |
+
if cdp:
|
| 387 |
+
entries_after = cdp.send('Page.getNavigationHistory')
|
| 388 |
+
self.assertEqual(entries_after['currentIndex'], entries_before['currentIndex'])
|
| 389 |
+
self.assertEqual([(entry['id'], entry['url']) for entry in entries_after['entries']],
|
| 390 |
+
[(entry['id'], entry['url']) for entry in entries_before['entries']])
|
| 391 |
+
self.assertTrue(any(response.status == 200 and response.from_service_worker
|
| 392 |
+
for response in responses), 'Reader shell must come through the actual worker')
|
| 393 |
+
# Worker cache-first still revalidates. Observe the server 503 as well as
|
| 394 |
+
# the browser's cached 200, not merely an allow flag or CacheStorage key.
|
| 395 |
+
self.assertTrue(self.page.evaluate('navigator.serviceWorker.controller !== null'))
|
| 396 |
+
self.assertTrue(self.server_control['failure_seen'].wait(timeout=5),
|
| 397 |
+
'The worker must actually revalidate against the failing server')
|
| 398 |
+
self.assertIn(shell, self.server_control['failed_requests'])
|
| 399 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 400 |
+
self.wait_search('paging')
|
| 401 |
+
self.assertEqual(self.page.url, search_url)
|
| 402 |
+
if PREFIX:
|
| 403 |
+
self.assertEqual(self.page.evaluate('navigator.serviceWorker.controller.scriptURL'), controller)
|
| 404 |
+
else:
|
| 405 |
+
# Space intentionally bypasses search navigations. Firefox can load
|
| 406 |
+
# that search document uncontrolled while registration stays active.
|
| 407 |
+
active = self.page.evaluate('''async () => {
|
| 408 |
+
const registration = await navigator.serviceWorker.getRegistration();
|
| 409 |
+
return registration?.active?.scriptURL;
|
| 410 |
+
}''')
|
| 411 |
+
self.assertEqual(active, controller)
|
| 412 |
+
self.assertEqual(self.page.evaluate('history.length'), length)
|
| 413 |
+
if cdp:
|
| 414 |
+
arrived = cdp.send('Page.getNavigationHistory')
|
| 415 |
+
self.assertEqual(arrived['currentIndex'], entries_before['currentIndex'] - 1)
|
| 416 |
+
self.assertEqual([(entry['id'], entry['url']) for entry in arrived['entries']],
|
| 417 |
+
[(entry['id'], entry['url']) for entry in entries_before['entries']])
|
| 418 |
+
self.page.go_forward(wait_until='domcontentloaded')
|
| 419 |
+
self.assertEqual(self.page.url, reader_url)
|
| 420 |
+
self.page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible')
|
| 421 |
+
content = (self.page.frame_locator('iframe.reader-overlay').locator('.reader-text')
|
| 422 |
+
if self.page.locator('iframe.reader-overlay').count() else self.page.locator('.reader-text'))
|
| 423 |
+
content.wait_for(state='visible')
|
| 424 |
+
self.assertIn('Reader history forward content.', content.inner_text())
|
| 425 |
+
# Forward may mount Reader in the uncontrolled Space search host. Check
|
| 426 |
+
# the document rendering the book, not the parent host's controller.
|
| 427 |
+
self.assertEqual(content.evaluate('() => navigator.serviceWorker.controller?.scriptURL'), controller)
|
| 428 |
+
self.assertEqual(self.page.evaluate('history.length'), length)
|
| 429 |
+
|
| 430 |
+
def test_reader_hash_traversal_keeps_live_reader_document(self):
|
| 431 |
+
reader_url = self.open_and_reload()
|
| 432 |
+
self.page.evaluate("window.__sameReader = true; location.hash = 'chapter-test'")
|
| 433 |
+
self.page.go_back(wait_until='domcontentloaded')
|
| 434 |
+
self.assertEqual(self.page.url, reader_url)
|
| 435 |
+
self.assertTrue(self.page.evaluate('window.__sameReader'))
|
| 436 |
+
self.assertIn('Reader history forward content.', self.page.locator('.reader-text').inner_text())
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
class ReaderReloadSearchDocumentChromium(ReaderReloadSearchDocumentCases, unittest.TestCase):
|
| 440 |
+
engine = 'chromium'
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
class ReaderReloadSearchDocumentFirefox(ReaderReloadSearchDocumentCases, unittest.TestCase):
|
| 444 |
+
engine = 'firefox'
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class ReaderTrueOfflineCases:
|
| 448 |
+
"""Space intentionally bypasses search navigations and API/book requests.
|
| 449 |
+
|
| 450 |
+
A fresh offline search document cannot load, even after an online visit.
|
| 451 |
+
Assert that browser limitation explicitly, not fictitious offline search
|
| 452 |
+
success or a blank product document. Recovery reloads search after the
|
| 453 |
+
network returns, then follows the preserved Forward entry to the book.
|
| 454 |
+
Pages covers native corpus recovery.
|
| 455 |
+
"""
|
| 456 |
+
|
| 457 |
+
setUpClass = classmethod(ReaderReloadSearchDocumentCases.setUpClass.__func__)
|
| 458 |
+
|
| 459 |
+
def test_true_offline_reader_reload_back_forward(self):
|
| 460 |
+
from playwright.sync_api import Error as PlaywrightError
|
| 461 |
+
|
| 462 |
+
# A fresh context has neither FETCH_SCRIPT's fetch shim nor its forced
|
| 463 |
+
# navigator.onLine value. Book bytes are synthetic only while online.
|
| 464 |
+
context = self.browser.new_context(service_workers='allow')
|
| 465 |
+
self.addCleanup(context.close)
|
| 466 |
+
page = context.new_page()
|
| 467 |
+
page.set_default_timeout(15000)
|
| 468 |
+
page.set_default_navigation_timeout(15000)
|
| 469 |
+
for pattern in ('**/api/reader-content**', '**/api/reader-resource**', SOURCE):
|
| 470 |
+
page.route(pattern, lambda route: route.fulfill(
|
| 471 |
+
content_type='text/plain; charset=utf-8', body=TEXT,
|
| 472 |
+
headers={'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store'}))
|
| 473 |
+
responses, failed = [], []
|
| 474 |
+
page.on('response', lambda response: responses.append(response))
|
| 475 |
+
page.on('requestfailed', lambda request: failed.append(request))
|
| 476 |
+
search_url = self.origin + '/?q=offline-history'
|
| 477 |
+
page.goto(search_url, wait_until='domcontentloaded')
|
| 478 |
+
page.locator('#search-input').wait_for(state='visible')
|
| 479 |
+
page.wait_for_function('navigator.serviceWorker.controller !== null')
|
| 480 |
+
self.assertEqual(page.evaluate('navigator.serviceWorker.controller.scriptURL'),
|
| 481 |
+
self.origin + '/sw.js')
|
| 482 |
+
target = '/static/reader.html?' + urlencode({
|
| 483 |
+
'ext': 'txt', 'url': SOURCE, 'title': 'Offline history book'})
|
| 484 |
+
self.assertTrue(page.evaluate('target => navigateToReader(target)', target))
|
| 485 |
+
content = page.frame_locator('iframe.reader-overlay').locator('.reader-text')
|
| 486 |
+
content.wait_for(state='visible')
|
| 487 |
+
self.assertIn('Reader history forward content.', content.inner_text())
|
| 488 |
+
reader_url = page.url
|
| 489 |
+
# Await real SW persistence of loaded assets, never seed CacheStorage.
|
| 490 |
+
assets = page.evaluate('''() => {
|
| 491 |
+
const frame = document.querySelector('iframe.reader-overlay');
|
| 492 |
+
return [...new Set([performance, frame.contentWindow.performance].flatMap(p =>
|
| 493 |
+
p.getEntriesByType('resource').map(entry => entry.name)).filter(url =>
|
| 494 |
+
url.startsWith(location.origin + '/') && /\\.(?:m?js|css)(?:[?]|$)/.test(url)))];
|
| 495 |
+
}''')
|
| 496 |
+
page.evaluate('''async urls => {
|
| 497 |
+
await Promise.all(urls.map(async url => {
|
| 498 |
+
const response = await fetch(url);
|
| 499 |
+
if (!response.ok) throw Error('Warm failed: ' + url);
|
| 500 |
+
await response.arrayBuffer();
|
| 501 |
+
}));
|
| 502 |
+
}''', assets)
|
| 503 |
+
page.wait_for_function('''async urls =>
|
| 504 |
+
(await Promise.all(urls.map(url => caches.match(url)))).every(r => r?.ok)
|
| 505 |
+
''', arg=['/static/reader.html', *assets])
|
| 506 |
+
self.assertFalse(page.evaluate('''async () => !!await caches.match('/')'''))
|
| 507 |
+
page.unroute_all(behavior='wait')
|
| 508 |
+
context.set_offline(True)
|
| 509 |
+
failed.clear()
|
| 510 |
+
response = page.reload(wait_until='domcontentloaded')
|
| 511 |
+
self.assertEqual(response.status, 200)
|
| 512 |
+
self.assertTrue(response.from_service_worker)
|
| 513 |
+
|
| 514 |
+
def assert_reader_error():
|
| 515 |
+
error = page.locator('.reader-error')
|
| 516 |
+
error.wait_for(state='visible')
|
| 517 |
+
# Current text transport exposes the browser error; Back remains
|
| 518 |
+
# available. There is no text-book Retry control to invent here.
|
| 519 |
+
self.assertRegex(error.inner_text(), 'Failed to fetch|NetworkError|网络|重试|下载')
|
| 520 |
+
self.assertEqual(page.locator('.reader-text, iframe.reader-overlay').count(), 0)
|
| 521 |
+
self.assertTrue(page.locator('#back').is_visible())
|
| 522 |
+
self.assertTrue(page.locator('#back').is_enabled())
|
| 523 |
+
self.assertFalse(page.evaluate('navigator.onLine'))
|
| 524 |
+
|
| 525 |
+
assert_reader_error()
|
| 526 |
+
self.assertTrue(any('/api/reader-content' in request.url or request.url == SOURCE
|
| 527 |
+
for request in failed), 'Book transport must actually fail offline')
|
| 528 |
+
length = page.evaluate('history.length')
|
| 529 |
+
responses.clear()
|
| 530 |
+
# Require an actual failed document request: BFCache reuse alone cannot
|
| 531 |
+
# establish the contract of the SW's deliberately uncached search shell.
|
| 532 |
+
with page.expect_event('requestfailed', predicate=lambda request:
|
| 533 |
+
request.is_navigation_request() and
|
| 534 |
+
request.frame == page.main_frame and
|
| 535 |
+
urlsplit(request.url).path == '/') as failure:
|
| 536 |
+
try:
|
| 537 |
+
page.go_back(wait_until='domcontentloaded')
|
| 538 |
+
except PlaywrightError as error:
|
| 539 |
+
self.assertRegex(str(error), 'ERR_INTERNET_DISCONNECTED|NS_ERROR_OFFLINE|NS_ERROR_NET_RESET')
|
| 540 |
+
self.assertEqual(failure.value.url, search_url)
|
| 541 |
+
self.assertTrue(failure.value.failure)
|
| 542 |
+
self.assertFalse(any(response.request.is_navigation_request() and
|
| 543 |
+
urlsplit(response.url).path == '/' and response.status == 200
|
| 544 |
+
for response in responses))
|
| 545 |
+
# requestfailed precedes the browser error document's commit. Wait for
|
| 546 |
+
# that document to settle before touching history again; Chromium can
|
| 547 |
+
# temporarily detach its page target during this transition. The error
|
| 548 |
+
# document belongs to the browser, not to the search application.
|
| 549 |
+
error_ready = False
|
| 550 |
+
deadline = time.monotonic() + 5
|
| 551 |
+
while time.monotonic() < deadline:
|
| 552 |
+
try:
|
| 553 |
+
error_ready = page.evaluate('''() =>
|
| 554 |
+
!document.querySelector('#search-input, .reader-error, .reader-text') &&
|
| 555 |
+
(document.documentURI.startsWith('about:neterror?e=netOffline') ||
|
| 556 |
+
(document.readyState === 'complete' &&
|
| 557 |
+
document.documentURI.startsWith('chrome-error://')))''')
|
| 558 |
+
except PlaywrightError:
|
| 559 |
+
# The browser can replace the error document's execution context.
|
| 560 |
+
error_ready = False
|
| 561 |
+
if error_ready:
|
| 562 |
+
break
|
| 563 |
+
page.wait_for_timeout(50)
|
| 564 |
+
self.assertTrue(error_ready, 'Expected the browser network error document')
|
| 565 |
+
context.set_offline(False)
|
| 566 |
+
# Restore the same online-only book fixture after reconnecting. No
|
| 567 |
+
# route or fetch shim supplies any response during the offline phase.
|
| 568 |
+
for pattern in ('**/api/reader-content**', '**/api/reader-resource**', SOURCE):
|
| 569 |
+
page.route(pattern, lambda route: route.fulfill(
|
| 570 |
+
content_type='text/plain; charset=utf-8', body=TEXT,
|
| 571 |
+
headers={'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store'}))
|
| 572 |
+
# Retry the failed search entry in place. goto(search_url) would create
|
| 573 |
+
# a new entry and discard Forward, hiding irreversible history loss.
|
| 574 |
+
response = page.reload(wait_until='domcontentloaded')
|
| 575 |
+
self.assertEqual(response.status, 200)
|
| 576 |
+
self.assertEqual(page.url, search_url)
|
| 577 |
+
page.locator('#search-input').wait_for(state='visible')
|
| 578 |
+
page.wait_for_function('''typeof STATE !== 'undefined' &&
|
| 579 |
+
STATE.query === 'offline-history' ''')
|
| 580 |
+
self.assertEqual(page.locator('.reader-error, .reader-text, iframe.reader-overlay').count(), 0)
|
| 581 |
+
self.assertEqual(page.evaluate('history.length'), length)
|
| 582 |
+
page.go_forward(wait_until='domcontentloaded')
|
| 583 |
+
page.wait_for_url(reader_url, wait_until='domcontentloaded')
|
| 584 |
+
page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible')
|
| 585 |
+
document = (page.frame_locator('iframe.reader-overlay')
|
| 586 |
+
if page.locator('iframe.reader-overlay').count() else page)
|
| 587 |
+
content = document.locator('.reader-text')
|
| 588 |
+
content.wait_for(state='visible')
|
| 589 |
+
self.assertIn('Reader history forward content.', content.inner_text())
|
| 590 |
+
self.assertEqual(document.locator('.reader-error').count(), 0)
|
| 591 |
+
self.assertEqual(page.url, reader_url)
|
| 592 |
+
self.assertEqual(page.evaluate('history.length'), length)
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
class ReaderTrueOfflineChromium(ReaderTrueOfflineCases, unittest.TestCase):
|
| 596 |
+
engine = 'chromium'
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
class ReaderTrueOfflineFirefox(ReaderTrueOfflineCases, unittest.TestCase):
|
| 600 |
+
engine = 'firefox'
|
tests/reader/core/test_reader_regression.js
CHANGED
|
@@ -368,7 +368,7 @@ const defaultReaderUrl = sandbox.self.VoiceOfMLReader.readerUrl(immutableRecord)
|
|
| 368 |
assert.ok(defaultReaderUrl.startsWith('/static/reader.html?'))
|
| 369 |
assert.strictEqual(JSON.stringify(immutableRecord), immutableBefore)
|
| 370 |
assert.strictEqual((reader.match(/function setToc\(/g) || []).length, 1)
|
| 371 |
-
assertCode(reader, 'const previousList = document.querySelector("#toc-list")')
|
| 372 |
assertCode(reader, 'previousList.cloneNode(false)')
|
| 373 |
assertCode(reader, 'previousList.replaceWith(list)')
|
| 374 |
assert.strictEqual((reader.match(/function activateFoliateTocEntry\(/g) || []).length, 1)
|
|
|
|
| 368 |
assert.ok(defaultReaderUrl.startsWith('/static/reader.html?'))
|
| 369 |
assert.strictEqual(JSON.stringify(immutableRecord), immutableBefore)
|
| 370 |
assert.strictEqual((reader.match(/function setToc\(/g) || []).length, 1)
|
| 371 |
+
assertCode(reader, 'const previousList = /** @type {HTMLElement} */ (document.querySelector("#toc-list"))')
|
| 372 |
assertCode(reader, 'previousList.cloneNode(false)')
|
| 373 |
assertCode(reader, 'previousList.replaceWith(list)')
|
| 374 |
assert.strictEqual((reader.match(/function activateFoliateTocEntry\(/g) || []).length, 1)
|
tests/search/browser/test_paging_recovery.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
"""Focused browser regressions for resumed and stalled result pagination."""
|
|
|
|
| 2 |
import unittest
|
| 3 |
|
| 4 |
from tests.support.real_server import get_shared_server
|
|
@@ -6,6 +7,9 @@ from playwright.sync_api import sync_playwright
|
|
| 6 |
|
| 7 |
|
| 8 |
FETCH_SCRIPT = r"""(() => {
|
|
|
|
|
|
|
|
|
|
| 9 |
const nativeFetch = window.fetch.bind(window);
|
| 10 |
window.pagingMode = 'stall';
|
| 11 |
window.pagingTotal = 301;
|
|
@@ -38,7 +42,9 @@ class PagingRecoveryTests(unittest.TestCase):
|
|
| 38 |
def setUpClass(cls):
|
| 39 |
cls.origin = get_shared_server().base_url
|
| 40 |
cls.playwright = sync_playwright().start()
|
| 41 |
-
|
|
|
|
|
|
|
| 42 |
|
| 43 |
@classmethod
|
| 44 |
def tearDownClass(cls):
|
|
@@ -46,7 +52,7 @@ class PagingRecoveryTests(unittest.TestCase):
|
|
| 46 |
cls.playwright.stop()
|
| 47 |
|
| 48 |
def setUp(self):
|
| 49 |
-
self.context = self.browser.new_context(viewport={'width': 1280, 'height': 800})
|
| 50 |
self.page = self.context.new_page()
|
| 51 |
self.errors = []
|
| 52 |
self.page.on('pageerror', lambda error: self.errors.append(str(error)))
|
|
|
|
| 1 |
"""Focused browser regressions for resumed and stalled result pagination."""
|
| 2 |
+
import os
|
| 3 |
import unittest
|
| 4 |
|
| 5 |
from tests.support.real_server import get_shared_server
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
FETCH_SCRIPT = r"""(() => {
|
| 10 |
+
// This fixture serves an online API through fetch interception. A loopback-only
|
| 11 |
+
// test namespace can report offline despite those responses being available.
|
| 12 |
+
Object.defineProperty(navigator, 'onLine', {configurable: true, get: () => true});
|
| 13 |
const nativeFetch = window.fetch.bind(window);
|
| 14 |
window.pagingMode = 'stall';
|
| 15 |
window.pagingTotal = 301;
|
|
|
|
| 42 |
def setUpClass(cls):
|
| 43 |
cls.origin = get_shared_server().base_url
|
| 44 |
cls.playwright = sync_playwright().start()
|
| 45 |
+
engine = os.environ.get('SEARCH_POSITION_BROWSER', 'chromium')
|
| 46 |
+
cls.browser = getattr(cls.playwright, engine).launch(
|
| 47 |
+
headless=True, **({'args': ['--no-sandbox']} if engine == 'chromium' else {}))
|
| 48 |
|
| 49 |
@classmethod
|
| 50 |
def tearDownClass(cls):
|
|
|
|
| 52 |
cls.playwright.stop()
|
| 53 |
|
| 54 |
def setUp(self):
|
| 55 |
+
self.context = self.browser.new_context(service_workers='block', viewport={'width': 1280, 'height': 800})
|
| 56 |
self.page = self.context.new_page()
|
| 57 |
self.errors = []
|
| 58 |
self.page.on('pageerror', lambda error: self.errors.append(str(error)))
|
tests/search/browser/test_session_transaction_browser.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Session-only native IndexedDB regressions; select Chromium or Firefox explicitly."""
|
| 2 |
+
import contextlib
|
| 3 |
+
import functools
|
| 4 |
+
import http.server
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import threading
|
| 8 |
+
import unittest
|
| 9 |
+
|
| 10 |
+
from playwright.sync_api import sync_playwright
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SessionTransactionBrowserTests(unittest.TestCase):
|
| 17 |
+
@classmethod
|
| 18 |
+
def setUpClass(cls):
|
| 19 |
+
stack = contextlib.ExitStack()
|
| 20 |
+
cls.addClassCleanup(stack.close)
|
| 21 |
+
|
| 22 |
+
class Handler(http.server.SimpleHTTPRequestHandler):
|
| 23 |
+
def log_message(self, *_args):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
server = http.server.ThreadingHTTPServer(
|
| 27 |
+
('127.0.0.1', 0), functools.partial(Handler, directory=str(ROOT)))
|
| 28 |
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
| 29 |
+
thread.start()
|
| 30 |
+
cls.addClassCleanup(lambda: (server.shutdown(), server.server_close(), thread.join(3)))
|
| 31 |
+
cls.origin = f'http://127.0.0.1:{server.server_port}'
|
| 32 |
+
playwright = stack.enter_context(sync_playwright())
|
| 33 |
+
engine = os.environ.get('SEARCH_SESSION_BROWSER', 'chromium')
|
| 34 |
+
if engine not in ('chromium', 'firefox'):
|
| 35 |
+
raise ValueError('SEARCH_SESSION_BROWSER must be chromium or firefox')
|
| 36 |
+
cls.browser = getattr(playwright, engine).launch(headless=True)
|
| 37 |
+
cls.addClassCleanup(cls.browser.close)
|
| 38 |
+
|
| 39 |
+
def setUp(self):
|
| 40 |
+
self.context = self.browser.new_context(service_workers='block')
|
| 41 |
+
self.addCleanup(self.context.close)
|
| 42 |
+
self.context.route('**/*', lambda route: route.continue_()
|
| 43 |
+
if route.request.url.startswith(self.origin + '/') else route.abort())
|
| 44 |
+
self.page = self.context.new_page()
|
| 45 |
+
self.page.set_default_timeout(8000)
|
| 46 |
+
errors = []
|
| 47 |
+
self.page.on('pageerror', lambda error: errors.append(str(error)))
|
| 48 |
+
self.addCleanup(lambda: self.assertEqual(errors, []))
|
| 49 |
+
self.page.route('**/session-fixture*', lambda route: route.fulfill(
|
| 50 |
+
content_type='text/html', body='<!doctype html><title>Session transaction</title>'))
|
| 51 |
+
self.page.goto(self.origin + '/session-fixture?q=first')
|
| 52 |
+
self.page.add_script_tag(url=self.origin + '/static/search/search-session.js')
|
| 53 |
+
self.page.evaluate('''() => {
|
| 54 |
+
window.session = VoiceOfMLSearchSession.createSearchSession({
|
| 55 |
+
canPersist: () => true, canRestore: target => !target || target.origin === location.origin
|
| 56 |
+
});
|
| 57 |
+
window.until = async predicate => {
|
| 58 |
+
const deadline = performance.now() + 5000;
|
| 59 |
+
while (!predicate()) {
|
| 60 |
+
if (performance.now() > deadline) throw new Error('session checkpoint timed out');
|
| 61 |
+
await new Promise(resolve => setTimeout(resolve, 5));
|
| 62 |
+
}
|
| 63 |
+
};
|
| 64 |
+
window.readSaved = async () => {
|
| 65 |
+
const db = await session.openSearchSessionDB();
|
| 66 |
+
try {
|
| 67 |
+
const tx = db.transaction('session', 'readonly');
|
| 68 |
+
const get = tx.objectStore('session').get('last-search');
|
| 69 |
+
await new Promise((resolve, reject) => {
|
| 70 |
+
tx.oncomplete = resolve; tx.onabort = () => reject(tx.error);
|
| 71 |
+
});
|
| 72 |
+
return get.result;
|
| 73 |
+
} finally { db.close(); }
|
| 74 |
+
};
|
| 75 |
+
}''')
|
| 76 |
+
|
| 77 |
+
def test_delayed_open_captures_url_and_coalesces_the_latest_save(self):
|
| 78 |
+
result = self.page.evaluate('''async () => {
|
| 79 |
+
const open = indexedDB.open.bind(indexedDB), put = IDBObjectStore.prototype.put;
|
| 80 |
+
let release, opens = 0;
|
| 81 |
+
const writes = [];
|
| 82 |
+
IDBObjectStore.prototype.put = function(value, ...args) {
|
| 83 |
+
writes.push(value.url); return put.call(this, value, ...args);
|
| 84 |
+
};
|
| 85 |
+
indexedDB.open = (...args) => {
|
| 86 |
+
opens++;
|
| 87 |
+
const request = open(...args);
|
| 88 |
+
if (opens !== 1) return request;
|
| 89 |
+
return new Proxy(request, {
|
| 90 |
+
get: (target, key) => target[key],
|
| 91 |
+
set(target, key, value) {
|
| 92 |
+
target[key] = key === 'onsuccess' ? event => { release = () => value(event); } : value;
|
| 93 |
+
return true;
|
| 94 |
+
}
|
| 95 |
+
});
|
| 96 |
+
};
|
| 97 |
+
try {
|
| 98 |
+
const original = location.href;
|
| 99 |
+
const first = session.persistSearchSession();
|
| 100 |
+
await until(() => !!release);
|
| 101 |
+
history.replaceState(null, '', '?q=second');
|
| 102 |
+
const pending = session.persistSearchSession();
|
| 103 |
+
let shared = true;
|
| 104 |
+
for (let i = 0; i < 2000; i++) {
|
| 105 |
+
// Only the final URL matters to persistence; avoid browser history rate limits.
|
| 106 |
+
shared = shared && session.persistSearchSession() === pending;
|
| 107 |
+
}
|
| 108 |
+
history.replaceState(null, '', '?q=latest');
|
| 109 |
+
shared = shared && session.persistSearchSession() === pending;
|
| 110 |
+
const latest = location.href, beforeRelease = opens;
|
| 111 |
+
release();
|
| 112 |
+
await Promise.all([first, pending]);
|
| 113 |
+
const saved = await readSaved();
|
| 114 |
+
return {original, latest, beforeRelease, shared, writes, saved: saved.url};
|
| 115 |
+
} finally { indexedDB.open = open; IDBObjectStore.prototype.put = put; }
|
| 116 |
+
}''')
|
| 117 |
+
self.assertEqual(result['beforeRelease'], 1)
|
| 118 |
+
self.assertTrue(result['shared'])
|
| 119 |
+
self.assertEqual(result['writes'], [result['original'], result['latest']])
|
| 120 |
+
self.assertEqual(result['saved'], result['latest'])
|
| 121 |
+
|
| 122 |
+
def test_read_success_followed_by_native_abort_does_not_restore(self):
|
| 123 |
+
result = self.page.evaluate('''async () => {
|
| 124 |
+
await session.persistSearchSession();
|
| 125 |
+
history.replaceState({foreign: 7}, '', '?q=current');
|
| 126 |
+
const get = IDBObjectStore.prototype.get;
|
| 127 |
+
let succeeded = false, aborted = false;
|
| 128 |
+
IDBObjectStore.prototype.get = function(...args) {
|
| 129 |
+
const request = get.apply(this, args), tx = this.transaction;
|
| 130 |
+
request.addEventListener('success', () => { succeeded = true; tx.abort(); });
|
| 131 |
+
tx.addEventListener('abort', () => { aborted = true; });
|
| 132 |
+
return request;
|
| 133 |
+
};
|
| 134 |
+
try {
|
| 135 |
+
const restored = await session.restoreSearchSession();
|
| 136 |
+
await until(() => aborted);
|
| 137 |
+
return {restored, succeeded, aborted, search: location.search, state: history.state};
|
| 138 |
+
} finally { IDBObjectStore.prototype.get = get; }
|
| 139 |
+
}''')
|
| 140 |
+
self.assertEqual(result, dict(restored=False, succeeded=True, aborted=True,
|
| 141 |
+
search='?q=current', state={'foreign': 7}))
|
| 142 |
+
|
| 143 |
+
def test_restore_waits_for_native_completion_and_keeps_foreign_state(self):
|
| 144 |
+
result = self.page.evaluate('''async () => {
|
| 145 |
+
await session.persistSearchSession();
|
| 146 |
+
history.replaceState({foreign: ['keep', 42]}, '', '?q=current');
|
| 147 |
+
const transaction = IDBDatabase.prototype.transaction;
|
| 148 |
+
let release, nativeComplete = false;
|
| 149 |
+
IDBDatabase.prototype.transaction = function(...args) {
|
| 150 |
+
const tx = transaction.apply(this, args);
|
| 151 |
+
tx.addEventListener('complete', () => { nativeComplete = true; });
|
| 152 |
+
return new Proxy(tx, {
|
| 153 |
+
get(target, key) {
|
| 154 |
+
const value = target[key]; return typeof value === 'function' ? value.bind(target) : value;
|
| 155 |
+
},
|
| 156 |
+
set(target, key, value) {
|
| 157 |
+
target[key] = key === 'oncomplete' ? event => { release = () => value(event); } : value;
|
| 158 |
+
return true;
|
| 159 |
+
}
|
| 160 |
+
});
|
| 161 |
+
};
|
| 162 |
+
try {
|
| 163 |
+
const pending = session.restoreSearchSession();
|
| 164 |
+
await until(() => !!release);
|
| 165 |
+
const beforeRelease = location.search;
|
| 166 |
+
release();
|
| 167 |
+
return {beforeRelease, nativeComplete, restored: await pending,
|
| 168 |
+
search: location.search, state: history.state};
|
| 169 |
+
} finally { IDBDatabase.prototype.transaction = transaction; }
|
| 170 |
+
}''')
|
| 171 |
+
self.assertEqual(result, dict(beforeRelease='?q=current', nativeComplete=True,
|
| 172 |
+
restored=True, search='?q=first', state={'foreign': ['keep', 42]}))
|
| 173 |
+
|
| 174 |
+
def test_pending_restore_cancels_on_observed_navigation_and_input(self):
|
| 175 |
+
for action in ('href', 'popstate', 'hashchange', 'pagehide', 'input',
|
| 176 |
+
'compositionstart', 'compositionupdate', 'compositionend', 'entry', 'traversal'):
|
| 177 |
+
with self.subTest(action=action):
|
| 178 |
+
result = self.page.evaluate('''async action => {
|
| 179 |
+
history.replaceState(null, '', '?q=saved');
|
| 180 |
+
await session.persistSearchSession();
|
| 181 |
+
history.replaceState({foreign:42}, '', '/session-fixture');
|
| 182 |
+
if (action === 'traversal') history.pushState(history.state, '', location.href);
|
| 183 |
+
const transaction = IDBDatabase.prototype.transaction;
|
| 184 |
+
let release;
|
| 185 |
+
IDBDatabase.prototype.transaction = function(...args) {
|
| 186 |
+
const tx = transaction.apply(this, args);
|
| 187 |
+
return new Proxy(tx, {
|
| 188 |
+
get(target, key) {
|
| 189 |
+
const value = target[key];
|
| 190 |
+
return typeof value === 'function' ? value.bind(target) : value;
|
| 191 |
+
},
|
| 192 |
+
set(target, key, value) {
|
| 193 |
+
target[key] = key === 'oncomplete' ? event => { release = () => value(event); } : value;
|
| 194 |
+
return true;
|
| 195 |
+
}
|
| 196 |
+
});
|
| 197 |
+
};
|
| 198 |
+
try {
|
| 199 |
+
const pending = session.restoreSearchSession();
|
| 200 |
+
await until(() => !!release);
|
| 201 |
+
const hasKey = !!window.navigation?.currentEntry?.key;
|
| 202 |
+
if (action === 'href') history.replaceState(history.state, '', '/session-fixture-other');
|
| 203 |
+
else if (action === 'traversal') {
|
| 204 |
+
await new Promise(resolve => {
|
| 205 |
+
window.addEventListener('popstate', resolve, {once:true});
|
| 206 |
+
history.back();
|
| 207 |
+
});
|
| 208 |
+
} else if (action === 'entry') {
|
| 209 |
+
history.pushState(history.state, '', location.href);
|
| 210 |
+
// Engines without entry keys rely on observable traversal.
|
| 211 |
+
if (!hasKey) window.dispatchEvent(new PopStateEvent('popstate'));
|
| 212 |
+
} else window.dispatchEvent(new Event(action));
|
| 213 |
+
const expected = location.href;
|
| 214 |
+
release();
|
| 215 |
+
const restored = await pending;
|
| 216 |
+
return {restored, unchanged:location.href === expected, state:history.state};
|
| 217 |
+
} finally { IDBDatabase.prototype.transaction = transaction; }
|
| 218 |
+
}''', action)
|
| 219 |
+
self.assertEqual(result, dict(restored=False, unchanged=True, state={'foreign': 42}))
|
| 220 |
+
|
| 221 |
+
def test_restore_cancellation_listeners_are_removed_after_every_attempt(self):
|
| 222 |
+
result = self.page.evaluate('''async () => {
|
| 223 |
+
await session.persistSearchSession();
|
| 224 |
+
const add = window.addEventListener, remove = window.removeEventListener;
|
| 225 |
+
const live = new Map();
|
| 226 |
+
window.addEventListener = function(type, listener, options) {
|
| 227 |
+
if (options === true) live.set(type, listener);
|
| 228 |
+
return add.call(this, type, listener, options);
|
| 229 |
+
};
|
| 230 |
+
window.removeEventListener = function(type, listener, options) {
|
| 231 |
+
if (live.get(type) === listener) live.delete(type);
|
| 232 |
+
return remove.call(this, type, listener, options);
|
| 233 |
+
};
|
| 234 |
+
try {
|
| 235 |
+
const first = await session.restoreSearchSession();
|
| 236 |
+
const afterSuccess = live.size;
|
| 237 |
+
window.dispatchEvent(new Event('input'));
|
| 238 |
+
const second = await session.restoreSearchSession();
|
| 239 |
+
const open = indexedDB.open;
|
| 240 |
+
indexedDB.open = () => { throw new Error('unavailable'); };
|
| 241 |
+
let failed;
|
| 242 |
+
try { failed = await session.restoreSearchSession(); }
|
| 243 |
+
finally { indexedDB.open = open; }
|
| 244 |
+
return {first, second, failed, afterSuccess, afterFailure:live.size};
|
| 245 |
+
} finally { window.addEventListener = add; window.removeEventListener = remove; }
|
| 246 |
+
}''')
|
| 247 |
+
self.assertEqual(result, dict(first=True, second=True, failed=False, afterSuccess=0, afterFailure=0))
|
| 248 |
+
|
| 249 |
+
def test_error_and_timeout_wait_for_native_abort_before_reopening(self):
|
| 250 |
+
for failure in ('request-error', 'timeout'):
|
| 251 |
+
with self.subTest(failure=failure):
|
| 252 |
+
result = self.page.evaluate('''async failure => {
|
| 253 |
+
await session.persistSearchSession();
|
| 254 |
+
const transaction = IDBDatabase.prototype.transaction;
|
| 255 |
+
const open = indexedDB.open.bind(indexedDB);
|
| 256 |
+
let opens = 0, captured = false, release, nativeAbort = false, opensAtAbort;
|
| 257 |
+
indexedDB.open = (...args) => { opens++; return open(...args); };
|
| 258 |
+
IDBDatabase.prototype.transaction = function(...args) {
|
| 259 |
+
const tx = transaction.apply(this, args);
|
| 260 |
+
if (captured || tx.mode !== 'readwrite') return tx;
|
| 261 |
+
captured = true;
|
| 262 |
+
tx.addEventListener('abort', () => { nativeAbort = true; opensAtAbort = opens; });
|
| 263 |
+
const store = tx.objectStore('session');
|
| 264 |
+
if (failure === 'timeout') {
|
| 265 |
+
// Keep a native transaction active until the adapter's real deadline aborts it.
|
| 266 |
+
const keepAlive = () => { store.get('keep-alive').onsuccess = keepAlive; };
|
| 267 |
+
keepAlive();
|
| 268 |
+
}
|
| 269 |
+
return new Proxy(tx, {
|
| 270 |
+
get(target, key) {
|
| 271 |
+
if (key === 'objectStore') return name => {
|
| 272 |
+
const current = target.objectStore(name);
|
| 273 |
+
if (failure === 'request-error') current.put = current.add.bind(current);
|
| 274 |
+
return current;
|
| 275 |
+
};
|
| 276 |
+
const value = target[key];
|
| 277 |
+
return typeof value === 'function' ? value.bind(target) : value;
|
| 278 |
+
},
|
| 279 |
+
set(target, key, value) {
|
| 280 |
+
target[key] = key === 'onabort' ? event => { release = () => value(event); } : value;
|
| 281 |
+
return true;
|
| 282 |
+
}
|
| 283 |
+
});
|
| 284 |
+
};
|
| 285 |
+
try {
|
| 286 |
+
const first = session.persistSearchSession();
|
| 287 |
+
await until(() => captured);
|
| 288 |
+
history.replaceState(null, '', '?q=' + failure);
|
| 289 |
+
const next = session.persistSearchSession();
|
| 290 |
+
// Callers must settle while the adapter's native terminal
|
| 291 |
+
// handler is still held. Releasing it first hides deadlocks.
|
| 292 |
+
let deadline;
|
| 293 |
+
const callersSettledBeforeRelease = await Promise.race([
|
| 294 |
+
Promise.all([first, next]).then(() => true),
|
| 295 |
+
new Promise(resolve => { deadline = setTimeout(() => resolve(false), 3000); })
|
| 296 |
+
]).finally(() => clearTimeout(deadline));
|
| 297 |
+
if (!callersSettledBeforeRelease) {
|
| 298 |
+
throw new Error('save callers did not settle within 3s while abort delivery was held');
|
| 299 |
+
}
|
| 300 |
+
await until(() => !!release);
|
| 301 |
+
const opensBeforeRelease = opens;
|
| 302 |
+
if (opensBeforeRelease !== 1) {
|
| 303 |
+
throw new Error('write queue reopened before held abort delivery');
|
| 304 |
+
}
|
| 305 |
+
release();
|
| 306 |
+
await until(() => opens === 2);
|
| 307 |
+
const saved = await readSaved();
|
| 308 |
+
return {nativeAbort, opensAtAbort, opensBeforeRelease, callersSettledBeforeRelease,
|
| 309 |
+
saved: new URL(saved.url).search};
|
| 310 |
+
} finally {
|
| 311 |
+
indexedDB.open = open;
|
| 312 |
+
IDBDatabase.prototype.transaction = transaction;
|
| 313 |
+
}
|
| 314 |
+
}''', failure)
|
| 315 |
+
self.assertEqual(result, dict(nativeAbort=True, opensAtAbort=1,
|
| 316 |
+
opensBeforeRelease=1, callersSettledBeforeRelease=True,
|
| 317 |
+
saved='?q=' + failure))
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__ == '__main__':
|
| 321 |
+
unittest.main()
|
tests/search/reader-navigation/test_reader_navigation_baseline.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
// Synthetic contracts for the existing search-host navigation module. These
|
| 2 |
-
// cover URL and
|
|
|
|
| 3 |
import assert from 'node:assert/strict';
|
| 4 |
import fs from 'node:fs';
|
| 5 |
import path from 'node:path';
|
|
@@ -11,7 +12,7 @@ const source = fs.readFileSync(filename, 'utf8');
|
|
| 11 |
const origin = 'https://search.example';
|
| 12 |
const readerPath = '/search/static/reader.html';
|
| 13 |
|
| 14 |
-
function fixture() {
|
| 15 |
const data = new Map();
|
| 16 |
const calls = [];
|
| 17 |
const storage = {
|
|
@@ -19,8 +20,7 @@ function fixture() {
|
|
| 19 |
setItem(key, value) { data.set(key, String(value)); },
|
| 20 |
removeItem(key) { data.delete(key); }
|
| 21 |
};
|
| 22 |
-
const root =
|
| 23 |
-
const document = {readyState: 'loading', addEventListener() {}};
|
| 24 |
const crypto = {randomUUID: () => 'fixed-token'};
|
| 25 |
const history = {
|
| 26 |
pushState(...args) { calls.push(['push', ...args]); },
|
|
@@ -28,15 +28,181 @@ function fixture() {
|
|
| 28 |
};
|
| 29 |
// Supply location and storage through the global as in browsers. Unrelated
|
| 30 |
// DOM and asynchronous Reader services remain intentionally unstubbed.
|
| 31 |
-
const context = vm.createContext({self: root, document, sessionStorage: storage,
|
| 32 |
localStorage: storage, location: new URL(origin + '/search/#/'), URL, URLSearchParams,
|
| 33 |
-
crypto, history, console});
|
| 34 |
vm.runInContext(source, context, {filename});
|
| 35 |
-
return {nav: root.VoiceOfMLReaderNavigation.createNavigation(
|
| 36 |
}
|
| 37 |
|
| 38 |
const json = value => JSON.parse(JSON.stringify(value));
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
test('parse accepts only the same-origin reader pathname', () => {
|
| 41 |
const {nav} = fixture();
|
| 42 |
assert.equal(nav.parse(readerPath + '?title=a%20b#part').href,
|
|
|
|
| 1 |
// Synthetic contracts for the existing search-host navigation module. These
|
| 2 |
+
// cover URL/session rules and DOM ownership with a synthetic shell. Real browser
|
| 3 |
+
// traversal, layout, speech and native navigation remain browser-test contracts.
|
| 4 |
import assert from 'node:assert/strict';
|
| 5 |
import fs from 'node:fs';
|
| 6 |
import path from 'node:path';
|
|
|
|
| 12 |
const origin = 'https://search.example';
|
| 13 |
const readerPath = '/search/static/reader.html';
|
| 14 |
|
| 15 |
+
function fixture(readerDestination = readerPath, document = {readyState: 'loading', addEventListener() {}}) {
|
| 16 |
const data = new Map();
|
| 17 |
const calls = [];
|
| 18 |
const storage = {
|
|
|
|
| 20 |
setItem(key, value) { data.set(key, String(value)); },
|
| 21 |
removeItem(key) { data.delete(key); }
|
| 22 |
};
|
| 23 |
+
const root = new EventTarget();
|
|
|
|
| 24 |
const crypto = {randomUUID: () => 'fixed-token'};
|
| 25 |
const history = {
|
| 26 |
pushState(...args) { calls.push(['push', ...args]); },
|
|
|
|
| 28 |
};
|
| 29 |
// Supply location and storage through the global as in browsers. Unrelated
|
| 30 |
// DOM and asynchronous Reader services remain intentionally unstubbed.
|
| 31 |
+
const context = vm.createContext({self: root, window: root, document, sessionStorage: storage,
|
| 32 |
localStorage: storage, location: new URL(origin + '/search/#/'), URL, URLSearchParams,
|
| 33 |
+
crypto, history, console, HTMLElement: ShellElement, Event});
|
| 34 |
vm.runInContext(source, context, {filename});
|
| 35 |
+
return {nav: root.VoiceOfMLReaderNavigation.createNavigation(readerDestination), data, storage, crypto, calls, context};
|
| 36 |
}
|
| 37 |
|
| 38 |
const json = value => JSON.parse(JSON.stringify(value));
|
| 39 |
|
| 40 |
+
// Deliberately small DOM double: events run synchronously so dispose reentry is
|
| 41 |
+
// observable. It does not simulate layout, iframe loading or browser history.
|
| 42 |
+
class ShellElement extends EventTarget {
|
| 43 |
+
constructor(document, tagName) {
|
| 44 |
+
super();
|
| 45 |
+
this.document = document;
|
| 46 |
+
this.tagName = tagName;
|
| 47 |
+
this.children = [];
|
| 48 |
+
this.attributes = new Map();
|
| 49 |
+
this.styles = new Map();
|
| 50 |
+
this.style = {
|
| 51 |
+
setProperty: (key, value) => this.styles.set(key, value),
|
| 52 |
+
removeProperty: key => this.styles.delete(key)
|
| 53 |
+
};
|
| 54 |
+
const classes = new Set();
|
| 55 |
+
this.classList = {
|
| 56 |
+
add: value => classes.add(value), remove: value => classes.delete(value),
|
| 57 |
+
contains: value => classes.has(value)
|
| 58 |
+
};
|
| 59 |
+
if (tagName === 'iframe') {
|
| 60 |
+
this.contentWindow = new EventTarget();
|
| 61 |
+
this.contentWindow.postMessage = () => {};
|
| 62 |
+
this.contentDocument = {title: 'VoiceOfML Reader', URL: 'about:blank'};
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
append(...children) {
|
| 66 |
+
for (const child of children) { child.parent = this; this.children.push(child); }
|
| 67 |
+
}
|
| 68 |
+
replaceChildren(...children) {
|
| 69 |
+
for (const child of [...this.children]) child.remove();
|
| 70 |
+
this.append(...children);
|
| 71 |
+
}
|
| 72 |
+
remove() {
|
| 73 |
+
if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
|
| 74 |
+
this.parent = null;
|
| 75 |
+
}
|
| 76 |
+
focus() { this.document.activeElement = this; }
|
| 77 |
+
setAttribute(key, value) { this.attributes.set(key, value); }
|
| 78 |
+
getAttribute(key) { return this.attributes.get(key) ?? null; }
|
| 79 |
+
hasAttribute(key) { return this.attributes.has(key); }
|
| 80 |
+
removeAttribute(key) { this.attributes.delete(key); }
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
function shellFixture(destination = readerPath) {
|
| 84 |
+
const document = {readyState: 'loading', title: 'Search', addEventListener() {}};
|
| 85 |
+
document.createElement = tag => new ShellElement(document, tag);
|
| 86 |
+
document.body = document.createElement('body');
|
| 87 |
+
const input = document.createElement('input');
|
| 88 |
+
document.body.append(input);
|
| 89 |
+
input.focus();
|
| 90 |
+
const state = fixture(destination, document);
|
| 91 |
+
return {...state, document, input,
|
| 92 |
+
shell: () => document.body.children.find(child => child.className === 'reader-overlay-opening')};
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
test('replacement revision preserves a Reader opened synchronously during disposal', () => {
|
| 96 |
+
const {nav, document, input} = shellFixture();
|
| 97 |
+
const first = nav.mount(new URL(origin + readerPath + '?id=first&nav=token&return=%2Fsearch%2F'));
|
| 98 |
+
assert.equal(nav.returnFocus, input);
|
| 99 |
+
assert.equal(nav.backgroundReader, null);
|
| 100 |
+
let newest;
|
| 101 |
+
first.contentWindow.addEventListener('voice-reader-dispose', () => {
|
| 102 |
+
newest = nav.mount(new URL(origin + readerPath + '?id=newest'));
|
| 103 |
+
});
|
| 104 |
+
const result = nav.replace(readerPath + '?id=stale', {top: 50});
|
| 105 |
+
assert.equal(result, newest, 'outer replacement must yield to the reentrant mount');
|
| 106 |
+
assert.equal(first.parent, null);
|
| 107 |
+
assert.equal(first.src, 'about:blank');
|
| 108 |
+
assert.equal(document.body.children.filter(child => child.tagName === 'iframe').length, 1);
|
| 109 |
+
assert.equal(nav.accepts({origin, source: newest.contentWindow}), true);
|
| 110 |
+
assert.equal(nav.accepts({origin: 'https://other.example', source: newest.contentWindow}), false);
|
| 111 |
+
assert.equal(nav.accepts({origin, source: {frameElement: newest}}), true);
|
| 112 |
+
assert.equal(nav.accepts({origin, source: null}), false);
|
| 113 |
+
assert.equal(nav.accepts({origin, source: {get frameElement() { throw new Error('cross-origin'); }}}), false);
|
| 114 |
+
assert.equal(nav.accepts({origin, source: first.contentWindow}), false);
|
| 115 |
+
nav.unmount(false);
|
| 116 |
+
assert.equal(nav.returnFocus, null);
|
| 117 |
+
assert.equal(nav.unmount(), null);
|
| 118 |
+
});
|
| 119 |
+
|
| 120 |
+
test('ordinary replacement carries handoff and focus while releasing background ownership', () => {
|
| 121 |
+
const {nav, document, input, data} = shellFixture();
|
| 122 |
+
const hidden = document.createElement('aside');
|
| 123 |
+
hidden.setAttribute('inert', '');
|
| 124 |
+
hidden.setAttribute('aria-hidden', 'false');
|
| 125 |
+
document.body.append(hidden);
|
| 126 |
+
const first = nav.mount(new URL(origin + readerPath + '?id=first&nav=token&return=%2Fsearch%2F'));
|
| 127 |
+
const next = nav.replace(readerPath + '?id=next', {top: 50});
|
| 128 |
+
assert.notEqual(next, first);
|
| 129 |
+
assert.equal(new URL(next.src).searchParams.get('nav'), 'token');
|
| 130 |
+
assert.equal(new URL(next.src).searchParams.get('return'), '/search/');
|
| 131 |
+
assert.equal(JSON.parse(data.get('reader-navigation-current')).readerUrl, next.src);
|
| 132 |
+
assert.equal(nav.returnFocus, input);
|
| 133 |
+
assert.equal(nav.unmount(false), input);
|
| 134 |
+
assert.equal(input.hasAttribute('inert'), false);
|
| 135 |
+
assert.equal(input.hasAttribute('aria-hidden'), false);
|
| 136 |
+
assert.equal(hidden.hasAttribute('inert'), true);
|
| 137 |
+
assert.equal(hidden.getAttribute('aria-hidden'), 'false');
|
| 138 |
+
});
|
| 139 |
+
|
| 140 |
+
test('close recovery validates both search routes without changing history or private handoff', () => {
|
| 141 |
+
for (const destination of [readerPath, '/static/reader.html']) {
|
| 142 |
+
const {nav, document, input, shell, data, calls} = shellFixture(destination);
|
| 143 |
+
const search = destination === readerPath ? '/search/' : '/';
|
| 144 |
+
nav.showCloseRecovery(search);
|
| 145 |
+
assert.equal(shell(), undefined, 'no recovery without an active Reader');
|
| 146 |
+
const url = nav.prepare(destination + '?id=book&title=Book', origin + search);
|
| 147 |
+
nav.mount(url);
|
| 148 |
+
nav.remember(url, {top: 50});
|
| 149 |
+
const saved = data.get('reader-navigation-current');
|
| 150 |
+
nav.showCloseRecovery(search);
|
| 151 |
+
assert.equal(shell().children.some(child => child.tagName === 'a'), false, 'no recovery before close');
|
| 152 |
+
nav.dismiss();
|
| 153 |
+
assert.equal(document.title, 'Search');
|
| 154 |
+
const valid = destination === readerPath ? '/search/#/Repo?q=book' : '/Repo?q=book';
|
| 155 |
+
for (const [raw, expected] of [
|
| 156 |
+
[valid, valid], ['https://other.example/', search], ['javascript:alert(1)', search],
|
| 157 |
+
['/static/reader.html', search], ['/elsewhere/page', search], ['http://[', search],
|
| 158 |
+
['https://user:password@search.example' + search, search]
|
| 159 |
+
]) {
|
| 160 |
+
nav.showCloseRecovery(raw);
|
| 161 |
+
const link = shell().children.find(child => child.tagName === 'a');
|
| 162 |
+
assert.equal(link.href, origin + expected);
|
| 163 |
+
assert.equal(shell().parent, document.body);
|
| 164 |
+
assert.equal(shell().hasAttribute('inert'), false);
|
| 165 |
+
assert.equal(shell().styles.has('opacity'), false);
|
| 166 |
+
assert.equal(shell().styles.has('pointer-events'), false);
|
| 167 |
+
assert.equal(document.activeElement, link);
|
| 168 |
+
assert.equal(input.hasAttribute('inert'), true);
|
| 169 |
+
}
|
| 170 |
+
assert.equal(calls.length, 1, 'recovery must not push or replace history');
|
| 171 |
+
assert.equal(data.get('reader-navigation-current'), saved);
|
| 172 |
+
assert.equal(data.has('reader-navigation-restore'), false, 'handoff waits for explicit activation');
|
| 173 |
+
assert.equal(nav.returnFocus, input);
|
| 174 |
+
nav.unmount(false);
|
| 175 |
+
assert.equal(shell(), undefined);
|
| 176 |
+
}
|
| 177 |
+
});
|
| 178 |
+
|
| 179 |
+
test('recovery survives late shell load and records handoff only on native link activation', () => {
|
| 180 |
+
const {nav, document, shell, data, calls, storage} = shellFixture();
|
| 181 |
+
const target = origin + '/search/#/?q=book';
|
| 182 |
+
const url = nav.prepare(readerPath + '?id=book', target);
|
| 183 |
+
const frame = nav.mount(url);
|
| 184 |
+
frame.contentDocument.URL = frame.src;
|
| 185 |
+
frame.dispatchEvent(new Event('load'));
|
| 186 |
+
assert.equal(shell(), undefined);
|
| 187 |
+
nav.dismiss();
|
| 188 |
+
nav.showCloseRecovery(target);
|
| 189 |
+
const recovery = shell();
|
| 190 |
+
const link = recovery.children.find(child => child.tagName === 'a');
|
| 191 |
+
frame.dispatchEvent(new Event('load'));
|
| 192 |
+
assert.equal(shell(), recovery);
|
| 193 |
+
assert.equal(document.activeElement, link);
|
| 194 |
+
const click = new Event('click', {cancelable: true});
|
| 195 |
+
link.dispatchEvent(click);
|
| 196 |
+
assert.equal(click.defaultPrevented, false, 'native href remains the navigation action');
|
| 197 |
+
assert.deepEqual(JSON.parse(data.get('reader-navigation-restore')), {readerUrl: url.href, returnUrl: target});
|
| 198 |
+
storage.setItem = () => { throw new Error('quota'); };
|
| 199 |
+
assert.doesNotThrow(() => link.dispatchEvent(new Event('click')));
|
| 200 |
+
assert.deepEqual(calls, []);
|
| 201 |
+
assert.equal(nav.unmount(false).tagName, 'input');
|
| 202 |
+
nav.showCloseRecovery(target);
|
| 203 |
+
assert.equal(shell(), undefined);
|
| 204 |
+
});
|
| 205 |
+
|
| 206 |
test('parse accepts only the same-origin reader pathname', () => {
|
| 207 |
const {nav} = fixture();
|
| 208 |
assert.equal(nav.parse(readerPath + '?title=a%20b#part').href,
|
tests/search/reader-navigation/test_search_history_races.mjs
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Focused host contracts. Browser traversal and DOM ownership are covered in
|
| 2 |
+
// test_reader_navigation_host.py; these isolate synchronous abort/input edges.
|
| 3 |
+
import assert from 'node:assert/strict';
|
| 4 |
+
import fs from 'node:fs';
|
| 5 |
+
import vm from 'node:vm';
|
| 6 |
+
import test from 'node:test';
|
| 7 |
+
|
| 8 |
+
const source = fs.readFileSync('static/app.js', 'utf8');
|
| 9 |
+
function fixture(names, values = {}) {
|
| 10 |
+
const context = vm.createContext({AbortController, ...values});
|
| 11 |
+
for (const name of names) {
|
| 12 |
+
const match = source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));
|
| 13 |
+
assert.ok(match, name);
|
| 14 |
+
vm.runInContext(match[0], context);
|
| 15 |
+
}
|
| 16 |
+
return context;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
test('reader handoff waits for usable target rows but not preview validation of adjacent pages', () => {
|
| 20 |
+
const saved = {viewKey:'B',index:1};
|
| 21 |
+
const c = fixture(['readerSearchHandoffReady'], {STATE:{isLoading:true,_loadedPage:0,total:3,results:[]},positionRestore:null});
|
| 22 |
+
assert.equal(c.readerSearchHandoffReady(saved), false);
|
| 23 |
+
c.STATE = {isLoading:false,_loadedPage:1,total:3,results:[{},{}]};
|
| 24 |
+
c.positionRestore = {key:'B',preview:false};
|
| 25 |
+
assert.equal(c.readerSearchHandoffReady(saved), false);
|
| 26 |
+
c.positionRestore.preview = true;
|
| 27 |
+
assert.equal(c.readerSearchHandoffReady(saved), true);
|
| 28 |
+
assert.equal(c.positionRestore.preview, true, 'validation remains owned and active');
|
| 29 |
+
c.positionRestore.key = 'A';
|
| 30 |
+
assert.equal(c.readerSearchHandoffReady(saved), false);
|
| 31 |
+
c.positionRestore.key = 'B';
|
| 32 |
+
delete c.STATE.results[1];
|
| 33 |
+
assert.equal(c.readerSearchHandoffReady(saved), false, 'sparse geometry alone is not a usable target');
|
| 34 |
+
c.positionRestore = null;
|
| 35 |
+
c.STATE.results[1] = {};
|
| 36 |
+
assert.equal(c.readerSearchHandoffReady(saved), true);
|
| 37 |
+
});
|
| 38 |
+
|
| 39 |
+
test('sort normalization uses the real backend whitelist, including empty and unknown URL values', () => {
|
| 40 |
+
const c = fixture(['normalizeSearchSort']);
|
| 41 |
+
for (const input of ['', null, undefined, 'custom', 'NAME', ' relevance '])
|
| 42 |
+
assert.equal(c.normalizeSearchSort(input), 'relevance');
|
| 43 |
+
for (const input of ['relevance', 'name', 'size']) assert.equal(c.normalizeSearchSort(input), input);
|
| 44 |
+
});
|
| 45 |
+
|
| 46 |
+
test('abort synchronously starting another search retains its controller and retires the outer owner', () => {
|
| 47 |
+
const old = new AbortController();
|
| 48 |
+
const c = fixture(['cancelActiveSearch'], {searchId: 4, searchRequestId: 8,
|
| 49 |
+
searchAbortController: old, cancelSearchPrefetch() {}});
|
| 50 |
+
let newer;
|
| 51 |
+
old.signal.addEventListener('abort', () => {
|
| 52 |
+
assert.equal(c.searchId, 5);
|
| 53 |
+
assert.equal(c.searchRequestId, 9);
|
| 54 |
+
assert.notEqual(c.searchAbortController, old);
|
| 55 |
+
assert.equal(c.cancelActiveSearch(), true);
|
| 56 |
+
newer = c.searchAbortController;
|
| 57 |
+
});
|
| 58 |
+
assert.equal(c.cancelActiveSearch(), false);
|
| 59 |
+
assert.equal(c.searchAbortController, newer);
|
| 60 |
+
assert.equal(newer.signal.aborted, false);
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
test('prefetch abort reentry cannot clear the replacement group', () => {
|
| 64 |
+
const old = new AbortController(), newer = new AbortController();
|
| 65 |
+
const c = fixture(['cancelSearchPrefetch'], {searchPrefetchAbortController: old,
|
| 66 |
+
cancelPendingSearchCacheWrites() {}});
|
| 67 |
+
old.signal.addEventListener('abort', () => { c.searchPrefetchAbortController = newer; });
|
| 68 |
+
c.cancelSearchPrefetch();
|
| 69 |
+
assert.equal(c.searchPrefetchAbortController, newer);
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
test('online first page prefetch starts pages two and three and path-only reuses the group', () => {
|
| 73 |
+
const requests = [];
|
| 74 |
+
const c = fixture(['prefetchSearchPages'], {searchPrefetchAbortController:null,
|
| 75 |
+
STATE:{_loadedPage:1,total:301,pageSize:100,_pageCache:{},results:[{}]},
|
| 76 |
+
document:{hidden:false},navigator:{onLine:true},searchPageMetadata:new WeakMap(),
|
| 77 |
+
getSearchViewKey:() => 'same-view',stableSearchStringify:JSON.stringify,
|
| 78 |
+
getCachedSearchResponse:() => null,
|
| 79 |
+
fetchSearchPage(key, base, body, signal) { requests.push({page:body.page,signal}); return new Promise(() => {}); },
|
| 80 |
+
APPEND_REQUEST_TIMEOUT:10000});
|
| 81 |
+
c.prefetchSearchPages('/api/search',{q:'paging',page:1,page_size:100});
|
| 82 |
+
assert.deepEqual(requests.map(r => r.page), [2,3]);
|
| 83 |
+
const group = c.searchPrefetchAbortController;
|
| 84 |
+
c.STATE.browserPath = 'path-only';
|
| 85 |
+
c.prefetchSearchPages('/api/search',{q:'paging',page:1,page_size:100});
|
| 86 |
+
assert.equal(c.searchPrefetchAbortController, group);
|
| 87 |
+
assert.equal(requests.length, 2);
|
| 88 |
+
assert.equal(group.signal.aborted, false);
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
test('position abort reentry retains the replacement window and restoration', () => {
|
| 92 |
+
const old = new AbortController(), newer = {controller: new AbortController()};
|
| 93 |
+
const c = fixture(['cancelPositionRestore'], {positionEntryId: 0,
|
| 94 |
+
resultWindow: {controller: old}, positionRestore: {controller: new AbortController()},
|
| 95 |
+
STATE: {isLoading: true}, cancelSnapshotClone() {}, updateResultWindowStatus() {}, showPositionRestoreStatus() {}});
|
| 96 |
+
old.signal.addEventListener('abort', () => { c.resultWindow = newer; c.positionRestore = newer; });
|
| 97 |
+
c.cancelPositionRestore();
|
| 98 |
+
assert.equal(c.resultWindow, newer);
|
| 99 |
+
assert.equal(c.positionRestore, newer);
|
| 100 |
+
assert.equal(newer.controller.signal.aborted, false);
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
test('filter change incorporates the pending completed query before cancelling debounce', () => {
|
| 104 |
+
const c = fixture(['prepareFilterChange'], {searchTimer: 1, searchComposing: false,
|
| 105 |
+
DOM: {searchInput: {value: ' current draft '}}, STATE: {query: 'old', page: 3, results: [1]},
|
| 106 |
+
applyPendingSizeFilters() {}, cancelPendingSearchControls() { c.searchTimer = null; },
|
| 107 |
+
saveSearchViewSnapshot() { assert.equal(c.STATE.query, 'old'); }});
|
| 108 |
+
c.prepareFilterChange(true);
|
| 109 |
+
assert.equal(c.STATE.query, 'current draft');
|
| 110 |
+
assert.equal(c.STATE.page, 1);
|
| 111 |
+
assert.equal(c.STATE.results.length, 0);
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
test('filter change preserves composing and overlong drafts without submitting them', () => {
|
| 115 |
+
for (const [composing, value] of [[true, 'composition'], [false, 'x'.repeat(257)]]) {
|
| 116 |
+
const c = fixture(['prepareFilterChange'], {searchTimer: 1, searchComposing: composing,
|
| 117 |
+
DOM: {searchInput: {value}}, STATE: {query: 'old'}, applyPendingSizeFilters() {},
|
| 118 |
+
cancelPendingSearchControls() {}, saveSearchViewSnapshot() {}});
|
| 119 |
+
c.prepareFilterChange(false);
|
| 120 |
+
assert.equal(c.STATE.query, 'old');
|
| 121 |
+
assert.equal(c.DOM.searchInput.value, value);
|
| 122 |
+
}
|
| 123 |
+
});
|
| 124 |
+
|
| 125 |
+
test('composition completion checks both visit generation and search view ownership', () => {
|
| 126 |
+
for (const change of ['generation', 'view', 'neither']) {
|
| 127 |
+
const handlers = new Map();
|
| 128 |
+
let scheduled = 0, key = 'A';
|
| 129 |
+
const c = fixture(['setupSearchInput'], {
|
| 130 |
+
DOM: {searchInput: {addEventListener(type, handler) { handlers.set(type, handler); }}},
|
| 131 |
+
searchInputReady: true, initialSearchDraft: false, searchTimer: null,
|
| 132 |
+
searchComposing: false, searchInputGeneration: 0, searchCompositionGeneration: 0,
|
| 133 |
+
searchCompositionViewKey: null, routeInitialized: true,
|
| 134 |
+
getSearchViewKey: () => key, clearTimeout() {}, syncSearchInputState() {},
|
| 135 |
+
window: {addEventListener() {}}, cancelInitialSearchDraft() {}, captureInitialSearchDraft() {},
|
| 136 |
+
debouncedSearch() { scheduled++; }
|
| 137 |
+
});
|
| 138 |
+
c.setupSearchInput();
|
| 139 |
+
handlers.get('compositionstart')();
|
| 140 |
+
if (change === 'generation') c.searchInputGeneration++;
|
| 141 |
+
if (change === 'view') key = 'B';
|
| 142 |
+
handlers.get('compositionend')();
|
| 143 |
+
assert.equal(c.searchComposing, false);
|
| 144 |
+
assert.equal(scheduled, change === 'neither' ? 1 : 0, change);
|
| 145 |
+
const before = scheduled;
|
| 146 |
+
handlers.get('input')({isComposing: false, inputType: 'insertCompositionText'});
|
| 147 |
+
assert.equal(scheduled, before);
|
| 148 |
+
handlers.get('input')({isComposing: false, inputType: 'insertText'});
|
| 149 |
+
assert.equal(scheduled, before + 1, 'a deliberate edit remains usable');
|
| 150 |
+
}
|
| 151 |
+
});
|
| 152 |
+
|
| 153 |
+
test('startup drafts require their original URL, entry and uninterrupted visit', () => {
|
| 154 |
+
for (const change of ['href', 'entry', 'event', 'none']) {
|
| 155 |
+
let key = 'entry-A', submits = 0;
|
| 156 |
+
const c = fixture(['captureInitialSearchDraft', 'cancelInitialSearchDraft',
|
| 157 |
+
'initialSearchDraftIsCurrent', 'finishInitialSearchInput'], {
|
| 158 |
+
location: {href: 'https://example.test/A'}, currentSearchEntryKey: () => key,
|
| 159 |
+
initialSearchDraftOwner: null, initialSearchDraft: false, searchInputReady: false,
|
| 160 |
+
searchInputGeneration: 0, window: {removeEventListener() {}},
|
| 161 |
+
debouncedSearch() { submits++; }
|
| 162 |
+
});
|
| 163 |
+
c.captureInitialSearchDraft();
|
| 164 |
+
if (change === 'href') c.location.href = 'https://example.test/B';
|
| 165 |
+
if (change === 'entry') key = 'entry-B';
|
| 166 |
+
if (change === 'event') c.cancelInitialSearchDraft();
|
| 167 |
+
c.finishInitialSearchInput(c.initialSearchDraftIsCurrent());
|
| 168 |
+
assert.equal(submits, change === 'none' ? 1 : 0, change);
|
| 169 |
+
assert.equal(c.searchInputGeneration, change === 'none' ? 0 : 1, change);
|
| 170 |
+
assert.equal(c.searchInputReady, true);
|
| 171 |
+
assert.equal(c.initialSearchDraftOwner, null);
|
| 172 |
+
}
|
| 173 |
+
});
|
| 174 |
+
|
| 175 |
+
test('a queued debounce cannot submit after its search view changes', () => {
|
| 176 |
+
let callback, submits = 0;
|
| 177 |
+
const c = fixture(['debouncedSearch'], {searchTimer: null, searchComposing: false,
|
| 178 |
+
searchInputReady: true, searchInputGeneration: 0,
|
| 179 |
+
DOM: {searchInput: {value: 'old draft'}}, clearTimeout() {},
|
| 180 |
+
setTimeout(fn) { callback = fn; return 1; }, submitSearchQuery() { submits++; }});
|
| 181 |
+
c.debouncedSearch();
|
| 182 |
+
c.searchInputGeneration++;
|
| 183 |
+
callback();
|
| 184 |
+
assert.equal(submits, 0);
|
| 185 |
+
c.debouncedSearch();
|
| 186 |
+
callback();
|
| 187 |
+
assert.equal(submits, 1);
|
| 188 |
+
});
|
| 189 |
+
|
| 190 |
+
test('a queued debounce cannot submit after composition starts', () => {
|
| 191 |
+
let callback, submits = 0;
|
| 192 |
+
const c = fixture(['debouncedSearch'], {searchTimer: null, searchComposing: false,
|
| 193 |
+
searchInputReady: true, searchInputGeneration: 0,
|
| 194 |
+
DOM: {searchInput: {value: 'intermediate'}}, clearTimeout() {},
|
| 195 |
+
setTimeout(fn) { callback = fn; return 1; }, submitSearchQuery() { submits++; }});
|
| 196 |
+
c.debouncedSearch();
|
| 197 |
+
c.searchComposing = true;
|
| 198 |
+
callback();
|
| 199 |
+
assert.equal(submits, 0);
|
| 200 |
+
assert.equal(c.searchTimer, null);
|
| 201 |
+
});
|
tests/search/session/test_search_session_contract.js
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require('node:assert/strict');
|
| 2 |
+
const fs = require('node:fs');
|
| 3 |
+
const path = require('node:path');
|
| 4 |
+
const test = require('node:test');
|
| 5 |
+
const vm = require('node:vm');
|
| 6 |
+
const {IDBFactory} = require('fake-indexeddb');
|
| 7 |
+
|
| 8 |
+
const filename = path.join(__dirname, '../../../static/search/search-session.js');
|
| 9 |
+
const source = fs.readFileSync(filename, 'utf8');
|
| 10 |
+
const turn = () => new Promise(resolve => setImmediate(resolve));
|
| 11 |
+
async function until(predicate) {
|
| 12 |
+
for (let i = 0; i < 200; i++) {
|
| 13 |
+
if (predicate()) return;
|
| 14 |
+
await turn();
|
| 15 |
+
}
|
| 16 |
+
assert.fail('IndexedDB checkpoint was not reached');
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
function fixture() {
|
| 20 |
+
const factory = new IDBFactory();
|
| 21 |
+
const timers = new Map();
|
| 22 |
+
let nextTimer = 0;
|
| 23 |
+
const h = {opens: 0, closes: 0, writes: [], terminals: [], openHook: null, transactionHook: null, openError: null};
|
| 24 |
+
const location = {href: 'https://example.test/search/?q=first'};
|
| 25 |
+
const history = {
|
| 26 |
+
state: {foreign: {value: 7}}, replacements: [],
|
| 27 |
+
replaceState(state, title, url) {
|
| 28 |
+
this.state = state;
|
| 29 |
+
this.replacements.push(url);
|
| 30 |
+
location.href = url;
|
| 31 |
+
}
|
| 32 |
+
};
|
| 33 |
+
const indexedDB = {
|
| 34 |
+
open(...args) {
|
| 35 |
+
h.opens++;
|
| 36 |
+
if (h.openError) throw h.openError;
|
| 37 |
+
const request = factory.open(...args);
|
| 38 |
+
request.addEventListener('success', () => {
|
| 39 |
+
const db = request.result;
|
| 40 |
+
const close = db.close.bind(db);
|
| 41 |
+
db.close = () => { h.closes++; close(); };
|
| 42 |
+
const transaction = db.transaction.bind(db);
|
| 43 |
+
db.transaction = (...txArgs) => {
|
| 44 |
+
const tx = transaction(...txArgs);
|
| 45 |
+
tx.addEventListener('complete', () => h.terminals.push('complete'));
|
| 46 |
+
tx.addEventListener('abort', () => h.terminals.push('abort'));
|
| 47 |
+
if (tx.mode === 'readwrite') {
|
| 48 |
+
const objectStore = tx.objectStore.bind(tx);
|
| 49 |
+
const instrumented = new WeakSet();
|
| 50 |
+
tx.objectStore = name => {
|
| 51 |
+
const store = objectStore(name);
|
| 52 |
+
if (!instrumented.has(store)) {
|
| 53 |
+
instrumented.add(store);
|
| 54 |
+
const put = store.put.bind(store);
|
| 55 |
+
store.put = (value, key) => { h.writes.push(value.url); return put(value, key); };
|
| 56 |
+
}
|
| 57 |
+
return store;
|
| 58 |
+
};
|
| 59 |
+
}
|
| 60 |
+
return h.transactionHook ? h.transactionHook(tx) : tx;
|
| 61 |
+
};
|
| 62 |
+
});
|
| 63 |
+
return h.openHook ? h.openHook(request) : request;
|
| 64 |
+
}
|
| 65 |
+
};
|
| 66 |
+
const context = vm.createContext({
|
| 67 |
+
indexedDB, window: Object.assign(new EventTarget(), {indexedDB}), location, history, URL,
|
| 68 |
+
setTimeout(callback) { const id = ++nextTimer; timers.set(id, callback); return id; },
|
| 69 |
+
clearTimeout(id) { timers.delete(id); }
|
| 70 |
+
});
|
| 71 |
+
vm.runInContext(source, context, {filename});
|
| 72 |
+
h.create = (options = {}) => context.VoiceOfMLSearchSession.createSearchSession({
|
| 73 |
+
canPersist: () => true, canRestore: () => true, ...options
|
| 74 |
+
});
|
| 75 |
+
h.session = h.create();
|
| 76 |
+
h.location = location;
|
| 77 |
+
h.history = history;
|
| 78 |
+
h.timers = timers;
|
| 79 |
+
h.expire = () => {
|
| 80 |
+
for (const [id, callback] of [...timers]) {
|
| 81 |
+
if (timers.delete(id)) callback();
|
| 82 |
+
}
|
| 83 |
+
};
|
| 84 |
+
h.saved = async () => {
|
| 85 |
+
const request = factory.open('voiceofml-search-state', 1);
|
| 86 |
+
const db = await new Promise((resolve, reject) => {
|
| 87 |
+
request.onsuccess = () => resolve(request.result);
|
| 88 |
+
request.onerror = () => reject(request.error);
|
| 89 |
+
});
|
| 90 |
+
try {
|
| 91 |
+
const tx = db.transaction('session', 'readonly');
|
| 92 |
+
const get = tx.objectStore('session').get('last-search');
|
| 93 |
+
await new Promise((resolve, reject) => {
|
| 94 |
+
tx.oncomplete = resolve;
|
| 95 |
+
tx.onabort = () => reject(tx.error);
|
| 96 |
+
});
|
| 97 |
+
return get.result;
|
| 98 |
+
} finally { db.close(); }
|
| 99 |
+
};
|
| 100 |
+
return h;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
// Delay delivery, not the fake IndexedDB backend: inspect final committed data too.
|
| 104 |
+
function holdOpen(h) {
|
| 105 |
+
let release;
|
| 106 |
+
h.openHook = request => new Proxy(request, {
|
| 107 |
+
set(target, key, value) {
|
| 108 |
+
if (key === 'onsuccess') target.onsuccess = event => { release = () => value(event); };
|
| 109 |
+
else target[key] = value;
|
| 110 |
+
return true;
|
| 111 |
+
},
|
| 112 |
+
get(target, key) { return target[key]; }
|
| 113 |
+
});
|
| 114 |
+
return {ready: () => !!release, release: () => { h.openHook = null; release(); }};
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
function holdTerminal(h, {abortThrows = false, failPut = false, requestError = false, preventError = false} = {}) {
|
| 118 |
+
let release;
|
| 119 |
+
let captured = false;
|
| 120 |
+
let aborts = 0;
|
| 121 |
+
h.transactionHook = tx => {
|
| 122 |
+
if (captured || tx.mode !== 'readwrite') return tx;
|
| 123 |
+
captured = true;
|
| 124 |
+
let requestErrorEvent;
|
| 125 |
+
tx.addEventListener('error', event => {
|
| 126 |
+
requestErrorEvent = event;
|
| 127 |
+
if (preventError) event.preventDefault();
|
| 128 |
+
});
|
| 129 |
+
return new Proxy(tx, {
|
| 130 |
+
set(target, key, value) {
|
| 131 |
+
if (key === 'oncomplete' || key === 'onabort') {
|
| 132 |
+
target[key] = event => { release = () => value(event); };
|
| 133 |
+
} else target[key] = value;
|
| 134 |
+
return true;
|
| 135 |
+
},
|
| 136 |
+
get(target, key) {
|
| 137 |
+
if (key === 'abort') return () => {
|
| 138 |
+
aborts++;
|
| 139 |
+
if (abortThrows) throw new Error('injected abort failure');
|
| 140 |
+
target.abort();
|
| 141 |
+
// fake-indexeddb 6.2.7 repeats the default abort even when an error
|
| 142 |
+
// listener already aborted the transaction, then removes it twice.
|
| 143 |
+
// Suppress only that redundant default after a successful explicit
|
| 144 |
+
// abort; still require the real abort event and committed-data checks.
|
| 145 |
+
requestErrorEvent?.preventDefault();
|
| 146 |
+
};
|
| 147 |
+
if (key === 'objectStore') return name => {
|
| 148 |
+
const store = target.objectStore(name);
|
| 149 |
+
if (failPut) store.put = () => { throw new Error('injected synchronous put failure'); };
|
| 150 |
+
if (requestError) store.put = (value, entry) => store.add(value, entry);
|
| 151 |
+
return store;
|
| 152 |
+
};
|
| 153 |
+
const value = target[key];
|
| 154 |
+
return typeof value === 'function' ? value.bind(target) : value;
|
| 155 |
+
}
|
| 156 |
+
});
|
| 157 |
+
};
|
| 158 |
+
return {ready: () => !!release, release: () => release(), aborts: () => aborts};
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
const options = {timeout: 5000};
|
| 162 |
+
|
| 163 |
+
test('save captures its URL before the database opens', options, async () => {
|
| 164 |
+
const h = fixture(), held = holdOpen(h);
|
| 165 |
+
const before = h.location.href;
|
| 166 |
+
const pending = h.session.persistSearchSession();
|
| 167 |
+
await until(held.ready);
|
| 168 |
+
h.location.href = 'https://example.test/reader/?book=next';
|
| 169 |
+
held.release();
|
| 170 |
+
await pending;
|
| 171 |
+
assert.equal((await h.saved()).url, before);
|
| 172 |
+
assert.deepEqual(h.writes, [before]);
|
| 173 |
+
});
|
| 174 |
+
|
| 175 |
+
test('delayed open serializes adapters and coalesces pending saves to the newest URL', options, async () => {
|
| 176 |
+
const h = fixture(), held = holdOpen(h);
|
| 177 |
+
const first = h.session.persistSearchSession();
|
| 178 |
+
await until(held.ready);
|
| 179 |
+
const other = h.create();
|
| 180 |
+
h.location.href = 'https://example.test/search/?q=second';
|
| 181 |
+
const pending = other.persistSearchSession();
|
| 182 |
+
for (let i = 0; i < 2000; i++) {
|
| 183 |
+
h.location.href = `https://example.test/search/?q=${i}`;
|
| 184 |
+
assert.equal(h.session.persistSearchSession(), pending, 'one shared pending promise');
|
| 185 |
+
}
|
| 186 |
+
assert.equal(h.opens, 1);
|
| 187 |
+
const latest = h.location.href;
|
| 188 |
+
held.release();
|
| 189 |
+
await Promise.all([first, pending]);
|
| 190 |
+
assert.equal((await h.saved()).url, latest);
|
| 191 |
+
assert.deepEqual(h.writes, ['https://example.test/search/?q=first', latest]);
|
| 192 |
+
});
|
| 193 |
+
|
| 194 |
+
test('timed out opens stay bounded, close late connections and resume only after native success', options, async () => {
|
| 195 |
+
const h = fixture(), held = holdOpen(h);
|
| 196 |
+
const first = h.session.persistSearchSession();
|
| 197 |
+
await until(held.ready);
|
| 198 |
+
h.expire();
|
| 199 |
+
await first;
|
| 200 |
+
h.location.href = 'https://example.test/search/?q=latest';
|
| 201 |
+
const pending = h.session.persistSearchSession();
|
| 202 |
+
h.expire();
|
| 203 |
+
await pending;
|
| 204 |
+
for (let i = 0; i < 2000; i++) assert.equal(h.session.persistSearchSession(), pending);
|
| 205 |
+
assert.equal(h.opens, 1);
|
| 206 |
+
assert.equal(h.timers.size, 0);
|
| 207 |
+
assert.deepEqual(h.writes, []);
|
| 208 |
+
held.release();
|
| 209 |
+
await until(() => h.writes.length === 1 && h.terminals.length === 1);
|
| 210 |
+
assert.equal((await h.saved()).url, h.location.href);
|
| 211 |
+
assert.equal(h.closes, 2, 'late abandoned connection and successful writer both close');
|
| 212 |
+
});
|
| 213 |
+
|
| 214 |
+
for (const fault of [
|
| 215 |
+
{name: 'timeout with throwing abort', abortThrows: true},
|
| 216 |
+
{name: 'synchronous put failure', failPut: true},
|
| 217 |
+
{name: 'request error', requestError: true},
|
| 218 |
+
{name: 'cancelled request error with throwing abort', requestError: true, abortThrows: true, preventError: true}
|
| 219 |
+
]) {
|
| 220 |
+
test(`${fault.name} cannot release a writer before native complete or abort delivery`, options, async () => {
|
| 221 |
+
const h = fixture();
|
| 222 |
+
if (fault.requestError) await h.session.persistSearchSession();
|
| 223 |
+
const opens = h.opens;
|
| 224 |
+
const held = holdTerminal(h, fault);
|
| 225 |
+
const first = h.session.persistSearchSession();
|
| 226 |
+
await until(held.ready);
|
| 227 |
+
h.location.href = 'https://example.test/search/?q=newer';
|
| 228 |
+
const pending = h.session.persistSearchSession();
|
| 229 |
+
h.expire();
|
| 230 |
+
await Promise.all([first, pending]);
|
| 231 |
+
assert.equal(held.aborts(), 1);
|
| 232 |
+
for (let i = 0; i < 2000; i++) assert.equal(h.session.persistSearchSession(), pending);
|
| 233 |
+
assert.equal(h.opens, opens + 1, 'no replacement open before terminal delivery');
|
| 234 |
+
assert.equal(h.timers.size, 0, 'stalled worker retains no growing timeout list');
|
| 235 |
+
const terminalCount = h.terminals.length;
|
| 236 |
+
held.release();
|
| 237 |
+
await until(() => h.terminals.length > terminalCount);
|
| 238 |
+
assert.equal((await h.saved()).url, h.location.href);
|
| 239 |
+
});
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
test('timeout abort returning is not native abort completion', options, async t => {
|
| 243 |
+
const h = fixture();
|
| 244 |
+
let release;
|
| 245 |
+
let aborts = 0;
|
| 246 |
+
let heldTransaction;
|
| 247 |
+
t.after(() => {
|
| 248 |
+
// A failed checkpoint must not leave the emulator's keep-alive loop running.
|
| 249 |
+
try { heldTransaction?.abort(); } catch (_) {}
|
| 250 |
+
});
|
| 251 |
+
h.transactionHook = tx => {
|
| 252 |
+
h.transactionHook = null;
|
| 253 |
+
heldTransaction = tx;
|
| 254 |
+
// Hold a real transaction live with successive requests until abort().
|
| 255 |
+
const store = tx.objectStore('session');
|
| 256 |
+
function keepAlive() { store.get('keep-alive').onsuccess = keepAlive; }
|
| 257 |
+
keepAlive();
|
| 258 |
+
return new Proxy(tx, {
|
| 259 |
+
set(target, key, value) {
|
| 260 |
+
target[key] = key === 'onabort' ? event => { release = () => value(event); } : value;
|
| 261 |
+
return true;
|
| 262 |
+
},
|
| 263 |
+
get(target, key) {
|
| 264 |
+
if (key === 'abort') return () => { aborts++; target.abort(); };
|
| 265 |
+
const value = target[key];
|
| 266 |
+
return typeof value === 'function' ? value.bind(target) : value;
|
| 267 |
+
}
|
| 268 |
+
});
|
| 269 |
+
};
|
| 270 |
+
const first = h.session.persistSearchSession();
|
| 271 |
+
await until(() => h.writes.length === 1);
|
| 272 |
+
h.location.href = 'https://example.test/search/?q=after-abort';
|
| 273 |
+
const pending = h.session.persistSearchSession();
|
| 274 |
+
h.expire();
|
| 275 |
+
await Promise.all([first, pending]);
|
| 276 |
+
assert.equal(aborts, 1);
|
| 277 |
+
assert.equal(h.opens, 1);
|
| 278 |
+
await until(() => !!release);
|
| 279 |
+
assert.equal(h.opens, 1);
|
| 280 |
+
release();
|
| 281 |
+
await until(() => h.writes.length === 2 && h.terminals.includes('complete'));
|
| 282 |
+
assert.equal((await h.saved()).url, h.location.href);
|
| 283 |
+
});
|
| 284 |
+
|
| 285 |
+
test('read success followed by abort never restores a provisional URL', options, async () => {
|
| 286 |
+
const h = fixture();
|
| 287 |
+
await h.session.persistSearchSession();
|
| 288 |
+
h.location.href = 'https://example.test/search/';
|
| 289 |
+
h.transactionHook = tx => {
|
| 290 |
+
const objectStore = tx.objectStore.bind(tx);
|
| 291 |
+
tx.objectStore = name => {
|
| 292 |
+
const store = objectStore(name), get = store.get.bind(store);
|
| 293 |
+
store.get = key => {
|
| 294 |
+
const request = get(key);
|
| 295 |
+
request.addEventListener('success', () => tx.abort());
|
| 296 |
+
return request;
|
| 297 |
+
};
|
| 298 |
+
return store;
|
| 299 |
+
};
|
| 300 |
+
return tx;
|
| 301 |
+
};
|
| 302 |
+
assert.equal(await h.session.restoreSearchSession(), false);
|
| 303 |
+
assert.deepEqual(h.history.replacements, []);
|
| 304 |
+
assert.equal(h.location.href, 'https://example.test/search/');
|
| 305 |
+
});
|
| 306 |
+
|
| 307 |
+
test('restore waits for completion, rechecks policy and preserves current foreign history state', options, async () => {
|
| 308 |
+
const h = fixture();
|
| 309 |
+
const saved = h.location.href;
|
| 310 |
+
await h.session.persistSearchSession();
|
| 311 |
+
let release;
|
| 312 |
+
h.transactionHook = tx => new Proxy(tx, {
|
| 313 |
+
set(target, key, value) {
|
| 314 |
+
target[key] = key === 'oncomplete' ? event => { release = () => value(event); } : value;
|
| 315 |
+
return true;
|
| 316 |
+
},
|
| 317 |
+
get(target, key) {
|
| 318 |
+
const value = target[key];
|
| 319 |
+
return typeof value === 'function' ? value.bind(target) : value;
|
| 320 |
+
}
|
| 321 |
+
});
|
| 322 |
+
h.location.href = 'https://example.test/search/';
|
| 323 |
+
const pending = h.session.restoreSearchSession();
|
| 324 |
+
await until(() => !!release);
|
| 325 |
+
assert.deepEqual(h.history.replacements, []);
|
| 326 |
+
const state = {foreign: ['updated', 42]};
|
| 327 |
+
h.history.state = state;
|
| 328 |
+
release();
|
| 329 |
+
assert.equal(await pending, true);
|
| 330 |
+
assert.equal(h.history.state, state);
|
| 331 |
+
assert.equal(h.location.href, saved);
|
| 332 |
+
|
| 333 |
+
release = null;
|
| 334 |
+
let allowed = true;
|
| 335 |
+
const guarded = h.create({canRestore: () => allowed});
|
| 336 |
+
const stale = guarded.restoreSearchSession();
|
| 337 |
+
await until(() => !!release);
|
| 338 |
+
allowed = false;
|
| 339 |
+
release();
|
| 340 |
+
assert.equal(await stale, false);
|
| 341 |
+
assert.equal(h.history.replacements.length, 1);
|
| 342 |
+
});
|
| 343 |
+
|
| 344 |
+
test('a read deadline prevents later completion from publishing', options, async () => {
|
| 345 |
+
const h = fixture();
|
| 346 |
+
await h.session.persistSearchSession();
|
| 347 |
+
let release;
|
| 348 |
+
h.transactionHook = tx => new Proxy(tx, {
|
| 349 |
+
set(target, key, value) {
|
| 350 |
+
target[key] = key === 'oncomplete' ? event => { release = () => value(event); } : value;
|
| 351 |
+
return true;
|
| 352 |
+
},
|
| 353 |
+
get(target, key) {
|
| 354 |
+
if (key === 'abort') return () => { throw new Error('already completing'); };
|
| 355 |
+
const value = target[key];
|
| 356 |
+
return typeof value === 'function' ? value.bind(target) : value;
|
| 357 |
+
}
|
| 358 |
+
});
|
| 359 |
+
const pending = h.session.restoreSearchSession();
|
| 360 |
+
await until(() => !!release);
|
| 361 |
+
h.expire();
|
| 362 |
+
assert.equal(await pending, false);
|
| 363 |
+
release();
|
| 364 |
+
await turn();
|
| 365 |
+
assert.deepEqual(h.history.replacements, []);
|
| 366 |
+
});
|
| 367 |
+
|
| 368 |
+
test('unavailable storage and disabled policy settle without leaking work', options, async () => {
|
| 369 |
+
const h = fixture();
|
| 370 |
+
const disabled = h.create({canPersist: () => false, canRestore: () => false});
|
| 371 |
+
await disabled.persistSearchSession();
|
| 372 |
+
assert.equal(await disabled.restoreSearchSession(), false);
|
| 373 |
+
assert.equal(h.opens, 0);
|
| 374 |
+
h.openError = new Error('storage unavailable');
|
| 375 |
+
await h.session.persistSearchSession();
|
| 376 |
+
await h.session.persistSearchSession();
|
| 377 |
+
assert.equal(await h.session.restoreSearchSession(), false);
|
| 378 |
+
});
|
typings/reader-globals.d.ts
CHANGED
|
@@ -362,6 +362,7 @@ interface SearchReaderNavigationApi {
|
|
| 362 |
mount(url: URL): HTMLIFrameElement;
|
| 363 |
unmount(keepSpeech?: boolean): HTMLElement | null;
|
| 364 |
dismiss(): void;
|
|
|
|
| 365 |
replace(raw: string, returnScroll: object): HTMLIFrameElement | null;
|
| 366 |
accepts(event: MessageEvent): boolean;
|
| 367 |
persistProgress(progress: {url?: unknown; closeTime?: unknown} | null | undefined): void;
|
|
|
|
| 362 |
mount(url: URL): HTMLIFrameElement;
|
| 363 |
unmount(keepSpeech?: boolean): HTMLElement | null;
|
| 364 |
dismiss(): void;
|
| 365 |
+
showCloseRecovery(raw: string): void;
|
| 366 |
replace(raw: string, returnScroll: object): HTMLIFrameElement | null;
|
| 367 |
accepts(event: MessageEvent): boolean;
|
| 368 |
persistProgress(progress: {url?: unknown; closeTime?: unknown} | null | undefined): void;
|