Skip to content
Merged
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
10 changes: 9 additions & 1 deletion docs/advanced/preinteraction-capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,18 @@ A request must already have reached native with eligible sources. Before the fir

An iOS host can set `stopScrollBeforeCapture: true` on `prepare` requests to use the same policy as its native activation setting. The default is `false` for existing hosts. While this policy is enabled, idle acquisition waits while any descendant scroll view is tracking, dragging or decelerating; it does not stop a user's scroll in the background. The existing preparation deadline and Web fallback remain in effect.

At the next contact, Engine checks the hit view against the native views supplied for the requested IDs. Only contact inside those native views cancels momentum. All registered owners settle that motion before any owner pins pixels, then the capture remeasures frames instead of using the pre-stop validation geometry. Acquisition still precedes UIKit's highlight and gesture dispatch. Contact in Web content does not invoke this cancellation, and an unregistered window rejects this policy without stopping anything.
At the next contact, Engine checks the hit view against the native views supplied for the requested IDs. Only contact inside those native views cancels momentum. All registered owners stop that motion and apply layout before any owner pins pixels. Each promoted capture then remeasures current frames and acquires pixels instead of using the pre-stop validation geometry. Contact promotion does not wait for another idle period. Acquisition still precedes UIKit's highlight and gesture dispatch. Contact in Web content does not invoke this cancellation, and an unregistered window rejects this policy without stopping anything.

This cancels the current fling without disabling scrolling. PNG encoding and decoding remain asynchronous, so stopping momentum is not a guarantee that every capture succeeds. Empty, stale or failed captures retain the normal Web fallback. Hosts should retain their activation-time cancellation for actions without a prepared capture. Disable this request flag when the application's `stopScrollOnActivate` setting is `false`.

## Scroll invalidation

Scroll tracking and notifications remain necessary for SDK views such as AdMob: they keep image placement synchronized during scrolling and invalidate composited pixels when the backdrop changes, including behind fixed translucent controls. Taps and long presses remain native input.

A scroll-origin `change` uses `retainPending: true` to retire completed pixels from next-contact selection while preserving a live request that has not acquired pixels. Its frame callback reads current geometry when acquisition runs; a replacement `prepare` atomically retires the older request. This keeps a request available for contact promotion between the scroll notification and the next `prepare`. Source/content invalidation, reset and replacement retain their normal cancellation behavior.

The document scroll listener covers standalone Engine integrations and background motion; renderer-provided `changed(owner)` also covers scrolling within Shadow DOM that does not reach the document. Both entry points are needed, although Light DOM integrations can report the same event through both paths.

## Idle capture

The Web manager observes document DOM changes, scrolling and resource loads in addition to renderer updates. Engine-owned projection nodes, attributes and image loads are excluded. The native request is armed immediately after coalescing notifications, rather than waiting for the entire debounce on the Web side.
Expand Down
10 changes: 8 additions & 2 deletions ios/Sources/WebViewNativeUIEngine/CoveredSnapshots.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,12 @@ public final class NativeUICoveredSnapshots {
}
}

