An open source design system that's fully customizable and agent ready
TypeScript
feat(native): SwiftUI views as the Astryx product in apple/, with core components and clone-only templates (#7981)
Cindy Zhangd42a692a934c
diff --git a/packages/native/README.md b/packages/native/README.mdindex 170a55bd11..2ef9e92fce 100644--- a/packages/native/README.md+++ b/packages/native/README.md@@ -12,20 +12,23 @@ rests on evidence.## What is here today-| Part | Path | What it does |-| -------------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Contracts | `src/contract/` | Reads a core component's documentation and splits its props into a portable **core contract** and a **web-only** part, with a reason for each web-only prop. Checks prop names against Swift and Kotlin keywords and platform toolkit names. |-| Platform types | `@astryxdesign/native/components` | TypeScript props per platform, chosen by type-resolution condition: `ios`, `android`, `macos`, `windows`, or `shared` for the core contract only. |-| Swift binding | `apple/` | A Swift package with props generated from the same contracts. iOS and macOS props sit behind `#if os(...)`. |-| Native theme | `defineNativeTheme` | Durable theme intent (`material: 'opaque' \| 'translucent'`) plus platform entries scoped by OS version, such as Liquid Glass from iOS 26. Never sets tokens. |-| Icons | `NATIVE_ICON_DEFAULTS` | Astryx's built-in icon names mapped to SF Symbols on Apple platforms and Material Symbols on Android. |-| Wire | `AstryxNode`, `AstryxAction` | Each component as JSON a TypeScript core sends a native host (arm C), and the action a host sends back when a view calls a callback. Swift decodes `<Name>Node` and turns it into `<Name>Props` with `viewProps(send:)`. |-| Logic core | `@astryxdesign/native/logic` | `createLogicCore` holds a screen's state, builds its node tree, and reduces actions; `connectBridge` carries it to a native host as JSON. ECMAScript built-ins only, so it runs in Hermes. Shaped after EJ Campbell's astryx-swift spike. |-| Logic host | `AstryxLogicHost` (Swift) | Runs a logic core bundle in JavaScriptCore, decodes each tree into `AstryxNode`, and sends views' actions back. A Hermes host speaks the same bridge. |+| Part | Path | What it does |+| -------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Contracts | `src/contract/` | Reads a core component's documentation and splits its props into a portable **core contract** and a **web-only** part, with a reason for each web-only prop. Checks prop names against Swift and Kotlin keywords and platform toolkit names. |+| Platform types | `@astryxdesign/native/components` | TypeScript props per platform, chosen by type-resolution condition: `ios`, `android`, `macos`, `windows`, or `shared` for the core contract only. |+| Swift binding | `apple/` | A Swift package with two products: `AstryxNative`, props generated from the same contracts (iOS and macOS props sit behind `#if os(...)`) plus the logic host, and `Astryx`, SwiftUI views drawn with core's tokens. Clone-only page templates sit in `apple/Templates/`. See [its README](apple/README.md). |+| Native theme | `defineNativeTheme` | Durable theme intent (`material: 'opaque' \| 'translucent'`) plus platform entries scoped by OS version, such as Liquid Glass from iOS 26. Never sets tokens. |+| Icons | `NATIVE_ICON_DEFAULTS` | Astryx's built-in icon names mapped to SF Symbols on Apple platforms and Material Symbols on Android. |+| Wire | `AstryxNode`, `AstryxAction` | Each component as JSON a TypeScript core sends a native host (arm C), and the action a host sends back when a view calls a callback. Swift decodes `<Name>Node` and turns it into `<Name>Props` with `viewProps(send:)`. |+| Logic core | `@astryxdesign/native/logic` | `createLogicCore` holds a screen's state, builds its node tree, and reduces actions; `connectBridge` carries it to a native host as JSON. ECMAScript built-ins only, so it runs in Hermes. Shaped after EJ Campbell's astryx-swift spike. |+| Logic host | `AstryxLogicHost` (Swift) | Runs a logic core bundle in JavaScriptCore, decodes each tree into `AstryxNode`, and sends views' actions back. A Hermes host speaks the same bridge. |Contracts cover Badge, Button, Card, Divider, Heading, HStack, ProgressBar,-Selector, Switch, Text, TextInput, and VStack. React Native and Android-bindings are not built yet; see [the experiment matrix](#experiment-matrix).+Selector, Switch, Text, TextInput, and VStack. The `Astryx` Swift product draws+Text, Heading, Button, TextInput, Card, and Banner, and `apple/Templates/` the+`login` template, in SwiftUI.+React Native and Android bindings are not built yet; see+[the experiment matrix](#experiment-matrix).```ts// tsconfig.json for an iOS app: "customConditions": ["ios"]@@ -129,6 +132,7 @@ pnpm -F @astryxdesign/native typecheck # source and testspnpm -F @astryxdesign/native build # dist/, including platform typespnpm -F @astryxdesign/native typecheck:types # every platform's types, after buildpnpm -F @astryxdesign/native generate:apple # regenerate apple/Sources/.../Generated+pnpm -F @astryxdesign/native generate:swift-ios # regenerate the Astryx product's default theme and stringspnpm vitest run --project node packages/native```diff --git a/packages/native/apple/Package.swift b/packages/native/apple/Package.swiftindex 4b7137dc14..c0d86d185a 100644--- a/packages/native/apple/Package.swift+++ b/packages/native/apple/Package.swift@@ -1,18 +1,35 @@// swift-tools-version: 6.0// Copyright (c) Meta Platforms, Inc. and affiliates.-// Experimental Astryx for Apple platforms (AST-082). The contract types under-// Sources/AstryxNative/Generated are generated by `pnpm generate:apple`; do not-// edit them by hand.+// Experimental Astryx for Apple platforms (AST-082). Two products:+// - `Astryx`: SwiftUI views painted with the theme's tokens, the theme+// environment, and core's localized messages (Sources/Astryx).+// - `AstryxNative`: the contract types generated by `pnpm generate:apple`+// (Sources/AstryxNative/Generated; do not edit them by hand) and the logic+// host.+// Page templates are a separate package in Templates/, with no products,+// because they are clone-only source and are never published.import PackageDescriptionlet package = Package(name: "AstryxNative",+ defaultLocalization: "en",platforms: [.iOS(.v17), .macOS(.v14)],- products: [.library(name: "AstryxNative", targets: ["AstryxNative"])],+ products: [+ .library(name: "Astryx", targets: ["Astryx"]),+ .library(name: "AstryxNative", targets: ["AstryxNative"]),+ ],targets: [.target(name: "AstryxNative", path: "Sources/AstryxNative"),+ // Resources holds core's catalog messages per locale, generated.+ .target(+ name: "Astryx",+ dependencies: ["AstryxNative"],+ path: "Sources/Astryx",+ resources: [.process("Resources")]+ ),.testTarget(name: "AstryxNativeTests", dependencies: ["AstryxNative"], path: "Tests/AstryxNativeTests"),+ .testTarget(name: "AstryxTests", dependencies: ["Astryx"], path: "Tests/AstryxTests"),])diff --git a/packages/native/apple/README.md b/packages/native/apple/README.mdnew file mode 100644index 0000000000..a3f87268bb--- /dev/null+++ b/packages/native/apple/README.md@@ -0,0 +1,146 @@+# Astryx for Apple platforms++> **Experimental. Canary only.** Part of `@astryxdesign/native`. APIs change+> without notice.++One Swift package with two products:++- **`Astryx`**: SwiftUI views painted with the theme's tokens, the theme+ environment, and core's localized messages. It is arm A of the AST-082+ experiment (pure native: platform views painted with Astryx's tokens).+- **`AstryxNative`**: contract types generated from core's component+ documentation, the wire a TypeScript logic core sends, and the logic host+ that runs one (arm C).++Page templates built from the views are a separate package with no products,+because templates are clone-only and never published.++## Layout++```text+apple/+├── Package.swift # products Astryx and AstryxNative+├── Sources/+│ ├── Astryx/ # SwiftUI views (module Astryx)+│ │ ├── Theme/ # tokens, the theme environment, Dynamic Type+│ │ │ └── Generated/ # core's default theme, generated; do not edit+│ │ ├── Resources/ # core's messages per locale, generated; do not edit+│ │ ├── Localization/+│ │ ├── Text/ # AstryxText+│ │ ├── Heading/ # AstryxHeading+│ │ ├── Button/ # AstryxButton+│ │ ├── TextInput/ # AstryxTextInput+│ │ ├── Card/ # AstryxCard+│ │ └── Banner/ # AstryxBanner+│ └── AstryxNative/ # contracts, wire, logic host (module AstryxNative)+│ └── Generated/ # generated; do not edit+├── Tests/+│ ├── AstryxTests/+│ └── AstryxNativeTests/+└── Templates/ # page templates to copy; its own package, never published+ ├── Package.swift # no products; compiles and tests the templates+ ├── Login/ # LoginTemplate, from `astryx template login`+ └── Tests/+```++- **`Sources/Astryx/<Name>/`** holds one folder per component, named as in+ `packages/core/src/<Name>/`. A component's parameters use core's prop names+ and values (`variant: .primary`, `size: .lg`, `isLoading`), so code reads+ the same across web and native, with six exceptions, the interim shape+ AST-093 FR5 exempts until the components move onto the generated contracts:+ - `AstryxButton` takes `action` where core has `onClick`.+ - `AstryxButton` takes `fillsWidth` where core has `width="100%"`.+ - `AstryxButton` takes `icon` as a shared icon name (`"search"`), which the+ generated `ButtonProps` does not carry yet.+ - `AstryxTextInput` takes a `Binding` where core has `value` and `onChange`.+ - `AstryxHeading`'s `level` is optional where core requires it.+ - `AstryxCard` takes `padding` as a whole spacing step, so it cannot spell+ core's `0.5` and `1.5` steps.+- **`Templates/`** holds one folder per page template, named after the+ `astryx template` id. Templates are clone-only, as on the web: you copy a+ template's folder into your app and own it from then on. They are a+ separate package with no products, so nothing imports them, and+ `@astryxdesign/native` leaves them out of its npm package. A template is+ built only from `Astryx` views and SwiftUI layout, and matches the web+ template's content and states. Rules a template needs, such as validation,+ live in a plain value type beside the view so tests can check them without a+ screen.++## Use it++Depend on the `Astryx` product. To start from a template, copy its folder,+such as `Templates/Login/`, into your app's sources; it then belongs to your+app.++```swift+import Astryx+import SwiftUI++@main+struct DemoApp: App {+ var body: some Scene {+ WindowGroup {+ LoginTemplate().astryxTheme() // copied from Templates/Login/+ }+ }+}+```++`astryxTheme(_:)` paints a subtree with a theme; without it, components use+core's default theme. Either way they follow Dark Mode and the person's text+size.++## Theme tokens++Components read every color, size, and font from the `astryx` environment+value, never from a constant of their own. Token names are core's, without+the leading `--` (`color-accent`, `spacing-4`, `size-element-md`). Text sizes+grow with Dynamic Type.++Font families come from the theme's `font-family-*` stacks: the first family+the device has wins, and a system family such as `-apple-system` or+`sans-serif` is the system font. Icons use core's shared icon names+(`success`, `warning`, …), drawn as an SF Symbol by default; a theme replaces+one with `AstryxTheme(…, icons: ["success": "checkmark.seal.fill"])`.++`Sources/Astryx/Theme/Generated/DefaultTheme.swift` is core's default theme+run through core's own resolver, light and dark. Regenerate it after a core+token change:++```sh+pnpm -F @astryxdesign/native generate:swift-ios+```++The same command writes+`Sources/Astryx/Resources/<locale>.lproj/Localizable.strings` from core's+locale catalogs, so words the components speak to assistive technology, such+as a loading button's "Loading", follow the person's language. Tests in+`@astryxdesign/native` fail when either committed output drifts from core.++## Working on it++On a Mac with Xcode or the Swift command-line tools:++```sh+cd packages/native/apple+swift test # both products+cd Templates && swift test # templates, against the Astryx product+```++Both packages also declare macOS 14 so they build and test on a Mac without a+simulator; iOS 17 is the target. Open `Templates/Package.swift` in Xcode to+run `LoginTemplate` in an iOS simulator through its preview.++To add a component, create `Sources/Astryx/<Name>/Astryx<Name>.swift` with+core's prop names, read its tokens from `astryx`, and add tests under+`Tests/AstryxTests/`. To add a template, create+`Templates/<Name>/<Name>Template.swift` from the output of+`astryx template <id>`, with tests under `Templates/Tests/`.++## Not here yet++- The views do not use the generated contract types in `AstryxNative` yet.+ Moving them onto those types is how a core prop change reaches Swift.+- Pixel and behavior parity with the web components has not been measured.+- Only the default theme is generated; named themes, Increase Contrast, and+ platform theme entries (`defineNativeTheme`) are not wired in.diff --git a/packages/native/apple/Sources/Astryx/Banner/AstryxBanner.swift b/packages/native/apple/Sources/Astryx/Banner/AstryxBanner.swiftnew file mode 100644index 0000000000..8760f74a5d--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Banner/AstryxBanner.swift@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI++/// Core's `Banner` statuses.+public enum AstryxBannerStatus: String, CaseIterable, Sendable {+ case info+ case warning+ case error+ case success++ /// The shared icon name for this status (AST-082 FR17), drawn as the+ /// theme's or the platform's symbol for it.+ var iconName: String { rawValue }++ var groundToken: String {+ switch self {+ case .info: "color-accent-muted"+ case .warning: "color-warning-muted"+ case .error: "color-error-muted"+ case .success: "color-success-muted"+ }+ }++ var iconToken: String {+ switch self {+ case .info: "color-accent"+ case .warning: "color-warning"+ case .error: "color-error"+ case .success: "color-success"+ }+ }+}++/// A message about the page or a section of it. The status sets the color+/// and icon only; the title must say what happened, because the icon is+/// decorative to VoiceOver.+public struct AstryxBanner: View {+ let status: AstryxBannerStatus+ let title: String+ let description: String?+ @Environment(\.astryx) private var astryx++ public init(status: AstryxBannerStatus, title: String, description: String? = nil) {+ self.status = status+ self.title = title+ self.description = description+ }++ public var body: some View {+ HStack(alignment: .firstTextBaseline, spacing: astryx.space(2)) {+ if let symbol = astryx.icon(status.iconName) {+ // Sized with the title so it grows with Dynamic Type.+ Image(systemName: symbol)+ .font(astryx.font(size: "text-body-size", 14, weight: "text-body-weight"))+ .foregroundStyle(astryx.color(status.iconToken))+ .accessibilityHidden(true)+ }+ VStack(alignment: .leading, spacing: astryx.space(1)) {+ AstryxText(title, weight: .semibold)+ if let description {+ AstryxText(description, color: .secondary)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .padding(astryx.space(3))+ .background(+ RoundedRectangle(cornerRadius: astryx.size("radius-container", 12), style: .continuous)+ .fill(astryx.color(status.groundToken))+ )+ .accessibilityElement(children: .ignore)+ .accessibilityLabel(Text(accessibilityText))+ }++ /// What VoiceOver reads: the title, then the description.+ var accessibilityText: String {+ description.map { "\(title), \($0)" } ?? title+ }+}diff --git a/packages/native/apple/Sources/Astryx/Button/AstryxButton.swift b/packages/native/apple/Sources/Astryx/Button/AstryxButton.swiftnew file mode 100644index 0000000000..e638a68e02--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Button/AstryxButton.swift@@ -0,0 +1,167 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// Adapted from github.com/ejc3/astryx-swift (MIT).++import SwiftUI++/// Core's `Button` variants.+public enum AstryxButtonVariant: String, CaseIterable, Sendable {+ case primary+ case secondary+ case ghost+ case destructive+}++/// Core's `Button` sizes: `size-element-sm`, `-md`, and `-lg` high.+public enum AstryxButtonSize: String, CaseIterable, Sendable {+ case sm+ case md+ case lg++ var heightToken: String { "size-element-\(rawValue)" }+ var fallbackHeight: CGFloat {+ switch self {+ case .sm: 28+ case .md: 32+ case .lg: 36+ }+ }+}++/// A labeled action, painted with the theme's tokens. The tap area reaches+/// the platform's 44-by-44-point minimum even when the drawn button is smaller.+public struct AstryxButton: View {+ let label: String+ let variant: AstryxButtonVariant+ let size: AstryxButtonSize+ let icon: String?+ let isLoading: Bool+ let isDisabled: Bool+ let fillsWidth: Bool+ let action: () -> Void+ @Environment(\.astryx) private var astryx++ /// - Parameters:+ /// - icon: a shared icon name, such as `"search"`, shown before the+ /// label; the theme's symbol for it, else the platform default.+ /// - fillsWidth: the button takes the whole width it is offered, as+ /// core's `width="100%"` does.+ public init(+ label: String,+ variant: AstryxButtonVariant = .secondary,+ size: AstryxButtonSize = .md,+ icon: String? = nil,+ isLoading: Bool = false,+ isDisabled: Bool = false,+ fillsWidth: Bool = false,+ action: @escaping () -> Void+ ) {+ self.label = label+ self.variant = variant+ self.size = size+ self.icon = icon+ self.isLoading = isLoading+ self.isDisabled = isDisabled+ self.fillsWidth = fillsWidth+ self.action = action+ }++ public var body: some View {+ Button(action: activate) {+ // The label keeps its place while loading so the width holds; the+ // spinner draws over it.+ HStack(spacing: astryx.space(2)) {+ if let icon, let symbol = astryx.icon(icon) {+ Image(systemName: symbol)+ }+ Text(label).lineLimit(1)+ }+ .opacity(isLoading ? 0 : 1)+ .overlay {+ if isLoading {+ ProgressView().controlSize(.small).tint(foreground)+ }+ }+ }+ .buttonStyle(+ AstryxButtonStyle(+ astryx: astryx,+ size: size,+ fillsWidth: fillsWidth,+ foreground: foreground,+ background: background+ )+ )+ // As core's Button: a loading button stays undimmed and focusable, keeps+ // its label, and says Loading; taps do nothing until it finishes.+ .disabled(isDisabled)+ .accessibilityLabel(Text(accessibilityText))+ .accessibilityAddTraits(Self.accessibilityTraits)+ .accessibilityValue(Text(loadingValue ?? ""))+ .onChange(of: isLoading) { _, loading in+ if loading { AccessibilityNotification.Announcement(AstryxStrings.buttonLoading).post() }+ }+ }++ /// The button's accessible name: its label, also while loading.+ var accessibilityText: String { label }++ /// The traits assistive technology gets: a button.+ static var accessibilityTraits: AccessibilityTraits { .isButton }++ /// What assistive technology reads after the label while loading: core's+ /// catalog message, in the person's language.+ var loadingValue: String? { isLoading ? AstryxStrings.buttonLoading : nil }++ /// Runs the action unless the button is loading.+ func activate() {+ guard !isLoading else { return }+ action()+ }++ private var foreground: Color {+ switch variant {+ case .primary: astryx.color("color-on-accent")+ case .destructive: astryx.color("color-on-error")+ case .secondary, .ghost: astryx.color("color-text-primary")+ }+ }++ private var background: Color {+ switch variant {+ case .primary: astryx.color("color-accent")+ case .destructive: astryx.color("color-error")+ case .secondary: astryx.color("color-neutral")+ case .ghost: .clear+ }+ }+}++struct AstryxButtonStyle: ButtonStyle {+ let astryx: AstryxStyle+ let size: AstryxButtonSize+ let fillsWidth: Bool+ let foreground: Color+ let background: Color+ @Environment(\.isEnabled) private var isEnabled++ func makeBody(configuration: Configuration) -> some View {+ let shape = RoundedRectangle(+ cornerRadius: astryx.size("radius-element", 8),+ style: .continuous+ )+ // Grows with text size, but not so far that one line of a large label+ // becomes a tall slab.+ let height = astryx.size(size.heightToken, size.fallbackHeight) * min(astryx.textScale, 1.4)+ configuration.label+ .font(astryx.font(size: "text-label-size", 14, weight: "text-label-weight"))+ .foregroundStyle(foreground)+ .padding(.horizontal, astryx.space(3))+ .frame(maxWidth: fillsWidth ? .infinity : nil, minHeight: height)+ .background(shape.fill(background))+ .opacity(isEnabled ? (configuration.isPressed ? 0.75 : 1) : 0.5)+ // Drawn at the token size; laid out at least 44 by 44 so the whole+ // platform-minimum tap area counts.+ .frame(minWidth: 44, minHeight: 44)+ .contentShape(Rectangle())+ }+}diff --git a/packages/native/apple/Sources/Astryx/Card/AstryxCard.swift b/packages/native/apple/Sources/Astryx/Card/AstryxCard.swiftnew file mode 100644index 0000000000..1fd20f8f69--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Card/AstryxCard.swift@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI++/// A card: one independent item on the theme's card ground, with a hairline+/// border and the container radius.+public struct AstryxCard<Content: View>: View {+ let padding: Int+ let content: Content+ @Environment(\.astryx) private var astryx++ /// - Parameter padding: a step on the spacing ladder, as core's `padding`.+ public init(padding: Int = 4, @ViewBuilder content: () -> Content) {+ self.padding = padding+ self.content = content()+ }++ public var body: some View {+ let shape = RoundedRectangle(+ cornerRadius: astryx.size("radius-container", 12),+ style: .continuous+ )+ // Several child views stack in one card, top to bottom with no gap of+ // their own, as children flow inside core's Card.+ VStack(alignment: .leading, spacing: 0) { content }+ .padding(astryx.space(padding))+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(shape.fill(astryx.color("color-background-card")))+ .overlay(+ shape.strokeBorder(astryx.color("color-border"), lineWidth: astryx.size("border-width", 1))+ )+ }+}diff --git a/packages/native/apple/Sources/Astryx/Heading/AstryxHeading.swift b/packages/native/apple/Sources/Astryx/Heading/AstryxHeading.swiftnew file mode 100644index 0000000000..51aed9c17a--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Heading/AstryxHeading.swift@@ -0,0 +1,46 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// Adapted from github.com/ejc3/astryx-swift (MIT).++import SwiftUI++/// A heading at levels 1 through 6, painted with the theme's heading tokens+/// and exposed to VoiceOver as a heading.+public struct AstryxHeading: View {+ let content: String+ let level: Int+ @Environment(\.astryx) private var astryx++ public init(_ content: String, level: Int = 2) {+ self.content = content+ self.level = min(max(level, 1), 6)+ }++ public var body: some View {+ Text(content)+ .font(+ astryx.font(+ size: "text-heading-\(level)-size",+ 20,+ weight: "text-heading-\(level)-weight",+ family: "font-family-heading"+ )+ )+ .foregroundStyle(astryx.color("color-text-primary"))+ .accessibilityAddTraits(Self.accessibilityTraits)+ .accessibilityHeading(headingLevel)+ }++ /// The traits assistive technology gets: a header.+ static var accessibilityTraits: AccessibilityTraits { .isHeader }++ var headingLevel: AccessibilityHeadingLevel {+ switch level {+ case 1: .h1+ case 2: .h2+ case 3: .h3+ case 4: .h4+ case 5: .h5+ default: .h6+ }+ }+}diff --git a/packages/native/apple/Sources/Astryx/Localization/AstryxStrings.swift b/packages/native/apple/Sources/Astryx/Localization/AstryxStrings.swiftnew file mode 100644index 0000000000..b1d0f4a2b8--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Localization/AstryxStrings.swift@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import Foundation++/// Core's catalog messages, read from `Resources/<locale>.lproj`, which+/// `generate:swift-ios` writes from core's locale catalogs.+enum AstryxStrings {+ /// What a loading button says to assistive technology.+ static var buttonLoading: String { localized("@astryx.button.loading", "Loading") }++ static func localized(_ key: String, _ english: String) -> String {+ resourceBundle.localizedString(forKey: key, value: english, table: nil)+ }++ static var resourceBundle: Bundle {+ #if SWIFT_PACKAGE+ Bundle.module+ #else+ Bundle.main+ #endif+ }+}diff --git a/packages/native/apple/Sources/Astryx/Resources/af.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/af.lproj/Localizable.stringsnew file mode 100644index 0000000000..813e6c77a5--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/af.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Laai tans";diff --git a/packages/native/apple/Sources/Astryx/Resources/ar.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/ar.lproj/Localizable.stringsnew file mode 100644index 0000000000..dccd508e2c--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/ar.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "جارٍ التحميل";diff --git a/packages/native/apple/Sources/Astryx/Resources/ca.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/ca.lproj/Localizable.stringsnew file mode 100644index 0000000000..89e09b3a6b--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/ca.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "S’està carregant";diff --git a/packages/native/apple/Sources/Astryx/Resources/cs.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/cs.lproj/Localizable.stringsnew file mode 100644index 0000000000..3a7d781bb8--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/cs.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Načítání";diff --git a/packages/native/apple/Sources/Astryx/Resources/da.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/da.lproj/Localizable.stringsnew file mode 100644index 0000000000..8ce2a0ea1f--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/da.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Indlæser";diff --git a/packages/native/apple/Sources/Astryx/Resources/de.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/de.lproj/Localizable.stringsnew file mode 100644index 0000000000..ff1bccd25f--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/de.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Wird geladen";diff --git a/packages/native/apple/Sources/Astryx/Resources/el.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/el.lproj/Localizable.stringsnew file mode 100644index 0000000000..0d47b6e858--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/el.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Φόρτωση";diff --git a/packages/native/apple/Sources/Astryx/Resources/en.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/en.lproj/Localizable.stringsnew file mode 100644index 0000000000..83b5dd9cd1--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/en.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Loading";diff --git a/packages/native/apple/Sources/Astryx/Resources/es.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/es.lproj/Localizable.stringsnew file mode 100644index 0000000000..8f34166c49--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/es.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Cargando";diff --git a/packages/native/apple/Sources/Astryx/Resources/fi.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/fi.lproj/Localizable.stringsnew file mode 100644index 0000000000..8c9ba77f88--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/fi.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Ladataan";diff --git a/packages/native/apple/Sources/Astryx/Resources/fr.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/fr.lproj/Localizable.stringsnew file mode 100644index 0000000000..dc0a07a622--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/fr.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Chargement";diff --git a/packages/native/apple/Sources/Astryx/Resources/he.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/he.lproj/Localizable.stringsnew file mode 100644index 0000000000..de3dfc3c00--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/he.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "טוען";diff --git a/packages/native/apple/Sources/Astryx/Resources/hu.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/hu.lproj/Localizable.stringsnew file mode 100644index 0000000000..9787ef4fc0--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/hu.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Betöltés";diff --git a/packages/native/apple/Sources/Astryx/Resources/it.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/it.lproj/Localizable.stringsnew file mode 100644index 0000000000..51e91e6968--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/it.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Caricamento";diff --git a/packages/native/apple/Sources/Astryx/Resources/ja.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/ja.lproj/Localizable.stringsnew file mode 100644index 0000000000..01611ef320--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/ja.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "読み込み中";diff --git a/packages/native/apple/Sources/Astryx/Resources/ko.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/ko.lproj/Localizable.stringsnew file mode 100644index 0000000000..9d3a31835a--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/ko.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "로드 중";diff --git a/packages/native/apple/Sources/Astryx/Resources/nb.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/nb.lproj/Localizable.stringsnew file mode 100644index 0000000000..9655829761--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/nb.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Laster";diff --git a/packages/native/apple/Sources/Astryx/Resources/nl.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/nl.lproj/Localizable.stringsnew file mode 100644index 0000000000..830ff8dd73--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/nl.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Laden";diff --git a/packages/native/apple/Sources/Astryx/Resources/pl.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/pl.lproj/Localizable.stringsnew file mode 100644index 0000000000..98cf571041--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/pl.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Ładowanie";diff --git a/packages/native/apple/Sources/Astryx/Resources/pt-BR.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/pt-BR.lproj/Localizable.stringsnew file mode 100644index 0000000000..7cbe853351--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/pt-BR.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Carregando";diff --git a/packages/native/apple/Sources/Astryx/Resources/pt-PT.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/pt-PT.lproj/Localizable.stringsnew file mode 100644index 0000000000..e1bb5f1e79--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/pt-PT.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "A carregar";diff --git a/packages/native/apple/Sources/Astryx/Resources/ro.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/ro.lproj/Localizable.stringsnew file mode 100644index 0000000000..65a69535e7--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/ro.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Se încarcă";diff --git a/packages/native/apple/Sources/Astryx/Resources/ru.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/ru.lproj/Localizable.stringsnew file mode 100644index 0000000000..b16c9adf22--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/ru.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Загрузка";diff --git a/packages/native/apple/Sources/Astryx/Resources/sr.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/sr.lproj/Localizable.stringsnew file mode 100644index 0000000000..27c4980a0f--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/sr.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Учитавање";diff --git a/packages/native/apple/Sources/Astryx/Resources/sv.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/sv.lproj/Localizable.stringsnew file mode 100644index 0000000000..254b3f4ed9--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/sv.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Läser in";diff --git a/packages/native/apple/Sources/Astryx/Resources/tr.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/tr.lproj/Localizable.stringsnew file mode 100644index 0000000000..709bb146a5--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/tr.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Yükleniyor";diff --git a/packages/native/apple/Sources/Astryx/Resources/uk.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/uk.lproj/Localizable.stringsnew file mode 100644index 0000000000..d72686e261--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/uk.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Завантаження";diff --git a/packages/native/apple/Sources/Astryx/Resources/vi.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/vi.lproj/Localizable.stringsnew file mode 100644index 0000000000..eeddfd2a3f--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/vi.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "Đang tải";diff --git a/packages/native/apple/Sources/Astryx/Resources/zh-Hans.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/zh-Hans.lproj/Localizable.stringsnew file mode 100644index 0000000000..c1fe6f2305--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/zh-Hans.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "加载中";diff --git a/packages/native/apple/Sources/Astryx/Resources/zh-Hant.lproj/Localizable.strings b/packages/native/apple/Sources/Astryx/Resources/zh-Hant.lproj/Localizable.stringsnew file mode 100644index 0000000000..46768a323c--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Resources/zh-Hant.lproj/Localizable.strings@@ -0,0 +1,4 @@+/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */++/* Screen-reader-only live-region announcement while a Button is in its loading state (spinner shown, action in flight). Progressive sense ("work in progress"), not a noun. Kept separate from `typeahead.loading` — translations may diverge. */+"@astryx.button.loading" = "載入中";diff --git a/packages/native/apple/Sources/Astryx/Text/AstryxText.swift b/packages/native/apple/Sources/Astryx/Text/AstryxText.swiftnew file mode 100644index 0000000000..14da07455f--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Text/AstryxText.swift@@ -0,0 +1,83 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// Adapted from github.com/ejc3/astryx-swift (MIT).++import SwiftUI++/// Core's `Text` semantic types this package draws so far.+public enum AstryxTextType: String, CaseIterable, Sendable {+ case body+ case large+ case label+ case supporting++ var token: String { "text-\(rawValue)" }++ /// The color core's Text uses when none is given: secondary for supporting+ /// text, primary otherwise.+ var defaultColor: AstryxTextColor { self == .supporting ? .secondary : .primary }+}++/// Core's `Text` colors this package draws so far.+public enum AstryxTextColor: String, CaseIterable, Sendable {+ case primary+ case secondary+ case disabled+ case accent++ var token: String { "color-text-\(rawValue)" }+}++/// Core's `Text` weights.+public enum AstryxTextWeight: String, CaseIterable, Sendable {+ case normal+ case medium+ case semibold+ case bold++ var token: String { "font-weight-\(rawValue)" }+}++/// Core's `Text` sizes this package draws so far, used to override the size+/// a semantic type sets. Core spells the extra-small size `xsm`; its token is+/// `font-size-xs`.+public enum AstryxTextSize: String, CaseIterable, Sendable {+ case xsm+ case sm+ case base+ case lg+ case xl++ var token: String { self == .xsm ? "font-size-xs" : "font-size-\(rawValue)" }+}++/// A run of text in a semantic type, painted with the theme's type tokens.+public struct AstryxText: View {+ let content: String+ let type: AstryxTextType+ let color: AstryxTextColor?+ let size: AstryxTextSize?+ let weight: AstryxTextWeight?+ @Environment(\.astryx) private var astryx++ public init(+ _ content: String,+ type: AstryxTextType = .body,+ color: AstryxTextColor? = nil,+ size: AstryxTextSize? = nil,+ weight: AstryxTextWeight? = nil+ ) {+ self.content = content+ self.type = type+ self.color = color+ self.size = size+ self.weight = weight+ }++ public var body: some View {+ let sizeToken = size?.token ?? "\(type.token)-size"+ let weightToken = weight?.token ?? "\(type.token)-weight"+ Text(content)+ .font(astryx.font(size: sizeToken, 14, weight: weightToken))+ .foregroundStyle(astryx.color((color ?? type.defaultColor).token))+ }+}diff --git a/packages/native/apple/Sources/Astryx/TextInput/AstryxTextInput.swift b/packages/native/apple/Sources/Astryx/TextInput/AstryxTextInput.swiftnew file mode 100644index 0000000000..67e8bb9d2c--- /dev/null+++ b/packages/native/apple/Sources/Astryx/TextInput/AstryxTextInput.swift@@ -0,0 +1,81 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// Adapted from github.com/ejc3/astryx-swift (MIT).++import SwiftUI++/// Core's `TextInput` types.+public enum AstryxTextInputType: String, CaseIterable, Sendable {+ case text+ case email+ case password+}++/// A labeled one-line text field, painted with the theme's tokens. The label+/// stays visible above the field and is the field's accessibility label.+public struct AstryxTextInput: View {+ let label: String+ @Binding var value: String+ let type: AstryxTextInputType+ let size: AstryxButtonSize+ let placeholder: String?+ let isDisabled: Bool+ @Environment(\.astryx) private var astryx++ public init(+ label: String,+ value: Binding<String>,+ type: AstryxTextInputType = .text,+ size: AstryxButtonSize = .md,+ placeholder: String? = nil,+ isDisabled: Bool = false+ ) {+ self.label = label+ self._value = value+ self.type = type+ self.size = size+ self.placeholder = placeholder+ self.isDisabled = isDisabled+ }++ public var body: some View {+ VStack(alignment: .leading, spacing: astryx.space(1)) {+ AstryxText(label, type: .label, color: .secondary)+ .accessibilityHidden(true)+ field+ .font(astryx.font(size: "text-body-size", 14, weight: "text-body-weight"))+ .foregroundStyle(astryx.color("color-text-primary"))+ .padding(.horizontal, astryx.space(3))+ .frame(minHeight: max(44, astryx.size(size.heightToken, size.fallbackHeight) * astryx.textScale))+ .background(+ RoundedRectangle(cornerRadius: astryx.size("radius-element", 8), style: .continuous)+ .strokeBorder(astryx.color("color-border-emphasized"), lineWidth: astryx.size("border-width", 1))+ )+ .disabled(isDisabled)+ .opacity(isDisabled ? 0.5 : 1)+ .accessibilityLabel(Text(accessibilityText))+ }+ }++ /// The field's accessible name: its visible label, which VoiceOver reads+ /// on the field itself rather than as separate text.+ var accessibilityText: String { label }++ @ViewBuilder private var field: some View {+ let prompt = placeholder.map { Text($0).foregroundStyle(astryx.color("color-text-secondary")) }+ switch type {+ case .password:+ SecureField("", text: $value, prompt: prompt)+ .textContentType(.password)+ case .email:+ TextField("", text: $value, prompt: prompt)+ .textContentType(.emailAddress)+ .autocorrectionDisabled()+ #if os(iOS)+ .keyboardType(.emailAddress)+ .textInputAutocapitalization(.never)+ #endif+ case .text:+ TextField("", text: $value, prompt: prompt)+ }+ }+}diff --git a/packages/native/apple/Sources/Astryx/Theme/AstryxIcons.swift b/packages/native/apple/Sources/Astryx/Theme/AstryxIcons.swiftnew file mode 100644index 0000000000..b2ab68c75a--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Theme/AstryxIcons.swift@@ -0,0 +1,37 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/// The SF Symbol each of Astryx's built-in icon names draws by default on+/// Apple platforms (AST-082 FR17). A test keeps this map equal to+/// `NATIVE_ICON_DEFAULTS` in `@astryxdesign/native`; a theme replaces any+/// entry through `AstryxTheme(icons:)`.+let astryxDefaultIcons: [String: String] = [+ "close": "xmark",+ "chevronDown": "chevron.down",+ "chevronLeft": "chevron.left",+ "chevronRight": "chevron.right",+ "chevronsLeft": "chevron.left.2",+ "chevronsRight": "chevron.right.2",+ "check": "checkmark",+ "success": "checkmark.circle.fill",+ "error": "exclamationmark.circle.fill",+ "warning": "exclamationmark.triangle.fill",+ "info": "info.circle.fill",+ "calendar": "calendar",+ "clock": "clock",+ "externalLink": "arrow.up.right.square",+ "menu": "line.3.horizontal",+ "moreHorizontal": "ellipsis",+ "search": "magnifyingglass",+ "upload": "square.and.arrow.up",+ "arrowUp": "arrow.up",+ "arrowDown": "arrow.down",+ "arrowsUpDown": "arrow.up.arrow.down",+ "funnel": "line.3.horizontal.decrease",+ "eyeSlash": "eye.slash",+ "viewColumns": "rectangle.split.3x1",+ "copy": "doc.on.doc",+ "checkDouble": "checkmark.message",+ "wrench": "wrench.adjustable",+ "stop": "stop.fill",+ "microphone": "mic",+]diff --git a/packages/native/apple/Sources/Astryx/Theme/AstryxTheme.swift b/packages/native/apple/Sources/Astryx/Theme/AstryxTheme.swiftnew file mode 100644index 0000000000..69120b2acc--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Theme/AstryxTheme.swift@@ -0,0 +1,226 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// Adapted from github.com/ejc3/astryx-swift (MIT).++import SwiftUI++#if canImport(UIKit)+import UIKit+#elseif canImport(AppKit)+import AppKit+#endif++/// One mode of a theme, resolved: colors as `#RRGGBBAA`, sizes in points, and+/// font families as their CSS stacks, first choice first, keyed by core's+/// token names without the leading `--`.+public struct AstryxTokens: Equatable, Sendable {+ public var colors: [String: String]+ public var sizes: [String: Double]+ public var fonts: [String: [String]]++ public init(colors: [String: String], sizes: [String: Double], fonts: [String: [String]] = [:]) {+ self.colors = colors+ self.sizes = sizes+ self.fonts = fonts+ }+}++/// A theme's light and dark tokens. `AstryxTheme.default` is core's default+/// theme, generated from core's own resolver.+public struct AstryxTheme: Equatable, Sendable {+ public var light: AstryxTokens+ public var dark: AstryxTokens+ /// SF Symbols that replace the defaults for shared icon names, such as+ /// `["success": "checkmark.seal.fill"]` (AST-082 FR17).+ public var icons: [String: String]++ public init(light: AstryxTokens, dark: AstryxTokens, icons: [String: String] = [:]) {+ self.light = light+ self.dark = dark+ self.icons = icons+ }++ public static let `default` = AstryxTheme(+ light: .defaultLight,+ dark: .defaultDark+ )+}++/// The tokens a component paints with: one mode of the theme, grown by the+/// person's Dynamic Type setting. Components read every color, size, and font+/// from here, never from a constant of their own.+public struct AstryxStyle: Sendable {+ public let tokens: AstryxTokens+ /// How much Dynamic Type grows text at the person's setting (1 at Large).+ public let textScale: CGFloat+ /// The theme's replacements for shared icon names.+ public let icons: [String: String]++ public init(tokens: AstryxTokens, textScale: CGFloat = 1, icons: [String: String] = [:]) {+ self.tokens = tokens+ self.textScale = textScale+ self.icons = icons+ }++ /// A token color. A token the theme does not define draws clear, so a+ /// missing token shows up in review instead of a guessed color.+ public func color(_ token: String) -> Color {+ guard let hex = tokens.colors[token] else { return .clear }+ return Color(astryxHex: hex)+ }++ /// A token size in points, or `fallback` when the theme does not define it.+ public func size(_ token: String, _ fallback: CGFloat) -> CGFloat {+ tokens.sizes[token].map { CGFloat($0) } ?? fallback+ }++ /// A step on the spacing ladder: `space(4)` reads `spacing-4`.+ public func space(_ step: Int) -> CGFloat {+ size("spacing-\(step)", CGFloat(step) * 4)+ }++ /// A token font size grown by Dynamic Type.+ public func fontSize(_ token: String, _ fallback: CGFloat) -> CGFloat {+ size(token, fallback) * textScale+ }++ /// The theme's font family at a token size and a token weight. The first+ /// family in the stack that the device has wins; a system family, such as+ /// `-apple-system` or `sans-serif`, is the system font.+ public func font(+ size token: String,+ _ fallback: CGFloat,+ weight: String,+ family: String = "font-family-body"+ ) -> Font {+ astryxFont(+ families: tokens.fonts[family] ?? [],+ size: fontSize(token, fallback),+ weight: fontWeight(size(weight, 400))+ )+ }++ /// The SF Symbol for a shared icon name (AST-082 FR17): the theme's+ /// replacement, else the default. An unknown name stops a development+ /// build with a message that names it, and draws nothing in a release build.+ public func icon(_ name: String) -> String? {+ if let symbol = icons[name] ?? astryxDefaultIcons[name] { return symbol }+ assertionFailure("Astryx has no icon named \"\(name)\"")+ return nil+ }++ func fontWeight(_ value: CGFloat) -> Font.Weight {+ switch value {+ case ..<350: .light+ case 350..<450: .regular+ case 450..<550: .medium+ case 550..<650: .semibold+ case 650..<750: .bold+ default: .heavy+ }+ }+}++extension Color {+ /// A color from `#RRGGBBAA`, the form the generated tokens use. `#RRGGBB`+ /// and `#RGB` also read; anything else is clear.+ public init(astryxHex hex: String) {+ var digits = hex.hasPrefix("#") ? String(hex.dropFirst()) : hex+ if digits.count == 3 { digits = digits.map { "\($0)\($0)" }.joined() }+ if digits.count == 6 { digits += "FF" }+ guard digits.count == 8, let value = UInt32(digits, radix: 16) else {+ self = .clear+ return+ }+ self.init(+ .sRGB,+ red: Double((value >> 24) & 0xFF) / 255,+ green: Double((value >> 16) & 0xFF) / 255,+ blue: Double((value >> 8) & 0xFF) / 255,+ opacity: Double(value & 0xFF) / 255+ )+ }+}++/// A font from a CSS family stack: the first system family or installed font.+func astryxFont(families: [String], size: CGFloat, weight: Font.Weight) -> Font {+ for family in families {+ switch family.lowercased() {+ case "-apple-system", "blinkmacsystemfont", "system-ui", "ui-sans-serif", "sans-serif":+ return .system(size: size, weight: weight)+ case "ui-monospace", "monospace":+ return .system(size: size, weight: weight, design: .monospaced)+ case "ui-serif", "serif":+ return .system(size: size, weight: weight, design: .serif)+ case "ui-rounded":+ return .system(size: size, weight: weight, design: .rounded)+ default:+ if astryxFontIsInstalled(family) {+ // Fixed size: the size already carries the Dynamic Type scale.+ return .custom(family, fixedSize: size).weight(weight)+ }+ }+ }+ return .system(size: size, weight: weight)+}++func astryxFontIsInstalled(_ name: String) -> Bool {+ #if canImport(UIKit)+ UIFont(name: name, size: 12) != nil+ #elseif canImport(AppKit)+ NSFont(name: name, size: 12) != nil+ #else+ false+ #endif+}++/// Dynamic Type's growth for body-sized text, as Apple's Body style grows+/// (17 pt at Large).+func astryxTextScale(for size: DynamicTypeSize) -> CGFloat {+ switch size {+ case .xSmall: 0.82+ case .small: 0.88+ case .medium: 0.94+ case .large: 1+ case .xLarge: 1.12+ case .xxLarge: 1.23+ case .xxxLarge: 1.35+ case .accessibility1: 1.6+ case .accessibility2: 1.9+ case .accessibility3: 2.35+ case .accessibility4: 2.75+ case .accessibility5: 3.1+ @unknown default: 1+ }+}++private struct AstryxThemeKey: EnvironmentKey {+ static let defaultValue = AstryxTheme.default+}++extension EnvironmentValues {+ /// The theme `astryxTheme(_:)` sets; core's default theme without it.+ public var astryxTheme: AstryxTheme {+ get { self[AstryxThemeKey.self] }+ set { self[AstryxThemeKey.self] = newValue }+ }++ /// The style components paint with: the theme's tokens for the current+ /// color scheme, grown by the person's text size. It follows Dark Mode and+ /// Dynamic Type with or without `astryxTheme(_:)`.+ public var astryx: AstryxStyle {+ let theme = astryxTheme+ return AstryxStyle(+ tokens: colorScheme == .dark ? theme.dark : theme.light,+ textScale: astryxTextScale(for: dynamicTypeSize),+ icons: theme.icons+ )+ }+}++extension View {+ /// Paints this subtree with a theme. Components follow the color scheme and+ /// the person's text size either way.+ public func astryxTheme(_ theme: AstryxTheme = .default) -> some View {+ environment(\.astryxTheme, theme)+ }+}diff --git a/packages/native/apple/Sources/Astryx/Theme/Generated/DefaultTheme.swift b/packages/native/apple/Sources/Astryx/Theme/Generated/DefaultTheme.swiftnew file mode 100644index 0000000000..37c7af3bfc--- /dev/null+++ b/packages/native/apple/Sources/Astryx/Theme/Generated/DefaultTheme.swift@@ -0,0 +1,482 @@+// Generated by @astryxdesign/native from core's theme resolver. Do not edit.+// Run `pnpm -F @astryxdesign/native generate:swift-ios` after a core token change.++extension AstryxTokens {+ /// Core's default theme, light mode.+ public static let defaultLight = AstryxTokens(+ colors: [+ "color-accent": "#0064E0FF",+ "color-accent-muted": "#0082FB33",+ "color-background-blue": "#0171E333",+ "color-background-body": "#F1F4F7FF",+ "color-background-card": "#FFFFFFFF",+ "color-background-cyan": "#03A7D733",+ "color-background-error-inverted": "#AA071EFF",+ "color-background-gray": "#0A131733",+ "color-background-green": "#24BB5E33",+ "color-background-inverted": "#0A1317FF",+ "color-background-muted": "#0536590C",+ "color-background-orange": "#F2790233",+ "color-background-pink": "#E638B333",+ "color-background-popover": "#FFFFFFFF",+ "color-background-purple": "#7952FF33",+ "color-background-red": "#E3193B33",+ "color-background-surface": "#FFFFFFFF",+ "color-background-teal": "#0DB7AF33",+ "color-background-yellow": "#E2A40033",+ "color-border": "#05365919",+ "color-border-blue": "#0064E0FF",+ "color-border-cyan": "#089DD0FF",+ "color-border-emphasized": "#CCD3DBFF",+ "color-border-gray": "#647685FF",+ "color-border-green": "#0D8626FF",+ "color-border-orange": "#EB6E00FF",+ "color-border-pink": "#F351C0FF",+ "color-border-purple": "#9081FFFF",+ "color-border-red": "#E3193BFF",+ "color-border-teal": "#08A3A3FF",+ "color-border-yellow": "#C58600FF",+ "color-data-blue-1": "#DBECFFFF",+ "color-data-blue-2": "#78BEFFFF",+ "color-data-blue-3": "#2694FEFF",+ "color-data-blue-4": "#004CBCFF",+ "color-data-blue-5": "#02165EFF",+ "color-data-categorical-blue": "#0171E3FF",+ "color-data-categorical-brown": "#965E03FF",+ "color-data-categorical-cyan": "#0171A4FF",+ "color-data-categorical-green": "#0B991FFF",+ "color-data-categorical-indigo": "#6F8AFFFF",+ "color-data-categorical-orange": "#EB6E00FF",+ "color-data-categorical-pink": "#F351C0FF",+ "color-data-categorical-purple": "#6B1EFDFF",+ "color-data-categorical-red": "#F5394FFF",+ "color-data-categorical-teal": "#08A3A3FF",+ "color-data-gray-1": "#F1F4F7FF",+ "color-data-gray-2": "#CCD3DBFF",+ "color-data-gray-3": "#AFB9C4FF",+ "color-data-gray-4": "#5D6C7BFF",+ "color-data-gray-5": "#25363FFF",+ "color-data-neutral": "#8494A3FF",+ "color-data-orange-1": "#FFE6CFFF",+ "color-data-orange-2": "#FDB876FF",+ "color-data-orange-3": "#FD9537FF",+ "color-data-orange-4": "#D66100FF",+ "color-data-orange-5": "#A13F04FF",+ "color-data-pink-1": "#FCE3F4FF",+ "color-data-pink-2": "#FEADE3FF",+ "color-data-pink-3": "#F989D3FF",+ "color-data-pink-4": "#D123A1FF",+ "color-data-pink-5": "#8E1073FF",+ "color-data-purple-1": "#E8E8FBFF",+ "color-data-purple-2": "#B3B0FEFF",+ "color-data-purple-3": "#9081FFFF",+ "color-data-purple-4": "#6B1EFDFF",+ "color-data-purple-5": "#3E0697FF",+ "color-data-red-1": "#FEE4E6FF",+ "color-data-red-2": "#FFB2B8FF",+ "color-data-red-3": "#FB7D87FF",+ "color-data-red-4": "#D31130FF",+ "color-data-red-5": "#9D0519FF",+ "color-data-shamrock-1": "#D6FEE4FF",+ "color-data-shamrock-2": "#8EF7AAFF",+ "color-data-shamrock-3": "#24BB5EFF",+ "color-data-shamrock-4": "#138546FF",+ "color-data-shamrock-5": "#0B603DFF",+ "color-data-teal-1": "#D7FCF8FF",+ "color-data-teal-2": "#6CE6D8FF",+ "color-data-teal-3": "#0DB7AFFF",+ "color-data-teal-4": "#0C9293FF",+ "color-data-teal-5": "#08767DFF",+ "color-data-yellow-1": "#FDF6BAFF",+ "color-data-yellow-2": "#FCEC85FF",+ "color-data-yellow-3": "#FBCE03FF",+ "color-data-yellow-4": "#D69804FF",+ "color-data-yellow-5": "#8A5001FF",+ "color-error": "#E3193BFF",+ "color-error-muted": "#E3193B33",+ "color-icon-accent": "#0064E0FF",+ "color-icon-blue": "#0064E0FF",+ "color-icon-cyan": "#00ACC1FF",+ "color-icon-disabled": "#A4B0BCFF",+ "color-icon-gray": "#4E606FFF",+ "color-icon-green": "#0D8626FF",+ "color-icon-orange": "#E9690BFF",+ "color-icon-pink": "#C2185BFF",+ "color-icon-primary": "#0A1317FF",+ "color-icon-purple": "#5B08D8FF",+ "color-icon-red": "#D31130FF",+ "color-icon-secondary": "#4E606FFF",+ "color-icon-teal": "#009688FF",+ "color-icon-yellow": "#FBC02DFF",+ "color-neutral": "#0536591A",+ "color-on-accent": "#FFFFFFFF",+ "color-on-dark": "#FFFFFFFF",+ "color-on-error": "#FFFFFFFF",+ "color-on-light": "#000000FF",+ "color-on-success": "#FFFFFFFF",+ "color-on-warning": "#0A1317FF",+ "color-overlay": "#01122866",+ "color-overlay-hover": "#0536590C",+ "color-overlay-pressed": "#05365919",+ "color-shadow": "#0536591A",+ "color-skeleton": "#CCD3DBFF",+ "color-success": "#0D8626FF",+ "color-success-muted": "#0B991F33",+ "color-syntax-added": "#0B991F0D",+ "color-syntax-added-marker": "#09441FFF",+ "color-syntax-attribute": "#083943FF",+ "color-syntax-background": "#0536590C",+ "color-syntax-comment": "#4E606FFF",+ "color-syntax-constant": "#6B2203FF",+ "color-syntax-diff-header": "#0536590C",+ "color-syntax-function": "#042F97FF",+ "color-syntax-keyword": "#0064E0FF",+ "color-syntax-number": "#6B2203FF",+ "color-syntax-operator": "#014975FF",+ "color-syntax-property": "#014975FF",+ "color-syntax-punctuation": "#4E606FFF",+ "color-syntax-removed": "#E3193B0D",+ "color-syntax-removed-marker": "#7B0210FF",+ "color-syntax-string": "#09441FFF",+ "color-syntax-tag": "#7B0210FF",+ "color-syntax-type": "#3E0697FF",+ "color-syntax-variable": "#0A1317FF",+ "color-text-accent": "#0064E0FF",+ "color-text-blue": "#042F97FF",+ "color-text-cyan": "#014975FF",+ "color-text-disabled": "#A4B0BCFF",+ "color-text-gray": "#0A1317FF",+ "color-text-green": "#09441FFF",+ "color-text-orange": "#6B2203FF",+ "color-text-pink": "#650053FF",+ "color-text-primary": "#0A1317FF",+ "color-text-purple": "#3E0697FF",+ "color-text-red": "#7B0210FF",+ "color-text-secondary": "#4E606FFF",+ "color-text-teal": "#083943FF",+ "color-text-yellow": "#753F07FF",+ "color-tint-hover": "#000000FF",+ "color-track": "#CCD3DBFF",+ "color-warning": "#E9AF08FF",+ "color-warning-muted": "#E2A40033",+ ],+ sizes: [+ "border-width": 1,+ "font-size-2xl": 24,+ "font-size-2xs": 8,+ "font-size-3xl": 29,+ "font-size-3xs": 7,+ "font-size-4xl": 35,+ "font-size-4xs": 6,+ "font-size-5xl": 42,+ "font-size-base": 14,+ "font-size-lg": 17,+ "font-size-sm": 12,+ "font-size-xl": 20,+ "font-size-xs": 10,+ "font-weight-bold": 700,+ "font-weight-medium": 500,+ "font-weight-normal": 400,+ "font-weight-semibold": 600,+ "radius-chat": 28,+ "radius-container": 12,+ "radius-element": 8,+ "radius-full": 9999,+ "radius-inner": 4,+ "radius-none": 0,+ "radius-page": 28,+ "size-element-lg": 36,+ "size-element-md": 32,+ "size-element-sm": 28,+ "spacing-0": 0,+ "spacing-0-5": 2,+ "spacing-1": 4,+ "spacing-1-5": 6,+ "spacing-10": 40,+ "spacing-11": 44,+ "spacing-12": 48,+ "spacing-2": 8,+ "spacing-3": 12,+ "spacing-4": 16,+ "spacing-5": 20,+ "spacing-6": 24,+ "spacing-7": 28,+ "spacing-8": 32,+ "spacing-9": 36,+ "text-body-leading": 1.4286,+ "text-body-size": 14,+ "text-body-weight": 400,+ "text-heading-1-leading": 1.3333,+ "text-heading-1-size": 24,+ "text-heading-1-weight": 600,+ "text-heading-2-leading": 1.4,+ "text-heading-2-size": 20,+ "text-heading-2-weight": 600,+ "text-heading-3-leading": 1.4118,+ "text-heading-3-size": 17,+ "text-heading-3-weight": 600,+ "text-heading-4-leading": 1.4286,+ "text-heading-4-size": 14,+ "text-heading-4-weight": 600,+ "text-heading-5-leading": 1.6667,+ "text-heading-5-size": 12,+ "text-heading-5-weight": 600,+ "text-heading-6-leading": 1.6,+ "text-heading-6-size": 10,+ "text-heading-6-weight": 600,+ "text-label-leading": 1.4286,+ "text-label-size": 14,+ "text-label-weight": 500,+ "text-large-leading": 1.4118,+ "text-large-size": 17,+ "text-large-weight": 600,+ "text-supporting-leading": 1.6667,+ "text-supporting-size": 12,+ "text-supporting-weight": 400,+ ],+ fonts: [+ "font-family-body": ["-apple-system", "BlinkMacSystemFont", "Segoe UI", "Roboto", "Helvetica", "Arial", "sans-serif"],+ "font-family-code": ["SF Mono", "Monaco", "Consolas", "monospace"],+ "font-family-heading": ["-apple-system", "BlinkMacSystemFont", "Segoe UI", "Roboto", "Helvetica", "Arial", "sans-serif"],+ ]+ )++ /// Core's default theme, dark mode.+ public static let defaultDark = AstryxTokens(+ colors: [+ "color-accent": "#2694FEFF",+ "color-accent-muted": "#0082FB3F",+ "color-background-blue": "#0171E333",+ "color-background-body": "#111112FF",+ "color-background-card": "#1F1F22FF",+ "color-background-cyan": "#03A7D733",+ "color-background-error-inverted": "#E3193BFF",+ "color-background-gray": "#666A724C",+ "color-background-green": "#24BB5E33",+ "color-background-inverted": "#FFFFFFFF",+ "color-background-muted": "#1111127F",+ "color-background-orange": "#F2790233",+ "color-background-pink": "#E638B333",+ "color-background-popover": "#28292CFF",+ "color-background-purple": "#7952FF33",+ "color-background-red": "#E3193B33",+ "color-background-surface": "#1F1F22FF",+ "color-background-teal": "#0DB7AF33",+ "color-background-yellow": "#E2A40033",+ "color-border": "#F2F4F619",+ "color-border-blue": "#2694FEFF",+ "color-border-cyan": "#0171A4FF",+ "color-border-emphasized": "#494D53FF",+ "color-border-gray": "#748695FF",+ "color-border-green": "#0B991FFF",+ "color-border-orange": "#B34A01FF",+ "color-border-pink": "#C02294FF",+ "color-border-purple": "#7340FEFF",+ "color-border-red": "#F5394FFF",+ "color-border-teal": "#08767DFF",+ "color-border-yellow": "#B47700FF",+ "color-data-blue-1": "#DBECFFFF",+ "color-data-blue-2": "#78BEFFFF",+ "color-data-blue-3": "#2694FEFF",+ "color-data-blue-4": "#004CBCFF",+ "color-data-blue-5": "#02165EFF",+ "color-data-categorical-blue": "#0171E3FF",+ "color-data-categorical-brown": "#965E03FF",+ "color-data-categorical-cyan": "#0171A4FF",+ "color-data-categorical-green": "#0B991FFF",+ "color-data-categorical-indigo": "#6F8AFFFF",+ "color-data-categorical-orange": "#EB6E00FF",+ "color-data-categorical-pink": "#F351C0FF",+ "color-data-categorical-purple": "#6B1EFDFF",+ "color-data-categorical-red": "#F5394FFF",+ "color-data-categorical-teal": "#08A3A3FF",+ "color-data-gray-1": "#F2F4F6FF",+ "color-data-gray-2": "#D0D3D6FF",+ "color-data-gray-3": "#B2B8BEFF",+ "color-data-gray-4": "#666A72FF",+ "color-data-gray-5": "#333338FF",+ "color-data-neutral": "#8C939BFF",+ "color-data-orange-1": "#FFE6CFFF",+ "color-data-orange-2": "#FDB876FF",+ "color-data-orange-3": "#FD9537FF",+ "color-data-orange-4": "#D66100FF",+ "color-data-orange-5": "#A13F04FF",+ "color-data-pink-1": "#FCE3F4FF",+ "color-data-pink-2": "#FEADE3FF",+ "color-data-pink-3": "#F989D3FF",+ "color-data-pink-4": "#D123A1FF",+ "color-data-pink-5": "#8E1073FF",+ "color-data-purple-1": "#E8E8FBFF",+ "color-data-purple-2": "#B3B0FEFF",+ "color-data-purple-3": "#9081FFFF",+ "color-data-purple-4": "#6B1EFDFF",+ "color-data-purple-5": "#3E0697FF",+ "color-data-red-1": "#FEE4E6FF",+ "color-data-red-2": "#FFB2B8FF",+ "color-data-red-3": "#FB7D87FF",+ "color-data-red-4": "#D31130FF",+ "color-data-red-5": "#9D0519FF",+ "color-data-shamrock-1": "#D6FEE4FF",+ "color-data-shamrock-2": "#8EF7AAFF",+ "color-data-shamrock-3": "#24BB5EFF",+ "color-data-shamrock-4": "#138546FF",+ "color-data-shamrock-5": "#0B603DFF",+ "color-data-teal-1": "#D7FCF8FF",+ "color-data-teal-2": "#6CE6D8FF",+ "color-data-teal-3": "#0DB7AFFF",+ "color-data-teal-4": "#0C9293FF",+ "color-data-teal-5": "#08767DFF",+ "color-data-yellow-1": "#FDF6BAFF",+ "color-data-yellow-2": "#FCEC85FF",+ "color-data-yellow-3": "#FBCE03FF",+ "color-data-yellow-4": "#D69804FF",+ "color-data-yellow-5": "#8A5001FF",+ "color-error": "#F5394FFF",+ "color-error-muted": "#F5394F3F",+ "color-icon-accent": "#2694FEFF",+ "color-icon-blue": "#2694FEFF",+ "color-icon-cyan": "#26C6DAFF",+ "color-icon-disabled": "#6F747CFF",+ "color-icon-gray": "#AAAFB5FF",+ "color-icon-green": "#26A756FF",+ "color-icon-orange": "#FB8C00FF",+ "color-icon-pink": "#EC407AFF",+ "color-icon-primary": "#DFE2E5FF",+ "color-icon-purple": "#7952FFFF",+ "color-icon-red": "#E3193BFF",+ "color-icon-secondary": "#AAAFB5FF",+ "color-icon-teal": "#26A69AFF",+ "color-icon-yellow": "#FFEE58FF",+ "color-neutral": "#DFE2E533",+ "color-on-accent": "#FFFFFFFF",+ "color-on-dark": "#FFFFFFFF",+ "color-on-error": "#FFFFFFFF",+ "color-on-light": "#000000FF",+ "color-on-success": "#FFFFFFFF",+ "color-on-warning": "#0A1317FF",+ "color-overlay": "#11111299",+ "color-overlay-hover": "#FFFFFF0C",+ "color-overlay-pressed": "#FFFFFF19",+ "color-shadow": "#0000004D",+ "color-skeleton": "#5A5E66FF",+ "color-success": "#0D8626FF",+ "color-success-muted": "#0B991F3F",+ "color-syntax-added": "#0B991F10",+ "color-syntax-added-marker": "#A5F690FF",+ "color-syntax-attribute": "#40DCCDFF",+ "color-syntax-background": "#1111127F",+ "color-syntax-comment": "#AAAFB5FF",+ "color-syntax-constant": "#FDB876FF",+ "color-syntax-diff-header": "#1111127F",+ "color-syntax-function": "#AFD7FFFF",+ "color-syntax-keyword": "#3E9EFBFF",+ "color-syntax-number": "#FDB876FF",+ "color-syntax-operator": "#A1EEF9FF",+ "color-syntax-property": "#A1EEF9FF",+ "color-syntax-punctuation": "#AAAFB5FF",+ "color-syntax-removed": "#F5394F10",+ "color-syntax-removed-marker": "#FFB2B8FF",+ "color-syntax-string": "#A5F690FF",+ "color-syntax-tag": "#FFB2B8FF",+ "color-syntax-type": "#B3B0FEFF",+ "color-syntax-variable": "#DFE2E5FF",+ "color-text-accent": "#3E9EFBFF",+ "color-text-blue": "#AFD7FFFF",+ "color-text-cyan": "#A1EEF9FF",+ "color-text-disabled": "#6F747CFF",+ "color-text-gray": "#E7EAEDFF",+ "color-text-green": "#A5F690FF",+ "color-text-orange": "#FDB876FF",+ "color-text-pink": "#FEADE3FF",+ "color-text-primary": "#DFE2E5FF",+ "color-text-purple": "#B3B0FEFF",+ "color-text-red": "#FFB2B8FF",+ "color-text-secondary": "#AAAFB5FF",+ "color-text-teal": "#40DCCDFF",+ "color-text-yellow": "#FBCE03FF",+ "color-tint-hover": "#FFFFFFFF",+ "color-track": "#5A5E66FF",+ "color-warning": "#F2C00BFF",+ "color-warning-muted": "#E2A4003F",+ ],+ sizes: [+ "border-width": 1,+ "font-size-2xl": 24,+ "font-size-2xs": 8,+ "font-size-3xl": 29,+ "font-size-3xs": 7,+ "font-size-4xl": 35,+ "font-size-4xs": 6,+ "font-size-5xl": 42,+ "font-size-base": 14,+ "font-size-lg": 17,+ "font-size-sm": 12,+ "font-size-xl": 20,+ "font-size-xs": 10,+ "font-weight-bold": 700,+ "font-weight-medium": 500,+ "font-weight-normal": 400,+ "font-weight-semibold": 600,+ "radius-chat": 28,+ "radius-container": 12,+ "radius-element": 8,+ "radius-full": 9999,+ "radius-inner": 4,+ "radius-none": 0,+ "radius-page": 28,+ "size-element-lg": 36,+ "size-element-md": 32,+ "size-element-sm": 28,+ "spacing-0": 0,+ "spacing-0-5": 2,+ "spacing-1": 4,+ "spacing-1-5": 6,+ "spacing-10": 40,+ "spacing-11": 44,+ "spacing-12": 48,+ "spacing-2": 8,+ "spacing-3": 12,+ "spacing-4": 16,+ "spacing-5": 20,+ "spacing-6": 24,+ "spacing-7": 28,+ "spacing-8": 32,+ "spacing-9": 36,+ "text-body-leading": 1.4286,+ "text-body-size": 14,+ "text-body-weight": 400,+ "text-heading-1-leading": 1.3333,+ "text-heading-1-size": 24,+ "text-heading-1-weight": 600,+ "text-heading-2-leading": 1.4,+ "text-heading-2-size": 20,+ "text-heading-2-weight": 600,+ "text-heading-3-leading": 1.4118,+ "text-heading-3-size": 17,+ "text-heading-3-weight": 600,+ "text-heading-4-leading": 1.4286,+ "text-heading-4-size": 14,+ "text-heading-4-weight": 600,+ "text-heading-5-leading": 1.6667,+ "text-heading-5-size": 12,+ "text-heading-5-weight": 600,+ "text-heading-6-leading": 1.6,+ "text-heading-6-size": 10,+ "text-heading-6-weight": 600,+ "text-label-leading": 1.4286,+ "text-label-size": 14,+ "text-label-weight": 500,+ "text-large-leading": 1.4118,+ "text-large-size": 17,+ "text-large-weight": 600,+ "text-supporting-leading": 1.6667,+ "text-supporting-size": 12,+ "text-supporting-weight": 400,+ ],+ fonts: [+ "font-family-body": ["-apple-system", "BlinkMacSystemFont", "Segoe UI", "Roboto", "Helvetica", "Arial", "sans-serif"],+ "font-family-code": ["SF Mono", "Monaco", "Consolas", "monospace"],+ "font-family-heading": ["-apple-system", "BlinkMacSystemFont", "Segoe UI", "Roboto", "Helvetica", "Arial", "sans-serif"],+ ]+ )+}diff --git a/packages/native/apple/Templates/Login/LoginTemplate.swift b/packages/native/apple/Templates/Login/LoginTemplate.swiftnew file mode 100644index 0000000000..cb1fc206f9--- /dev/null+++ b/packages/native/apple/Templates/Login/LoginTemplate.swift@@ -0,0 +1,121 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import Astryx+import SwiftUI++/// The `login` template's state and rules, kept apart from the drawing so+/// they can be tested without a screen.+public struct LoginForm: Equatable, Sendable {+ public var email = ""+ public var password = ""+ public var error: String?+ public var isLoading = false++ public init() {}++ /// Checks the fields as the web template does: both are required. Returns+ /// true when sign-in may start.+ public mutating func submit() -> Bool {+ error = nil+ guard !email.isEmpty, !password.isEmpty else {+ error = "Please enter both email and password."+ return false+ }+ isLoading = true+ return true+ }+}++/// The `login` template: a centered credential form on the page ground, two+/// fields and a submit. It matches `astryx template login` in content and+/// states, and draws with SwiftUI's own layout.+public struct LoginTemplate: View {+ @State private var form = LoginForm()+ @Environment(\.astryx) private var astryx++ public init() {}++ public var body: some View {+ ScrollView {+ LoginTemplateContent(form: $form, signIn: signIn)+ }+ .background(astryx.color("color-background-body").ignoresSafeArea())+ }++ private func signIn() {+ guard form.submit() else { return }+ // The template has no backend: it shows the loading state, then returns.+ Task { @MainActor in+ try? await Task.sleep(for: .seconds(2))+ form.isLoading = false+ }+ }+}++/// The template's column, apart from its scroll view so it can be drawn to+/// an image (an image render draws a scroll view empty).+struct LoginTemplateContent: View {+ @Binding var form: LoginForm+ let signIn: () -> Void+ @Environment(\.astryx) private var astryx++ var body: some View {+ VStack(spacing: astryx.space(4)) {+ VStack(spacing: astryx.space(2)) {+ Image(systemName: "cube")+ .font(.system(size: astryx.fontSize("font-size-2xl", 24)))+ .foregroundStyle(astryx.color("color-icon-primary"))+ .accessibilityHidden(true)+ AstryxText("Product Inc.", size: .lg, weight: .bold)+ }++ AstryxCard(padding: 8) {+ VStack(alignment: .leading, spacing: astryx.space(4)) {+ VStack(spacing: astryx.space(1)) {+ AstryxHeading("Sign in", level: 2)+ AstryxText("Enter your credentials to continue", color: .secondary, size: .sm)+ }+ .frame(maxWidth: .infinity)++ if let error = form.error {+ AstryxBanner(status: .error, title: error)+ }++ AstryxTextInput(+ label: "Email",+ value: $form.email,+ type: .email,+ size: .lg,+ placeholder: "[email protected]"+ )+ AstryxTextInput(+ label: "Password",+ value: $form.password,+ type: .password,+ size: .lg,+ placeholder: "Enter your password"+ )+ AstryxButton(+ label: "Sign in",+ variant: .primary,+ size: .lg,+ isLoading: form.isLoading,+ fillsWidth: true,+ action: signIn+ )+ }+ }+ }+ .frame(maxWidth: 400)+ .padding(astryx.space(6))+ .frame(maxWidth: .infinity)+ }+}++// A PreviewProvider rather than `#Preview`: the macro needs Xcode, and this+// package builds with the command-line tools alone.+struct LoginTemplatePreviews: PreviewProvider {+ static var previews: some View {+ LoginTemplate().astryxTheme()+ }+}diff --git a/packages/native/apple/Templates/Package.swift b/packages/native/apple/Templates/Package.swiftnew file mode 100644index 0000000000..4d609b46e4--- /dev/null+++ b/packages/native/apple/Templates/Package.swift@@ -0,0 +1,24 @@+// swift-tools-version: 6.0+// Copyright (c) Meta Platforms, Inc. and affiliates.++// Page templates drawn with Astryx's SwiftUI views. Templates are clone-only:+// copy a template's folder into an app and own it from then on. This package+// exists only so the templates compile and are tested against the `Astryx`+// product; it has no products, and `@astryxdesign/native` does not publish it.++import PackageDescription++let package = Package(+ name: "AstryxTemplates",+ platforms: [.iOS(.v17), .macOS(.v14)],+ dependencies: [.package(path: "..")],+ targets: [+ .target(+ name: "AstryxTemplates",+ dependencies: [.product(name: "Astryx", package: "apple")],+ path: ".",+ exclude: ["Package.swift", "Tests"]+ ),+ .testTarget(name: "AstryxTemplatesTests", dependencies: ["AstryxTemplates"], path: "Tests"),+ ]+)diff --git a/packages/native/apple/Templates/Tests/LoginTemplateTests.swift b/packages/native/apple/Templates/Tests/LoginTemplateTests.swiftnew file mode 100644index 0000000000..8c20879971--- /dev/null+++ b/packages/native/apple/Templates/Tests/LoginTemplateTests.swift@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import Testing+@testable import AstryxTemplates++@Test func loginRequiresBothFields() {+ var form = LoginForm()+ form.email = "[email protected]"+ #expect(form.submit() == false)+ #expect(form.error == "Please enter both email and password.")+ #expect(form.isLoading == false)+}++@Test func loginStartsLoadingAndClearsTheError() {+ var form = LoginForm()+ _ = form.submit()+ form.email = "[email protected]"+ form.password = "secret"+ #expect(form.submit() == true)+ #expect(form.error == nil)+ #expect(form.isLoading == true)+}diff --git a/packages/native/apple/Tests/AstryxTests/BannerTests.swift b/packages/native/apple/Tests/AstryxTests/BannerTests.swiftnew file mode 100644index 0000000000..91f7e4e1de--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/BannerTests.swift@@ -0,0 +1,47 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++@Test func bannerStatusesUseSharedIconNamesAndCoreTokens() {+ let style = AstryxStyle(tokens: .defaultLight)+ #expect(AstryxBannerStatus.allCases.map(\.iconName) == ["info", "warning", "error", "success"])+ for status in AstryxBannerStatus.allCases {+ #expect(style.icon(status.iconName) != nil)+ #expect(style.tokens.colors[status.groundToken] != nil)+ #expect(style.tokens.colors[status.iconToken] != nil)+ }+}++@Test func aThemeReplacesASharedIcon() {+ let style = AstryxStyle(tokens: .defaultLight, icons: ["success": "checkmark.seal.fill"])+ #expect(style.icon("success") == "checkmark.seal.fill")+ #expect(style.icon("error") == "exclamationmark.circle.fill")+}++@MainActor+@Test func aBannerPaintsItsStatusGround() {+ var theme = AstryxTheme.default+ theme.light.colors["color-success-muted"] = "#FDE68AFF"+ let banner = AstryxBanner(status: .success, title: "Saved").frame(width: 240)+ let pixels = Pixels(banner, theme: theme)+ #expect(close(pixels.at(pixels.width - 6, pixels.height / 2), rgba("#FDE68AFF")))+}++@MainActor+@Test func aBannerReadsItsTitleThenItsDescription() {+ #expect(AstryxBanner(status: .error, title: "Upload failed").accessibilityText == "Upload failed")+ #expect(+ AstryxBanner(status: .error, title: "Upload failed", description: "Try again.").accessibilityText+ == "Upload failed, Try again."+ )+}++@MainActor+@Test func aBannerGrowsAtTheLargestTextSize() {+ let banner = AstryxBanner(status: .info, title: "Heads up", description: "Details.").frame(width: 320)+ let large = Pixels(banner)+ let largest = Pixels(banner, typeSize: .accessibility5)+ #expect(largest.height > large.height * 2)+}diff --git a/packages/native/apple/Tests/AstryxTests/ButtonTests.swift b/packages/native/apple/Tests/AstryxTests/ButtonTests.swiftnew file mode 100644index 0000000000..1c57f5cd6a--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/ButtonTests.swift@@ -0,0 +1,72 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++// Core's Button keeps a loading button undimmed and focusable, announces+// Loading, and ignores presses until it finishes.++@MainActor+@Test func aLoadingButtonIgnoresPressesAndSaysLoading() {+ var presses = 0+ let loading = AstryxButton(label: "Save", isLoading: true) { presses += 1 }+ loading.activate()+ #expect(presses == 0)+ #expect(loading.loadingValue == "Loading")++ let ready = AstryxButton(label: "Save") { presses += 1 }+ ready.activate()+ #expect(presses == 1)+ #expect(ready.loadingValue == nil)+}++@MainActor+@Test func aLoadingButtonIsNotDimmedAndKeepsItsWidth() {+ let accent = rgba(AstryxTokens.defaultLight.colors["color-accent"]!)+ let loading = Pixels(AstryxButton(label: "Continue", variant: .primary, isLoading: true) {}.fixedSize())+ let ready = Pixels(AstryxButton(label: "Continue", variant: .primary) {}.fixedSize())+ #expect(close(loading.at(8, loading.height / 2), accent))+ #expect(loading.width == ready.width)+}++@MainActor+@Test func aDisabledButtonIsDimmed() {+ let accent = rgba(AstryxTokens.defaultLight.colors["color-accent"]!)+ let disabled = Pixels(AstryxButton(label: "Continue", variant: .primary, isDisabled: true) {}.fixedSize())+ #expect(!close(disabled.at(8, disabled.height / 2), accent))+}++@MainActor+@Test func theTapAreaIsAtLeast44PointsEvenForSmallButtons() {+ let small = Pixels(AstryxButton(label: "OK", size: .sm) {}.fixedSize())+ #expect(small.width >= 44)+ #expect(small.height >= 44)+}++@MainActor+@Test func buttonLabelsGrowAtTheLargestTextSizeWithoutClipping() {+ let large = Pixels(AstryxButton(label: "Continue") {}.fixedSize())+ let largest = Pixels(AstryxButton(label: "Continue") {}.fixedSize(), typeSize: .accessibility5)+ #expect(largest.width > large.width)+ #expect(largest.height > large.height)+}++@MainActor+@Test func aButtonIsNamedByItsLabelAndIsAButton() {+ #expect(AstryxButton(label: "Save") {}.accessibilityText == "Save")+ #expect(AstryxButton(label: "Save", isLoading: true) {}.accessibilityText == "Save")+ #expect(AstryxButton.accessibilityTraits.contains(.isButton))+}++@Test func buttonIconsUseSharedNamesAndTheTheme() {+ #expect(AstryxStyle(tokens: .defaultLight).icon("search") == "magnifyingglass")+ #expect(AstryxStyle(tokens: .defaultLight, icons: ["search": "sparkle.magnifyingglass"]).icon("search") == "sparkle.magnifyingglass")+}++@MainActor+@Test func aButtonDrawsItsSharedIcon() {+ let plain = Pixels(AstryxButton(label: "Find") {}.fixedSize())+ let withIcon = Pixels(AstryxButton(label: "Find", icon: "search") {}.fixedSize())+ #expect(withIcon.width > plain.width)+}diff --git a/packages/native/apple/Tests/AstryxTests/CardTests.swift b/packages/native/apple/Tests/AstryxTests/CardTests.swiftnew file mode 100644index 0000000000..83e3ed3d18--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/CardTests.swift@@ -0,0 +1,19 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++@MainActor+@Test func severalChildrenStackInOneCard() {+ let card = AstryxCard(padding: 0) {+ Color(astryxHex: "#FF0000FF").frame(width: 80, height: 40)+ Color(astryxHex: "#0000FFFF").frame(width: 80, height: 40)+ }+ .frame(width: 120)+ let pixels = Pixels(card)+ // One card, the two children one above the other.+ #expect(pixels.height >= 80)+ #expect(close(pixels.at(40, 20), rgba("#FF0000FF")))+ #expect(close(pixels.at(40, 60), rgba("#0000FFFF")))+}diff --git a/packages/native/apple/Tests/AstryxTests/EnvironmentTests.swift b/packages/native/apple/Tests/AstryxTests/EnvironmentTests.swiftnew file mode 100644index 0000000000..d935326517--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/EnvironmentTests.swift@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++// AST-082 FR11: components follow Dark Mode and Dynamic Type even without+// astryxTheme(_:).++@MainActor+@Test func withoutAThemeComponentsFollowDarkMode() {+ let card = AstryxCard { Color.clear.frame(width: 80, height: 40) }.frame(width: 120)+ let light = Pixels(card, scheme: .light)+ let dark = Pixels(card, scheme: .dark)+ #expect(close(light.at(60, light.height / 2), rgba(AstryxTokens.defaultLight.colors["color-background-card"]!)))+ #expect(close(dark.at(60, dark.height / 2), rgba(AstryxTokens.defaultDark.colors["color-background-card"]!)))+}++@MainActor+@Test func withoutAThemeTextFollowsDynamicType() {+ let large = Pixels(AstryxText("Hello").fixedSize())+ let larger = Pixels(AstryxText("Hello").fixedSize(), typeSize: .xxxLarge)+ #expect(larger.width > large.width)+}++@Test func fontStacksPickTheFirstFamilyTheDeviceHas() {+ #expect(astryxFont(families: ["-apple-system", "Helvetica"], size: 14, weight: .regular) == .system(size: 14, weight: .regular))+ #expect(astryxFont(families: ["Not A Real Font", "monospace"], size: 14, weight: .regular) == .system(size: 14, weight: .regular, design: .monospaced))+ #expect(astryxFont(families: ["Helvetica", "sans-serif"], size: 14, weight: .bold) == .custom("Helvetica", fixedSize: 14).weight(.bold))+ #expect(astryxFont(families: [], size: 14, weight: .regular) == .system(size: 14, weight: .regular))+}++@Test func theDefaultThemeCarriesCoresFontFamilies() {+ #expect(AstryxTokens.defaultLight.fonts["font-family-body"]?.first == "-apple-system")+ #expect(AstryxTokens.defaultLight.fonts["font-family-heading"] != nil)+}diff --git a/packages/native/apple/Tests/AstryxTests/HeadingTests.swift b/packages/native/apple/Tests/AstryxTests/HeadingTests.swiftnew file mode 100644index 0000000000..d22213f720--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/HeadingTests.swift@@ -0,0 +1,40 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++@MainActor+@Test func headingLevelsAreClampedAndExposedToVoiceOver() {+ #expect(AstryxHeading("Title", level: 0).level == 1)+ #expect(AstryxHeading("Title", level: 9).level == 6)+ #expect(AstryxHeading("Title", level: 1).headingLevel == .h1)+ #expect(AstryxHeading("Title", level: 3).headingLevel == .h3)+ #expect(AstryxHeading("Title", level: 6).headingLevel == .h6)+}++@MainActor+@Test func headingsShrinkByLevel() {+ let h1 = Pixels(AstryxHeading("Settings", level: 1).fixedSize())+ let h4 = Pixels(AstryxHeading("Settings", level: 4).fixedSize())+ #expect(h1.width > h4.width)+}++@MainActor+@Test func headingsGrowAtTheLargestTextSizeAndFollowASecondTheme() {+ let large = Pixels(AstryxHeading("Settings").fixedSize())+ let largest = Pixels(AstryxHeading("Settings").fixedSize(), typeSize: .accessibility5)+ #expect(largest.width > large.width * 2)++ var theme = AstryxTheme.default+ theme.light.sizes["text-heading-2-size"] = 48+ theme.light.colors["color-text-primary"] = "#FF0000FF"+ let themed = Pixels(AstryxHeading("Settings").fixedSize(), theme: theme)+ #expect(themed.width > large.width)+ #expect(themed.contains { $0[0] > 200 && $0[1] < 60 && $0[2] < 60 && $0[3] > 200 })+}++@MainActor+@Test func aHeadingIsAHeader() {+ #expect(AstryxHeading.accessibilityTraits.contains(.isHeader))+}diff --git a/packages/native/apple/Tests/AstryxTests/Pixels.swift b/packages/native/apple/Tests/AstryxTests/Pixels.swiftnew file mode 100644index 0000000000..9d5a027fd7--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/Pixels.swift@@ -0,0 +1,62 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import CoreGraphics+import SwiftUI+@testable import Astryx++/// RGBA pixels of a view drawn at 1x, with an optional theme, color scheme,+/// and Dynamic Type size.+struct Pixels {+ let width: Int+ let height: Int+ private let bytes: [UInt8]++ @MainActor+ init<V: View>(+ _ view: V,+ theme: AstryxTheme? = nil,+ scheme: ColorScheme = .light,+ typeSize: DynamicTypeSize = .large+ ) {+ let themed = Group {+ if let theme { view.astryxTheme(theme) } else { view }+ }+ let renderer = ImageRenderer(+ content: themed.environment(\.colorScheme, scheme).environment(\.dynamicTypeSize, typeSize)+ )+ renderer.scale = 1+ let image = renderer.cgImage!+ width = image.width+ height = image.height+ var data = [UInt8](repeating: 0, count: width * height * 4)+ let context = CGContext(+ data: &data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,+ space: CGColorSpace(name: CGColorSpace.sRGB)!,+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue+ )!+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))+ bytes = data+ }++ /// The pixel at `x`, `y` from the top left, as RGBA components. A bitmap+ /// context stores its top row first.+ func at(_ x: Int, _ y: Int) -> [Int] {+ let i = (y * width + x) * 4+ return (0..<4).map { Int(bytes[i + $0]) }+ }++ func contains(where match: ([Int]) -> Bool) -> Bool {+ for y in 0..<height { for x in 0..<width where match(at(x, y)) { return true } }+ return false+ }+}++/// The components of a `#RRGGBBAA` token.+func rgba(_ hex: String) -> [Int] {+ let value = UInt32(hex.dropFirst(), radix: 16)!+ return [24, 16, 8, 0].map { Int((value >> UInt32($0)) & 0xFF) }+}++func close(_ a: [Int], _ b: [Int], within tolerance: Int = 8) -> Bool {+ zip(a, b).allSatisfy { abs($0 - $1) <= tolerance }+}diff --git a/packages/native/apple/Tests/AstryxTests/StringsTests.swift b/packages/native/apple/Tests/AstryxTests/StringsTests.swiftnew file mode 100644index 0000000000..3772d54642--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/StringsTests.swift@@ -0,0 +1,23 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import Foundation+import Testing+@testable import Astryx++// The loading message comes from core's locale catalogs, so VoiceOver speaks+// it in the person's language.++@Test func theLoadingMessageIsLocalizedFromCoresCatalog() throws {+ func message(in locale: String) throws -> String {+ // SwiftPM may change a localization folder's case, so match it loosely.+ let resources = AstryxStrings.resourceBundle+ let name = try #require(resources.localizations.first { $0.lowercased() == locale.lowercased() })+ let path = try #require(resources.path(forResource: name, ofType: "lproj"))+ let bundle = try #require(Bundle(path: path))+ return bundle.localizedString(forKey: "@astryx.button.loading", value: nil, table: nil)+ }+ #expect(try message(in: "en") == "Loading")+ #expect(try message(in: "de") == "Wird geladen")+ #expect(try message(in: "pt-BR") == "Carregando")+ #expect(try message(in: "ja") != "Loading")+}diff --git a/packages/native/apple/Tests/AstryxTests/TextInputTests.swift b/packages/native/apple/Tests/AstryxTests/TextInputTests.swiftnew file mode 100644index 0000000000..87d99e4fc9--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/TextInputTests.swift@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++@MainActor+@Test func aTextFieldIsAtLeast44PointsTallAtEveryTextSize() {+ let field = AstryxTextInput(label: "Email", value: .constant(""), size: .sm).frame(width: 240)+ for typeSize in [DynamicTypeSize.xSmall, .large, .accessibility5] {+ let pixels = Pixels(field, typeSize: typeSize)+ // The label sits above a field at least 44 tall.+ #expect(pixels.height >= 44 + 12)+ }+}++@MainActor+@Test func aFieldLabelUsesTheSecondaryTextColor() {+ var theme = AstryxTheme.default+ theme.light.colors["color-text-secondary"] = "#FF0000FF"+ let pixels = Pixels(AstryxTextInput(label: "Email", value: .constant("")).frame(width: 240), theme: theme)+ #expect(pixels.contains { $0[0] > 200 && $0[1] < 60 && $0[2] < 60 && $0[3] > 200 })+}++@MainActor+@Test func aTextFieldIsNamedByItsLabel() {+ let field = AstryxTextInput(label: "Email", value: .constant(""))+ #expect(field.accessibilityText == "Email")+}diff --git a/packages/native/apple/Tests/AstryxTests/TextTests.swift b/packages/native/apple/Tests/AstryxTests/TextTests.swiftnew file mode 100644index 0000000000..dae80e048f--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/TextTests.swift@@ -0,0 +1,25 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++@Test func textColorDefaultsByTypeAsCoreDoes() {+ #expect(AstryxTextType.supporting.defaultColor == .secondary)+ for type in [AstryxTextType.body, .large, .label] {+ #expect(type.defaultColor == .primary)+ }+}++@Test func extraSmallIsSpelledAsCoreSpellsIt() {+ #expect(AstryxTextSize(rawValue: "xsm") == .xsm)+ #expect(AstryxTextSize.xsm.token == "font-size-xs")+ #expect(AstryxTextSize.sm.token == "font-size-sm")+}++@MainActor+@Test func textGrowsAtTheLargestDynamicTypeSize() {+ let large = Pixels(AstryxText("Hello").fixedSize())+ let largest = Pixels(AstryxText("Hello").fixedSize(), typeSize: .accessibility5)+ #expect(largest.width > large.width * 2)+}diff --git a/packages/native/apple/Tests/AstryxTests/ThemeTests.swift b/packages/native/apple/Tests/AstryxTests/ThemeTests.swiftnew file mode 100644index 0000000000..1882f24bc3--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/ThemeTests.swift@@ -0,0 +1,39 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++@Test func defaultThemeCarriesCoreTokensInBothModes() {+ for tokens in [AstryxTokens.defaultLight, AstryxTokens.defaultDark] {+ for color in ["color-accent", "color-on-accent", "color-text-primary", "color-background-card"] {+ #expect(tokens.colors[color] != nil, "missing \(color)")+ }+ #expect(tokens.sizes["size-element-md"] == 32)+ #expect(tokens.sizes["radius-element"] == 8)+ }+ #expect(AstryxTokens.defaultLight.colors["color-text-primary"] != AstryxTokens.defaultDark.colors["color-text-primary"])+}++@Test func styleReadsTokensAndFallsBackOnlyForSizes() {+ let style = AstryxStyle(+ tokens: AstryxTokens(colors: ["color-accent": "#0064E0FF"], sizes: ["spacing-4": 16]),+ textScale: 1.5+ )+ #expect(style.space(4) == 16)+ #expect(style.space(3) == 12)+ #expect(style.size("radius-element", 8) == 8)+ #expect(style.fontSize("spacing-4", 0) == 24)+ #expect(style.color("color-missing") == .clear)+}++@Test func hexColorsRead() {+ #expect(Color(astryxHex: "#0064E0FF") == Color(.sRGB, red: 0, green: 100 / 255, blue: 224 / 255, opacity: 1))+ #expect(Color(astryxHex: "#FFF") == Color(.sRGB, red: 1, green: 1, blue: 1, opacity: 1))+ #expect(Color(astryxHex: "not a color") == .clear)+}++@Test func textScaleFollowsDynamicType() {+ #expect(astryxTextScale(for: .large) == 1)+ #expect(astryxTextScale(for: .accessibility5) > astryxTextScale(for: .xxxLarge))+}diff --git a/packages/native/apple/Tests/AstryxTests/TwoThemeTests.swift b/packages/native/apple/Tests/AstryxTests/TwoThemeTests.swiftnew file mode 100644index 0000000000..70cdc1b7c4--- /dev/null+++ b/packages/native/apple/Tests/AstryxTests/TwoThemeTests.swift@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import SwiftUI+import Testing+@testable import Astryx++// AST-093 FR4 and FR5: a component renders from two different themes with no+// value of its own in between. Each test draws a component under core's+// default theme and under a second theme with a different color, type size,+// and corner shape, and reads the pixels.++/// Core's default tokens with a different accent, card, text color, type+/// size, and corner shape, in both modes.+private let secondTheme: AstryxTheme = {+ func restyle(_ base: AstryxTokens) -> AstryxTokens {+ var tokens = base+ tokens.colors["color-accent"] = "#C2410CFF"+ tokens.colors["color-background-card"] = "#FDE68AFF"+ tokens.colors["color-text-primary"] = "#FF0000FF"+ tokens.sizes["text-label-size"] = 28+ tokens.sizes["text-body-size"] = 30+ tokens.sizes["radius-container"] = 0+ tokens.sizes["radius-element"] = 0+ return tokens+ }+ return AstryxTheme(light: restyle(.defaultLight), dark: restyle(.defaultDark))+}()++@MainActor+@Test func cardFollowsTheThemesGroundAndShape() {+ let card = AstryxCard { Color.clear.frame(width: 80, height: 40) }.frame(width: 120)+ let standard = Pixels(card, theme: .default)+ let second = Pixels(card, theme: secondTheme)++ let center = (second.width / 2, second.height / 2)+ #expect(close(standard.at(center.0, center.1), rgba(AstryxTokens.defaultLight.colors["color-background-card"]!)))+ #expect(close(second.at(center.0, center.1), rgba("#FDE68AFF")))+ // Corner shape: the default container radius leaves the corner empty;+ // a radius of 0 fills it.+ #expect(standard.at(2, 2)[3] == 0)+ #expect(close(second.at(2, 2), rgba("#FDE68AFF")))+}++@MainActor+@Test func buttonFollowsTheThemesAccentTypeAndShape() {+ let button = AstryxButton(label: "Continue", variant: .primary) {}.fixedSize()+ let standard = Pixels(button, theme: .default)+ let second = Pixels(button, theme: secondTheme)++ #expect(close(standard.at(8, standard.height / 2), rgba(AstryxTokens.defaultLight.colors["color-accent"]!)))+ #expect(close(second.at(8, second.height / 2), rgba("#C2410CFF")))+ // A larger label size makes the same label wider.+ #expect(second.width > standard.width)+}++@MainActor+@Test func textFollowsTheThemesColorAndTypeSize() {+ let text = AstryxText("Hello").fixedSize()+ let standard = Pixels(text, theme: .default)+ let second = Pixels(text, theme: secondTheme)++ #expect(second.width > standard.width)+ #expect(second.contains { $0[0] > 200 && $0[1] < 60 && $0[2] < 60 && $0[3] > 200 })+ #expect(!standard.contains { $0[0] > 200 && $0[1] < 60 && $0[2] < 60 && $0[3] > 200 })+}diff --git a/packages/native/package.json b/packages/native/package.jsonindex a4bce47ed2..5dabc4ba62 100644--- a/packages/native/package.json+++ b/packages/native/package.json@@ -32,6 +32,7 @@"dist","src","apple",+ "!apple/Templates","README.md"],"exports": {@@ -73,6 +74,7 @@"prepack": "pnpm build","build": "node ../../scripts/clean-dist.mjs && tsc --project tsconfig.build.json && node scripts/generate.mjs --types","generate:apple": "pnpm build && node scripts/generate.mjs --apple",+ "generate:swift-ios": "pnpm -F @astryxdesign/core build && node scripts/swift-ios-theme.mjs && node scripts/swift-ios-strings.mjs","test": "vitest run --root ../.. packages/native","typecheck": "tsc --project tsconfig.json --noEmit","typecheck:types": "tsc --project tsconfig.types.json"diff --git a/packages/native/scripts/swift-ios-strings.d.mts b/packages/native/scripts/swift-ios-strings.d.mtsnew file mode 100644index 0000000000..f2a60fa04e--- /dev/null+++ b/packages/native/scripts/swift-ios-strings.d.mts@@ -0,0 +1,5 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export declare const SWIFT_IOS_STRINGS_DIR: string;+export declare const SWIFT_IOS_STRING_KEYS: string[];+export declare function renderSwiftIOSStrings(): Record<string, string>;diff --git a/packages/native/scripts/swift-ios-strings.mjs b/packages/native/scripts/swift-ios-strings.mjsnew file mode 100644index 0000000000..ff34ee9a0d--- /dev/null+++ b/packages/native/scripts/swift-ios-strings.mjs@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file scripts/swift-ios-strings.mjs+ * @input Core's locale catalogs (`@astryxdesign/core/locales/*.json`)+ * @output apple/Sources/Astryx/Resources/<locale>.lproj/Localizable.strings+ * @position Run by `generate:swift-ios`; the output is committed and a test+ * fails when it drifts from core's catalogs+ */++import fs from 'node:fs';+import path from 'node:path';+import {createRequire} from 'node:module';+import {fileURLToPath} from 'node:url';++const PACKAGE_ROOT = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '..',+);+export const SWIFT_IOS_STRINGS_DIR = path.join(+ PACKAGE_ROOT,+ 'apple',+ 'Sources',+ 'Astryx',+ 'Resources',+);++/** The catalog messages the Swift components speak. */+export const SWIFT_IOS_STRING_KEYS = ['@astryx.button.loading'];++// Apple names a localization by its language alone unless one language has+// several catalogs (pt-BR, pt-PT), and writes Chinese by script.+const APPLE_LOCALES = {'zh-CN': 'zh-Hans', 'zh-TW': 'zh-Hant', 'no-NO': 'nb'};++function appleLocale(locale, languageCounts) {+ if (APPLE_LOCALES[locale]) return APPLE_LOCALES[locale];+ const language = locale.split('-')[0];+ return languageCounts[language] > 1 ? locale : language;+}++function localesDir() {+ const require = createRequire(import.meta.url);+ // Read through core's public `./locales/*.json` export.+ return path.dirname(require.resolve('@astryxdesign/core/locales/en.json'));+}++function quote(text) {+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;+}++/**+ * The generated `.strings` files, keyed by their path under+ * `core/Resources/`. Core's pseudo-locale is left out.+ */+export function renderSwiftIOSStrings() {+ const dir = localesDir();+ const locales = fs+ .readdirSync(dir)+ .filter(file => file.endsWith('.json') && file !== 'pseudo.json')+ .map(file => file.slice(0, -'.json'.length))+ .sort();+ const languageCounts = {};+ for (const locale of locales) {+ const language = locale.split('-')[0];+ languageCounts[language] = (languageCounts[language] ?? 0) + 1;+ }+ const files = {};+ for (const locale of locales) {+ const file = `${locale}.json`;+ const catalog = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));+ const lines = [+ "/* Generated by @astryxdesign/native from core's locale catalogs. Do not edit. */",+ ];+ for (const key of SWIFT_IOS_STRING_KEYS) {+ const entry = catalog[key];+ if (!entry) throw new Error(`${file} has no ${key}`);+ lines.push('', `/* ${entry.description.replace(/\*\//g, '* /')} */`);+ lines.push(`${quote(key)} = ${quote(entry.defaultMessage)};`);+ }+ files[`${appleLocale(locale, languageCounts)}.lproj/Localizable.strings`] =+ `${lines.join('\n')}\n`;+ }+ return files;+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ fs.rmSync(SWIFT_IOS_STRINGS_DIR, {recursive: true, force: true});+ const files = renderSwiftIOSStrings();+ for (const [relative, text] of Object.entries(files)) {+ const out = path.join(SWIFT_IOS_STRINGS_DIR, relative);+ fs.mkdirSync(path.dirname(out), {recursive: true});+ fs.writeFileSync(out, text);+ }+ console.log(+ `wrote ${Object.keys(files).length} files to ${path.relative(PACKAGE_ROOT, SWIFT_IOS_STRINGS_DIR)}`,+ );+}diff --git a/packages/native/scripts/swift-ios-theme.d.mts b/packages/native/scripts/swift-ios-theme.d.mtsnew file mode 100644index 0000000000..bb62e26787--- /dev/null+++ b/packages/native/scripts/swift-ios-theme.d.mts@@ -0,0 +1,7 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export declare const SWIFT_IOS_THEME_FILE: string;+export declare function toHexColor(value: string): string | null;+export declare function toPoints(value: string): number | null;+export declare function toFontFamilies(value: string): string[];+export declare function renderSwiftIOSTheme(): Promise<string>;diff --git a/packages/native/scripts/swift-ios-theme.mjs b/packages/native/scripts/swift-ios-theme.mjsnew file mode 100644index 0000000000..7fa6230cdc--- /dev/null+++ b/packages/native/scripts/swift-ios-theme.mjs@@ -0,0 +1,167 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file scripts/swift-ios-theme.mjs+ * @input Core's theme resolver, run over the default theme in light and dark+ * @output apple/Sources/Astryx/Theme/Generated/DefaultTheme.swift+ * @position Run by `generate:swift-ios`; the Swift output is committed and a+ * test fails when it drifts from core's tokens+ */++import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';++const PACKAGE_ROOT = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '..',+);+export const SWIFT_IOS_THEME_FILE = path.join(+ PACKAGE_ROOT,+ 'apple',+ 'Sources',+ 'Astryx',+ 'Theme',+ 'Generated',+ 'DefaultTheme.swift',+);++// The token groups the Swift components read. Everything else (shadows,+// motion, layout breakpoints) stays out until a component needs it.+const KEEP =+ /^--(color-|spacing-|radius-|size-element-|border-width$|font-family-|font-size-|font-weight-|text-(heading-\d|body|large|label|supporting)-)/;+const REM = 16;++function hex2(n) {+ return Math.round(n).toString(16).padStart(2, '0').toUpperCase();+}++// The CSS color keywords core's resolved tokens use.+const NAMED_COLORS = {+ black: '#000000FF',+ white: '#FFFFFFFF',+ transparent: '#00000000',+};++/** A CSS color as `#RRGGBBAA`, or null when it is not a plain color. */+export function toHexColor(value) {+ const v = value.trim();+ let m = /^#([0-9a-f]{3,8})$/i.exec(v);+ if (m) {+ let h = m[1];+ if (h.length === 3 || h.length === 4) h = [...h].map(c => c + c).join('');+ if (h.length === 6) h += 'FF';+ return h.length === 8 ? `#${h.toUpperCase()}` : null;+ }+ m =+ /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)$/i.exec(+ v,+ );+ if (m) {+ const alpha =+ m[4] === undefined+ ? 1+ : m[4].endsWith('%')+ ? parseFloat(m[4]) / 100+ : parseFloat(m[4]);+ return `#${hex2(+m[1])}${hex2(+m[2])}${hex2(+m[3])}${hex2(alpha * 255)}`;+ }+ return NAMED_COLORS[v.toLowerCase()] ?? null;+}++/** A CSS font-family stack as its family names, first choice first. */+export function toFontFamilies(value) {+ return value+ .split(',')+ .map(family => family.trim().replace(/^(["'])(.*)\1$/, '$2'))+ .filter(Boolean);+}++/** A CSS length or unitless number as points, or null. */+export function toPoints(value) {+ const m = /^(-?[\d.]+)(rem|px)?$/.exec(value.trim());+ if (!m) return null;+ return m[2] === 'rem' ? parseFloat(m[1]) * REM : parseFloat(m[1]);+}++async function resolveMode(mode) {+ const {defineTheme} = await import('@astryxdesign/core/theme');+ const {resolveThemeTokens} = await import('@astryxdesign/core/theme/tokens');+ const theme = defineTheme({name: 'astryx', tokens: {}});+ const colors = {};+ const sizes = {};+ const fonts = {};+ for (const [name, value] of Object.entries(+ resolveThemeTokens(theme, {mode}),+ )) {+ if (!KEEP.test(name) || typeof value !== 'string') continue;+ const key = name.slice(2);+ // A kept token that cannot be read fails the run, so no token goes+ // missing from the Swift theme without a message.+ if (key.startsWith('font-family-')) {+ const families = toFontFamilies(value);+ if (families.length === 0) {+ throw new Error(`${mode}: ${name} names no font family: ${value}`);+ }+ fonts[key] = families;+ } else if (key.startsWith('color-')) {+ const color = toHexColor(value);+ if (color === null) {+ throw new Error(+ `${mode}: ${name} is not a color Swift can read: ${value}`,+ );+ }+ colors[key] = color;+ } else {+ const points = toPoints(value);+ if (points === null) {+ throw new Error(+ `${mode}: ${name} is not a size Swift can read: ${value}`,+ );+ }+ sizes[key] = points;+ }+ }+ return {colors, sizes, fonts};+}++function swiftDictionary(entries, format) {+ const keys = Object.keys(entries).sort();+ return keys.map(key => ` "${key}": ${format(entries[key])},`).join('\n');+}++function swiftTokens(name, mode, {colors, sizes, fonts}) {+ return ` /// Core's default theme, ${mode} mode.+ public static let ${name} = AstryxTokens(+ colors: [+${swiftDictionary(colors, v => `"${v}"`)}+ ],+ sizes: [+${swiftDictionary(sizes, v => String(v))}+ ],+ fonts: [+${swiftDictionary(fonts, v => `[${v.map(f => JSON.stringify(f)).join(', ')}]`)}+ ]+ )`;+}++/** The generated Swift source for core's default theme. */+export async function renderSwiftIOSTheme() {+ const light = await resolveMode('light');+ const dark = await resolveMode('dark');+ return `// Generated by @astryxdesign/native from core's theme resolver. Do not edit.+// Run \`pnpm -F @astryxdesign/native generate:swift-ios\` after a core token change.++extension AstryxTokens {+${swiftTokens('defaultLight', 'light', light)}++${swiftTokens('defaultDark', 'dark', dark)}+}+`;+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ fs.mkdirSync(path.dirname(SWIFT_IOS_THEME_FILE), {recursive: true});+ fs.writeFileSync(SWIFT_IOS_THEME_FILE, await renderSwiftIOSTheme());+ console.log(`wrote ${path.relative(PACKAGE_ROOT, SWIFT_IOS_THEME_FILE)}`);+}diff --git a/packages/native/src/icons/swiftIcons.test.ts b/packages/native/src/icons/swiftIcons.test.tsnew file mode 100644index 0000000000..daa4f992e6--- /dev/null+++ b/packages/native/src/icons/swiftIcons.test.ts@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {describe, expect, it} from 'vitest';+import {SF_SYMBOL_NAMES} from './defaults.js';++const SWIFT_ICONS = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../apple/Sources/Astryx/Theme/AstryxIcons.swift',+);++describe('Astryx Swift icon defaults', () => {+ it('match NATIVE_ICON_DEFAULTS for Apple platforms', () => {+ const swift = fs.readFileSync(SWIFT_ICONS, 'utf8');+ const entries = Object.fromEntries(+ [...swift.matchAll(/^ {2}"(\w+)": "([^"]+)",$/gm)].map(m => [m[1], m[2]]),+ );+ expect(entries).toEqual({...SF_SYMBOL_NAMES});+ });+});diff --git a/packages/native/src/theme/swiftIOSStrings.test.ts b/packages/native/src/theme/swiftIOSStrings.test.tsnew file mode 100644index 0000000000..05b1752539--- /dev/null+++ b/packages/native/src/theme/swiftIOSStrings.test.ts@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import path from 'node:path';+import {describe, expect, it} from 'vitest';+import {+ SWIFT_IOS_STRINGS_DIR,+ renderSwiftIOSStrings,+} from '../../scripts/swift-ios-strings.mjs';++describe('swift-ios localized strings', () => {+ it("speaks core's catalog message in each locale", () => {+ const files = renderSwiftIOSStrings();+ expect(files['en.lproj/Localizable.strings']).toContain(+ '"@astryx.button.loading" = "Loading";',+ );+ expect(files['de.lproj/Localizable.strings']).toContain(+ '"@astryx.button.loading" = "Wird geladen";',+ );+ expect(Object.keys(files)).toEqual(+ expect.arrayContaining([+ 'pt-BR.lproj/Localizable.strings',+ 'pt-PT.lproj/Localizable.strings',+ 'zh-Hans.lproj/Localizable.strings',+ 'nb.lproj/Localizable.strings',+ ]),+ );+ expect(Object.keys(files).some(name => name.startsWith('pseudo'))).toBe(+ false,+ );+ });++ it("keeps the committed files in sync with core's catalogs", () => {+ const files = renderSwiftIOSStrings();+ const committed = fs+ .readdirSync(SWIFT_IOS_STRINGS_DIR)+ .map(dir => `${dir}/Localizable.strings`)+ .sort();+ expect(+ committed,+ 'Localizable.strings files are stale; run pnpm -F @astryxdesign/native generate:swift-ios',+ ).toEqual(Object.keys(files).sort());+ for (const [relative, text] of Object.entries(files)) {+ expect(+ fs.readFileSync(path.join(SWIFT_IOS_STRINGS_DIR, relative), 'utf8'),+ ).toBe(text);+ }+ });+});diff --git a/packages/native/src/theme/swiftIOSTheme.test.ts b/packages/native/src/theme/swiftIOSTheme.test.tsnew file mode 100644index 0000000000..a5297810b1--- /dev/null+++ b/packages/native/src/theme/swiftIOSTheme.test.ts@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import {describe, expect, it} from 'vitest';+import {+ SWIFT_IOS_THEME_FILE,+ renderSwiftIOSTheme,+ toFontFamilies,+ toHexColor,+ toPoints,+} from '../../scripts/swift-ios-theme.mjs';++describe('swift-ios default theme', () => {+ it('reads CSS colors and lengths as Swift values', () => {+ expect(toHexColor('#0064E0')).toBe('#0064E0FF');+ expect(toHexColor('#fff')).toBe('#FFFFFFFF');+ expect(toHexColor('rgba(5, 54, 89, 0.1)')).toBe('#0536591A');+ expect(toHexColor('transparent')).toBe('#00000000');+ expect(toHexColor('black')).toBe('#000000FF');+ expect(toHexColor('white')).toBe('#FFFFFFFF');+ expect(toHexColor('light-dark(#000, #fff)')).toBeNull();+ expect(toPoints('0.875rem')).toBe(14);+ expect(toPoints('32px')).toBe(32);+ expect(toPoints('600')).toBe(600);+ expect(toPoints('cubic-bezier(0, 0, 1, 1)')).toBeNull();+ });++ it('reads font stacks as family names, first choice first', async () => {+ expect(+ toFontFamilies('-apple-system, "Segoe UI", \'Inter\', sans-serif'),+ ).toEqual(['-apple-system', 'Segoe UI', 'Inter', 'sans-serif']);+ expect(await renderSwiftIOSTheme()).toContain(+ '"font-family-heading": ["-apple-system",',+ );+ });++ it('keeps every color token, keywords included', async () => {+ expect(await renderSwiftIOSTheme()).toContain(+ '"color-tint-hover": "#000000FF"',+ );+ });++ it('keeps the committed Swift theme in sync with core tokens', async () => {+ expect(+ fs.readFileSync(SWIFT_IOS_THEME_FILE, 'utf8'),+ 'DefaultTheme.swift is stale; run pnpm -F @astryxdesign/native generate:swift-ios',+ ).toBe(await renderSwiftIOSTheme());+ });+});