An open source design system that's fully customizable and agent ready
TypeScript
feat(native): Swift Avatar with core's picture, initials, and fallback order (#8306)
Cindy Zhang253fe637a090
diff --git a/packages/native/apple/Package.swift b/packages/native/apple/Package.swiftindex ebb6cc5238..da37c458ac 100644--- a/packages/native/apple/Package.swift+++ b/packages/native/apple/Package.swift@@ -28,7 +28,7 @@ let package = Package(dependencies: ["AstryxNative"],path: "Sources/Astryx",// Each component's spec lives beside its view (AST-093 FR1).- exclude: ["Icon/Icon.spec.md"],+ exclude: ["Avatar/Avatar.spec.md", "Icon/Icon.spec.md"],resources: [.process("Resources")]),.testTarget(name: "AstryxNativeTests", dependencies: ["AstryxNative"], path: "Tests/AstryxNativeTests"),diff --git a/packages/native/apple/README.md b/packages/native/apple/README.mdindex 344f83c5f7..aada711627 100644--- a/packages/native/apple/README.md+++ b/packages/native/apple/README.md@@ -27,6 +27,7 @@ apple/│ │ ├── Resources/ # core's messages per locale, generated; do not edit│ │ ├── Localization/│ │ ├── Icon/ # Icon, Icon.spec.md+│ │ ├── Avatar/ # Avatar, Avatar.spec.md│ │ ├── Text/ # Text│ │ ├── Heading/ # Heading│ │ ├── Button/ # Buttondiff --git a/packages/native/apple/Sources/Astryx/Avatar/Avatar.spec.md b/packages/native/apple/Sources/Astryx/Avatar/Avatar.spec.mdnew file mode 100644index 0000000000..41ac0f3d0a--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Avatar/Avatar.spec.md@@ -0,0 +1,210 @@+---+schema_version: 5+template_version: 8+kind: component+id: component:swift/Avatar+platform_of: component:Avatar+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [cixzhang]+review_triggers: [public-api, behavior, layout, theming, accessibility]+verified_by:+ [+ packages/native/apple/Tests/AstryxTests/AvatarTests.swift,+ packages/native/src/contract/contracts.test.ts,+ packages/native/src/contract/parseDocType.test.ts,+ ]+modules: []+families: []+design_specs: []+architecture: []+contributing: []+system_specs: [spec:AST-082, spec:AST-093]+---++# Avatar (Swift) component contract++## Contract at a glance++| Area | Contract |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `Avatar(_ name: String? = nil, src:, fallbackSrc:, alt:, size: AvatarSize?, shape: AvatarShape?, tooltip: AvatarTooltip?, href:, onClick:)` and `Avatar(_ props: AvatarProps)`, a SwiftUI `View` in module `Astryx`. `size` is the named sizes `xsm` to `xl`. |+| Behavior | Draws the image at `src`, else `fallbackSrc`, else initials from `name` on the theme's neutral plate, else a person symbol, clipped to its shape. With `href` it is a SwiftUI `Link`; with only `onClick` it is a button; it draws the same either way. |+| End-user impact | A person sees the same picture, initials, and shape as on the web, and VoiceOver reads the avatar's name, or skips a decorative one. |+| Builder impact | An app passes a name and an image URL, and optionally tooltip words. Pixel sizes, `status`, `target`, and `rel` have no Swift form; an `href` must be an absolute URL. |+| Compatibility/readiness | Additive: a new view and generated `AvatarProps`. Draft; built and tested on macOS and the iOS Simulator; device captures are attached to the change. |+| Review checks | Reject a size or shape beyond the contract, a disabled state, a link or button that draws differently from the static avatar, a layout that grows for the touch target, or a static avatar VoiceOver reads without a name. |+| Governing rules | `spec:AST-082` FR3, FR4, FR7; `spec:AST-093` FR1–FR5; the Swift component API (A1–A9), theme environment, and accessibility records under `packages/native/specs/swift/library/`. |++This table is a review projection; the body below is authoritative.++## Intent++Avatar on Apple platforms shows a person's or an entity's picture with core's+fallback order, sizes, shapes, and naming, drawn with SwiftUI's own image+loading and link and button controls.++## Compatibility and migration++- Released default preserved: `not yet released`+- Compatibility class: additive+- Controlled/uncontrolled behavior: not applicable+- Migration decision: none++Consumer migration instructions belong in consumer docs and release notes.++## Ownership boundary++**Owns**++- Loading `src`, then `fallbackSrc`, with SwiftUI `AsyncImage`.+- Initials, the person symbol, the plate color, and the shape clip.+- Switching to a SwiftUI `Link` or `Button` for `href` or `onClick` without+ changing the drawing.+- The avatar's VoiceOver name and its touch target.++**Does not own / non-goals**++- The meaning of the props, the initials rule, and the size scale — owned by+ `component:Avatar`.+- Status dots and avatar groups, which have no Swift view.++## Public concepts++| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ------- | ---------------------------------------------- | --------------------------------------------------- | ----------------------------------------- | -------- | ------------------------ | ------------ | -------------------------------------------------------------------------- |+| size | `xsm`, `sm`, `md`, `lg`, `xl` | 20, 24, 36, 48, 128 points at the default text size | always | `md` | `component:Avatar` | experimental | core's pixel sizes have no Swift form |+| shape | `circle`, `rounded`, `square` | full round, the theme's element radius, no radius | always | `circle` | `component:Avatar` | experimental | none |+| picture | image, fallback image, initials, person symbol | the first that is available, in that order | always | — | `component:Avatar` | experimental | an empty or unloadable URL moves to the next |+| control | static, link (`href`), button (`onClick`) | how a tap behaves; the drawing is the same | always | static | `component:swift/Avatar` | experimental | an `href` that is not an absolute URL leaves the avatar static or a button |++## Behavioral and layout contract++| ID | Candidate invariant | Basis | Draft review state |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- | ------------------ |+| FR1 | The view MUST show the image at `src`; when it is absent or fails, the image at `fallbackSrc`; then initials from a `name` that is not blank; then a person symbol. The fallback image loads only after `src` fails or when there is no `src`; while an image loads, the initials or the person symbol show. | core `Avatar` fallback order; `spec:AST-093` FR2 | verify |+| FR2 | Initials MUST follow core's rule: the first letter, digit, or emoji of the first and last words that have one, uppercased, skipping leading punctuation, keeping a whole emoji, flag, or joined emoji sequence. A name with none shows the person symbol and still names the avatar. | core `Avatar` initials | verify |+| FR3 | The avatar MUST be a square of 20, 24, 36, 48, or 128 points for `xsm` to `xl` at the default text size, grown with Dynamic Type up to 1.6 times and never shrunk, so it and its initials grow with the name beside them without swallowing a row (`spec:AST-082` FR11). It is clipped to a circle, to the theme's `radius.element`, or to a square. | core `Avatar` sizes and shapes | verify |+| FR4 | Initials and the person symbol MUST draw in `color.textSecondary` on `color.neutral`; initials use the theme's body family at medium weight and 40% of the side. | core `Avatar` fallback styles; `spec:AST-093` FR4 | verify |+| FR5 | With an `href` that is an absolute URL (it has a scheme), the avatar MUST be a SwiftUI `Link`; with `onClick` too, `onClick` runs as it opens and the URL then goes to the app's own URL handler, or the system's. An `href` that is not an absolute URL, such as a web path, MUST stop a development build with a message naming it; a release build draws the avatar without a link, as a button with `onClick` or static. With only `onClick`, a SwiftUI `Button`. Either draws exactly as the static avatar, and the avatar has no disabled state. | Swift component API A4 | verify |+| FR6 | Both initializers MUST build the same `AvatarProps`; `name` is the unlabeled first parameter and `onClick` the last, so it can be a trailing closure. Base props come through `AvatarProps`: with `isHidden` the view draws nothing; `id` becomes the accessibility identifier. | Swift component API A2–A4, A7; `spec:AST-082` FR7 | verify |+| FR8 | `tooltip` MUST resolve, as core does, to the name for `nil` or `true`, the given words for a string, and nothing for `false` or blank words, and MUST show through the Astryx tooltip (`architecture:native-swift-library-tooltip`), with the focus and touch the Tooltip by input table below states: a static avatar is a tab stop and opens on a tap; a link or button keeps its focus and its tap. Given words are the VoiceOver hint. On the wire it is the web value, a string or a Bool. | core `Avatar` `tooltip`; core `Tooltip`; `spec:AST-082` FR3 | verify |++**Tooltip by input (FR8).** The Astryx tooltip's rules apply; this table+states Avatar's choices.++| Input | Default name | Given words | Off (`false` or blank) |+| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------ |+| Pointer | the bubble shows the name above the avatar after 200 ms, stays while the pointer is on it, and a press hides it | the same, with the words | nothing |+| Keyboard focus | the bubble shows the name at once and Escape hides it; a static avatar is a tab stop | the same, with the words | nothing; a static avatar is not a tab stop |+| Touch tap | a direct tap on a static avatar opens the bubble with the name; another tap on it, or a tap anywhere else, closes it, and that tap still reaches what it lands on; the tap is shared with an enclosing row; a link or button keeps its tap | the same, with the words | nothing |+| VoiceOver | the name is read once, as the avatar's own; the bubble is hidden and the tap is left alone | the words are the hint, as core puts them in the description | nothing |++### Allowed variation++- **AV1 — Loading.** While an image loads, the initials or the person symbol+ show instead of an empty plate.+- **AV2 — Glyph.** The person symbol is the SF Symbol `person.fill`, not core's+ SVG.++- **AV3 — Tooltip surface.** The tooltip is the Astryx tooltip's bubble in+ core's tooltip colors on every input. SwiftUI's `.help` does not fit: it is+ also the VoiceOver hint, so it would read the name twice, and it shows with+ the system's look and delay, never on keyboard focus or a tap.++### Representative states++| State | Required invariant | Allowed variation |+| ------------------------------ | -------------------------------------- | ----------------- |+| image | the image fills the shape | image content |+| failed image with a fallback | the fallback image | none |+| initials, every size and shape | initials centered on the neutral plate | glyph metrics |+| no name | the person symbol at 60% of the side | none |+| link and button | the same drawing as static | none |+| light and dark, two themes | each theme's plate and text color | none |++### Transformation and precedence order++- **ORD1 — Picture.** `src` → `fallbackSrc` → initials → person symbol.+- **ORD2 — Name.** `alt` → `name` → none, where a blank string is none.+- **ORD3 — Control.** `href` (link) → `onClick` (button) → static.++### Performance and resources++- **PR1 — System loading.** Images load through `AsyncImage` and the system+ URL cache; the view keeps no image cache of its own.++## Accessibility contract++- **AR1 — Named or decorative.** A static avatar with a name is one image+ element named by `alt`, else `name`; without one it is hidden from VoiceOver.+ A link or button avatar is one element with the link or button trait and the+ same name; the initials are never an element of their own (Swift+ accessibility X1, X5).+- **AR2 — Touch target.** A link or button avatar, and a static avatar whose+ tap opens its tooltip, answers taps across at least 44 by 44 points without+ changing its drawn size or layout (X7).+- **AR3 — Rendered tree not measured.** Tests assert what the view sets; the+ rendered accessibility tree and the hit region are not measured until an+ app-hosted target exists.+- **AR4 — Unnamed taps are flagged.** A link or button avatar without `alt`+ or `name` logs a development warning, as core warns.+- **AR5 — Initials contrast.** The initials draw in core's tokens,+ `color.textSecondary` on `color.neutral`, as core's Avatar does. In the+ default and neutral themes' dark appearance that pair is below 4.5:1, in+ core as well; the fix belongs to the theme tokens.++## Design relationships++| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------- | ---------------------------------------- | ------------------------ | -------------- | ------------------ |+| Photo, initials | Apple Human Interface Guidelines, Images | prescribed by core | prominent | FR1–FR4 |++The component implements design requirements without copying their rationale.++Platform controls: SwiftUI `AsyncImage` for the images, SwiftUI `Link` for+`href`, and SwiftUI `Button` for `onClick` (`spec:AST-093` FR2). SwiftUI has no+avatar control, so the plate, initials, and clip are drawn here. Guideline+pages: Images, Buttons, and Accessibility in the Apple Human Interface+Guidelines.++Theme values read: `color.neutral`, `color.textSecondary`, `radius.element`,+`font.family.body`, `font.weight.medium`, and Bold Text; for the tooltip bubble,+`color.textPrimary`, `color.backgroundSurface`, `space.s1`, `space.s2`,+`radius.container`, and the body text size and weight.++## Family and system relationships++- `component:Avatar` owns the props, the sizes, the initials rule, and the+ fallback order; this record states only how Swift draws them.+- An owner that holds an Avatar in a slot leaves an unsized Avatar at `md`+ (Swift slots S4).++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |+| FR1, FR2 | `AvatarTests.swift` initials and fallback tests | core's initials cases; blank and symbol names | a wrong initial or a missing person symbol fails | `audit:swift/Avatar/picture` |+| FR3, FR4 | `AvatarTests.swift` size, text-size growth, shape, and two-theme renders | each size; xx-large and the largest text size; circle and square; light, dark, butter | a wrong side, no growth or growth past 1.6 times, an unclipped corner, or a color of its own fails | `audit:swift/Avatar/look` |+| FR5, AR2, AR4 | `AvatarTests.swift` link and button renders; tap, trait, tap-area, warning, `linkURL`, and web-path tests | static, link, button; malformed, relative, and empty `href` | a link or button that draws differently, a malformed `href` made a link, a web path not flagged, or an unflagged unnamed tap fails | `audit:swift/Avatar/control` |+| FR8 | `AvatarTests.swift` tooltip words, focus and touch, VoiceOver hint, and wire tests; `TooltipPresenterTests.swift` for each input; `contracts.test.ts`; `parseDocType.test.ts` | name, `true`, words, `false`, blank, no name; static, link, button | a wrong tooltip, a static avatar that is not a tab stop or does not open on a tap, a control that loses its tap, or a wire value that is not the web's fails | `audit:swift/Avatar/tooltip` |+| FR6 | `AvatarTests.swift` initializer and hidden tests; `contracts.test.ts` | both initializers; `isHidden`; named sizes | differing props, a drawn hidden avatar, or a pixel size in Swift fails | `audit:swift/Avatar/api` |+| AR1 | `AvatarTests.swift` naming and trait tests | `alt`, `name`, blank, none | a wrong name or a named decorative avatar fails | `audit:swift/Avatar/a11y` |+| AR5 | `AvatarTests.swift` two-theme renders draw the initials in core's tokens | default and neutral, light and dark | initials in tokens other than core's fail | `audit:swift/Avatar/look` |++## Decision log++No component-local decision is recorded.++## Open questions++- **OQ2 — Status dots.** (`human-api`) `status` holds `AvatarStatusDot`, which+ has no Swift view, so it stays on the web until one exists.++## Content boundary++This file does not duplicate consumer prop tables/examples, current audit+results, implementation steps, or family/system rules. It links to their owners.diff --git a/packages/native/apple/Sources/Astryx/Avatar/Avatar.swift b/packages/native/apple/Sources/Astryx/Avatar/Avatar.swiftnew file mode 100644index 0000000000..d64eaad455--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Avatar/Avatar.swift@@ -0,0 +1,418 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import AstryxNative+import SwiftUI+import os++/// A person's or an entity's picture: the image at `src`, else `fallbackSrc`,+/// else initials from `name`, else a person symbol (core `Avatar`).+///+/// ```swift+/// Avatar("Ada Lovelace", src: "https://example.com/ada.jpg")+/// Avatar("Ada Lovelace", size: .lg, shape: .rounded)+/// Avatar("Ada Lovelace", href: "https://example.com/ada")+/// Avatar("Ada Lovelace") { showProfile() }+/// ```+public struct Avatar: View {+ /// The contract the view draws, the same for both initializers.+ public let props: AvatarProps+ @Environment(\.astryx) private var astryx++ /// An avatar from its labeled props.+ /// - Parameters:+ /// - name: The person's or entity's name, for initials and the accessible name (core `name`).+ /// - src: The image URL (core `src`).+ /// - fallbackSrc: The image URL to try when `src` fails (core `fallbackSrc`).+ /// - alt: The accessible name, when it differs from `name` (core `alt`).+ /// - size: `xsm` 20, `sm` 24, `md` 36, `lg` 48, or `xl` 128 points; `nil` is `md` (core `size`).+ /// - shape: `circle`, `rounded`, or `square`; `nil` is `circle` (core `shape`).+ /// - tooltip: Words shown where there is a pointer: `nil` or `true` the name, a string those words, `false` none (core `tooltip`).+ /// - href: A URL the system opens when the avatar is tapped; the avatar becomes a link (core `href`).+ /// - onClick: Runs when the avatar is tapped; without `href` the avatar becomes a button (core `onClick`).+ public init(+ _ name: String? = nil,+ src: String? = nil,+ fallbackSrc: String? = nil,+ alt: String? = nil,+ size: AvatarSize? = nil,+ shape: AvatarShape? = nil,+ tooltip: AvatarTooltip? = nil,+ href: String? = nil,+ onClick: (() -> Void)? = nil+ ) {+ self.init(+ AvatarProps(+ src: src, fallbackSrc: fallbackSrc, name: name, alt: alt, size: size, shape: shape, tooltip: tooltip, href: href,+ onClick: onClick+ ))+ }++ /// An avatar from its generated contract, for generated and wire-driven callers.+ public init(_ props: AvatarProps) {+ self.props = props+ }++ public var body: some View {+ if props.base.isHidden != true {+ control+ // The Astryx tooltip (library/tooltip.spec.md), as core's Avatar uses+ // core's tooltip: a static avatar is a tab stop and opens on a tap;+ // a link or button keeps its focus and its tap.+ // Touch is core's `auto`: a static avatar opens on a tap; a control's+ // tap belongs to its action.+ .astryxTooltip(tooltipText, hint: tooltipHint, focus: Avatar.tooltipFocus(tap))+ .modifier(AvatarIdentifier(id: props.base.id))+ .onAppear(perform: checkInDevelopment)+ }+ }++ /// Development checks core makes too: an `href` an app cannot open stops+ /// the build with its value, and an unnamed link or button is flagged.+ private func checkInDevelopment() {+ #if DEBUG+ if Avatar.isUnusableHref(props.href) {+ assertionFailure(+ "Avatar href \"\(props.href ?? "")\" is not an absolute URL an app can open; it draws without a link.")+ }+ if Avatar.needsNameWarning(tap: tap, isNamed: accessibilityLabel != nil) {+ Logger(subsystem: "Astryx", category: "Avatar").warning(+ "An Avatar with href or onClick has no alt or name, so VoiceOver reads it without a name.")+ }+ #endif+ }++ /// The tooltip's words: the name for `nil` or `true`, the given words, or+ /// none for `false` or blank words, as core resolves it.+ var tooltipText: String? {+ switch props.tooltip ?? .on {+ case .on: Avatar.meaningful(props.name).map(Avatar.trimmed)+ case .off: nil+ case .text(let words): Avatar.meaningful(words).map(Avatar.trimmed)+ }+ }++ /// The VoiceOver hint: given tooltip words, as core puts them in the+ /// description; the default name is the avatar's own name, not repeated.+ var tooltipHint: String? {+ guard case .text = props.tooltip else { return nil }+ return tooltipText+ }++ /// A non-empty `href` that is not an absolute URL, such as a web path.+ nonisolated static func isUnusableHref(_ href: String?) -> Bool {+ guard let href, !href.isEmpty else { return false }+ guard let url = URL(string: href) else { return true }+ return url.scheme == nil+ }++ /// The picture as a link with `href`, a button with only `onClick`, or a+ /// static image (Swift component API, A4). All three draw the same.+ @ViewBuilder private var control: some View {+ if let url = linkURL {+ SwiftUI.Link(destination: url) { picture }+ .buttonStyle(.plain)+ .modifier(AvatarRunsBeforeOpening(onClick: props.onClick))+ .modifier(AvatarTarget(side: side))+ .modifier(AvatarName(label: accessibilityLabel, tap: .link))+ } else if let onClick = props.onClick {+ SwiftUI.Button(action: onClick) { picture }+ .buttonStyle(.plain)+ .modifier(AvatarTarget(side: side))+ .modifier(AvatarName(label: accessibilityLabel, tap: .button))+ } else {+ picture+ // A static avatar whose tap opens its tooltip answers taps across+ // 44 points too.+ .modifier(AvatarTarget(side: Avatar.tapTargetSide(side, takesTaps: tooltipText != nil)))+ .modifier(AvatarName(label: accessibilityLabel, tap: .none))+ }+ }++ /// How the avatar takes a tap: a link with a usable `href`, else a button+ /// with `onClick`, else none.+ enum Tap: Equatable { case link, button, none }++ /// How far a tappable avatar's tap area reaches past its side: to 44+ /// points (Swift accessibility, X7).+ nonisolated static func tapOutset(side: CGFloat) -> CGFloat { max(0, (44 - side) / 2) }++ /// The side a static avatar's tap area grows from: its own when a tap+ /// opens its tooltip, and 44, which adds nothing, when it takes no taps.+ nonisolated static func tapTargetSide(_ side: CGFloat, takesTaps: Bool) -> CGFloat { takesTaps ? side : 44 }++ /// How keyboard focus reaches the tooltip: a static avatar is made a tab+ /// stop, as core gives it one; a link or button takes focus already.+ nonisolated static func tooltipFocus(_ tap: Tap) -> TooltipFocus { tap == .none ? .tabStop : .control }+++ var tap: Tap {+ if linkURL != nil { return .link }+ if props.onClick != nil { return .button }+ return .none+ }++ /// The traits the avatar adds: a named static avatar is an image; a link or+ /// button keeps its own trait and adds none (Swift accessibility, X1).+ nonisolated static func addedTraits(tap: Tap, isNamed: Bool) -> AccessibilityTraits {+ guard isNamed else { return [] }+ switch tap {+ case .none: return .isImage+ case .link: return .isLink+ case .button: return []+ }+ }++ /// Traits a named avatar drops: a link avatar is a link, not the button+ /// SwiftUI reports for `Link`.+ nonisolated static func removedTraits(tap: Tap, isNamed: Bool) -> AccessibilityTraits {+ isNamed && tap == .link ? .isButton : []+ }++ /// A link or button avatar needs a name, as core warns in development.+ nonisolated static func needsNameWarning(tap: Tap, isNamed: Bool) -> Bool {+ tap != .none && !isNamed+ }++ /// The photo; the fallback photo only after it fails or when there is+ /// none, as core does; initials or the symbol while either loads and+ /// after both fail.+ private var picture: some View {+ AvatarImage(url: url(props.src)) {+ plate+ } failure: {+ AvatarImage(url: url(props.fallbackSrc)) { plate } failure: { plate }+ }+ .frame(width: side, height: side)+ .clipShape(AvatarShapeOutline(shape: resolvedShape, radius: cornerRadius))+ }++ /// The fallback: initials on the neutral plate, else a person symbol.+ private var plate: some View {+ ZStack {+ astryx.tokens.color.neutral+ if let initials {+ // Drawn, not laid out as a Text view, so the initials are never an+ // accessibility element of their own; the name names the avatar.+ let font = initialsFont+ let color = astryx.tokens.color.textSecondary+ Canvas { context, size in+ let text = context.resolve(SwiftUI.Text(initials).font(font).foregroundColor(color))+ context.draw(text, at: CGPoint(x: size.width / 2, y: size.height / 2), anchor: .center)+ }+ .accessibilityHidden(true)+ } else {+ Image(systemName: "person.fill")+ .resizable()+ .scaledToFit()+ .frame(width: side * 0.6, height: side * 0.6)+ .foregroundStyle(astryx.tokens.color.textSecondary)+ .accessibilityHidden(true)+ }+ }+ }++ /// The side of the avatar in points.+ /// The side of the avatar in points: core's size grown with Dynamic Type,+ /// as the name beside it grows, up to 1.6 times so it never swallows a row.+ var side: CGFloat { Avatar.side(for: props.size ?? .md, textScale: astryx.textScale) }++ /// The most an avatar grows with Dynamic Type.+ nonisolated static var maximumTextScale: CGFloat { 1.6 }++ nonisolated static func side(for size: AvatarSize, textScale: CGFloat) -> CGFloat {+ (points(for: size) * min(max(textScale, 1), maximumTextScale)).rounded()+ }++ var resolvedShape: AvatarShape { props.shape ?? .circle }++ /// The corner radius for `rounded`, from the theme's element radius.+ private var cornerRadius: CGFloat { astryx.tokens.radius.element }++ /// Initials drawn at 40% of the side in the theme's body family, medium weight.+ private var initialsFont: Font {+ astryxFont(+ families: astryx.tokens.font.family.body,+ size: side * 0.4,+ weight: astryx.fontWeight(astryx.tokens.font.weight.medium),+ isBoldText: astryx.isBoldText+ )+ }++ /// The initials the plate shows, or `nil` for the person symbol.+ var initials: String? {+ guard let name = Avatar.meaningful(props.name) else { return nil }+ let initials = Avatar.initials(from: name)+ return initials.isEmpty ? nil : initials+ }++ /// The name VoiceOver reads: `alt`, else `name`; `nil` when neither+ /// carries anything, and then a static avatar is decorative.+ var accessibilityLabel: String? {+ Avatar.meaningful(props.alt) ?? Avatar.meaningful(props.name)+ }++ /// The URL the avatar opens, or `nil` when it has no usable `href`.+ var linkURL: URL? {+ // Only an absolute URL the system can open; a malformed or relative+ // `href` leaves the avatar static or a button.+ guard let url = url(props.href), url.scheme != nil else { return nil }+ return url+ }++ private func url(_ string: String?) -> URL? {+ guard let string, !string.isEmpty else { return nil }+ return URL(string: string)+ }++ /// Core's named sizes in points.+ nonisolated static func points(for size: AvatarSize) -> CGFloat {+ switch size {+ case .xsm: 20+ case .sm: 24+ case .md: 36+ case .lg: 48+ case .xl: 128+ }+ }++ /// The string when it carries something, `nil` when it is absent or blank.+ /// Words without their leading and trailing space, as core trims the+ /// tooltip it shows.+ nonisolated static func trimmed(_ value: String) -> String {+ value.trimmingCharacters(in: .whitespacesAndNewlines)+ }++ nonisolated static func meaningful(_ value: String?) -> String? {+ guard let value, !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }+ return value+ }++ /// Core's initials: the first letter, digit, or emoji of the first and last+ /// words that have one, uppercased. Leading punctuation in a word is skipped.+ nonisolated static func initials(from name: String) -> String {+ let letters = name.split(whereSeparator: { $0.isWhitespace }).compactMap { word in+ word.first(where: canStandForAWord)+ }+ guard let first = letters.first else { return "" }+ guard letters.count > 1, let last = letters.last else { return String(first).uppercased() }+ return (String(first) + String(last)).uppercased()+ }++ /// A letter, a digit, or an emoji, as core's `\p{L}`, `\p{N}`,+ /// `\p{Extended_Pictographic}`, and `\p{Regional_Indicator}`.+ nonisolated static func canStandForAWord(_ character: Character) -> Bool {+ if character.isLetter || character.isNumber { return true }+ guard let scalar = character.unicodeScalars.first else { return false }+ // `isEmoji` also covers `#`, `*`, and the digits, which are ASCII.+ return scalar.value > 0x7F && scalar.properties.isEmoji+ }+}++/// Draws the image at a URL: `loading` while it loads, `failure` when it+/// fails or there is no URL.+private struct AvatarImage<Loading: View, Failure: View>: View {+ let url: URL?+ @ViewBuilder let loading: () -> Loading+ @ViewBuilder let failure: () -> Failure++ var body: some View {+ if let url {+ AsyncImage(url: url) { phase in+ if let image = phase.image {+ image.resizable().scaledToFill()+ } else if phase.error != nil {+ failure()+ } else {+ loading()+ }+ }+ } else {+ failure()+ }+ }+}++/// Runs `onClick` as a link opens, then hands the URL to whatever opens URLs+/// above the avatar, so an app's own handler still applies. Without+/// `onClick` it changes nothing.+private struct AvatarRunsBeforeOpening: ViewModifier {+ let onClick: (() -> Void)?+ @Environment(\.openURL) private var inheritedOpenURL++ func body(content: Content) -> some View {+ if let onClick {+ content.environment(\.openURL, OpenURLAction { url in+ onClick()+ inheritedOpenURL(url)+ return .handled+ })+ } else {+ content+ }+ }+}++/// The outline each shape clips to: a circle, the element radius, or square.+private struct AvatarShapeOutline: Shape {+ let shape: AvatarShape+ let radius: CGFloat++ func path(in rect: CGRect) -> Path {+ switch shape {+ case .circle: Circle().path(in: rect)+ case .rounded: RoundedRectangle(cornerRadius: radius, style: .continuous).path(in: rect)+ case .square: Rectangle().path(in: rect)+ }+ }+}++/// One element named by the avatar's label. A static avatar without a label+/// is hidden; an interactive one keeps its link or button trait.+private struct AvatarName: ViewModifier {+ let label: String?+ let tap: Avatar.Tap++ func body(content: Content) -> some View {+ let isNamed = label != nil+ let added = Avatar.addedTraits(tap: tap, isNamed: isNamed)+ let removed = Avatar.removedTraits(tap: tap, isNamed: isNamed)+ if let label {+ if tap == .none {+ // One image element named by the name.+ content.accessibilityElement(children: .ignore).accessibilityLabel(label)+ .accessibilityAddTraits(added)+ } else {+ // The link or button itself carries the name, so VoiceOver reads+ // "Grace Hopper, button", not the initials inside it.+ content.accessibilityLabel(label).accessibilityAddTraits(added).accessibilityRemoveTraits(removed)+ }+ } else if tap != .none {+ content+ } else {+ content.accessibilityHidden(true)+ }+ }+}++/// A tappable avatar answers taps across at least 44 by 44 points without+/// changing its drawn size or its layout (Swift accessibility, X7).+private struct AvatarTarget: ViewModifier {+ let side: CGFloat++ func body(content: Content) -> some View {+ content.contentShape(.interaction, Rectangle().inset(by: -Avatar.tapOutset(side: side)))+ }+}++/// The base `id` becomes the accessibility identifier (AST-082 FR7).+private struct AvatarIdentifier: ViewModifier {+ let id: String?++ func body(content: Content) -> some View {+ if let id {+ content.accessibilityIdentifier(id)+ } else {+ content+ }+ }+}diff --git a/packages/native/apple/Sources/Astryx/Wire/AstryxNodeView.swift b/packages/native/apple/Sources/Astryx/Wire/AstryxNodeView.swiftindex 84336b5966..8603a38707 100644--- a/packages/native/apple/Sources/Astryx/Wire/AstryxNodeView.swift+++ b/packages/native/apple/Sources/Astryx/Wire/AstryxNodeView.swift@@ -19,6 +19,7 @@ public struct AstryxNodeView: View {case .heading(let heading): Heading(heading.viewProps(send: send))case .card(let card): Card(card.viewProps(send: send), children: card.props.children ?? [], send: send)case .icon(let icon): Icon(icon.viewProps(send: send))+ case .avatar(let avatar): Avatar(avatar.viewProps(send: send))default: AstryxUnsupportedNode(component: Self.componentName(node))}}@@ -26,6 +27,7 @@ public struct AstryxNodeView: View {/// The component a node names on the wire.static func componentName(_ node: AstryxNode) -> String {switch node {+ case .avatar: "Avatar"case .badge: "Badge"case .button: "Button"case .card: "Card"diff --git a/packages/native/apple/Sources/AstryxNative/Generated/AstryxNode.swift b/packages/native/apple/Sources/AstryxNative/Generated/AstryxNode.swiftindex f5af9061a7..d34a5e73b4 100644--- a/packages/native/apple/Sources/AstryxNative/Generated/AstryxNode.swift+++ b/packages/native/apple/Sources/AstryxNative/Generated/AstryxNode.swift@@ -7,6 +7,7 @@ import Foundation/// or a known one with a value its enums lack or a required prop missing. An older/// app then keeps drawing the rest of a newer core's tree.public enum AstryxNode: Decodable, Equatable, Sendable {+ case avatar(AvatarNode)case badge(BadgeNode)case button(ButtonNode)case card(CardNode)@@ -24,6 +25,7 @@ public enum AstryxNode: Decodable, Equatable, Sendable {public var key: String {switch self {+ case .avatar(let node): return node.keycase .badge(let node): return node.keycase .button(let node): return node.keycase .card(let node): return node.key@@ -49,6 +51,7 @@ public enum AstryxNode: Decodable, Equatable, Sendable {let key = try container.decode(String.self, forKey: .key)do {switch component {+ case "Avatar": self = .avatar(try AvatarNode(from: decoder))case "Badge": self = .badge(try BadgeNode(from: decoder))case "Button": self = .button(try ButtonNode(from: decoder))case "Card": self = .card(try CardNode(from: decoder))diff --git a/packages/native/apple/Sources/AstryxNative/Generated/Avatar.swift b/packages/native/apple/Sources/AstryxNative/Generated/Avatar.swiftnew file mode 100644index 0000000000..1743097dcd--- /dev/null+++ b/packages/native/apple/Sources/AstryxNative/Generated/Avatar.swift@@ -0,0 +1,163 @@+// Generated by @astryxdesign/native. Do not edit.+public enum AvatarSize: String, CaseIterable, Codable, Sendable {+ case xsm = "xsm"+ case sm = "sm"+ case md = "md"+ case lg = "lg"+ case xl = "xl"+}+public enum AvatarShape: String, CaseIterable, Codable, Sendable {+ case circle = "circle"+ case rounded = "rounded"+ case square = "square"+}+/// Words or a switch: `.on` is the component's own words, `.off` none,+/// `.text` the given words. On the wire it is the web value, a string or a Bool.+public enum AvatarTooltip: Equatable, Codable, Sendable, ExpressibleByStringLiteral, ExpressibleByBooleanLiteral {+ case on+ case off+ case text(String)+ public init(stringLiteral value: String) { self = .text(value) }+ public init(booleanLiteral value: Bool) { self = value ? .on : .off }+ public init(from decoder: any Decoder) throws {+ let container = try decoder.singleValueContainer()+ if let value = try? container.decode(Bool.self) { self = value ? .on : .off }+ else { self = .text(try container.decode(String.self)) }+ }+ public func encode(to encoder: any Encoder) throws {+ var container = encoder.singleValueContainer()+ switch self {+ case .on: try container.encode(true)+ case .off: try container.encode(false)+ case .text(let value): try container.encode(value)+ }+ }+}+#if os(iOS)+public struct AvatarProps {+ /// Base props attach to this part on every platform.+ public static let baseTarget: AstryxBaseTarget = .root+ public var base: AstryxBaseProps+ public var src: String?+ public var fallbackSrc: String?+ public var name: String?+ public var alt: String?+ public var size: AvatarSize?+ public var shape: AvatarShape?+ public var tooltip: AvatarTooltip?+ public var href: String?+ public var onClick: (() -> Void)?+ public init(src: String? = nil, fallbackSrc: String? = nil, name: String? = nil, alt: String? = nil, size: AvatarSize? = nil, shape: AvatarShape? = nil, tooltip: AvatarTooltip? = nil, href: String? = nil, onClick: (() -> Void)? = nil, base: AstryxBaseProps = AstryxBaseProps()) {+ self.src = src+ self.fallbackSrc = fallbackSrc+ self.name = name+ self.alt = alt+ self.size = size+ self.shape = shape+ self.tooltip = tooltip+ self.href = href+ self.onClick = onClick+ self.base = base+ }+}+public struct AvatarNode: Decodable, Equatable, Sendable {+ public struct Props: Decodable, Equatable, Sendable {+ public var src: String?+ public var fallbackSrc: String?+ public var name: String?+ public var alt: String?+ public var size: AvatarSize?+ public var shape: AvatarShape?+ public var tooltip: AvatarTooltip?+ public var href: String?+ }+ public let key: String+ public let base: AstryxBaseProps?+ public let props: Props+ /// The callbacks the core listens to, by prop name.+ public let events: [String]?++ public func listens(_ event: String) -> Bool { events?.contains(event) ?? false }++ /// The contract a Avatar view takes; its callbacks send actions to the core.+ public func viewProps(send: @escaping @Sendable (AstryxAction) -> Void) -> AvatarProps {+ let key = self.key+ return AvatarProps(+ src: props.src,+ fallbackSrc: props.fallbackSrc,+ name: props.name,+ alt: props.alt,+ size: props.size,+ shape: props.shape,+ tooltip: props.tooltip,+ href: props.href,+ onClick: listens("onClick") ? { send(AstryxAction(key: key, component: "Avatar", event: "onClick", args: [])) } : nil,+ base: base ?? AstryxBaseProps()+ )+ }+}+#endif+#if os(macOS)+public struct AvatarProps {+ /// Base props attach to this part on every platform.+ public static let baseTarget: AstryxBaseTarget = .root+ public var base: AstryxBaseProps+ public var src: String?+ public var fallbackSrc: String?+ public var name: String?+ public var alt: String?+ public var size: AvatarSize?+ public var shape: AvatarShape?+ public var tooltip: AvatarTooltip?+ public var href: String?+ public var onClick: (() -> Void)?+ public init(src: String? = nil, fallbackSrc: String? = nil, name: String? = nil, alt: String? = nil, size: AvatarSize? = nil, shape: AvatarShape? = nil, tooltip: AvatarTooltip? = nil, href: String? = nil, onClick: (() -> Void)? = nil, base: AstryxBaseProps = AstryxBaseProps()) {+ self.src = src+ self.fallbackSrc = fallbackSrc+ self.name = name+ self.alt = alt+ self.size = size+ self.shape = shape+ self.tooltip = tooltip+ self.href = href+ self.onClick = onClick+ self.base = base+ }+}+public struct AvatarNode: Decodable, Equatable, Sendable {+ public struct Props: Decodable, Equatable, Sendable {+ public var src: String?+ public var fallbackSrc: String?+ public var name: String?+ public var alt: String?+ public var size: AvatarSize?+ public var shape: AvatarShape?+ public var tooltip: AvatarTooltip?+ public var href: String?+ }+ public let key: String+ public let base: AstryxBaseProps?+ public let props: Props+ /// The callbacks the core listens to, by prop name.+ public let events: [String]?++ public func listens(_ event: String) -> Bool { events?.contains(event) ?? false }++ /// The contract a Avatar view takes; its callbacks send actions to the core.+ public func viewProps(send: @escaping @Sendable (AstryxAction) -> Void) -> AvatarProps {+ let key = self.key+ return AvatarProps(+ src: props.src,+ fallbackSrc: props.fallbackSrc,+ name: props.name,+ alt: props.alt,+ size: props.size,+ shape: props.shape,+ tooltip: props.tooltip,+ href: props.href,+ onClick: listens("onClick") ? { send(AstryxAction(key: key, component: "Avatar", event: "onClick", args: [])) } : nil,+ base: base ?? AstryxBaseProps()+ )+ }+}+#endifdiff --git a/packages/native/apple/Tests/AstryxTests/AvatarTests.swift b/packages/native/apple/Tests/AstryxTests/AvatarTests.swiftnew file mode 100644index 0000000000..6eddb1be76--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/AvatarTests.swift@@ -0,0 +1,263 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import AstryxNative+import SwiftUI+import Testing+@testable import Astryx++// Swift Avatar spec (component:swift/Avatar): core's picture, initials, and+// person-symbol fallback, at core's sizes and shapes, named by alt or name.++@Test func initialsComeFromLettersDigitsAndEmojiNotPunctuation() {+ let cases: [(String, String)] = [+ ("Ada Lovelace", "AL"),+ ("Northwind Workbench (automation)", "NA"),+ ("Ada \"The Countess\" Lovelace", "AL"),+ ("“Ada” Lovelace", "AL"),+ ("Ada - Lovelace", "AL"),+ ("Ada Lovelace —", "AL"),+ ("Mary-Jane Watson", "MW"),+ ("(Ada)", "A"),+ ("Alice", "A"),+ ("R2 D2", "RD"),+ ("3M", "3"),+ ("émile zola", "ÉZ"),+ ("😀 Ada", "😀A"),+ ("🇬🇧 Ada", "🇬🇧A"),+ ("👨👩👧👦 Ada", "👨👩👧👦A"),+ ("Ada (😀)", "A😀"),+ ("- ()", ""),+ ("# *", ""),+ ]+ for (name, expected) in cases {+ #expect(Avatar.initials(from: name) == expected, "\(name)")+ }+}++@MainActor+@Test func aNameWithNoInitialsShowsThePersonSymbolAndStillNamesTheAvatar() {+ let avatar = Avatar("- ()")+ #expect(avatar.initials == nil)+ #expect(avatar.accessibilityLabel == "- ()")+ #expect(Avatar(" ").initials == nil)+ #expect(Avatar(" ").accessibilityLabel == nil)+}++@MainActor+@Test func altNamesTheAvatarBeforeName() {+ #expect(Avatar("Ada Lovelace", alt: "Ada, profile photo").accessibilityLabel == "Ada, profile photo")+ #expect(Avatar("Ada Lovelace").accessibilityLabel == "Ada Lovelace")+ #expect(Avatar("Ada Lovelace", alt: " ").accessibilityLabel == "Ada Lovelace")+ #expect(Avatar(src: "https://example.com/a.png").accessibilityLabel == nil)+}++@MainActor+@Test func avatarInitializersBuildTheSameProps() {+ let labeled = Avatar("Ada", src: "a", fallbackSrc: "b", alt: "c", size: .lg, shape: .square, href: "https://example.com").props+ let fromProps = Avatar(AvatarProps(src: "a", fallbackSrc: "b", name: "Ada", alt: "c", size: .lg, shape: .square, href: "https://example.com")).props+ #expect(labeled.name == fromProps.name)+ #expect(labeled.src == fromProps.src)+ #expect(labeled.fallbackSrc == fromProps.fallbackSrc)+ #expect(labeled.alt == fromProps.alt)+ #expect(labeled.size == fromProps.size)+ #expect(labeled.shape == fromProps.shape)+ #expect(labeled.href == fromProps.href)+ #expect(labeled.base == fromProps.base)+ let defaults = Avatar().props+ #expect(defaults.size == nil && defaults.shape == nil && defaults.onClick == nil)+}++@MainActor+@Test func namedSizesDrawCoresPointSizes() {+ #expect(Avatar.points(for: .xsm) == 20)+ #expect(Avatar.points(for: .sm) == 24)+ #expect(Avatar.points(for: .md) == 36)+ #expect(Avatar.points(for: .lg) == 48)+ #expect(Avatar.points(for: .xl) == 128)+ #expect(Avatar.side(for: .md, textScale: 1) == 36)+ let drawn = Pixels(Avatar("Ada", size: .lg).fixedSize())+ #expect(drawn.width == 48 && drawn.height == 48)+}++@MainActor+@Test func theFallbackPlateUsesTheThemesNeutralColor() {+ let neutral = plate(Theme.default.light.color.neutral)+ let square = Pixels(Avatar("Ada Lovelace", size: .lg, shape: .square).fixedSize())+ #expect(close(square.at(2, 2), neutral))+ // A circle leaves its corners clear.+ let circle = Pixels(Avatar("Ada Lovelace", size: .lg).fixedSize())+ #expect(circle.at(1, 1)[3] < 32)+ #expect(close(circle.at(24, 4), neutral))+}++@MainActor+@Test func anAvatarRendersFromTwoThemesWithNoColorOfItsOwn() {+ // On white, so the translucent plates of different themes tell apart.+ let view = Avatar("Ada Lovelace", size: .lg, shape: .square).background(Color.white).fixedSize()+ let byDefault = Pixels(view).at(2, 2)+ let butter = Pixels(view, theme: .butter).at(2, 2)+ let defaultPlate = onWhite(Theme.default.light.color.neutral)+ let butterPlate = onWhite(Theme.butter.light.color.neutral)+ #expect(close(byDefault, defaultPlate, within: 3))+ #expect(close(butter, butterPlate, within: 3))+ #expect(!close(butter, defaultPlate, within: 3))+ let dark = Pixels(Avatar("Ada Lovelace", size: .lg, shape: .square).fixedSize(), scheme: .dark)+ #expect(close(dark.at(2, 2), plate(Theme.default.dark.color.neutral)))+}++@MainActor+@Test func aLinkOrButtonAvatarDrawsTheSameAsAStaticOne() {+ let still = Pixels(Avatar("Ada Lovelace", size: .sm).fixedSize())+ let link = Pixels(Avatar("Ada Lovelace", size: .sm, href: "https://example.com/ada").fixedSize())+ let button = Pixels(Avatar("Ada Lovelace", size: .sm) {}.fixedSize())+ #expect(link.width == still.width && link.height == still.height)+ #expect(button.width == still.width && button.height == still.height)+ #expect(close(link.at(12, 2), still.at(12, 2)))+}++@MainActor+@Test func hrefMakesALinkAndAnUnusableHrefDoesNot() {+ #expect(Avatar("Ada", href: "https://example.com/ada").linkURL == URL(string: "https://example.com/ada"))+ #expect(Avatar("Ada", href: "mailto:[email protected]").linkURL != nil)+ #expect(Avatar("Ada", href: "").linkURL == nil)+ #expect(Avatar("Ada", href: "not a url").linkURL == nil)+ #expect(Avatar("Ada", href: "/people/ada").linkURL == nil)+ #expect(Avatar("Ada").linkURL == nil)+}++@MainActor+@Test func avatarsReadTheirTapAndTraits() {+ #expect(Avatar("Ada").tap == .none)+ #expect(Avatar("Ada", onClick: {}).tap == .button)+ #expect(Avatar("Ada", href: "https://example.com", onClick: {}).tap == .link)+ #expect(Avatar("Ada", href: "not a url", onClick: {}).tap == .button)+ #expect(Avatar.addedTraits(tap: .none, isNamed: true) == .isImage)+ // A link avatar is a link, not the button SwiftUI reports for `Link`.+ #expect(Avatar.addedTraits(tap: .link, isNamed: true) == .isLink)+ #expect(Avatar.removedTraits(tap: .link, isNamed: true) == .isButton)+ #expect(Avatar.removedTraits(tap: .button, isNamed: true) == [])+ #expect(Avatar.addedTraits(tap: .button, isNamed: true) == [])+}++@Test func aLinkOrButtonAvatarWithoutANameIsWarnedAbout() {+ #expect(Avatar.needsNameWarning(tap: .button, isNamed: false))+ #expect(Avatar.needsNameWarning(tap: .link, isNamed: false))+ #expect(!Avatar.needsNameWarning(tap: .button, isNamed: true))+ #expect(!Avatar.needsNameWarning(tap: .none, isNamed: false))+}++@MainActor+@Test func avatarsGrowWithTextSizeUpToTheirCap() {+ let large = Pixels(Avatar("Ada Lovelace", size: .md).fixedSize())+ let larger = Pixels(Avatar("Ada Lovelace", size: .md).fixedSize(), typeSize: .xxLarge)+ let largest = Pixels(Avatar("Ada Lovelace", size: .md).fixedSize(), typeSize: .accessibility5)+ #expect(large.width == 36)+ #expect(larger.width == Int(Avatar.side(for: .md, textScale: 1.23)))+ #expect(largest.width == Int((36 * Avatar.maximumTextScale).rounded()))+ #expect(Avatar.side(for: .xl, textScale: 0.82) == 128)+}++@MainActor+@Test func theTooltipIsTheNameUnlessGivenWordsOrTurnedOff() {+ #expect(Avatar("Ada Lovelace").tooltipText == "Ada Lovelace")+ #expect(Avatar("Ada Lovelace", tooltip: true).tooltipText == "Ada Lovelace")+ #expect(Avatar("Ada Lovelace", tooltip: "Ada Lovelace, Mathematician").tooltipText == "Ada Lovelace, Mathematician")+ #expect(Avatar("Ada Lovelace", tooltip: false).tooltipText == nil)+ #expect(Avatar("Ada Lovelace", tooltip: " ").tooltipText == nil)+ #expect(Avatar(src: "https://example.com/a.png").tooltipText == nil)+}++@Test func tooltipsTravelAsTheWebValue() throws {+ let encoded = try JSONEncoder().encode([AvatarTooltip.on, .off, "Ada"])+ #expect(String(decoding: encoded, as: UTF8.self) == #"[true,false,"Ada"]"#)+ #expect(try JSONDecoder().decode([AvatarTooltip].self, from: encoded) == [.on, .off, .text("Ada")])+}++@Test func aWebPathIsAnHrefTheAppCannotOpen() {+ #expect(Avatar.isUnusableHref("/people/ada"))+ #expect(Avatar.isUnusableHref("not a url"))+ #expect(!Avatar.isUnusableHref("https://example.com/ada"))+ #expect(!Avatar.isUnusableHref(""))+ #expect(!Avatar.isUnusableHref(nil))+}++@MainActor+@Test func aHiddenAvatarDrawsNothing() {+ let hidden = Pixels(+ HStack(spacing: 0) {+ Color.clear.frame(width: 1, height: 1)+ Avatar(AvatarProps(name: "Ada", base: AstryxBaseProps(isHidden: true)))+ }.fixedSize()+ )+ #expect(hidden.width == 1)+}++/// A theme color as the renderer stores it: premultiplied by its alpha, since+/// the neutral plate is translucent.+private func plate(_ color: Color) -> [Int] {+ let c = rgba(color)+ return [c[0] * c[3] / 255, c[1] * c[3] / 255, c[2] * c[3] / 255, c[3]]+}++/// A theme color drawn over white.+private func onWhite(_ color: Color) -> [Int] {+ let c = rgba(color)+ return (0..<3).map { (c[$0] * c[3] + 255 * (255 - c[3])) / 255 } + [255]+}++// FR8: Avatar's words, focus, touch, and hint for the shared tooltip+// (library/tooltip.spec.md), whose inputs `TooltipPresenterTests.swift` covers.++@Test func aStaticAvatarIsATabStopAndOpensOnATapAndAControlKeepsBoth() {+ // Core's `auto` touch resolves from focus: a static avatar opens on a tap,+ // a control keeps its tap.+ #expect(Avatar.tooltipFocus(.none) == .tabStop)+ #expect(TooltipPresenter.resolvedTouch(.auto, focus: Avatar.tooltipFocus(.none)) == .tap)+ #expect(Avatar.tooltipFocus(.button) == .control)+ #expect(TooltipPresenter.resolvedTouch(.auto, focus: Avatar.tooltipFocus(.button)) == .none)+ #expect(Avatar.tooltipFocus(.link) == .control)+ #expect(TooltipPresenter.resolvedTouch(.auto, focus: Avatar.tooltipFocus(.link)) == .none)+}++@MainActor+@Test func voiceOverHearsGivenWordsAsTheHintAndTheNameOnce() {+ #expect(Avatar("Ada Lovelace").tooltipHint == nil)+ #expect(Avatar("Ada Lovelace", tooltip: true).tooltipHint == nil)+ #expect(Avatar("Ada Lovelace", tooltip: "Ada Lovelace, Mathematician").tooltipHint == "Ada Lovelace, Mathematician")+ #expect(Avatar("Ada Lovelace", tooltip: false).tooltipHint == nil)+ #expect(Avatar("Ada Lovelace").accessibilityLabel == "Ada Lovelace")+}++@Test func aStaticAvatarWhoseTapOpensItsTooltipAnswersAcross44Points() {+ // xsm, sm, and md grow their tap area to 44 points; a static avatar with+ // no tooltip takes no taps and adds nothing.+ for side in [CGFloat(20), 24, 36] {+ let target = Avatar.tapTargetSide(side, takesTaps: true)+ #expect(target + 2 * Avatar.tapOutset(side: target) == 44)+ }+ #expect(Avatar.tapOutset(side: Avatar.tapTargetSide(20, takesTaps: false)) == 0)+ #expect(Avatar.tapOutset(side: 128) == 0)+}+++// AST-082 FR19: an Avatar node from a logic core draws as Avatar.+@MainActor+@Test func anAvatarNodeDrawsAsAnAvatar() {+ let json = #"{"component":"Avatar","key":"a","props":{"name":"Ada Lovelace","size":"lg"}}"#+ guard let node = try? JSONDecoder().decode(AstryxNode.self, from: Data(json.utf8)) else {+ Issue.record("the avatar did not decode")+ return+ }+ #expect(AstryxNodeView.componentName(node) == "Avatar")+ let wired = Pixels(AstryxNodeView(node) { _ in }.fixedSize())+ let direct = Pixels(Avatar("Ada Lovelace", size: .lg).fixedSize())+ #expect(wired.width == direct.width && wired.height == direct.height)+}++@MainActor+@Test func theTooltipShowsTrimmedWordsAsCoreDoes() {+ #expect(Avatar(" Ada Lovelace ").tooltipText == "Ada Lovelace")+ #expect(Avatar("Ada Lovelace", tooltip: .text(" Mathematician \n")).tooltipText == "Mathematician")+ #expect(Avatar("Ada Lovelace", tooltip: .text(" Mathematician ")).tooltipHint == "Mathematician")+}+diff --git a/packages/native/specs/swift/library/component-api.md b/packages/native/specs/swift/library/component-api.mdindex 8316ee38f8..e66cb79d81 100644--- a/packages/native/specs/swift/library/component-api.md+++ b/packages/native/specs/swift/library/component-api.md@@ -148,10 +148,10 @@ same generated contract.(SwiftUI views with core's names, `Button`, `Text`, and so on, re-exportingSwiftUI and the contracts) and the `AstryxNative` product (generated contracttypes, unprefixed: `ButtonProps`, `ButtonVariant`).-- Card, Heading, Icon, and Text take their generated `<Name>Props`; Button and+- Avatar, Card, Heading, Icon, and Text take their generated `<Name>Props`; Button andTextInput still take hand-written parameters until each moves onto itsgenerated props; Banner has no generated contract.-- `AstryxNodeView` draws Card, Heading, Icon, and Text wire nodes. Any other+- `AstryxNodeView` draws Avatar, Card, Heading, Icon, and Text wire nodes. Any othernode, HStack and VStack included, renders in its place as unsupported, andits siblings still render, until the logic host draws stacks (A9).- The generated iOS `SwitchProps` still declares `size`, and `HStackProps` anddiff --git a/packages/native/src/components/Avatar.ts b/packages/native/src/components/Avatar.tsnew file mode 100644index 0000000000..b28b1b5ac0--- /dev/null+++ b/packages/native/src/components/Avatar.ts@@ -0,0 +1,27 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file components/Avatar.ts+ * @input None+ * @output What @astryxdesign/native adds to the core Avatar contract+ * @position Native additions read by fromComponentDoc together with core's+ * Avatar documentation+ */++import type {NativeAdditions} from '../contract/fromComponentDoc.js';++export const avatar: NativeAdditions = {+ name: 'Avatar',+ baseTarget: 'root',+ callbacks: ['onClick'],+ sameMeaning: {onClick: 'a press, as in Compose'},+ // The named sizes every platform draws; the pixel sizes stay on the web.+ projections: {+ size: {xsm: 'xsm', sm: 'sm', md: 'md', lg: 'lg', xl: 'xl'},+ },+ webOnly: {+ target: 'HTML link target',+ rel: 'HTML link relationship',+ status: 'holds AvatarStatusDot, which has no native view yet',+ },+};diff --git a/packages/native/src/components/index.ts b/packages/native/src/components/index.tsindex 2d2a14635f..c59523985d 100644--- a/packages/native/src/components/index.ts+++ b/packages/native/src/components/index.ts@@ -9,6 +9,7 @@*/import type {NativeAdditions} from '../contract/fromComponentDoc.js';+import {avatar} from './Avatar.js';import {badge} from './Badge.js';import {button} from './Button.js';import {card} from './Card.js';@@ -24,6 +25,7 @@ import {textInput} from './TextInput.js';import {vStack} from './VStack.js';export const NATIVE_COMPONENTS: readonly NativeAdditions[] = [+ avatar,badge,button,card,diff --git a/packages/native/src/contract/contracts.test.ts b/packages/native/src/contract/contracts.test.tsindex 69b2969dd1..f0352f2db5 100644--- a/packages/native/src/contract/contracts.test.ts+++ b/packages/native/src/contract/contracts.test.ts@@ -136,6 +136,35 @@ describe('native contracts', () => {expect(types['core.d.ts']).toContain('icon: IconName;');});+ it('gives Avatar its named sizes, a press, and a link, and leaves pixel sizes on the web', async () => {+ const {contracts} = await buildContracts(loadCoreDoc);+ const avatar = contracts.find(contract => contract.name === 'Avatar');+ expect(avatar).toBeDefined();+ expect(avatar!.core.size.type).toEqual({+ kind: 'enum',+ values: ['xsm', 'sm', 'md', 'lg', 'xl'],+ });+ expect(Object.entries(avatar!.projections?.size ?? {})).toEqual(+ ['xsm', 'sm', 'md', 'lg', 'xl'].map(size => [size, size]),+ );+ expect(Object.keys(avatar!.core)).toEqual(+ expect.arrayContaining([+ 'src',+ 'fallbackSrc',+ 'name',+ 'alt',+ 'shape',+ 'href',+ 'onClick',+ ]),+ );+ // `string | boolean`: words, or on (the name) and off.+ expect(avatar!.core.tooltip?.type).toEqual({kind: 'textOrBoolean'});+ expect(avatar!.webOnly.map(prop => prop.name)).toEqual(+ expect.arrayContaining(['target', 'rel', 'status', 'as']),+ );+ });+it('reports naming and portability errors', () => {const bad: ComponentContract = {name: 'Bad',diff --git a/packages/native/src/contract/fromComponentDoc.ts b/packages/native/src/contract/fromComponentDoc.tsindex 42dae22cd9..5dd2e20097 100644--- a/packages/native/src/contract/fromComponentDoc.ts+++ b/packages/native/src/contract/fromComponentDoc.ts@@ -87,7 +87,7 @@ export interface NativeAdditions {* Props whose web type is wider than a portable kind, with the closed set of* values every platform supports, each mapped to the one web value it means* (AST-082 FR4), such as Button `width`: `content` is the web's `'auto'`- * and `fill` its `'100%'`. The first value is the default. The prop's other+ * and `fill` its `'100%'`. The web's default keeps its meaning. The prop's other* web values stay in the web contract.*/readonly projections?: Readonly<diff --git a/packages/native/src/contract/generateSwift.ts b/packages/native/src/contract/generateSwift.tsindex d6948a9bac..483d2ef522 100644--- a/packages/native/src/contract/generateSwift.ts+++ b/packages/native/src/contract/generateSwift.ts@@ -88,6 +88,36 @@ class SwiftWriter {return '[AstryxNode]';case 'icon':return 'IconName';+ case 'textOrBoolean': {+ const name = `${owner}${pascal(prop)}`;+ this.decls.push(+ [+ `/// Words or a switch: \`.on\` is the component's own words, \`.off\` none,`,+ `/// \`.text\` the given words. On the wire it is the web value, a string or a Bool.`,+ `public enum ${name}: Equatable, Codable, Sendable, ExpressibleByStringLiteral, ExpressibleByBooleanLiteral {`,+ ' case on',+ ' case off',+ ' case text(String)',+ ' public init(stringLiteral value: String) { self = .text(value) }',+ ' public init(booleanLiteral value: Bool) { self = value ? .on : .off }',+ ' public init(from decoder: any Decoder) throws {',+ ' let container = try decoder.singleValueContainer()',+ ' if let value = try? container.decode(Bool.self) { self = value ? .on : .off }',+ ' else { self = .text(try container.decode(String.self)) }',+ ' }',+ ' public func encode(to encoder: any Encoder) throws {',+ ' var container = encoder.singleValueContainer()',+ ' switch self {',+ ' case .on: try container.encode(true)',+ ' case .off: try container.encode(false)',+ ' case .text(let value): try container.encode(value)',+ ' }',+ ' }',+ '}',+ ].join('\n'),+ );+ return name;+ }case 'named':return type.name;}diff --git a/packages/native/src/contract/generateTypeScript.ts b/packages/native/src/contract/generateTypeScript.tsindex 4434111b8f..138d079e71 100644--- a/packages/native/src/contract/generateTypeScript.ts+++ b/packages/native/src/contract/generateTypeScript.ts@@ -40,6 +40,8 @@ function tsType(type: PropType, content = 'AstryxContentNode'): string {return `ReadonlyArray<${content}>`;case 'icon':return 'IconName';+ case 'textOrBoolean':+ return 'string | boolean';case 'named':return type.name;}diff --git a/packages/native/src/contract/parseDocType.test.ts b/packages/native/src/contract/parseDocType.test.tsindex a286a2bbf1..aeb340227c 100644--- a/packages/native/src/contract/parseDocType.test.ts+++ b/packages/native/src/contract/parseDocType.test.ts@@ -4,6 +4,18 @@ import {describe, expect, it} from 'vitest';import {parseDocType} from './parseDocType.js';describe('parseDocType', () => {+ it('reads words-or-a-switch, and no other union of different kinds', () => {+ expect(parseDocType('string | boolean')).toEqual({+ ok: true,+ type: {kind: 'textOrBoolean'},+ });+ expect(parseDocType('boolean | string')).toEqual({+ ok: true,+ type: {kind: 'textOrBoolean'},+ });+ expect(parseDocType('string | number').ok).toBe(false);+ });+it('reads portable forms', () => {expect(parseDocType('string')).toEqual({ok: true, type: {kind: 'string'}});expect(parseDocType("'sm' | 'md' | 'lg'")).toEqual({diff --git a/packages/native/src/contract/parseDocType.ts b/packages/native/src/contract/parseDocType.tsindex 5c0017c4de..4724ebccd1 100644--- a/packages/native/src/contract/parseDocType.ts+++ b/packages/native/src/contract/parseDocType.ts@@ -178,8 +178,8 @@ function parseFunction(text: string): ParsedType | null {* Parses a documented type string. Supported portable forms: `string`,* `number`, `boolean`, closed string or number unions, arrays, plain object* literals, callbacks with portable arguments (a trailing DOM event argument- * is the web's part), and named types. A union of different- * kinds has no Swift or Kotlin form.+ * is the web's part), named types, and `string | boolean` (words or a+ * switch). Any other union of different kinds has no Swift or Kotlin form.*/export function parseDocType(raw: string): ParsedType {const text = stripOuterParens(raw.replace(/\s+/g, ' ').trim());@@ -202,6 +202,13 @@ export function parseDocType(raw: string): ParsedType {if (members.every(m => /^-?\d+(?:\.\d+)?$/.test(m))) {return ok({kind: 'numberEnum', values: members.map(Number)});}+ if (+ members.length === 2 &&+ members.includes('string') &&+ members.includes('boolean')+ ) {+ return ok({kind: 'textOrBoolean'});+ }const webOnly = members.find(m => WEB_ONLY_TYPES[m] != null);if (webOnly) {return no(WEB_ONLY_TYPES[webOnly]);diff --git a/packages/native/src/contract/types.ts b/packages/native/src/contract/types.tsindex 598328832a..38bbc91a78 100644--- a/packages/native/src/contract/types.ts+++ b/packages/native/src/contract/types.ts@@ -25,6 +25,11 @@ export type PropType =| {kind: 'content'}/** A shared icon name: the typed icon slot (AST-082 FR4, FR17). */| {kind: 'icon'}+ /**+ * Words or a switch, such as a tooltip that is on (`true`, the component's+ * own words), off (`false`), or given words.+ */+ | {kind: 'textOrBoolean'}| {kind: 'named'; name: string};export interface PropSpec {