Skip to content

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

TypeScript

feat(native): Swift Item draws core's row with typed slots, as a link or a button (#8321)

Cindy Zhangd545bc5a941c
diff --git a/docs/specs/components/Item/Item.swift.spec.md b/docs/specs/components/Item/Item.swift.spec.md
new file mode 100644
index 0000000000..9988790e44
--- /dev/null
+++ b/docs/specs/components/Item/Item.swift.spec.md
@@ -0,0 +1,192 @@
+---
+schema_version: 3
+template_version: 7
+kind: component
+id: component:swift/Item
+platform_of: component:Item
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers: [public-api, behavior, layout, theming, accessibility]
+verified_by:
+ [
+ packages/native/apple/Tests/AstryxTests/ItemTests.swift,
+ packages/native/src/contract/contracts.test.ts,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture: []
+contributing: []
+system_specs: [spec:AST-082, spec:AST-093]
+---
+
+# Item (Swift) component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `Item(_ label:, description:, align:, density:, labelLines:, descriptionLines:, layout:, href:, isHighlighted:, isSelected:, isDisabled:, startContent:, endContent:, marker:, onClick:)` and `Item(_ props: ItemProps, startContent:, endContent:, marker:)`, a generic SwiftUI `View`. |
+| Behavior | Draws core's row: marker, start content, the label over or beside its description, end content, with core's density padding, alignment, line limits, and highlighted, selected, and disabled looks. With `href` it is a SwiftUI `Link`; with only `onClick` a SwiftUI `Button`. |
+| End-user impact | A person sees list, menu, and settings rows that line up and read like the web's, can tap a whole row, and VoiceOver reads one row in slot order with its selected or dimmed state. |
+| Builder impact | Slots take any SwiftUI view through closures; a single trailing closure is the start content. Swipe actions, `target`, `rel`, and `data-testid` have no Swift form. |
+| Compatibility/readiness | Additive: a new view and generated `ItemProps`. Draft; built and tested on macOS and the iOS Simulator; device captures are attached to the change. |
+| Review checks | Reject a slot typed as `AnyView`, a row that draws differently as a link or button, a static row grown to the touch target, a disabled link that opens, colors that are not theme tokens, or a swipe prop the row cannot honor. |
+| Governing rules | `spec:AST-082` FR3, FR4, FR7; `spec:AST-093` FR1–FR5; the Swift component API (A2–A4, A7, A9), slots (S1, S3–S5), theme environment, and accessibility (X1, X2, X5, X7) records under `packages/native/specs/swift/library/`. |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+Item on Apple platforms is core's row primitive: the shared layout for list
+rows, menu rows, and settings rows, drawn with theme tokens and SwiftUI's own
+link and button controls.
+
+## Compatibility and migration
+
+- Released default preserved: `not yet released`
+- Compatibility class: additive
+- Controlled/uncontrolled behavior: not applicable
+- Migration decision: none
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- The row's slot order, spacing, padding per density, and alignment of the
+ start and end content against the words.
+- Line limits, the label and description type, and the highlighted, selected,
+ and disabled looks.
+- Switching to a SwiftUI `Link` or `Button` without changing the drawing, and
+ the row's accessibility element.
+
+**Does not own / non-goals**
+
+- The meaning of the props — owned by `component:Item`.
+- List markers, dividers, and edges — owned by the list that holds the rows.
+- What a slot draws: an `Icon`, an `Avatar`, or any view keeps its own size and
+ look (Swift slots S4: an unsized Avatar stays `md`).
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ------- | ----------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------- | ---------- | ---------------------- | ------------ | --------------------------------------------------- |
+| slots | marker, startContent, endContent | any SwiftUI view through a `@ViewBuilder` closure | always | empty | `component:Item` | experimental | none |
+| density | `compact`, `balanced`, `spacious` | block padding of spacing 1, 2, 3; inline padding 2, or 3 when spacious | always | `balanced` | `component:Item` | experimental | none |
+| align | `center`, `start`, `firstLine` | slots centered on the words, at their top, or on the label's first line | always | `center` | `component:Item` | experimental | none |
+| layout | `stacked`, `inline` | description under or beside the label | with a description | `stacked` | `component:Item` | experimental | none |
+| control | static, link (`href`), button (`onClick`) | how a tap behaves; the drawing is the same | always | static | `component:swift/Item` | experimental | an `href` that is not an absolute URL is not a link |
+
+## Behavioral and layout contract
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ------------------ |
+| FR1 | The row MUST lay out marker, start content, the words, and end content in that order with a gap of `space.s2`, the words taking the remaining width, inside block padding of `space.s1`, `s2`, or `s3` for `compact`, `balanced`, or `spacious` and inline padding of `space.s2`, or `s3` when spacious. | core `Item` styles | verify |
+| FR2 | The label MUST draw in the body type and `color.textPrimary`, the description in the supporting type and `color.textSecondary`, each limited to `labelLines` or `descriptionLines` lines and truncating after them: one line when unset, and every line for zero, as core's row does. Each line takes the theme's leading, grown with Dynamic Type. With `inline` and a description, the description sits beside the label with a gap of `space.s1` and the label does not shrink; without a description the label keeps its line limit. | core `Item` styles | verify |
+| FR3 | `center` MUST center each slot on the words; `start` MUST put each slot's top on the words' top; `firstLine` MUST center each slot on the label's first line. | core `Item` `align` | verify |
+| FR4 | `isSelected` MUST paint `color.accentMuted` behind the row and `isHighlighted` `color.overlayHover`, with selected winning, in the element radius. `isDisabled` MUST draw the words and the end content at half opacity, as core does; the marker and start content keep their own look. A pressed button or link row paints `color.overlayPressed` above its selected or highlighted fill, as core does. | core `Item` styles | verify |
+| FR5 | With an `href` that is an absolute URL (it has a scheme), the row MUST be a SwiftUI `Link`, and `onClick` does not run. In core the link is the label and a click elsewhere on the row runs `onClick`; a SwiftUI `Link` takes the whole row, so the Swift row has no such area. A script URL (`javascript:`, `vbscript:`) or an HTML document in a `data:` URL MUST leave the row inert, never a link, as core's navigation destinations refuse them (`family:navigation-destinations` FR4). An `href` that is not an absolute URL, such as a web path, MUST stop a development build with a message naming it; a release build draws the row without a link. With only `onClick`, a SwiftUI `Button`. A tappable row is at least 44 points tall; a static row keeps core's height. A disabled link or button stays reachable, reads as dimmed, and does nothing. | Swift component API A4; Swift accessibility X2, X7 | verify |
+| FR6 | Both initializers MUST build the same `ItemProps`. Slots are generic `@ViewBuilder` closures with empty defaults, never `AnyView`; a single trailing closure is the start content and `onClick` comes last. Base props come through `ItemProps`: with `isHidden` the view draws nothing; `id` becomes the accessibility identifier. | Swift component API A2–A4, A7; Swift slots S3 | verify |
+
+### Allowed variation
+
+- **AV1 — Touch height.** A tappable row is at least 44 points tall, which can
+ be taller than core's compact or balanced row.
+- **AV2 — Line metrics.** A line's height comes from the theme's leading over
+ the system font's own line height, so a custom face can differ by a point.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ----------------------------------- | -------------------------------------------------- | ----------------- |
+| each density | core's block and inline padding | none |
+| label and description, both layouts | description under or beside the label | none |
+| each alignment with a tall slot | slots centered, at the top, or on the first line | none |
+| selected, highlighted, disabled | each look from the theme; selected wins | none |
+| static, link, button | the same drawing; tappable rows at least 44 points | AV1 |
+| light and dark, two themes | each theme's colors | none |
+
+### Transformation and precedence order
+
+- **ORD1 — Background.** Selected → highlighted → none.
+- **ORD2 — Control.** `href` (link) → `onClick` (button) → static.
+
+### Performance and resources
+
+- **PR1 — No type erasure.** Slots are generic, so the row adds no `AnyView`
+ boxing.
+
+## Accessibility contract
+
+- **AR1 — One element per row.** A static row is one element whose label reads
+ the slots in order: marker, start content, label, description, end content.
+ A link or button row is one link or button element read the same way
+ (Swift accessibility X5; Swift slots S5).
+- **AR2 — State.** A selected row reads as selected. A disabled row stays in
+ the VoiceOver order and reads as dimmed (X1, X2).
+- **AR3 — Touch target.** A tappable row is at least 44 points tall (X7).
+- **AR4 — Rendered tree not measured.** Tests assert what the view sets; the
+ rendered accessibility tree is not measured until an app-hosted target
+ exists.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | -------------------------------------------------- | ------------------------ | -------------- | ------------------ |
+| Row | Apple Human Interface Guidelines, Lists and tables | prescribed by core | supporting | FR1–FR5 |
+
+The component implements design requirements without copying their rationale.
+
+Platform control: SwiftUI `List` was considered and does not fit: it is a
+scrolling container that owns its rows, while core's Item is a row that sits
+in any container, including a Card, a Section, or a dialog (`spec:AST-093`
+FR2). The row uses SwiftUI `Link` and `Button` for its taps and draws its own
+layout. Guideline pages: Lists and tables, Buttons, and Accessibility in the
+Apple Human Interface Guidelines.
+
+Theme values read: `space.s1`, `space.s2`, `space.s3`, `radius.element`,
+`color.textPrimary`, `color.textSecondary`, `color.accentMuted`,
+`color.overlayHover`, `color.overlayPressed`, the body and supporting type, and Dynamic Type.
+
+## Family and system relationships
+
+- `component:Item` owns the props, the slots, and the row's look; this record
+ states only how Swift draws them.
+- A list owns its rows' markers, dividers, and edges.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| -------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
+| FR1, FR2 | `ItemTests.swift` density, leading, line-limit, and largest-text renders | each density; one and three label lines; the largest text size | wrong padding, leading, or line limit, or a row that does not grow fails | `audit:swift/Item/layout` |
+| FR3 | `ItemTests.swift` alignment renders | `start` and `center` with a description; `firstLine` with a slot taller than one line | a slot off the words' top, middle, or the label's first line fails | `audit:swift/Item/align` |
+| FR4 | `ItemTests.swift` background, two-theme, and disabled renders | selected, highlighted, both; neutral, butter; disabled | a wrong token, highlighted beating selected, or an undimmed disabled row fails | `audit:swift/Item/states` |
+| FR5, AR2 | `ItemTests.swift` touch-height renders; tap, trait, `linkURL`, and refused-destination tests | static, button, link; selected; empty `href`; `javascript:`, `vbscript:`, and `data:text/html` hrefs | a short tappable row, a grown static row, or a missing selected trait fails; a refused destination that becomes a link fails | `audit:swift/Item/control` |
+| FR6 | `ItemTests.swift` initializer, trailing-closure, hidden, and wire-slot tests; `contracts.test.ts` | both initializers; each slot; `isHidden` | differing props, a closure filling the wrong slot, or a drawn hidden row fails; a wire node whose slots do not draw fails | `audit:swift/Item/api` |
+
+## Decision log
+
+### DEC-1 — Swipe actions are web-only for now
+
+**Reference:** `component:swift/Item/DEC-1`
+**Decider:** cixzhang, 2026-10-31
+
+`swipeActions` has no Swift form. SwiftUI's swipe actions work only on rows
+inside a SwiftUI `List`, so an Item anywhere else could not honor them; a
+person on iPhone or Mac uses the row's own action or its end content instead.
+A Swift form waits until a row can honor swipe actions wherever it sits.
+
+## Open questions
+
+None.
+
+## Content boundary
+
+This file does not duplicate consumer prop tables/examples, current audit
+results, implementation steps, or family/system rules. It links to their owners.
diff --git a/packages/native/apple/README.md b/packages/native/apple/README.md
index 41cb10506a..7ad616aa7f 100644
--- a/packages/native/apple/README.md
+++ b/packages/native/apple/README.md
@@ -28,6 +28,7 @@ apple/
│ │ ├── Localization/
│ │ ├── Icon/ # Icon
│ │ ├── Avatar/ # Avatar
+│ │ ├── Item/ # Item
│ │ ├── Text/ # Text
│ │ ├── Heading/ # Heading
│ │ ├── Button/ # Button
diff --git a/packages/native/apple/Sources/Astryx/Avatar/Avatar.swift b/packages/native/apple/Sources/Astryx/Avatar/Avatar.swift
index 40404ab856..1b17fd4ada 100644
--- a/packages/native/apple/Sources/Astryx/Avatar/Avatar.swift
+++ b/packages/native/apple/Sources/Astryx/Avatar/Avatar.swift
@@ -77,10 +77,7 @@ public struct Avatar<Status: View>: View {
/// the build with its value, and an unnamed link or button is flagged.
private func checkInDevelopment() {
#if DEBUG
- if Avatar.isUnusableHref(props.href) {
- assertionFailure(
- "Avatar href \"\(props.href ?? "")\" is not an absolute URL an app can open; it draws without a link.")
- }
+ astryxCheckHref(props.href, in: "Avatar")
// The avatar's own name: a status label alone does not name a person.
let ownName = Avatar.meaningful(props.alt) ?? Avatar.meaningful(props.name)
if Avatar.needsNameWarning(tap: tap, isNamed: ownName != nil) {
@@ -108,11 +105,7 @@ public struct Avatar<Status: View>: View {
}
/// A non-empty `href` that is not an absolute URL, such as a web path.
- nonisolated static func isUnusableHref(_ href: String?) -> Bool {
- guard let href, !href.isEmpty else { return false }
- guard let url = URL(string: href) else { return true }
- return url.scheme == nil
- }
+ nonisolated static func isUnusableHref(_ href: String?) -> Bool { astryxIsUnusableHref(href) }
/// The picture as a link with `href`, a button with only `onClick`, or a
/// static image (Swift component API, A4). All three draw the same.
diff --git a/packages/native/apple/Sources/Astryx/Base/SafeDestination.swift b/packages/native/apple/Sources/Astryx/Base/SafeDestination.swift
new file mode 100644
index 0000000000..aa46576701
--- /dev/null
+++ b/packages/native/apple/Sources/Astryx/Base/SafeDestination.swift
@@ -0,0 +1,48 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import Foundation
+
+/// An `href` as a link reads it: control characters removed and surrounding
+/// whitespace trimmed, as core's shared destination rule does.
+func astryxNormalizedHref(_ href: String) -> String {
+ String(String.UnicodeScalarView(
+ href.unicodeScalars.filter { $0.value > 0x1F && $0.value != 0x7F }
+ )).trimmingCharacters(in: .whitespacesAndNewlines)
+}
+
+/// A destination a link may open, normalized as core's shared rule does, or
+/// nil for a script URL or an HTML document in a `data:` URL, which core's
+/// navigation destinations refuse (`family:navigation-destinations` FR4).
+/// The scheme is compared in lowercase without the spaces after its colon,
+/// which a data URL's media type ignores (`data: text/html` is HTML).
+func astryxSafeDestination(_ href: String) -> String? {
+ let normalized = astryxNormalizedHref(href)
+ var comparable = normalized.lowercased()
+ if let colon = comparable.firstIndex(of: ":"),
+ comparable[..<colon].range(of: "^[a-z][a-z0-9+.-]*$", options: .regularExpression) != nil {
+ let rest = comparable[comparable.index(after: colon)...].drop { $0 == " " }
+ comparable = String(comparable[...colon]) + rest
+ }
+ for blocked in ["javascript:", "vbscript:", "data:text/html"] where comparable.hasPrefix(blocked) {
+ return nil
+ }
+ return normalized
+}
+
+/// A non-empty `href` that is not an absolute URL, such as a web path. Pass
+/// the `href` as the view's link reads it, so the check and the link agree.
+func astryxIsUnusableHref(_ href: String?) -> Bool {
+ guard let href, !href.isEmpty else { return false }
+ guard let url = URL(string: href) else { return true }
+ return url.scheme == nil
+}
+
+/// Stops a development build on an `href` an app cannot open, naming the
+/// component and the value; a release build draws the view without a link.
+func astryxCheckHref(_ href: String?, in component: String) {
+ #if DEBUG
+ if astryxIsUnusableHref(href) {
+ assertionFailure("\(component) href \"\(href ?? "")\" is not an absolute URL an app can open; it draws without a link.")
+ }
+ #endif
+}
diff --git a/packages/native/apple/Sources/Astryx/Button/Button.swift b/packages/native/apple/Sources/Astryx/Button/Button.swift
index ad73329a66..6f25cba836 100644
--- a/packages/native/apple/Sources/Astryx/Button/Button.swift
+++ b/packages/native/apple/Sources/Astryx/Button/Button.swift
@@ -82,27 +82,9 @@ public struct Button: View {
/// disabled button, as core draws a disabled `<button>`.
var link: URL? { isDisabled ? nil : destination }
- /// A destination a link may open, normalized as core's shared rule does, or
- /// nil for a script URL or an HTML document in a `data:` URL, which core's
- /// navigation destinations refuse (`family:navigation-destinations` FR4).
- /// Control characters are removed and whitespace trimmed; the scheme is
- /// compared in lowercase without the spaces after its colon, which a data
- /// URL's media type ignores (`data: text/html` is HTML).
- nonisolated static func safeDestination(_ href: String) -> String? {
- let normalized = String(String.UnicodeScalarView(
- href.unicodeScalars.filter { $0.value > 0x1F && $0.value != 0x7F }
- )).trimmingCharacters(in: .whitespacesAndNewlines)
- var comparable = normalized.lowercased()
- if let colon = comparable.firstIndex(of: ":"),
- comparable[..<colon].range(of: "^[a-z][a-z0-9+.-]*$", options: .regularExpression) != nil {
- let rest = comparable[comparable.index(after: colon)...].drop { $0 == " " }
- comparable = String(comparable[...colon]) + rest
- }
- for blocked in ["javascript:", "vbscript:", "data:text/html"] where comparable.hasPrefix(blocked) {
- return nil
- }
- return normalized
- }
+ /// A destination a link may open, or nil when core's navigation
+ /// destinations refuse it (`astryxSafeDestination`).
+ nonisolated static func safeDestination(_ href: String) -> String? { astryxSafeDestination(href) }
public var body: some View {
control
diff --git a/packages/native/apple/Sources/Astryx/Item/Item.swift b/packages/native/apple/Sources/Astryx/Item/Item.swift
new file mode 100644
index 0000000000..2813be44ab
--- /dev/null
+++ b/packages/native/apple/Sources/Astryx/Item/Item.swift
@@ -0,0 +1,354 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import AstryxNative
+import SwiftUI
+
+#if canImport(UIKit)
+import UIKit
+#elseif canImport(AppKit)
+import AppKit
+#endif
+
+/// A row: optional marker and leading content, a label with an optional
+/// description, and optional trailing content (core `Item`). With `onClick`
+/// it is a button and with `href` a link; either way it draws the same row.
+///
+/// ```swift
+/// Item("Ada Lovelace", description: "Mathematician") {
+/// Icon(.check)
+/// } endContent: {
+/// Icon(.chevronRight, color: .secondary)
+/// }
+/// Item("Notifications", onClick: openNotifications)
+/// Item("Archive") { Icon(.upload) } onClick: { archive() }
+/// ```
+public struct Item<Marker: View, StartContent: View, EndContent: View>: View {
+ /// The contract the view draws, the same for every initializer.
+ public let props: ItemProps
+ let marker: Marker
+ let startContent: StartContent
+ let endContent: EndContent
+ @Environment(\.astryx) private var astryx
+
+ /// A row from its labeled props. A single trailing closure is the start
+ /// content; set `onClick` by label or as a trailing `onClick:` closure.
+ /// - Parameters:
+ /// - label: The row's main words (core `label`).
+ /// - description: Supporting words under or beside the label (core `description`).
+ /// - align: How the start and end content line up with the words: `center`, `start`, or `firstLine`; `nil` is `center` (core `align`).
+ /// - density: `compact`, `balanced`, or `spacious` padding; `nil` is `balanced` (core `density`).
+ /// - labelLines: Lines the label may take before it truncates; `nil` is one (core `labelLines`).
+ /// - descriptionLines: Lines the description may take before it truncates; `nil` is one (core `descriptionLines`).
+ /// - layout: `stacked` puts the description under the label, `inline` beside it; `nil` is `stacked` (core `layout`).
+ /// - href: A URL the system opens when the row is tapped; the row becomes a link and `onClick` does not run (core `href`).
+ /// - isHighlighted: Draws the row's highlighted background (core `isHighlighted`).
+ /// - isSelected: Draws the row as selected and reads it as selected (core `isSelected`).
+ /// - isDisabled: Dims the row; a button or link row stays reachable and does nothing (core `isDisabled`).
+ /// - startContent: Content before the words: an `Icon`, an `Avatar`, or a checkbox (core `startContent`).
+ /// - endContent: Content after the words, such as a badge, a value, or an icon (core `endContent`).
+ /// - marker: A list marker before the start content; pass every slot by label when you set it (core `marker`).
+ /// - onClick: Runs when the row is tapped; the row becomes a button when it has no `href` (core `onClick`).
+ public init(
+ _ label: String,
+ description: String? = nil,
+ align: ItemAlign? = nil,
+ density: ItemDensity? = nil,
+ labelLines: Double? = nil,
+ descriptionLines: Double? = nil,
+ layout: ItemLayout? = nil,
+ href: String? = nil,
+ isHighlighted: Bool? = nil,
+ isSelected: Bool? = nil,
+ isDisabled: Bool? = nil,
+ @ViewBuilder startContent: () -> StartContent = { EmptyView() },
+ @ViewBuilder endContent: () -> EndContent = { EmptyView() },
+ @ViewBuilder marker: () -> Marker = { EmptyView() },
+ onClick: (() -> Void)? = nil
+ ) {
+ self.init(
+ ItemProps(
+ label: label, description: description, align: align, density: density, labelLines: labelLines,
+ descriptionLines: descriptionLines, layout: layout, onClick: onClick, href: href,
+ isHighlighted: isHighlighted, isSelected: isSelected, isDisabled: isDisabled
+ ),
+ startContent: startContent, endContent: endContent, marker: marker
+ )
+ }
+
+ /// A row from its generated contract, for generated and wire-driven callers.
+ public init(
+ _ props: ItemProps,
+ @ViewBuilder startContent: () -> StartContent = { EmptyView() },
+ @ViewBuilder endContent: () -> EndContent = { EmptyView() },
+ @ViewBuilder marker: () -> Marker = { EmptyView() }
+ ) {
+ self.props = props
+ self.marker = marker()
+ self.startContent = startContent()
+ self.endContent = endContent()
+ }
+
+ public var body: some View {
+ control
+ .onAppear(perform: checkInDevelopment)
+ .astryxBase(props.base)
+ }
+
+ /// An `href` an app cannot open, such as a web path, stops a development
+ /// build with its value; a release build draws the row without a link.
+ private func checkInDevelopment() {
+ astryxCheckHref(props.href.map(astryxNormalizedHref), in: "Item")
+ }
+
+ /// A non-empty `href` that is not an absolute URL, read as the row's link
+ /// reads it (trimmed, control characters removed).
+ nonisolated static func isUnusableHref(_ href: String?) -> Bool {
+ astryxIsUnusableHref(href.map(astryxNormalizedHref))
+ }
+
+ /// The row as a link with `href`, a button with only `onClick`, or static
+ /// (Swift component API, A4). All three draw the same row.
+ @ViewBuilder private var control: some View {
+ if let url = linkURL {
+ SwiftUI.Link(destination: url) { row(minHeight: Item.minimumTarget, paintsFill: false) }
+ .buttonStyle(pressStyle)
+ .disabled(isDisabled)
+ .modifier(ItemAccessibility(isSelected: isSelected))
+ } else if let onClick = props.onClick {
+ SwiftUI.Button(action: onClick) { row(minHeight: Item.minimumTarget, paintsFill: false) }
+ .buttonStyle(pressStyle)
+ .disabled(isDisabled)
+ .modifier(ItemAccessibility(isSelected: isSelected))
+ } else {
+ row(minHeight: nil, paintsFill: true)
+ .accessibilityElement(children: .combine)
+ // A disabled row reads as dimmed, as core marks it aria-disabled.
+ .disabled(isDisabled)
+ .modifier(ItemAccessibility(isSelected: isSelected))
+ }
+ }
+
+ /// A link or button row's fill and its press, painted by the button style
+ /// so the press sits above a selected or highlighted fill, as core's does.
+ private var pressStyle: ItemPressStyle {
+ ItemPressStyle(radius: astryx.tokens.radius.element, fill: background, pressed: astryx.tokens.color.overlayPressed)
+ }
+
+ /// The row's drawing; a tappable row is at least `minHeight` tall. A static
+ /// row paints its own fill; a link or button row's style paints it.
+ private func row(minHeight: CGFloat?, paintsFill: Bool) -> some View {
+ HStack(alignment: rowAlignment, spacing: astryx.tokens.space.s2) {
+ slot(marker)
+ slot(startContent)
+ // A disabled row dims its words and end content, as core does; the
+ // marker and start content keep their own look (a checkbox shows its
+ // own disabled state).
+ words
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .opacity(isDisabled ? 0.5 : 1)
+ slot(endContent)
+ .opacity(isDisabled ? 0.5 : 1)
+ }
+ .padding(.horizontal, inlinePadding)
+ .padding(.vertical, blockPadding)
+ .frame(maxWidth: .infinity, minHeight: minHeight, alignment: .leading)
+ .background(
+ RoundedRectangle(cornerRadius: astryx.tokens.radius.element, style: .continuous)
+ .fill(paintsFill ? background ?? .clear : .clear)
+ )
+ .contentShape(Rectangle())
+ }
+
+ /// A slot's content. For `firstLine`, its center sits on the center of
+ /// the label's first line box, however tall the slot is.
+ @ViewBuilder private func slot<Content: View>(_ content: Content) -> some View {
+ if resolvedAlign == .firstLine {
+ let lineCenterAboveBaseline = firstLineCenterAboveBaseline
+ content.alignmentGuide(.firstTextBaseline) { d in d.height / 2 + lineCenterAboveBaseline }
+ } else {
+ content
+ }
+ }
+
+ @ViewBuilder private var words: some View {
+ let label = SwiftUI.Text(props.label)
+ .font(astryx.font(size: "text-body-size", 14, weight: "text-body-weight"))
+ .foregroundStyle(astryx.tokens.color.textPrimary)
+ .lineLimit(Item.lines(props.labelLines))
+ .modifier(ItemLeading(extra: extraLeading(astryx.tokens.font.body.leading, size: astryx.tokens.font.body.size)))
+ let description = props.description.map { words in
+ SwiftUI.Text(words)
+ .font(astryx.font(size: "text-supporting-size", 12, weight: "text-supporting-weight"))
+ .foregroundStyle(astryx.tokens.color.textSecondary)
+ .lineLimit(Item.lines(props.descriptionLines))
+ .modifier(
+ ItemLeading(extra: extraLeading(astryx.tokens.font.supporting.leading, size: astryx.tokens.font.supporting.size)))
+ }
+ // Inline only with a description, as core's: a label alone keeps its
+ // width limit and truncates.
+ if (props.layout ?? .stacked) == .inline, description != nil {
+ HStack(alignment: .firstTextBaseline, spacing: astryx.tokens.space.s1) {
+ label.fixedSize(horizontal: true, vertical: false)
+ description
+ }
+ } else {
+ VStack(alignment: .leading, spacing: 0) {
+ label
+ description
+ }
+ }
+ }
+
+ var resolvedAlign: ItemAlign { props.align ?? .center }
+
+ private var rowAlignment: VerticalAlignment {
+ switch resolvedAlign {
+ case .center: .center
+ case .start: .top
+ case .firstLine: .firstTextBaseline
+ }
+ }
+
+ /// How far the center of the label's first line sits above its baseline:
+ /// half the font's line height above the line's bottom, less the descent,
+ /// in the font's own metrics at the current text size. The theme's extra
+ /// leading is split evenly above and below, so it does not move the center.
+ var firstLineCenterAboveBaseline: CGFloat {
+ let metrics = astryxSystemFontMetrics(astryx.tokens.font.body.size)
+ return (metrics.ascender - metrics.lineHeight / 2) * astryx.textScale
+ }
+
+ var isDisabled: Bool { props.isDisabled == true }
+ var isSelected: Bool { props.isSelected == true }
+
+ /// Selected wins over highlighted, as core's styles order them.
+ var background: Color? {
+ if isSelected { return astryx.tokens.color.accentMuted }
+ if props.isHighlighted == true { return astryx.tokens.color.overlayHover }
+ return nil
+ }
+
+ /// Block padding per density: spacing 1, 2, or 3.
+ var blockPadding: CGFloat {
+ switch props.density ?? .balanced {
+ case .compact: astryx.tokens.space.s1
+ case .balanced: astryx.tokens.space.s2
+ case .spacious: astryx.tokens.space.s3
+ }
+ }
+
+ /// Inline padding: spacing 2, or 3 when spacious.
+ var inlinePadding: CGFloat {
+ (props.density ?? .balanced) == .spacious ? astryx.tokens.space.s3 : astryx.tokens.space.s2
+ }
+
+ /// The space core's line height adds to the font's own line, grown with
+ /// Dynamic Type, so a line takes the theme's leading as on the web. The
+ /// leading tokens are unitless line heights, as in CSS.
+ private func extraLeading(_ leading: CGFloat, size: CGFloat) -> CGFloat {
+ max(0, leading * size - astryxSystemLineHeight(size)) * astryx.textScale
+ }
+
+ /// The URL the row opens, or `nil` when it has no usable `href`.
+ var linkURL: URL? {
+ // Only an absolute URL the system can open, and never one core's
+ // navigation destinations refuse (a script URL or an HTML `data:` URL);
+ // a malformed, relative, or refused `href` leaves the row static or a
+ // button.
+ guard let href = props.href, let safe = astryxSafeDestination(href), !safe.isEmpty,
+ let url = URL(string: safe), url.scheme != nil
+ else { return nil }
+ return url
+ }
+
+ /// How the row takes a tap: a link with a usable `href`, else a button
+ /// with `onClick`, else none.
+ enum Tap: Equatable { case link, button, none }
+
+ var tap: Tap {
+ if linkURL != nil { return .link }
+ if props.onClick != nil { return .button }
+ return .none
+ }
+
+ /// The traits the row adds to what its control already carries: selected
+ /// when selected. A link or button keeps its own trait (X1).
+ nonisolated static func addedTraits(isSelected: Bool) -> AccessibilityTraits {
+ isSelected ? .isSelected : []
+ }
+
+ /// A tappable row is at least 44 points tall (Swift accessibility, X7).
+ static var minimumTarget: CGFloat { 44 }
+
+ /// The line limit for `labelLines` or `descriptionLines`: one when unset,
+ /// as core's row truncates a label to one line by default, and otherwise
+ /// core's shared count (`astryxLineLimit`), so zero shows every line.
+ nonisolated static func lines(_ value: Double?) -> Int? { astryxLineLimit(value ?? 1) }
+}
+
+/// Paints a link or button row's fill and, while pressed, the pressed
+/// overlay above it, as core's interactive rows do.
+struct ItemPressStyle: ButtonStyle {
+ let radius: CGFloat
+ /// The selected or highlighted fill, if any.
+ let fill: Color?
+ let pressed: Color
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .background(ItemPressBackground(radius: radius, fill: fill, pressed: pressed, isPressed: configuration.isPressed))
+ }
+}
+
+/// The fill with the press above it.
+struct ItemPressBackground: View {
+ let radius: CGFloat
+ let fill: Color?
+ let pressed: Color
+ let isPressed: Bool
+
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: radius, style: .continuous)
+ ZStack {
+ shape.fill(fill ?? .clear)
+ shape.fill(isPressed ? pressed : .clear)
+ }
+ }
+}
+
+/// Spreads the extra leading between lines and half above and below, as a
+/// CSS line height does.
+private struct ItemLeading: ViewModifier {
+ let extra: CGFloat
+
+ func body(content: Content) -> some View {
+ content.lineSpacing(extra).padding(.vertical, extra / 2)
+ }
+}
+
+/// The system font's own line height at a size.
+func astryxSystemLineHeight(_ size: CGFloat) -> CGFloat {
+ astryxSystemFontMetrics(size).lineHeight
+}
+
+/// The system font's ascender and line height at a size.
+func astryxSystemFontMetrics(_ size: CGFloat) -> (ascender: CGFloat, lineHeight: CGFloat) {
+ #if canImport(UIKit)
+ let font = UIFont.systemFont(ofSize: size)
+ return (font.ascender, font.lineHeight)
+ #elseif canImport(AppKit)
+ let font = NSFont.systemFont(ofSize: size)
+ return (font.ascender, font.ascender - font.descender + font.leading)
+ #else
+ return (size * 0.95, size * 1.2)
+ #endif
+}
+
+/// A selected row reads as selected (Swift accessibility, X1).
+private struct ItemAccessibility: ViewModifier {
+ let isSelected: Bool
+
+ func body(content: Content) -> some View {
+ content.accessibilityAddTraits(Item<EmptyView, EmptyView, EmptyView>.addedTraits(isSelected: isSelected))
+ }
+}
diff --git a/packages/native/apple/Sources/Astryx/Wire/AstryxNodeView.swift b/packages/native/apple/Sources/Astryx/Wire/AstryxNodeView.swift
index 7b65ddc7dd..ffa26ea39b 100644
--- a/packages/native/apple/Sources/Astryx/Wire/AstryxNodeView.swift
+++ b/packages/native/apple/Sources/Astryx/Wire/AstryxNodeView.swift
@@ -25,6 +25,14 @@ public struct AstryxNodeView: View {
Avatar(avatar.viewProps(send: send)) { AstryxNodeList(nodes: avatar.props.status ?? [], send: send) }
case .avatarStatusDot(let dot): AvatarStatusDot(dot.viewProps(send: send))
case .thumbnail(let thumbnail): Thumbnail(thumbnail.viewProps(send: send))
+ case .item(let item):
+ Item(item.viewProps(send: send)) {
+ AstryxNodeList(nodes: item.props.startContent ?? [], send: send)
+ } endContent: {
+ AstryxNodeList(nodes: item.props.endContent ?? [], send: send)
+ } marker: {
+ AstryxNodeList(nodes: item.props.marker ?? [], send: send)
+ }
default: AstryxUnsupportedNode(component: Self.componentName(node))
}
}
@@ -41,6 +49,7 @@ public struct AstryxNodeView: View {
case .heading: "Heading"
case .hStack: "HStack"
case .icon: "Icon"
+ case .item: "Item"
case .progressBar: "ProgressBar"
case .selector: "Selector"
case .switch: "Switch"
diff --git a/packages/native/apple/Sources/AstryxNative/Generated/AstryxNode.swift b/packages/native/apple/Sources/AstryxNative/Generated/AstryxNode.swift
index 2c025079fd..eeddd55bc8 100644
--- a/packages/native/apple/Sources/AstryxNative/Generated/AstryxNode.swift
+++ b/packages/native/apple/Sources/AstryxNative/Generated/AstryxNode.swift
@@ -16,6 +16,7 @@ public enum AstryxNode: Decodable, Equatable, Sendable {
case heading(HeadingNode)
case hStack(HStackNode)
case icon(IconNode)
+ case item(ItemNode)
case progressBar(ProgressBarNode)
case selector(SelectorNode)
case `switch`(SwitchNode)
@@ -36,6 +37,7 @@ public enum AstryxNode: Decodable, Equatable, Sendable {
case .heading(let node): return node.key
case .hStack(let node): return node.key
case .icon(let node): return node.key
+ case .item(let node): return node.key
case .progressBar(let node): return node.key
case .selector(let node): return node.key
case .`switch`(let node): return node.key
@@ -64,6 +66,7 @@ public enum AstryxNode: Decodable, Equatable, Sendable {
case "Heading": self = .heading(try HeadingNode(from: decoder))
case "HStack": self = .hStack(try HStackNode(from: decoder))
case "Icon": self = .icon(try IconNode(from: decoder))
+ case "Item": self = .item(try ItemNode(from: decoder))
case "ProgressBar": self = .progressBar(try ProgressBarNode(from: decoder))
case "Selector": self = .selector(try SelectorNode(from: decoder))
case "Switch": self = .`switch`(try SwitchNode(from: decoder))
diff --git a/packages/native/apple/Sources/AstryxNative/Generated/Item.swift b/packages/native/apple/Sources/AstryxNative/Generated/Item.swift
new file mode 100644
index 0000000000..04ba079bfb
--- /dev/null
+++ b/packages/native/apple/Sources/AstryxNative/Generated/Item.swift
@@ -0,0 +1,173 @@
+// Generated by @astryxdesign/native. Do not edit.
+public enum ItemAlign: String, CaseIterable, Codable, Sendable {
+ case center = "center"
+ case start = "start"
+ case firstLine = "first-line"
+}
+public enum ItemDensity: String, CaseIterable, Codable, Sendable {
+ case compact = "compact"
+ case balanced = "balanced"
+ case spacious = "spacious"
+}
+public enum ItemLayout: String, CaseIterable, Codable, Sendable {
+ case stacked = "stacked"
+ case inline = "inline"
+}
+#if os(iOS)
+public struct ItemProps {
+ /// Base props attach to this part on every platform.
+ public static let baseTarget: AstryxBaseTarget = .root
+ public var base: AstryxBaseProps
+ public var label: String
+ public var description: String?
+ public var align: ItemAlign?
+ public var density: ItemDensity?
+ public var labelLines: Double?
+ public var descriptionLines: Double?
+ public var layout: ItemLayout?
+ public var onClick: (() -> Void)?
+ public var href: String?
+ public var isHighlighted: Bool?
+ public var isSelected: Bool?
+ public var isDisabled: Bool?
+ public init(label: String, description: String? = nil, align: ItemAlign? = nil, density: ItemDensity? = nil, labelLines: Double? = nil, descriptionLines: Double? = nil, layout: ItemLayout? = nil, onClick: (() -> Void)? = nil, href: String? = nil, isHighlighted: Bool? = nil, isSelected: Bool? = nil, isDisabled: Bool? = nil, base: AstryxBaseProps = AstryxBaseProps()) {
+ self.label = label
+ self.description = description
+ self.align = align
+ self.density = density
+ self.labelLines = labelLines
+ self.descriptionLines = descriptionLines
+ self.layout = layout
+ self.onClick = onClick
+ self.href = href
+ self.isHighlighted = isHighlighted
+ self.isSelected = isSelected
+ self.isDisabled = isDisabled
+ self.base = base
+ }
+}
+public struct ItemNode: Decodable, Equatable, Sendable {
+ public struct Props: Decodable, Equatable, Sendable {
+ public var label: String
+ public var marker: [AstryxNode]?
+ public var startContent: [AstryxNode]?
+ public var description: String?
+ public var endContent: [AstryxNode]?
+ public var align: ItemAlign?
+ public var density: ItemDensity?
+ public var labelLines: Double?
+ public var descriptionLines: Double?
+ public var layout: ItemLayout?
+ public var href: String?
+ public var isHighlighted: Bool?
+ public var isSelected: Bool?
+ public var isDisabled: Bool?
+ }
+ public let key: String
+ public let base: AstryxBaseProps?
+ public let props: Props
+ /// The callbacks the core listens to, by prop name.
+ public let events: [String]?
+
+ public func listens(_ event: String) -> Bool { events?.contains(event) ?? false }
+
+ /// The contract a Item view takes; its callbacks send actions to the core.
+ public func viewProps(send: @escaping @Sendable (AstryxAction) -> Void) -> ItemProps {
+ let key = self.key
+ return ItemProps(
+ label: props.label,
+ description: props.description,
+ align: props.align,
+ density: props.density,
+ labelLines: props.labelLines,
+ descriptionLines: props.descriptionLines,
+ layout: props.layout,
+ onClick: listens("onClick") ? { send(AstryxAction(key: key, component: "Item", event: "onClick", args: [])) } : nil,
+ href: props.href,
+ isHighlighted: props.isHighlighted,
+ isSelected: props.isSelected,
+ isDisabled: props.isDisabled,
+ base: base ?? AstryxBaseProps()
+ )
+ }
+}
+#endif
+#if os(macOS)
+public struct ItemProps {
+ /// Base props attach to this part on every platform.
+ public static let baseTarget: AstryxBaseTarget = .root
+ public var base: AstryxBaseProps
+ public var label: String
+ public var description: String?
+ public var align: ItemAlign?
+ public var density: ItemDensity?
+ public var labelLines: Double?
+ public var descriptionLines: Double?
+ public var layout: ItemLayout?
+ public var onClick: (() -> Void)?
+ public var href: String?
+ public var isHighlighted: Bool?
+ public var isSelected: Bool?
+ public var isDisabled: Bool?
+ public init(label: String, description: String? = nil, align: ItemAlign? = nil, density: ItemDensity? = nil, labelLines: Double? = nil, descriptionLines: Double? = nil, layout: ItemLayout? = nil, onClick: (() -> Void)? = nil, href: String? = nil, isHighlighted: Bool? = nil, isSelected: Bool? = nil, isDisabled: Bool? = nil, base: AstryxBaseProps = AstryxBaseProps()) {
+ self.label = label
+ self.description = description
+ self.align = align
+ self.density = density
+ self.labelLines = labelLines
+ self.descriptionLines = descriptionLines
+ self.layout = layout
+ self.onClick = onClick
+ self.href = href
+ self.isHighlighted = isHighlighted
+ self.isSelected = isSelected
+ self.isDisabled = isDisabled
+ self.base = base
+ }
+}
+public struct ItemNode: Decodable, Equatable, Sendable {
+ public struct Props: Decodable, Equatable, Sendable {
+ public var label: String
+ public var marker: [AstryxNode]?
+ public var startContent: [AstryxNode]?
+ public var description: String?
+ public var endContent: [AstryxNode]?
+ public var align: ItemAlign?
+ public var density: ItemDensity?
+ public var labelLines: Double?
+ public var descriptionLines: Double?
+ public var layout: ItemLayout?
+ public var href: String?
+ public var isHighlighted: Bool?
+ public var isSelected: Bool?
+ public var isDisabled: Bool?
+ }
+ public let key: String
+ public let base: AstryxBaseProps?
+ public let props: Props
+ /// The callbacks the core listens to, by prop name.
+ public let events: [String]?
+
+ public func listens(_ event: String) -> Bool { events?.contains(event) ?? false }
+
+ /// The contract a Item view takes; its callbacks send actions to the core.
+ public func viewProps(send: @escaping @Sendable (AstryxAction) -> Void) -> ItemProps {
+ let key = self.key
+ return ItemProps(
+ label: props.label,
+ description: props.description,
+ align: props.align,
+ density: props.density,
+ labelLines: props.labelLines,
+ descriptionLines: props.descriptionLines,
+ layout: props.layout,
+ onClick: listens("onClick") ? { send(AstryxAction(key: key, component: "Item", event: "onClick", args: [])) } : nil,
+ href: props.href,
+ isHighlighted: props.isHighlighted,
+ isSelected: props.isSelected,
+ isDisabled: props.isDisabled,
+ base: base ?? AstryxBaseProps()
+ )
+ }
+}
+#endif
diff --git a/packages/native/apple/Tests/AstryxTests/ItemTests.swift b/packages/native/apple/Tests/AstryxTests/ItemTests.swift
new file mode 100644
index 0000000000..37e3fc32f6
--- /dev/null
+++ b/packages/native/apple/Tests/AstryxTests/ItemTests.swift
@@ -0,0 +1,295 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import AstryxNative
+import SwiftUI
+import Testing
+@testable import Astryx
+
+// Swift Item spec (component:swift/Item): core's row, its slots in reading
+// order, density, alignment, and states, drawn the same static, as a button,
+// or as a link.
+
+@MainActor
+@Test func trailingClosuresFillTheSlotsTheyName() {
+ let start = Item("Ada") { Color.red }
+ let both = Item("Ada") { Color.red } endContent: { Color.blue }
+ let end = Item("Ada", endContent: { Color.blue })
+ let pressable = Item("Settings", onClick: {})
+ let trailingPress = Item("Archive") { Color.red } onClick: {}
+ #expect(type(of: start) == Item<EmptyView, Color, EmptyView>.self)
+ #expect(type(of: both) == Item<EmptyView, Color, Color>.self)
+ #expect(type(of: end) == Item<EmptyView, EmptyView, Color>.self)
+ #expect(type(of: pressable) == Item<EmptyView, EmptyView, EmptyView>.self)
+ #expect(pressable.props.onClick != nil)
+ #expect(type(of: trailingPress) == Item<EmptyView, Color, EmptyView>.self)
+ #expect(trailingPress.props.onClick != nil)
+}
+
+@MainActor
+@Test func itemInitializersBuildTheSameProps() {
+ let labeled = Item(
+ "Ada", description: "Mathematician", align: .firstLine, density: .spacious, labelLines: 2,
+ descriptionLines: 3, layout: .inline, href: "https://example.com", isHighlighted: true, isSelected: true,
+ isDisabled: true
+ ).props
+ let fromProps = Item(
+ ItemProps(
+ label: "Ada", description: "Mathematician", align: .firstLine, density: .spacious, labelLines: 2,
+ descriptionLines: 3, layout: .inline, href: "https://example.com", isHighlighted: true, isSelected: true,
+ isDisabled: true)
+ ).props
+ #expect(labeled.label == fromProps.label)
+ #expect(labeled.description == fromProps.description)
+ #expect(labeled.align == fromProps.align)
+ #expect(labeled.density == fromProps.density)
+ #expect(labeled.labelLines == fromProps.labelLines)
+ #expect(labeled.descriptionLines == fromProps.descriptionLines)
+ #expect(labeled.layout == fromProps.layout)
+ #expect(labeled.href == fromProps.href)
+ #expect(labeled.isHighlighted == fromProps.isHighlighted)
+ #expect(labeled.isSelected == fromProps.isSelected)
+ #expect(labeled.isDisabled == fromProps.isDisabled)
+ #expect(labeled.base == fromProps.base)
+}
+
+@MainActor
+@Test func densityAddsCoresBlockPadding() {
+ let tokens = Theme.default.light.space
+ let compact = Pixels(Item("Ada", density: .compact).frame(width: 240))
+ let balanced = Pixels(Item("Ada").frame(width: 240))
+ let spacious = Pixels(Item("Ada", density: .spacious).frame(width: 240))
+ #expect(balanced.height - compact.height == Int(2 * (tokens.s2 - tokens.s1)))
+ #expect(spacious.height - balanced.height == Int(2 * (tokens.s3 - tokens.s2)))
+}
+
+@MainActor
+@Test func aTappableRowIsAtLeast44PointsTallAndAStaticOneKeepsCoresHeight() {
+ let still = Pixels(Item("Ada", density: .compact).frame(width: 240))
+ let button = Pixels(Item("Ada", density: .compact, onClick: {}).frame(width: 240))
+ let link = Pixels(Item("Ada", density: .compact, href: "https://example.com").frame(width: 240))
+ #expect(still.height < 44)
+ #expect(button.height == 44)
+ #expect(link.height == 44)
+}
+
+@MainActor
+@Test func selectedWinsOverHighlightedAndBothUseTheTheme() {
+ let accentMuted = rgba(Theme.default.light.color.accentMuted)
+ let overlay = rgba(Theme.default.light.color.overlayHover)
+ let selected = Pixels(Item("Ada", isHighlighted: true, isSelected: true).frame(width: 240).background(Color.white))
+ let highlighted = Pixels(Item("Ada", isHighlighted: true).frame(width: 240).background(Color.white))
+ let plain = Pixels(Item("Ada").frame(width: 240).background(Color.white))
+ let x = 230, y = 10
+ #expect(close(selected.at(x, y), onWhite(accentMuted), within: 3))
+ #expect(close(highlighted.at(x, y), onWhite(overlay), within: 3))
+ #expect(close(plain.at(x, y), [255, 255, 255, 255], within: 1))
+}
+
+@MainActor
+@Test func anItemRendersFromTwoThemesWithNoColorOfItsOwn() {
+ let view = Item("Ada", isSelected: true).frame(width: 240).background(Color.white)
+ let neutral = Pixels(view, theme: .neutral).at(230, 10)
+ let butter = Pixels(view, theme: .butter).at(230, 10)
+ #expect(close(neutral, onWhite(rgba(Theme.neutral.light.color.accentMuted)), within: 3))
+ #expect(close(butter, onWhite(rgba(Theme.butter.light.color.accentMuted)), within: 3))
+}
+
+@MainActor
+@Test func aDisabledRowDimsItsWordsAndEndContentNotItsStartContent() {
+ let red = [255, 0, 0, 255]
+ let swatch = { Color(red: 1, green: 0, blue: 0).frame(width: 12, height: 12) }
+ let start = Pixels(Item("Ada", isDisabled: true, startContent: swatch).frame(width: 240))
+ let end = Pixels(Item("Ada", isDisabled: true, endContent: swatch).frame(width: 240))
+ let enabledEnd = Pixels(Item("Ada", endContent: swatch).frame(width: 240))
+ #expect(start.contains { close($0, red) })
+ #expect(!end.contains { close($0, red) })
+ #expect(enabledEnd.contains { close($0, red) })
+}
+
+@MainActor
+@Test func alignPlacesTheSlotsOnTheWords() {
+ let tokens = Theme.default.light
+ let marker = { Color(red: 1, green: 0, blue: 0).frame(width: 8, height: 8) }
+ let start = Pixels(Item("Ada", description: "Mathematician", align: .start, startContent: marker).frame(width: 240))
+ let centered = Pixels(Item("Ada", description: "Mathematician", startContent: marker).frame(width: 240))
+ let red = [255, 0, 0, 255]
+ let x = Int(tokens.space.s2) + 4
+ // `start`: the slot's top is on the row's top padding.
+ #expect(close(start.at(x, Int(tokens.space.s2) + 1), red))
+ #expect(!close(start.at(x, start.height / 2 + 6), red))
+ // `center`: the slot sits in the middle of the row.
+ #expect(close(centered.at(x, centered.height / 2), red))
+}
+
+@MainActor
+@Test func aLineTakesTheThemesLeading() {
+ let tokens = Theme.default.light
+ let row = Pixels(Item("Ada", density: .compact).frame(width: 240))
+ #expect(abs(row.height - Int((2 * tokens.space.s1 + tokens.font.body.leading * tokens.font.body.size).rounded())) <= 1)
+}
+
+@MainActor
+@Test func firstLineCentersATallSlotOnTheLabelsFirstLine() {
+ let red = [255, 0, 0, 255]
+ let tall = { Color(red: 1, green: 0, blue: 0).frame(width: 10, height: 40) }
+ func slotCenter(_ p: Pixels) -> Double {
+ let rows = (0..<p.height).filter { y in close(p.at(14, y), red) }
+ return Double(rows.first! + rows.last!) / 2
+ }
+ /// The middle of the label's ink: the first run of drawn rows in the words.
+ func labelCenter(_ p: Pixels) -> Double {
+ let ink = (0..<p.height).map { y in (30..<120).contains { x in p.at(x, y)[3] > 128 } }
+ let top = ink.firstIndex(of: true)!
+ var bottom = top
+ while bottom + 1 < ink.count && ink[bottom + 1] { bottom += 1 }
+ return Double(top + bottom) / 2
+ }
+ let first = Pixels(Item("Ada", description: "Mathematician", align: .firstLine, startContent: tall).frame(width: 240))
+ let center = Pixels(Item("Ada", description: "Mathematician", startContent: tall).frame(width: 240))
+ #expect(abs(slotCenter(first) - labelCenter(first)) <= 1.5)
+ // `center` puts the same slot on the middle of the words instead.
+ #expect(abs(slotCenter(center) - labelCenter(center)) > 4)
+}
+
+@MainActor
+@Test func rowsReadTheirTapAndState() {
+ #expect(Item("Ada").tap == .none)
+ #expect(Item("Ada", onClick: {}).tap == .button)
+ #expect(Item("Ada", href: "https://example.com", onClick: {}).tap == .link)
+ #expect(Item<EmptyView, EmptyView, EmptyView>.addedTraits(isSelected: true) == .isSelected)
+ #expect(Item<EmptyView, EmptyView, EmptyView>.addedTraits(isSelected: false) == [])
+}
+
+@MainActor
+@Test func rowsGrowWithTheLargestTextSize() {
+ let large = Pixels(Item("Ada", description: "Mathematician").frame(width: 320))
+ let largest = Pixels(Item("Ada", description: "Mathematician").frame(width: 320), typeSize: .accessibility5)
+ #expect(largest.height > large.height * 2)
+ let tappable = Pixels(Item("Ada", onClick: {}).frame(width: 320), typeSize: .accessibility5)
+ #expect(tappable.height > 44)
+}
+
+@MainActor
+@Test func aWebPathIsAnItemHrefTheAppCannotOpen() {
+ #expect(Item<EmptyView, EmptyView, EmptyView>.isUnusableHref("/calendar"))
+ #expect(!Item<EmptyView, EmptyView, EmptyView>.isUnusableHref("https://example.com/calendar"))
+ #expect(!Item<EmptyView, EmptyView, EmptyView>.isUnusableHref(nil))
+ // The check reads the href as the link does: a padded absolute URL opens
+ // as a link and is not flagged.
+ #expect(!Item<EmptyView, EmptyView, EmptyView>.isUnusableHref(" https://example.com "))
+ #expect(Item("Ada", href: " https://example.com ").linkURL == URL(string: "https://example.com"))
+}
+
+@MainActor
+@Test func anInlineLabelWithoutADescriptionStillTruncates() {
+ let words = "A label long enough to need more than the row's width at one line"
+ let stacked = Pixels(Item(words).frame(width: 160))
+ let inline = Pixels(Item(words, layout: .inline).frame(width: 160))
+ #expect(inline.width == 160)
+ #expect(inline.height == stacked.height)
+ // The end content stays inside the row instead of being pushed past it.
+ let withEnd = Pixels(Item(words, layout: .inline, endContent: { Color(red: 1, green: 0, blue: 0).frame(width: 10, height: 10) }).frame(width: 160))
+ #expect(withEnd.contains { close($0, [255, 0, 0, 255]) })
+}
+
+@MainActor
+@Test func aPressShowsAboveASelectedFill() {
+ let tokens = Theme.neutral.light.color
+ let rest = Pixels(ItemPressBackground(radius: 0, fill: tokens.accentMuted, pressed: tokens.overlayPressed, isPressed: false).frame(width: 8, height: 8))
+ let pressed = Pixels(ItemPressBackground(radius: 0, fill: tokens.accentMuted, pressed: tokens.overlayPressed, isPressed: true).frame(width: 8, height: 8))
+ #expect(!close(rest.at(4, 4), pressed.at(4, 4), within: 3))
+}
+
+@Test func lineCountsComeFromTheContract() {
+ // Unset is one line; otherwise core's shared count: zero, a fraction, or a
+ // count too large to reach shows every line, as core's unclamped row does.
+ #expect(Item<EmptyView, EmptyView, EmptyView>.lines(nil) == 1)
+ #expect(Item<EmptyView, EmptyView, EmptyView>.lines(0) == nil)
+ #expect(Item<EmptyView, EmptyView, EmptyView>.lines(3) == 3)
+ #expect(Item<EmptyView, EmptyView, EmptyView>.lines(.infinity) == nil)
+ #expect(Item<EmptyView, EmptyView, EmptyView>.lines(1e300) == nil)
+}
+
+@MainActor
+@Test func aLongLabelTruncatesToItsLines() {
+ let words = "A label long enough to wrap onto more than one line in a narrow row"
+ let one = Pixels(Item(words).frame(width: 160))
+ let three = Pixels(Item(words, labelLines: 3).frame(width: 160))
+ #expect(three.height > one.height)
+}
+
+@MainActor
+@Test func hrefMakesALinkAndStatesReadFromTheContract() {
+ #expect(Item("Ada", href: "https://example.com/ada").linkURL == URL(string: "https://example.com/ada"))
+ #expect(Item("Ada", href: "").linkURL == nil)
+ #expect(Item("Ada", href: "not a url").linkURL == nil)
+ #expect(Item("Ada", href: "/calendar").linkURL == nil)
+ // A script URL or an HTML document in a data URL stays inert, as core's
+ // navigation destinations refuse them; the row is static or a button.
+ for refused in ["javascript:alert(1)", " JavaScript: alert(1)", "vbscript:msgbox", "data:text/html,<p>", "data: text/html,<p>"] {
+ #expect(Item("Ada", href: refused).linkURL == nil, "\(refused)")
+ #expect(Item("Ada", href: refused).tap == .none, "\(refused)")
+ }
+ #expect(Item("Ada", href: "javascript:alert(1)", onClick: {}).tap == .button)
+ #expect(Item("Ada", isSelected: true).isSelected)
+ #expect(!Item("Ada").isSelected)
+ #expect(Item("Ada", isDisabled: true).isDisabled)
+}
+
+@MainActor
+@Test func aHiddenItemDrawsNothing() {
+ let hidden = Pixels(
+ HStack(spacing: 0) {
+ Color.clear.frame(width: 1, height: 1)
+ Item(ItemProps(label: "Ada", base: AstryxBaseProps(isHidden: true)))
+ }.fixedSize()
+ )
+ #expect(hidden.width == 1)
+}
+
+/// A theme color drawn over white.
+private func onWhite(_ c: [Int]) -> [Int] {
+ (0..<3).map { (c[$0] * c[3] + 255 * (255 - c[3])) / 255 } + [255]
+}
+
+// AST-082 FR19: an Item node from a logic core draws as Item.
+@MainActor
+@Test func anItemNodeDrawsAsAnItem() {
+ let json = #"{"component":"Item","key":"i","props":{"label":"Ada Lovelace"}}"#
+ guard let node = try? JSONDecoder().decode(AstryxNode.self, from: Data(json.utf8)) else {
+ Issue.record("the item did not decode")
+ return
+ }
+ #expect(AstryxNodeView.componentName(node) == "Item")
+ let wired = Pixels(AstryxNodeView(node) { _ in }.frame(width: 200))
+ let direct = Pixels(Item("Ada Lovelace").frame(width: 200))
+ #expect(wired.height == direct.height)
+}
+
+// AST-082 FR19: an Item node's content slots draw their nodes, as a direct
+// Item draws its slots.
+@MainActor
+@Test func anItemNodeDrawsItsContentSlots() {
+ let json = """
+ {"component":"Item","key":"i","props":{"label":"Ada Lovelace",
+ "startContent":[{"component":"Avatar","key":"a","props":{"name":"Ada Lovelace","size":"sm"}}],
+ "endContent":[{"component":"Text","key":"t","props":{"children":"Admin"}}]}}
+ """
+ guard let node = try? JSONDecoder().decode(AstryxNode.self, from: Data(json.utf8)) else {
+ Issue.record("the item did not decode")
+ return
+ }
+ let wired = Pixels(AstryxNodeView(node) { _ in }.frame(width: 240))
+ let direct = Pixels(
+ Item("Ada Lovelace") { Avatar("Ada Lovelace", size: .sm) } endContent: { Astryx.Text("Admin") }.frame(width: 240))
+ let bare = Pixels(Item("Ada Lovelace").frame(width: 240))
+ #expect(wired.width == direct.width && wired.height == direct.height)
+ // The slots draw: the wired row is not the bare row. The leading 40
+ // points hold the avatar, which a bare row leaves empty.
+ var leadingDiffers = false
+ for y in 0..<min(wired.height, bare.height) {
+ for x in 0..<40 where wired.at(x, y) != bare.at(x, y) { leadingDiffers = true }
+ }
+ #expect(leadingDiffers)
+}
+
diff --git a/packages/native/specs/swift/library/component-api.md b/packages/native/specs/swift/library/component-api.md
index 2b45a4a19e..0bb66d115c 100644
--- a/packages/native/specs/swift/library/component-api.md
+++ b/packages/native/specs/swift/library/component-api.md
@@ -154,11 +154,9 @@ same generated contract.
(SwiftUI views with core's names, `Button`, `Text`, and so on, re-exporting
SwiftUI and the contracts) and the `AstryxNative` product (generated contract
types, unprefixed: `ButtonProps`, `ButtonVariant`).
-- Avatar, AvatarStatusDot, Button, Card, Heading, Icon, Text, TextInput, and
- Thumbnail take their generated `<Name>Props`; Banner has no generated
+- Avatar, AvatarStatusDot, Button, Card, Heading, Icon, Item, Text, TextInput, and Thumbnail take their generated `<Name>Props`; Banner has no generated
contract.
-- `AstryxNodeView` draws Avatar (with its status dot), AvatarStatusDot, Button,
- Card, Heading, Icon, Text, TextInput, and Thumbnail wire nodes. Any other
+- `AstryxNodeView` draws Avatar (with its status dot), AvatarStatusDot, Button, Card, Heading, Icon, Item, Text, TextInput, and Thumbnail wire nodes. Any other
node, HStack and VStack included, renders in its place as unsupported, and
its siblings still render, until the logic host draws stacks (A9).
- The generated iOS `SwitchProps` still declares `size`, and `HStackProps` and
diff --git a/packages/native/src/components/Item.ts b/packages/native/src/components/Item.ts
new file mode 100644
index 0000000000..1bda3062f8
--- /dev/null
+++ b/packages/native/src/components/Item.ts
@@ -0,0 +1,34 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file components/Item.ts
+ * @input None
+ * @output What @astryxdesign/native adds to the core Item contract
+ * @position Native additions read by fromComponentDoc together with core's
+ * Item documentation
+ */
+
+import type {NativeAdditions} from '../contract/fromComponentDoc.js';
+
+export const item: NativeAdditions = {
+ name: 'Item',
+ doc: {file: 'Item/Item', component: 'Item'},
+ baseTarget: 'root',
+ slots: {
+ label: 'text',
+ description: 'text',
+ marker: 'content',
+ startContent: 'content',
+ endContent: 'content',
+ },
+ callbacks: ['onClick'],
+ sameMeaning: {onClick: 'a press, as in Compose'},
+ webOnly: {
+ target: 'HTML link target',
+ rel: 'HTML link relationship',
+ 'data-testid': 'web test selector; native platforms use the base id',
+ swipeActions:
+ "a native platform's swipe actions work only inside its own scrolling list, so a row elsewhere could not honor them",
+ swipeBehavior: 'applies only with swipeActions',
+ },
+};
diff --git a/packages/native/src/components/index.ts b/packages/native/src/components/index.ts
index a6422494a9..99573b5101 100644
--- a/packages/native/src/components/index.ts
+++ b/packages/native/src/components/index.ts
@@ -18,6 +18,7 @@ import {divider} from './Divider.js';
import {heading} from './Heading.js';
import {hStack} from './HStack.js';
import {icon} from './Icon.js';
+import {item} from './Item.js';
import {progressBar} from './ProgressBar.js';
import {selector} from './Selector.js';
import {switchControl} from './Switch.js';
@@ -36,6 +37,7 @@ export const NATIVE_COMPONENTS: readonly NativeAdditions[] = [
heading,
hStack,
icon,
+ item,
progressBar,
selector,
switchControl,
diff --git a/packages/native/src/contract/contracts.test.ts b/packages/native/src/contract/contracts.test.ts
index eb1143d982..15f59493be 100644
--- a/packages/native/src/contract/contracts.test.ts
+++ b/packages/native/src/contract/contracts.test.ts
@@ -207,6 +207,45 @@ describe('native contracts', () => {
);
});
+ it('gives Item typed text and content slots, a press, and a link, and leaves swipes on the web', async () => {
+ const {contracts} = await buildContracts(loadCoreDoc);
+ const item = contracts.find(contract => contract.name === 'Item');
+ expect(item).toBeDefined();
+ expect(item!.core.label).toMatchObject({
+ type: {kind: 'string'},
+ optional: false,
+ });
+ expect(item!.core.description?.type).toEqual({kind: 'string'});
+ for (const slot of ['marker', 'startContent', 'endContent']) {
+ expect(item!.core[slot]?.type).toEqual({kind: 'content'});
+ }
+ expect(Object.keys(item!.core)).toEqual(
+ expect.arrayContaining([
+ 'align',
+ 'density',
+ 'labelLines',
+ 'descriptionLines',
+ 'layout',
+ 'onClick',
+ 'href',
+ 'isHighlighted',
+ 'isSelected',
+ 'isDisabled',
+ ]),
+ );
+ expect(item!.webOnly.map(prop => prop.name)).toEqual(
+ expect.arrayContaining([
+ 'swipeActions',
+ 'swipeBehavior',
+ 'target',
+ 'rel',
+ 'data-testid',
+ 'as',
+ 'interactiveRef',
+ ]),
+ );
+ });
+
it('reports naming and portability errors', () => {
const bad: ComponentContract = {
name: 'Bad',