diff --git a/.github/workflows/native-ui-engine.yml b/.github/workflows/native-ui-engine.yml index e1263a9..adba425 100644 --- a/.github/workflows/native-ui-engine.yml +++ b/.github/workflows/native-ui-engine.yml @@ -36,9 +36,10 @@ jobs: COVERED_ORIENTATION=NativeUIPluginTests/NativeUIPluginLifecycleTests/testOrientationPreservesCoveredControlsUntilRestore CAPTURE_INTERACTION=NativeUIPluginTests/NativeUIPluginLifecycleTests/testSnapshotInteractionForwardsEnginePayloadToCapacitor SOURCE_ORDER=NativeUIPluginTests/NativeUISnapshotTests/testViewCapturePreservesNativeSourceOrder - xcodebuild -scheme RdlaboCapacitorNativeUi-Package -destination "platform=iOS Simulator,id=$DEVICE" CODE_SIGNING_ALLOWED=NO -clonedSourcePackagesDirPath "$RUNNER_TEMP/native-ui-spm" -skip-testing:"$POPOVER_CLOSE" -skip-testing:"$POPOVER_REPLACE" -skip-testing:"$COVERED_ORIENTATION" -skip-testing:"$CAPTURE_INTERACTION" -skip-testing:"$SOURCE_ORDER" test + TOOLBAR_BADGE=NativeUIPluginTests/NativeUISnapshotTests/testSwiftUIToolbarBadgeUpdatesAndRemoval + xcodebuild -scheme RdlaboCapacitorNativeUi-Package -destination "platform=iOS Simulator,id=$DEVICE" CODE_SIGNING_ALLOWED=NO -clonedSourcePackagesDirPath "$RUNNER_TEMP/native-ui-spm" -skip-testing:"$POPOVER_CLOSE" -skip-testing:"$POPOVER_REPLACE" -skip-testing:"$COVERED_ORIENTATION" -skip-testing:"$CAPTURE_INTERACTION" -skip-testing:"$SOURCE_ORDER" -skip-testing:"$TOOLBAR_BADGE" test cd ios/Tests - xcodebuild -project NativeUIHostedTests.xcodeproj -scheme NativeUIHostedTests -destination "platform=iOS Simulator,id=$DEVICE" CODE_SIGNING_ALLOWED=NO -clonedSourcePackagesDirPath "$RUNNER_TEMP/native-ui-spm" -only-testing:"$POPOVER_CLOSE" -only-testing:"$POPOVER_REPLACE" -only-testing:"$COVERED_ORIENTATION" -only-testing:"$CAPTURE_INTERACTION" -only-testing:"$SOURCE_ORDER" test + xcodebuild -project NativeUIHostedTests.xcodeproj -scheme NativeUIHostedTests -destination "platform=iOS Simulator,id=$DEVICE" CODE_SIGNING_ALLOWED=NO -clonedSourcePackagesDirPath "$RUNNER_TEMP/native-ui-spm" -only-testing:"$POPOVER_CLOSE" -only-testing:"$POPOVER_REPLACE" -only-testing:"$COVERED_ORIENTATION" -only-testing:"$CAPTURE_INTERACTION" -only-testing:"$SOURCE_ORDER" -only-testing:"$TOOLBAR_BADGE" test android: runs-on: ubuntu-latest steps: diff --git a/Package.swift b/Package.swift index a936e59..678628f 100644 --- a/Package.swift +++ b/Package.swift @@ -7,7 +7,7 @@ let package = Package( .library(name: "RdlaboCapacitorNativeUi", targets: ["NativeUIPlugin"]), .library(name: "NativeUICore", targets: ["NativeUICore"]) ], - dependencies: [.package(url: "https://github.com/webview-native-ui/engine.git", exact: "1.0.9"), .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")], + dependencies: [.package(url: "https://github.com/webview-native-ui/engine.git", exact: "1.0.11"), .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "8.0.0")], targets: [.target( name: "NativeUICore", dependencies: [.product(name: "WebViewNativeUIEngine", package: "engine")], diff --git a/README.md b/README.md index f7bac2d..1d4d9bf 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,34 @@ # Capacitor Native UI -Capacitor Native UI provides native controls, device colors and custom native content for WebView applications. +Render supported Web controls natively on iOS, use Android Dynamic Color, or add custom SwiftUI and Compose views to a Capacitor app. For a complete Ionic app setup combining iOS Native UI and Android Dynamic Color, follow [WebView Native UI Standard setup](https://webview-native-ui.com/standard-setup). ## Individual guides +Choose the guide for the feature you need. + ### 1. Use the plugin’s Native UI The plugin renders supported Ionic and HTML controls natively on iOS. Your application keeps its state, routing and handlers. -| Your app | Guide | -| ------------------------------------ | --------------------------------------------------- | -| Ionic with the standard iOS 27 theme | [Ionic setup](docs/setup.md) | -| Ionic with an existing Web theme | [Existing-theme setup](docs/ionic-vertical-bars.md) | -| HTML without Ionic | [HTML setup](docs/framework-independent.md) | +| Your app | Guide | +| ------------------------------------ | ----------------------------------------------------------------------------------------------------------- | +| Ionic with the standard iOS 27 theme | [Ionic setup](https://webview-native-ui.com/projects/capacitor-native-ui/docs/setup) | +| Ionic with an existing Web theme | [Existing-theme setup](https://webview-native-ui.com/projects/capacitor-native-ui/docs/ionic-vertical-bars) | +| HTML without Ionic | [HTML setup](https://webview-native-ui.com/projects/capacitor-native-ui/docs/framework-independent) | #### How projection works -Native UI presents the original Web control natively while retaining its state and handlers. See [supported controls and projection behavior](docs/native-ui.md). +Native UI presents the original Web control natively while retaining its state and handlers. See [supported controls and projection behavior](https://webview-native-ui.com/projects/capacitor-native-ui/docs/native-ui). ### 2. Use Dynamic Color -Read Android’s device palette and apply it through your theme. Use the [Dynamic Color guide](docs/dynamic-colors.md) for this feature on its own, appearance preferences and color mapping. +Read Android’s device palette and apply it through your theme. Use the [Dynamic Color guide](https://webview-native-ui.com/projects/capacitor-native-ui/docs/dynamic-colors) for this feature on its own, appearance preferences and color mapping. ### 3. Build your own Native UI -Render your own SwiftUI or Android Compose content through [app-local extensions](docs/native-ui-extensions.md). This feature is experimental. +Render your own SwiftUI or Android Compose content through [app-local extensions](https://webview-native-ui.com/projects/capacitor-native-ui/docs/native-ui-extensions). This feature is experimental. ## Requirements diff --git a/RdlaboCapacitorNativeUi.podspec b/RdlaboCapacitorNativeUi.podspec index 0bbdace..e5dd2cd 100644 --- a/RdlaboCapacitorNativeUi.podspec +++ b/RdlaboCapacitorNativeUi.podspec @@ -13,6 +13,6 @@ Pod::Spec.new do |s| s.source_files = 'ios/Sources/**/*.{swift,h,m,c,cc,mm,cpp}', 'packages/native-ui-core/ios/Sources/**/*.swift' s.ios.deployment_target = '15.0' s.dependency 'Capacitor' - s.dependency 'WebViewNativeUIEngine', '1.0.9' + s.dependency 'WebViewNativeUIEngine', '1.0.11' s.swift_version = '5.9' end diff --git a/android/build.gradle b/android/build.gradle index f127db5..d575f18 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -70,7 +70,7 @@ repositories { } dependencies { - implementation 'io.github.webview-native-ui:engine:1.0.9' + implementation 'io.github.webview-native-ui:engine:1.0.11' api platform("androidx.compose:compose-bom:2025.10.00") api "androidx.compose.ui:ui" api "androidx.compose.foundation:foundation" diff --git a/android/src/main/java/shared-core/dev/rdlabo/nativeui/core/NativeUIController.kt b/android/src/main/java/shared-core/dev/rdlabo/nativeui/core/NativeUIController.kt index ec24385..e495848 100644 --- a/android/src/main/java/shared-core/dev/rdlabo/nativeui/core/NativeUIController.kt +++ b/android/src/main/java/shared-core/dev/rdlabo/nativeui/core/NativeUIController.kt @@ -32,6 +32,7 @@ class NativeUIController( private val context get() = activity private val handler = Handler(Looper.getMainLooper()) private val snapshots by lazy { NativeUISnapshots(File(context.cacheDir, "native-ui-snapshots")) } + private var stopInteractions: (() -> Unit)? = null private var host: FrameLayout? = null private var revision = 0L private var sequence = 0L @@ -53,7 +54,12 @@ class NativeUIController( } fun load() { - activity.runOnUiThread { webView.addOnLayoutChangeListener(layoutListener) } + activity.runOnUiThread { + webView.addOnLayoutChangeListener(layoutListener) + stopInteractions = snapshots.observeInteractions(activity.window) { event -> + notifyListeners("snapshotInteraction", event) + } + } } fun configure(call: NativeUICall) = onMain(call) { @@ -114,10 +120,6 @@ class NativeUIController( val (node, content) = pair val entry = entries[id] ?: Entry(ComposeView(activity), node).also { entry -> entry.view.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) - entry.clip.interaction = { active -> - snapshots.interaction(active) - notifyListeners("snapshotInteraction", JSONObject().put("active", active)) - } container.addView(entry.clip) entry.view.setContent { entry.content.value?.invoke() } entries[id] = entry @@ -229,6 +231,8 @@ class NativeUIController( notifyListeners("webViewMetricsChange", JSONObject().put("radius", 0)) } fun destroy() { + stopInteractions?.invoke() + stopInteractions = null webView.removeOnLayoutChangeListener(layoutListener) clearViews() snapshots.close() diff --git a/docs/dynamic-colors.md b/docs/dynamic-colors.md index 6713ad4..dbaa25b 100644 --- a/docs/dynamic-colors.md +++ b/docs/dynamic-colors.md @@ -1,10 +1,12 @@ --- -title: Android dynamic colors +title: Android Dynamic Color --- -# Android dynamic colors +# Android Dynamic Color -Dynamic colors are a supported, opt-in API. Read the device's Material You palette + + +Android Dynamic Color is an opt-in API. Read the device's Material You palette without enabling Native UI projection, changing the Activity theme, or requesting wallpaper/storage permissions. Ionic is not required to read colors. App-local SwiftUI/Compose extensions remain experimental; their status is separate. diff --git a/docs/migration.md b/docs/migration.md index b25fd9b..794763a 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -77,7 +77,7 @@ The same appearance applies to existing `.button-submit` actions with solid fill Native controls keep ownership during navigation, modal animations and image handoffs. An image shown in the WebView is still the native projection's presentation, not a return to the original Web button. Retest and remove transition-specific workarounds that force those controls back to Web. Keep intentional opt-outs and handling for unsupported controls or native failures; no additional animation flags or second runtime are needed. -Check both rail edges, rail disappearance, fold/rotation, card/sheet/full-screen presentation, and solid submit actions. Also check ordinary iPhone and browser fallback. For Cordova, use the [bundled integration](https://github.com/webview-native-ui/cordova-plugin); its pinned theme and native changes arrive through a Cordova plugin release rather than these Capacitor installation commands. +Check both rail edges, rail disappearance, fold/rotation, card/sheet/full-screen presentation, and solid submit buttons. Also check ordinary iPhone and browser fallback. For Cordova, use the [bundled integration](https://github.com/webview-native-ui/cordova-plugin); its pinned theme and native changes arrive through a Cordova plugin release rather than these Capacitor installation commands. ## Upgrading from 1.2.1 diff --git a/docs/native-ui-extension-reference.md b/docs/native-ui-extension-reference.md new file mode 100644 index 0000000..0468c06 --- /dev/null +++ b/docs/native-ui-extension-reference.md @@ -0,0 +1,203 @@ +# App-local Native UI extension reference (experimental) + +For a working counter on iOS or Android, follow the [extension setup guide](native-ui-extensions.md). + +## Reader contract + +| Part | Requirement | +| -------------- | -------------------------------------------------------------------------------------------------------------- | +| Execution | Synchronous and read-only. | +| Web fallback | Return `null` when the source should stay on the Web. | +| `props` | JSON object containing finite numbers, strings, booleans, null, arrays and objects; limited to 64K characters. | +| Action targets | The source itself or its descendants. Missing, hidden and disabled targets cannot be activated. | +| Action count | Up to 30 per source. | + +## Native scroll tracking on iOS (experimental) + +For an element inside a single overflow scroller, supply `scrollElement`. The Web side measures layout; iOS observes the matching `UIScrollView` and updates only native position and clipping during scrolling. Sources in the same container share one observer. The binding calibrates DOM/native coordinate origins while the scroller is at rest, then retains that mapping across content updates. Partially visible controls remain native, and fully clipped controls cannot receive input. + +```ts +const scrollElement = await ionContent.getScrollElement(); +const counter = defineNativeUI({ + name: 'app.counter', + selector: '[data-counter]', + scrollElement: () => scrollElement, + read(element) { + return { + props: { count: Number(element.getAttribute('data-count') ?? 0) }, + actions: { increment: element.querySelector('button') }, + }; + }, +}); +``` + +With plain HTML, return the element with `overflow: auto` or `scroll`. Return `null` until it is ready, then call `shell.markForCheck()` if readiness did not change the DOM. Keep source dimensions and content-layout changes observable; use `markForCheck()` for changes the shell cannot observe. + +This uses WebKit's internal overflow-view hierarchy without private class names. A binding must match exactly one native scroller; missing or ambiguous matches keep the interactive Web source. Nested scrolling, rounded or shaped clipping, CSS transforms/zoom, sticky/fixed descendants, document scrolling, older native binaries and Android are not supported by this opt-in. Omit `scrollElement` to keep the existing JS-based placement path. Other unbound projection sources inside the same scroller still require ordinary layout synchronization. Each `scrollend` performs one reconciliation through the normal update/acknowledgement path, including retries after a temporary binding refusal. + +`NativeUIContext.sourceFrame` is the latest layout sample, not a per-scroll notification. Native tracking does not rebuild SwiftUI content for scroll offsets. Fixed tab accessories do not use this binding. Web Modal transforms remain on their existing handoff path; noninteractive covered content can use prepared images, while interactive scrolling content stays native. + +## Content and placement are independent + +| `placement` | Behavior | +| ---------------------- | ------------------------------------------------------------------------------------- | +| Omitted or `'element'` | Hosts native content in the source element's Web frame on iOS 26+ or Android API 24+. | +| `'tab-accessory'` | Attaches the View to a projected tab bar's system SwiftUI tab accessory on iOS 26.1+. | + +Extensions are independent of `controls` and `ionic.auto`, including with `enableVerticalControlArea()`. The application controls their presentation: return `null` from the reader when a source should stay on the Web, then call `markForCheck()` when that condition changes. Accessories still require their supported native tab host. + +### Tab accessory requirements + +| Requirement | Supported configuration | +| ------------------- | ------------------------------------------------------------------------------------------------- | +| Source location | Inside its owning `ion-tabs`; the shell resolves that element's `ion-tab-bar`. | +| Native host | Vertical Bars SwiftUI tab host on iOS 26.1+. | +| Accessory count | A single accessory for the host. | +| Web fallback layout | Keep an equivalent Web layout, such as a fixed footer; the source retains its space while hidden. | + +Ordinary UIKit tab bars, missing native tabs, iOS 26.0 or competing accessories keep the source on the Web. Applications do not pass native controller references, and the shell does not approximate a system accessory with a floating overlay. + +## Read source geometry and presentation state + +The shell measures the source DOM element automatically. With the default `element` placement, it positions and sizes the SwiftUI host to match that rectangle. You do not need to send coordinates in `props` or position the native view yourself. + +Use the three-argument registration closure to receive that information: + +```swift +try NativeUI.register("app.counter") { + (props: CounterProps, actions: NativeUIActions, context: NativeUIContext) in + CounterView(props: props, actions: actions) + .padding(.horizontal, context.sourceFrame.width < 240 ? 4 : 12) +} +``` + +The existing `(props, actions)` closure remains supported. Both forms use the same registration names and duplicate-name checks. + +| Context property | Meaning | +| ---------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `sourceID` | Opaque source identity for its current lifetime; not the HTML `id`. | +| `sourceFrame` | DOM `getBoundingClientRect()` in CSS pixels relative to the Web viewport, including `x`, `y`, `width`, and `height`. | +| `sourceFrameInWebView` | The source rectangle converted to UIKit points in the WebView's local coordinate system; not screen coordinates. | +| `viewportWidth` | CSS viewport width used for that snapshot's coordinate conversion. | +| `pointsPerCSSPixel` | UIKit points per CSS pixel; not device pixel density. | +| `placement` | `.element` or `.tabAccessory`. | +| `colorScheme` | `.light` or `.dark`, also applied to the SwiftUI environment. | +| `layoutDirection` | `.leftToRight` or `.rightToLeft`, also applied to the SwiftUI environment. | + +The closure receives a fresh context when the shell applies an updated snapshot, including source movement, resizing, and appearance changes. Use the current context rather than caching its geometry in `@State`. Updates cross the Web/native bridge; they are not a synchronous DOM measurement from Swift. + +For `tabAccessory`, `sourceFrame` still describes the original DOM element. The system assigns the accessory's actual location and size. Use SwiftUI's `GeometryReader` inside your View for the actual local space in either placement: + +```swift +GeometryReader { geometry in + CounterView(props: props, actions: actions) + .frame(width: geometry.size.width, height: geometry.size.height) +} +``` + +Do not apply `sourceFrame.x` or `y` as another SwiftUI offset: the shell already positions the host for `element`. Your View lays out its contents within that host. + +## Use the shared projection capabilities + +| Capability | How an extension uses it | +| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Position and size | Automatic host placement plus `NativeUIContext`; actual local bounds through `GeometryReader`. | +| Dark mode and RTL | `context` or SwiftUI `@Environment(\.colorScheme)` and `@Environment(\.layoutDirection)`. | +| Reduce Motion and accessibility | SwiftUI environment values such as `@Environment(\.accessibilityReduceMotion)` and native accessibility modifiers. Give custom controls accessible names. | +| DOM-backed application state | Return JSON `props` from `read(element)`; DOM changes trigger synchronization. For changes without a DOM mutation, call `shell.markForCheck()`. | +| Enabled/visible action targets | `actions.availableNames` or `actions.isAvailable("increment")`; unavailable DOM targets are omitted. | +| Invoke the original Web action | `try await actions.activate("increment")`; completion and failure follow the contract below. | +| Temporary Web fallback and teardown | Managed automatically for unsupported content, overlays, navigation suspension, and source removal. | +| Application-controlled suspension | Use the shell handle's `suspend()`, the returned token's `resume()`, and `destroy()` from JavaScript. | + +For example, disable a native button when its original action is unavailable: + +```swift +Button("Increment") { + Task { @MainActor in + do { try await actions.activate("increment") } + catch { /* Present an application-appropriate error. */ } + } +} +.disabled(!actions.isAvailable("increment")) +``` + +Availability is a snapshot, not a reservation: a target can disappear before activation, so handle errors too. Custom text, selected state, fonts, colors, and badges belong in your extension's `props` and SwiftUI View; the shell does not infer a custom component's visual structure from CSS. Read the desired element's computed styles and attributes in your reader. Use the shared image and color conversion APIs below instead of reimplementing those transformations. + +## Schedule a source check + +DOM attributes, text, children, observed element sizes, scrolling, and supported lifecycle events trigger automatic checks. The shell does not poll JavaScript variables or arbitrary DOM properties. After changing state that your reader uses without a DOM mutation, request a check: + +```ts +source.playbackPosition = newPosition; // An application-defined property read by your extension. +shell.markForCheck(); +``` + +`markForCheck(): void` schedules a re-read and geometry measurement; it does not update the application's DOM or force a native redraw. Repeated calls are batched, and unchanged snapshots are not sent. A call during a bridge update schedules another check afterwards. Suspended projection stays suspended until resumed. Calls after `destroy()` or in an environment without a projection runtime do nothing. + +Call after your framework has committed any relevant DOM changes. This API does not trigger Angular change detection, React rendering, or Vue rendering, and it is not a promise that waits for native completion. It also works for standard controls when their properties change without an observable mutation. + +## Reuse native artwork and color conversion + +A reader's second argument exposes the standard SVG capture and rasterization path. It accepts a local `svg` or a resolved `ion-icon` belonging to the source and returns an **opaque image reference**, or `null` for unsupported artwork. Return the reference in `props`; do not try to read image bytes synchronously: + +```ts +const badge = defineNativeUI({ + name: 'app.badge', + selector: '[data-badge]', + read(element, context) { + return { + props: { + icon: context.image(element.querySelector('ion-icon')), + color: getComputedStyle(element).color, + }, + }; + }, +}); +``` + +Before sending the snapshot, the shell resolves references into `{ data, width, height, template }`: base64 PNG data, CSS dimensions, and rendering mode. Nested references and copies are supported; the `$nativeUIImage` key is reserved for references returned by the current read context. Use `{ template: true }` as the second argument to `image()` when SwiftUI should tint the icon; the default preserves source colors. The same local SVG restrictions, RTL capture, display-scale rasterization, and image cache used by standard controls apply. External resources and unsupported SVG content return `null`; unresolved `ion-icon` content should retain your Web fallback until loaded. Rasterization failure or props exceeding the size limit keeps that extension on the Web. + +On iOS, decode the resulting value with `NativeUIImage` and use the shared converters: + +```swift +struct BadgeProps: Decodable { + let icon: NativeUIImage? + let color: String +} + +struct BadgeView: View { + let props: BadgeProps + var body: some View { + if let icon = props.icon, let image = NativeUIRendering.image(icon) { + Image(uiImage: image) + .foregroundStyle(Color(uiColor: NativeUIRendering.color(props.color))) + } + } +} +``` + +`NativeUIRendering.image` returns `nil` for invalid image data. `NativeUIRendering.color` accepts computed `rgb()`/`rgba()` values; unsupported formats use `.label`, or the `fallback:` color you pass. Both are shared with the standard native renderers. They do not evaluate CSS selectors, variables, named colors, or arbitrary stylesheets. + +## Lifecycle and action completion + +The shell owns discovery, geometry, state synchronization, native controller containment, overlay retirement, suspension and teardown. Extensions do not implement attach/detach hooks. Web sources are hidden only after native accepts the projection. An unregistered renderer, a failing props decoder, unsupported placement or failed reader leaves that instance on the Web. Existing shell overlay policy applies; extensions return to the Web while Web overlays cover the page. + +Element placement requires the source to fit fully inside the viewport and its ancestors' overflow clipping bounds, including Ionic's shadow scroll containers. Partially clipped sources stay on the Web and become eligible again when scrolled fully into view. Tab accessories use the system host's placement instead. + +### Action completion + +| Event | Result of `try await actions.activate(name)` | +| ------------------------------------------------------------------ | -------------------------------------------- | +| Original Web element receives its click | Completes. | +| Handler starts a network request, navigation or modal presentation | Does not wait for that application work. | +| Action is disabled, removed or stale | Rejects. | +| Teardown, native task cancellation or bridge timeout | Settles pending calls. | + +The bridge acknowledgement is a Capacitor Promise method. + +The [demo reader](https://github.com/webview-native-ui/ionic-theme-ios27/blob/main/demo/src/native-ui/counter.ts) and [demo SwiftUI View](https://github.com/webview-native-ui/ionic-theme-ios27/blob/main/demo/ios/App/App/NativeUICounter.swift) show both placements using app-local files. Open the Native UI demo page to compare native projection with its Web fallback. + +## Example: mini-player + +The demo mini-player shows the same pattern with track metadata and playback actions: a [DOM reader and Web fallback](https://github.com/webview-native-ui/ionic-theme-ios27/blob/main/demo/src/native-ui/mini-player.ts) paired with an [app-local SwiftUI View](https://github.com/webview-native-ui/ionic-theme-ios27/blob/main/demo/ios/App/App/NativeMiniPlayer.swift). The Web app owns playback state and modal presentation; native `open` and `toggle` actions activate its original buttons. This is a UI example, not an audio engine. Adapt the files after completing the [extension setup](native-ui-extensions.md). diff --git a/docs/native-ui-extensions.md b/docs/native-ui-extensions.md index b2ec3de..1c1b84b 100644 --- a/docs/native-ui-extensions.md +++ b/docs/native-ui-extensions.md @@ -66,41 +66,6 @@ source.querySelector('button')!.addEventListener('click', () => { The shell observes DOM changes and sends the new props to the native content. State rendered into DOM attributes or text is observed automatically. For properties or external state read by the reader that do not mutate the DOM, call `shell.markForCheck()` after changing them. -### Reader contract - -| Part | Requirement | -| -------------- | -------------------------------------------------------------------------------------------------------------- | -| Execution | Synchronous and read-only. | -| Web fallback | Return `null` when the source should stay on the Web. | -| `props` | JSON object containing finite numbers, strings, booleans, null, arrays and objects; limited to 64K characters. | -| Action targets | The source itself or its descendants. Missing, hidden and disabled targets cannot be activated. | -| Action count | Up to 30 per source. | - -### Native scroll tracking on iOS (experimental) - -For an element inside a single overflow scroller, supply `scrollElement`. The Web side measures layout; iOS observes the matching `UIScrollView` and updates only native position and clipping during scrolling. Sources in the same container share one observer. The binding calibrates DOM/native coordinate origins while the scroller is at rest, then retains that mapping across content updates. Partially visible controls remain native, and fully clipped controls cannot receive input. - -```ts -const scrollElement = await ionContent.getScrollElement(); -const counter = defineNativeUI({ - name: 'app.counter', - selector: '[data-counter]', - scrollElement: () => scrollElement, - read(element) { - return { - props: { count: Number(element.getAttribute('data-count') ?? 0) }, - actions: { increment: element.querySelector('button') }, - }; - }, -}); -``` - -With plain HTML, return the element with `overflow: auto` or `scroll`. Return `null` until it is ready, then call `shell.markForCheck()` if readiness did not change the DOM. Keep source dimensions and content-layout changes observable; use `markForCheck()` for changes the shell cannot observe. - -This uses WebKit's internal overflow-view hierarchy without private class names. A binding must match exactly one native scroller; missing or ambiguous matches keep the interactive Web source. Nested scrolling, rounded or shaped clipping, CSS transforms/zoom, sticky/fixed descendants, document scrolling, older native binaries and Android are not supported by this opt-in. Omit `scrollElement` to keep the existing JS-based placement path. Other unbound projection sources inside the same scroller still require ordinary layout synchronization. Each `scrollend` performs one reconciliation through the normal update/acknowledgement path, including retries after a temporary binding refusal. - -`NativeUIContext.sourceFrame` is the latest layout sample, not a per-scroll notification. Native tracking does not rebuild SwiftUI content for scroll offsets. Fixed tab accessories do not use this binding. Web Modal transforms remain on their existing handoff path; noninteractive covered content can use prepared images, while interactive scrolling content stays native. - ## 2a. Register a SwiftUI View on iOS For CocoaPods projects, first complete the [Engine Podfile setup](https://docs.rdlabo.dev/projects/capacitor-native-ui/docs/setup#4-build-sync-and-run). SwiftPM resolves Engine automatically. @@ -255,167 +220,16 @@ Tap Increment: the original Web handler should update `data-count`, and the nati For source-specific fallback reasons, temporarily enable [`debug: true`](https://docs.rdlabo.dev/projects/capacitor-native-ui/docs/configuration#understand-why-a-source-stays-on-the-web). If the source stays on the Web, confirm that registration runs before JavaScript enables the shell and that the names and props agree on both sides. On Android, check that your `Application` subclass is declared in the manifest; on iOS, check that the Swift file belongs to the app target. -## Content and placement are independent - -| `placement` | Behavior | -| ---------------------- | ------------------------------------------------------------------------------------- | -| Omitted or `'element'` | Hosts native content in the source element's Web frame on iOS 26+ or Android API 24+. | -| `'tab-accessory'` | Attaches the View to a projected tab bar's system SwiftUI tab accessory on iOS 26.1+. | - -Extensions are independent of `controls` and `ionic.auto`, including with `enableVerticalControlArea()`. The application controls their presentation: return `null` from the reader when a source should stay on the Web, then call `markForCheck()` when that condition changes. Accessories still require their supported native tab host. - -### Tab accessory requirements - -| Requirement | Supported configuration | -| ------------------- | ------------------------------------------------------------------------------------------------- | -| Source location | Inside its owning `ion-tabs`; the shell resolves that element's `ion-tab-bar`. | -| Native host | Vertical Bars SwiftUI tab host on iOS 26.1+. | -| Accessory count | A single accessory for the host. | -| Web fallback layout | Keep an equivalent Web layout, such as a fixed footer; the source retains its space while hidden. | - -Ordinary UIKit tab bars, missing native tabs, iOS 26.0 or competing accessories keep the source on the Web. Applications do not pass native controller references, and the shell does not approximate a system accessory with a floating overlay. - -## Read source geometry and presentation state - -The shell measures the source DOM element automatically. With the default `element` placement, it positions and sizes the SwiftUI host to match that rectangle. You do not need to send coordinates in `props` or position the native view yourself. - -Use the three-argument registration closure to receive that information: - -```swift -try NativeUI.register("app.counter") { - (props: CounterProps, actions: NativeUIActions, context: NativeUIContext) in - CounterView(props: props, actions: actions) - .padding(.horizontal, context.sourceFrame.width < 240 ? 4 : 12) -} -``` - -The existing `(props, actions)` closure remains supported. Both forms use the same registration names and duplicate-name checks. - -| Context property | Meaning | -| ---------------------- | -------------------------------------------------------------------------------------------------------------------- | -| `sourceID` | Opaque source identity for its current lifetime; not the HTML `id`. | -| `sourceFrame` | DOM `getBoundingClientRect()` in CSS pixels relative to the Web viewport, including `x`, `y`, `width`, and `height`. | -| `sourceFrameInWebView` | The source rectangle converted to UIKit points in the WebView's local coordinate system; not screen coordinates. | -| `viewportWidth` | CSS viewport width used for that snapshot's coordinate conversion. | -| `pointsPerCSSPixel` | UIKit points per CSS pixel; not device pixel density. | -| `placement` | `.element` or `.tabAccessory`. | -| `colorScheme` | `.light` or `.dark`, also applied to the SwiftUI environment. | -| `layoutDirection` | `.leftToRight` or `.rightToLeft`, also applied to the SwiftUI environment. | - -The closure receives a fresh context when the shell applies an updated snapshot, including source movement, resizing, and appearance changes. Use the current context rather than caching its geometry in `@State`. Updates cross the Web/native bridge; they are not a synchronous DOM measurement from Swift. - -For `tabAccessory`, `sourceFrame` still describes the original DOM element. The system assigns the accessory's actual location and size. Use SwiftUI's `GeometryReader` inside your View for the actual local space in either placement: - -```swift -GeometryReader { geometry in - CounterView(props: props, actions: actions) - .frame(width: geometry.size.width, height: geometry.size.height) -} -``` - -Do not apply `sourceFrame.x` or `y` as another SwiftUI offset: the shell already positions the host for `element`. Your View lays out its contents within that host. - -## Use the shared projection capabilities - -| Capability | How an extension uses it | -| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Position and size | Automatic host placement plus `NativeUIContext`; actual local bounds through `GeometryReader`. | -| Dark mode and RTL | `context` or SwiftUI `@Environment(\.colorScheme)` and `@Environment(\.layoutDirection)`. | -| Reduce Motion and accessibility | SwiftUI environment values such as `@Environment(\.accessibilityReduceMotion)` and native accessibility modifiers. Give custom controls accessible names. | -| DOM-backed application state | Return JSON `props` from `read(element)`; DOM changes trigger synchronization. For changes without a DOM mutation, call `shell.markForCheck()`. | -| Enabled/visible action targets | `actions.availableNames` or `actions.isAvailable("increment")`; unavailable DOM targets are omitted. | -| Invoke the original Web action | `try await actions.activate("increment")`; completion and failure follow the contract below. | -| Temporary Web fallback and teardown | Managed automatically for unsupported content, overlays, navigation suspension, and source removal. | -| Application-controlled suspension | Use the shell handle's `suspend()`, the returned token's `resume()`, and `destroy()` from JavaScript. | - -For example, disable a native button when its original action is unavailable: - -```swift -Button("Increment") { - Task { @MainActor in - do { try await actions.activate("increment") } - catch { /* Present an application-appropriate error. */ } - } -} -.disabled(!actions.isAvailable("increment")) -``` - -Availability is a snapshot, not a reservation: a target can disappear before activation, so handle errors too. Custom text, selected state, fonts, colors, and badges belong in your extension's `props` and SwiftUI View; the shell does not infer a custom component's visual structure from CSS. Read the desired element's computed styles and attributes in your reader. Use the shared image and color conversion APIs below instead of reimplementing those transformations. - -## Schedule a source check - -DOM attributes, text, children, observed element sizes, scrolling, and supported lifecycle events trigger automatic checks. The shell does not poll JavaScript variables or arbitrary DOM properties. After changing state that your reader uses without a DOM mutation, request a check: - -```ts -source.playbackPosition = newPosition; // An application-defined property read by your extension. -shell.markForCheck(); -``` - -`markForCheck(): void` schedules a re-read and geometry measurement; it does not update the application's DOM or force a native redraw. Repeated calls are batched, and unchanged snapshots are not sent. A call during a bridge update schedules another check afterwards. Suspended projection stays suspended until resumed. Calls after `destroy()` or in an environment without a projection runtime do nothing. - -Call after your framework has committed any relevant DOM changes. This API does not trigger Angular change detection, React rendering, or Vue rendering, and it is not a promise that waits for native completion. It also works for standard controls when their properties change without an observable mutation. - -## Reuse native artwork and color conversion - -A reader's second argument exposes the standard SVG capture and rasterization path. It accepts a local `svg` or a resolved `ion-icon` belonging to the source and returns an **opaque image reference**, or `null` for unsupported artwork. Return the reference in `props`; do not try to read image bytes synchronously: - -```ts -const badge = defineNativeUI({ - name: 'app.badge', - selector: '[data-badge]', - read(element, context) { - return { - props: { - icon: context.image(element.querySelector('ion-icon')), - color: getComputedStyle(element).color, - }, - }; - }, -}); -``` - -Before sending the snapshot, the shell resolves references into `{ data, width, height, template }`: base64 PNG data, CSS dimensions, and rendering mode. Nested references and copies are supported; the `$nativeUIImage` key is reserved for references returned by the current read context. Use `{ template: true }` as the second argument to `image()` when SwiftUI should tint the icon; the default preserves source colors. The same local SVG restrictions, RTL capture, display-scale rasterization, and image cache used by standard controls apply. External resources and unsupported SVG content return `null`; unresolved `ion-icon` content should retain your Web fallback until loaded. Rasterization failure or props exceeding the size limit keeps that extension on the Web. - -On iOS, decode the resulting value with `NativeUIImage` and use the shared converters: - -```swift -struct BadgeProps: Decodable { - let icon: NativeUIImage? - let color: String -} - -struct BadgeView: View { - let props: BadgeProps - var body: some View { - if let icon = props.icon, let image = NativeUIRendering.image(icon) { - Image(uiImage: image) - .foregroundStyle(Color(uiColor: NativeUIRendering.color(props.color))) - } - } -} -``` - -`NativeUIRendering.image` returns `nil` for invalid image data. `NativeUIRendering.color` accepts computed `rgb()`/`rgba()` values; unsupported formats use `.label`, or the `fallback:` color you pass. Both are shared with the standard native renderers. They do not evaluate CSS selectors, variables, named colors, or arbitrary stylesheets. - -## Lifecycle and action completion - -The shell owns discovery, geometry, state synchronization, native controller containment, overlay retirement, suspension and teardown. Extensions do not implement attach/detach hooks. Web sources are hidden only after native accepts the projection. An unregistered renderer, a failing props decoder, unsupported placement or failed reader leaves that instance on the Web. Existing shell overlay policy applies; extensions return to the Web while Web overlays cover the page. - -Element placement requires the source to fit fully inside the viewport and its ancestors' overflow clipping bounds, including Ionic's shadow scroll containers. Partially clipped sources stay on the Web and become eligible again when scrolled fully into view. Tab accessories use the system host's placement instead. - -### Action completion - -| Event | Result of `try await actions.activate(name)` | -| ------------------------------------------------------------------ | -------------------------------------------- | -| Original Web element receives its click | Completes. | -| Handler starts a network request, navigation or modal presentation | Does not wait for that application work. | -| Action is disabled, removed or stale | Rejects. | -| Teardown, native task cancellation or bridge timeout | Settles pending calls. | - -The bridge acknowledgement is a Capacitor Promise method. - -The [demo reader](https://github.com/webview-native-ui/ionic-theme-ios27/blob/main/demo/src/native-ui/counter.ts) and [demo SwiftUI View](https://github.com/webview-native-ui/ionic-theme-ios27/blob/main/demo/ios/App/App/NativeUICounter.swift) show both placements using app-local files. Open the Native UI demo page to compare native projection with its Web fallback. - -## Example: mini-player - -The demo mini-player shows the same pattern with track metadata and playback actions: a [DOM reader and Web fallback](https://github.com/webview-native-ui/ionic-theme-ios27/blob/main/demo/src/native-ui/mini-player.ts) paired with an [app-local SwiftUI View](https://github.com/webview-native-ui/ionic-theme-ios27/blob/main/demo/ios/App/App/NativeMiniPlayer.swift). The Web app owns playback state and modal presentation; native `open` and `toggle` actions activate its original buttons. This is a UI example, not an audio engine. Adapt the files after completing the extension setup above. +## Extension reference + +- [Reader contract](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#reader-contract) +- [Native scroll tracking on iOS (experimental)](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#native-scroll-tracking-on-ios-experimental) +- [Content and placement are independent](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#content-and-placement-are-independent) +- [Tab accessory requirements](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#tab-accessory-requirements) +- [Read source geometry and presentation state](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#read-source-geometry-and-presentation-state) +- [Use the shared projection capabilities](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#use-the-shared-projection-capabilities) +- [Schedule a source check](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#schedule-a-source-check) +- [Reuse native artwork and color conversion](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#reuse-native-artwork-and-color-conversion) +- [Lifecycle and action completion](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#lifecycle-and-action-completion) +- [Action completion](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#action-completion) +- [Example: mini-player](https://github.com/webview-native-ui/capacitor-plugin/blob/main/docs/native-ui-extension-reference.md#example-mini-player) diff --git a/docs/native-ui.md b/docs/native-ui.md index b4c21d2..7a99b17 100644 --- a/docs/native-ui.md +++ b/docs/native-ui.md @@ -131,7 +131,7 @@ The table below describes the ordinary Native UI. Vertical Bars uses the separat | Ionic component | Supported appearance and placement | Native rendering | | --------------------------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | -| `ion-button` | Fixed toolbar: default, clear in ungrouped `ion-buttons`, or solid: `type="submit"` or `.button-submit` | Glass `UIButton`, prominent for solid submit actions | +| `ion-button` | Fixed toolbar: default, clear in ungrouped `ion-buttons`, or solid: `type="submit"` or `.button-submit` | Glass `UIButton`, prominent for solid submit buttons | | `ion-buttons` | Fixed toolbar, two or more direct clear `ion-button` / `ion-menu-button` children sharing the theme glass | One `UIGlassEffect` surface with independent native buttons | | `ion-back-button` | Standard icon and color in a fixed header/footer toolbar | Glass `UIButton`, using the resolved Ionic label/icon | | `ion-menu-button` | Fixed toolbar, inside the theme glass `ion-buttons` | Glass `UIButton`; original Ionic menu toggle | @@ -139,7 +139,7 @@ The table below describes the ordinary Native UI. Vertical Bars uses the separat | `ion-segment` | Fixed toolbar, non-scrollable, text **or** one icon per item | `UISegmentedControl` | | `ion-fab` / `ion-fab-button` / `ion-fab-list` | Glass FAB in an `ion-content` fixed slot; one main button and optional directional lists | Persistent glass `UIButton` per button; one FAB synchronization group | -Solid submit actions (`fill="solid"` with `type="submit"` or `.button-submit`) also support Ionic `color`, such as `color="primary"`. Their prominent glass tint comes from the resolved Web background color. In a mixed `ion-buttons` container, they project individually rather than joining a shared glass surface. The existing color restriction for other individually projected horizontal `ion-button` actions remains unchanged. +Solid submit buttons (`fill="solid"` with `type="submit"` or `.button-submit`) also support Ionic `color`, such as `color="primary"`. Their prominent glass tint comes from the resolved Web background color. In a mixed `ion-buttons` container, they project individually rather than joining a shared glass surface. The existing color restriction for other individually projected horizontal `ion-button` actions remains unchanged. For the ordinary Native UI, only supported iOS-mode components are eligible. Theme variables are not required; calling `enableNativeUI()` opts into native projection. Explicitly enabled Vertical Bars is mode-independent as described below. `ios-theme-disabled` and the legacy `ios26-disabled` on an element or ancestor always exclude it. A disabled theme on one tab/segment item keeps its whole group on the Web. diff --git a/docs/setup.md b/docs/setup.md index 229e625..d6ffc9b 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -1,6 +1,6 @@ # Set up Native UI in an Ionic app -Install the packages, configure the theme, and start Native UI. Ordinary controls and **Vertical Bars are enabled by default**; the device determines whether a native rail is available. +Use this guide for an Ionic app with Capacitor 8 and the iOS 27 theme. To keep your current theme, follow [Set up Vertical Bars with an existing theme](ionic-vertical-bars.md). Ordinary controls and **Vertical Bars are enabled by default**; the device determines whether a native rail is available. ## 1. Install the packages @@ -8,7 +8,7 @@ Install the packages, configure the theme, and start Native UI. Ordinary control npm install @rdlabo/capacitor-native-ui @rdlabo/ionic-theme-ios27 @erkamyaman/capacitor-foldable ``` -Use an existing Ionic app with Capacitor 8 and an iOS project. The standard setup uses the iOS 27 theme preset and Foldable 8.5 or later within version 8. +The iOS build requires an iOS project. This setup uses the iOS 27 theme preset and Foldable 8.5 or later within version 8. ## 2. Configure the theme diff --git a/docs/vertical-bars.md b/docs/vertical-bars.md index dc02a98..7455ad2 100644 --- a/docs/vertical-bars.md +++ b/docs/vertical-bars.md @@ -275,10 +275,10 @@ Use `ionic.verticalBars.buttonProjection` to choose native button appearance. For native vertical `ion-button` and `ion-menu-button` actions, choose who controls appearance: -| `buttonProjection` | Appearance | -| -------------------- | ----------------------------------------------------------------------------------------------------------- | -| `'system'` (default) | SwiftUI styles the buttons and tints their icons. Ionic fill, colors and borders are not applied. | -| `'source'` | Projects the supported Ionic fill and computed colors described in [Source fill rules](#source-fill-rules). | +| `buttonProjection` | Appearance | +| -------------------- | --------------------------------------------------------------------------------------------------------------------- | +| `'system'` (default) | SwiftUI supplies the glass background. An explicit Ionic `color` tints the action. Other actions use the system tint. | +| `'source'` | Projects the supported Ionic fill and computed colors described in [Source fill rules](#source-fill-rules). | ```ts const rail = await enableNativeUI({ ionic: { verticalBars: { buttonProjection: 'source' } } }); diff --git a/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift b/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift index 25fff79..aa4d113 100644 --- a/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift +++ b/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift @@ -317,6 +317,68 @@ final class NativeUISnapshotTests: XCTestCase { XCTAssertEqual(model.groups.first?.items.first?.transitionID, "legacy") } + @MainActor func testSwiftUIToolbarBadgeUpdatesAndRemoval() async throws { + guard UIApplication.shared.delegate != nil else { throw XCTSkip("Requires hosted UIApplication") } + guard #available(iOS 26.0, *) else { throw XCTSkip("Requires native toolbar badges") } + let owner = UIViewController() + let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + let window = UIWindow(windowScene: scene) + window.frame = scene.coordinateSpace.bounds + owner.view.backgroundColor = .systemBackground + window.rootViewController = owner + window.makeKeyAndVisible() + let rail = NativeUIVerticalBarsController(activate: { _ in }, changed: { _, _, _, _, _ in 0 }) + rail.attach(to: owner, in: owner.view) + defer { rail.detach(); window.isHidden = true } + func buttons(_ vc: UIViewController) -> [UIBarButtonItem] { + let own = (vc as? UINavigationController)?.navigationBar.items?.flatMap { + ($0.leadingItemGroups + $0.centerItemGroups + $0.trailingItemGroups).flatMap(\.barButtonItems) + } ?? [] + return own + vc.children.flatMap(buttons) + } + let image = UIImage(systemName: "ellipsis")!.pngData()!.base64EncodedString() + for (value, background, foreground) in [("3", "rgb(0, 84, 233)", "rgb(255, 255, 255)"), + ("3", "rgb(45, 211, 111)", "rgb(0, 0, 0)"), + ("99+", "rgb(0, 84, 233)", "rgb(255, 255, 255)"), + ("", "rgb(0, 84, 233)", "rgb(255, 255, 255)"), + (nil, "rgb(0, 84, 233)", "rgb(255, 255, 255)")] as [(String?, String, String)] { + var inboxItem = item(["id": "inbox", "label": "Inbox", "transitionId": "badge-inbox", + "icon": image, "iconWidth": 24.0, "iconHeight": 24.0, "iconTemplate": true]) + if let value { + inboxItem["badge"] = ["value": value, "color": background, "textColor": foreground] + } + let settingsItem = item(["id": "settings", "label": "Settings", "transitionId": "badge-settings", + "icon": image, "iconWidth": 24.0, "iconHeight": 24.0, "iconTemplate": true]) + let group = control(["kind": "button-group", "placement": "vertical-bars", + "transitionId": "badge-group", "items": [inboxItem, settingsItem]]) + let nodes = try decode([group]).controls + rail.apply(nodes, rendering: NativeUIControlRendering(), edge: "right", animated: false) + for _ in 0..<40 { + owner.view.layoutIfNeeded() + if let inbox = buttons(owner).first(where: { $0.identifier == "badge-inbox" }), + (value == nil ? inbox.badge == nil : inbox.badge != nil), + value == nil || value == "" || inbox.badge?.stringValue == value { break } + try await Task.sleep(nanoseconds: 50_000_000) + } + let inbox = try XCTUnwrap(buttons(owner).first { $0.identifier == "badge-inbox" }) + XCTAssertEqual(inbox.badge != nil, value != nil) + if let value, !value.isEmpty { XCTAssertEqual(inbox.badge?.stringValue, value) } + if value != nil { + XCTAssertEqual(inbox.badge?.backgroundColor, NativeUIRendering.color(background)) + XCTAssertEqual(inbox.badge?.foregroundColor, NativeUIRendering.color(foreground)) + } + XCTAssertNil(buttons(owner).first { $0.identifier == "badge-settings" }?.badge) + try await Task.sleep(nanoseconds: 300_000_000) + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + XCTAssertTrue(window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)) + } + let attachment = XCTAttachment(image: image) + attachment.name = "toolbar-badge-\(value.map { $0.isEmpty ? "dot" : $0 } ?? "removed")-\(background)" + attachment.lifetime = .keepAlways + add(attachment) + } + } + @MainActor func testSwiftUIToolbarForwardsTransitionIdentifier() async throws { guard #available(iOS 26.0, *) else { throw XCTSkip("Requires SwiftUI toolbar") } let owner = UIViewController() diff --git a/package-lock.json b/package-lock.json index 5ca489f..a0a2b98 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,19 +1,19 @@ { "name": "@rdlabo/capacitor-native-ui", - "version": "2.1.8", + "version": "2.1.11", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@rdlabo/capacitor-native-ui", - "version": "2.1.8", + "version": "2.1.11", "license": "MIT", "workspaces": [ "packages/native-ui-core" ], "dependencies": { "@rdlabo/ionic-theme-utils": "0.1.5", - "@webview-native-ui/engine": "1.0.9" + "@webview-native-ui/engine": "1.0.11" }, "devDependencies": { "@capacitor/android": "^8.5.3", @@ -2232,9 +2232,9 @@ "link": true }, "node_modules/@webview-native-ui/engine": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@webview-native-ui/engine/-/engine-1.0.9.tgz", - "integrity": "sha512-u99rxK+edFbJRv9Z6XKG+GOdTD70MagTB8icKxOE8RyfeyZhPX7JoQ5tqs7dS+B4JfPDDcQ2cN1Sj2rDkexb8Q==", + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@webview-native-ui/engine/-/engine-1.0.11.tgz", + "integrity": "sha512-+gSA43PpzOflopNNpR0jyDYvnw39eMcy77vhziWOug6nLpEwj14WZschM8c6k4OUNT9iJpUxRpDsrYBV6HMQJg==", "license": "MIT", "dependencies": { "@rdlabo/ionic-theme-utils": "0.1.5" @@ -8078,7 +8078,7 @@ "license": "MIT", "dependencies": { "@rdlabo/ionic-theme-utils": "0.1.5", - "@webview-native-ui/engine": "1.0.9" + "@webview-native-ui/engine": "1.0.11" }, "devDependencies": { "@ionic/core": "^8.8.19", diff --git a/package.json b/package.json index 8f827b7..bf975f6 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "2.1.8", + "version": "2.1.11", "author": "Masahiko Sakakibara ", "license": "MIT", "repository": { @@ -101,7 +101,7 @@ }, "dependencies": { "@rdlabo/ionic-theme-utils": "0.1.5", - "@webview-native-ui/engine": "1.0.9" + "@webview-native-ui/engine": "1.0.11" }, "devDependencies": { "@capacitor/android": "^8.5.3", diff --git a/packages/native-ui-core/android/src/main/java/dev/rdlabo/nativeui/core/NativeUIController.kt b/packages/native-ui-core/android/src/main/java/dev/rdlabo/nativeui/core/NativeUIController.kt index ec24385..e495848 100644 --- a/packages/native-ui-core/android/src/main/java/dev/rdlabo/nativeui/core/NativeUIController.kt +++ b/packages/native-ui-core/android/src/main/java/dev/rdlabo/nativeui/core/NativeUIController.kt @@ -32,6 +32,7 @@ class NativeUIController( private val context get() = activity private val handler = Handler(Looper.getMainLooper()) private val snapshots by lazy { NativeUISnapshots(File(context.cacheDir, "native-ui-snapshots")) } + private var stopInteractions: (() -> Unit)? = null private var host: FrameLayout? = null private var revision = 0L private var sequence = 0L @@ -53,7 +54,12 @@ class NativeUIController( } fun load() { - activity.runOnUiThread { webView.addOnLayoutChangeListener(layoutListener) } + activity.runOnUiThread { + webView.addOnLayoutChangeListener(layoutListener) + stopInteractions = snapshots.observeInteractions(activity.window) { event -> + notifyListeners("snapshotInteraction", event) + } + } } fun configure(call: NativeUICall) = onMain(call) { @@ -114,10 +120,6 @@ class NativeUIController( val (node, content) = pair val entry = entries[id] ?: Entry(ComposeView(activity), node).also { entry -> entry.view.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) - entry.clip.interaction = { active -> - snapshots.interaction(active) - notifyListeners("snapshotInteraction", JSONObject().put("active", active)) - } container.addView(entry.clip) entry.view.setContent { entry.content.value?.invoke() } entries[id] = entry @@ -229,6 +231,8 @@ class NativeUIController( notifyListeners("webViewMetricsChange", JSONObject().put("radius", 0)) } fun destroy() { + stopInteractions?.invoke() + stopInteractions = null webView.removeOnLayoutChangeListener(layoutListener) clearViews() snapshots.close() diff --git a/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift b/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift index 9d0df42..9f0dbb9 100644 --- a/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift +++ b/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift @@ -22,6 +22,7 @@ final class NativeUIVerticalBarsModel: ObservableObject { let accessibilityLabel: String let image: UIImage? let clear: Bool + var foregroundTint: Color? = nil let background: Color? let borderColor: Color? let borderWidth: CGFloat @@ -63,6 +64,9 @@ final class NativeUIVerticalBarsModel: ObservableObject { // UIKit toolbar extraction uses the UIImage's rendering mode. image: source.content.disabled ? image?.withRenderingMode(.alwaysTemplate) : image, clear: source.content.buttonFill == .clear, + foregroundTint: source.content.iconTemplate == true && source.content.buttonStyle != .prominent && + !source.content.disabled && source.content.color.hasPrefix("rgb") + ? Color(uiColor: rendering.color(source.content.color)) : nil, background: source.content.buttonStyle == .prominent ? Color(uiColor: rendering.color(source.content.color)) : source.content.backgroundColor.map { Color(uiColor: rendering.color($0)) }, @@ -148,6 +152,8 @@ private struct NativeUIVerticalBarsLabel: View { @ViewBuilder private func verticalBarsButton(_ item: NativeUIVerticalBarsModel.Item, model: NativeUIVerticalBarsModel) -> some View { let button = Button { model.activate(item.id) } label: { NativeUIVerticalBarsLabel(item: item) } + .modifier(NativeUIVerticalBarsBadge(badge: item.badge)) + .accessibilityValue(item.badge?.value ?? "") .disabled(item.disabled) .accessibilityLabel(item.accessibilityLabel) .accessibilityIdentifier(item.isBack ? "BackButton" : item.id) @@ -156,6 +162,8 @@ private func verticalBarsButton(_ item: NativeUIVerticalBarsModel.Item, model: N } if let background = item.background { button.buttonStyle(.glassProminent).tint(background) + } else if let tint = item.foregroundTint { + button.tint(tint) } else { button.overlay { if let borderColor = item.borderColor { @@ -453,12 +461,14 @@ final class NativeUIVerticalBarsController: NativeUIVerticalBarsControlling { var railEdge = "right" var layoutSearch: (() -> Void)? var layoutTabs: (() -> Void)? + var layoutBadges: (() -> Void)? var layoutToolbar: (() -> Void)? override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() layoutSurfaces() layoutSearch?() layoutTabs?() + layoutBadges?() layoutToolbar?() } @@ -577,12 +587,16 @@ final class NativeUIVerticalBarsController: NativeUIVerticalBarsControlling { model.activate = activate // UIKit can materialize tab/navigation backings after the hosting layout. // Reuse the same transparency policy at the inner content layout boundary. - model.layoutSurfaces = { [weak self] in self?.controller.layoutSurfaces() } + model.layoutSurfaces = { [weak self] in + self?.controller.layoutSurfaces() + self?.applyToolbarBadgeAppearance() + } container.backgroundColor = .clear controller.view.backgroundColor = .clear controller.view.isOpaque = false controller.layoutSearch = { [weak self] in self?.model.search?.configureField() } controller.layoutTabs = { [weak self] in self?.applyTabTint() } + controller.layoutBadges = { [weak self] in self?.applyToolbarBadgeAppearance() } } private var toolbarLayoutGeneration = 0 @@ -622,6 +636,32 @@ final class NativeUIVerticalBarsController: NativeUIVerticalBarsControlling { private weak var tintedTabBar: UITabBar? private var appliedTabTint: String? + private func applyToolbarBadgeAppearance() { + MainActor.assumeIsolated { + let badges = Dictionary(model.groups.flatMap(\.items).compactMap { item in + item.badge.map { (item.transitionID, $0) } + }, uniquingKeysWith: { _, latest in latest }) + @MainActor func apply(in controller: UIViewController) { + let items = (controller as? UINavigationController)?.navigationBar.items ?? [] + let buttons = items.flatMap { + ($0.leadingItemGroups + $0.centerItemGroups + $0.trailingItemGroups).flatMap(\.barButtonItems) + } + (controller.toolbarItems ?? []) + for button in buttons { + guard let id = button.identifier, let source = badges[id], var badge = button.badge else { continue } + let background = NativeUIRendering.color(source.color) + let foreground = NativeUIRendering.color(source.textColor) + // Setting an unchanged badge schedules another UIKit layout pass. + guard badge.backgroundColor != background || badge.foregroundColor != foreground else { continue } + badge.backgroundColor = background + badge.foregroundColor = foreground + button.badge = badge + } + controller.children.forEach(apply) + } + apply(in: controller) + } + } + private func applyTabTint() { let tint = model.tabTint.map { NativeUIRendering.color($0) } func visit(_ owner: UIViewController) { @@ -683,6 +723,7 @@ final class NativeUIVerticalBarsController: NativeUIVerticalBarsControlling { } } controller.overrideUserInterfaceStyle = controls.contains(where: \.dark) ? .dark : .light + applyToolbarBadgeAppearance() } func presentPopover(anchor: String, host: NativeUIOverlayHost, completion: @escaping (Bool) -> Void) -> Bool { diff --git a/packages/native-ui-core/package.json b/packages/native-ui-core/package.json index ce25107..4ea21b7 100644 --- a/packages/native-ui-core/package.json +++ b/packages/native-ui-core/package.json @@ -45,7 +45,7 @@ }, "dependencies": { "@rdlabo/ionic-theme-utils": "0.1.5", - "@webview-native-ui/engine": "1.0.9" + "@webview-native-ui/engine": "1.0.11" }, "peerDependencies": { "@ionic/core": ">=8.8.1 <10" diff --git a/packages/native-ui-core/src/native/runtime.ts b/packages/native-ui-core/src/native/runtime.ts index f93c0e7..d42d02d 100644 --- a/packages/native-ui-core/src/native/runtime.ts +++ b/packages/native-ui-core/src/native/runtime.ts @@ -752,6 +752,7 @@ export const createRuntime = async ( return; } handoffInstant = tabSwitchHandoff || handoffAcrossPending || modalHandoff || win.performance.now() < handoffUntil; + let settledRevision: number | undefined; try { // A retained sync performs no update; keep the modal handoff armed so the // deferred retirement still runs instantly after the overlay releases. @@ -1215,6 +1216,7 @@ export const createRuntime = async ( // Sources that became ineligible must paint before their cover is removed. await painted(); } + settledRevision = snapshot.revision; } catch (error) { await fail(error); } finally { @@ -1228,7 +1230,15 @@ export const createRuntime = async ( } handoffAcrossPending = false; if (updateQueue.waiting || !updateQueue.dirty || stopped) finishWaiters(); - if (!stopped && !updateQueue.dirty && acceptedRevision === revision && !navigation.current && !verticalGesture) { + // List recycling may keep the queue dirty after an acknowledged handoff. + // Once its fade settles, that revision is ready for capture even then. + if ( + !stopped && + (!updateQueue.dirty || settledRevision === revision) && + acceptedRevision === revision && + !navigation.current && + !verticalGesture + ) { projectionSurfaces.consider(acceptedRevision, acknowledged); } } diff --git a/packages/native-ui-core/src/native/shared/candidate.ts b/packages/native-ui-core/src/native/shared/candidate.ts index 5484ee5..29b3916 100644 --- a/packages/native-ui-core/src/native/shared/candidate.ts +++ b/packages/native-ui-core/src/native/shared/candidate.ts @@ -77,10 +77,9 @@ export const appendItem = ( const labelElement = content.querySelector('[part="text"], ion-label') ?? child; const native = child.shadowRoot?.querySelector('[part="native"]'); const labelStyle = getComputedStyle(labelElement); - const badge = child.querySelector('ion-badge'); - // Rail tabs are placed independently of their Web coordinates, including their badges. - const railTab = candidate.control.kind === 'tab-bar' && isVerticalBarsSource(candidate.element); - const badgeStyle = badge && visible(badge, railTab) ? getComputedStyle(badge) : undefined; + const badge = child.querySelector(child.matches('ion-button') ? ':scope > ion-badge' : 'ion-badge'); + // Rail actions and tabs are placed independently of their Web coordinates. + const badgeStyle = badge && visible(badge, isVerticalBarsSource(candidate.element)) ? getComputedStyle(badge) : undefined; const sourceFill = (child as HTMLIonButtonElement).fill; const projectionOwner = [child, child.closest('ion-buttons')].find((element) => element?.matches('[data-projection="source"], [data-projection="system"], .ios-theme-projection-source, .ios-theme-projection-system'), @@ -102,6 +101,10 @@ export const appendItem = ( const submit = isSolidSubmit(child, fill); const prominent = submit || child.getAttribute('data-native-ui') === 'button-submit'; const buttonStyle = getComputedStyle(native ?? child); + const palette = child.getAttribute('color') || (child as HTMLIonButtonElement).color; + const paletteRGB = + systemButton && !prominent && palette ? getComputedStyle(child).getPropertyValue(`--ion-color-${palette}-rgb`).trim() : ''; + const systemColor = paletteRGB ? `rgb(${paletteRGB})` : 'currentColor'; const buttonFill = !systemButton && isVerticalBarsSource(child) && @@ -126,7 +129,7 @@ export const appendItem = ( selected: !!(child as ItemElement).selected, fontSize: parseFloat(labelStyle.fontSize), fontWeight: parseInt(labelStyle.fontWeight, 10) || 400, - color: submit ? buttonStyle.backgroundColor : systemButton && !prominent ? 'currentColor' : buttonStyle.color, + color: submit ? buttonStyle.backgroundColor : systemButton && !prominent ? systemColor : buttonStyle.color, iconTemplate: systemButton ? true : undefined, buttonFill, buttonStyle: prominent ? 'prominent' : undefined, diff --git a/packages/native-ui-core/src/native/vertical-bars-web.ts b/packages/native-ui-core/src/native/vertical-bars-web.ts index 39b00da..c8af688 100644 --- a/packages/native-ui-core/src/native/vertical-bars-web.ts +++ b/packages/native-ui-core/src/native/vertical-bars-web.ts @@ -272,6 +272,7 @@ export const createVerticalBarsWebProjection = ( alignVerticalBarClone(target, original, surface); }; const actionContents = new WeakMap(); + const actionBadges = new WeakMap(); const syncAction = (target: HTMLElement, original: HTMLElement) => { copyAttributes(target, original); target.classList.add('ios-theme-vertical-bars-toolbar-action', 'ion-cloned-element'); @@ -283,12 +284,51 @@ export const createVerticalBarsWebProjection = ( if ('disabled' in original) (target as HTMLIonButtonElement).disabled = (original as HTMLIonButtonElement).disabled; if (original.matches('ion-button')) { const icon = original.querySelector('ion-icon, svg'); - const text = original.textContent?.trim() || label || ''; + const badge = original.querySelector(':scope > ion-badge'); + const text = + Array.from(original.childNodes) + .filter((node) => node !== badge) + .map((node) => node.textContent ?? '') + .join('') + .trim() || + label || + ''; + // Source hiding belongs to projection ownership, not the badge's own visibility. + const badgeStyle = badge + ? unprojected(projectedSources(), () => + withoutPrehide(badge, () => { + const style = win.getComputedStyle(badge); + return { + backgroundColor: style.backgroundColor, + color: style.color, + display: style.display, + visibility: style.visibility, + opacity: style.opacity, + overlay: style.position === 'absolute', + }; + }), + ) + : undefined; const content = icon ? `icon:${icon.outerHTML}` : `text:${text}`; - if (actionContents.get(target) === content) return; - const clonedIcon = icon?.cloneNode(true) as HTMLElement | undefined; - clonedIcon?.setAttribute('slot', 'icon-only'); - target.replaceChildren(...(clonedIcon ? [clonedIcon] : [document.createTextNode(text)])); + const badgeContent = JSON.stringify([badge?.outerHTML, badgeStyle]); + const changedContent = actionContents.get(target) !== content; + if (changedContent) { + const clonedIcon = icon?.cloneNode(true) as HTMLElement | undefined; + clonedIcon?.setAttribute('slot', 'icon-only'); + target.replaceChildren(...(clonedIcon ? [clonedIcon] : [document.createTextNode(text)])); + } + if (changedContent || actionBadges.get(target) !== badgeContent) { + target.querySelector(':scope > ion-badge')?.remove(); + const clonedBadge = badge?.cloneNode(true) as HTMLElement | undefined; + if (clonedBadge && badgeStyle) { + clonedBadge.removeAttribute('id'); + clonedBadge.toggleAttribute('data-native-ui-badge-overlay', badgeStyle.overlay); + const { overlay, ...style } = badgeStyle; + Object.assign(clonedBadge.style, style); + target.append(clonedBadge); + } + actionBadges.set(target, badgeContent); + } actionContents.set(target, content); } }; diff --git a/packages/native-ui-core/tests/native-ui-html.spec.ts b/packages/native-ui-core/tests/native-ui-html.spec.ts index a886c3e..b7ef103 100644 --- a/packages/native-ui-core/tests/native-ui-html.spec.ts +++ b/packages/native-ui-core/tests/native-ui-html.spec.ts @@ -1611,3 +1611,126 @@ test.each(['reject', 'mismatched-revision'] as const)('obsolete %s cannot clear await vi.waitFor(() => expect(snapshots.at(-1)?.controls[0]?.items[0]?.accessibilityLabel).toBe('Latest')); expect(clear).not.toHaveBeenCalled(); }); + +test('accepted sources remain capturable while list recycling leaves another update pending', async () => { + const { source, options } = mount(); + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); + vi.spyOn(window, 'matchMedia').mockReturnValue({ + matches: true, + addEventListener() {}, + removeEventListener() {}, + } as unknown as MediaQueryList); + const consider = vi.fn(); + const surface = { + owners: [], + visibleOwners: [], + preparedOwners: [], + restoring: false, + handoffPending: false, + invalidate() {}, + changed() {}, + moved() {}, + end() {}, + begin() {}, + consider, + updated() {}, + destroy: async () => {}, + } as unknown as snapshotsModule.CoveredSnapshots; + vi.spyOn(snapshotsModule, 'createCoveredSnapshots').mockResolvedValue(surface); + let recycle = false; + let acceptedRevision: number | undefined; + let release: (() => void) | undefined; + const plugin = { + addListener: async () => ({ remove: async () => {} }), + coveredSnapshot: async () => ({}), + update: async (snapshot: NativeUISnapshot) => { + if (recycle) { + if (acceptedRevision === undefined) { + acceptedRevision = snapshot.revision; + source.textContent = 'Recycled again'; + await Promise.resolve(); + } else + await new Promise((resolve) => { + release = resolve; + }); + } + return { revision: snapshot.revision }; + }, + clear: async () => {}, + } as unknown as NativeUIPlugin; + const runtime = await createRuntime(document, plugin, { ...options, coveredSnapshots: true }); + handles.push(runtime); + await vi.waitFor(() => expect(consider).toHaveBeenCalled()); + consider.mockClear(); + recycle = true; + source.textContent = 'New tab action'; + try { + await vi.waitFor(() => expect(release).toBeDefined()); + expect(consider).toHaveBeenCalledWith(acceptedRevision, expect.arrayContaining([expect.objectContaining({ element: source })])); + } finally { + recycle = false; + release?.(); + } +}); + +test('capture preparation starts only after the acquisition fade settles', async () => { + const { source, options } = mount(); + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); + vi.spyOn(window, 'matchMedia').mockReturnValue({ + matches: false, + addEventListener() {}, + removeEventListener() {}, + } as unknown as MediaQueryList); + let finish!: () => void; + const finished = new Promise((resolve) => { + finish = resolve; + }); + source.animate = vi.fn(() => ({ finished, cancel: vi.fn() }) as unknown as Animation); + const consider = vi.fn(); + const surface = { + owners: [], + visibleOwners: [], + preparedOwners: [], + restoring: false, + handoffPending: false, + invalidate() {}, + changed() {}, + moved() {}, + end() {}, + begin() {}, + consider, + updated() {}, + destroy: async () => {}, + } as unknown as snapshotsModule.CoveredSnapshots; + vi.spyOn(snapshotsModule, 'createCoveredSnapshots').mockResolvedValue(surface); + const plugin = { + addListener: async () => ({ remove: async () => {} }), + coveredSnapshot: async () => ({}), + update: async (snapshot: NativeUISnapshot) => ({ revision: snapshot.revision }), + clear: async () => {}, + } as unknown as NativeUIPlugin; + handles.push(await createRuntime(document, plugin, { ...options, coveredSnapshots: true })); + try { + await vi.waitFor(() => expect(source.hasAttribute('data-native-ui-fading')).toBe(true)); + expect(consider).not.toHaveBeenCalled(); + finish(); + await vi.waitFor(() => expect(consider).toHaveBeenCalled()); + expect(source.hasAttribute('data-native-ui-fading')).toBe(false); + } finally { + finish(); + } +}); diff --git a/packages/native-ui-core/tests/vertical-bars-button-fill.spec.ts b/packages/native-ui-core/tests/vertical-bars-button-fill.spec.ts index c3e3e82..90a5b81 100644 --- a/packages/native-ui-core/tests/vertical-bars-button-fill.spec.ts +++ b/packages/native-ui-core/tests/vertical-bars-button-fill.spec.ts @@ -129,6 +129,20 @@ test.each([undefined, 'system'] as const)('projection %s ignores source styling expect(candidate.actions.get('button-2')).toBe(disabled); }); +test('system glass follows explicit palette changes without projecting a solid fill', () => { + const button = mount(['solid']); + button.style.setProperty('--ion-color-primary-rgb', '12, 34, 56'); + button.style.setProperty('--ion-color-danger-rgb', '210, 30, 40'); + const read = () => readCandidate(button, () => 'button')!.control.items[0]; + button.setAttribute('color', 'primary'); + expect(read()).toMatchObject({ color: 'rgb(12, 34, 56)', iconTemplate: true }); + expect(read().backgroundColor).toBeUndefined(); + button.setAttribute('color', 'danger'); + expect(read().color).toBe('rgb(210, 30, 40)'); + button.removeAttribute('color'); + expect(read().color).toBe('currentColor'); +}); + test('system is the default but retains default fill for local source overrides', async () => { const first = await enableVerticalControlArea(); try { diff --git a/packages/native-ui-core/tests/vertical-bars-web.spec.ts b/packages/native-ui-core/tests/vertical-bars-web.spec.ts index 8d6aace..a4f37a5 100644 --- a/packages/native-ui-core/tests/vertical-bars-web.spec.ts +++ b/packages/native-ui-core/tests/vertical-bars-web.spec.ts @@ -123,6 +123,31 @@ test.each(['Save', '', '

('ion-badge')?.style.display).toBe('none'); + expect(target.querySelector('ion-badge')?.style.backgroundColor).toBe('rgb(45, 211, 111)'); + badge.remove(); + handle.markForCheck(); + await nextFrame(); + expect(target.querySelector('ion-badge')).toBeNull(); handle.markForCheck(); await nextFrame(); expect(target.firstChild).toBe(initial);