From f140c7b94476f5eaeb74fd8a85c75d1f31e02034 Mon Sep 17 00:00:00 2001 From: romchornyi <270373998+romchornyi@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:52:11 +0200 Subject: [PATCH 1/3] refactor: route asset names through DashIcon The toast, nav bar and converter badge drew their icons from string names that conventions.sh could not see; they now use DashIcon cases. NavigationBarElement keeps its public raw values and draws through DashIcon.NavigationBar; a test keeps the two in step. conventions.sh flags a package-bundle lookup whose name is not one literal (outside the Icon_DashUI / Color+DashUI resolvers), a computed name in the host bundle, an empty name and a computed dashAsset() name. A unit test checks that every DashIcon case resolves in the package bundle. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/conventions.sh | 60 ++++++++++---- .github/scripts/tests/conventions-test.sh | 79 +++++++++++++++++-- CLAUDE.md | 8 +- .../Components/BottomSheet/SheetFeature.swift | 6 +- .../ConverterCard/ConverterArrowBadge.swift | 8 +- .../DashUIKit/Components/NavigationBar.swift | 16 +++- .../Components/NavigationBarCircleIcon.swift | 2 +- Sources/DashUIKit/Components/Toast.swift | 43 ++++------ Tests/DashUIKitTests/DashIconTests.swift | 59 ++++++++++++++ .../NavigationBarElementTests.swift | 30 +++++++ docs/feedback.md | 9 +-- docs/foundation.md | 10 ++- docs/lists-and-rows.md | 2 +- docs/navigation-and-containers.md | 2 +- 14 files changed, 261 insertions(+), 73 deletions(-) create mode 100644 Tests/DashUIKitTests/DashIconTests.swift create mode 100644 Tests/DashUIKitTests/NavigationBarElementTests.swift diff --git a/.github/scripts/conventions.sh b/.github/scripts/conventions.sh index c049c5e..4c6a9eb 100755 --- a/.github/scripts/conventions.sh +++ b/.github/scripts/conventions.sh @@ -4,10 +4,15 @@ # # 1. every DashIcon raw value has an imageset, and every imageset is named by a # DashIcon case or a literal (rule 3); no name twice; -# 2. the same for dashAsset("…") tokens in Color+DashUI.swift and colorsets; +# 2. the same for dashAsset("…") tokens in Color+DashUI.swift and colorsets; a +# dashAsset call whose name is not one literal is flagged; # 3. asset names written as literals (Image("…", bundle:), .custom("…", bundle:), # Color("…", bundle:), UIImage(named: "…", in:), …) exist, and are looked up -# in the package bundle (.module / .dashUIKit), not the host app's; +# in the package bundle (.module / .dashUIKit), not the host app's; a +# package-bundle lookup whose name is not one literal (a variable, +# interpolation, ternary, concatenation) is flagged, as is an empty one, since the +# name escapes this check: a bundled icon is a DashIcon case, a color a +# Color.dash token; # 4. every imageset and colorset has a valid Contents.json naming at least one # image or color, every image it names exists, and no catalog folder provides # a namespace (names would gain a "Folder/" prefix); @@ -22,10 +27,15 @@ # # Calls are parsed with their arguments (labels, nesting, several lines); string # contents and `//` comments are ignored, interpolated code is scanned. Not -# handled: /* block comments */, raw and multi-line string literals, names that -# are interpolated ("icon-\(x)"), concatenated or passed through a variable -# (Image(name) may be an ImageResource; only UIImage(named:) and .custom are -# checked for their bundle then), a .custom(…) that is not after DashIconSource, +# handled: /* block comments */, raw and multi-line string literals (as a name +# they count as computed), computed names inside Icon_DashUI.swift and +# Color+DashUI.swift (the resolvers), ImageResource / ColorResource written as +# .init(name:bundle:), names reaching the DashIconAsset resolver +# from a conformance other than a DashIcon enum case, computed names +# looked up in a bundle passed in as a variable (Image+DashUI.swift resolves a +# host's DashIconSource that way) or without one (Image(name) may be an +# ImageResource; only UIImage(named:) and .custom are checked for their bundle +# then), a .custom(…) that is not after DashIconSource, # `dash:` or an `…icon:` label, NSImage(named:), SwiftUI Text("…") and # LocalizedStringResource localization. Icon_DashUI.swift is # expected to keep each `case` list on one line. @@ -85,7 +95,7 @@ list_sets colorset > "$colorsets" scan=$work/scan # shellcheck disable=SC2016 # awk fields, not shell variables find "$src" -name '*.swift' -print0 | sort -z | - xargs -0 awk -v exempt="$colors" -v ios_floor="$ios_floor" -v mac_floor="$mac_floor" ' + xargs -0 awk -v exempt="$colors" -v icons="$icons" -v ios_floor="$ios_floor" -v mac_floor="$mac_floor" ' # mask(s): string contents become spaces, so a match in M is always code. # Interpolated code ("\(x)") stays visible, its "\(" written as " (". function mask(s, i, c, instr, n, pd, out) { @@ -155,9 +165,9 @@ find "$src" -name '*.swift' -print0 | sort -z | } # Rule 3: literal asset names. - function assets(li, ml, base, call, before, open, kind, label, k, s, n, name) { + function assets(li, ml, base, call, before, open, kind, label, k, s, n, name, computed) { ml = M[li]; base = 0 - while (match(substr(ml, base + 1), /(^|[^A-Za-z0-9_])(Image|UIImage|Color|UIColor|Label|Button|Toggle|Menu|Tab|ContentUnavailableView)[[:space:]]*(\.init)?[[:space:]]*\(|\.custom[[:space:]]*\(/)) { + while (match(substr(ml, base + 1), /(^|[^A-Za-z0-9_])(ImageResource|ColorResource|Image|UIImage|Color|UIColor|Label|Button|Toggle|Menu|Tab|ContentUnavailableView)[[:space:]]*(\.init)?[[:space:]]*\(|\.custom[[:space:]]*\(/)) { call = substr(ml, base + RSTART, RLENGTH) before = substr(ml, 1, base + RSTART - 1) open = base + RSTART + RLENGTH - 1 @@ -172,20 +182,37 @@ find "$src" -name '*.swift' -print0 | sort -z | kind = (call ~ /Color/) ? "colorset" : "imageset" label = (call ~ /UI/) ? "in" : "bundle" if (call ~ /UI/) { if (alabel[1] != "named") continue } + else if (call ~ /Resource/) { if (alabel[1] != "name") continue } else if (call ~ /Image/) { if (alabel[1] != "" && alabel[1] != "decorative") continue } else if (alabel[1] != "") continue + # A pattern (`case .custom(let name, let bundle)`, `case let .custom(n, + # bundle: b)`) is not a lookup. + if (amask[1] ~ /^[[:space:]]*(let|var)[[:space:]]/ || before ~ /(^|[^A-Za-z0-9_])case([[:space:]]+(let|var))?[[:space:]]*$/) continue + # A name that is not one literal, looked up in the package bundle, is not + # checked against the catalog. Icon_DashUI.swift and Color+DashUI.swift are + # exempt: they hold the resolvers for DashIcon cases and Color.dash tokens, + # whose names rules 1 and 2 check where they are declared. In this package + # only DashIconSource has a .custom case that takes a bundle. A literal + # with an escape counts as computed: its name is not read below. + k = arg(label) + computed = (amask[1] !~ /^[[:space:]]*"[[:space:]]*"[[:space:]]*$/ || index(atop[1], "\\")) + if (k && pkg(amask[k]) && computed && file != icons && file != exempt) + out(li, "asset name is not one literal, so the catalog check cannot follow it; use " (kind == "colorset" ? "a Color.dash token" : "a DashIcon case (DashIcon...source or .image)")) + # A computed name looked up in the host app bundle by name (a literal one + # gets the same report from bundle_ok below). + else if (k && computed && trim(amask[k]) ~ /^(nil|(Bundle[[:space:]]*)?\.main)$/) + out(li, label ": " trim(amask[k]) " is not the package bundle; use .dashUIKit") # Other enums have a .custom case too: .custom counts only where a # DashIconSource is expected (after `DashIconSource`, `dash:` or an # `…icon:` / `…Icon:` label). if (call ~ /custom/ && before !~ /(DashIconSource[[:space:]]*=?|(dash|[A-Za-z]*[Ii]con):)[[:space:]]*$/) continue - # A pattern (`case .custom(let name, let bundle)`) is not a lookup. - if (amask[1] ~ /^[[:space:]]*(let|var)[[:space:]]/) continue # "a" + b is an expression, not a name. s = (index(amask[1], "+") ? "" : atop[1]); n = 0 while (match(s, /"([^"\\]|\\.)*"/)) { name = substr(s, RSTART + 1, RLENGTH - 2) s = substr(s, RSTART + RLENGTH) - if (name == "" || index(name, "\\")) continue + if (name == "") { if (trim(amask[1]) == "\"\"") out(li, "empty asset name"); continue } + if (index(name, "\\")) continue print "L\t" kind "\t" name "\t" file "\t" li n++ } @@ -273,18 +300,23 @@ find "$src" -name '*.swift' -print0 | sort -z | } # Color tokens: dashAsset("Name") calls in Color+DashUI.swift. - function tokens(li, ml, base, open, s) { + # A token whose name is not one literal is unchecked, like a computed name + # in rule 3. + function tokens(li, ml, base, open, s, before) { if (file != exempt) return ml = M[li]; base = 0 while (match(substr(ml, base + 1), /(^|[^A-Za-z0-9_])dashAsset[[:space:]]*\(/)) { + before = substr(ml, 1, base + RSTART) open = base + RSTART + RLENGTH - 1 base = open + if (before ~ /func[[:space:]]+$/) continue parse(li, open) s = atop[1] if (alabel[1] == "" && match(s, /^[[:space:]]*"[^"\\]+"[[:space:]]*$/)) { match(s, /"[^"]+"/) print "T\t" substr(s, RSTART + 1, RLENGTH - 2) "\t" file "\t" li - } + } else + out(li, "dashAsset(…) needs one literal colorset name, or it is not checked against the catalog") } } diff --git a/.github/scripts/tests/conventions-test.sh b/.github/scripts/tests/conventions-test.sh index b20b591..b219300 100755 --- a/.github/scripts/tests/conventions-test.sh +++ b/.github/scripts/tests/conventions-test.sh @@ -40,13 +40,17 @@ write_fixture() { } # expect NAME fail|pass [NEEDLE...]: runs the script on the copy; a failure must -# exit 1 and print every needle. +# exit 1 and print every needle, and none of the needles written as "!text". expect() { local name=$1 want=$2 output status=0 needle missing="" shift 2 output=$(cd "$work/tree" && "$script" 2>&1) || status=$? for needle in "$@"; do - [[ "$output" == *"$needle"* ]] || missing="${missing} missing: ${needle}"$'\n' + if [[ "$needle" == '!'* ]]; then + [[ "$output" != *"${needle#!}"* ]] || missing="${missing} unexpected: ${needle#!}"$'\n' + else + [[ "$output" == *"$needle"* ]] || missing="${missing} missing: ${needle}"$'\n' + fi done if { [ "$want" = pass ] && [ "$status" -eq 0 ]; } || { [ "$want" = fail ] && [ "$status" -eq 1 ] && [ -z "$missing" ]; }; then @@ -184,27 +188,86 @@ expect "literal asset names" fail \ fresh; write_fixture \ 'let a = Font.custom("Inter", size: 12)' \ - 'let b = Image(dash: .custom("icon-\(n)", bundle: .dashUIKit))' \ + 'let b = Image(dash: DashIcon.Toast.info.source)' \ 'let c = Image(systemName: "xmark").accessibilityLabel(NSLocalizedString("Close", bundle: .module, comment: ""))' \ 'let d = Image(dash: source).overlay(Text("Done", bundle: .module))' \ "let e = Image(\"${img}\", bundle: Bundle.dashUIKit)" \ 'let f = Color(uiColor: .systemBackground).opacity(0.5)' \ - 'let g = Image(String(format: "menu-%@", x), bundle: .module)' \ - "let h = Image(icons[\"key\"] ?? \"${img}\", bundle: .module)" \ + 'let g = Image(name, bundle: bundle)' \ + "let h = Image(ImageResource(name: \"${img}\", bundle: .module))" \ 'let i = Color(UIColor(named: "'"${col}"'", in: .module, compatibleWith: nil)!)' \ - 'let j = Image(dash: .custom("icon-\(flag ? "a" : "b")", bundle: .dashUIKit))' \ + 'let j = Image(dash: .custom("'"${img}"'", bundle: .dashUIKit))' \ 'let k = Image(.resourceName)' \ "let l = Image(\"${img}\", bundle: #bundle)" \ - 'let m = Image("icon-" + name, bundle: .module)' \ + 'func m(s: DashIconSource) { switch s { case let .custom(name, bundle: b): _ = (name, b); default: break } }' \ 'let n = Image(icon.resource)' \ 'let o = Label("Title", systemImage: "xmark")' \ 'func p(s: DashIconSource) { switch s { case let .custom(name, bundle): _ = (name, bundle); default: break } }' \ 'func q(s: DashIconSource) { if case .custom(_, let b) = s { _ = b } }' \ 'let r: Set = [.medium, .custom(Half.self)]' \ 'let t = Button(style: .custom(style))' \ - 'let u = Placement.custom("Compact")' + 'let u = Placement.custom("Compact")' \ + 'func v(s: DashIconSource) -> Bool { if case .custom(_, bundle: _) = s { return true }; return false }' expect "calls that are not literal asset lookups" pass +# A name the scanner cannot read, looked up in the package bundle. +fresh; write_fixture \ + 'let a = Image(dash: .custom("icon-\(n)", bundle: .dashUIKit))' \ + 'let b = Image(dash: .custom("icon-\(flag ? "a" : "b")", bundle: .dashUIKit))' \ + 'let c = Image(dash: .custom(style.iconName, bundle: .dashUIKit))' \ + 'var d: DashIconSource { .custom(rawValue, bundle: .module) }' \ + 'let e = NavigationBarCircleIcon(' \ + ' .custom(' \ + ' names[0],' \ + ' bundle: .module))' \ + "let f = DashIconSource.custom(\"${img}\" + suffix, bundle: .dashUIKit)" \ + 'let g = Image(String(format: "menu-%@", x), bundle: .module)' \ + "let h = Image(icons[\"key\"] ?? \"${img}\", bundle: .module)" \ + 'let i = Image(decorative: name, bundle: .dashUIKit)' \ + 'let j = UIImage(named: name, in: .module, with: nil)' \ + 'let k = Color(token, bundle: .module)' \ + 'let l = UIColor(named: token, in: .dashUIKit, compatibleWith: nil)' \ + 'let m = Image(dash: .custom(#"icon-\#(n)"#, bundle: .dashUIKit))' \ + 'let n = Image(ImageResource(name: name, bundle: .module))' \ + 'let o = Color(ColorResource(name: "NoSuchColor4", bundle: .module))' \ + 'let p = Image(dash: .custom("", bundle: .dashUIKit))' \ + 'let q = Image(dash: .custom("no\u{2d}such", bundle: .module))' \ + 'let r = Image(name, bundle: nil)' \ + 'let s = Image(dash: .custom(name, bundle: .main))' \ + 'let t = UIImage(named: name, in: Bundle.main, with: nil)' \ + 'let u = Color(name, bundle: Bundle .main)' \ + 'let v = Image("icon-" + name, bundle: .module)' +expect "computed names in the package bundle" fail \ + "${fixture}:1: asset name is not one literal" \ + "${fixture}:2: asset name is not one literal" \ + "${fixture}:3: asset name is not one literal" \ + "${fixture}:4: asset name is not one literal" \ + "${fixture}:6: asset name is not one literal" \ + "${fixture}:9: asset name is not one literal" \ + "${fixture}:10: asset name is not one literal" \ + "${fixture}:11: asset name is not one literal" \ + "${fixture}:12: asset name is not one literal" \ + "${fixture}:13: asset name is not one literal" \ + "${fixture}:14: asset name is not one literal, so the catalog check cannot follow it; use a Color.dash token" \ + "${fixture}:15: asset name is not one literal, so the catalog check cannot follow it; use a Color.dash token" \ + "${fixture}:16: asset name is not one literal" \ + "${fixture}:17: asset name is not one literal" \ + "${fixture}:18: no colorset named \"NoSuchColor4\"" \ + "${fixture}:19: empty asset name" \ + "${fixture}:20: asset name is not one literal" \ + "${fixture}:21: bundle: nil is not the package bundle" \ + "${fixture}:22: bundle: .main is not the package bundle" \ + "${fixture}:23: in: Bundle.main is not the package bundle" \ + "${fixture}:24: bundle: Bundle .main is not the package bundle" \ + "${fixture}:25: asset name is not one literal" \ + '!no imageset named "icon-' + +# The resolver files may pass a name on; a computed token name is still flagged. +fresh; echo 'func fixtureSource(_ n: String) -> DashIconSource { .custom(n, bundle: .dashUIKit) }' >> "$work/tree/$src/Foundation/Icon_DashUI.swift" +echo 'extension DashColors { static func fixtureState(_ s: String) -> Color { dashAsset("State-" + s) } }' >> "$work/tree/$src/Foundation/Color+DashUI.swift" +expect "computed token name" fail '!Icon_DashUI.swift:' \ + "Color+DashUI.swift:$(wc -l < "$work/tree/$src/Foundation/Color+DashUI.swift" | tr -d ' '): dashAsset(…) needs one literal colorset name" + # 4. Set contents and namespaces. fresh; dir=$(first_set imageset); png=$(jq -r '.images[] | .filename // empty' "$dir/Contents.json" | awk 'NR == 1'); rm "$dir/$png" expect "image file missing" fail "lists \"${png}\", which is not in the imageset" diff --git a/CLAUDE.md b/CLAUDE.md index d7ccbda..388c357 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,6 +56,9 @@ Sources/DashUIKit/ or `Font.dash.subhead` when you only need the font. Tokens defined in `DashTextStyle.swift`. - **Icons:** pass a `DashIconSource` (`.system` / `.custom(name, bundle:)` / `.uiImage`) and render with `Image(dash: source)`. Custom assets resolve from `.dashUIKit`/`.module`. + Inside the library a bundled icon is a `DashIcon` case (`DashIcon.Toast.info.source`, + `.image`), never a name built at runtime: CI rejects a package-bundle lookup whose name + is not one literal. - **Availability:** don't annotate. The floor is declared in `Package.swift`; gate an API that needs something *newer* than it with `if #available(...)` in the body. - **UIKit-only files** are wrapped in `#if canImport(UIKit)` (e.g. `SearchBar`, `Toast`, @@ -70,8 +73,9 @@ Sources/DashUIKit/ host. Don't add view models or persistence here. - CI enforces the mechanical ones with `.github/scripts/conventions.sh`: `DashIcon` ↔ imagesets, `Color.dash` tokens ↔ colorsets, literal asset names and their bundle, no - colors built from components (`Color(red:…)`, hex), `NSLocalizedString` / - `String(localized:)` with the package bundle, no `@available` at or below the floor. + computed names in the package bundle, no colors built from components (`Color(red:…)`, + hex), `NSLocalizedString` / `String(localized:)` with the package bundle, no + `@available` at or below the floor. It does not check system colors (`Color.red`) or `Text("…")` keys. Run it from the repo root before pushing. diff --git a/Sources/DashUIKit/Components/BottomSheet/SheetFeature.swift b/Sources/DashUIKit/Components/BottomSheet/SheetFeature.swift index 387094d..957b326 100644 --- a/Sources/DashUIKit/Components/BottomSheet/SheetFeature.swift +++ b/Sources/DashUIKit/Components/BottomSheet/SheetFeature.swift @@ -108,15 +108,15 @@ public extension SheetFeature where Icon == AnyView { SheetFeature( title: "Identity", description: "Register a username and be paid by name instead of an address.", - icon: .custom("feature-identity", bundle: .dashUIKit)) + icon: DashIcon.Features.identity.source) SheetFeature( title: "Platform", description: "Store contacts and profile data on Dash Platform.", - icon: .custom("feature-platform", bundle: .dashUIKit)) + icon: DashIcon.Features.platform.source) SheetFeature( title: "Shield", description: "Move funds into shielded balances that stay off the public ledger.", - icon: .custom("feature-shield", bundle: .dashUIKit)) + icon: DashIcon.Features.shield.source) } .padding(20) .background(Color.dash.primaryBackground) diff --git a/Sources/DashUIKit/Components/ConverterCard/ConverterArrowBadge.swift b/Sources/DashUIKit/Components/ConverterCard/ConverterArrowBadge.swift index c45e77c..ed9d802 100644 --- a/Sources/DashUIKit/Components/ConverterCard/ConverterArrowBadge.swift +++ b/Sources/DashUIKit/Components/ConverterCard/ConverterArrowBadge.swift @@ -35,14 +35,14 @@ struct ConverterArrowBadge: View { withAnimation(.spring(response: 0.35, dampingFraction: 0.82)) { rotation += 180 } onSwap() } label: { - badge(iconName: "diagonal-up-down", iconRotation: rotation) + badge(icon: .diagonalUpDown, iconRotation: rotation) } .buttonStyle(.plain) .accessibilityLabel(Text(NSLocalizedString("Swap direction", bundle: .module, comment: "DashUIKit"))) } else { // Decorative — the card's row order already conveys the direction, // and without this the icon announces its asset name. - badge(iconName: "arrow-down", iconRotation: 0) + badge(icon: .arrowDown, iconRotation: 0) .accessibilityHidden(true) } } @@ -50,7 +50,7 @@ struct ConverterArrowBadge: View { .padding(.horizontal, 10) } - private func badge(iconName: String, iconRotation: Double) -> some View { + private func badge(icon: DashIcon.Common, iconRotation: Double) -> some View { RoundedRectangle(cornerRadius: 10, style: .continuous) .fill(Color.dash.secondaryBackground) .frame(width: 35, height: 35) @@ -59,7 +59,7 @@ struct ConverterArrowBadge: View { .stroke(Color.dash.primaryBackground, lineWidth: 5) ) .overlay( - Image(dash: .custom(iconName, bundle: .dashUIKit)) + icon.image .rotationEffect(.degrees(iconRotation)) ) } diff --git a/Sources/DashUIKit/Components/NavigationBar.swift b/Sources/DashUIKit/Components/NavigationBar.swift index cb283fb..8e6d07e 100644 --- a/Sources/DashUIKit/Components/NavigationBar.swift +++ b/Sources/DashUIKit/Components/NavigationBar.swift @@ -85,7 +85,7 @@ public extension NavigationBar where Leading == EmptyView, Central == EmptyView } } -public enum NavigationBarElement: String { +public enum NavigationBarElement: String, CaseIterable { case back = "navigationbar-back" case close = "navigationbar-close" case plus = "navigationbar-plus" @@ -104,10 +104,20 @@ public enum NavigationBarElement: String { } } - private var source: DashIconSource { - .custom(rawValue, bundle: .module) + /// The imageset drawn for the element. The raw value is the same name, + /// kept for hosts; drawing goes through `DashIcon` so the catalog check + /// sees it. + var asset: DashIcon.NavigationBar { + switch self { + case .back: return .back + case .close: return .close + case .plus: return .plus + case .info: return .info + } } + private var source: DashIconSource { asset.source } + public func button(action: @escaping () -> Void) -> some View { NavigationBarButton(accessibilityLabel: Text(accessibilityLabelText), action: action) { icon diff --git a/Sources/DashUIKit/Components/NavigationBarCircleIcon.swift b/Sources/DashUIKit/Components/NavigationBarCircleIcon.swift index fa7e51c..926a9f5 100644 --- a/Sources/DashUIKit/Components/NavigationBarCircleIcon.swift +++ b/Sources/DashUIKit/Components/NavigationBarCircleIcon.swift @@ -72,7 +72,7 @@ nonisolated struct NavigationBarCircleIconContent: View { #if DEBUG #Preview("NavigationBarCircleIcon") { HStack(spacing: 10) { - NavigationBarCircleIcon(.custom(NavigationBarElement.back.rawValue, bundle: .module)) + NavigationBarCircleIcon(DashIcon.NavigationBar.back.source) NavigationBarCircleIcon(.system("arrow.clockwise")) NavigationBarCircleIcon(.system("ellipsis")) } diff --git a/Sources/DashUIKit/Components/Toast.swift b/Sources/DashUIKit/Components/Toast.swift index b6096b5..22fa582 100644 --- a/Sources/DashUIKit/Components/Toast.swift +++ b/Sources/DashUIKit/Components/Toast.swift @@ -31,31 +31,19 @@ struct BackgroundBlurView: UIViewRepresentable { // MARK: - ToastStyle -/// NOTE: Create the 6 imagesets listed below under -/// `Media.xcassets/Icons & Illustrations/Toast/` before shipping. -/// Until they exist, the icon slot renders empty — that is expected. -/// -/// toast-warning.imageset -/// toast-info.imageset -/// toast-error.imageset -/// toast-success.imageset -/// toast-copied.imageset -/// toast-loading.imageset (optional — `loading` uses `LoadingSpinner`) public enum ToastStyle { case warning, info, error, success, copied, loading, noInternet - /// Placeholder asset names — REAL ICONS TO BE ADDED by the user into - /// `Media.xcassets/Icons & Illustrations/Toast/`. - /// (`loading` renders the `LoadingSpinner` instead — see `Toast.leadingIcon`.) - var iconName: String { + /// The leading icon; `nil` for `loading`, which draws `LoadingSpinner`. + var icon: DashIcon.Toast? { switch self { - case .warning: return "toast-warning" - case .info: return "toast-info" - case .error: return "toast-error" - case .success: return "toast-success" - case .copied: return "toast-copied" - case .loading: return "toast-loading" - case .noInternet: return "toast-no-wifi" + case .warning: return .warning + case .info: return .info + case .error: return .error + case .success: return .success + case .copied: return .copied + case .loading: return nil + case .noInternet: return .noWifi } } } @@ -119,15 +107,15 @@ public struct Toast: View { @ViewBuilder private var leadingIcon: some View { - if case .loading = style { - // Reuse the design-system spinner (12 white spokes at graduated opacity, 18×18). - // LoadingSpinner applies its own per-spoke opacity on top of toastText. - LoadingSpinner(size: 16, color: Color.dash.toastText) - } else { - Image(dash: .custom(style.iconName, bundle: .dashUIKit)) + if let icon = style.icon { + icon.image .resizable() .scaledToFit() .frame(width: 16, height: 16) + } else { + // Reuse the design-system spinner (12 spokes at graduated opacity). + // LoadingSpinner applies its own per-spoke opacity on top of toastText. + LoadingSpinner(size: 16, color: Color.dash.toastText) } } } @@ -144,6 +132,7 @@ public struct Toast: View { Toast(style: .success, message: "Done", onDismiss: {}) Toast(style: .copied, message: "Copied to clipboard") Toast(style: .loading, message: "Loading…") + Toast(style: .noInternet, message: "No internet connection") } .padding() .background(Color.dash.blue) diff --git a/Tests/DashUIKitTests/DashIconTests.swift b/Tests/DashUIKitTests/DashIconTests.swift new file mode 100644 index 0000000..6a4899e --- /dev/null +++ b/Tests/DashUIKitTests/DashIconTests.swift @@ -0,0 +1,59 @@ +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + + +#if canImport(UIKit) +import UIKit +import XCTest +@testable import DashUIKit + +final class DashIconTests: XCTestCase { + + /// Every case names an imageset that ships in the package bundle, so a + /// raw value that drifts from the catalog fails here, not as a blank image. + func testEveryCaseResolvesInThePackageBundle() { + assertResolves(DashIcon.Common.self) + assertResolves(DashIcon.Icons.self) + assertResolves(DashIcon.Illustrations.self) + assertResolves(DashIcon.Features.self) + assertResolves(DashIcon.Checkbox.self) + assertResolves(DashIcon.SegmentedControl.self) + assertResolves(DashIcon.SearchBar.self) + assertResolves(DashIcon.Menu.self) + assertResolves(DashIcon.NavigationBar.self) + assertResolves(DashIcon.SystemMessage.self) + assertResolves(DashIcon.Toast.self) + assertResolves(DashIcon.Other.self) + assertResolves(DashIcon.AdditionalInfo.self) + assertResolves(DashIcon.Transaction.self) + } + + private func assertResolves( + _ group: Group.Type, + file: StaticString = #filePath, + line: UInt = #line + ) { + for icon in group.allCases { + XCTAssertNotNil( + UIImage(named: icon.assetName, in: .dashUIKit, compatibleWith: nil), + "\(group).\(icon) → \"\(icon.assetName)\"", + file: file, + line: line + ) + } + } +} +#endif diff --git a/Tests/DashUIKitTests/NavigationBarElementTests.swift b/Tests/DashUIKitTests/NavigationBarElementTests.swift new file mode 100644 index 0000000..0dac5b3 --- /dev/null +++ b/Tests/DashUIKitTests/NavigationBarElementTests.swift @@ -0,0 +1,30 @@ +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + + +import XCTest +@testable import DashUIKit + +final class NavigationBarElementTests: XCTestCase { + + /// Hosts may still build an element from its raw value, so the raw value + /// must stay the name of the imageset it draws. + func testRawValueNamesTheDrawnImageset() { + for element in NavigationBarElement.allCases { + XCTAssertEqual(element.rawValue, element.asset.assetName, "\(element)") + } + } +} diff --git a/docs/feedback.md b/docs/feedback.md index 3498eb8..e10b0e7 100644 --- a/docs/feedback.md +++ b/docs/feedback.md @@ -21,13 +21,8 @@ Toast( ``` **`ToastStyle`** — `.warning` · `.info` · `.error` · `.success` · `.copied` · `.loading` -· `.noInternet`. Each maps to an icon asset under -`Media.xcassets/Icons & Illustrations/Toast/` (`toast-warning`, `toast-info`, …, -`toast-no-wifi`). `.loading` instead renders the DS `LoadingSpinner`. - -> ⚠️ The toast icon assets are placeholders to be supplied. Until the imagesets exist the -> icon slot renders empty for the non-loading styles — that's expected, not a bug. See the -> note at the top of `Toast.swift` for the exact asset names. +· `.noInternet`. Each draws a `DashIcon.Toast` case (`.warning`, `.info`, …, `.noWifi` +for `.noInternet`). `.loading` instead renders the DS `LoadingSpinner`. This is just the toast *view* — presentation/animation/auto-dismiss timing is the host's responsibility (e.g. overlay it and drive visibility yourself). diff --git a/docs/foundation.md b/docs/foundation.md index fb0a41c..980ed27 100644 --- a/docs/foundation.md +++ b/docs/foundation.md @@ -103,10 +103,15 @@ public enum DashIconSource { } Image(dash: .system("info.circle")) -Image(dash: .custom("menu-send", bundle: .dashUIKit)) +Image(dash: DashIcon.Menu.send.source) .resizable().scaledToFit().frame(width: 30, height: 30) ``` +Every bundled image is a case of a `DashIcon` group (`Foundation/Icon_DashUI.swift`), whose +raw value is the imageset name: `DashIcon.Menu.send.source` is the `DashIconSource`, +`.image` the plain `Image`. Inside the library, use these cases rather than +`.custom(name, bundle:)`; CI rejects a package-bundle lookup whose name is not one literal. + Many components accept a `DashIconSource?` directly (`DashButton.leadingIcon`, `MenuItem.leadingIcon`, `RadioButtonRow.icon`, …). @@ -129,4 +134,5 @@ the unselected segment), and illustrations File `Foundation/BundleToken.swift`. `Bundle.dashUIKit` is a convenience alias for `Bundle.module`, used when loading custom -assets from the package bundle (`Image(dash: .custom(name, bundle: .dashUIKit))`). +assets from the package bundle (`Image("menu-send", bundle: .dashUIKit)`; inside the library +prefer `DashIcon`). diff --git a/docs/lists-and-rows.md b/docs/lists-and-rows.md index 71a279c..6d1977a 100644 --- a/docs/lists-and-rows.md +++ b/docs/lists-and-rows.md @@ -43,7 +43,7 @@ help text, and a flexible trailing **accessory**. ```swift MenuItem( - leadingIcon: .custom("menu-send", bundle: .dashUIKit), // DashIconSource? + leadingIcon: DashIcon.Menu.send.source, // DashIconSource? title: "Network fee", helpText: "Estimated cost for this transaction", info: .round(color: Color.dash.gray300Alpha70), diff --git a/docs/navigation-and-containers.md b/docs/navigation-and-containers.md index fad6f95..4aaa394 100644 --- a/docs/navigation-and-containers.md +++ b/docs/navigation-and-containers.md @@ -200,7 +200,7 @@ sentence. Stack several to describe what a feature unlocks. SheetFeature( title: "Identity", description: "Register a username and be paid by name instead of an address.", - icon: .custom("feature-identity", bundle: .dashUIKit), + icon: DashIcon.Features.identity.source, iconColor: Color.dash.purple) // omit to keep the asset's own colours SheetFeature(title: "Custom", description: "…") { // or any view in the slot From 3171eedddcc1f760a8f32944dbc32c0030cc8320 Mon Sep 17 00:00:00 2001 From: romchornyi <270373998+romchornyi@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:56:24 +0200 Subject: [PATCH 2/3] ci: one report per asset lookup, and host-bundle lookups wherever they are MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to the review of this PR: - each call's literal names are read once, so a ternary in the host bundle or a repeated missing name is reported once; - a .custom(…) that passes a bundle is a lookup wherever it sits, and a computed name in .main / nil / .none is reported; - an empty name also gets its bundle checked; - negative needles ("!text") are checked in pass cases too; - CLAUDE.md, docs/foundation.md and the script header say what the scan does and does not follow. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/conventions.sh | 51 +++++++++++++---------- .github/scripts/tests/conventions-test.sh | 51 +++++++++++++++++++++-- CLAUDE.md | 7 +++- Tests/DashUIKitTests/DashIconTests.swift | 1 + docs/foundation.md | 4 +- 5 files changed, 84 insertions(+), 30 deletions(-) diff --git a/.github/scripts/conventions.sh b/.github/scripts/conventions.sh index 4c6a9eb..8d9e324 100755 --- a/.github/scripts/conventions.sh +++ b/.github/scripts/conventions.sh @@ -8,11 +8,12 @@ # dashAsset call whose name is not one literal is flagged; # 3. asset names written as literals (Image("…", bundle:), .custom("…", bundle:), # Color("…", bundle:), UIImage(named: "…", in:), …) exist, and are looked up -# in the package bundle (.module / .dashUIKit), not the host app's; a -# package-bundle lookup whose name is not one literal (a variable, -# interpolation, ternary, concatenation) is flagged, as is an empty one, since the -# name escapes this check: a bundled icon is a DashIcon case, a color a -# Color.dash token; +# in the package bundle (.module / .dashUIKit), not the host app's (a +# computed name in .main / nil / .none too); a package-bundle lookup whose +# name is not one literal (a variable, interpolation, ternary, +# concatenation) is flagged, since the name escapes this check: a bundled +# icon is a DashIcon case, a color a Color.dash token; an empty name ("") +# is flagged too; # 4. every imageset and colorset has a valid Contents.json naming at least one # image or color, every image it names exists, and no catalog folder provides # a namespace (names would gain a "Folder/" prefix); @@ -35,7 +36,8 @@ # looked up in a bundle passed in as a variable (Image+DashUI.swift resolves a # host's DashIconSource that way) or without one (Image(name) may be an # ImageResource; only UIImage(named:) and .custom are checked for their bundle -# then), a .custom(…) that is not after DashIconSource, +# then), the host bundle written other than .main / nil / .none (Optional.none, +# Bundle(for:)), a .custom(…) without a bundle that is not after DashIconSource, # `dash:` or an `…icon:` label, NSImage(named:), SwiftUI Text("…") and # LocalizedStringResource localization. Icon_DashUI.swift is # expected to keep each `case` list on one line. @@ -165,7 +167,7 @@ find "$src" -name '*.swift' -print0 | sort -z | } # Rule 3: literal asset names. - function assets(li, ml, base, call, before, open, kind, label, k, s, n, name, computed) { + function assets(li, ml, base, call, before, open, kind, label, k, s, n, name, computed, seen, names, empty, context, k2) { ml = M[li]; base = 0 while (match(substr(ml, base + 1), /(^|[^A-Za-z0-9_])(ImageResource|ColorResource|Image|UIImage|Color|UIColor|Label|Button|Toggle|Menu|Tab|ContentUnavailableView)[[:space:]]*(\.init)?[[:space:]]*\(|\.custom[[:space:]]*\(/)) { call = substr(ml, base + RSTART, RLENGTH) @@ -198,25 +200,30 @@ find "$src" -name '*.swift' -print0 | sort -z | computed = (amask[1] !~ /^[[:space:]]*"[[:space:]]*"[[:space:]]*$/ || index(atop[1], "\\")) if (k && pkg(amask[k]) && computed && file != icons && file != exempt) out(li, "asset name is not one literal, so the catalog check cannot follow it; use " (kind == "colorset" ? "a Color.dash token" : "a DashIcon case (DashIcon...source or .image)")) - # A computed name looked up in the host app bundle by name (a literal one - # gets the same report from bundle_ok below). - else if (k && computed && trim(amask[k]) ~ /^(nil|(Bundle[[:space:]]*)?\.main)$/) - out(li, label ": " trim(amask[k]) " is not the package bundle; use .dashUIKit") - # Other enums have a .custom case too: .custom counts only where a - # DashIconSource is expected (after `DashIconSource`, `dash:` or an - # `…icon:` / `…Icon:` label). - if (call ~ /custom/ && before !~ /(DashIconSource[[:space:]]*=?|(dash|[A-Za-z]*[Ii]con):)[[:space:]]*$/) continue - # "a" + b is an expression, not a name. - s = (index(amask[1], "+") ? "" : atop[1]); n = 0 + # The literal names in the call, each once. "a" + b is an expression, not + # a name. + s = (index(amask[1], "+") ? "" : atop[1]); n = 0; empty = 0 + split("", seen) while (match(s, /"([^"\\]|\\.)*"/)) { name = substr(s, RSTART + 1, RLENGTH - 2) s = substr(s, RSTART + RLENGTH) - if (name == "") { if (trim(amask[1]) == "\"\"") out(li, "empty asset name"); continue } - if (index(name, "\\")) continue - print "L\t" kind "\t" name "\t" file "\t" li - n++ + if (name == "") { empty = (trim(amask[1]) == "\"\""); continue } + if (index(name, "\\") || (name in seen)) continue + seen[name] = 1; names[++n] = name } - if (n) bundle_ok(label, li) + # Other enums have a .custom case too: its literals are read as names only + # where a DashIconSource is expected (after `DashIconSource`, `dash:` or + # an `…icon:` / `…Icon:` label) or when it passes a bundle, which in this + # package only DashIconSource.custom does. + context = (call !~ /custom/ || arg("bundle") || before ~ /(DashIconSource[[:space:]]*=?|(dash|[A-Za-z]*[Ii]con):)[[:space:]]*$/) + # A computed name looked up in the host app bundle, unless bundle_ok + # below reports the same call for the literals inside it. + if (k && computed && trim(amask[k]) ~ /^(nil|\.none|(Bundle[[:space:]]*)?\.main)$/ && !(context && n)) + out(li, label ": " trim(amask[k]) " is not the package bundle; use .dashUIKit") + if (!context) continue + if (empty) out(li, "empty asset name") + for (k2 = 1; k2 <= n; k2++) print "L\t" kind "\t" names[k2] "\t" file "\t" li + if (n || empty) bundle_ok(label, li) # UIImage(named: name) without in: always looks in the host app bundle, # and so does DashIconSource.custom(name) (bundle defaults to nil). else if (!arg(label) && call ~ /UI|custom/) diff --git a/.github/scripts/tests/conventions-test.sh b/.github/scripts/tests/conventions-test.sh index b219300..85938ff 100755 --- a/.github/scripts/tests/conventions-test.sh +++ b/.github/scripts/tests/conventions-test.sh @@ -39,8 +39,9 @@ write_fixture() { printf '%s\n' "$@" > "$work/tree/$fixture" } -# expect NAME fail|pass [NEEDLE...]: runs the script on the copy; a failure must -# exit 1 and print every needle, and none of the needles written as "!text". +# expect NAME fail|pass [NEEDLE...]: runs the script on the copy (a failure must +# exit 1); in either mode the output must contain every needle, and must not +# contain a needle written as "!text". expect() { local name=$1 want=$2 output status=0 needle missing="" shift 2 @@ -52,7 +53,7 @@ expect() { [[ "$output" == *"$needle"* ]] || missing="${missing} missing: ${needle}"$'\n' fi done - if { [ "$want" = pass ] && [ "$status" -eq 0 ]; } || + if { [ "$want" = pass ] && [ "$status" -eq 0 ] && [ -z "$missing" ]; } || { [ "$want" = fail ] && [ "$status" -eq 1 ] && [ -z "$missing" ]; }; then echo "ok ${name}" else @@ -260,7 +261,49 @@ expect "computed names in the package bundle" fail \ "${fixture}:23: in: Bundle.main is not the package bundle" \ "${fixture}:24: bundle: Bundle .main is not the package bundle" \ "${fixture}:25: asset name is not one literal" \ - '!no imageset named "icon-' + '!no imageset named "icon-' \ + '!no imageset named "menu-' \ + '!no imageset named "key"' + +# One defect, one report: a ternary of literals in the host bundle is reported +# by the literal path (bundle_ok) only, not also as a computed name. +fresh; write_fixture "let a = Image(flag ? \"${img}\" : \"${img}\", bundle: .main)" +host_report="${fixture}:1: bundle: .main is not the package bundle; use .dashUIKit" +expect "ternary in the host bundle, reported once" fail "$host_report" 'Conventions: 1 violation(s)' + +# A .custom that passes a bundle is a lookup wherever it is: a ternary's names +# are read and its host bundle reported once; a repeated missing name, once. +fresh; write_fixture \ + 'let x = foo(source: .custom(flag ? "a" : "b", bundle: .main))' \ + 'let y = Image(flag ? "nosuch-a" : "nosuch-a", bundle: .module)' \ + 'let z = Image("", bundle: .main)' +expect "ternary outside the context; repeated name; empty name in the host bundle" fail \ + "${fixture}:1: bundle: .main is not the package bundle" \ + "${fixture}:1: no imageset named \"a\"" \ + "${fixture}:2: asset name is not one literal" \ + "${fixture}:2: no imageset named \"nosuch-a\"" \ + "!${fixture}:2: no imageset named \"nosuch-a\" in Sources/DashUIKit/Resources/Media.xcassets"$'\n'"${fixture}:2: no imageset named" \ + "${fixture}:3: bundle: .main is not the package bundle" \ + "${fixture}:3: empty asset name" \ + 'Conventions: 7 violation(s)' + +# A computed name in the host bundle is reported wherever the call is. +fresh; write_fixture \ + 'var d1: DashIconSource { .custom(name, bundle: .main) }' \ + 'func d2() -> DashIconSource { return .custom(name, bundle: .main) }' \ + 'let d3 = NavigationBarCircleIcon(.custom(name, bundle: nil))' \ + 'let d4 = foo(source: .custom(name, bundle: .main))' \ + 'let d5 = Image(name, bundle: .none)' \ + 'func d6() -> DashIconSource { return .custom("nosuch-d6", bundle: .main) }' +expect "computed .custom names in the host bundle" fail \ + "${fixture}:5: bundle: .none is not the package bundle" \ + "${fixture}:6: bundle: .main is not the package bundle" \ + "${fixture}:6: no imageset named \"nosuch-d6\"" \ + 'Conventions: 7 violation(s)' \ + "${fixture}:1: bundle: .main is not the package bundle" \ + "${fixture}:2: bundle: .main is not the package bundle" \ + "${fixture}:3: bundle: nil is not the package bundle" \ + "${fixture}:4: bundle: .main is not the package bundle" # The resolver files may pass a name on; a computed token name is still flagged. fresh; echo 'func fixtureSource(_ n: String) -> DashIconSource { .custom(n, bundle: .dashUIKit) }' >> "$work/tree/$src/Foundation/Icon_DashUI.swift" diff --git a/CLAUDE.md b/CLAUDE.md index 388c357..ca0dfa6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,8 +57,11 @@ Sources/DashUIKit/ - **Icons:** pass a `DashIconSource` (`.system` / `.custom(name, bundle:)` / `.uiImage`) and render with `Image(dash: source)`. Custom assets resolve from `.dashUIKit`/`.module`. Inside the library a bundled icon is a `DashIcon` case (`DashIcon.Toast.info.source`, - `.image`), never a name built at runtime: CI rejects a package-bundle lookup whose name - is not one literal. + `.image`), never a name built at runtime: CI rejects a lookup in `.dashUIKit` / + `.module` whose name is not one literal, and a lookup in the host bundle (`.main`, + `nil`, `.none`). It is a text scan: the call shapes it cannot follow (a bundle in a + variable, `.custom(name)` with no bundle and no `dash:` / `icon:` label, …) are listed + in the script header. - **Availability:** don't annotate. The floor is declared in `Package.swift`; gate an API that needs something *newer* than it with `if #available(...)` in the body. - **UIKit-only files** are wrapped in `#if canImport(UIKit)` (e.g. `SearchBar`, `Toast`, diff --git a/Tests/DashUIKitTests/DashIconTests.swift b/Tests/DashUIKitTests/DashIconTests.swift index 6a4899e..f89cb9c 100644 --- a/Tests/DashUIKitTests/DashIconTests.swift +++ b/Tests/DashUIKitTests/DashIconTests.swift @@ -24,6 +24,7 @@ final class DashIconTests: XCTestCase { /// Every case names an imageset that ships in the package bundle, so a /// raw value that drifts from the catalog fails here, not as a blank image. + /// One line per group in `Foundation/Icon_DashUI.swift`: add a new group here. func testEveryCaseResolvesInThePackageBundle() { assertResolves(DashIcon.Common.self) assertResolves(DashIcon.Icons.self) diff --git a/docs/foundation.md b/docs/foundation.md index 980ed27..3da3974 100644 --- a/docs/foundation.md +++ b/docs/foundation.md @@ -134,5 +134,5 @@ the unselected segment), and illustrations File `Foundation/BundleToken.swift`. `Bundle.dashUIKit` is a convenience alias for `Bundle.module`, used when loading custom -assets from the package bundle (`Image("menu-send", bundle: .dashUIKit)`; inside the library -prefer `DashIcon`). +assets from the package bundle. For a bundled icon, `DashIcon` already does this with a +compile-checked name: `DashIcon.Menu.send.image` rather than `Image("menu-send", bundle: .dashUIKit)`. From 54f6fd6dc686decbd2da0f74bcb17a5a3f02db8d Mon Sep 17 00:00:00 2001 From: romchornyi <270373998+romchornyi@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:29:23 +0200 Subject: [PATCH 3/3] fix: hide the toast icon from VoiceOver VoiceOver read the icon by its asset name ("toast-warning, image") before the message. The icon is now hidden, and a new init takes an accessibilityLabel that VoiceOver reads instead of the message, for hosts that want the style spoken. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- Sources/DashUIKit/Components/Toast.swift | 22 +++++++++++++++++++++- docs/feedback.md | 14 ++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 11b6f30..6660d92 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ a component already exists before building your own. | `NavigationBarCircleIcon` | The nav bar's 34pt token circle around any icon | [Navigation & containers](docs/navigation-and-containers.md) | | `BottomSheet` | Sheet chrome (grabber + nav bar) with self-sizing support | [Navigation & containers](docs/navigation-and-containers.md) | | `MenuViewModifier` | Card chrome — rounded background + shadow | [Navigation & containers](docs/navigation-and-containers.md) | -| `Toast` | Blurred toast — warning/info/error/success/copied/loading | [Feedback](docs/feedback.md) | +| `Toast` | Blurred toast — warning/info/error/success/copied/loading/noInternet; optional VoiceOver label | [Feedback](docs/feedback.md) | | `LoadingIllustration` / `LoadingSpinner` | iOS-style activity spinner | [Feedback](docs/feedback.md) | | `SuccessIllustration` / `ErrorIllustration` | 90×90 status badges | [Feedback](docs/feedback.md) | | `XmarkIcon` | Code-drawn close (✕) icon | [Feedback](docs/feedback.md) | diff --git a/Sources/DashUIKit/Components/Toast.swift b/Sources/DashUIKit/Components/Toast.swift index 22fa582..184ac7b 100644 --- a/Sources/DashUIKit/Components/Toast.swift +++ b/Sources/DashUIKit/Components/Toast.swift @@ -54,29 +54,48 @@ public struct Toast: View { private let style: ToastStyle private let message: String + private let accessibilityLabel: Text private let onDismiss: (() -> Void)? public init( style: ToastStyle, message: String, onDismiss: (() -> Void)? = nil + ) { + self.init(style: style, message: message, accessibilityLabel: Text(message), onDismiss: onDismiss) + } + + /// `accessibilityLabel` is what VoiceOver reads instead of `message`, for a + /// host that wants the style spoken too ("Error, payment failed"). It is a + /// `Text`, so the host localizes it as it would a `Button` title. It replaces + /// the message's label, so pass a new one with every new message. The icon + /// itself is never read. + public init( + style: ToastStyle, + message: String, + accessibilityLabel: Text, + onDismiss: (() -> Void)? = nil ) { self.style = style self.message = message + self.accessibilityLabel = accessibilityLabel self.onDismiss = onDismiss } public var body: some View { HStack(alignment: .top, spacing: 8) { HStack(alignment: .top, spacing: 0) { + // Otherwise VoiceOver reads the asset name ("toast-warning, image"). leadingIcon .frame(width: 24, height: 24) + .accessibilityHidden(true) Text(message) .dashFont(.footnoteMedium) .foregroundColor(Color.dash.toastText) .padding(.vertical, 3) .padding(.leading, 8) + .accessibilityLabel(accessibilityLabel) } .padding(.trailing, 8) @@ -126,9 +145,10 @@ public struct Toast: View { #Preview { VStack(spacing: 12) { - Toast(style: .warning, message: "Sgome coins are not available", onDismiss: {}) + Toast(style: .warning, message: "Some coins are not available", onDismiss: {}) Toast(style: .info, message: "Heads up", onDismiss: {}) Toast(style: .error, message: "Something went wrong", onDismiss: {}) + Toast(style: .error, message: "Payment failed", accessibilityLabel: Text("Error, payment failed"), onDismiss: {}) Toast(style: .success, message: "Done", onDismiss: {}) Toast(style: .copied, message: "Copied to clipboard") Toast(style: .loading, message: "Loading…") diff --git a/docs/feedback.md b/docs/feedback.md index e10b0e7..5334a35 100644 --- a/docs/feedback.md +++ b/docs/feedback.md @@ -24,6 +24,20 @@ Toast( · `.noInternet`. Each draws a `DashIcon.Toast` case (`.warning`, `.info`, …, `.noWifi` for `.noInternet`). `.loading` instead renders the DS `LoadingSpinner`. +VoiceOver reads only the message; the icon is hidden from it. When the style matters to a +listener and the message does not say it, pass an `accessibilityLabel:` to read instead of +the message. It is a `Text`: a literal `Text("…")` is looked up in the app's main bundle, +`Text("…", bundle: .module)` in a package's, and a `String` variable is read as is. VoiceOver +reads it when focus lands on the message (the dismiss button is a separate stop); announcing +the toast as it appears is the host's job, like its presentation. The label replaces the +message's, for UI tests too, so build it from the same localized message, and add the new +key to the host's strings like any other: + +```swift +Toast(style: .error, message: paymentFailed, + accessibilityLabel: Text("Error, \(paymentFailed)")) // key "Error, %@" +``` + This is just the toast *view* — presentation/animation/auto-dismiss timing is the host's responsibility (e.g. overlay it and drive visibility yourself).