From cc35cc493c0abc610ff61cc6452cbfc8a290366e Mon Sep 17 00:00:00 2001 From: rdlabo Date: Sat, 28 Nov 2026 20:45:40 +0900 Subject: [PATCH 1/7] Share projection measurement and document-bound UI lifecycle --- android/build.gradle | 3 + .../engine/NativeUIActivityLifecycle.kt | 43 ++++++++ .../engine/NativeUIActivityLifecycleTest.kt | 27 ++++++ docs/reference/platforms.md | 22 +++++ .../DocumentObservation.swift | 38 ++++++++ .../DocumentObservationTests.swift | 37 +++++++ src/dom/placement.ts | 97 +++++++++++++++++++ src/index.ts | 1 + tests/dom/placement.spec.ts | 55 +++++++++++ 9 files changed, 323 insertions(+) create mode 100644 android/src/main/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycle.kt create mode 100644 android/src/test/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycleTest.kt create mode 100644 ios/Sources/WebViewNativeUIEngine/DocumentObservation.swift create mode 100644 ios/Tests/WebViewNativeUIEngineTests/DocumentObservationTests.swift create mode 100644 src/dom/placement.ts create mode 100644 tests/dom/placement.spec.ts diff --git a/android/build.gradle b/android/build.gradle index ff826ec..3ed63f1 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -23,8 +23,11 @@ android { publishing { singleVariant('release') { withSourcesJar(); withJavadocJar() } } } dependencies { + api 'androidx.lifecycle:lifecycle-common:2.8.7' implementation 'androidx.webkit:webkit:1.14.0' implementation 'androidx.annotation:annotation:1.9.1' + testImplementation 'junit:junit:4.13.2' + testImplementation 'androidx.lifecycle:lifecycle-runtime:2.8.7' androidTestImplementation 'androidx.test:runner:1.6.2' androidTestImplementation 'androidx.test.ext:junit:1.2.1' } diff --git a/android/src/main/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycle.kt b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycle.kt new file mode 100644 index 0000000..db445d4 --- /dev/null +++ b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycle.kt @@ -0,0 +1,43 @@ +package io.github.webview_native_ui.engine + +import android.app.Activity +import androidx.annotation.MainThread +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner + +/** Native SDK work queued for an activity must recheck its owner when it runs. */ +object NativeUIActivityLifecycle { + @JvmStatic + fun isAvailable(activity: Activity?): Boolean = + activity != null && !activity.isFinishing && !activity.isDestroyed + + /** Check again on the UI thread, immediately before creating or presenting SDK UI. */ + @JvmStatic + fun runOnUiThread(activity: Activity?, unavailable: Runnable, action: Runnable) { + if (activity == null) unavailable.run() + else + activity.runOnUiThread { + if (isAvailable(activity)) action.run() else unavailable.run() + } + } + + /** Register SDK-specific teardown once, including when the owner is already destroyed. */ + @JvmStatic + @MainThread + fun onDestroy(owner: LifecycleOwner, release: Runnable) { + val lifecycle = owner.lifecycle + if (lifecycle.currentState == Lifecycle.State.DESTROYED) { + release.run() + return + } + lifecycle.addObserver( + object : DefaultLifecycleObserver { + override fun onDestroy(owner: LifecycleOwner) { + owner.lifecycle.removeObserver(this) + release.run() + } + } + ) + } +} diff --git a/android/src/test/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycleTest.kt b/android/src/test/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycleTest.kt new file mode 100644 index 0000000..204990a --- /dev/null +++ b/android/src/test/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycleTest.kt @@ -0,0 +1,27 @@ +package io.github.webview_native_ui.engine + +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import org.junit.Assert.assertEquals +import org.junit.Test + +class NativeUIActivityLifecycleTest { + @Test + fun releasesEachRegistrationOnceIncludingLateOwners() { + val owner = + object : LifecycleOwner { + override val lifecycle = LifecycleRegistry.createUnsafe(this) + } + var count = 0 + owner.lifecycle.currentState = Lifecycle.State.CREATED + NativeUIActivityLifecycle.onDestroy(owner) { count++ } + NativeUIActivityLifecycle.onDestroy(owner) { count++ } + assertEquals(0, count) + owner.lifecycle.currentState = Lifecycle.State.DESTROYED + assertEquals(2, count) + assertEquals(0, owner.lifecycle.observerCount) + NativeUIActivityLifecycle.onDestroy(owner) { count++ } + assertEquals(3, count) + } +} diff --git a/docs/reference/platforms.md b/docs/reference/platforms.md index d461cba..fc24967 100644 --- a/docs/reference/platforms.md +++ b/docs/reference/platforms.md @@ -140,3 +140,25 @@ Prepared images stay in the app's private temporary storage. iOS uses `FileManag `Capacitor.convertFileSrc` maps the returned file URL to the existing WebView local server. It grants no filesystem permission and does not upload the image. If the application sets a Content Security Policy, its `img-src` must allow the local app origin used by that URL; do not enable broad `file:` access or unrelated WebView file-access settings. `release(token)` and owner teardown remove owned snapshot files. Abrupt process termination can leave temporary images until the operating system clears the cache or the app is uninstalled; immediate deletion after a crash is not guaranteed. Keep this storage private and treat it as disposable, not persistent application data. + +## Document-bound SDK views + +Measure the DOM host with `measureProjectionFrame(element)`. The returned frame +and clip use viewport CSS pixels and account for scaled, axis-aligned overflow +ancestors, including slots and shadow hosts. A renderer that owns native scrolling +can pass `scrollOwner` and translate the result into that container's coordinates. +Use `observeProjectionStyles(elements, update)` alongside scroll and resize events +to remeasure when an author attribute changes. Disconnect it on teardown and +rebind when the host or its ancestors change. + +On iOS, retain a `NativeUIDocumentObservation(webView:onReplacement:)` when +the first document-bound session starts. Its closure runs at the start of the +next main document in that WebView, including a reload after WebContent process +termination. Release resources and discard pending bridge replies for the old +document there. Capture the session owner weakly. + +On Android, register SDK teardown in `NativeUIActivityLifecycle.onDestroy(owner, release)` +on the main thread. Queue SDK presentation with +`NativeUIActivityLifecycle.runOnUiThread(activity, unavailable, action)` so a +finishing or destroyed Activity is checked when queued work actually runs. +The plugin supplies the SDK cleanup and the response to a cancelled operation. diff --git a/ios/Sources/WebViewNativeUIEngine/DocumentObservation.swift b/ios/Sources/WebViewNativeUIEngine/DocumentObservation.swift new file mode 100644 index 0000000..3384fd3 --- /dev/null +++ b/ios/Sources/WebViewNativeUIEngine/DocumentObservation.swift @@ -0,0 +1,38 @@ +import WebKit + +/// Retain the observation for the lifetime of the renderer. Only new main documents trigger cleanup. +@MainActor +public final class NativeUIDocumentObservation { + fileprivate weak var webView: WKWebView? + fileprivate let documentStarted: () -> Void + + public init(webView: WKWebView, onReplacement: @escaping () -> Void) { + self.webView = webView + documentStarted = onReplacement + DocumentHandler.shared(webView.configuration.userContentController).observations.add(self) + } +} + +@MainActor +private final class DocumentHandler: NSObject, WKScriptMessageHandler { + static let handlers = NSMapTable.weakToWeakObjects() + let observations = NSHashTable.weakObjects() + + static func shared(_ controller: WKUserContentController) -> DocumentHandler { + if let existing = handlers.object(forKey: controller) { return existing } + let handler = DocumentHandler() + let world = WKContentWorld.world(name: "WebViewNativeUIEngine.Document") + controller.add(handler, contentWorld: world, name: "documentStarted") + controller.addUserScript(WKUserScript(source: "window.webkit.messageHandlers.documentStarted.postMessage(null)", + injectionTime: .atDocumentStart, forMainFrameOnly: true, in: world)) + handlers.setObject(handler, forKey: controller) + return handler + } + + func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + guard message.frameInfo.isMainFrame, let source = message.webView else { return } + for observation in observations.allObjects where observation.webView === source { + observation.documentStarted() + } + } +} diff --git a/ios/Tests/WebViewNativeUIEngineTests/DocumentObservationTests.swift b/ios/Tests/WebViewNativeUIEngineTests/DocumentObservationTests.swift new file mode 100644 index 0000000..9c899ea --- /dev/null +++ b/ios/Tests/WebViewNativeUIEngineTests/DocumentObservationTests.swift @@ -0,0 +1,37 @@ +import WebKit +import XCTest +import WebViewNativeUIEngine + +@MainActor +final class DocumentObservationTests: XCTestCase { + func testObservationFollowsItsWebViewAndTokenLifetime() async { + let configuration = WKWebViewConfiguration() + let first = WKWebView(frame: .zero, configuration: configuration) + let second = WKWebView(frame: .zero, configuration: configuration) + var firstCount = 0 + var secondCount = 0 + var pending = expectation(description: "First document") + let retained = NativeUIDocumentObservation(webView: first) { + firstCount += 1 + pending.fulfill() + } + var extra: NativeUIDocumentObservation? = NativeUIDocumentObservation(webView: first) { + secondCount += 1 + } + let otherDocument = expectation(description: "Other WebView") + let other = NativeUIDocumentObservation(webView: second) { otherDocument.fulfill() } + first.loadHTMLString("First", baseURL: nil) + await fulfillment(of: [pending], timeout: 10) + XCTAssertEqual(secondCount, 1) + XCTAssertNotNil(extra) + extra = nil + second.loadHTMLString("Other", baseURL: nil) + await fulfillment(of: [otherDocument], timeout: 10) + pending = expectation(description: "Replacement document") + first.loadHTMLString("Replacement", baseURL: nil) + await fulfillment(of: [pending], timeout: 10) + XCTAssertEqual(firstCount, 2) + XCTAssertEqual(secondCount, 1) + withExtendedLifetime((retained, other)) {} + } +} diff --git a/src/dom/placement.ts b/src/dom/placement.ts new file mode 100644 index 0000000..bda5b55 --- /dev/null +++ b/src/dom/placement.ts @@ -0,0 +1,97 @@ +import type { Frame } from '../types.js'; +import { projectionAncestors } from './geometry.js'; +import { getUnprojectedVisibility } from './visibility.js'; + +const intersectFrames = (a: Frame, b: Frame): Frame => { + const x = Math.max(a.x, b.x); + const y = Math.max(a.y, b.y); + return { + x, + y, + width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x), + height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y), + }; +}; + +export interface ProjectionFrameOptions { + /** Reuse the viewport bounds already read by the renderer during this layout pass. */ + bounds?: Frame; + /** Optional additional clip, in viewport CSS pixels. */ + visibleArea?: Frame; + /** Native scrolling owns this ancestor and its outer clips. The result still uses viewport coordinates. */ + scrollOwner?: HTMLElement; +} + +/** Measure an axis-aligned host and its visible client area, following slots and shadow hosts. */ +export function measureProjectionFrame( + element: HTMLElement, + options: ProjectionFrameOptions = {}, +): { + frame: Frame; + clip: Frame; + visible: boolean; +} { + const { x, y, width, height } = options.bounds ?? element.getBoundingClientRect(); + const frame = { x, y, width, height }; + const win = element.ownerDocument.defaultView; + if (!win) return { frame, clip: { ...frame, width: 0, height: 0 }, visible: false }; + const viewport = win.visualViewport; + let clip = options.scrollOwner + ? frame + : intersectFrames(frame, { + x: viewport?.offsetLeft ?? 0, + y: viewport?.offsetTop ?? 0, + width: viewport?.width ?? win.innerWidth, + height: viewport?.height ?? win.innerHeight, + }); + const area = options.visibleArea; + if (area && [area.x, area.y, area.width, area.height].every(Number.isFinite)) clip = intersectFrames(clip, area); + let reachedScrollOwner = false; + let transparent = false; + for (const parent of projectionAncestors(element)) { + const style = win.getComputedStyle(parent); + if (style.opacity === '0') transparent = true; + if (parent === options.scrollOwner) reachedScrollOwner = true; + if (reachedScrollOwner) continue; + const clipsX = /^(hidden|scroll|auto|clip)$/.test(style.overflowX || style.overflow); + const clipsY = /^(hidden|scroll|auto|clip)$/.test(style.overflowY || style.overflow); + if ((!clipsX && !clipsY) || style.display === 'contents') continue; + const rect = parent.getBoundingClientRect(); + const scaleX = parent.offsetWidth ? rect.width / parent.offsetWidth : 1; + const scaleY = parent.offsetHeight ? rect.height / parent.offsetHeight : 1; + clip = intersectFrames(clip, { + x: clipsX ? rect.left + parent.clientLeft * scaleX : clip.x, + y: clipsY ? rect.top + parent.clientTop * scaleY : clip.y, + width: clipsX ? parent.clientWidth * scaleX : clip.width, + height: clipsY ? parent.clientHeight * scaleY : clip.height, + }); + } + const style = win.getComputedStyle(element); + const visible = + (!options.scrollOwner || reachedScrollOwner) && + !transparent && + element.isConnected && + clip.width > 0 && + clip.height > 0 && + style.display !== 'none' && + parseFloat(style.opacity) !== 0 && + (style.visibility === 'visible' || getUnprojectedVisibility(element) === 'visible'); + return { frame, clip, visible }; +} + +/** Observe author attributes that can change visibility or clipping without moving the host. */ +export function observeProjectionStyles(elements: Iterable, changed: () => void): MutationObserver { + const observer = new MutationObserver((records) => { + if (records.some((record) => !record.attributeName?.startsWith('data-native-ui-'))) changed(); + }); + const observed = new Set(); + for (const element of elements) { + for (const ancestor of [element, ...projectionAncestors(element)]) { + if (!observed.has(ancestor)) { + observed.add(ancestor); + observer.observe(ancestor, { attributes: true }); + } + } + } + return observer; +} diff --git a/src/index.ts b/src/index.ts index 64e64b3..5ffaddb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ export * from './types.js'; export * from './dom/geometry.js'; +export * from './dom/placement.js'; export * from './dom/scroll-placement.js'; export { createWebProjectionScope, type WebProjectionScope } from './projection/scope.js'; export * from './projection/web.js'; diff --git a/tests/dom/placement.spec.ts b/tests/dom/placement.spec.ts new file mode 100644 index 0000000..24783d7 --- /dev/null +++ b/tests/dom/placement.spec.ts @@ -0,0 +1,55 @@ +import { expect, test } from '@playwright/test'; +import { buildSync } from 'esbuild'; +import type * as placement from '../../src/dom/placement'; + +test('scaled overflow, native scrolling and visibility follow a slotted host', async ({ page }) => { + await page.setContent(` + +
`); + await page.addScriptTag({ + content: buildSync({ entryPoints: ['src/dom/placement.ts'], bundle: true, format: 'iife', globalName: 'placement', write: false }) + .outputFiles[0].text, + }); + const result = await page.evaluate(async () => { + const { measureProjectionFrame, observeProjectionStyles } = (window as unknown as { placement: typeof placement }).placement; + const shell = document.querySelector('#shell')!; + const ad = document.querySelector('#ad')!; + const root = shell.attachShadow({ mode: 'open' }); + root.innerHTML = '
'; + const scroller = root.firstElementChild as HTMLElement; + const initial = measureProjectionFrame(ad); + const owned = measureProjectionFrame(ad, { scrollOwner: scroller }); + const area = measureProjectionFrame(ad, { visibleArea: { x: 3, y: 3, width: 10, height: 10 } }); + let changes = 0; + const observer = observeProjectionStyles([ad], () => changes++); + ad.setAttribute('data-native-ui-snapshot-source', ''); + await Promise.resolve(); + const internalChanges = changes; + shell.setAttribute('data-closed', ''); + await Promise.resolve(); + const hidden = measureProjectionFrame(ad).visible; + shell.removeAttribute('data-closed'); + await Promise.resolve(); + observer.disconnect(); + shell.style.opacity = '0'; + const transparent = measureProjectionFrame(ad, { scrollOwner: scroller }).visible; + shell.style.removeProperty('opacity'); + return { initial, owned, area: area.clip, internalChanges, changes, hidden, transparent, restored: measureProjectionFrame(ad).visible }; + }); + const frame = { x: 2, y: 2, width: 200, height: 20 }; + expect(result).toEqual({ + initial: { frame, clip: { ...frame, width: 46 }, visible: true }, + owned: { frame, clip: frame, visible: true }, + area: { x: 3, y: 3, width: 10, height: 10 }, + internalChanges: 0, + changes: 2, + hidden: false, + transparent: false, + restored: true, + }); +}); From 693f537e02c479c32ba68453161278a36bcc9596 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Sat, 28 Nov 2026 21:04:23 +0900 Subject: [PATCH 2/7] Observe visual viewport changes for native placement --- docs/reference/platforms.md | 4 +++- src/dom/placement.ts | 15 +++++++++++++++ tests/dom/placement.spec.ts | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/docs/reference/platforms.md b/docs/reference/platforms.md index fc24967..d31689b 100644 --- a/docs/reference/platforms.md +++ b/docs/reference/platforms.md @@ -147,7 +147,9 @@ Measure the DOM host with `measureProjectionFrame(element)`. The returned frame and clip use viewport CSS pixels and account for scaled, axis-aligned overflow ancestors, including slots and shadow hosts. A renderer that owns native scrolling can pass `scrollOwner` and translate the result into that container's coordinates. -Use `observeProjectionStyles(elements, update)` alongside scroll and resize events +Use `observeProjectionViewport(window, update)` for layout viewport resize and +visual viewport resize or pan, including pinch zoom. Call the returned function +on teardown. Use `observeProjectionStyles(elements, update)` alongside element scroll and resize events to remeasure when an author attribute changes. Disconnect it on teardown and rebind when the host or its ancestors change. diff --git a/src/dom/placement.ts b/src/dom/placement.ts index bda5b55..865f29d 100644 --- a/src/dom/placement.ts +++ b/src/dom/placement.ts @@ -95,3 +95,18 @@ export function observeProjectionStyles(elements: Iterable, changed } return observer; } + +/** Invalidate viewport-relative clips when the layout or visual viewport moves or resizes. */ +export function observeProjectionViewport(win: Window, changed: () => void): () => void { + const viewport = win.visualViewport; + // A visual viewport pan changes the clip even when native scrolling owns the content position. + const invalidate = () => changed(); + win.addEventListener('resize', invalidate); + viewport?.addEventListener('resize', invalidate); + viewport?.addEventListener('scroll', invalidate); + return () => { + win.removeEventListener('resize', invalidate); + viewport?.removeEventListener('resize', invalidate); + viewport?.removeEventListener('scroll', invalidate); + }; +} diff --git a/tests/dom/placement.spec.ts b/tests/dom/placement.spec.ts index 24783d7..8a0d6c9 100644 --- a/tests/dom/placement.spec.ts +++ b/tests/dom/placement.spec.ts @@ -53,3 +53,38 @@ test('scaled overflow, native scrolling and visibility follow a slotted host', a restored: true, }); }); + +test('pinch zoom remeasures an unchanged host and teardown releases viewport listeners', async ({ page, context }) => { + await page.setViewportSize({ width: 800, height: 600 }); + await page.setContent( + '
', + ); + await page.addScriptTag({ + content: buildSync({ entryPoints: ['src/dom/placement.ts'], bundle: true, format: 'iife', globalName: 'placement', write: false }) + .outputFiles[0].text, + }); + await page.evaluate(() => { + const { measureProjectionFrame, observeProjectionViewport } = (window as unknown as { placement: typeof placement }).placement; + const host = document.querySelector('div')!; + const stop = observeProjectionViewport(window, () => { + host.dataset.width = String(measureProjectionFrame(host).clip.width); + }); + host.addEventListener('stop', stop, { once: true }); + }); + const session = await context.newCDPSession(page); + await session.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2 }); + await expect(page.locator('div')).toHaveAttribute('data-width', '400'); + const widths = await page.evaluate(() => { + const host = document.querySelector('div')!; + host.removeAttribute('data-width'); + window.visualViewport!.dispatchEvent(new Event('scroll')); + const pan = host.dataset.width; + host.dispatchEvent(new Event('stop')); + host.removeAttribute('data-width'); + window.visualViewport!.dispatchEvent(new Event('scroll')); + window.visualViewport!.dispatchEvent(new Event('resize')); + window.dispatchEvent(new Event('resize')); + return [pan, host.dataset.width]; + }); + expect(widths).toEqual(['400', undefined]); +}); From 371782dd594e8e1170a21d009ab22f26b53a081f Mon Sep 17 00:00:00 2001 From: rdlabo Date: Sat, 28 Nov 2026 21:40:14 +0900 Subject: [PATCH 3/7] Own snapshot visible areas and native pixel placement --- .../engine/NativeUIEngineTest.kt | 13 ++++ .../engine/NativeUIScrollHostingTest.kt | 52 +++++++++----- .../engine/NativeUIClippedView.kt | 60 ++++++++-------- .../engine/NativeUIPixelFrame.kt | 31 ++++++++ .../engine/NativeUIScrollHosting.kt | 10 ++- docs/reference/platforms.md | 10 +++ src/index.ts | 2 + src/projection/visible-area.ts | 72 +++++++++++++++++++ src/projection/web.ts | 11 ++- tests/projection/web.spec.ts | 64 ++++++++++++++++- 10 files changed, 273 insertions(+), 52 deletions(-) create mode 100644 android/src/main/java/io/github/webview_native_ui/engine/NativeUIPixelFrame.kt create mode 100644 src/projection/visible-area.ts diff --git a/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIEngineTest.kt b/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIEngineTest.kt index 44636de..eb64277 100644 --- a/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIEngineTest.kt +++ b/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIEngineTest.kt @@ -16,6 +16,19 @@ import org.junit.Assert.* import org.junit.Test class NativeUIEngineTest { + @Test + fun cssFramesRoundDimensionsAndRejectUnsafeCoordinates() { + val rect = JSONObject("""{"x":-2.5,"y":3.2,"width":3.5,"height":0}""") + val pixels = NativeUIPixelFrame.fromCss(rect, 2f)!! + assertEquals(RectF(5f, 16f, 12f, 16f), pixels.bounds(10f, 10f)) + assertNull(NativeUIPixelFrame.fromCss(rect, Float.NaN)) + assertNull(NativeUIPixelFrame.fromCss(rect.put("width", -1), 2f)) + assertNull(NativeUIPixelFrame.fromCss(rect.put("width", Int.MAX_VALUE), 2f)) + assertNull(NativeUIPixelFrame.fromCss(rect.put("width", "12"), 2f)) + rect.remove("width") + assertNull(NativeUIPixelFrame.fromCss(rect, 2f)) + } + @Test fun configuredOriginsExcludeNavigationDestinations() { val config = diff --git a/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIScrollHostingTest.kt b/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIScrollHostingTest.kt index 9b264bd..1fbe823 100644 --- a/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIScrollHostingTest.kt +++ b/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIScrollHostingTest.kt @@ -1,7 +1,6 @@ package io.github.webview_native_ui.engine import android.content.Intent -import android.graphics.RectF import android.os.SystemClock import android.view.InputDevice import android.view.MotionEvent @@ -28,7 +27,7 @@ class NativeUIScrollHostingTest { private lateinit var activity: EngineTestActivity private lateinit var button: Button - private lateinit var clipped: NativeUIClippedView + private lateinit var clipped: NativeUIScrollHosting private var projection: NativeUIProjection? = null private var firstWebMove: (() -> Unit)? = null private var softwareDraws = 0 @@ -60,6 +59,16 @@ class NativeUIScrollHostingTest { return result } + private fun frame(x: Float, y: Float, width: Float, height: Float) = + NativeUIPixelFrame.fromCss( + JSONObject() + .put("x", x.toDouble()) + .put("y", y.toDouble()) + .put("width", width.toDouble()) + .put("height", height.toDouble()), + scale, + )!! + private fun load(kind: String = "overflow") { activity = instrumentation.startActivitySync( @@ -121,12 +130,11 @@ class NativeUIScrollHostingTest { true } } - val host = NativeUIScrollHosting(activity.web, button) - clipped = NativeUIClippedView(host) + clipped = NativeUIScrollHosting(activity.web, button) activity.root.addView(clipped, FrameLayout.LayoutParams(1, 1)) clipped.place( - RectF(20 * scale, 80 * scale, (20 + (cssWidth - 40) / 2) * scale, 580 * scale), - RectF(20 * scale, 80 * scale, (cssWidth - 20) * scale, 580 * scale), + frame(20f, 80f, (cssWidth - 40) / 2, 500f), + frame(20f, 80f, cssWidth - 40, 500f), ) activity.web.setOnTouchListener { _, event -> if (event.actionMasked == MotionEvent.ACTION_MOVE) { @@ -270,8 +278,8 @@ class NativeUIScrollHostingTest { main { button.setBackgroundColor(android.graphics.Color.RED) clipped.place( - RectF(20 * scale, 80 * scale, (20 + (cssWidth - 40) / 2) * scale, 330 * scale), - RectF(20 * scale, 80 * scale, (cssWidth - 20) * scale, 580 * scale), + frame(20f, 80f, (cssWidth - 40) / 2, 250f), + frame(20f, 80f, cssWidth - 40, 500f), ) activity.web.webViewClient = object : WebViewClient() { @@ -300,16 +308,10 @@ class NativeUIScrollHostingTest { captureMode = NativeUIProjection.CaptureMode.VIEW, updatePlacement = { value -> val clip = value.getJSONObject("clip") - fun rect(raw: JSONObject) = - RectF( - (raw.getDouble("x") * scale).toFloat(), - (raw.getDouble("y") * scale).toFloat(), - ((raw.getDouble("x") + raw.getDouble("width")) * scale) - .toFloat(), - ((raw.getDouble("y") + raw.getDouble("height")) * scale) - .toFloat(), - ) - clipped.place(rect(value), rect(clip)) + clipped.place( + NativeUIPixelFrame.fromCss(value, scale)!!, + NativeUIPixelFrame.fromCss(clip, scale)!!, + ) }, view = { button }, ) @@ -455,6 +457,20 @@ class NativeUIScrollHostingTest { assertTrue(clicked) } + @Test + fun onlyTheVisiblePartOfThePhotoReceivesSdkTaps() { + load() + main { + clipped.place(frame(20f, 80f, cssWidth / 2, 500f), frame(20f, 200f, cssWidth / 2, 200f)) + } + instrumentation.waitForIdleSync() + touch(true, y = 120f) + touch(true, y = 300f) + instrumentation.waitForIdleSync() + main { assertEquals(1, taps) } + assertEquals("1", js("webClicks")) + } + @Test fun nativeTapAndLongPressNeverReachWeb() { load() diff --git a/android/src/main/java/io/github/webview_native_ui/engine/NativeUIClippedView.kt b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIClippedView.kt index c855501..02854b7 100644 --- a/android/src/main/java/io/github/webview_native_ui/engine/NativeUIClippedView.kt +++ b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIClippedView.kt @@ -31,36 +31,38 @@ class NativeUIClippedView(val content: View) : FrameLayout(content.context) { addView(content) } - fun place(frame: RectF, clip: RectF): Boolean { - check(Looper.myLooper() == Looper.getMainLooper()) - val visible = RectF(frame) - if (!frame.valid() || !clip.valid() || !visible.intersect(clip)) { - visibility = View.INVISIBLE - return false - } - val width = ceil(visible.width().toDouble()).toInt() - val height = ceil(visible.height().toDouble()).toInt() - val params = layoutParams ?: LayoutParams(width, height) - if (layoutParams == null || params.width != width || params.height != height) { - params.width = width - params.height = height - layoutParams = params - } - x = visible.left - y = visible.top - val contentWidth = ceil(frame.width().toDouble()).toInt() - val contentHeight = ceil(frame.height().toDouble()).toInt() - val child = content.layoutParams - if (child.width != contentWidth || child.height != contentHeight) { - child.width = contentWidth - child.height = contentHeight - content.layoutParams = child - } - content.x = frame.left - visible.left - content.y = frame.top - visible.top - visibility = View.VISIBLE - return true + fun place(frame: RectF, clip: RectF): Boolean = placeClippedContent(content, frame, clip) +} + +internal fun FrameLayout.placeClippedContent(content: View, frame: RectF, clip: RectF): Boolean { + check(Looper.myLooper() == Looper.getMainLooper()) + val visible = RectF(frame) + if (!frame.valid() || !clip.valid() || !visible.intersect(clip)) { + visibility = View.INVISIBLE + return false + } + val width = ceil(visible.width().toDouble()).toInt() + val height = ceil(visible.height().toDouble()).toInt() + val params = layoutParams ?: FrameLayout.LayoutParams(width, height) + if (layoutParams == null || params.width != width || params.height != height) { + params.width = width + params.height = height + layoutParams = params + } + x = visible.left + y = visible.top + val contentWidth = ceil(frame.width().toDouble()).toInt() + val contentHeight = ceil(frame.height().toDouble()).toInt() + val child = content.layoutParams + if (child.width != contentWidth || child.height != contentHeight) { + child.width = contentWidth + child.height = contentHeight + content.layoutParams = child } + content.x = frame.left - visible.left + content.y = frame.top - visible.top + visibility = View.VISIBLE + return true } internal fun RectF.valid(): Boolean = diff --git a/android/src/main/java/io/github/webview_native_ui/engine/NativeUIPixelFrame.kt b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIPixelFrame.kt new file mode 100644 index 0000000..1ef6fe0 --- /dev/null +++ b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIPixelFrame.kt @@ -0,0 +1,31 @@ +package io.github.webview_native_ui.engine + +import android.graphics.RectF +import kotlin.math.roundToInt +import org.json.JSONObject + +/** A viewport CSS rectangle converted to integer device pixels, including empty clips. */ +class NativeUIPixelFrame +private constructor(val x: Int, val y: Int, val width: Int, val height: Int) { + internal fun bounds(offsetX: Float, offsetY: Float): RectF = + RectF(offsetX + x, offsetY + y, offsetX + (x + width), offsetY + (y + height)) + + companion object { + @JvmStatic + fun fromCss(value: JSONObject?, density: Float): NativeUIPixelFrame? { + if (value == null || !density.isFinite() || density <= 0) return null + // MeasureSpec reserves two bits. This limit also keeps endpoint sums inside Int. + val limit = 0x3fffffff.toDouble() + fun pixel(key: String, min: Double): Int? { + val scaled = (value.opt(key) as? Number)?.toDouble()?.times(density) ?: return null + return if (scaled in min..limit) scaled.roundToInt() else null + } + return NativeUIPixelFrame( + pixel("x", -limit) ?: return null, + pixel("y", -limit) ?: return null, + pixel("width", 0.0) ?: return null, + pixel("height", 0.0) ?: return null, + ) + } + } +} diff --git a/android/src/main/java/io/github/webview_native_ui/engine/NativeUIScrollHosting.kt b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIScrollHosting.kt index fee364e..251f641 100644 --- a/android/src/main/java/io/github/webview_native_ui/engine/NativeUIScrollHosting.kt +++ b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIScrollHosting.kt @@ -10,7 +10,7 @@ import android.widget.FrameLayout /** SDK taps stay native; only a drag is handed to the WebView's own scroll recognizer. */ @SuppressLint("ViewConstructor") -class NativeUIScrollHosting(private val webView: WebView, content: View) : +class NativeUIScrollHosting(private val webView: WebView, private val content: View) : FrameLayout(content.context) { private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop private var down: MotionEvent? = null @@ -20,6 +20,14 @@ class NativeUIScrollHosting(private val webView: WebView, content: View) : addView(content, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) } + /** Place a sibling of the WebView from viewport-relative device pixels. */ + fun place(frame: NativeUIPixelFrame, clip: NativeUIPixelFrame): Boolean = + placeClippedContent( + content, + frame.bounds(webView.x, webView.y), + clip.bounds(webView.x, webView.y), + ) + override fun dispatchTouchEvent(event: MotionEvent): Boolean { if (event.actionMasked == MotionEvent.ACTION_DOWN) { reset() diff --git a/docs/reference/platforms.md b/docs/reference/platforms.md index d31689b..3e7b334 100644 --- a/docs/reference/platforms.md +++ b/docs/reference/platforms.md @@ -153,6 +153,16 @@ on teardown. Use `observeProjectionStyles(elements, update)` alongside element s to remeasure when an author attribute changes. Disconnect it on teardown and rebind when the host or its ancestors change. +If the app supplies a viewport clip, pass the same callback to +`bindSnapshotVisibleArea(element, visibleArea)` and pass its current result to `measureProjectionFrame` as `visibleArea`. +The Engine clips each snapshot image in viewport coordinates while it moves. +Release the binding when the plugin detaches the host. + +On Android, `NativeUIPixelFrame.fromCss(rect, density)` validates and rounds +bridge rectangle components to device pixels. It accepts empty clips and returns +null for malformed values. For fixed-size SDK views, `NativeUIScrollHosting.place` +applies the same clipping geometry as `NativeUIClippedView.place` while preserving SDK taps and WebView drags. + On iOS, retain a `NativeUIDocumentObservation(webView:onReplacement:)` when the first document-bound session starts. Its closure runs at the start of the next main document in that WebView, including a reload after WebContent process diff --git a/src/index.ts b/src/index.ts index 5ffaddb..677cc5e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,6 +9,8 @@ export type { ProjectionEvents, ProjectionDestination } from './projection/event export { getOverlayCoordinator, usesOverlayBackdrop, type OverlayChange, type OverlayOptions } from './dom/overlays.js'; export { getUnprojectedVisibility } from './dom/visibility.js'; +export { bindSnapshotVisibleArea } from './projection/visible-area.js'; + export { bindProjectionPlacement, type ProjectionPlacementBinding } from './projection/placement.js'; export { createWebProjectionSurfaces } from './projection/surfaces.js'; diff --git a/src/projection/visible-area.ts b/src/projection/visible-area.ts new file mode 100644 index 0000000..66aa19f --- /dev/null +++ b/src/projection/visible-area.ts @@ -0,0 +1,72 @@ +import type { Frame } from '../types.js'; + +// A plugin and the injected runtime may load separate copies of the Engine. +const key = Symbol.for('webview-native-ui-engine.snapshot-visible-area'); +interface ClipState { + images: Map; + read?: () => Frame | undefined; + frame: number; +} +type Host = HTMLElement & { [key]?: ClipState }; + +function refresh(host: Host, state: ClipState) { + const win = host.ownerDocument.defaultView!; + win.cancelAnimationFrame(state.frame); + if (!state.read || !state.images.size) { + for (const [image, previous] of state.images) { + if (previous) image.style.removeProperty('clip-path'); + state.images.set(image, ''); + } + if (!state.read && !state.images.size) delete host[key]; + return; + } + state.frame = win.requestAnimationFrame(() => refresh(host, state)); + const area = state.read(); + for (const [image, previous] of state.images) { + let inset = ''; + if (area && [area.x, area.y, area.width, area.height].every(Number.isFinite)) { + const box = image.getBoundingClientRect(); + const percent = (outside: number, size: number) => Math.min(100, Math.max(0, (100 * outside) / size)); + if (!box.width || !box.height || area.width <= 0 || area.height <= 0) inset = 'inset(100%)'; + else { + const edges = [ + percent(area.y - box.top, box.height), + percent(box.right - area.x - area.width, box.width), + percent(box.bottom - area.y - area.height, box.height), + percent(area.x - box.left, box.width), + ]; + if (edges.some(Boolean)) inset = `inset(${edges.map((edge) => edge + '%').join(' ')})`; + } + } + if (inset === previous) continue; + state.images.set(image, inset); + if (inset) image.style.setProperty('clip-path', inset, 'important'); + else image.style.removeProperty('clip-path'); + } +} + +/** Clip this host's snapshot images to a dynamic viewport area, including during scrolling. */ +export function bindSnapshotVisibleArea(element: HTMLElement, read: () => Frame | undefined): () => void { + const host = element as Host; + const state: ClipState = (host[key] ??= { images: new Map(), frame: 0 }); + const provider = () => read(); + state.read = provider; + refresh(host, state); + return () => { + if (state.read !== provider) return; + delete state.read; + refresh(host, state); + }; +} + +export function attachSnapshotClip(element: HTMLElement, image: HTMLImageElement): () => void { + const host = element as Host; + const state: ClipState = (host[key] ??= { images: new Map(), frame: 0 }); + state.images.set(image, ''); + refresh(host, state); + return () => { + state.images.delete(image); + image.style.removeProperty('clip-path'); + refresh(host, state); + }; +} diff --git a/src/projection/web.ts b/src/projection/web.ts index 64694d5..c9d89ab 100644 --- a/src/projection/web.ts +++ b/src/projection/web.ts @@ -9,6 +9,7 @@ import type { import type { WebProjectionScope } from './scope.js'; import { bounded, boundedListener } from '../native/bridge.js'; import { bindProjectionEvents, type ProjectionEvents, type ProjectionDestination } from './events.js'; +import { attachSnapshotClip } from './visible-area.js'; import { createSnapshotStyles, imageMarker } from './styles.js'; import { sourcesForCapture } from './capture-parts.js'; import { getProjectionPause } from './pause.js'; @@ -560,7 +561,7 @@ const createProjectionEngine = async (scope: WebProjectionScope, transport: WebP resetPresentation(); for (const element of offsets.keys()) element.style.setProperty('opacity', '0', 'important'); unparkImages(); - offsets.clear(); + clearOffsets(); clearPrepared(); handoff = undefined; rendered.forEach(clearTarget); @@ -620,6 +621,11 @@ const createProjectionEngine = async (scope: WebProjectionScope, transport: WebP }; const preparedKeys = new Map(); const offsets = new Map(); + const releaseClips: (() => void)[] = []; + const clearOffsets = () => { + for (const release of releaseClips.splice(0)) release(); + offsets.clear(); + }; const parked = new Map(); const parkImages = (image: Prepared, frames: Frame[]) => { const layer = callbacks.imageSurface; @@ -709,7 +715,7 @@ const createProjectionEngine = async (scope: WebProjectionScope, transport: WebP }), ); preparedKeys.clear(); - offsets.clear(); + clearOffsets(); rendered.forEach(clearTarget); rendered.clear(); for (const target of new Set(targets)) { @@ -764,6 +770,7 @@ const createProjectionEngine = async (scope: WebProjectionScope, transport: WebP } image.parents = image.scopes.map((scope) => scope.element.parentNode); updateOffsets(); + for (const [element, { target }] of offsets) releaseClips.push(attachSnapshotClip(target, element)); return true; }; diff --git a/tests/projection/web.spec.ts b/tests/projection/web.spec.ts index c4d3156..813e7be 100644 --- a/tests/projection/web.spec.ts +++ b/tests/projection/web.spec.ts @@ -36,6 +36,7 @@ const prepare = async ( captureDelayMs, transient = false, webSurface = false, + opaqueUnderlay = false, }: { shadow?: boolean; proxy?: boolean; @@ -44,6 +45,7 @@ const prepare = async ( captureDelayMs?: number; transient?: boolean; webSurface?: boolean; + opaqueUnderlay?: boolean; } = {}, ) => { await boot(page); @@ -55,7 +57,7 @@ const prepare = async ( (window as any).sourceRoot = host.shadowRoot; }); await page.evaluate( - async ({ proxy, shared, events, captureDelayMs, transient, webSurface }) => { + async ({ proxy, shared, events, captureDelayMs, transient, webSurface, opaqueUnderlay }) => { const w = window as any, source = (w.sourceRoot ?? document).querySelector('#source') as HTMLElement, owner = (w.sourceRoot ?? document).querySelector('#scroll') as HTMLElement; @@ -132,6 +134,7 @@ const prepare = async ( captureDelayMs, transient, imageSurface: webSurface ? document.body : undefined, + opaqueUnderlay, wake() { w.onWake?.(); }, @@ -152,7 +155,7 @@ const prepare = async ( ); w.manager.consider(1, [w.source]); }, - { proxy, shared, events, captureDelayMs, transient, webSurface }, + { proxy, shared, events, captureDelayMs, transient, webSurface, opaqueUnderlay }, ); await expect(page.locator(shared ? '#projection-host' : proxy ? '#proxy' : '#source')).toHaveAttribute('data-native-ui-snapshot', /.+/); }; @@ -2219,3 +2222,60 @@ for (const reused of [false, true]) await expect(page.locator('img[data-native-ui-projection-image]')).toHaveAttribute('src', /blue/); await destroyProjection(page); }); + +for (const opaqueUnderlay of [false, true]) + test(`visibleArea follows scrolling, scale and rebinding (opaque underlay: ${opaqueUnderlay})`, async ({ page }) => { + await prepare(page, { opaqueUnderlay }); + await page.evaluate((opaqueUnderlay) => { + const w = window as any; + const host = w.scope.element as HTMLElement; + host.style.transformOrigin = 'top left'; + host.style.transform = 'scale(.5)'; + if (!opaqueUnderlay) w.manager.begin(); + }, opaqueUnderlay); + const image = page.locator('img[data-native-ui-projection-image]'); + await expect(image).toHaveCSS('opacity', '1'); + const box = (await image.boundingBox())!; + const left = { x: Math.ceil(box.x + 2), y: Math.ceil(box.y + 2), width: 2, height: 2 }; + const red = await page.screenshot({ clip: left }); + await page.evaluate(() => { + const w = window as any; + const img = document.querySelector('img[data-native-ui-projection-image]')!; + const box = img.getBoundingClientRect(); + w.area = { x: box.x + box.width / 2, y: box.y, width: box.width, height: box.height }; + w.releaseClip = w.engine.bindSnapshotVisibleArea(w.scope.element, () => w.area); + }); + await expect(image).toHaveCSS('clip-path', 'inset(0% 0% 0% 50%)'); + expect(await page.screenshot({ clip: left })).not.toEqual(red); + await expect(page.locator('#source')).toHaveCSS('clip-path', 'none'); + await page.evaluate(() => { + document.querySelector('#scroll')!.scrollTop += 6; + }); + await expect.poll(() => image.evaluate((img) => parseFloat(getComputedStyle(img).clipPath.slice(6)))).toBeGreaterThan(0); + await page.evaluate(() => { + const w = window as any; + w.releaseNext = w.engine.bindSnapshotVisibleArea(w.scope.element, () => ({ x: 0, y: 0, width: 0, height: 0 })); + w.releaseClip(); + }); + await expect(image).toHaveCSS('clip-path', 'inset(100%)'); + await page.evaluate(() => (window as any).releaseNext()); + await expect(image).toHaveCSS('clip-path', 'none'); + await page.evaluate(() => { + const w = window as any; + w.reads = 0; + w.release = w.engine.bindSnapshotVisibleArea(w.scope.element, () => { + ++w.reads; + return undefined; + }); + }); + await destroyProjection(page); + const counts = await page.evaluate(async () => { + const w = window as any; + const atDestroy = w.reads; + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + w.release(); + return [atDestroy, w.reads]; + }); + expect(counts[0]).toBeGreaterThan(0); + expect(counts[1]).toBe(counts[0]); + }); From e1b8365ea3252ce41680e0398b68419b98bb134b Mon Sep 17 00:00:00 2001 From: rdlabo Date: Sat, 28 Nov 2026 21:57:18 +0900 Subject: [PATCH 4/7] Track snapshot clipping only while the image is visible --- android/build.gradle | 3 - .../engine/NativeUIScrollHostingTest.kt | 21 ++- .../engine/NativeUIActivityLifecycle.kt | 23 --- .../engine/NativeUIActivityLifecycleTest.kt | 27 ---- docs/reference/platforms.md | 4 +- src/projection/web.ts | 24 ++- tests/projection/web.spec.ts | 137 +++++++++++------- 7 files changed, 117 insertions(+), 122 deletions(-) delete mode 100644 android/src/test/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycleTest.kt diff --git a/android/build.gradle b/android/build.gradle index 3ed63f1..ff826ec 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -23,11 +23,8 @@ android { publishing { singleVariant('release') { withSourcesJar(); withJavadocJar() } } } dependencies { - api 'androidx.lifecycle:lifecycle-common:2.8.7' implementation 'androidx.webkit:webkit:1.14.0' implementation 'androidx.annotation:annotation:1.9.1' - testImplementation 'junit:junit:4.13.2' - testImplementation 'androidx.lifecycle:lifecycle-runtime:2.8.7' androidTestImplementation 'androidx.test:runner:1.6.2' androidTestImplementation 'androidx.test.ext:junit:1.2.1' } diff --git a/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIScrollHostingTest.kt b/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIScrollHostingTest.kt index 1fbe823..84c588e 100644 --- a/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIScrollHostingTest.kt +++ b/android/src/androidTest/java/io/github/webview_native_ui/engine/NativeUIScrollHostingTest.kt @@ -69,7 +69,7 @@ class NativeUIScrollHostingTest { scale, )!! - private fun load(kind: String = "overflow") { + private fun load(kind: String = "overflow", useHostingClip: Boolean = false) { activity = instrumentation.startActivitySync( Intent(instrumentation.targetContext, EngineTestActivity::class.java) @@ -131,11 +131,16 @@ class NativeUIScrollHostingTest { } } clipped = NativeUIScrollHosting(activity.web, button) - activity.root.addView(clipped, FrameLayout.LayoutParams(1, 1)) - clipped.place( - frame(20f, 80f, (cssWidth - 40) / 2, 500f), - frame(20f, 80f, cssWidth - 40, 500f), - ) + val bounds = frame(20f, 80f, (cssWidth - 40) / 2, 500f) + val clip = frame(20f, 80f, cssWidth - 40, 500f) + if (useHostingClip) { + activity.root.addView(clipped, FrameLayout.LayoutParams(1, 1)) + clipped.place(bounds, clip) + } else { + val wrapper = NativeUIClippedView(clipped) + activity.root.addView(wrapper, FrameLayout.LayoutParams(1, 1)) + wrapper.place(bounds.bounds(0f, 0f), clip.bounds(0f, 0f)) + } activity.web.setOnTouchListener { _, event -> if (event.actionMasked == MotionEvent.ACTION_MOVE) { val check = firstWebMove @@ -262,7 +267,7 @@ class NativeUIScrollHostingTest { androidx.webkit.WebViewFeature.DOCUMENT_START_SCRIPT ) ) - load() + load(useHostingClip = true) js( """ var slot=document.createElement('div'); slot.id='slot';slot.style.cssText='width:50%;height:250px';feed.prepend(slot); @@ -459,7 +464,7 @@ class NativeUIScrollHostingTest { @Test fun onlyTheVisiblePartOfThePhotoReceivesSdkTaps() { - load() + load(useHostingClip = true) main { clipped.place(frame(20f, 80f, cssWidth / 2, 500f), frame(20f, 200f, cssWidth / 2, 200f)) } diff --git a/android/src/main/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycle.kt b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycle.kt index db445d4..ac07941 100644 --- a/android/src/main/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycle.kt +++ b/android/src/main/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycle.kt @@ -1,10 +1,6 @@ package io.github.webview_native_ui.engine import android.app.Activity -import androidx.annotation.MainThread -import androidx.lifecycle.DefaultLifecycleObserver -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleOwner /** Native SDK work queued for an activity must recheck its owner when it runs. */ object NativeUIActivityLifecycle { @@ -21,23 +17,4 @@ object NativeUIActivityLifecycle { if (isAvailable(activity)) action.run() else unavailable.run() } } - - /** Register SDK-specific teardown once, including when the owner is already destroyed. */ - @JvmStatic - @MainThread - fun onDestroy(owner: LifecycleOwner, release: Runnable) { - val lifecycle = owner.lifecycle - if (lifecycle.currentState == Lifecycle.State.DESTROYED) { - release.run() - return - } - lifecycle.addObserver( - object : DefaultLifecycleObserver { - override fun onDestroy(owner: LifecycleOwner) { - owner.lifecycle.removeObserver(this) - release.run() - } - } - ) - } } diff --git a/android/src/test/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycleTest.kt b/android/src/test/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycleTest.kt deleted file mode 100644 index 204990a..0000000 --- a/android/src/test/java/io/github/webview_native_ui/engine/NativeUIActivityLifecycleTest.kt +++ /dev/null @@ -1,27 +0,0 @@ -package io.github.webview_native_ui.engine - -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.LifecycleRegistry -import org.junit.Assert.assertEquals -import org.junit.Test - -class NativeUIActivityLifecycleTest { - @Test - fun releasesEachRegistrationOnceIncludingLateOwners() { - val owner = - object : LifecycleOwner { - override val lifecycle = LifecycleRegistry.createUnsafe(this) - } - var count = 0 - owner.lifecycle.currentState = Lifecycle.State.CREATED - NativeUIActivityLifecycle.onDestroy(owner) { count++ } - NativeUIActivityLifecycle.onDestroy(owner) { count++ } - assertEquals(0, count) - owner.lifecycle.currentState = Lifecycle.State.DESTROYED - assertEquals(2, count) - assertEquals(0, owner.lifecycle.observerCount) - NativeUIActivityLifecycle.onDestroy(owner) { count++ } - assertEquals(3, count) - } -} diff --git a/docs/reference/platforms.md b/docs/reference/platforms.md index 3e7b334..a780eec 100644 --- a/docs/reference/platforms.md +++ b/docs/reference/platforms.md @@ -169,8 +169,8 @@ next main document in that WebView, including a reload after WebContent process termination. Release resources and discard pending bridge replies for the old document there. Capture the session owner weakly. -On Android, register SDK teardown in `NativeUIActivityLifecycle.onDestroy(owner, release)` -on the main thread. Queue SDK presentation with +On Android, release SDK resources in the plugin teardown callback (for Capacitor, +`handleOnDestroy`). Queue SDK presentation with `NativeUIActivityLifecycle.runOnUiThread(activity, unavailable, action)` so a finishing or destroyed Activity is checked when queued work actually runs. The plugin supplies the SDK cleanup and the response to a cancelled operation. diff --git a/src/projection/web.ts b/src/projection/web.ts index c9d89ab..abafbad 100644 --- a/src/projection/web.ts +++ b/src/projection/web.ts @@ -617,13 +617,26 @@ const createProjectionEngine = async (scope: WebProjectionScope, transport: WebP target.toggleAttribute('data-native-ui-snapshot-visible', visible); styling.syncContent(target); } - image.images.forEach((element) => element.style.setProperty('opacity', visible ? '1' : '0', 'important')); + image.images.forEach((element) => setImageVisible(element, visible)); }; const preparedKeys = new Map(); - const offsets = new Map(); - const releaseClips: (() => void)[] = []; + const offsets = new Map< + HTMLImageElement, + { target: HTMLElement; frame: Frame; scale?: { x: number; y: number }; releaseClip?: () => void } + >(); + const setImageVisible = (element: HTMLImageElement, visible: boolean) => { + const placement = offsets.get(element); + if (placement) { + if (visible) placement.releaseClip ??= attachSnapshotClip(placement.target, element); + else if (placement.releaseClip) { + placement.releaseClip(); + delete placement.releaseClip; + } + } + element.style.setProperty('opacity', visible ? '1' : '0', 'important'); + }; const clearOffsets = () => { - for (const release of releaseClips.splice(0)) release(); + for (const placement of offsets.values()) placement.releaseClip?.(); offsets.clear(); }; const parked = new Map(); @@ -763,14 +776,13 @@ const createProjectionEngine = async (scope: WebProjectionScope, transport: WebP element.style.setProperty('height', `${frame.height}px`, 'important'); element.style.setProperty('left', '0px', 'important'); element.style.setProperty('top', '0px', 'important'); - element.style.setProperty('opacity', callbacks.opaqueUnderlay ? '1' : '0', 'important'); if (element.parentNode !== parent) parent.insertBefore(element, null); offsets.set(element, { target, frame }); } } image.parents = image.scopes.map((scope) => scope.element.parentNode); updateOffsets(); - for (const [element, { target }] of offsets) releaseClips.push(attachSnapshotClip(target, element)); + if (callbacks.opaqueUnderlay) for (const element of offsets.keys()) setImageVisible(element, true); return true; }; diff --git a/tests/projection/web.spec.ts b/tests/projection/web.spec.ts index 813e7be..bfb8f90 100644 --- a/tests/projection/web.spec.ts +++ b/tests/projection/web.spec.ts @@ -2223,59 +2223,90 @@ for (const reused of [false, true]) await destroyProjection(page); }); -for (const opaqueUnderlay of [false, true]) - test(`visibleArea follows scrolling, scale and rebinding (opaque underlay: ${opaqueUnderlay})`, async ({ page }) => { - await prepare(page, { opaqueUnderlay }); - await page.evaluate((opaqueUnderlay) => { - const w = window as any; - const host = w.scope.element as HTMLElement; - host.style.transformOrigin = 'top left'; - host.style.transform = 'scale(.5)'; - if (!opaqueUnderlay) w.manager.begin(); - }, opaqueUnderlay); - const image = page.locator('img[data-native-ui-projection-image]'); - await expect(image).toHaveCSS('opacity', '1'); - const box = (await image.boundingBox())!; - const left = { x: Math.ceil(box.x + 2), y: Math.ceil(box.y + 2), width: 2, height: 2 }; - const red = await page.screenshot({ clip: left }); - await page.evaluate(() => { - const w = window as any; - const img = document.querySelector('img[data-native-ui-projection-image]')!; - const box = img.getBoundingClientRect(); - w.area = { x: box.x + box.width / 2, y: box.y, width: box.width, height: box.height }; - w.releaseClip = w.engine.bindSnapshotVisibleArea(w.scope.element, () => w.area); - }); - await expect(image).toHaveCSS('clip-path', 'inset(0% 0% 0% 50%)'); - expect(await page.screenshot({ clip: left })).not.toEqual(red); - await expect(page.locator('#source')).toHaveCSS('clip-path', 'none'); - await page.evaluate(() => { - document.querySelector('#scroll')!.scrollTop += 6; - }); - await expect.poll(() => image.evaluate((img) => parseFloat(getComputedStyle(img).clipPath.slice(6)))).toBeGreaterThan(0); - await page.evaluate(() => { - const w = window as any; - w.releaseNext = w.engine.bindSnapshotVisibleArea(w.scope.element, () => ({ x: 0, y: 0, width: 0, height: 0 })); - w.releaseClip(); - }); - await expect(image).toHaveCSS('clip-path', 'inset(100%)'); - await page.evaluate(() => (window as any).releaseNext()); - await expect(image).toHaveCSS('clip-path', 'none'); - await page.evaluate(() => { - const w = window as any; - w.reads = 0; - w.release = w.engine.bindSnapshotVisibleArea(w.scope.element, () => { - ++w.reads; - return undefined; - }); +test('a prepared snapshot reads its visible area only while shown', async ({ page }) => { + await prepare(page); + const idleReads = await page.evaluate(async () => { + const w = window as any; + w.reads = 0; + w.engine.bindSnapshotVisibleArea(w.scope.element, () => { + w.reads++; + return { x: 0, y: 0, width: 0, height: 0 }; }); - await destroyProjection(page); - const counts = await page.evaluate(async () => { - const w = window as any; - const atDestroy = w.reads; - await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); - w.release(); - return [atDestroy, w.reads]; + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + const idleReads = w.reads; + w.manager.begin(); + return idleReads; + }); + expect(idleReads).toBe(0); + const image = page.locator('img[data-native-ui-projection-image]'); + await expect(image).toHaveCSS('opacity', '1'); + await expect(image).toHaveCSS('clip-path', 'inset(100%)'); + await page.evaluate(() => { + const w = window as any; + w.manager.end(); + w.manager.updated(undefined, ['counter'], 2); + }); + await expect(image).toHaveCSS('opacity', '0'); + const idleReadDelta = await page.evaluate(async () => { + const w = window as any; + const before = w.reads; + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + return w.reads - before; + }); + expect(idleReadDelta).toBe(0); + await destroyProjection(page); +}); + +test('an opaque underlay follows scrolling, scale and visible area rebinding', async ({ page }) => { + await prepare(page, { opaqueUnderlay: true }); + await page.evaluate(() => { + const host = (window as any).scope.element as HTMLElement; + host.style.transformOrigin = 'top left'; + host.style.transform = 'scale(.5)'; + }); + const image = page.locator('img[data-native-ui-projection-image]'); + await expect(image).toHaveCSS('opacity', '1'); + const box = (await image.boundingBox())!; + const left = { x: Math.ceil(box.x + 2), y: Math.ceil(box.y + 2), width: 2, height: 2 }; + const red = await page.screenshot({ clip: left }); + await page.evaluate(() => { + const w = window as any; + const img = document.querySelector('img[data-native-ui-projection-image]')!; + const box = img.getBoundingClientRect(); + w.area = { x: box.x + box.width / 2, y: box.y, width: box.width, height: box.height }; + w.releaseClip = w.engine.bindSnapshotVisibleArea(w.scope.element, () => w.area); + }); + await expect(image).toHaveCSS('clip-path', 'inset(0% 0% 0% 50%)'); + expect(await page.screenshot({ clip: left })).not.toEqual(red); + await expect(page.locator('#source')).toHaveCSS('clip-path', 'none'); + await page.evaluate(() => { + document.querySelector('#scroll')!.scrollTop += 6; + }); + await expect.poll(() => image.evaluate((img) => parseFloat(getComputedStyle(img).clipPath.slice(6)))).toBeGreaterThan(0); + await page.evaluate(() => { + const w = window as any; + w.releaseNext = w.engine.bindSnapshotVisibleArea(w.scope.element, () => ({ x: 0, y: 0, width: 0, height: 0 })); + w.releaseClip(); + }); + await expect(image).toHaveCSS('clip-path', 'inset(100%)'); + await page.evaluate(() => (window as any).releaseNext()); + await expect(image).toHaveCSS('clip-path', 'none'); + await page.evaluate(() => { + const w = window as any; + w.reads = 0; + w.release = w.engine.bindSnapshotVisibleArea(w.scope.element, () => { + ++w.reads; + return undefined; }); - expect(counts[0]).toBeGreaterThan(0); - expect(counts[1]).toBe(counts[0]); }); + await destroyProjection(page); + const counts = await page.evaluate(async () => { + const w = window as any; + const atDestroy = w.reads; + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + w.release(); + return [atDestroy, w.reads]; + }); + expect(counts[0]).toBeGreaterThan(0); + expect(counts[1]).toBe(counts[0]); +}); From 63e6061ec285fe96bcd8d31c2750c144bd3c4fe8 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Sat, 28 Nov 2026 22:09:03 +0900 Subject: [PATCH 5/7] Unify DOM layout observation for native projections --- docs/reference/platforms.md | 10 ++++---- src/dom/placement.ts | 33 +++++++++++++------------- src/projection/visible-area.ts | 15 +++++------- tests/dom/placement.spec.ts | 43 ++++++++++++++++++++++++---------- 4 files changed, 58 insertions(+), 43 deletions(-) diff --git a/docs/reference/platforms.md b/docs/reference/platforms.md index a780eec..ec47a64 100644 --- a/docs/reference/platforms.md +++ b/docs/reference/platforms.md @@ -147,11 +147,11 @@ Measure the DOM host with `measureProjectionFrame(element)`. The returned frame and clip use viewport CSS pixels and account for scaled, axis-aligned overflow ancestors, including slots and shadow hosts. A renderer that owns native scrolling can pass `scrollOwner` and translate the result into that container's coordinates. -Use `observeProjectionViewport(window, update)` for layout viewport resize and -visual viewport resize or pan, including pinch zoom. Call the returned function -on teardown. Use `observeProjectionStyles(elements, update)` alongside element scroll and resize events -to remeasure when an author attribute changes. Disconnect it on teardown and -rebind when the host or its ancestors change. +Use `observeProjectionLayout(window, hosts, update)` for author attribute changes, +scrolls in the document and shadow trees, and viewport resize or pan. Only DOM +scroll passes its event to `update`. Observe element sizes with `ResizeObserver` +as needed. Call the returned function on teardown or before rebinding a changed +set of hosts or ancestors. If the app supplies a viewport clip, pass the same callback to `bindSnapshotVisibleArea(element, visibleArea)` and pass its current result to `measureProjectionFrame` as `visibleArea`. diff --git a/src/dom/placement.ts b/src/dom/placement.ts index 865f29d..ae61937 100644 --- a/src/dom/placement.ts +++ b/src/dom/placement.ts @@ -79,32 +79,33 @@ export function measureProjectionFrame( return { frame, clip, visible }; } -/** Observe author attributes that can change visibility or clipping without moving the host. */ -export function observeProjectionStyles(elements: Iterable, changed: () => void): MutationObserver { +/** Watch a set of hosts. Only DOM scroll forwards its event, so native scrollers can keep ownership of motion. */ +export function observeProjectionLayout(win: Window, elements: Iterable, changed: (scroll?: Event) => void): () => void { + const viewport = win.visualViewport; + const invalidate = () => changed(); const observer = new MutationObserver((records) => { - if (records.some((record) => !record.attributeName?.startsWith('data-native-ui-'))) changed(); + if (records.some((record) => !record.attributeName?.startsWith('data-native-ui-'))) invalidate(); }); const observed = new Set(); + const roots = new Set([win]); for (const element of elements) { - for (const ancestor of [element, ...projectionAncestors(element)]) { - if (!observed.has(ancestor)) { - observed.add(ancestor); - observer.observe(ancestor, { attributes: true }); - } + for (const node of [element, ...projectionAncestors(element)]) { + if (observed.has(node)) continue; + observed.add(node); + observer.observe(node, { attributes: true }); + // Scroll events inside a shadow tree do not reach the window. + const root = node.getRootNode(); + if (root instanceof ShadowRoot) roots.add(root); } } - return observer; -} - -/** Invalidate viewport-relative clips when the layout or visual viewport moves or resizes. */ -export function observeProjectionViewport(win: Window, changed: () => void): () => void { - const viewport = win.visualViewport; - // A visual viewport pan changes the clip even when native scrolling owns the content position. - const invalidate = () => changed(); + const onScroll = (event: Event) => changed(event); + for (const root of roots) root.addEventListener('scroll', onScroll, true); win.addEventListener('resize', invalidate); viewport?.addEventListener('resize', invalidate); viewport?.addEventListener('scroll', invalidate); return () => { + observer.disconnect(); + for (const root of roots) root.removeEventListener('scroll', onScroll, true); win.removeEventListener('resize', invalidate); viewport?.removeEventListener('resize', invalidate); viewport?.removeEventListener('scroll', invalidate); diff --git a/src/projection/visible-area.ts b/src/projection/visible-area.ts index 66aa19f..76874de 100644 --- a/src/projection/visible-area.ts +++ b/src/projection/visible-area.ts @@ -12,19 +12,16 @@ type Host = HTMLElement & { [key]?: ClipState }; function refresh(host: Host, state: ClipState) { const win = host.ownerDocument.defaultView!; win.cancelAnimationFrame(state.frame); - if (!state.read || !state.images.size) { - for (const [image, previous] of state.images) { - if (previous) image.style.removeProperty('clip-path'); - state.images.set(image, ''); - } - if (!state.read && !state.images.size) delete host[key]; + if (!state.images.size) { + if (!state.read) delete host[key]; return; } - state.frame = win.requestAnimationFrame(() => refresh(host, state)); - const area = state.read(); + if (state.read) state.frame = win.requestAnimationFrame(() => refresh(host, state)); + const area = state.read?.(); + const hasArea = area && [area.x, area.y, area.width, area.height].every(Number.isFinite); for (const [image, previous] of state.images) { let inset = ''; - if (area && [area.x, area.y, area.width, area.height].every(Number.isFinite)) { + if (hasArea) { const box = image.getBoundingClientRect(); const percent = (outside: number, size: number) => Math.min(100, Math.max(0, (100 * outside) / size)); if (!box.width || !box.height || area.width <= 0 || area.height <= 0) inset = 'inset(100%)'; diff --git a/tests/dom/placement.spec.ts b/tests/dom/placement.spec.ts index 8a0d6c9..333c033 100644 --- a/tests/dom/placement.spec.ts +++ b/tests/dom/placement.spec.ts @@ -16,7 +16,7 @@ test('scaled overflow, native scrolling and visibility follow a slotted host', a .outputFiles[0].text, }); const result = await page.evaluate(async () => { - const { measureProjectionFrame, observeProjectionStyles } = (window as unknown as { placement: typeof placement }).placement; + const { measureProjectionFrame, observeProjectionLayout } = (window as unknown as { placement: typeof placement }).placement; const shell = document.querySelector('#shell')!; const ad = document.querySelector('#ad')!; const root = shell.attachShadow({ mode: 'open' }); @@ -26,7 +26,12 @@ test('scaled overflow, native scrolling and visibility follow a slotted host', a const owned = measureProjectionFrame(ad, { scrollOwner: scroller }); const area = measureProjectionFrame(ad, { visibleArea: { x: 3, y: 3, width: 10, height: 10 } }); let changes = 0; - const observer = observeProjectionStyles([ad], () => changes++); + let scrolls = 0; + const stop = observeProjectionLayout(window, [ad], (event) => { + if (event?.target === scroller) scrolls++; + else changes++; + }); + scroller.dispatchEvent(new Event('scroll')); ad.setAttribute('data-native-ui-snapshot-source', ''); await Promise.resolve(); const internalChanges = changes; @@ -35,17 +40,29 @@ test('scaled overflow, native scrolling and visibility follow a slotted host', a const hidden = measureProjectionFrame(ad).visible; shell.removeAttribute('data-closed'); await Promise.resolve(); - observer.disconnect(); + stop(); + scroller.dispatchEvent(new Event('scroll')); shell.style.opacity = '0'; const transparent = measureProjectionFrame(ad, { scrollOwner: scroller }).visible; shell.style.removeProperty('opacity'); - return { initial, owned, area: area.clip, internalChanges, changes, hidden, transparent, restored: measureProjectionFrame(ad).visible }; + return { + initial, + owned, + area: area.clip, + scrolls, + internalChanges, + changes, + hidden, + transparent, + restored: measureProjectionFrame(ad).visible, + }; }); const frame = { x: 2, y: 2, width: 200, height: 20 }; expect(result).toEqual({ initial: { frame, clip: { ...frame, width: 46 }, visible: true }, owned: { frame, clip: frame, visible: true }, area: { x: 3, y: 3, width: 10, height: 10 }, + scrolls: 1, internalChanges: 0, changes: 2, hidden: false, @@ -64,27 +81,27 @@ test('pinch zoom remeasures an unchanged host and teardown releases viewport lis .outputFiles[0].text, }); await page.evaluate(() => { - const { measureProjectionFrame, observeProjectionViewport } = (window as unknown as { placement: typeof placement }).placement; + const { measureProjectionFrame, observeProjectionLayout } = (window as unknown as { placement: typeof placement }).placement; const host = document.querySelector('div')!; - const stop = observeProjectionViewport(window, () => { - host.dataset.width = String(measureProjectionFrame(host).clip.width); + const stop = observeProjectionLayout(window, [host], () => { + host.textContent = String(measureProjectionFrame(host).clip.width); }); host.addEventListener('stop', stop, { once: true }); }); const session = await context.newCDPSession(page); await session.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2 }); - await expect(page.locator('div')).toHaveAttribute('data-width', '400'); + await expect(page.locator('div')).toHaveText('400'); const widths = await page.evaluate(() => { const host = document.querySelector('div')!; - host.removeAttribute('data-width'); + host.textContent = ''; window.visualViewport!.dispatchEvent(new Event('scroll')); - const pan = host.dataset.width; + const pan = host.textContent; host.dispatchEvent(new Event('stop')); - host.removeAttribute('data-width'); + host.textContent = ''; window.visualViewport!.dispatchEvent(new Event('scroll')); window.visualViewport!.dispatchEvent(new Event('resize')); window.dispatchEvent(new Event('resize')); - return [pan, host.dataset.width]; + return [pan, host.textContent]; }); - expect(widths).toEqual(['400', undefined]); + expect(widths).toEqual(['400', '']); }); From 1eefac19073c334769e746743d627b8a85681568 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Sat, 28 Nov 2026 22:15:08 +0900 Subject: [PATCH 6/7] Preserve the viewport clip during document scroll and callback failures --- docs/reference/platforms.md | 1 + src/dom/placement.ts | 17 ++++++++++++++++ src/projection/visible-area.ts | 9 ++++++++- tests/dom/placement.spec.ts | 37 ++++++++++++++++++++++++++++++++++ tests/projection/web.spec.ts | 16 +++++++++++++++ 5 files changed, 79 insertions(+), 1 deletion(-) diff --git a/docs/reference/platforms.md b/docs/reference/platforms.md index ec47a64..4fa0210 100644 --- a/docs/reference/platforms.md +++ b/docs/reference/platforms.md @@ -156,6 +156,7 @@ set of hosts or ancestors. If the app supplies a viewport clip, pass the same callback to `bindSnapshotVisibleArea(element, visibleArea)` and pass its current result to `measureProjectionFrame` as `visibleArea`. The Engine clips each snapshot image in viewport coordinates while it moves. +If the callback throws, the image stays clipped to an empty area until a later read succeeds. Release the binding when the plugin detaches the host. On Android, `NativeUIPixelFrame.fromCss(rect, density)` validates and rounds diff --git a/src/dom/placement.ts b/src/dom/placement.ts index ae61937..f0dc987 100644 --- a/src/dom/placement.ts +++ b/src/dom/placement.ts @@ -56,6 +56,23 @@ export function measureProjectionFrame( const clipsX = /^(hidden|scroll|auto|clip)$/.test(style.overflowX || style.overflow); const clipsY = /^(hidden|scroll|auto|clip)$/.test(style.overflowY || style.overflow); if ((!clipsX && !clipsY) || style.display === 'contents') continue; + // Root overflow clips at the viewport, which was intersected above. + const doc = element.ownerDocument; + if (parent === doc.documentElement) continue; + if (parent === doc.body && parent.parentElement === doc.documentElement) { + const rootStyle = win.getComputedStyle(doc.documentElement); + if ( + rootStyle.overflowX === 'visible' && + rootStyle.overflowY === 'visible' && + [rootStyle, style].every( + (value) => + value.contain === 'none' && + (!value.containerType || value.containerType === 'normal') && + (!value.contentVisibility || value.contentVisibility === 'visible'), + ) + ) + continue; + } const rect = parent.getBoundingClientRect(); const scaleX = parent.offsetWidth ? rect.width / parent.offsetWidth : 1; const scaleY = parent.offsetHeight ? rect.height / parent.offsetHeight : 1; diff --git a/src/projection/visible-area.ts b/src/projection/visible-area.ts index 76874de..cf71bc1 100644 --- a/src/projection/visible-area.ts +++ b/src/projection/visible-area.ts @@ -46,7 +46,14 @@ function refresh(host: Host, state: ClipState) { export function bindSnapshotVisibleArea(element: HTMLElement, read: () => Frame | undefined): () => void { const host = element as Host; const state: ClipState = (host[key] ??= { images: new Map(), frame: 0 }); - const provider = () => read(); + const provider = () => { + try { + return read(); + } catch { + // A transient app layout failure must not reveal pixels outside its requested area. + return { x: 0, y: 0, width: 0, height: 0 }; + } + }; state.read = provider; refresh(host, state); return () => { diff --git a/tests/dom/placement.spec.ts b/tests/dom/placement.spec.ts index 333c033..27120d8 100644 --- a/tests/dom/placement.spec.ts +++ b/tests/dom/placement.spec.ts @@ -105,3 +105,40 @@ test('pinch zoom remeasures an unchanged host and teardown releases viewport lis }); expect(widths).toEqual(['400', '']); }); + +test('viewport overflow stays fixed during document scroll and an independently scrolling body still clips', async ({ page }) => { + await page.setViewportSize({ width: 400, height: 500 }); + await page.setContent(`
`); + await page.addScriptTag({ + content: buildSync({ entryPoints: ['src/dom/placement.ts'], bundle: true, format: 'iife', globalName: 'placement', write: false }) + .outputFiles[0].text, + }); + const results = await page.evaluate(() => { + const { measureProjectionFrame } = (window as unknown as { placement: typeof placement }).placement; + const host = document.getElementById('slot')!; + const root = document.documentElement; + const body = document.body; + root.style.overflowY = 'auto'; + window.scrollTo(0, 800); + const htmlOverflow = measureProjectionFrame(host); + root.style.overflowY = 'visible'; + body.style.overflowY = 'auto'; + window.scrollTo(0, 800); + const bodyOverflow = measureProjectionFrame(host); + window.scrollTo(0, 0); + root.style.overflowY = 'auto'; + body.style.height = '240px'; + body.scrollTop = 800; + return [htmlOverflow, bodyOverflow, measureProjectionFrame(host)]; + }); + const frame = { x: 0, y: 200, width: 100, height: 80 }; + expect(results).toEqual([ + { frame, clip: frame, visible: true }, + { frame, clip: frame, visible: true }, + { frame, clip: { ...frame, height: 40 }, visible: true }, + ]); +}); diff --git a/tests/projection/web.spec.ts b/tests/projection/web.spec.ts index bfb8f90..11ef4ba 100644 --- a/tests/projection/web.spec.ts +++ b/tests/projection/web.spec.ts @@ -2310,3 +2310,19 @@ test('an opaque underlay follows scrolling, scale and visible area rebinding', a expect(counts[0]).toBeGreaterThan(0); expect(counts[1]).toBe(counts[0]); }); + +test('a failing visible area callback hides the image and leaves the binding disposable', async ({ page }) => { + await prepare(page, { opaqueUnderlay: true }); + await page.evaluate(() => { + const w = window as any; + w.releaseArea = w.engine.bindSnapshotVisibleArea(w.scope.element, () => { + if (!w.areaReady) throw new Error('Header has not mounted'); + }); + }); + const image = page.locator('img[data-native-ui-projection-image]'); + await expect(image).toHaveCSS('clip-path', 'inset(100%)'); + await page.evaluate(() => ((window as any).areaReady = true)); + await expect(image).toHaveCSS('clip-path', 'none'); + await page.evaluate(() => (window as any).releaseArea()); + await destroyProjection(page); +}); From 9521139775dc674c511a9adb29c079576bddd895 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Sat, 28 Nov 2026 22:28:06 +0900 Subject: [PATCH 7/7] test(ios): run document navigation with a host and acknowledge background handoff --- .github/workflows/native-ui-engine.yml | 1 + .../WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift | 1 + ios/Tests/project.yml | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/native-ui-engine.yml b/.github/workflows/native-ui-engine.yml index 1db39b8..0e7d13b 100644 --- a/.github/workflows/native-ui-engine.yml +++ b/.github/workflows/native-ui-engine.yml @@ -75,6 +75,7 @@ jobs: -derivedDataPath "$RUNNER_TEMP/swift-package" \ -parallel-testing-enabled NO \ -collect-test-diagnostics never \ + -skip-testing:WebViewNativeUIEngineTests/DocumentObservationTests \ -skip-testing:WebViewNativeUIEngineTests/NativeUIProjectionTests \ -skip-testing:WebViewNativeUIEngineTests/NativeUIScrollTrackerTests \ -skip-testing:WebViewNativeUIControlsTests/NativeUISnapshotTests/testNativePopoverClosureNotifiesWebBeforeReopening \ diff --git a/ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift b/ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift index b1258ee..80a673d 100644 --- a/ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift +++ b/ios/Tests/WebViewNativeUIEngineTests/CoveredSnapshotsTests.swift @@ -747,6 +747,7 @@ final class NativeUICoveredSnapshotsTests: XCTestCase { let backCapture = await capture("back") let background = try XCTUnwrap(backCapture["token"] as? String) XCTAssertTrue(snapshots.cover(background, in: view, views: [])) + snapshots.retireCopy(background) let modalCapture = await capture("modal") let foreground = try XCTUnwrap(modalCapture["token"] as? String) XCTAssertTrue(snapshots.cover(foreground, in: view, views: [], transient: true)) diff --git a/ios/Tests/project.yml b/ios/Tests/project.yml index 3887812..6089b17 100644 --- a/ios/Tests/project.yml +++ b/ios/Tests/project.yml @@ -86,7 +86,7 @@ schemes: test: targets: - name: WebViewNativeUIEngineTests - selectedTests: [NativeUIProjectionTests, NativeUIScrollTrackerTests] + selectedTests: [DocumentObservationTests, NativeUIProjectionTests, NativeUIScrollTrackerTests] - name: WebViewNativeUIControlsTests selectedTests: - NativeUISnapshotTests/testNativePopoverClosureNotifiesWebBeforeReopening()