func invalidateAcquisition(owner: String? = nil) {
func invalidateAcquisition(owner: String? = nil, retainPending: Bool = false) {
let retired = owner.map { acquisitions[$0].map { [$0] } ?? [] } ?? Array(acquisitions.values)
for job in retired {
// The next prepare replaces this lease atomically. Until then a
// contact can still measure current frames and acquire fresh pixels.
if retainPending, !job.pixels, job.run != nil { continue }
acquisitions.removeValue(forKey: job.owner)
if !job.pinned { job.cancel?() }
}
Expand Down Expand Up @@ -217,7 +220,10 @@ public final class NativeUICoveredSnapshots {
case "painted", "restored":
retireCopy(token, entry: request["action"] as? String == "painted")
complete(request["action"] as? String == "painted" ? ["shown": captures[token] != nil] : [:])
case "change": invalidateAcquisition(owner: request["captureOwner"] as? String); complete([:])
case "change":
invalidateAcquisition(owner: request["captureOwner"] as? String,
retainPending: request["retainPending"] as? Bool == true)
complete([:])
case "release": release(token); complete([:])
case "reset": reset(); complete([:])
default: complete([:])
Expand Down
37 changes: 37 additions & 0 deletions ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,43 @@ import WebKit
@testable import WebViewNativeUIEngine

final class NativeUICoveredSnapshotsTests: XCTestCase {
@MainActor func testScrollChangeRetainsLivePendingGeometryButNotCompletedPixels() async throws {
let window = SnapshotTestWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIViewController(); window.makeKeyAndVisible()
let web = try XCTUnwrap(window.rootViewController?.view)
let control = UIView(frame: CGRect(x: 40, y: 100, width: 60, height: 44))
web.addSubview(control)
let snapshots = NativeUICoveredSnapshots()
var events: [[String: Any]] = []
snapshots.observeInteractions(window) { events.append($0) }
defer { snapshots.reset(); window.isHidden = true }
let ready = expectation(description: "contact acquires pending scroll pixels")
var result: [String: Any]?
var measuredY: CGFloat = 0
snapshots.handle(["action": "prepare", "ids": ["control"], "revision": 1,
"captureID": "moving", "captureOwner": "page", "captureDelayMs": 500,
"viewportWidth": Double(web.bounds.width), "stopScrollBeforeCapture": true], in: web,
frames: { _, _ in measuredY = control.frame.minY; return ["control": control.frame] },
views: { _ in [control] }, complete: { value in result = value; ready.fulfill() })
func changed() {
snapshots.handle(["action": "change", "captureOwner": "page", "retainPending": true], in: web,
frames: { _, _ in [:] }, views: { _ in [] }, complete: { _ in })
}
changed()
XCTAssertNil(result, "A scroll must not cancel the only pending contact acquisition")
control.frame.origin.y = 160
snapshots.pinBeforeInteraction(touchedViews: [control])
XCTAssertEqual(measuredY, 160, "Contact measures current geometry, never a pre-scroll frame")
XCTAssertEqual(window.draws, 1)
await fulfillment(of: [ready], timeout: 3)
XCTAssertNotNil(result?["token"])
let previousEvents = events.count
changed()
snapshots.pinBeforeInteraction(touchedViews: [control])
XCTAssertEqual(events.count, previousEvents, "Completed pre-scroll pixels cannot be selected by the next contact")
XCTAssertEqual(window.draws, 1)
}

@MainActor func testCompletedCaptureCannotCoverAnotherWindowWithIdenticalGeometry() async throws {
let first = SnapshotTestWindow(frame: UIScreen.main.bounds)
first.rootViewController = UIViewController(); first.makeKeyAndVisible()
Expand Down
6 changes: 4 additions & 2 deletions src/projection/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,8 @@ const createProjectionEngine = async (scope: WebProjectionScope, transport: WebP
}
visualRevision++;
generation++;
if (preinteraction) void call({ action: 'change', captureOwner: imageIdentity }).catch(() => {});
if (preinteraction)
void call({ action: 'change', captureOwner: imageIdentity, ...(scrollOwner ? { retainPending: true } : {}) }).catch(() => {});
schedule();
};
const listener = await boundedListener(
Expand Down Expand Up @@ -523,7 +524,8 @@ const createProjectionEngine = async (scope: WebProjectionScope, transport: WebP
});
changes.observe(doc.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
const backgroundChanged = (event: Event) => {
if (preinteraction && !projectionNode(event.target as Node | null)) changed();
if (preinteraction && !projectionNode(event.target as Node | null))
changed(event.type === 'scroll' ? (event.target ?? undefined) : undefined);
};
doc.addEventListener('scroll', backgroundChanged, true);
doc.addEventListener('load', backgroundChanged, true);
Expand Down
7 changes: 6 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,12 @@ export type WebProjectionRequest =
| { action: 'prepared' | 'painted' | 'restored' | 'release'; token: string }
| { action: 'decoded'; token: string }
| { action: 'reset' }
| { action: 'change'; captureOwner?: string };
| {
action: 'change';
captureOwner?: string;
/** Scroll changes retire old pixels while keeping live, unacquired geometry available for contact. */
retainPending?: boolean;
};
/** Empty prepare results mean capture is unavailable; a partial capture is never valid. */
export type WebProjectionResult<Request extends WebProjectionRequest> = Request extends { action: 'prepare' }
? PreparedWebProjection | { token?: never; parts?: never }
Expand Down
18 changes: 18 additions & 0 deletions tests/projection/web.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1612,6 +1612,24 @@ const beginDelayedReturn = async (page: Page) => {
await expect.poll(() => page.evaluate(() => !!(window as any).releaseReply)).toBe(true);
};

test('scroll changes retain pending native acquisition while source invalidation still cancels it', async ({ page }) => {
await prepare(page);
await page.evaluate(() => {
const w = window as any;
w.interact({ active: false, capturePolicy: 'preinteraction' });
w.calls = [];
document.querySelector('#scroll')!.dispatchEvent(new Event('scroll', { bubbles: true }));
});
const changes = await page.evaluate(() => (window as any).calls.filter((call: any) => call.action === 'change'));
expect(changes.length).toBeGreaterThan(0);
expect(changes.every((call: any) => call.retainPending === true)).toBe(true);
await page.evaluate(() => (window as any).manager.invalidate());
expect(
await page.evaluate(() => (window as any).calls.filter((call: any) => call.action === 'change').at(-1).retainPending),
).toBeUndefined();
await destroyProjection(page);
});

test('scrolling followed by modal handoff covers with a decoded PNG instead of Web fallback', async ({ page }) => {
await prepare(page);
await page.evaluate((png) => {
Expand Down
Loading