mirror of
https://github.com/readest/readest.git
synced 2026-12-01 13:36:39 +00:00
perf(reader): hand off native page warm-up and freeze webview during turns (#8102)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* perf(reader): hand off native page warm-up and freeze webview during turns
- Hand off in-flight idle neighbor warm-up directly into beginDrag()
instead of aborting and re-capturing the same adjacent page.
- Keep the native cover up across back-to-back queued turns via
keepCover / coverHeld capability negotiation (iOS safely falls back
to re-covering when coverHeld is not reported).
- Suppress redundant WebView repaints/animations while the opaque native
sheet covers the viewport (data-native-turn-frozen).
- Suppress op: move IPCs while beginDrag() is still preparing.
Co-Authored-By: Antigravity (Gemini) <noreply@google.com>
* fix(reader): scope turn freeze to host cell and harden warm-up handoff edge cases
- Scope data-native-turn-frozen to the turning cell's hostElement so sibling parallel-view readers stay visible.
- Guard post-start freeze against disposal/stale scenes, clear rejected session before releasing held cover, reconcile native result.keys on aborted captures, and replay buffered drag pose when touchTracked is false.
- Fix animate-rejection test to reject animate specifically and add regression tests for all edge cases.
Co-Authored-By: Antigravity (Gemini) <noreply@google.com>
* fix(reader): lower adopted covers, drop aborted uploads, stop previews on touch
Review fixes for the native warm-up and cover handoff:
- A turn that adopts a held cover skips `cover`, so native keeps the
previous turn's id. When that turn failed before `start`, `#restore`
sent `finish` with its own id, native dropped it, and the sheet stayed
up over the reader. `#restore` now also sends `idle` when it drops a
held cover.
- An aborted capture whose upload had finished returned its key in
`result.keys`, and JS kept it, but `abortCapture` drops that texture
on native. A later turn then called `start` with a missing destination.
The aborted key is now left out of the reconciled set.
- `#touchRetained` was cleared only by `releasePreparedCapture`. A
committed turn's relocate reaches it through
`invalidatePreparedCapture`, but a cancelled swipe whose DOM touch end
takes the drag path never does, so warm-ups after it took the current
page only until the next touch. `beginDrag` now clears it.
- A touch no longer stopped a running warm-up preview, so the paginator
stayed on the neighbouring page under the finger until its capture
ended (`previewPage` restores the live page only on abort). Contact
now aborts an in-flight preview and starts no new one. A capture of
the current page keeps running for the turn to take over. The cost:
the aborted page is captured again after the touch, and a tap turn
in that direction no longer reuses the in-flight preview.
- Native `cancel` hides the sheet while the WebView was still hidden
by `data-native-turn-frozen`, leaving a blank cell until the finger
lifted. `invalidatePreparedCapture` now thaws the WebView when it
sends `cancel`.
The reconciliation test now makes page 0 resident before the warm-up,
so it fails without the reconciliation (CodeRabbit).
Verified:
- New tests in native-page-turn.test.ts fail on 0cddd67a0 and pass
here. With each fix removed alone, only its own test fails:
- reconciles resident keys...: expected 1 to be 2 (also with no
aborted-key reconciliation at all: expected 1 to be 2)
- lowers a held cover...: expected true to be false
- warms both neighbouring pages again after a cancelled swipe:
expected false to be true
- returns a touched page from a warm-up preview...: expected false
to be true
- shows the reader again when an overlay cancels...: expected 'true'
to be undefined
- pnpm test --run native-page-turn, useCapturedTurn and
useCapturedTurn-scrollLock: 187 passed
- pnpm test:browser --run paginator-paginated.browser.test.ts: 37 passed
- pnpm lint (tsc + biome) and pnpm format:check: clean
- Debug x86_64 APK built (compiles the NativePaperTurn.kt change, which
PR CI does not); ./gradlew :tauri-plugin-native-bridge:
testFossGenericPenDebugUnitTest: 55 passed
- Android 17 emulator (Readest_API37, WebView 145), alice.epub, Curl,
native ops traced with a CDP logpoint on the paper_curl invoke:
- 5 queued turns (view.next() x5): each finish sent keepCover, the
next turn captured its destination under the held cover with no
`cover`, and the last finish lowered it. A paginator goTo to the
next chapter then showed on screen, so no sheet was left up.
- Swipes: committed swipes warm both neighbours on 0cddd67a0 too,
because the relocate releases the lease. The cancelled-swipe case
was not exercised on the device.
- Touch while the warm-up previews the next page: on 0cddd67a0 the
paginator still showed the preview page at the first sample after
touchstart and returned when the capture finished (~30-50 ms).
Here it was back on the live page at the first sample, with
`abortCapture` sent, and the page was captured again after release.
- Not run: the held-cover failure path, the aborted-upload race and the
overlay `cancel` on a device (timing-dependent; covered by the unit
tests above). iOS.
Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
* docs(reader): say why a touch keeps a current-page capture running
The comment on retainPreparedCapture said a turn can take the capture
over. It cannot: beginDrag aborts any warm-up that is not previewing in
the turn's direction. The capture keeps running because it leaves the
viewport alone.
Comment only. native-page-turn.test.ts: 36 passed; biome check clean.
Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
* fix(reader): keep a refreshed page out when native reports its pages
`#capture` replaced the resident set with the page list native returns,
even for an aborted warm-up capture. `refreshCurrentPage` (a PDF page
drawing its sharp layer once shown) stops the warm-up and drops the
current page, but a neighbour capture that native had already finished
still listed the old current page and put it back. The next turn then
used the stale sheet. On main this could not happen: stopping a warm-up
cleared every key, and an aborted capture's list was ignored.
Native's list now only removes pages (an evicted texture, or the aborted
upload its `abortCapture` drops); the captured page is added on success.
The test fixture's `previewPage` now returns to the live page when its
signal aborts, as the paginator does. The iOS re-cover test now checks
that both turns succeed and that the second turn's `cover` comes before
its page 3 capture (CodeRabbit).
Verified:
- "keeps a refreshed page stale when an aborted warm-up returns native
keys" fails without the nativePageTurn change: expected 1 to be 2.
"reconciles resident keys..." still fails with no reconciliation at
all (expected 1 to be 2).
- "re-covers on the next queued turn..." fails when JS takes the cover
as held without native's `coverHeld`: expected -1 to be greater
than -1.
- native-page-turn, useCapturedTurn and useCapturedTurn-scrollLock:
189 passed. pnpm lint and pnpm format:check: clean.
Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
---------
Co-authored-by: Antigravity (Gemini) <noreply@google.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
This commit is contained in:
parent
f3fc4ef65c
commit
5d820e4269
4 changed files with 638 additions and 43 deletions
|
|
@ -40,6 +40,7 @@ class NativePaperArgs {
|
|||
var commit = false; var velocity = 0f
|
||||
var columns = 1
|
||||
var flip = false
|
||||
var keepCover = false
|
||||
}
|
||||
|
||||
/** CSS px -> WebView px as [left, top, width, height]. The CSS viewport can
|
||||
|
|
@ -327,14 +328,19 @@ internal class NativePaperTurn(private val activity: Activity, private val webVi
|
|||
p.resolve()
|
||||
}
|
||||
"finish" -> {
|
||||
presented(p) {
|
||||
if (args.turnId != turnId) {
|
||||
p.resolve(JSObject().put("ready", false).put("cancelled", true)); return@presented
|
||||
}
|
||||
if (args.keepCover && !dirtyAfterFinish) {
|
||||
active = false; dragging = false
|
||||
view?.host?.alpha = if (dirtyAfterFinish) 0f else 0.004f
|
||||
if (dirtyAfterFinish) { view?.clear(false); dirtyAfterFinish = false }
|
||||
p.resolve()
|
||||
p.resolve(JSObject().put("coverHeld", true))
|
||||
} else {
|
||||
presented(p) {
|
||||
if (args.turnId != turnId) {
|
||||
p.resolve(JSObject().put("ready", false).put("cancelled", true)); return@presented
|
||||
}
|
||||
active = false; dragging = false
|
||||
view?.host?.alpha = if (dirtyAfterFinish) 0f else 0.004f
|
||||
if (dirtyAfterFinish) { view?.clear(false); dirtyAfterFinish = false }
|
||||
p.resolve()
|
||||
}
|
||||
}
|
||||
}
|
||||
"invalidate" -> {
|
||||
|
|
|
|||
|
|
@ -10,18 +10,26 @@ import type { Renderer } from '@/types/view';
|
|||
|
||||
const fixture = (columns?: number, flip?: () => boolean) => {
|
||||
let page = 1;
|
||||
let allowed = true;
|
||||
const events: string[] = [];
|
||||
const renderer = {
|
||||
setAttribute: vi.fn(),
|
||||
removeAttribute: vi.fn(),
|
||||
getPageTurnKey: (delta = 0) => String(page + delta),
|
||||
previewPage: async <T>(forward: boolean, read: () => Promise<T>) => {
|
||||
previewPage: async <T>(forward: boolean, read: () => Promise<T>, signal?: AbortSignal) => {
|
||||
const original = page;
|
||||
page += forward ? 1 : -1;
|
||||
try {
|
||||
return { key: String(page), value: await read() };
|
||||
} finally {
|
||||
const key = String(page);
|
||||
// Like the paginator, an abort returns to the live page at once.
|
||||
const restore = () => {
|
||||
page = original;
|
||||
};
|
||||
signal?.addEventListener('abort', restore, { once: true });
|
||||
try {
|
||||
return { key, value: await read() };
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', restore);
|
||||
restore();
|
||||
}
|
||||
},
|
||||
} as unknown as Renderer;
|
||||
|
|
@ -34,7 +42,10 @@ const fixture = (columns?: number, flip?: () => boolean) => {
|
|||
});
|
||||
const call = vi.fn(async (args: NativePaperCommand): Promise<NativePaperResult> => {
|
||||
events.push(args.op);
|
||||
return { touchTracked: true };
|
||||
return {
|
||||
touchTracked: true,
|
||||
...(args.op === 'finish' && args.keepCover ? { coverHeld: true } : {}),
|
||||
};
|
||||
});
|
||||
const controller = new NativePageTurn(
|
||||
{
|
||||
|
|
@ -42,12 +53,16 @@ const fixture = (columns?: number, flip?: () => boolean) => {
|
|||
getContentRect: () => new DOMRect(0, 0, 360, 780),
|
||||
...(columns ? { getColumnCount: () => columns } : {}),
|
||||
...(flip ? { isPageFlip: flip } : {}),
|
||||
isCaptureAllowed: () => allowed,
|
||||
capture,
|
||||
navigate,
|
||||
},
|
||||
{ renderer, enabled: () => true, call },
|
||||
);
|
||||
return { controller, call, capture, navigate, events, renderer };
|
||||
const block = () => {
|
||||
allowed = false;
|
||||
};
|
||||
return { controller, call, capture, navigate, events, renderer, block };
|
||||
};
|
||||
|
||||
describe('Android native page-turn pipeline', () => {
|
||||
|
|
@ -580,4 +595,417 @@ describe('Android native page-turn pipeline', () => {
|
|||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('reuses an in-flight matching warm-up capture and hands off the cover without idle/recapture', async () => {
|
||||
const f = fixture();
|
||||
let releaseSecondCapture!: (result: NativePaperResult) => void;
|
||||
let captureCount = 0;
|
||||
const baseCall = f.call.getMockImplementation()!;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
if (args.op === 'capture' && ++captureCount === 2) {
|
||||
f.events.push('capture');
|
||||
return await new Promise<NativePaperResult>((resolve) => {
|
||||
releaseSecondCapture = resolve;
|
||||
});
|
||||
}
|
||||
return baseCall(args);
|
||||
});
|
||||
try {
|
||||
const warming = f.controller.prepareCapture('curl');
|
||||
await vi.waitFor(() => expect(captureCount).toBe(2));
|
||||
|
||||
// Dragging toward page '2' while page '2' is mid-capture must NOT abort or wait for idle.
|
||||
const dragging = f.controller.beginDrag(true, false, 'curl');
|
||||
releaseSecondCapture({ ready: true });
|
||||
|
||||
expect(await warming).toBe(true);
|
||||
expect(await dragging).toBe(true);
|
||||
|
||||
const capturedKeys = f.call.mock.calls
|
||||
.filter(([args]) => args.op === 'capture')
|
||||
.map(([args]) => args.key);
|
||||
expect(capturedKeys).toEqual(['1', '2']);
|
||||
expect(f.call.mock.calls.some(([args]) => args.op === 'abortCapture')).toBe(false);
|
||||
expect(f.events).not.toContain('idle');
|
||||
expect(f.events.indexOf('cover')).toBeLessThan(f.events.indexOf('start'));
|
||||
expect(f.call.mock.calls.filter(([args]) => args.op === 'cover')).toHaveLength(1);
|
||||
|
||||
await f.controller.endDrag(true);
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('binds data-native-turn-frozen strictly to the turning host cell during start..settling and thaws on navigate/error', async () => {
|
||||
const f = fixture();
|
||||
const frozenAtOp: Record<string, string | undefined> = {};
|
||||
let frozenAtNavigate: string | undefined;
|
||||
const baseCall = f.call.getMockImplementation()!;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
const res = await baseCall(args);
|
||||
frozenAtOp[args.op] = document.body.dataset['nativeTurnFrozen'];
|
||||
return res;
|
||||
});
|
||||
const baseNavigate = f.navigate.getMockImplementation()!;
|
||||
f.navigate.mockImplementation(async (forward) => {
|
||||
frozenAtNavigate = document.body.dataset['nativeTurnFrozen'];
|
||||
await baseNavigate(forward);
|
||||
});
|
||||
try {
|
||||
await f.controller.prepareCapture('curl');
|
||||
expect(document.body.dataset['nativeTurnFrozen']).toBeUndefined();
|
||||
|
||||
expect(await f.controller.beginDrag(true, false, 'curl')).toBe(true);
|
||||
expect(document.body.dataset['nativeTurnFrozen']).toBe('true');
|
||||
// Document root must stay untouched so sibling parallel-view readers are not hidden.
|
||||
expect(document.documentElement.dataset['nativeTurnFrozen']).toBeUndefined();
|
||||
|
||||
await f.controller.endDrag(true);
|
||||
expect(frozenAtOp['capture']).toBeUndefined();
|
||||
expect(frozenAtOp['animate']).toBe('true');
|
||||
expect(frozenAtNavigate).toBeUndefined();
|
||||
expect(frozenAtOp['finish']).toBeUndefined();
|
||||
expect(document.body.dataset['nativeTurnFrozen']).toBeUndefined();
|
||||
|
||||
// Also clears cleanly when animate itself fails (rejecting animate specifically, not cover).
|
||||
let frozenWhenAnimateRejected: string | undefined;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
if (args.op === 'animate') {
|
||||
frozenWhenAnimateRejected = document.body.dataset['nativeTurnFrozen'];
|
||||
throw new Error('animate failed');
|
||||
}
|
||||
return baseCall(args);
|
||||
});
|
||||
await expect(f.controller.turn(true, false, 'curl')).rejects.toThrow('animate failed');
|
||||
expect(frozenWhenAnimateRejected).toBe('true');
|
||||
expect(document.body.dataset['nativeTurnFrozen']).toBeUndefined();
|
||||
} finally {
|
||||
delete document.body.dataset['nativeTurnFrozen'];
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('suppresses op: move IPC before start resolves and replays the buffered drag pose once start settles with touchTracked: false', async () => {
|
||||
const f = fixture();
|
||||
let releaseStart!: (result: NativePaperResult) => void;
|
||||
const baseCall = f.call.getMockImplementation()!;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
if (args.op === 'start') {
|
||||
f.events.push('start');
|
||||
return await new Promise<NativePaperResult>((resolve) => {
|
||||
releaseStart = resolve;
|
||||
});
|
||||
}
|
||||
return baseCall(args);
|
||||
});
|
||||
try {
|
||||
await f.controller.prepareCapture('curl');
|
||||
f.call.mockClear();
|
||||
const dragging = f.controller.beginDrag(true, false, 'curl');
|
||||
await vi.waitFor(() =>
|
||||
expect(f.call.mock.calls.some(([args]) => args.op === 'start')).toBe(true),
|
||||
);
|
||||
|
||||
// Move calls before start resolves must only buffer session state, not emit op: move IPCs.
|
||||
f.controller.moveDrag(0.35, 0.5);
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => setTimeout(resolve, 0)));
|
||||
expect(f.call.mock.calls.some(([args]) => args.op === 'move')).toBe(false);
|
||||
|
||||
// Once start resolves with touchTracked: false, the buffered pose (0.35) is replayed
|
||||
// even if the user holds still without further moveDrag calls.
|
||||
releaseStart({ ready: true, touchTracked: false });
|
||||
expect(await dragging).toBe(true);
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
f.call.mock.calls.some(([args]) => args.op === 'move' && args.progress === 0.35),
|
||||
).toBe(true),
|
||||
);
|
||||
|
||||
f.controller.moveDrag(0.55, 0.6);
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
f.call.mock.calls.some(([args]) => args.op === 'move' && args.progress === 0.55),
|
||||
).toBe(true),
|
||||
);
|
||||
|
||||
await f.controller.endDrag(false);
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not freeze the host when start resolves after dispose', async () => {
|
||||
const f = fixture();
|
||||
let releaseStart!: (result: NativePaperResult) => void;
|
||||
const baseCall = f.call.getMockImplementation()!;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
if (args.op === 'start') {
|
||||
return await new Promise<NativePaperResult>((resolve) => {
|
||||
releaseStart = resolve;
|
||||
});
|
||||
}
|
||||
return baseCall(args);
|
||||
});
|
||||
try {
|
||||
await f.controller.prepareCapture('curl');
|
||||
const dragging = f.controller.beginDrag(true, false, 'curl');
|
||||
await vi.waitFor(() => expect(releaseStart).toBeTypeOf('function'));
|
||||
|
||||
f.controller.dispose();
|
||||
releaseStart({ ready: true, touchTracked: true });
|
||||
expect(await dragging).toBe(false);
|
||||
expect(document.body.dataset['nativeTurnFrozen']).toBeUndefined();
|
||||
} finally {
|
||||
delete document.body.dataset['nativeTurnFrozen'];
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('reconciles resident keys when an aborted capture still returns native keys', async () => {
|
||||
const f = fixture();
|
||||
let resolveAdjacent!: (result: NativePaperResult) => void;
|
||||
let adjacentCaptures = 0;
|
||||
const baseCall = f.call.getMockImplementation()!;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
if (args.op === 'capture' && args.key === '2' && ++adjacentCaptures === 1) {
|
||||
f.events.push('capture');
|
||||
return await new Promise<NativePaperResult>((resolve) => {
|
||||
resolveAdjacent = resolve;
|
||||
});
|
||||
}
|
||||
return baseCall(args);
|
||||
});
|
||||
const captures = (key: string) =>
|
||||
f.call.mock.calls.filter(([args]) => args.op === 'capture' && args.key === key).length;
|
||||
try {
|
||||
// Make page 0 resident beside page 1, then warm page 2.
|
||||
expect(await f.controller.turn(false, false, 'curl')).toBe(true);
|
||||
expect(await f.controller.turn(true, false, 'curl')).toBe(true);
|
||||
expect(captures('0')).toBe(1);
|
||||
const warm = f.controller.prepareCapture('curl');
|
||||
await vi.waitFor(() => expect(resolveAdjacent).toBeTypeOf('function'));
|
||||
|
||||
// Abort warm-up by starting a backward drag (opposite direction).
|
||||
const drag = f.controller.beginDrag(false, false, 'curl');
|
||||
// Native uploaded page 2 before the abort arrived, evicting page 0. Its
|
||||
// `abortCapture` then drops page 2 again.
|
||||
resolveAdjacent({ ready: true, keys: ['1', '2'] });
|
||||
await warm;
|
||||
expect(await drag).toBe(true);
|
||||
// Page 0 was evicted, so the backward turn takes it again.
|
||||
expect(captures('0')).toBe(2);
|
||||
await f.controller.endDrag(false);
|
||||
|
||||
// The aborted upload of page 2 is not resident either.
|
||||
expect(await f.controller.turn(true, false, 'curl')).toBe(true);
|
||||
expect(captures('2')).toBe(2);
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
// A PDF page draws its sharp layer once shown, so its sheet is retaken.
|
||||
it('keeps a refreshed page stale when an aborted warm-up returns native keys', async () => {
|
||||
const f = fixture();
|
||||
let resolveAdjacent!: (result: NativePaperResult) => void;
|
||||
const baseCall = f.call.getMockImplementation()!;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
if (args.op === 'capture' && args.key === '2' && !resolveAdjacent) {
|
||||
f.events.push('capture');
|
||||
return await new Promise<NativePaperResult>((resolve) => {
|
||||
resolveAdjacent = resolve;
|
||||
});
|
||||
}
|
||||
return baseCall(args);
|
||||
});
|
||||
const captures = (key: string) =>
|
||||
f.call.mock.calls.filter(([args]) => args.op === 'capture' && args.key === key).length;
|
||||
try {
|
||||
const warm = f.controller.prepareCapture('curl');
|
||||
await vi.waitFor(() => expect(resolveAdjacent).toBeTypeOf('function'));
|
||||
expect(captures('1')).toBe(1);
|
||||
|
||||
f.controller.refreshCurrentPage();
|
||||
// Native finished page 2 before the abort, and still holds the old page 1.
|
||||
resolveAdjacent({ ready: true, keys: ['1', '2'] });
|
||||
await warm;
|
||||
|
||||
expect(await f.controller.turn(true, false, 'curl')).toBe(true);
|
||||
expect(captures('1')).toBe(2);
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('lowers a held cover when the turn that adopted it fails before start', async () => {
|
||||
const f = fixture();
|
||||
// Native binds the cover to the turn that raised it and drops another turn's `finish`.
|
||||
let nativeTurn = 0;
|
||||
let coverUp = false;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
f.events.push(args.op);
|
||||
if (args.op === 'cover' || args.op === 'start') {
|
||||
nativeTurn = args.turnId ?? 0;
|
||||
coverUp = true;
|
||||
} else if (args.op === 'idle') {
|
||||
coverUp = false;
|
||||
} else if (args.op === 'finish') {
|
||||
if (args.turnId !== nativeTurn) return { ready: false, cancelled: true };
|
||||
if (args.keepCover) return { coverHeld: true };
|
||||
coverUp = false;
|
||||
} else if (args.op === 'capture' && args.key === '3') {
|
||||
// The queued turn cannot take its destination sheet.
|
||||
return { ready: false };
|
||||
}
|
||||
return { touchTracked: true };
|
||||
});
|
||||
try {
|
||||
await f.controller.prepareCapture('curl');
|
||||
const turns = await Promise.all([
|
||||
f.controller.turn(true, false, 'curl'),
|
||||
f.controller.turn(true, false, 'curl'),
|
||||
]);
|
||||
expect(turns).toEqual([true, false]);
|
||||
// Only the warm-up raised a cover: the second turn adopted the held one.
|
||||
expect(f.call.mock.calls.filter(([args]) => args.op === 'cover')).toHaveLength(1);
|
||||
expect(coverUp).toBe(false);
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('warms both neighbouring pages again after a cancelled swipe', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
// A swipe retains the prepared surface on touch-down. A DOM touch end
|
||||
// takes the drag path, which does not release it, and a cancelled
|
||||
// turn sends no relocate to release it either.
|
||||
f.controller.retainPreparedCapture();
|
||||
expect(await f.controller.beginDrag(true, false, 'curl')).toBe(true);
|
||||
await f.controller.endDrag(false);
|
||||
|
||||
expect(await f.controller.prepareCapture('curl')).toBe(true);
|
||||
expect(f.call.mock.calls.some(([args]) => args.op === 'capture' && args.key === '0')).toBe(
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns a touched page from a warm-up preview to the live page', async () => {
|
||||
const f = fixture();
|
||||
let releaseAdjacent!: (result: NativePaperResult) => void;
|
||||
const baseCall = f.call.getMockImplementation()!;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
if (args.op === 'capture' && args.key === '2') {
|
||||
f.events.push('capture');
|
||||
return await new Promise<NativePaperResult>((resolve) => {
|
||||
releaseAdjacent = resolve;
|
||||
});
|
||||
}
|
||||
return baseCall(args);
|
||||
});
|
||||
// The paginator restores the live page when its preview signal aborts.
|
||||
const preview = f.renderer.previewPage!;
|
||||
let previewSignal: AbortSignal | undefined;
|
||||
f.renderer.previewPage = (forward, read, signal) => {
|
||||
previewSignal = signal;
|
||||
return preview(forward, read, signal);
|
||||
};
|
||||
try {
|
||||
const warm = f.controller.prepareCapture('curl');
|
||||
await vi.waitFor(() => expect(releaseAdjacent).toBeTypeOf('function'));
|
||||
expect(f.renderer.getPageTurnKey!()).toBe('2');
|
||||
|
||||
// A finger lands while page 2 is parked under the cover, e.g. on a link.
|
||||
f.controller.retainPreparedCapture();
|
||||
expect(previewSignal?.aborted).toBe(true);
|
||||
releaseAdjacent({ ready: true });
|
||||
await warm;
|
||||
// No further preview starts under the finger.
|
||||
expect(f.call.mock.calls.some(([args]) => args.op === 'capture' && args.key === '0')).toBe(
|
||||
false,
|
||||
);
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the reader again when an overlay cancels a native turn mid-drag', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
expect(await f.controller.beginDrag(true, false, 'curl')).toBe(true);
|
||||
expect(document.body.dataset['nativeTurnFrozen']).toBe('true');
|
||||
|
||||
// Native `cancel` hides its sheet while the finger is still down.
|
||||
f.block();
|
||||
f.controller.invalidatePreparedCapture();
|
||||
expect(f.events.at(-1)).toBe('cancel');
|
||||
expect(document.body.dataset['nativeTurnFrozen']).toBeUndefined();
|
||||
await f.controller.endDrag(false);
|
||||
} finally {
|
||||
delete document.body.dataset['nativeTurnFrozen'];
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('releases a warm-up held cover when an interrupting drag is rejected at a boundary', async () => {
|
||||
const f = fixture();
|
||||
let releaseCapture!: (result: NativePaperResult) => void;
|
||||
const baseCall = f.call.getMockImplementation()!;
|
||||
f.call.mockImplementation(async (args) => {
|
||||
if (args.op === 'capture' && args.key === '2') {
|
||||
f.events.push('capture');
|
||||
return await new Promise<NativePaperResult>((resolve) => {
|
||||
releaseCapture = resolve;
|
||||
});
|
||||
}
|
||||
return baseCall(args);
|
||||
});
|
||||
try {
|
||||
const warm = f.controller.prepareCapture('curl');
|
||||
await vi.waitFor(() => expect(releaseCapture).toBeTypeOf('function'));
|
||||
|
||||
// Mark atEnd so the interrupting forward drag hands off cover, then rejects at boundary.
|
||||
(f.renderer as unknown as { atEnd: boolean }).atEnd = true;
|
||||
const drag = f.controller.beginDrag(true, false, 'curl');
|
||||
releaseCapture({ ready: true, keys: ['1', '2'] });
|
||||
await warm;
|
||||
expect(await drag).toBe(false);
|
||||
expect(f.events.at(-1)).toBe('idle');
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('re-covers on the next queued turn when native finish does not report coverHeld (e.g. iOS)', async () => {
|
||||
const f = fixture();
|
||||
// Simulate a native bridge (such as iOS) that ignores keepCover and lowers its cover on finish.
|
||||
f.call.mockImplementation(async (args) => {
|
||||
f.events.push(args.op);
|
||||
return { touchTracked: true };
|
||||
});
|
||||
try {
|
||||
await f.controller.prepareCapture('curl');
|
||||
f.call.mockClear();
|
||||
|
||||
expect(
|
||||
await Promise.all([
|
||||
f.controller.turn(true, false, 'curl'),
|
||||
f.controller.turn(true, false, 'curl'),
|
||||
]),
|
||||
).toEqual([true, true]);
|
||||
|
||||
// Turn 2 needed to capture page 3 and native did not hold the cover, so it must re-cover first.
|
||||
const ops = f.call.mock.calls.map(([args]) => args);
|
||||
const second = ops.filter((args) => args.op === 'start')[1]?.turnId;
|
||||
const cover = ops.findIndex((args) => args.op === 'cover' && args.turnId === second);
|
||||
const capture = ops.findIndex((args) => args.op === 'capture' && args.key === '3');
|
||||
expect(cover).toBeGreaterThan(-1);
|
||||
expect(cover).toBeLessThan(capture);
|
||||
} finally {
|
||||
f.controller.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -34,16 +34,24 @@ export interface NativePaperCommand {
|
|||
velocity?: number;
|
||||
columns?: number;
|
||||
flip?: boolean;
|
||||
keepCover?: boolean;
|
||||
}
|
||||
export interface NativePaperResult {
|
||||
ready?: boolean;
|
||||
touchTracked?: boolean;
|
||||
cancelled?: boolean;
|
||||
coverHeld?: boolean;
|
||||
keys?: string[];
|
||||
}
|
||||
type Rect = { x: number; y: number; width: number; height: number };
|
||||
type Session = { id: number; released: boolean; progress: number; grabY: number };
|
||||
type Scene = { session: Session; forward: boolean; navigated: boolean; touchTracked: boolean };
|
||||
type Scene = {
|
||||
session: Session;
|
||||
forward: boolean;
|
||||
navigated: boolean;
|
||||
started: boolean;
|
||||
touchTracked: boolean;
|
||||
};
|
||||
// The native scene outlives a page reload. Start each page load at its own
|
||||
// owner, or a reloaded reader inherits the old page's generation and every
|
||||
// capture is refused. Kept within a 32-bit Int for the Kotlin side.
|
||||
|
|
@ -61,14 +69,22 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
#scene: Scene | null = null;
|
||||
#queue: Promise<unknown> = Promise.resolve();
|
||||
#warming: Promise<boolean> | null = null;
|
||||
#warmingKey: string | null = null;
|
||||
#warmingDelta: number | null = null;
|
||||
#warmingStopAfterKey: string | null = null;
|
||||
#warmingHandoffToTurnId: number | null = null;
|
||||
#abort: AbortController | null = null;
|
||||
#moveRaf = 0;
|
||||
#request = 0;
|
||||
#turn = 0;
|
||||
#frozenHost: HTMLElement | null = null;
|
||||
#cancellations = new Set<Promise<unknown>>();
|
||||
#invalidations: Promise<unknown> = Promise.resolve();
|
||||
#invalidationHeld = false;
|
||||
#restoring = false;
|
||||
#touchRetained = false;
|
||||
#coverHeld = false;
|
||||
#lastForward = true;
|
||||
|
||||
constructor(
|
||||
private host: CapturedTurnHost,
|
||||
|
|
@ -123,10 +139,25 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
if (nativeOwner && nativeOwner !== this) nativeOwner.invalidateNativePages();
|
||||
nativeOwner = this;
|
||||
}
|
||||
/** Abort idle previews so input can restore and use the live paginator. */
|
||||
/** Hide the turning cell's WebView once the native sheet covers it at `start`. */
|
||||
#freezeWebView() {
|
||||
if (this.#frozenHost) return;
|
||||
const host = this.host.getHostElement?.();
|
||||
if (!host) return;
|
||||
this.#frozenHost = host;
|
||||
host.dataset['nativeTurnFrozen'] = 'true';
|
||||
}
|
||||
/** Restore the turning cell's WebView before navigation commits and cover removal. */
|
||||
#thawWebView() {
|
||||
const host = this.#frozenHost;
|
||||
if (!host) return;
|
||||
this.#frozenHost = null;
|
||||
delete host.dataset['nativeTurnFrozen'];
|
||||
}
|
||||
/** Abort idle previews so input can restore and use the live paginator.
|
||||
* Already-uploaded resident keys are kept in sync with native `result.keys`. */
|
||||
#stopWarm() {
|
||||
if (this.#abort && !this.#abort.signal.aborted) {
|
||||
this.#keys.clear();
|
||||
this.#abort.abort();
|
||||
}
|
||||
}
|
||||
|
|
@ -151,6 +182,15 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
// Android picks its paper surface for this column count before the upload.
|
||||
const columns = this.host.getColumnCount?.() ?? 1;
|
||||
const result = await this.#call({ op: 'capture', key, requestId, columns, ...rect });
|
||||
signal?.removeEventListener('abort', cancel);
|
||||
// Even if this capture was aborted mid-flight, an upload that already completed on
|
||||
// native may have evicted an older texture, so drop what native no longer holds.
|
||||
// Native's list never adds a page back: one retaken as stale (`refreshCurrentPage`)
|
||||
// stays out, and the aborted upload is dropped by its own `abortCapture`.
|
||||
if (generation === this.#generation && result.keys && !this.#invalidationHeld) {
|
||||
const resident = new Set(result.keys);
|
||||
for (const page of this.#keys) if (!resident.has(page)) this.#keys.delete(page);
|
||||
}
|
||||
if (
|
||||
generation !== this.#generation ||
|
||||
signal?.aborted ||
|
||||
|
|
@ -158,9 +198,7 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
result.ready === false
|
||||
)
|
||||
return false;
|
||||
// A held invalidation will delete the other pages native reports.
|
||||
if (result.keys && !this.#invalidationHeld) this.#keys = new Set(result.keys);
|
||||
else this.#keys.add(key);
|
||||
this.#keys.add(key);
|
||||
while (this.#keys.size > 3) this.#keys.delete(this.#keys.values().next().value!);
|
||||
return true;
|
||||
} finally {
|
||||
|
|
@ -182,26 +220,64 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
const rect = this.#rect();
|
||||
const key = this.#key();
|
||||
if (!rect || !key || !this.#allowed()) return Promise.resolve(false);
|
||||
const currentOnly = this.#touchRetained;
|
||||
const primary = this.#lastForward ? 1 : -1;
|
||||
const deltas = !currentOnly && this.native.renderer.previewPage ? [primary, -primary] : [];
|
||||
const missingAdjacent = deltas.some((delta) => {
|
||||
const adjacent = this.#key(delta);
|
||||
return !!adjacent && !this.#keys.has(adjacent);
|
||||
});
|
||||
if (this.#keys.has(key) && !missingAdjacent) return Promise.resolve(true);
|
||||
const abort = new AbortController();
|
||||
this.#abort = abort;
|
||||
const run = (async () => {
|
||||
if (!(await this.#capture(key, rect, abort.signal))) return false;
|
||||
if (abort.signal.aborted) return false;
|
||||
await this.#call({ op: 'cover', key, ...rect });
|
||||
if (abort.signal.aborted || this.#touchRetained) return !abort.signal.aborted;
|
||||
const toWarm = deltas.filter((delta) => {
|
||||
const adjacent = this.#key(delta);
|
||||
return !!adjacent && !this.#keys.has(adjacent);
|
||||
});
|
||||
if (toWarm.length === 0) return true;
|
||||
const coverResult = await this.#call({ op: 'cover', key, ...rect });
|
||||
if (coverResult.ready === false) return false;
|
||||
let covered = true;
|
||||
try {
|
||||
for (const forward of this.native.renderer.previewPage ? [true, false] : []) {
|
||||
if (abort.signal.aborted || !this.#allowed()) break;
|
||||
const adjacent = this.#key(forward ? 1 : -1);
|
||||
for (const delta of toWarm) {
|
||||
if (abort.signal.aborted || this.#touchRetained || !this.#allowed()) break;
|
||||
const adjacent = this.#key(delta);
|
||||
if (!adjacent || this.#keys.has(adjacent)) continue;
|
||||
await this.native.renderer.previewPage!(
|
||||
forward,
|
||||
() => this.#capture(adjacent, rect, abort.signal),
|
||||
abort.signal,
|
||||
);
|
||||
this.#warmingKey = adjacent;
|
||||
this.#warmingDelta = delta;
|
||||
try {
|
||||
await this.native.renderer.previewPage!(
|
||||
delta > 0,
|
||||
() => this.#capture(adjacent, rect, abort.signal),
|
||||
abort.signal,
|
||||
);
|
||||
} finally {
|
||||
this.#warmingKey = null;
|
||||
this.#warmingDelta = null;
|
||||
}
|
||||
if (this.#warmingStopAfterKey !== null && this.#warmingStopAfterKey === adjacent) break;
|
||||
}
|
||||
} catch (error) {
|
||||
covered = false;
|
||||
throw error;
|
||||
} finally {
|
||||
await Promise.allSettled([...this.#cancellations]);
|
||||
await this.#call({ op: 'idle' });
|
||||
const handoffCover =
|
||||
covered &&
|
||||
this.#warmingHandoffToTurnId !== null &&
|
||||
this.#warmingHandoffToTurnId === this.#turn &&
|
||||
!this.#invalidationHeld &&
|
||||
!this.#dead &&
|
||||
this.#allowed() &&
|
||||
this.#keys.has(key);
|
||||
if (handoffCover) {
|
||||
this.#coverHeld = true;
|
||||
} else {
|
||||
await this.#call({ op: 'idle' });
|
||||
}
|
||||
}
|
||||
return !abort.signal.aborted;
|
||||
})()
|
||||
|
|
@ -210,7 +286,13 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
return false;
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.#warming === run) this.#warming = null;
|
||||
if (this.#warming === run) {
|
||||
this.#warming = null;
|
||||
this.#warmingKey = null;
|
||||
this.#warmingDelta = null;
|
||||
this.#warmingStopAfterKey = null;
|
||||
this.#warmingHandoffToTurnId = null;
|
||||
}
|
||||
if (this.#abort === abort) this.#abort = null;
|
||||
this.#releaseInvalidation();
|
||||
});
|
||||
|
|
@ -218,11 +300,18 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
return run;
|
||||
}
|
||||
|
||||
/** Stop native warm-up when a gesture leases the prepared surface. */
|
||||
/** Return a previewed page to the live paginator on contact. A capture of the
|
||||
* current page leaves the viewport alone, so it keeps running. */
|
||||
override retainPreparedCapture() {
|
||||
this.#stopWarm();
|
||||
this.#touchRetained = true;
|
||||
if (this.#warmingKey) this.#stopWarm();
|
||||
super.retainPreparedCapture();
|
||||
}
|
||||
/** Release touch retention so subsequent idle warm-ups can preview neighbours again. */
|
||||
override releasePreparedCapture() {
|
||||
this.#touchRetained = false;
|
||||
super.releasePreparedCapture();
|
||||
}
|
||||
/** Cancel incomplete preparation while retaining reusable settled captures. */
|
||||
override invalidatePendingPreparedCapture() {
|
||||
this.#stopWarm();
|
||||
|
|
@ -231,8 +320,11 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
/** Invalidate preparation and cancel an active scene when interaction becomes blocked. */
|
||||
override invalidatePreparedCapture() {
|
||||
this.#stopWarm();
|
||||
if (this.#scene && !this.#allowed())
|
||||
if (this.#scene && !this.#allowed()) {
|
||||
// Native `cancel` hides its sheet, so the reader must show again.
|
||||
this.#thawWebView();
|
||||
void this.#call({ op: 'cancel', turnId: this.#scene.session.id }).catch(() => {});
|
||||
}
|
||||
super.invalidatePreparedCapture();
|
||||
}
|
||||
/** Retake the page on screen at the next warm-up. Its pixels changed after its
|
||||
|
|
@ -249,6 +341,7 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
this.#abort?.abort();
|
||||
this.#generation++;
|
||||
this.#keys.clear();
|
||||
this.#coverHeld = false;
|
||||
this.#invalidationHeld = true;
|
||||
this.#releaseInvalidation();
|
||||
}
|
||||
|
|
@ -272,12 +365,23 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
): Promise<boolean> {
|
||||
if (!this.#eligible(style)) return super.beginDrag(forward, rtl, style);
|
||||
this.#claim();
|
||||
this.#stopWarm();
|
||||
this.#lastForward = forward;
|
||||
// The turn takes over the touch, so warm-ups after it preview neighbours again.
|
||||
this.#touchRetained = false;
|
||||
if (this.#scene && !this.#session)
|
||||
void this.#call({ op: 'complete', turnId: this.#scene.session.id }).catch(() => {});
|
||||
if (this.#session) void this.endDrag(false).catch(() => {});
|
||||
const session: Session = { id: ++this.#turn, released: false, progress: 0, grabY: 0.5 };
|
||||
this.#session = session;
|
||||
if (this.#warming) {
|
||||
const wantedDelta = forward ? 1 : -1;
|
||||
this.#warmingHandoffToTurnId = session.id;
|
||||
if (this.#warmingKey && this.#warmingDelta === wantedDelta) {
|
||||
this.#warmingStopAfterKey = this.#warmingKey;
|
||||
} else {
|
||||
this.#stopWarm();
|
||||
}
|
||||
}
|
||||
const run = this.#queue.then(async () => {
|
||||
await this.#warming;
|
||||
if (!this.#allowed()) return false;
|
||||
|
|
@ -285,7 +389,13 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
const rect = this.#rect();
|
||||
const key = this.#key();
|
||||
if (!rect || !key) return false;
|
||||
const scene: Scene = { session, forward, navigated: false, touchTracked: false };
|
||||
const scene: Scene = {
|
||||
session,
|
||||
forward,
|
||||
navigated: false,
|
||||
started: false,
|
||||
touchTracked: false,
|
||||
};
|
||||
this.#scene = scene;
|
||||
try {
|
||||
await this.host.onBeforeCapture?.('curl');
|
||||
|
|
@ -293,8 +403,10 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
const resident = !!destination && this.#keys.has(key) && this.#keys.has(destination);
|
||||
if (!(await this.#capture(key, rect))) return false;
|
||||
if (!resident) {
|
||||
const covered = await this.#call({ op: 'cover', key, turnId: session.id, ...rect });
|
||||
if (covered.ready === false) throw new Error('Native paper ownership changed');
|
||||
if (!this.#coverHeld) {
|
||||
const covered = await this.#call({ op: 'cover', key, turnId: session.id, ...rect });
|
||||
if (covered.ready === false) throw new Error('Native paper ownership changed');
|
||||
}
|
||||
await this.host.onCovered?.('curl', true);
|
||||
}
|
||||
if (!this.#allowed()) return false;
|
||||
|
|
@ -318,6 +430,8 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
await this.#capture(destination, rect);
|
||||
}
|
||||
if (!destination || !this.#keys.has(destination) || !this.#allowed()) return false;
|
||||
const startProgress = session.progress;
|
||||
const startGrabY = session.grabY;
|
||||
const result = await this.#call({
|
||||
op: 'start',
|
||||
turnId: session.id,
|
||||
|
|
@ -326,15 +440,26 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
destination,
|
||||
forward,
|
||||
rtl,
|
||||
progress: session.progress,
|
||||
grabY: session.grabY,
|
||||
progress: startProgress,
|
||||
grabY: startGrabY,
|
||||
// A spread turns its outer column as a leaf hinged at the spine.
|
||||
columns: this.host.getColumnCount?.() ?? 1,
|
||||
// The native scene may still curl, e.g. a spread.
|
||||
flip: this.host.isPageFlip?.() ?? false,
|
||||
});
|
||||
if (result.ready === false) throw new Error('Native paper scene was not started');
|
||||
if (this.#dead || this.#scene !== scene || !this.#allowed()) return false;
|
||||
this.#coverHeld = false;
|
||||
this.#freezeWebView();
|
||||
scene.started = true;
|
||||
scene.touchTracked = result.touchTracked === true;
|
||||
if (
|
||||
!scene.touchTracked &&
|
||||
!session.released &&
|
||||
(session.progress !== startProgress || session.grabY !== startGrabY)
|
||||
) {
|
||||
this.moveDrag(session.progress, session.grabY);
|
||||
}
|
||||
if (resident) await this.host.onCovered?.('curl', true);
|
||||
return true;
|
||||
} catch (error) {
|
||||
|
|
@ -348,6 +473,10 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
async (started) => {
|
||||
if (!started && this.#scene?.session === session) await this.#restore(this.#scene);
|
||||
if (!started && this.#session === session) this.#session = null;
|
||||
if (!started && this.#coverHeld && this.#turn === session.id && !this.#session) {
|
||||
this.#coverHeld = false;
|
||||
await this.#call({ op: 'idle' }).catch(() => {});
|
||||
}
|
||||
return started;
|
||||
},
|
||||
(error) => {
|
||||
|
|
@ -369,7 +498,14 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
session.progress = Math.max(0, Math.min(1, progress));
|
||||
session.grabY = grabY;
|
||||
const scene = this.#scene;
|
||||
if (!scene || scene.session !== session || scene.touchTracked || this.#moveRaf) return;
|
||||
if (
|
||||
!scene ||
|
||||
scene.session !== session ||
|
||||
!scene.started ||
|
||||
scene.touchTracked ||
|
||||
this.#moveRaf
|
||||
)
|
||||
return;
|
||||
this.#moveRaf = requestAnimationFrame(() => {
|
||||
this.#moveRaf = 0;
|
||||
if (this.#scene === scene)
|
||||
|
|
@ -407,15 +543,28 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
if (this.#turn > session.id)
|
||||
void this.#call({ op: 'complete', turnId: session.id }).catch(() => {});
|
||||
const result = await settling;
|
||||
this.#thawWebView();
|
||||
const confirmed = commit && !result.cancelled && this.#allowed();
|
||||
if (confirmed && !scene.navigated) await this.#navigate(scene.forward);
|
||||
if (!confirmed && scene.navigated) await this.#navigate(!scene.forward);
|
||||
// The final reading position is settled. A later presentation error
|
||||
// must not undo a committed turn or repeat an already completed rollback.
|
||||
scene.navigated = false;
|
||||
if (confirmed) this.#lastForward = scene.forward;
|
||||
if (!confirmed) await this.host.onCancelled?.('curl');
|
||||
// Native visual-state/frame-commit synchronization happens before hide.
|
||||
await this.#call({ op: 'finish', turnId: session.id });
|
||||
// When another turn is already queued behind this one, keep the native
|
||||
// cover up instead of dropping it and re-covering for the next page.
|
||||
const keepCover =
|
||||
confirmed &&
|
||||
!this.#invalidationHeld &&
|
||||
this.#allowed() &&
|
||||
(this.#turn > session.id || this.#session !== null);
|
||||
const finishResult = await this.#call({
|
||||
op: 'finish',
|
||||
turnId: session.id,
|
||||
...(keepCover ? { keepCover: true } : {}),
|
||||
});
|
||||
this.#coverHeld = keepCover && !this.#invalidationHeld && finishResult.coverHeld === true;
|
||||
} catch (error) {
|
||||
await this.#restore(scene);
|
||||
throw error;
|
||||
|
|
@ -432,6 +581,11 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
async #restore(scene: Scene) {
|
||||
if (this.#scene !== scene) return;
|
||||
this.#scene = null;
|
||||
// A held cover still carries the turn id that raised it, so native drops
|
||||
// this scene's `finish`; it is lowered with `idle` instead.
|
||||
const coverHeld = this.#coverHeld;
|
||||
this.#coverHeld = false;
|
||||
this.#thawWebView();
|
||||
this.#restoring = true;
|
||||
// A native failure can destroy the EGL context and its whole texture bank.
|
||||
this.#keys.clear();
|
||||
|
|
@ -440,6 +594,7 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
await this.host.onCancelled?.('curl');
|
||||
} finally {
|
||||
await this.#call({ op: 'finish', turnId: scene.session.id }).catch(() => {});
|
||||
if (coverHeld) await this.#call({ op: 'idle' }).catch(() => {});
|
||||
this.#restoring = false;
|
||||
this.#releaseInvalidation();
|
||||
}
|
||||
|
|
@ -463,6 +618,7 @@ export class NativePageTurn extends CapturedPageTurn {
|
|||
if (nativeOwner === this) nativeOwner = null;
|
||||
this.#abort?.abort();
|
||||
cancelAnimationFrame(this.#moveRaf);
|
||||
this.#thawWebView();
|
||||
this.#keys.clear();
|
||||
this.#scene = null;
|
||||
this.#session = null;
|
||||
|
|
|
|||
|
|
@ -1860,3 +1860,8 @@
|
|||
animation: none;
|
||||
transition: none;
|
||||
}
|
||||
|
||||
/* The native turn sheet covers the turning cell, so its webview does not repaint while it plays. */
|
||||
[data-native-turn-frozen] foliate-view {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue