Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(native): one internal Swift tooltip that follows core's useTooltip on pointer, keyboard, touch, and VoiceOver (#8402)

Cindy Zhangce34b3796175
diff --git a/packages/native/apple/Sources/Astryx/Tooltip/TooltipPresenter.swift b/packages/native/apple/Sources/Astryx/Tooltip/TooltipPresenter.swift
new file mode 100644
index 0000000000..12e4f66587
--- /dev/null
+++ b/packages/native/apple/Sources/Astryx/Tooltip/TooltipPresenter.swift
@@ -0,0 +1,511 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import AstryxNative
+import SwiftUI
+
+/// How keyboard focus reaches a tooltip, as core's `focusTrigger`.
+enum TooltipFocus: Equatable, Sendable {
+ /// The view is not a tab stop and focus shows nothing, as core's tooltip on
+ /// an element that is not focusable.
+ case none
+ /// The view is a control that takes focus already; focus shows the tooltip.
+ case control
+ /// The view is made a tab stop so focus can show the tooltip, as core gives
+ /// a static element with a tooltip a tab stop.
+ case tabStop
+}
+
+/// What a direct tap on a touch screen does, as core's `touchTrigger`.
+enum TooltipTouch: Equatable, Sendable {
+ /// Core's default: a tap opens the tooltip unless the view is a control,
+ /// whose tap belongs to its action.
+ case auto
+ /// A tap always opens the tooltip; an action on the view still runs.
+ case tap
+ /// A tap never opens the tooltip.
+ case none
+}
+
+extension View {
+ /// The Astryx tooltip, one behavior for every component, following core's
+ /// `useTooltip` and `Tooltip` (`library/tooltip.spec.md`).
+ /// - Parameters:
+ /// - text: The tooltip's words; `nil` shows nothing.
+ /// - hint: Words VoiceOver reads as the hint, as core puts given tooltip
+ /// words in the description; `nil` for words already in the name.
+ /// - focus: How keyboard focus reaches the tooltip.
+ /// - touch: What a direct tap does; `auto`, core's default, by default.
+ /// - isDisabled: A disabled view shows no tooltip.
+ func astryxTooltip(
+ _ text: String?, hint: String? = nil, focus: TooltipFocus = .none, touch: TooltipTouch = .auto,
+ isDisabled: Bool = false
+ ) -> some View {
+ modifier(
+ TooltipPresenter(
+ text: TooltipPresenter.shownText(text, isDisabled: isDisabled), hint: isDisabled ? nil : hint,
+ focus: focus, touch: touch))
+ }
+}
+
+/// Core's tooltip on Apple platforms (`library/tooltip.spec.md`):
+///
+/// - The bubble sits above the view, as core places it, below when there is
+/// no room above, and slides sideways to stay inside the window's safe area
+/// with core's `space.s4` floor; long words wrap at core's 300-point width.
+/// - A resting pointer shows the bubble after 200 ms; it stays while the
+/// pointer is on the view or the bubble, hides 100 ms after it leaves both,
+/// and a press hides it.
+/// - Keyboard focus shows it at once, as core's `focusin` does, and hides it
+/// 100 ms after focus leaves; focus a pointer press brings shows nothing,
+/// as core's `:focus-visible` check keeps it shut, decided once as focus
+/// arrives. Escape hides a shown bubble wherever focus is,
+/// as core's top-most layer takes the press.
+/// - On a touch screen a direct tap opens it at once; a click from a trackpad
+/// or mouse, which hovers first, does not. The tap is shared, so the view's
+/// own action and an enclosing row still run. A tap anywhere but the view or
+/// the bubble, or a scroll or pinch anywhere but the bubble, closes it and
+/// still reaches what it lands on, as core's outside dismissal does.
+/// - VoiceOver never sees the bubble and the tap is left alone while it runs;
+/// given words are the hint.
+///
+/// It keeps one view structure whatever its words, so a change of words or a
+/// disabled toggle never rebuilds the view it decorates.
+struct TooltipPresenter: ViewModifier {
+ let text: String?
+ let hint: String?
+ let focus: TooltipFocus
+ let touch: TooltipTouch
+ @Environment(\.astryx) private var astryx
+ @Environment(\.accessibilityVoiceOverEnabled) private var voiceOver
+ @State private var isShown = false
+ @State private var isHovering = false
+ @State private var isHoveringBubble = false
+ @State private var isTapShown = false
+ @State private var pending: Task<Void, Never>?
+ @State private var viewFrame: CGRect = .zero
+ @State private var bubbleFrame: CGRect = .zero
+ @State private var window = TooltipWindowMetrics()
+ @State private var pressedAt: Date = .distantPast
+ /// Whether the keyboard brought the current focus, decided once as it
+ /// arrives, as core's `:focus-visible` check does.
+ @State private var focusIsKeyboard = false
+ @FocusState private var isFocused: Bool
+
+ /// Core's delay before showing.
+ nonisolated static var delay: Duration { .milliseconds(200) }
+ /// Core's grace before hiding, so the pointer can cross onto the bubble.
+ nonisolated static var bridge: Duration { .milliseconds(100) }
+ /// Core's widest bubble; longer words wrap.
+ nonisolated static var maximumWidth: CGFloat { 300 }
+
+ /// Whether the bubble goes above the view: core's placement, unless the
+ /// bubble and its gap would not fit between the view and `topEdge`, the
+ /// window's safe top plus core's `space.s4` floor.
+ nonisolated static func placesAbove(viewTop: CGFloat, bubbleHeight: CGFloat, gap: CGFloat, topEdge: CGFloat = 0)
+ -> Bool
+ {
+ viewTop - topEdge >= bubbleHeight + gap
+ }
+
+ /// How far the bubble, centered on the view, slides sideways to stay
+ /// inside a window `windowWidth` wide, `leading` and `trailing` from its
+ /// edges, as core's layer slides to stay inside the viewport. Zero when the
+ /// window's width is unknown.
+ nonisolated static func slide(
+ viewMinX: CGFloat, viewWidth: CGFloat, bubbleWidth: CGFloat, windowWidth: CGFloat?, margin: CGFloat,
+ trailing: CGFloat? = nil
+ ) -> CGFloat {
+ guard let windowWidth, windowWidth > 0 else { return 0 }
+ let left = viewMinX + (viewWidth - bubbleWidth) / 2
+ let lowest = margin, highest = windowWidth - (trailing ?? margin) - bubbleWidth
+ guard highest >= lowest else { return lowest - left }
+ return min(max(left, lowest), highest) - left
+ }
+
+ /// How long to wait before the bubble shows or hides: a pointer waits
+ /// core's delay; focus shows at once; hiding waits the bridge.
+ nonisolated static func wait(showing: Bool, byFocus: Bool) -> Duration {
+ showing ? (byFocus ? .zero : delay) : bridge
+ }
+
+ /// The words to show: blank words and a disabled view show nothing.
+ nonisolated static func shownText(_ text: String?, isDisabled: Bool) -> String? {
+ guard !isDisabled, let text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }
+ return text
+ }
+
+ /// Whether the bubble should be up for a pointer or the keyboard: words to
+ /// show, and the pointer on the view or the bubble, or keyboard focus where
+ /// focus reaches the tooltip.
+ nonisolated static func wantsBubble(
+ hasText: Bool, isHovering: Bool, isHoveringBubble: Bool, isFocused: Bool, focus: TooltipFocus
+ ) -> Bool {
+ hasText && (isHovering || isHoveringBubble || (isFocused && focus != .none))
+ }
+
+ /// What a tap does once `auto` is resolved as core resolves it: a tap
+ /// opens the tooltip unless the view is a control.
+ nonisolated static func resolvedTouch(_ touch: TooltipTouch, focus: TooltipFocus) -> TooltipTouch {
+ guard touch == .auto else { return touch }
+ return focus == .control ? .none : .tap
+ }
+
+ /// Whether a tap opens the bubble: a tap trigger with words, a direct touch
+ /// (a pointer hovers before it clicks), and VoiceOver not running.
+ nonisolated static func tapOpens(touch: TooltipTouch, hasText: Bool, isHovering: Bool, voiceOver: Bool) -> Bool {
+ touch == .tap && hasText && !isHovering && !voiceOver
+ }
+
+ /// Whether a gesture starting at `point`, in window coordinates, closes a
+ /// tap-opened bubble: anywhere but the bubble, and, for a tap, but the
+ /// view, whose own tap toggles it. A scroll or pinch on the view closes it.
+ nonisolated static func closesTapBubble(point: CGPoint, isTap: Bool, viewFrame: CGRect, bubbleFrame: CGRect) -> Bool {
+ !bubbleFrame.contains(point) && !(isTap && viewFrame.contains(point))
+ }
+
+ /// Whether focus came from the keyboard, as core's `:focus-visible`: not
+ /// while a pointer rests on the view, and not within a press of it.
+ nonisolated static func isKeyboardFocus(isHovering: Bool, sincePress: TimeInterval) -> Bool {
+ !isHovering && sincePress > 0.5
+ }
+
+ func body(content: Content) -> some View {
+ content
+ .modifier(TooltipTabStop(focus: focus, isOn: text != nil))
+ .focused($isFocused)
+ .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { viewFrame = $0 }
+ .simultaneousGesture(TapGesture().onEnded { pressed() })
+ .onHover { inside in
+ isHovering = inside
+ update()
+ }
+ .onChange(of: isFocused) {
+ focusIsKeyboard =
+ isFocused && Self.isKeyboardFocus(isHovering: isHovering, sincePress: Date().timeIntervalSince(pressedAt))
+ update()
+ }
+ .onChange(of: text) {
+ if text == nil { isTapShown = false }
+ update()
+ }
+ .overlay(alignment: above ? .top : .bottom) {
+ if isShown || isTapShown, let text {
+ let gap = astryx.tokens.space.s1
+ let isAbove = above
+ TooltipBubble(text: text)
+ .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { bubbleFrame = $0 }
+ .background(TooltipWindowReader { window = $0 })
+ .onHover { inside in
+ isHoveringBubble = inside
+ update()
+ }
+ .offset(x: sideways)
+ .background(TooltipEscape(hide: hideAll))
+ .background(
+ TooltipOutsideTap(isActive: isTapShown, viewFrame: viewFrame, bubbleFrame: bubbleFrame) {
+ isTapShown = false
+ })
+ // `space.s1` between the bubble and the view, above or below it.
+ .alignmentGuide(isAbove ? .top : .bottom) { d in isAbove ? d[.bottom] + gap : d[.top] - gap }
+ }
+ }
+ .zIndex(isShown || isTapShown ? 1 : 0)
+ .modifier(TooltipHint(text: hint))
+ }
+
+ /// Whether the bubble goes above the view now.
+ private var above: Bool {
+ Self.placesAbove(
+ viewTop: viewFrame.minY, bubbleHeight: bubbleFrame.height, gap: astryx.tokens.space.s1,
+ topEdge: window.safeTop + astryx.tokens.space.s4)
+ }
+
+ /// How far the bubble slides to stay inside the window now.
+ private var sideways: CGFloat {
+ Self.slide(
+ viewMinX: viewFrame.minX, viewWidth: viewFrame.width, bubbleWidth: bubbleFrame.width,
+ windowWidth: window.width, margin: window.safeLeading + astryx.tokens.space.s4,
+ trailing: window.safeTrailing + astryx.tokens.space.s4)
+ }
+
+ private func pressed() {
+ pressedAt = Date()
+ let wasTapShown = isTapShown
+ hideAll()
+ let resolved = Self.resolvedTouch(touch, focus: focus)
+ if !wasTapShown, Self.tapOpens(touch: resolved, hasText: text != nil, isHovering: isHovering, voiceOver: voiceOver) {
+ isTapShown = true
+ }
+ }
+
+ private func hideAll() {
+ pending?.cancel()
+ isShown = false
+ isTapShown = false
+ }
+
+ /// Shows the bubble after the delay; hides it after the bridge.
+ private func update() {
+ pending?.cancel()
+ let keyboardFocused = isFocused && focusIsKeyboard
+ let wants = Self.wantsBubble(
+ hasText: text != nil, isHovering: isHovering, isHoveringBubble: isHoveringBubble,
+ isFocused: keyboardFocused || (isShown && isFocused), focus: focus)
+ guard wants != isShown else { return }
+ let byFocus = keyboardFocused && focus != .none && !isHovering && !isHoveringBubble
+ let wait = Self.wait(showing: wants, byFocus: byFocus)
+ pending = Task { @MainActor in
+ try? await Task.sleep(for: wait)
+ if !Task.isCancelled { isShown = wants }
+ }
+ }
+}
+
+/// The window that holds the bubble: its width and safe-area insets, so the
+/// bubble stays inside that window's safe area with core's `space.s4` floor.
+struct TooltipWindowMetrics: Equatable {
+ var width: CGFloat?
+ var safeTop: CGFloat = 0
+ var safeLeading: CGFloat = 0
+ var safeTrailing: CGFloat = 0
+}
+
+/// Reads the window that holds the bubble.
+private struct TooltipWindowReader: View {
+ let report: (TooltipWindowMetrics) -> Void
+
+ var body: some View {
+ TooltipWindowProbe(report: report)
+ .frame(width: 0, height: 0)
+ .accessibilityHidden(true)
+ }
+}
+
+#if os(iOS)
+private struct TooltipWindowProbe: UIViewRepresentable {
+ let report: (TooltipWindowMetrics) -> Void
+
+ func makeUIView(context: Context) -> UIView {
+ let view = UIView()
+ view.isUserInteractionEnabled = false
+ return view
+ }
+
+ func updateUIView(_ view: UIView, context: Context) {
+ let report = report
+ Task { @MainActor in
+ guard let window = view.window else { return report(TooltipWindowMetrics()) }
+ let insets = window.safeAreaInsets
+ let rtl = window.effectiveUserInterfaceLayoutDirection == .rightToLeft
+ report(
+ TooltipWindowMetrics(
+ width: window.bounds.width, safeTop: insets.top, safeLeading: rtl ? insets.right : insets.left,
+ safeTrailing: rtl ? insets.left : insets.right))
+ }
+ }
+}
+#elseif os(macOS)
+private struct TooltipWindowProbe: NSViewRepresentable {
+ let report: (TooltipWindowMetrics) -> Void
+
+ func makeNSView(context: Context) -> NSView { NSView() }
+
+ func updateNSView(_ view: NSView, context: Context) {
+ let report = report
+ Task { @MainActor in report(TooltipWindowMetrics(width: view.window?.contentView?.bounds.width)) }
+ }
+}
+#else
+private struct TooltipWindowProbe: View {
+ let report: (TooltipWindowMetrics) -> Void
+ var body: some View { Color.clear }
+}
+#endif
+
+/// Escape hides a shown bubble wherever focus is, as core's top-most layer
+/// takes the press: a hidden button bound to Escape lives while the bubble
+/// shows.
+private struct TooltipEscape: View {
+ let hide: () -> Void
+
+ var body: some View {
+ SwiftUI.Button(action: hide) { EmptyView() }
+ .keyboardShortcut(.escape, modifiers: [])
+ .focusable(false)
+ .opacity(0)
+ .frame(width: 0, height: 0)
+ .accessibilityHidden(true)
+ }
+}
+
+/// On iOS, a tap anywhere outside the view closes a tap-opened bubble and
+/// still reaches what it lands on, as core's outside tap does: a recognizer on
+/// the window that never cancels the touch.
+private struct TooltipOutsideTap: View {
+ let isActive: Bool
+ let viewFrame: CGRect
+ let bubbleFrame: CGRect
+ let close: () -> Void
+
+ var body: some View {
+ #if os(iOS)
+ TooltipOutsideTapMonitor(isActive: isActive, viewFrame: viewFrame, bubbleFrame: bubbleFrame, close: close)
+ .frame(width: 0, height: 0)
+ .accessibilityHidden(true)
+ #else
+ EmptyView()
+ #endif
+ }
+}
+
+#if os(iOS)
+import UIKit
+
+private struct TooltipOutsideTapMonitor: UIViewRepresentable {
+ let isActive: Bool
+ let viewFrame: CGRect
+ let bubbleFrame: CGRect
+ let close: () -> Void
+
+ func makeCoordinator() -> Coordinator { Coordinator() }
+
+ func makeUIView(context: Context) -> UIView {
+ let view = UIView()
+ view.isUserInteractionEnabled = false
+ return view
+ }
+
+ func updateUIView(_ view: UIView, context: Context) {
+ let coordinator = context.coordinator
+ coordinator.viewFrame = viewFrame
+ coordinator.bubbleFrame = bubbleFrame
+ coordinator.close = close
+ let isActive = isActive
+ // The view joins its window after this update, so attach on the next turn.
+ Task { @MainActor in coordinator.attach(to: isActive ? view.window : nil) }
+ }
+
+ static func dismantleUIView(_ view: UIView, coordinator: Coordinator) {
+ coordinator.attach(to: nil)
+ }
+
+ @MainActor final class Coordinator: NSObject, UIGestureRecognizerDelegate {
+ var viewFrame: CGRect = .zero
+ var bubbleFrame: CGRect = .zero
+ var close: () -> Void = {}
+ private var recognizers: [UIGestureRecognizer] = []
+ private weak var window: UIWindow?
+
+ func attach(to newWindow: UIWindow?) {
+ guard newWindow !== window || (newWindow != nil && recognizers.isEmpty) else { return }
+ for recognizer in recognizers { window?.removeGestureRecognizer(recognizer) }
+ recognizers = []
+ window = newWindow
+ guard let newWindow else { return }
+ // A tap, a scroll, or a pinch that starts outside closes the bubble.
+ let made: [UIGestureRecognizer] = [
+ UITapGestureRecognizer(target: self, action: #selector(began(_:))),
+ UIPanGestureRecognizer(target: self, action: #selector(began(_:))),
+ UIPinchGestureRecognizer(target: self, action: #selector(began(_:))),
+ ]
+ for recognizer in made {
+ // The gesture still reaches what it lands on.
+ recognizer.cancelsTouchesInView = false
+ recognizer.delaysTouchesBegan = false
+ recognizer.delaysTouchesEnded = false
+ recognizer.delegate = self
+ newWindow.addGestureRecognizer(recognizer)
+ }
+ recognizers = made
+ }
+
+ @objc func began(_ recognizer: UIGestureRecognizer) {
+ guard recognizer.state == .began || recognizer.state == .ended else { return }
+ let point = recognizer.location(in: recognizer.view)
+ let isTap = recognizer is UITapGestureRecognizer
+ if TooltipPresenter.closesTapBubble(point: point, isTap: isTap, viewFrame: viewFrame, bubbleFrame: bubbleFrame) {
+ close()
+ }
+ }
+
+ func gestureRecognizer(
+ _ gestureRecognizer: UIGestureRecognizer,
+ shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
+ ) -> Bool { true }
+ }
+}
+#endif
+
+/// Core's tooltip surface: the primary text color behind surface-colored
+/// body text, padded `space.s1` by `space.s2`, with the container radius.
+/// VoiceOver skips it.
+struct TooltipBubble: View {
+ let text: String
+ @Environment(\.astryx) private var astryx
+
+ var body: some View {
+ SwiftUI.Text(text)
+ .font(astryx.font(size: "text-body-size", 14, weight: "text-body-weight"))
+ .foregroundStyle(astryx.tokens.color.backgroundSurface)
+ .padding(.vertical, astryx.tokens.space.s1)
+ .padding(.horizontal, astryx.tokens.space.s2)
+ .background(
+ RoundedRectangle(cornerRadius: astryx.tokens.radius.container, style: .continuous)
+ .fill(astryx.tokens.color.textPrimary)
+ )
+ .fixedSize(horizontal: false, vertical: true)
+ .modifier(TooltipWidth(maximum: TooltipPresenter.maximumWidth))
+ .accessibilityHidden(true)
+ }
+}
+
+/// Lays the bubble out at its words' own width, up to `maximum`, wrapping
+/// past it, whatever width the view it decorates offers.
+private struct TooltipWidth: ViewModifier {
+ let maximum: CGFloat
+
+ func body(content: Content) -> some View {
+ TooltipWidthLayout(maximum: maximum) { content }
+ }
+}
+
+private struct TooltipWidthLayout: Layout {
+ let maximum: CGFloat
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ guard let view = subviews.first else { return .zero }
+ let ideal = view.sizeThatFits(.unspecified)
+ return view.sizeThatFits(ProposedViewSize(width: min(ideal.width, maximum), height: nil))
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ subviews.first?.place(at: bounds.origin, proposal: ProposedViewSize(width: bounds.width, height: bounds.height))
+ }
+}
+
+/// Makes a static view a keyboard tab stop while it has a tooltip. Only a
+/// `tabStop` view gets the modifier, so a control keeps its own focus, which
+/// `focusable(false)` would take away; the branch follows `focus`, which a
+/// call site never changes, so the view keeps one structure.
+private struct TooltipTabStop: ViewModifier {
+ let focus: TooltipFocus
+ let isOn: Bool
+
+ func body(content: Content) -> some View {
+ if focus == .tabStop {
+ content.focusable(isOn)
+ } else {
+ content
+ }
+ }
+}
+
+/// Given words as the VoiceOver hint; an empty hint, which VoiceOver does not
+/// read, otherwise, so the view keeps one structure.
+private struct TooltipHint: ViewModifier {
+ let text: String?
+
+ func body(content: Content) -> some View {
+ content.accessibilityHint(SwiftUI.Text(verbatim: text ?? ""))
+ }
+}
diff --git a/packages/native/apple/Tests/AstryxTests/TooltipPresenterTests.swift b/packages/native/apple/Tests/AstryxTests/TooltipPresenterTests.swift
new file mode 100644
index 0000000000..b06257f6f2
--- /dev/null
+++ b/packages/native/apple/Tests/AstryxTests/TooltipPresenterTests.swift
@@ -0,0 +1,160 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import AstryxNative
+import SwiftUI
+import Testing
+@testable import Astryx
+
+// The Astryx tooltip (library/tooltip.spec.md), one cell at a time.
+
+@Test func tooltipsWaitCoresDelayAndBridge() {
+ #expect(TooltipPresenter.delay == .milliseconds(200))
+ #expect(TooltipPresenter.bridge == .milliseconds(100))
+}
+
+@Test func blankWordsAndADisabledViewShowNothing() {
+ #expect(TooltipPresenter.shownText("Ada", isDisabled: false) == "Ada")
+ #expect(TooltipPresenter.shownText("Ada", isDisabled: true) == nil)
+ #expect(TooltipPresenter.shownText(" \n", isDisabled: false) == nil)
+ #expect(TooltipPresenter.shownText(nil, isDisabled: false) == nil)
+}
+
+@Test func aPointerOnTheViewOrTheBubbleKeepsItUp() {
+ typealias P = TooltipPresenter
+ #expect(P.wantsBubble(hasText: true, isHovering: true, isHoveringBubble: false, isFocused: false, focus: .none))
+ #expect(P.wantsBubble(hasText: true, isHovering: false, isHoveringBubble: true, isFocused: false, focus: .none))
+ #expect(!P.wantsBubble(hasText: true, isHovering: false, isHoveringBubble: false, isFocused: false, focus: .none))
+ #expect(!P.wantsBubble(hasText: false, isHovering: true, isHoveringBubble: false, isFocused: false, focus: .none))
+}
+
+@Test func focusShowsItOnlyWhereFocusReachesTheTooltip() {
+ typealias P = TooltipPresenter
+ #expect(P.wantsBubble(hasText: true, isHovering: false, isHoveringBubble: false, isFocused: true, focus: .control))
+ #expect(P.wantsBubble(hasText: true, isHovering: false, isHoveringBubble: false, isFocused: true, focus: .tabStop))
+ #expect(!P.wantsBubble(hasText: true, isHovering: false, isHoveringBubble: false, isFocused: true, focus: .none))
+}
+
+@Test func onlyADirectTouchOnATapTriggerOpensTheBubble() {
+ typealias P = TooltipPresenter
+ #expect(P.tapOpens(touch: .tap, hasText: true, isHovering: false, voiceOver: false))
+ // A trackpad or mouse hovers before it clicks.
+ #expect(!P.tapOpens(touch: .tap, hasText: true, isHovering: true, voiceOver: false))
+ #expect(!P.tapOpens(touch: .tap, hasText: true, isHovering: false, voiceOver: true))
+ #expect(!P.tapOpens(touch: .none, hasText: true, isHovering: false, voiceOver: false))
+ #expect(!P.tapOpens(touch: .tap, hasText: false, isHovering: false, voiceOver: false))
+}
+
+@MainActor
+@Test func theBubbleDrawsInCoresTooltipColorsAndPadding() {
+ for theme in [Theme.default, Theme.butter] {
+ let bubble = Pixels(TooltipBubble(text: "Ada Lovelace"), theme: theme)
+ #expect(close(bubble.at(bubble.width / 2, 2), rgba(theme.light.color.textPrimary), within: 6))
+ // Padded on every side: the corners of the padding hold no ink.
+ let space = theme.light.space
+ #expect(bubble.height > Int(2 * space.s1) + 10)
+ #expect(bubble.width > Int(2 * space.s2) + 40)
+ }
+}
+
+@MainActor
+@Test func aViewWithATooltipDrawsAsItDidWithout() {
+ // The tooltip adds nothing to the view's own drawing until it shows.
+ let plain = Pixels(Color.red.frame(width: 20, height: 20))
+ let decorated = Pixels(Color.red.frame(width: 20, height: 20).astryxTooltip("Ada", touch: .tap))
+ #expect(plain.width == decorated.width && plain.height == decorated.height)
+ #expect(plain.at(10, 10) == decorated.at(10, 10))
+}
+
+@Test func theBubbleSitsAboveUnlessThereIsNoRoom() {
+ typealias P = TooltipPresenter
+ #expect(P.placesAbove(viewTop: 200, bubbleHeight: 25, gap: 4))
+ #expect(P.placesAbove(viewTop: 29, bubbleHeight: 25, gap: 4))
+ #expect(!P.placesAbove(viewTop: 20, bubbleHeight: 25, gap: 4))
+}
+
+@Test func aPointerWaitsFocusShowsAtOnceAndHidingWaitsTheBridge() {
+ typealias P = TooltipPresenter
+ #expect(P.wait(showing: true, byFocus: false) == .milliseconds(200))
+ #expect(P.wait(showing: true, byFocus: true) == .zero)
+ #expect(P.wait(showing: false, byFocus: false) == .milliseconds(100))
+ #expect(P.wait(showing: false, byFocus: true) == .milliseconds(100))
+}
+
+@MainActor
+@Test func longWordsWrapAtCoresWidth() {
+ #expect(TooltipPresenter.maximumWidth == 300)
+ let short = Pixels(TooltipBubble(text: "beach.jpg"))
+ let long = Pixels(TooltipBubble(text: String(repeating: "a-very-long-file-name ", count: 8)))
+ #expect(short.width < 300)
+ #expect(long.width <= 300)
+ #expect(long.height > short.height * 2)
+}
+
+@Test func theBubbleSlidesToStayInsideTheWindow() {
+ typealias P = TooltipPresenter
+ // Centered on a view in the middle: no slide.
+ #expect(P.slide(viewMinX: 180, viewWidth: 40, bubbleWidth: 100, windowWidth: 400, margin: 4) == 0)
+ // Near the left edge: slides right to the margin.
+ #expect(P.slide(viewMinX: 0, viewWidth: 40, bubbleWidth: 100, windowWidth: 400, margin: 4) == 34)
+ // Near the right edge: slides left.
+ #expect(P.slide(viewMinX: 360, viewWidth: 40, bubbleWidth: 100, windowWidth: 400, margin: 4) == -34)
+ // An unknown window: no slide.
+ #expect(P.slide(viewMinX: 0, viewWidth: 40, bubbleWidth: 100, windowWidth: nil, margin: 4) == 0)
+}
+
+@Test func aGestureElsewhereClosesATapOpenedBubbleButNotOnTheBubble() {
+ let view = CGRect(x: 100, y: 100, width: 40, height: 40)
+ let bubble = CGRect(x: 80, y: 60, width: 80, height: 30)
+ typealias P = TooltipPresenter
+ #expect(P.closesTapBubble(point: CGPoint(x: 10, y: 10), isTap: true, viewFrame: view, bubbleFrame: bubble))
+ // A tap on the view toggles it instead; a scroll or pinch on the view closes it.
+ #expect(!P.closesTapBubble(point: CGPoint(x: 120, y: 120), isTap: true, viewFrame: view, bubbleFrame: bubble))
+ #expect(P.closesTapBubble(point: CGPoint(x: 120, y: 120), isTap: false, viewFrame: view, bubbleFrame: bubble))
+ // A gesture on the bubble is left alone.
+ #expect(!P.closesTapBubble(point: CGPoint(x: 90, y: 70), isTap: true, viewFrame: view, bubbleFrame: bubble))
+ #expect(!P.closesTapBubble(point: CGPoint(x: 90, y: 70), isTap: false, viewFrame: view, bubbleFrame: bubble))
+}
+
+@Test func onlyKeyboardFocusShowsTheBubble() {
+ #expect(TooltipPresenter.isKeyboardFocus(isHovering: false, sincePress: 10))
+ // Focus a pointer brings: while it rests on the view, or right after a press.
+ #expect(!TooltipPresenter.isKeyboardFocus(isHovering: true, sincePress: 10))
+ #expect(!TooltipPresenter.isKeyboardFocus(isHovering: false, sincePress: 0.1))
+}
+
+@Test func autoTouchOpensUnlessTheViewIsAControl() {
+ typealias P = TooltipPresenter
+ #expect(P.resolvedTouch(.auto, focus: .none) == .tap)
+ #expect(P.resolvedTouch(.auto, focus: .tabStop) == .tap)
+ #expect(P.resolvedTouch(.auto, focus: .control) == .none)
+ // Explicit choices override, as core's `tap` and `none`.
+ #expect(P.resolvedTouch(.tap, focus: .control) == .tap)
+ #expect(P.resolvedTouch(.none, focus: .none) == .none)
+}
+
+@Test func noSwiftViewUsesHelpForTooltips() throws {
+ // `.help` is also the VoiceOver hint and never shows on focus or a tap, so
+ // every tooltip goes through `astryxTooltip` (library/tooltip.spec.md).
+ let sources = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ .appendingPathComponent("Sources")
+ let files = FileManager.default.enumerator(at: sources, includingPropertiesForKeys: nil)?
+ .compactMap { $0 as? URL }.filter { $0.pathExtension == "swift" } ?? []
+ #expect(!files.isEmpty)
+ for file in files {
+ let text = try String(contentsOf: file, encoding: .utf8)
+ #expect(!text.contains(".help("), "\(file.lastPathComponent) uses .help")
+ }
+}
+
+@Test func theBubbleStaysInsideTheSafeAreaWithCoresFloor() {
+ typealias P = TooltipPresenter
+ // Under a 59-point status bar with a 16-point floor, a 25-point bubble needs
+ // the view at least 59 + 16 + 25 + 4 points down to go above.
+ #expect(P.placesAbove(viewTop: 104, bubbleHeight: 25, gap: 4, topEdge: 75))
+ #expect(!P.placesAbove(viewTop: 90, bubbleHeight: 25, gap: 4, topEdge: 75))
+ // A 44-point sensor inset on the leading side with the floor.
+ #expect(P.slide(viewMinX: 0, viewWidth: 40, bubbleWidth: 100, windowWidth: 800, margin: 60, trailing: 16) == 90)
+ #expect(P.slide(viewMinX: 760, viewWidth: 40, bubbleWidth: 100, windowWidth: 800, margin: 60, trailing: 16) == -46)
+}
+
diff --git a/packages/native/specs/swift/library/README.md b/packages/native/specs/swift/library/README.md
index 164919b094..cbde4012b3 100644
--- a/packages/native/specs/swift/library/README.md
+++ b/packages/native/specs/swift/library/README.md
@@ -16,5 +16,6 @@ wins.
| `component-api.md` | How a SwiftUI view is named and takes its generated contract |
| `slots.md` | How each slot kind (text, icon, content) appears in SwiftUI |
| `styles.md` | How Astryx's look ships as SwiftUI styles |
+| `tooltip.spec.md` | How core's tooltips reach pointer, keyboard, touch, and VoiceOver (internal) |
| `theme-environment.md` | How the theme rides on SwiftUI's environment in both directions |
| `theme-generator.md` | How any Astryx theme becomes a Swift `Theme` |
diff --git a/packages/native/specs/swift/library/tooltip.spec.md b/packages/native/specs/swift/library/tooltip.spec.md
new file mode 100644
index 0000000000..b3ffc9591d
--- /dev/null
+++ b/packages/native/specs/swift/library/tooltip.spec.md
@@ -0,0 +1,130 @@
+---
+schema_version: 1
+template_version: 3
+kind: architecture
+id: architecture:native-swift-library-tooltip
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+applies_to: [packages/native/apple/Sources/Astryx/Tooltip/]
+verified_by:
+ [packages/native/apple/Tests/AstryxTests/TooltipPresenterTests.swift]
+deciding_specs: []
+---
+
+# Swift tooltip architecture
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Governing contract | `spec:AST-082` FR3: a platform honors a core prop as core does, here the tooltips core's components show through `useTooltip` and `Tooltip`, including its `touchTrigger`; `spec:AST-093` FR4. |
+| System behavior | One internal modifier, `astryxTooltip`, shows every Swift component's tooltip as core's: above the view, on a resting pointer, keyboard focus, or a direct tap; hidden by a press, Escape, or leaving; never seen by VoiceOver. |
+| End-user impact | A person on an iPhone, an iPad, or a Mac reads a tooltip the same way in every component and as on the web, and a VoiceOver user hears its words once. |
+| Builder impact | A component passes its words, its hint, and how focus and touch reach it; it does not build its own tooltip. |
+| Compatibility/readiness | Internal; no public API. Draft; hover, focus, Escape, and tap are tested as logic until an app-hosted UI test exists. |
+| Review checks | Reject a component tooltip built outside `astryxTooltip`, SwiftUI's `.help` anywhere in the package, a bubble VoiceOver reads, a tap that keeps an enclosing row from running, or a change that rebuilds the decorated view. |
+| Governing rules | `spec:AST-082` FR3; `spec:AST-093` FR2, FR4. |
+
+This table is a review projection; the body below is authoritative.
+
+## Purpose
+
+Core's components show tooltips through one hook, so every tooltip on the web
+opens, places, and dismisses the same way. This record states how Swift does
+the same: one internal modifier that every Swift component uses, so a
+component records only its words and which inputs reach its tooltip.
+
+## System model
+
+A component calls `astryxTooltip(_ text:, hint:, focus:, touch:, isDisabled:)`
+on the view the tooltip describes.
+
+- `text` is the tooltip's words. Blank words and a disabled view show nothing.
+- `hint` is words VoiceOver reads as the hint, as core puts given tooltip words
+ in the description; it is `nil` for words already in the view's name.
+- `focus` says how keyboard focus reaches the tooltip, as core's
+ `focusTrigger`: `none` (focus shows nothing, as on an element that is not
+ focusable), `control` (the view is a control that takes focus already), or
+ `tabStop` (a static view is made a tab stop while it has words, as core gives
+ a static element with a tooltip a tab stop).
+- `touch` says what a direct tap does, as core's `touchTrigger`: `auto` (the
+ default) opens the tooltip unless the view is a control, `tap` always opens
+ it, and `none` never does.
+
+The bubble is an overlay drawn in core's tooltip look, the same on every input. SwiftUI's `.help` does not fit: it is also
+the VoiceOver hint, so it reads words already in a view's name twice, and it
+shows with the system's own look and delay, never on keyboard focus or a tap.
+
+## Boundaries and invariants
+
+- **INV1 — Placement and size.** The bubble sits `space.s1` above the view, as
+ core places it, below when the bubble and its gap do not fit under the
+ window's safe top plus core's `space.s4` floor, and slides sideways to stay
+ inside the safe area of the window that holds the view with the same floor,
+ as core's layer stays inside the viewport. Its words wrap past core's
+ 300-point width. The bubble draws in the view's own layer, so a scroll view
+ or another clipping container around the view cuts it off, where core's top
+ layer is never clipped.
+- **INV2 — Pointer.** A pointer resting on the view shows the bubble after
+ core's 200 ms. It stays while the pointer is on the view or on the bubble,
+ hides 100 ms after the pointer leaves both, and a press hides it.
+- **INV3 — Keyboard focus.** Where focus reaches the tooltip, focus the
+ keyboard brings shows the bubble at once, as core's `focusin` does, and it
+ hides 100 ms after focus leaves. Whether the keyboard brought focus is
+ decided once, as focus arrives, as core's `:focus-visible` check is: focus
+ that arrives while a pointer rests on the view, or within half a second of a
+ press, shows nothing until focus leaves and returns. SwiftUI does not say who
+ moved focus, so focus code moves counts as the keyboard's.
+- **INV4 — Escape.** Escape hides a shown bubble wherever focus is and goes no
+ further, as core's top-most layer takes the press.
+- **INV5 — Touch.** `auto`, core's default, opens the tooltip on a tap unless
+ the view is a control (`focus: control`), whose tap belongs to its action;
+ `tap` and `none` override it, as core's. A direct tap opens the bubble at
+ once; a click from a trackpad or mouse, which hovers first, opens nothing.
+ The tap is a simultaneous gesture, so the view's own action and an enclosing
+ row's button or link still run. Another tap on the view closes it; a tap
+ anywhere but the view or the bubble, or a scroll or pinch anywhere but the
+ bubble, closes it and still reaches what it lands on, as core's outside
+ dismissal does.
+- **INV6 — Disabled and blank.** A disabled view and blank words show no
+ tooltip on any input.
+- **INV7 — VoiceOver.** VoiceOver never sees the bubble, and the tap is left
+ alone while VoiceOver runs; `hint` is the hint.
+- **INV8 — Look.** The bubble draws body text in `color.backgroundSurface` on
+ `color.textPrimary`, padded `space.s1` by `space.s2`, with
+ `radius.container`.
+- **INV9 — One structure.** The modifier keeps one view structure whatever its
+ words or disabled state, so a change never rebuilds the view it decorates.
+
+## Change coupling
+
+A change to core's `useTooltip`, `Tooltip`, or `useTouchTrigger` behavior, or
+to how a Swift component calls `astryxTooltip`, reviews this record. The
+tooltip tests prove it stays current.
+
+## Owning code
+
+- `packages/native/apple/Sources/Astryx/Tooltip/TooltipPresenter.swift` — the
+ modifier, the bubble, the Escape shortcut, and the outside-tap monitor.
+
+## Deciding specs
+
+- `spec:AST-082` FR3 — a platform honors a core prop as core does, here core's `useTooltip`, `Tooltip`, and `touchTrigger`.
+
+## Verification
+
+| Invariant | Evidence | Failure signal |
+| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
+| INV1 | `TooltipPresenterTests.swift`: above unless no room; slides inside the window; long words wrap within 300 points | a bubble below with room above, or one line past 300 points |
+| INV2 | `TooltipPresenterTests.swift`: delay and bridge; the pointer on the view or the bubble keeps it up | a bubble that hides while hovered or shows at once on a pointer |
+| INV3 | `TooltipPresenterTests.swift`: focus shows at once for `control` and `tabStop`, never for `none`; only keyboard focus | a delayed focus bubble, one on a view focus does not reach, or one a pointer's focus opens |
+| INV5 | `TooltipPresenterTests.swift`: `auto` resolves as core's; only a direct touch on a tap trigger opens it; a gesture elsewhere closes it, one on the view or the bubble does not | a bubble from a pointer click, under VoiceOver, or on a control under `auto`; one a gesture elsewhere leaves open |
+| INV6 | `TooltipPresenterTests.swift`: blank words and a disabled view show nothing | a tooltip on a disabled view |
+| INV8 | `TooltipPresenterTests.swift`: the bubble's colors and padding in two themes | a bubble in other colors |
+| INV9 | `TooltipPresenterTests.swift`: a view with a tooltip draws as it did without | a decorated view that draws differently |
+| No `.help` | `TooltipPresenterTests.swift`: no Swift source uses `.help(` | a view that shows tooltip words through `.help` |
+| INV2–INV7 | Not measured: hover, focus, Escape, and tap need an app-hosted UI test, which the package lacks | none until that test exists |