diff --git a/.github/scripts/conventions.sh b/.github/scripts/conventions.sh index c049c5e..3a36bf7 100755 --- a/.github/scripts/conventions.sh +++ b/.github/scripts/conventions.sh @@ -4,10 +4,16 @@ # # 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 +# 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); @@ -22,13 +28,21 @@ # # 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, -# `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. +# 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), 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, on its line or, when it starts the line, on the +# last line with code before it (past #if / #endif; a label-like `case .icon:` +# or `icon:` key counts too), NSImage(named:), SwiftUI Text("…") and LocalizedStringResource +# localization. Icon_DashUI.swift is expected to keep each `case` list on one +# line. # Run from the repository root (tests: .github/scripts/tests/conventions-test.sh). # Every rule runs; exits 1 if any reported a violation, 2 if it could not run. set -euo pipefail @@ -85,7 +99,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) { @@ -113,6 +127,14 @@ find "$src" -name '*.swift' -print0 | sort -z | function pkg(v) { return trim(v) ~ /^((Bundle[[:space:]]*)?\.(module|dashUIKit)|#bundle)$/ } function trim(s) { gsub(/^[[:space:]]+|[[:space:]]+$/, "", s); return s } function out(line, message) { print "R\t" file "\t" line "\t" message } + # lead(li, before): the code before a call; when the call starts its line, the + # last line with code before it too, past #if / #endif (`Image(dash:` / + # `.custom(…)`, `func` / `dashAsset(`). + function lead(li, before, k) { + if (before !~ /^[[:space:]]*$/) return before + for (k = li - 1; k > 0 && M[k] ~ /^[[:space:]]*(#(if|endif)([^A-Za-z0-9_].*)?)?$/; k--) ; + return k > 0 ? M[k] " " before : before + } # parse(li, col): the arguments of the call whose "(" is at M[li], col. # Fills nargs, alabel[k] ("" when unlabeled), atext[k] (source), amask[k], @@ -155,9 +177,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, seen, names, empty, context, k2) { 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,24 +194,47 @@ 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 - # 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 + # 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)")) + # 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 == "" || 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. + if (call ~ /^\.custom/) before = lead(li, before) + 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/) @@ -273,18 +318,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 = lead(li, substr(ml, 1, base + RSTART - 1)) open = base + RSTART + RLENGTH - 1 base = open + if (before ~ /(^|[^A-Za-z0-9_])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..e58dc44 100755 --- a/.github/scripts/tests/conventions-test.sh +++ b/.github/scripts/tests/conventions-test.sh @@ -39,16 +39,21 @@ 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. +# 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 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 ]; } || + if { [ "$want" = pass ] && [ "$status" -eq 0 ] && [ -z "$missing" ]; } || { [ "$want" = fail ] && [ "$status" -eq 1 ] && [ -z "$missing" ]; }; then echo "ok ${name}" else @@ -129,6 +134,12 @@ expect "token without colorset" fail 'Color+DashUI.swift:' 'no colorset named "N fresh; printf '%s\n' 'let fixtureToken = dashAsset(' ' "NoSuchSplit")' >> "$work/tree/$src/Foundation/Color+DashUI.swift" expect "token split over two lines" fail 'no colorset named "NoSuchSplit"' +fresh; printf '%s\n' 'extension DashColors { static func' ' dashAsset(_ name: Int) -> Color { .clear } }' >> "$work/tree/$src/Foundation/Color+DashUI.swift" +expect "dashAsset declared over two lines" pass '!needs one literal colorset name' + +fresh; printf '%s\n' 'extension DashColors { static let fixtureToken =' ' dashAsset("NoSuchNextLine") }' >> "$work/tree/$src/Foundation/Color+DashUI.swift" +expect "token on the line after its declaration" fail 'no colorset named "NoSuchNextLine"' + fresh; echo "let fixtureToken = 1 // was dashAsset(\"NoSuchToken\")" >> "$work/tree/$src/Foundation/Color+DashUI.swift" echo 'let other = xdashAsset("NoSuchOther")' >> "$work/tree/$src/Foundation/Color+DashUI.swift" dir=$(first_set colorset); cp -R "$dir" "${dir%/*}/LiteralOnly.colorset" @@ -160,7 +171,21 @@ fresh; write_fixture \ 'let p = Image(dash: .custom(style.iconName))' \ 'let q = DashButton(title: "x", leadingIcon: .custom(name))' \ 'let r: DashIconSource = .custom(name)' \ - 'let s = Tab("Home", image: "nope-tab")' + 'let s = Tab("Home", image: "nope-tab")' \ + 'let t = Image(dash:' \ + " .custom(\"${img}\"))" \ + 'let u = Image(dash:' \ + ' // a comment' \ + '' \ + ' .custom("nope-gap"))' \ + 'let v = DashButton(title: "x", leadingIcon:' \ + ' .custom(name))' \ + 'let w: DashIconSource =' \ + ' .custom("nope-type"))' \ + 'let x = Image(dash:' \ + '#if DEBUG' \ + ' .custom("nope-directive"))' \ + '#endif' expect "literal asset names" fail \ "${fixture}:1: no imageset named \"nope-one\"" \ "${fixture}:2: no colorset named \"NoSuchColor\"" \ @@ -180,31 +205,139 @@ expect "literal asset names" fail \ "${fixture}:18: asset looked up in the host app bundle: pass bundle" \ "${fixture}:19: asset looked up in the host app bundle: pass bundle" \ "${fixture}:20: asset looked up in the host app bundle: pass bundle" \ - "${fixture}:21: image: \"…\" is looked up in the host app bundle" + "${fixture}:21: image: \"…\" is looked up in the host app bundle" \ + "${fixture}:23: asset looked up in the host app bundle: pass bundle" \ + "${fixture}:27: no imageset named \"nope-gap\"" \ + "${fixture}:29: asset looked up in the host app bundle: pass bundle" \ + "${fixture}:31: no imageset named \"nope-type\"" \ + "${fixture}:34: no imageset named \"nope-directive\"" 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")' \ + 'let w = Text("x").font(' \ + ' .custom("Inter", size: 12))' \ + '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-' \ + '!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" +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..ca0dfa6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,6 +56,12 @@ 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 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`, @@ -70,8 +76,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..f89cb9c --- /dev/null +++ b/Tests/DashUIKitTests/DashIconTests.swift @@ -0,0 +1,60 @@ +// +// 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. + /// One line per group in `Foundation/Icon_DashUI.swift`: add a new group here. + 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..3da3974 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. For a bundled icon, `DashIcon` already does this with a +compile-checked name: `DashIcon.Menu.send.image` rather than `Image("menu-send", bundle: .dashUIKit)`. 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