Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/core/src/router-client/diagnostics.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,51 @@ export function warnIfSmoothScrollOnHtml() {
);
}

/**
* #1428 diagnostic, TEMPORARY. Reads a guarded paint-timing lever an app sets
* on `window.__webjsDiag` (e.g. `{ raf: true }`) so the iOS back-swipe blank
* can be A/B'd on a real device. Default off, so the production nav path is
* byte-for-byte unchanged when nothing sets the object.
*
* The same shape as the #637 levers that isolated #610, and for the same
* reason: the symptom exists only on a real iPhone, where no harness we have
* can see it, so the only way to tell a candidate fix from a guess is to ship
* both behaviours behind a flag and let the device choose.
*
* @param {string} name
* @returns {boolean}
*/
export function diagFlag(name) {
try { return !!(typeof window !== 'undefined' && window.__webjsDiag && window.__webjsDiag[name]); }
catch { return false; }
}

/**
* #1428 diagnostic, TEMPORARY. Resolve after `frames` animation frames, or
* `null` when there is no `requestAnimationFrame` to wait on (the unit runner's
* DOM shim), so a caller can `await` it unconditionally.
*
* Why a frame and not a microtask: the thing being tested is whether WebKit has
* COMPOSITED the outgoing page before it captures the back-forward snapshot. A
* microtask runs inside the same task and paints nothing, so only a frame
* boundary can tell the two hypotheses apart.
*
* @param {number} frames
* @returns {Promise<void> | null}
*/
export function diagFrameYield(frames) {
if (typeof requestAnimationFrame !== 'function') return null;
return new Promise((resolve) => {
let left = frames;
const step = () => {
left -= 1;
if (left <= 0) resolve(undefined);
else requestAnimationFrame(step);
};
requestAnimationFrame(step);
});
}

/**
* Nav-in-flight signalling. The router can expose `data-navigating` on <html>
* so an app may style a loading indicator with `html[data-navigating] { … }`.
Expand Down
91 changes: 76 additions & 15 deletions packages/core/src/router-client/fetch-apply.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { markStale, parseTagHeader } from '../action-cache-client.js';
import { renderStream } from '../webjs-stream.js';
import { buildHaveHeader } from './boundaries.js';
import { STREAM_MIME } from './constants.js';
import { warnIfSmoothScrollOnHtml } from './diagnostics.js';
import { diagFlag, diagFrameYield, warnIfSmoothScrollOnHtml } from './diagnostics.js';
import { restoreOptimistic } from './dom-differ.js';
import { parseHTML } from './dom-parse.js';
import { clearFrameBusy, markFrameBusy } from './frames.js';
Expand Down Expand Up @@ -307,6 +307,43 @@ export async function fetchAndApply(href, frameId, recordHistory, optimisticStat
}
: null;

// #1428 diagnostic, TEMPORARY (default off, so an app that sets nothing runs
// the path above byte for byte). #1410 put the push ahead of the mutation and
// the blank SURVIVED on a real iPhone, which leaves exactly one assumption
// behind that fix untested: that WebKit binds the gesture snapshot
// synchronously, at the `pushState` call. If it instead captures the
// compositing surface when the `didSameDocumentNavigation` IPC lands in the
// UI process, that happens only after this whole task (push, swap,
// scroll-to-top) has run, so reordering WITHIN the task changes nothing the
// device can see, and the fix would need a composited frame instead. These
// levers test that by handing WebKit a frame to paint the OUTGOING page
// between the push and the swap.
//
// The yield sits HERE rather than at the four commit points inside
// `applySwap` because that function is synchronous and cannot await. The
// thunk is one-shot, so calling it here fires the push for whichever commit
// point the swap goes on to reach and leaves that call a no-op, which is the
// same ordering at every one of them rather than at a chosen few. Tied to
// `recordHistoryNow` being non-null so the background paths (a revalidation,
// a refresh, the popstate restore) are untouched: they record no entry, so
// there is no snapshot to compose, and delaying them would move a second
// variable in a run that is trying to isolate one.
const diagFrames = diagFlag('raf2') ? 2 : diagFlag('raf') ? 1 : 0;
if (diagFrames && recordHistoryNow) {
recordHistoryNow();
const painted = diagFrameYield(diagFrames);
if (painted) await painted;
// The yield reopens the supersede window the guard above just closed, so
// re-check rather than swapping in a document a newer navigation has
// already moved past. The push has landed by now and is not rolled back:
// the newer navigation pushes its own entry over it, and this is a
// diagnostic that only runs when a device A/B has opted in.
if (myToken !== currentNavigationToken) {
if (streamCtx && streamCtx.reader) { try { streamCtx.reader.cancel(); } catch { /* ignore */ } }
return { ok: false, status: respStatus, aborted: true, applied: false };
}
}

