Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/native-ui-engine.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
62 changes: 62 additions & 0 deletions ios/Tests/NativeUIPluginTests/NativeUISnapshotTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
rdlabo marked this conversation as resolved.
Resolved
}
}

@MainActor func testSwiftUIToolbarForwardsTransitionIdentifier() async throws {
guard #available(iOS 26.0, *) else { throw XCTSkip("Requires SwiftUI toolbar") }
let owner = UIViewController()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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?()
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down
7 changes: 3 additions & 4 deletions packages/native-ui-core/src/native/shared/candidate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>('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<HTMLElement>(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'),
Expand Down
50 changes: 45 additions & 5 deletions packages/native-ui-core/src/native/vertical-bars-web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ export const createVerticalBarsWebProjection = (
alignVerticalBarClone(target, original, surface);
};
const actionContents = new WeakMap<HTMLElement, string>();
const actionBadges = new WeakMap<HTMLElement, string>();
const syncAction = (target: HTMLElement, original: HTMLElement) => {
copyAttributes(target, original);
target.classList.add('ios-theme-vertical-bars-toolbar-action', 'ion-cloned-element');
Expand All @@ -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<HTMLElement>('ion-icon, svg');
const text = original.textContent?.trim() || label || '';
const badge = original.querySelector<HTMLElement>(':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);
}
};
Expand Down
25 changes: 25 additions & 0 deletions packages/native-ui-core/tests/vertical-bars-web.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,31 @@ test.each(['Save', '<ion-icon name="save"></ion-icon>', '<svg><path d="M0 0"></p
await nextFrame();
const target = projectionState.getTarget(source)!;
const initial = target.firstChild;
const badge = document.createElement('ion-badge');
Object.assign(badge.style, { position: 'absolute', backgroundColor: 'rgb(0, 84, 233)', color: 'white' });
source.append(badge);
handle.markForCheck();
await nextFrame();
expect(target.querySelector('ion-badge')?.textContent).toBe('');
expect(target.querySelector('ion-badge')?.hasAttribute('data-native-ui-badge-overlay')).toBe(true);
expect(target.firstChild).toBe(initial);
// Angular updates the existing text node; the clone must also observe characterData.
badge.append(document.createTextNode('3'));
handle.markForCheck();
await nextFrame();
badge.firstChild!.textContent = '99+';
await nextFrame();
await nextFrame();
expect(target.querySelector('ion-badge')?.textContent).toBe('99+');
Object.assign(badge.style, { backgroundColor: 'rgb(45, 211, 111)', color: 'black', display: 'none' });
handle.markForCheck();
await nextFrame();
expect(target.querySelector<HTMLElement>('ion-badge')?.style.display).toBe('none');
expect(target.querySelector<HTMLElement>('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);
Expand Down
Loading