From 49470a09bda2c8316d7ca5d80dca40e09997ce4b Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 16 Nov 2026 18:23:30 +0900 Subject: [PATCH 1/4] feat: project toolbar button badges with Ionic colors --- .../NativeUISnapshotTests.swift | 54 +++++++++++++++++++ .../Components/NativeUIVerticalBars.swift | 36 ++++++++++++- .../src/native/shared/candidate.ts | 5 +- 3 files changed, 91 insertions(+), 4 deletions(-) diff --git a/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift b/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift index 25fff79..8e67da7 100644 --- a/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift +++ b/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift @@ -317,6 +317,60 @@ 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: String? in ["3", "99+", "", nil] { + 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": "rgb(0, 84, 233)", "textColor": "rgb(255, 255, 255)"] + } + 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) } + 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")" + 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..4f0c1ab 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?.applyToolbarBadgeColors() + } 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?.applyToolbarBadgeColors() } } private var toolbarLayoutGeneration = 0 @@ -622,6 +630,32 @@ final class NativeUIVerticalBarsController: NativeUIVerticalBarsControlling { private weak var tintedTabBar: UITabBar? private var appliedTabTint: String? + private func applyToolbarBadgeColors() { + 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) { diff --git a/packages/native-ui-core/src/native/shared/candidate.ts b/packages/native-ui-core/src/native/shared/candidate.ts index 5484ee5..4f820a7 100644 --- a/packages/native-ui-core/src/native/shared/candidate.ts +++ b/packages/native-ui-core/src/native/shared/candidate.ts @@ -78,9 +78,8 @@ export const appendItem = ( 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; + // 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'), From 3cd9cb434cca8087b9c8d99f859f427aa300027a Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 16 Nov 2026 18:33:04 +0900 Subject: [PATCH 2/4] fix: refresh badge colors and accessibility without a label change --- .../NativeUISnapshotTests.swift | 15 ++++++++++++--- .../Components/NativeUIVerticalBars.swift | 16 +++++++++------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift b/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift index 8e67da7..96a32a1 100644 --- a/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift +++ b/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift @@ -337,11 +337,15 @@ final class NativeUISnapshotTests: XCTestCase { return own + vc.children.flatMap(buttons) } let image = UIImage(systemName: "ellipsis")!.pngData()!.base64EncodedString() - for value: String? in ["3", "99+", "", nil] { + 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": "rgb(0, 84, 233)", "textColor": "rgb(255, 255, 255)"] + 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]) @@ -358,14 +362,19 @@ final class NativeUISnapshotTests: XCTestCase { } let inbox = try XCTUnwrap(buttons(owner).first { $0.identifier == "badge-inbox" }) XCTAssertEqual(inbox.badge != nil, value != nil) + XCTAssertEqual(inbox.accessibilityValue, value) 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")" + attachment.name = "toolbar-badge-\(value.map { $0.isEmpty ? "dot" : $0 } ?? "removed")-\(background)" attachment.lifetime = .keepAlways add(attachment) } 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 4f0c1ab..0397990 100644 --- a/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift +++ b/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift @@ -583,14 +583,14 @@ final class NativeUIVerticalBarsController: NativeUIVerticalBarsControlling { // Reuse the same transparency policy at the inner content layout boundary. model.layoutSurfaces = { [weak self] in self?.controller.layoutSurfaces() - self?.applyToolbarBadgeColors() + 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?.applyToolbarBadgeColors() } + controller.layoutBadges = { [weak self] in self?.applyToolbarBadgeAppearance() } } private var toolbarLayoutGeneration = 0 @@ -630,18 +630,19 @@ final class NativeUIVerticalBarsController: NativeUIVerticalBarsControlling { private weak var tintedTabBar: UITabBar? private var appliedTabTint: String? - private func applyToolbarBadgeColors() { + 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 }) + let itemsByID = Dictionary(model.groups.flatMap(\.items).map { ($0.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 } + guard let id = button.identifier, let item = itemsByID[id] else { continue } + button.accessibilityValue = item.badge?.value + guard let source = item.badge, 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. @@ -717,6 +718,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 { From 870d48cfcdb5746c7397cfd2a67ebb70cbb96afc Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 16 Nov 2026 18:36:20 +0900 Subject: [PATCH 3/4] fix: preserve SwiftUI ownership of toolbar accessibility values --- .../NativeUIPluginTests/NativeUISnapshotTests.swift | 1 - .../NativeUICore/Components/NativeUIVerticalBars.swift | 9 ++++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift b/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift index 96a32a1..aa4d113 100644 --- a/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift +++ b/ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift @@ -362,7 +362,6 @@ final class NativeUISnapshotTests: XCTestCase { } let inbox = try XCTUnwrap(buttons(owner).first { $0.identifier == "badge-inbox" }) XCTAssertEqual(inbox.badge != nil, value != nil) - XCTAssertEqual(inbox.accessibilityValue, value) if let value, !value.isEmpty { XCTAssertEqual(inbox.badge?.stringValue, value) } if value != nil { XCTAssertEqual(inbox.badge?.backgroundColor, NativeUIRendering.color(background)) 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 0397990..116db93 100644 --- a/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift +++ b/packages/native-ui-core/ios/Sources/NativeUICore/Components/NativeUIVerticalBars.swift @@ -632,17 +632,16 @@ final class NativeUIVerticalBarsController: NativeUIVerticalBarsControlling { private func applyToolbarBadgeAppearance() { MainActor.assumeIsolated { - let itemsByID = Dictionary(model.groups.flatMap(\.items).map { ($0.transitionID, $0) }, - uniquingKeysWith: { _, latest in latest }) + 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 item = itemsByID[id] else { continue } - button.accessibilityValue = item.badge?.value - guard let source = item.badge, var badge = button.badge else { continue } + 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. From 97cc5e21f7e932c3119c702238967cb454fa95b9 Mon Sep 17 00:00:00 2001 From: rdlabo Date: Mon, 16 Nov 2026 19:12:56 +0900 Subject: [PATCH 4/4] fix: preserve direct toolbar badges in Web rail projections --- .github/workflows/native-ui-engine.yml | 5 +- .../src/native/shared/candidate.ts | 2 +- .../src/native/vertical-bars-web.ts | 50 +++++++++++++++++-- .../tests/vertical-bars-web.spec.ts | 25 ++++++++++ 4 files changed, 74 insertions(+), 8 deletions(-) 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/packages/native-ui-core/src/native/shared/candidate.ts b/packages/native-ui-core/src/native/shared/candidate.ts index 4f820a7..cb0a9db 100644 --- a/packages/native-ui-core/src/native/shared/candidate.ts +++ b/packages/native-ui-core/src/native/shared/candidate.ts @@ -77,7 +77,7 @@ 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'); + 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; 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);