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/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/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift b/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift index 9d0df42..116db93 100644 --- a/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift +++ b/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift @@ -148,6 +148,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) @@ -453,12 +455,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 +581,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 +630,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 +717,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/src/native/shared/candidate.ts b/packages/native-ui-core/src/native/shared/candidate.ts index 5484ee5..cb0a9db 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'), 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/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);