@astryxdesign/native 0.7.5-canary.268f109 → 0.7.5-canary.2af4d30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/apple/Package.swift +1 -1
  2. package/apple/README.md +1 -0
  3. package/apple/Sources/Astryx/Avatar/Avatar.spec.md +210 -0
  4. package/apple/Sources/Astryx/Avatar/Avatar.swift +418 -0
  5. package/apple/Sources/Astryx/Card/Card.swift +4 -1
  6. package/apple/Sources/Astryx/Icon/Icon.spec.md +12 -11
  7. package/apple/Sources/Astryx/Icon/Icon.swift +4 -3
  8. package/apple/Sources/Astryx/Theme/Generated/ButterTheme.swift +352 -314
  9. package/apple/Sources/Astryx/Theme/Generated/ChocolateTheme.swift +352 -314
  10. package/apple/Sources/Astryx/Theme/Generated/DefaultTheme.swift +352 -314
  11. package/apple/Sources/Astryx/Theme/Generated/GothicTheme.swift +352 -314
  12. package/apple/Sources/Astryx/Theme/Generated/MatchaTheme.swift +352 -314
  13. package/apple/Sources/Astryx/Theme/Generated/NeutralTheme.swift +352 -314
  14. package/apple/Sources/Astryx/Theme/Generated/StoneTheme.swift +352 -314
  15. package/apple/Sources/Astryx/Theme/Generated/Tokens.swift +95 -0
  16. package/apple/Sources/Astryx/Theme/Generated/Y2kTheme.swift +352 -314
  17. package/apple/Sources/Astryx/Theme/Shadow.swift +5 -3
  18. package/apple/Sources/Astryx/Theme/Theme.swift +79 -34
  19. package/apple/Sources/Astryx/Tooltip/TooltipPresenter.swift +49 -9
  20. package/apple/Sources/Astryx/Wire/AstryxNodeView.swift +2 -0
  21. package/apple/Sources/AstryxNative/Generated/AstryxNode.swift +3 -0
  22. package/apple/Sources/AstryxNative/Generated/Avatar.swift +163 -0
  23. package/apple/Sources/AstryxNative/Generated/Icon.swift +1 -0
  24. package/apple/Sources/AstryxNative/Generated/Switch.swift +2 -26
  25. package/apple/Tests/AstryxTests/AvatarTests.swift +263 -0
  26. package/apple/Tests/AstryxTests/BannerTests.swift +1 -1
  27. package/apple/Tests/AstryxTests/CardTests.swift +31 -6
  28. package/apple/Tests/AstryxTests/EnvironmentTests.swift +90 -0
  29. package/apple/Tests/AstryxTests/HeadingTests.swift +1 -1
  30. package/apple/Tests/AstryxTests/IconTests.swift +4 -3
  31. package/apple/Tests/AstryxTests/TextInputTests.swift +1 -1
  32. package/apple/Tests/AstryxTests/ThemeTests.swift +2 -8
  33. package/apple/Tests/AstryxTests/TooltipPresenterTests.swift +60 -0
  34. package/apple/Tests/AstryxTests/TwoThemeTests.swift +3 -3
  35. package/dist/components/Avatar.d.ts +10 -0
  36. package/dist/components/Avatar.d.ts.map +1 -0
  37. package/dist/components/Avatar.js +16 -0
  38. package/dist/components/Switch.d.ts.map +1 -1
  39. package/dist/components/Switch.js +13 -0
  40. package/dist/components/index.d.ts.map +1 -1
  41. package/dist/components/index.js +2 -0
  42. package/dist/contract/fromComponentDoc.d.ts +11 -1
  43. package/dist/contract/fromComponentDoc.d.ts.map +1 -1
  44. package/dist/contract/fromComponentDoc.js +15 -1
  45. package/dist/contract/generateSwift.d.ts.map +1 -1
  46. package/dist/contract/generateSwift.js +28 -0
  47. package/dist/contract/generateTypeScript.d.ts.map +1 -1
  48. package/dist/contract/generateTypeScript.js +2 -0
  49. package/dist/contract/parseDocType.d.ts +2 -2
  50. package/dist/contract/parseDocType.d.ts.map +1 -1
  51. package/dist/contract/parseDocType.js +7 -2
  52. package/dist/contract/types.d.ts +7 -0
  53. package/dist/contract/types.d.ts.map +1 -1
  54. package/dist/types/android.d.ts +21 -5
  55. package/dist/types/core.d.ts +13 -3
  56. package/dist/types/ios.d.ts +18 -5
  57. package/dist/types/macos.d.ts +18 -5
  58. package/dist/types/shared.d.ts +18 -5
  59. package/dist/types/windows.d.ts +21 -5
  60. package/package.json +3 -3
  61. package/src/components/Avatar.ts +27 -0
  62. package/src/components/Switch.ts +13 -0
  63. package/src/components/index.ts +2 -0
  64. package/src/contract/contracts.test.ts +43 -0
  65. package/src/contract/fromComponentDoc.ts +36 -2
  66. package/src/contract/generateSwift.ts +30 -0
  67. package/src/contract/generateTypeScript.ts +2 -0
  68. package/src/contract/parseDocType.test.ts +12 -0
  69. package/src/contract/parseDocType.ts +9 -2
  70. package/src/contract/types.ts +5 -0
  71. package/src/theme/swiftIOSTheme.test.ts +12 -4
@@ -28,7 +28,7 @@ let package = Package(
28
28
  dependencies: ["AstryxNative"],
29
29
  path: "Sources/Astryx",
30
30
  // Each component's spec lives beside its view (AST-093 FR1).
31
- exclude: ["Icon/Icon.spec.md"],
31
+ exclude: ["Avatar/Avatar.spec.md", "Icon/Icon.spec.md"],
32
32
  resources: [.process("Resources")]
33
33
  ),
34
34
  .testTarget(name: "AstryxNativeTests", dependencies: ["AstryxNative"], path: "Tests/AstryxNativeTests"),
package/apple/README.md CHANGED
@@ -27,6 +27,7 @@ apple/
27
27
  │ │ ├── Resources/ # core's messages per locale, generated; do not edit
28
28
  │ │ ├── Localization/
29
29
  │ │ ├── Icon/ # Icon, Icon.spec.md
30
+ │ │ ├── Avatar/ # Avatar, Avatar.spec.md
30
31
  │ │ ├── Text/ # Text
31
32
  │ │ ├── Heading/ # Heading
32
33
  │ │ ├── Button/ # Button
@@ -0,0 +1,210 @@
1
+ ---
2
+ schema_version: 3
3
+ template_version: 7
4
+ kind: component
5
+ id: component:swift/Avatar
6
+ platform_of: component:Avatar
7
+ authority: draft
8
+ archive_reason: null
9
+ superseded_by: null
10
+ approved_by: null
11
+ approved_at: null
12
+ owners: [cixzhang]
13
+ review_triggers: [public-api, behavior, layout, theming, accessibility]
14
+ verified_by:
15
+ [
16
+ packages/native/apple/Tests/AstryxTests/AvatarTests.swift,
17
+ packages/native/src/contract/contracts.test.ts,
18
+ packages/native/src/contract/parseDocType.test.ts,
19
+ ]
20
+ modules: []
21
+ families: []
22
+ design_specs: []
23
+ architecture: []
24
+ contributing: []
25
+ system_specs: [spec:AST-082, spec:AST-093]
26
+ ---
27
+
28
+ # Avatar (Swift) component contract
29
+
30
+ ## Contract at a glance
31
+
32
+ | Area | Contract |
33
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34
+ | 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`. |
35
+ | 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. |
36
+ | 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. |
37
+ | 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. |
38
+ | 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. |
39
+ | 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. |
40
+ | 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/`. |
41
+
42
+ This table is a review projection; the body below is authoritative.
43
+
44
+ ## Intent
45
+
46
+ Avatar on Apple platforms shows a person's or an entity's picture with core's
47
+ fallback order, sizes, shapes, and naming, drawn with SwiftUI's own image
48
+ loading and link and button controls.
49
+
50
+ ## Compatibility and migration
51
+
52
+ - Released default preserved: `not yet released`
53
+ - Compatibility class: additive
54
+ - Controlled/uncontrolled behavior: not applicable
55
+ - Migration decision: none
56
+
57
+ Consumer migration instructions belong in consumer docs and release notes.
58
+
59
+ ## Ownership boundary
60
+
61
+ **Owns**
62
+
63
+ - Loading `src`, then `fallbackSrc`, with SwiftUI `AsyncImage`.
64
+ - Initials, the person symbol, the plate color, and the shape clip.
65
+ - Switching to a SwiftUI `Link` or `Button` for `href` or `onClick` without
66
+ changing the drawing.
67
+ - The avatar's VoiceOver name and its touch target.
68
+
69
+ **Does not own / non-goals**
70
+
71
+ - The meaning of the props, the initials rule, and the size scale — owned by
72
+ `component:Avatar`.
73
+ - Status dots and avatar groups, which have no Swift view.
74
+
75
+ ## Public concepts
76
+
77
+ | Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
78
+ | ------- | ---------------------------------------------- | --------------------------------------------------- | ----------------------------------------- | -------- | ------------------------ | ------------ | -------------------------------------------------------------------------- |
79
+ | 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 |
80
+ | shape | `circle`, `rounded`, `square` | full round, the theme's element radius, no radius | always | `circle` | `component:Avatar` | experimental | none |
81
+ | 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 |
82
+ | 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 |
83
+
84
+ ## Behavioral and layout contract
85
+
86
+ | ID | Candidate invariant | Basis | Draft review state |
87
+ | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- | ------------------ |
88
+ | 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 |
89
+ | 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 |
90
+ | 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 |
91
+ | 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 |
92
+ | 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 |
93
+ | 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 |
94
+ | 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 |
95
+
96
+ **Tooltip by input (FR8).** The Astryx tooltip's rules apply; this table
97
+ states Avatar's choices.
98
+
99
+ | Input | Default name | Given words | Off (`false` or blank) |
100
+ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------ |
101
+ | 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 |
102
+ | 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 |
103
+ | 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 |
104
+ | 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 |
105
+
106
+ ### Allowed variation
107
+
108
+ - **AV1 — Loading.** While an image loads, the initials or the person symbol
109
+ show instead of an empty plate.
110
+ - **AV2 — Glyph.** The person symbol is the SF Symbol `person.fill`, not core's
111
+ SVG.
112
+
113
+ - **AV3 — Tooltip surface.** The tooltip is the Astryx tooltip's bubble in
114
+ core's tooltip colors on every input. SwiftUI's `.help` does not fit: it is
115
+ also the VoiceOver hint, so it would read the name twice, and it shows with
116
+ the system's look and delay, never on keyboard focus or a tap.
117
+
118
+ ### Representative states
119
+
120
+ | State | Required invariant | Allowed variation |
121
+ | ------------------------------ | -------------------------------------- | ----------------- |
122
+ | image | the image fills the shape | image content |
123
+ | failed image with a fallback | the fallback image | none |
124
+ | initials, every size and shape | initials centered on the neutral plate | glyph metrics |
125
+ | no name | the person symbol at 60% of the side | none |
126
+ | link and button | the same drawing as static | none |
127
+ | light and dark, two themes | each theme's plate and text color | none |
128
+
129
+ ### Transformation and precedence order
130
+
131
+ - **ORD1 — Picture.** `src` → `fallbackSrc` → initials → person symbol.
132
+ - **ORD2 — Name.** `alt` → `name` → none, where a blank string is none.
133
+ - **ORD3 — Control.** `href` (link) → `onClick` (button) → static.
134
+
135
+ ### Performance and resources
136
+
137
+ - **PR1 — System loading.** Images load through `AsyncImage` and the system
138
+ URL cache; the view keeps no image cache of its own.
139
+
140
+ ## Accessibility contract
141
+
142
+ - **AR1 — Named or decorative.** A static avatar with a name is one image
143
+ element named by `alt`, else `name`; without one it is hidden from VoiceOver.
144
+ A link or button avatar is one element with the link or button trait and the
145
+ same name; the initials are never an element of their own (Swift
146
+ accessibility X1, X5).
147
+ - **AR2 — Touch target.** A link or button avatar, and a static avatar whose
148
+ tap opens its tooltip, answers taps across at least 44 by 44 points without
149
+ changing its drawn size or layout (X7).
150
+ - **AR3 — Rendered tree not measured.** Tests assert what the view sets; the
151
+ rendered accessibility tree and the hit region are not measured until an
152
+ app-hosted target exists.
153
+ - **AR4 — Unnamed taps are flagged.** A link or button avatar without `alt`
154
+ or `name` logs a development warning, as core warns.
155
+ - **AR5 — Initials contrast.** The initials draw in core's tokens,
156
+ `color.textSecondary` on `color.neutral`, as core's Avatar does. In the
157
+ default and neutral themes' dark appearance that pair is below 4.5:1, in
158
+ core as well; the fix belongs to the theme tokens.
159
+
160
+ ## Design relationships
161
+
162
+ | Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
163
+ | ---------------- | ---------------------------------------- | ------------------------ | -------------- | ------------------ |
164
+ | Photo, initials | Apple Human Interface Guidelines, Images | prescribed by core | prominent | FR1–FR4 |
165
+
166
+ The component implements design requirements without copying their rationale.
167
+
168
+ Platform controls: SwiftUI `AsyncImage` for the images, SwiftUI `Link` for
169
+ `href`, and SwiftUI `Button` for `onClick` (`spec:AST-093` FR2). SwiftUI has no
170
+ avatar control, so the plate, initials, and clip are drawn here. Guideline
171
+ pages: Images, Buttons, and Accessibility in the Apple Human Interface
172
+ Guidelines.
173
+
174
+ Theme values read: `color.neutral`, `color.textSecondary`, `radius.element`,
175
+ `font.family.body`, `font.weight.medium`, and Bold Text; for the tooltip bubble,
176
+ `color.textPrimary`, `color.backgroundSurface`, `space.s1`, `space.s2`,
177
+ `radius.container`, and the body text size and weight.
178
+
179
+ ## Family and system relationships
180
+
181
+ - `component:Avatar` owns the props, the sizes, the initials rule, and the
182
+ fallback order; this record states only how Swift draws them.
183
+ - An owner that holds an Avatar in a slot leaves an unsized Avatar at `md`
184
+ (Swift slots S4).
185
+
186
+ ## Verification map
187
+
188
+ | Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
189
+ | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
190
+ | 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` |
191
+ | 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` |
192
+ | 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` |
193
+ | 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` |
194
+ | 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` |
195
+ | AR1 | `AvatarTests.swift` naming and trait tests | `alt`, `name`, blank, none | a wrong name or a named decorative avatar fails | `audit:swift/Avatar/a11y` |
196
+ | 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` |
197
+
198
+ ## Decision log
199
+
200
+ No component-local decision is recorded.
201
+
202
+ ## Open questions
203
+
204
+ - **OQ2 — Status dots.** (`human-api`) `status` holds `AvatarStatusDot`, which
205
+ has no Swift view, so it stays on the web until one exists.
206
+
207
+ ## Content boundary
208
+
209
+ This file does not duplicate consumer prop tables/examples, current audit
210
+ results, implementation steps, or family/system rules. It links to their owners.
@@ -0,0 +1,418 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ import AstryxNative
4
+ import SwiftUI
5
+ import os
6
+
7
+ /// A person's or an entity's picture: the image at `src`, else `fallbackSrc`,
8
+ /// else initials from `name`, else a person symbol (core `Avatar`).
9
+ ///
10
+ /// ```swift
11
+ /// Avatar("Ada Lovelace", src: "https://example.com/ada.jpg")
12
+ /// Avatar("Ada Lovelace", size: .lg, shape: .rounded)
13
+ /// Avatar("Ada Lovelace", href: "https://example.com/ada")
14
+ /// Avatar("Ada Lovelace") { showProfile() }
15
+ /// ```
16
+ public struct Avatar: View {
17
+ /// The contract the view draws, the same for both initializers.
18
+ public let props: AvatarProps
19
+ @Environment(\.astryx) private var astryx
20
+
21
+ /// An avatar from its labeled props.
22
+ /// - Parameters:
23
+ /// - name: The person's or entity's name, for initials and the accessible name (core `name`).
24
+ /// - src: The image URL (core `src`).
25
+ /// - fallbackSrc: The image URL to try when `src` fails (core `fallbackSrc`).
26
+ /// - alt: The accessible name, when it differs from `name` (core `alt`).
27
+ /// - size: `xsm` 20, `sm` 24, `md` 36, `lg` 48, or `xl` 128 points; `nil` is `md` (core `size`).
28
+ /// - shape: `circle`, `rounded`, or `square`; `nil` is `circle` (core `shape`).
29
+ /// - tooltip: Words shown where there is a pointer: `nil` or `true` the name, a string those words, `false` none (core `tooltip`).
30
+ /// - href: A URL the system opens when the avatar is tapped; the avatar becomes a link (core `href`).
31
+ /// - onClick: Runs when the avatar is tapped; without `href` the avatar becomes a button (core `onClick`).
32
+ public init(
33
+ _ name: String? = nil,
34
+ src: String? = nil,
35
+ fallbackSrc: String? = nil,
36
+ alt: String? = nil,
37
+ size: AvatarSize? = nil,
38
+ shape: AvatarShape? = nil,
39
+ tooltip: AvatarTooltip? = nil,
40
+ href: String? = nil,
41
+ onClick: (() -> Void)? = nil
42
+ ) {
43
+ self.init(
44
+ AvatarProps(
45
+ src: src, fallbackSrc: fallbackSrc, name: name, alt: alt, size: size, shape: shape, tooltip: tooltip, href: href,
46
+ onClick: onClick
47
+ ))
48
+ }
49
+
50
+ /// An avatar from its generated contract, for generated and wire-driven callers.
51
+ public init(_ props: AvatarProps) {
52
+ self.props = props
53
+ }
54
+
55
+ public var body: some View {
56
+ if props.base.isHidden != true {
57
+ control
58
+ // The Astryx tooltip (library/tooltip.spec.md), as core's Avatar uses
59
+ // core's tooltip: a static avatar is a tab stop and opens on a tap;
60
+ // a link or button keeps its focus and its tap.
61
+ // Touch is core's `auto`: a static avatar opens on a tap; a control's
62
+ // tap belongs to its action.
63
+ .astryxTooltip(tooltipText, hint: tooltipHint, focus: Avatar.tooltipFocus(tap))
64
+ .modifier(AvatarIdentifier(id: props.base.id))
65
+ .onAppear(perform: checkInDevelopment)
66
+ }
67
+ }
68
+
69
+ /// Development checks core makes too: an `href` an app cannot open stops
70
+ /// the build with its value, and an unnamed link or button is flagged.
71
+ private func checkInDevelopment() {
72
+ #if DEBUG
73
+ if Avatar.isUnusableHref(props.href) {
74
+ assertionFailure(
75
+ "Avatar href \"\(props.href ?? "")\" is not an absolute URL an app can open; it draws without a link.")
76
+ }
77
+ if Avatar.needsNameWarning(tap: tap, isNamed: accessibilityLabel != nil) {
78
+ Logger(subsystem: "Astryx", category: "Avatar").warning(
79
+ "An Avatar with href or onClick has no alt or name, so VoiceOver reads it without a name.")
80
+ }
81
+ #endif
82
+ }
83
+
84
+ /// The tooltip's words: the name for `nil` or `true`, the given words, or
85
+ /// none for `false` or blank words, as core resolves it.
86
+ var tooltipText: String? {
87
+ switch props.tooltip ?? .on {
88
+ case .on: Avatar.meaningful(props.name).map(Avatar.trimmed)
89
+ case .off: nil
90
+ case .text(let words): Avatar.meaningful(words).map(Avatar.trimmed)
91
+ }
92
+ }
93
+
94
+ /// The VoiceOver hint: given tooltip words, as core puts them in the
95
+ /// description; the default name is the avatar's own name, not repeated.
96
+ var tooltipHint: String? {
97
+ guard case .text = props.tooltip else { return nil }
98
+ return tooltipText
99
+ }
100
+
101
+ /// A non-empty `href` that is not an absolute URL, such as a web path.
102
+ nonisolated static func isUnusableHref(_ href: String?) -> Bool {
103
+ guard let href, !href.isEmpty else { return false }
104
+ guard let url = URL(string: href) else { return true }
105
+ return url.scheme == nil
106
+ }
107
+
108
+ /// The picture as a link with `href`, a button with only `onClick`, or a
109
+ /// static image (Swift component API, A4). All three draw the same.
110
+ @ViewBuilder private var control: some View {
111
+ if let url = linkURL {
112
+ SwiftUI.Link(destination: url) { picture }
113
+ .buttonStyle(.plain)
114
+ .modifier(AvatarRunsBeforeOpening(onClick: props.onClick))
115
+ .modifier(AvatarTarget(side: side))
116
+ .modifier(AvatarName(label: accessibilityLabel, tap: .link))
117
+ } else if let onClick = props.onClick {
118
+ SwiftUI.Button(action: onClick) { picture }
119
+ .buttonStyle(.plain)
120
+ .modifier(AvatarTarget(side: side))
121
+ .modifier(AvatarName(label: accessibilityLabel, tap: .button))
122
+ } else {
123
+ picture
124
+ // A static avatar whose tap opens its tooltip answers taps across
125
+ // 44 points too.
126
+ .modifier(AvatarTarget(side: Avatar.tapTargetSide(side, takesTaps: tooltipText != nil)))
127
+ .modifier(AvatarName(label: accessibilityLabel, tap: .none))
128
+ }
129
+ }
130
+
131
+ /// How the avatar takes a tap: a link with a usable `href`, else a button
132
+ /// with `onClick`, else none.
133
+ enum Tap: Equatable { case link, button, none }
134
+
135
+ /// How far a tappable avatar's tap area reaches past its side: to 44
136
+ /// points (Swift accessibility, X7).
137
+ nonisolated static func tapOutset(side: CGFloat) -> CGFloat { max(0, (44 - side) / 2) }
138
+
139
+ /// The side a static avatar's tap area grows from: its own when a tap
140
+ /// opens its tooltip, and 44, which adds nothing, when it takes no taps.
141
+ nonisolated static func tapTargetSide(_ side: CGFloat, takesTaps: Bool) -> CGFloat { takesTaps ? side : 44 }
142
+
143
+ /// How keyboard focus reaches the tooltip: a static avatar is made a tab
144
+ /// stop, as core gives it one; a link or button takes focus already.
145
+ nonisolated static func tooltipFocus(_ tap: Tap) -> TooltipFocus { tap == .none ? .tabStop : .control }
146
+
147
+
148
+ var tap: Tap {
149
+ if linkURL != nil { return .link }
150
+ if props.onClick != nil { return .button }
151
+ return .none
152
+ }
153
+
154
+ /// The traits the avatar adds: a named static avatar is an image; a link or
155
+ /// button keeps its own trait and adds none (Swift accessibility, X1).
156
+ nonisolated static func addedTraits(tap: Tap, isNamed: Bool) -> AccessibilityTraits {
157
+ guard isNamed else { return [] }
158
+ switch tap {
159
+ case .none: return .isImage
160
+ case .link: return .isLink
161
+ case .button: return []
162
+ }
163
+ }
164
+
165
+ /// Traits a named avatar drops: a link avatar is a link, not the button
166
+ /// SwiftUI reports for `Link`.
167
+ nonisolated static func removedTraits(tap: Tap, isNamed: Bool) -> AccessibilityTraits {
168
+ isNamed && tap == .link ? .isButton : []
169
+ }
170
+
171
+ /// A link or button avatar needs a name, as core warns in development.
172
+ nonisolated static func needsNameWarning(tap: Tap, isNamed: Bool) -> Bool {
173
+ tap != .none && !isNamed
174
+ }
175
+
176
+ /// The photo; the fallback photo only after it fails or when there is
177
+ /// none, as core does; initials or the symbol while either loads and
178
+ /// after both fail.
179
+ private var picture: some View {
180
+ AvatarImage(url: url(props.src)) {
181
+ plate
182
+ } failure: {
183
+ AvatarImage(url: url(props.fallbackSrc)) { plate } failure: { plate }
184
+ }
185
+ .frame(width: side, height: side)
186
+ .clipShape(AvatarShapeOutline(shape: resolvedShape, radius: cornerRadius))
187
+ }
188
+
189
+ /// The fallback: initials on the neutral plate, else a person symbol.
190
+ private var plate: some View {
191
+ ZStack {
192
+ astryx.tokens.color.neutral
193
+ if let initials {
194
+ // Drawn, not laid out as a Text view, so the initials are never an
195
+ // accessibility element of their own; the name names the avatar.
196
+ let font = initialsFont
197
+ let color = astryx.tokens.color.textSecondary
198
+ Canvas { context, size in
199
+ let text = context.resolve(SwiftUI.Text(initials).font(font).foregroundColor(color))
200
+ context.draw(text, at: CGPoint(x: size.width / 2, y: size.height / 2), anchor: .center)
201
+ }
202
+ .accessibilityHidden(true)
203
+ } else {
204
+ Image(systemName: "person.fill")
205
+ .resizable()
206
+ .scaledToFit()
207
+ .frame(width: side * 0.6, height: side * 0.6)
208
+ .foregroundStyle(astryx.tokens.color.textSecondary)
209
+ .accessibilityHidden(true)
210
+ }
211
+ }
212
+ }
213
+
214
+ /// The side of the avatar in points.
215
+ /// The side of the avatar in points: core's size grown with Dynamic Type,
216
+ /// as the name beside it grows, up to 1.6 times so it never swallows a row.
217
+ var side: CGFloat { Avatar.side(for: props.size ?? .md, textScale: astryx.textScale) }
218
+
219
+ /// The most an avatar grows with Dynamic Type.
220
+ nonisolated static var maximumTextScale: CGFloat { 1.6 }
221
+
222
+ nonisolated static func side(for size: AvatarSize, textScale: CGFloat) -> CGFloat {
223
+ (points(for: size) * min(max(textScale, 1), maximumTextScale)).rounded()
224
+ }
225
+
226
+ var resolvedShape: AvatarShape { props.shape ?? .circle }
227
+
228
+ /// The corner radius for `rounded`, from the theme's element radius.
229
+ private var cornerRadius: CGFloat { astryx.tokens.radius.element }
230
+
231
+ /// Initials drawn at 40% of the side in the theme's body family, medium weight.
232
+ private var initialsFont: Font {
233
+ astryxFont(
234
+ families: astryx.tokens.font.family.body,
235
+ size: side * 0.4,
236
+ weight: astryx.fontWeight(astryx.tokens.font.weight.medium),
237
+ isBoldText: astryx.isBoldText
238
+ )
239
+ }
240
+
241
+ /// The initials the plate shows, or `nil` for the person symbol.
242
+ var initials: String? {
243
+ guard let name = Avatar.meaningful(props.name) else { return nil }
244
+ let initials = Avatar.initials(from: name)
245
+ return initials.isEmpty ? nil : initials
246
+ }
247
+
248
+ /// The name VoiceOver reads: `alt`, else `name`; `nil` when neither
249
+ /// carries anything, and then a static avatar is decorative.
250
+ var accessibilityLabel: String? {
251
+ Avatar.meaningful(props.alt) ?? Avatar.meaningful(props.name)
252
+ }
253
+
254
+ /// The URL the avatar opens, or `nil` when it has no usable `href`.
255
+ var linkURL: URL? {
256
+ // Only an absolute URL the system can open; a malformed or relative
257
+ // `href` leaves the avatar static or a button.
258
+ guard let url = url(props.href), url.scheme != nil else { return nil }
259
+ return url
260
+ }
261
+
262
+ private func url(_ string: String?) -> URL? {
263
+ guard let string, !string.isEmpty else { return nil }
264
+ return URL(string: string)
265
+ }
266
+
267
+ /// Core's named sizes in points.
268
+ nonisolated static func points(for size: AvatarSize) -> CGFloat {
269
+ switch size {
270
+ case .xsm: 20
271
+ case .sm: 24
272
+ case .md: 36
273
+ case .lg: 48
274
+ case .xl: 128
275
+ }
276
+ }
277
+
278
+ /// The string when it carries something, `nil` when it is absent or blank.
279
+ /// Words without their leading and trailing space, as core trims the
280
+ /// tooltip it shows.
281
+ nonisolated static func trimmed(_ value: String) -> String {
282
+ value.trimmingCharacters(in: .whitespacesAndNewlines)
283
+ }
284
+
285
+ nonisolated static func meaningful(_ value: String?) -> String? {
286
+ guard let value, !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }
287
+ return value
288
+ }
289
+
290
+ /// Core's initials: the first letter, digit, or emoji of the first and last
291
+ /// words that have one, uppercased. Leading punctuation in a word is skipped.
292
+ nonisolated static func initials(from name: String) -> String {
293
+ let letters = name.split(whereSeparator: { $0.isWhitespace }).compactMap { word in
294
+ word.first(where: canStandForAWord)
295
+ }
296
+ guard let first = letters.first else { return "" }
297
+ guard letters.count > 1, let last = letters.last else { return String(first).uppercased() }
298
+ return (String(first) + String(last)).uppercased()
299
+ }
300
+
301
+ /// A letter, a digit, or an emoji, as core's `\p{L}`, `\p{N}`,
302
+ /// `\p{Extended_Pictographic}`, and `\p{Regional_Indicator}`.
303
+ nonisolated static func canStandForAWord(_ character: Character) -> Bool {
304
+ if character.isLetter || character.isNumber { return true }
305
+ guard let scalar = character.unicodeScalars.first else { return false }
306
+ // `isEmoji` also covers `#`, `*`, and the digits, which are ASCII.
307
+ return scalar.value > 0x7F && scalar.properties.isEmoji
308
+ }
309
+ }
310
+
311
+ /// Draws the image at a URL: `loading` while it loads, `failure` when it
312
+ /// fails or there is no URL.
313
+ private struct AvatarImage<Loading: View, Failure: View>: View {
314
+ let url: URL?
315
+ @ViewBuilder let loading: () -> Loading
316
+ @ViewBuilder let failure: () -> Failure
317
+
318
+ var body: some View {
319
+ if let url {
320
+ AsyncImage(url: url) { phase in
321
+ if let image = phase.image {
322
+ image.resizable().scaledToFill()
323
+ } else if phase.error != nil {
324
+ failure()
325
+ } else {
326
+ loading()
327
+ }
328
+ }
329
+ } else {
330
+ failure()
331
+ }
332
+ }
333
+ }
334
+
335
+ /// Runs `onClick` as a link opens, then hands the URL to whatever opens URLs
336
+ /// above the avatar, so an app's own handler still applies. Without
337
+ /// `onClick` it changes nothing.
338
+ private struct AvatarRunsBeforeOpening: ViewModifier {
339
+ let onClick: (() -> Void)?
340
+ @Environment(\.openURL) private var inheritedOpenURL
341
+
342
+ func body(content: Content) -> some View {
343
+ if let onClick {
344
+ content.environment(\.openURL, OpenURLAction { url in
345
+ onClick()
346
+ inheritedOpenURL(url)
347
+ return .handled
348
+ })
349
+ } else {
350
+ content
351
+ }
352
+ }
353
+ }
354
+
355
+ /// The outline each shape clips to: a circle, the element radius, or square.
356
+ private struct AvatarShapeOutline: Shape {
357
+ let shape: AvatarShape
358
+ let radius: CGFloat
359
+
360
+ func path(in rect: CGRect) -> Path {
361
+ switch shape {
362
+ case .circle: Circle().path(in: rect)
363
+ case .rounded: RoundedRectangle(cornerRadius: radius, style: .continuous).path(in: rect)
364
+ case .square: Rectangle().path(in: rect)
365
+ }
366
+ }
367
+ }
368
+
369
+ /// One element named by the avatar's label. A static avatar without a label
370
+ /// is hidden; an interactive one keeps its link or button trait.
371
+ private struct AvatarName: ViewModifier {
372
+ let label: String?
373
+ let tap: Avatar.Tap
374
+
375
+ func body(content: Content) -> some View {
376
+ let isNamed = label != nil
377
+ let added = Avatar.addedTraits(tap: tap, isNamed: isNamed)
378
+ let removed = Avatar.removedTraits(tap: tap, isNamed: isNamed)
379
+ if let label {
380
+ if tap == .none {
381
+ // One image element named by the name.
382
+ content.accessibilityElement(children: .ignore).accessibilityLabel(label)
383
+ .accessibilityAddTraits(added)
384
+ } else {
385
+ // The link or button itself carries the name, so VoiceOver reads
386
+ // "Grace Hopper, button", not the initials inside it.
387
+ content.accessibilityLabel(label).accessibilityAddTraits(added).accessibilityRemoveTraits(removed)
388
+ }
389
+ } else if tap != .none {
390
+ content
391
+ } else {
392
+ content.accessibilityHidden(true)
393
+ }
394
+ }
395
+ }
396
+
397
+ /// A tappable avatar answers taps across at least 44 by 44 points without
398
+ /// changing its drawn size or its layout (Swift accessibility, X7).
399
+ private struct AvatarTarget: ViewModifier {
400
+ let side: CGFloat
401
+
402
+ func body(content: Content) -> some View {
403
+ content.contentShape(.interaction, Rectangle().inset(by: -Avatar.tapOutset(side: side)))
404
+ }
405
+ }
406
+
407
+ /// The base `id` becomes the accessibility identifier (AST-082 FR7).
408
+ private struct AvatarIdentifier: ViewModifier {
409
+ let id: String?
410
+
411
+ func body(content: Content) -> some View {
412
+ if let id {
413
+ content.accessibilityIdentifier(id)
414
+ } else {
415
+ content
416
+ }
417
+ }
418
+ }