const disposition = applySwap(doc, frameId, !!revalidating, finalUrl, incomingBuild, incomingSrc, refresh, recordHistoryNow);
// `'none'` means applySwap returned WITHOUT committing anything: the frame the
// response was for is missing, or it degraded to a hard navigation (an
Expand Down Expand Up @@ -341,21 +378,45 @@ export async function fetchAndApply(href, frameId, recordHistory, optimisticStat
// restoration themselves before dispatching popstate, so
// leaving scroll alone preserves the browser-native UX.
if (recordHistory) {
// Use the final URL (after any server-side redirect) so hash
// anchors point at the document we actually rendered.
const url = new URL(finalUrl);
if (url.hash) {
const t = document.getElementById(url.hash.slice(1));
// A hash anchor is the one nav scroll we DON'T force instant: a
// `#section` link is exactly where an app's `scroll-behavior: smooth`
// is wanted, and native browsers animate it too.
if (t) t.scrollIntoView();
else { warnIfSmoothScrollOnHtml(); window.scrollTo({ left: 0, top: 0, behavior: 'instant' }); }
const applyNavScroll = () => {
// Use the final URL (after any server-side redirect) so hash
// anchors point at the document we actually rendered.
const url = new URL(finalUrl);
if (url.hash) {
const t = document.getElementById(url.hash.slice(1));
// A hash anchor is the one nav scroll we DON'T force instant: a
// `#section` link is exactly where an app's `scroll-behavior: smooth`
// is wanted, and native browsers animate it too.
if (t) t.scrollIntoView();
else { warnIfSmoothScrollOnHtml(); window.scrollTo({ left: 0, top: 0, behavior: 'instant' }); }
} else {
// Scroll-to-top on a forward nav. behavior:'instant' so an app-level
// `scroll-behavior: smooth` does not animate it (match native nav).
warnIfSmoothScrollOnHtml();
window.scrollTo({ left: 0, top: 0, behavior: 'instant' });
}
};
// #1428 diagnostic, TEMPORARY (default off). Isolates the CLAMP from the
// swap. The scroll-to-top runs in the same task as the push and the
// mutation, so if WebKit composes its snapshot from a later frame it reads
// an offset of 0 against the destination, and neither the #1410 ordering
// nor a frame yield would change that. Deferring the scroll past the frame
// says whether the offset is the part that matters. Extracted to a thunk so
// both paths run identical code and the run compares one variable.
if (diagFlag('scrolllast')) {
const painted = diagFrameYield(1);
// Guarded on the nav token, because deferring the scroll puts it outside
// this navigation's own task: a newer navigation can start in that frame,
// and then this would scroll ITS page. The synchronous path cannot do
// that, so an unguarded `.then` would be the lever writing scroll into a
// page it has nothing to do with. Worst on the hash branch, where
// `scrollIntoView` would hunt this URL's anchor in the new document and
// land somewhere arbitrary if the id happens to exist. A diagnostic
// measuring scroll behaviour cannot afford to move scroll on its own.
if (painted) painted.then(() => { if (myToken === currentNavigationToken) applyNavScroll(); });
Comment thread
vivek7405 marked this conversation as resolved.
else applyNavScroll();
} else {
// Scroll-to-top on a forward nav. behavior:'instant' so an app-level
// `scroll-behavior: smooth` does not animate it (match native nav).
warnIfSmoothScrollOnHtml();
window.scrollTo({ left: 0, top: 0, behavior: 'instant' });
applyNavScroll();
}
}

Expand Down
212 changes: 212 additions & 0 deletions packages/core/test/routing/browser/nav-swipe-ab-levers.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
/**
* Real-browser test for #1428: the guarded paint-timing levers that let a real
* iPhone decide what actually fixes the back-swipe blank.
*
* #1410 moved the `pushState` ahead of the DOM mutation and the blank survived
* on-device, which leaves one assumption behind that fix untested: that WebKit
* binds the back-forward gesture snapshot synchronously, at the `pushState`
* call. If it instead captures the compositing surface when the
* `didSameDocumentNavigation` IPC lands in the UI process, that happens after
* the whole push-swap-scroll task has run, and reordering inside that task
* changes nothing a device can see.
*
* The gesture preview is iOS-only and cannot be asserted anywhere but a real
* iPhone. What CAN be asserted in any browser is the thing the levers change:
* whether a FRAME BOUNDARY falls between the push and the mutation. That is the
* whole mechanism under test, so it is what these pin, in both directions.
*
* The default direction matters as much as the lever direction. These sit on
* the live navigation path, so an app that opts into nothing must run exactly
* the timing it ran before, and only a test that fails when the lever leaks can
* say so.
*/
import { enableClientRouter, navigate } from '../../../src/router-client.js';

import { assert } from '../../../../../test/browser-assert.js';
import { installNavGuard } from '../../../../../test/browser-nav-guard.js';

const OUTGOING_SENTINEL = 'outgoing-page-1428';
const INCOMING_SENTINEL = 'incoming-page-1428';
const SCROLL_TO = 800;

suite('Client router: back-swipe A/B levers (#1428)', () => {
let origFetch, origPushState, navGuard, origHref, observer, seq, pushes;

/** @param {Record<string, boolean> | null} levers */
function setup(levers) {
origHref = location.href;
enableClientRouter();
navGuard = installNavGuard();

if (levers) window.__webjsDiag = levers;
else delete window.__webjsDiag;

// A genuinely TALL outgoing document against a SHORT destination, the shape
// the defect was measured on: the engine really clamps the offset, so the
// #1410 guarantee is being re-checked against real layout rather than a
// stub.
document.body.innerHTML =
`<!--wj:children:/:/-->${OUTGOING_SENTINEL}<div style="height:3000px"></div><!--/wj:children:/-->`;
window.scrollTo({ left: 0, top: SCROLL_TO, behavior: 'instant' });

// One ordered trace of the three events the levers reorder. `frame` is
// requested from INSIDE the push wrapper, so it is queued ahead of any
// frame the router itself requests afterwards and therefore fires first
// within that frame. That ordering is what makes `frame` before `mutate`
// mean "the router waited for a frame" rather than "some frame elapsed".
seq = [];
pushes = [];
origPushState = history.pushState;
history.pushState = function (...args) {
seq.push('push');
pushes.push({ text: document.body.textContent || '', scrollY: window.scrollY });
requestAnimationFrame(() => seq.push('frame'));
return origPushState.apply(this, args);
};

// A MutationObserver callback is a microtask, so a synchronous swap records
// `mutate` before the next frame can run, which is exactly the distinction
// being drawn.
observer = new MutationObserver(() => {
if (!seq.includes('mutate')) seq.push('mutate');
});
observer.observe(document.body, { childList: true, subtree: true });

origFetch = window.fetch;
window.fetch = () => Promise.resolve(new Response(
'<!doctype html><html><head></head><body>'
+ `<!--wj:children:/:/-->${INCOMING_SENTINEL}<!--/wj:children:/--></body></html>`,
{ headers: { 'content-type': 'text/html', 'x-webjs-build': '' } },
));
}

function teardown() {
if (observer) observer.disconnect();
window.fetch = origFetch;
history.pushState = origPushState;
delete window.__webjsDiag;
if (navGuard) navGuard.remove();
document.body.innerHTML = '';
window.scrollTo({ left: 0, top: 0, behavior: 'instant' });
history.replaceState(null, '', origHref);
}

/** Let any pending frame callback land, so the trace is complete. */
function settleFrames() {
return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(undefined))));
}

test('default: no lever set, so the swap still happens in the push\'s own task', async () => {
setup(null);
try {
await navigate(location.origin + '/swipe-ab-default');
await settleFrames();

assert.equal(navGuard.hardNavigations.length, 0,
`the swap must not degrade here (fallbacks: ${JSON.stringify(navGuard.fallbacks)})`);
assert.deepEqual(seq, ['push', 'mutate', 'frame'],
`with no lever the mutation lands before any frame boundary (got ${JSON.stringify(seq)})`);
} finally { teardown(); }
});

test('?raf: a frame boundary falls between the push and the mutation', async () => {
setup({ raf: true });
try {
await navigate(location.origin + '/swipe-ab-raf');
await settleFrames();

assert.equal(navGuard.hardNavigations.length, 0,
`the swap must not degrade here (fallbacks: ${JSON.stringify(navGuard.fallbacks)})`);
assert.deepEqual(seq, ['push', 'frame', 'mutate'],
`the lever must paint a frame between the push and the swap (got ${JSON.stringify(seq)})`);
} finally { teardown(); }
});

test('?raf2: same ordering, and the entry is still recorded exactly once', async () => {
setup({ raf2: true });
try {
await navigate(location.origin + '/swipe-ab-raf2');
await settleFrames();

assert.deepEqual(seq, ['push', 'frame', 'mutate'],
`the double-frame lever must also swap after a frame (got ${JSON.stringify(seq)})`);
// The lever calls the one-shot thunk itself and `applySwap` calls it
// again at its commit point, so the guard is the only thing between this
// and a duplicated history entry.
assert.equal(pushes.length, 1, 'exactly one pushState per navigation under the lever');
} finally { teardown(); }
});

test('?scrolllast: the scroll-to-top lands after a frame, not in the swap\'s task', async () => {
setup({ scrolllast: true });
const scrolls = [];
const origScrollTo = window.scrollTo;
try {
// Recorded rather than suppressed: the lever is about WHEN the write
// happens, so the write still has to happen.
window.scrollTo = function (...args) { scrolls.push(seq.slice()); return origScrollTo.apply(this, args); };
await navigate(location.origin + '/swipe-ab-scrolllast');
const beforeFrame = scrolls.length;
await settleFrames();

assert.equal(beforeFrame, 0,
`the deferred scroll must not have run yet when the navigation resolved (ran ${beforeFrame} times)`);
assert.equal(scrolls.length, 1, 'the scroll still runs, one frame later');
assert.ok(scrolls[0].includes('frame'),
`the scroll landed after a frame boundary (trace at the write: ${JSON.stringify(scrolls[0])})`);
} finally { window.scrollTo = origScrollTo; teardown(); }
});

test('?scrolllast: a superseded navigation does not scroll the page that replaced it', async () => {
setup({ scrolllast: true });
const scrolls = [];
const origScrollTo = window.scrollTo;
try {
window.scrollTo = function (...args) { scrolls.push('scroll'); return origScrollTo.apply(this, args); };
await navigate(location.origin + '/swipe-ab-superseded');

// Start a second navigation inside the deferred scroll's frame gap. It
// bumps the nav token and then does nothing else, which isolates the
// guard from anything the newer navigation would itself have done to
// scroll.
//
// Aborted rather than left pending. A fetch that never settles leaves a
// navigation in flight for the rest of the page's life, holding the
// router's token and its own frame state, and a test that never cleans
// that up is a leak looking for somewhere to surface. An AbortError is
// the shape the router already treats as a superseded navigation, so it
// settles down the path it would take in production.
let abortPending;
window.fetch = () => new Promise((_, reject) => { abortPending = reject; });
const superseder = navigate(location.origin + '/swipe-ab-superseder');
await settleFrames();
if (abortPending) abortPending(new DOMException('aborted', 'AbortError'));
await superseder.catch(() => {});

// Without the token guard the first navigation's scroll fires here, into
// a document a newer navigation already owns.
assert.equal(scrolls.length, 0,
'the superseded navigation abandoned its deferred scroll');
} finally { window.scrollTo = origScrollTo; teardown(); }
});

test('?raf: the #1410 guarantee survives, the outgoing page is still live at the push', async () => {
setup({ raf: true });
try {
await navigate(location.origin + '/swipe-ab-raf-state');
await settleFrames();

assert.equal(pushes.length, 1, 'the navigation recorded exactly one history entry');
const at = pushes[0];
// The lever moves the push EARLIER (ahead of the yield), so what #1410
// pinned has to still hold: a lever that fixed the frame timing by
// sacrificing the recorded state would be a regression wearing a fix.
assert.ok(at.text.includes(OUTGOING_SENTINEL),
'the outgoing page is still in the DOM at the pushState call');
assert.ok(!at.text.includes(INCOMING_SENTINEL),
'the incoming page has NOT been swapped in yet at the pushState call');
assert.ok(at.scrollY >= SCROLL_TO - 5,
`the outgoing scroll offset is still live at the pushState call (expected about ${SCROLL_TO}, got ${at.scrollY})`);
} finally { teardown(); }
});
});
Loading
Loading