From 376b630fd91aaa5ffe5c05466409825a993e926f Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 16 Nov 2026 10:28:51 +0900 Subject: [PATCH 1/3] fix: retain pending capture across scroll invalidation --- .../CoveredSnapshots.swift | 10 ++++- .../CoveredSnapshotsTests.swift | 37 +++++++++++++++++++ src/projection/web.ts | 6 ++- src/types.ts | 7 +++- tests/projection/web.spec.ts | 18 +++++++++ 5 files changed, 73 insertions(+), 5 deletions(-) diff --git a/ios/Sources/WebViewNativeUIEngine/CoveredSnapshots.swift b/ios/Sources/WebViewNativeUIEngine/CoveredSnapshots.swift index 077ddf1..100bcef 100644 --- a/ios/Sources/WebViewNativeUIEngine/CoveredSnapshots.swift +++ b/ios/Sources/WebViewNativeUIEngine/CoveredSnapshots.swift @@ -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?() } } @@ -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([:]) diff --git a/ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift b/ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift index 064f3fc..b1258ee 100644 --- a/ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift +++ b/ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift @@ -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() diff --git a/src/projection/web.ts b/src/projection/web.ts index 0cd79b8..dd5c903 100644 --- a/src/projection/web.ts +++ b/src/projection/web.ts @@ -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( @@ -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); diff --git a/src/types.ts b/src/types.ts index 347ebd3..a8b5799 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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 { action: 'prepare' } ? PreparedWebProjection | { token?: never; parts?: never } diff --git a/tests/projection/web.spec.ts b/tests/projection/web.spec.ts index 0f970b7..f0e995c 100644 --- a/tests/projection/web.spec.ts +++ b/tests/projection/web.spec.ts @@ -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) => { From d60ff3398b2ace14bdfe82488a4b55e47283c10f Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 16 Nov 2026 10:42:59 +0900 Subject: [PATCH 2/3] docs: clarify scroll notifications and capture ordering --- docs/advanced/preinteraction-capture.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/advanced/preinteraction-capture.md b/docs/advanced/preinteraction-capture.md index 3a3b0eb..772c9ff 100644 --- a/docs/advanced/preinteraction-capture.md +++ b/docs/advanced/preinteraction-capture.md @@ -22,6 +22,28 @@ Custom transports should use `observeInteractions(_:changed:)`, forward the enti Apple documents [Window event dispatch](https://developer.apple.com/documentation/uikit/uiwindow/sendevent%28_%3A%29) and [adding an inherited-method override](https://developer.apple.com/documentation/objectivec/class_addmethod%28_%3A_%3A_%3A_%3A%29). A [gesture recognizer receives touches before its attached view](https://developer.apple.com/documentation/uikit/uigesturerecognizer/touchesbegan%28_%3Awith%3A%29); that does not establish its ordering relative to other recognizers implementing press appearance, so it is not used as the pre-dispatch guarantee. +## Scrolling, image handoff and native activation + +Scroll observation remains necessary for SDK views such as AdMob. Offset tracking and image handoff let the Web image follow scrolling without taking taps or long presses away from the native view. A scroll can also change the backdrop behind fixed translucent controls, so completed composited pixels must lose next-contact eligibility even when the control's own frame is unchanged. + +These responsibilities are distinct: + +| Signal or operation | Responsibility | +| ------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| Native scroll hosting / placement tracking | Synchronize the native view and Web scroller while preserving native input | +| Scroll and renderer motion notifications | Update image placement and invalidate pixels whose background or layout changed | +| Scroll-origin `change` with `retainPending` | Retire completed pixels, but preserve a live request that has not read pixels yet | +| Source/content invalidation, reset or replacement | Cancel obsolete requests using the normal invalidation path | +| Pre-dispatch native contact | Stop configured momentum, apply layout, measure current frames and acquire pixels in that order | + +Stopping is not a new scroll notification or a request to wait for another idle period. When contact promotes a pending request, native runs its existing callback immediately after cancellation and layout, before forwarding input. PNG conversion, delivery and Web decoding remain asynchronous. Idle preparation still waits for stable geometry, and a completed valid image still needs no new acquisition. + +Do not cancel an unacquired request just because scrolling changed its geometry. Its frame callback reads current geometry at acquisition; the replacement `prepare` atomically retires the older request. Cancelling it earlier creates a gap between `change` and the next bridge request, exactly when another native contact may arrive. + +The document scroll listener covers standalone Engine integrations and background motion. A renderer's explicit `changed(owner)` also covers scrolls within Shadow DOM and other events that never reach the document. Both entry points are required. Light DOM integrations can report the same event through both paths. This is redundant work, but does not justify removing either path. Time-window/position deduplication must also respect capture-generation boundaries; the same coordinate after a new acquisition is not the same invalidation. Event-origin deduplication can be evaluated separately if bridge cost warrants it. + +This capture fix retains the required scroll notifications and removes only their unnecessary cancellation of live, unacquired requests. It does not replace native scroll tracking, remove SDK image switching, or change tap/long-press ownership. + ## State and ownership A capture has an owner, request ID and lifecycle epoch. Initial DOM construction and subsequent changes use the same invalidation path. From a59cc02a92279257dd53d35f119538cb38942aa9 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 16 Nov 2026 10:53:44 +0900 Subject: [PATCH 3/3] docs: consolidate pre-interaction capture guidance --- docs/advanced/preinteraction-capture.md | 32 +++++++------------------ 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/docs/advanced/preinteraction-capture.md b/docs/advanced/preinteraction-capture.md index 772c9ff..93c216d 100644 --- a/docs/advanced/preinteraction-capture.md +++ b/docs/advanced/preinteraction-capture.md @@ -22,28 +22,6 @@ Custom transports should use `observeInteractions(_:changed:)`, forward the enti Apple documents [Window event dispatch](https://developer.apple.com/documentation/uikit/uiwindow/sendevent%28_%3A%29) and [adding an inherited-method override](https://developer.apple.com/documentation/objectivec/class_addmethod%28_%3A_%3A_%3A_%3A%29). A [gesture recognizer receives touches before its attached view](https://developer.apple.com/documentation/uikit/uigesturerecognizer/touchesbegan%28_%3Awith%3A%29); that does not establish its ordering relative to other recognizers implementing press appearance, so it is not used as the pre-dispatch guarantee. -## Scrolling, image handoff and native activation - -Scroll observation remains necessary for SDK views such as AdMob. Offset tracking and image handoff let the Web image follow scrolling without taking taps or long presses away from the native view. A scroll can also change the backdrop behind fixed translucent controls, so completed composited pixels must lose next-contact eligibility even when the control's own frame is unchanged. - -These responsibilities are distinct: - -| Signal or operation | Responsibility | -| ------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| Native scroll hosting / placement tracking | Synchronize the native view and Web scroller while preserving native input | -| Scroll and renderer motion notifications | Update image placement and invalidate pixels whose background or layout changed | -| Scroll-origin `change` with `retainPending` | Retire completed pixels, but preserve a live request that has not read pixels yet | -| Source/content invalidation, reset or replacement | Cancel obsolete requests using the normal invalidation path | -| Pre-dispatch native contact | Stop configured momentum, apply layout, measure current frames and acquire pixels in that order | - -Stopping is not a new scroll notification or a request to wait for another idle period. When contact promotes a pending request, native runs its existing callback immediately after cancellation and layout, before forwarding input. PNG conversion, delivery and Web decoding remain asynchronous. Idle preparation still waits for stable geometry, and a completed valid image still needs no new acquisition. - -Do not cancel an unacquired request just because scrolling changed its geometry. Its frame callback reads current geometry at acquisition; the replacement `prepare` atomically retires the older request. Cancelling it earlier creates a gap between `change` and the next bridge request, exactly when another native contact may arrive. - -The document scroll listener covers standalone Engine integrations and background motion. A renderer's explicit `changed(owner)` also covers scrolls within Shadow DOM and other events that never reach the document. Both entry points are required. Light DOM integrations can report the same event through both paths. This is redundant work, but does not justify removing either path. Time-window/position deduplication must also respect capture-generation boundaries; the same coordinate after a new acquisition is not the same invalidation. Event-origin deduplication can be evaluated separately if bridge cost warrants it. - -This capture fix retains the required scroll notifications and removes only their unnecessary cancellation of live, unacquired requests. It does not replace native scroll tracking, remove SDK image switching, or change tap/long-press ownership. - ## State and ownership A capture has an owner, request ID and lifecycle epoch. Initial DOM construction and subsequent changes use the same invalidation path. @@ -62,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.