From 7474b584b146e308c2d31945f3df8e592c9f74c4 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:44:56 +0100 Subject: [PATCH 01/13] Keep every source file simulator-only and on the package floor Locale+Identifier.swift was the one file outside #if targetEnvironment(simulator), so its 950-case enum compiled into device builds. LegibilityWeight's CustomStringConvertible conformance named iOS 13 only. --- .../EnvironmentVariationPreview/Helpers/LegibilityWeight.swift | 2 +- .../EnvironmentVariationPreview/Helpers/Locale+Identifier.swift | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/EnvironmentVariationPreview/Helpers/LegibilityWeight.swift b/Sources/EnvironmentVariationPreview/Helpers/LegibilityWeight.swift index 65834a1..bc811a2 100644 --- a/Sources/EnvironmentVariationPreview/Helpers/LegibilityWeight.swift +++ b/Sources/EnvironmentVariationPreview/Helpers/LegibilityWeight.swift @@ -2,7 +2,7 @@ import Foundation import SwiftUI -@available(iOS 13.0, *) +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) extension LegibilityWeight: CustomStringConvertible { public var description: String { switch self { diff --git a/Sources/EnvironmentVariationPreview/Helpers/Locale+Identifier.swift b/Sources/EnvironmentVariationPreview/Helpers/Locale+Identifier.swift index 1c2a33a..047a6ff 100644 --- a/Sources/EnvironmentVariationPreview/Helpers/Locale+Identifier.swift +++ b/Sources/EnvironmentVariationPreview/Helpers/Locale+Identifier.swift @@ -1,3 +1,4 @@ +#if targetEnvironment(simulator) import Foundation /// An extension to the `Locale` type, providing a custom initializer and an `Identifier` enumeration. @@ -954,3 +955,4 @@ extension Locale { case zu_za = "zu_ZA" } } +#endif From 1bc9b147845e94abb48ed80feedaec983d88d394 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:44:56 +0100 Subject: [PATCH 02/13] Add simulator tests for item lists, identity and captions --- .../EnvironmentVariationPreviewTests.swift | 45 ++++++++++++++++--- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/Tests/EnvironmentVariationPreviewTests/EnvironmentVariationPreviewTests.swift b/Tests/EnvironmentVariationPreviewTests/EnvironmentVariationPreviewTests.swift index 8306cc4..4d7cf6b 100644 --- a/Tests/EnvironmentVariationPreviewTests/EnvironmentVariationPreviewTests.swift +++ b/Tests/EnvironmentVariationPreviewTests/EnvironmentVariationPreviewTests.swift @@ -1,12 +1,45 @@ +// The library compiles only for the simulator, so these tests run there: +// `xcodebuild test -scheme EnvironmentVariationPreview -destination 'platform=iOS Simulator,name=…'`. +#if targetEnvironment(simulator) +import SwiftUI import XCTest @testable import EnvironmentVariationPreview final class EnvironmentVariationPreviewTests: XCTestCase { - func testExample() throws { - // XCTest Documenation - // https://developer.apple.com/documentation/xctest + func testArrayLiteralKeepsOrder() { + let list: EnvironmentValueItemList = [.colorScheme(.light), .colorScheme(.dark), .layoutDirection(.rightToLeft)] + XCTAssertEqual(list.count, 3) + XCTAssertEqual(list.map(\.description), [ + "colorScheme: light", + "colorScheme: dark", + "layoutDirection: rightToLeft", + ]) + } - // Defining Test Cases and Test Methods - // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods - } + func testEachItemHasItsOwnIdentity() { + let list: EnvironmentValueItemList = [.colorScheme(.light), .colorScheme(.light)] + XCTAssertNotEqual(list[0], list[1]) + XCTAssertEqual(Set(list.map(\.id)).count, 2) + XCTAssertEqual(list[0], list[0]) + } + + func testColorSchemeIsReadBackOnlyFromColorSchemeCases() { + let list: EnvironmentValueItemList = [.colorScheme(.dark), .isEnabled(false)] + XCTAssertEqual(list[0].colorScheme, .dark) + XCTAssertNil(list[1].colorScheme) + } + + func testDescriptionsNameTheirCase() { + XCTAssertEqual(EnvironmentValueItem.lineLimit(nil).description, "lineLimit: nil") + XCTAssertEqual(EnvironmentValueItem.lineLimit(2).description, "lineLimit: Optional(2)") + XCTAssertEqual(EnvironmentValueItem.legibilityWeight(.bold).description, "legibilityWeight: bold") + XCTAssertEqual(EnvironmentValueItem.legibilityWeight(nil).description, "legibilityWeight: nil") + XCTAssertEqual(EnvironmentValueItem.isEnabled(true).description, "isEnabled: true") + } + + func testDefaultVariationsBuildAView() { + let view = Text("Hello").environmentVariations() + XCTAssertNotNil(view) + } } +#endif From bb7a6f5b7c64df964d7a518a15f3eda38f243d91 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:44:56 +0100 Subject: [PATCH 03/13] Add architecture rules with swift-llm-check Seven rules from CODING_STANDARDS.md: simulator-only sources, the import budget, one availability floor, AnyView only in apply(to:), erased payloads name their type, and captions name their case. Detector tests and the generated docs/architecture-rules.md included. --- .gitignore | 4 +- .llm-check.yaml | 9 ++ AGENTS.md | 30 ++++ Architecture/Package.swift | 23 +++ .../ArchitectureTests/ArchitectureRules.swift | 61 +++++++ .../Tests/ArchitectureTests/Detect.swift | 125 ++++++++++++++ .../ArchitectureTests/DetectorTests.swift | 153 ++++++++++++++++++ .../Tests/ArchitectureTests/Rules.swift | 138 ++++++++++++++++ .../Tests/ArchitectureTests/Support.swift | 22 +++ CLAUDE.md | 1 + CODING_STANDARDS.md | 44 +++++ docs/architecture-rules.md | 148 +++++++++++++++++ 12 files changed, 757 insertions(+), 1 deletion(-) create mode 100644 .llm-check.yaml create mode 100644 AGENTS.md create mode 100644 Architecture/Package.swift create mode 100644 Architecture/Tests/ArchitectureTests/ArchitectureRules.swift create mode 100644 Architecture/Tests/ArchitectureTests/Detect.swift create mode 100644 Architecture/Tests/ArchitectureTests/DetectorTests.swift create mode 100644 Architecture/Tests/ArchitectureTests/Rules.swift create mode 100644 Architecture/Tests/ArchitectureTests/Support.swift create mode 100644 CLAUDE.md create mode 100644 CODING_STANDARDS.md create mode 100644 docs/architecture-rules.md diff --git a/.gitignore b/.gitignore index 3b29812..62c7a46 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .DS_Store -/.build +.build/ /Packages /*.xcodeproj xcuserdata/ @@ -7,3 +7,5 @@ DerivedData/ .swiftpm/config/registries.json .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata .netrc +/Architecture/Package.resolved +/Benchmarks/Package.resolved diff --git a/.llm-check.yaml b/.llm-check.yaml new file mode 100644 index 0000000..82e58a9 --- /dev/null +++ b/.llm-check.yaml @@ -0,0 +1,9 @@ +# swift-llm-check: what the rules in Architecture/ read. `Codebase()` finds the repository root here. +# A name matches any folder or file; a path with a slash matches from the root. +excludes: + - Architecture + - Benchmarks + - docs + - site +# Folders ending in Tests hold test code. +testSuffixes: [Tests] diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b69cbb1 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,30 @@ +# Agent notes + +`EnvironmentVariationPreview` is a SwiftUI library, not an app: one view modifier, `.environmentVariations([...])`, +that renders a view once per environment value (color scheme, dynamic type, layout direction, locale…) with a caption. +It compiles only for the simulator. Usage is in `README.md`. + +Read `CODING_STANDARDS.md` before writing code. + +## How to work +- **Smallest diff.** Every changed line traces to the request. Match the surrounding file's idioms (two-space indent, + DocC comments on public API). +- **Test first.** A bug gets a failing test; a new environment value gets a description test. +- A new environment value is a new `EnvironmentValueItem` case plus its branch in `apply(to:)` and in `description`. + +## Docs travel with code +- `README.md` is the user documentation; DocC comments are the API reference (Swift Package Index, see `.spi.yml`). +- `site/index.html` is the landing page (GitHub Pages, `.github/workflows/pages.yml`). Its code samples and install + snippet repeat the README: update them in the same change. + +## Build and test +- Host: `swift build --build-tests && swift test` builds an empty module (everything is simulator-only), which checks + the package resolves and the guards are intact. +- Simulator: `xcodebuild test -scheme EnvironmentVariationPreview -destination 'platform=iOS Simulator,name='` + runs the real tests. CI also builds for tvOS, watchOS and visionOS simulators. +- Architecture rules: `swift test --package-path Architecture` (macOS only) runs the mechanical part of + `CODING_STANDARDS.md` as [swift-llm-check](https://github.com/mackoj/swift-llm-check) rules, listed in + `docs/architecture-rules.md`. A failure prints the rule, why it exists and how to fix it: fix the code, never add a + baseline. A new or changed rule needs a `DetectorTests` case and + `LLM_CHECK_RECORD=1 swift test --package-path Architecture` to regenerate the document. +- Releases: tags are bare semver (`1.1.4`, no `v`), created with `gh release create`. diff --git a/Architecture/Package.swift b/Architecture/Package.swift new file mode 100644 index 0000000..5d5f25d --- /dev/null +++ b/Architecture/Package.swift @@ -0,0 +1,23 @@ +// swift-tools-version: 6.0 +import PackageDescription + +// EnvironmentVariationPreview's mechanical rules (CODING_STANDARDS.md) as tests, written with swift-llm-check. +// Test-only and macOS-only, so the library never builds it and its swift-tools-version 5.7.1 floor is unaffected. +// Run from the repository root: `swift test --package-path Architecture`. +let package = Package( + name: "Architecture", + platforms: [.macOS(.v14)], + dependencies: [ + .package(url: "https://github.com/mackoj/swift-llm-check.git", from: "0.4.1"), + .package(url: "https://github.com/swiftlang/swift-syntax.git", "601.0.0"..<"700.0.0"), + ], + targets: [ + .testTarget( + name: "ArchitectureTests", + dependencies: [ + .product(name: "LLMCheck", package: "swift-llm-check"), + .product(name: "SwiftSyntax", package: "swift-syntax"), + ] + ) + ] +) diff --git a/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift new file mode 100644 index 0000000..05da2cc --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/ArchitectureRules.swift @@ -0,0 +1,61 @@ +import LLMCheck +import Testing + +/// The rules, run on the repository. A failure prints the rule, why it exists and how to fix it. +@Suite("Architecture rules") +struct ArchitectureRules { + static func sources() throws -> Scope { try repository().productionCode.in("/Sources") } + + @Test func sourcesAreSimulatorOnly() throws { + let sources = try Self.sources() + #expect(sources.relativePaths.count > 5) + expectNone(Detect.codeOutsideSimulatorGuard(in: sources), rule: .sourcesAreSimulatorOnly) + } + + @Test func importsStayWithinBudget() throws { + expectNone(Detect.importsOverBudget(in: try Self.sources()), rule: .importsStayWithinBudget) + } + + @Test func availabilityNamesThePackageFloor() throws { + let found = Detect.availabilityOffTheFloor(in: try Self.sources(), floor: packageFloor) + expectNone(found, rule: .availabilityNamesThePackageFloor) + } + + @Test func publicTypesDeclareAvailability() throws { + let sources = try Self.sources() + #expect(sources.declarations.withModifier("public").count > 10) + expectNone(Detect.publicDeclarationsWithoutAvailability(in: sources), rule: .publicTypesDeclareAvailability) + } + + @Test func anyViewStaysInApply() throws { + let sources = try Self.sources() + #expect(sources.references(to: "AnyView").count > 40) + expectNone(Detect.anyViewOutsideApply(in: sources), rule: .anyViewStaysInApply) + } + + @Test func erasedPayloadsNameTheirType() throws { + expectNone(Detect.erasedPayloadsWithoutTypeComment(in: try Self.sources()), rule: .erasedPayloadsNameTheirType) + } + + @Test func descriptionsNameTheirCase() throws { + let sources = try Self.sources() + #expect(sources.containing("var description").relativePaths.count >= 2) + expectNone(Detect.descriptionsNamingAnotherCase(in: sources), rule: .descriptionsNameTheirCase) + } +} + +/// Keeps `docs/architecture-rules.md` in step with the rules. Regenerate with +/// `LLM_CHECK_RECORD=1 swift test --package-path Architecture`. +@Test func rulesDocumentIsUpToDate() throws { + let catalog = RuleCatalog(allRules) + #expect(catalog.duplicateIDs.isEmpty) + try expectFile( + "docs/architecture-rules.md", in: repository(), + matches: catalog.markdown( + title: "Architecture rules", + introduction: """ + The mechanical part of `CODING_STANDARDS.md`, enforced by the `Architecture/` package with \ + [swift-llm-check](https://github.com/mackoj/swift-llm-check): \ + `swift test --package-path Architecture` (macOS). Generated from its rules; do not edit by hand. + """)) +} diff --git a/Architecture/Tests/ArchitectureTests/Detect.swift b/Architecture/Tests/ArchitectureTests/Detect.swift new file mode 100644 index 0000000..992c468 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Detect.swift @@ -0,0 +1,125 @@ +import Foundation +import LLMCheck +import SwiftSyntax + +/// The detectors, separate from the codebase so `DetectorTests` can run them on snippets. +enum Detect { + /// Top-level code outside one whole-file `#if targetEnvironment(simulator)` with no `#else`. A file that is not + /// guarded at all is reported at its first statement; a guarded file at whatever sits beside the guard. + static func codeOutsideSimulatorGuard(in scope: Scope) -> [Match] { + scope.files.flatMap { file -> [Match] in + file.syntax.statements.compactMap { statement in + if let guarded = statement.item.as(IfConfigDeclSyntax.self), isSimulatorGuard(guarded) { return nil } + return Match(node: Syntax(statement), file: file) + } + } + } + + private static func isSimulatorGuard(_ node: IfConfigDeclSyntax) -> Bool { + node.clauses.count == 1 && node.clauses.first?.condition?.trimmedDescription == "targetEnvironment(simulator)" + } + + /// What the library may import. + static let allowedModules: Set = ["Foundation", "SwiftUI", "CoreData"] + + /// Imports of any other module. + static func importsOverBudget(in scope: Scope) -> [Match] { + scope.imports.filter { !allowedModules.contains($0.node.moduleName) } + } + + /// Platform names that make an `@available` a statement about the floor. + static let platformNames = ["iOS", "macOS", "tvOS", "watchOS", "visionOS", "macCatalyst"] + + /// `@available(…)` attributes that name a platform but not exactly the package floor. + static func availabilityOffTheFloor(in scope: Scope, floor: String) -> [Match] { + scope.containing("@available").nodes(of: AttributeSyntax.self) { match in + guard match.node.attributeName.trimmedDescription == "available", + let arguments = match.node.arguments?.trimmedDescription + else { return false } + let namesPlatform = arguments.split(whereSeparator: { !$0.isLetter }).contains { + platformNames.contains(String($0)) + } + return namesPlatform && arguments != floor + } + } + + /// Public types without `@available`, and public members of extensions when neither has it. + static func publicDeclarationsWithoutAvailability(in scope: Scope) -> [Declaration] { + scope.declarations.filter { declaration in + guard declaration.hasModifier("public"), !declaration.hasAttribute("available") else { return false } + switch declaration.kind { + case .struct, .class, .enum, .actor, .protocol: + return true + case .function, .initializer, .variable: + guard let parent = declaration.parent, parent.kind == .extension else { return false } + return !parent.hasAttribute("available") + default: + return false + } + } + } + + /// `AnyView` anywhere but inside `EnvironmentValueItem.apply`. + static func anyViewOutsideApply(in scope: Scope) -> [Match] { + scope.references(to: "AnyView").filter { !$0.declarationNames.contains("EnvironmentValueItem.apply") } + } + + /// Enum cases with an `Any` or `Any?` parameter and no `// TypeName` comment after them on the same line. A type + /// name is UpperCamelCase, so `// TODO` is not one. + static func erasedPayloadsWithoutTypeComment(in scope: Scope) -> [Match] { + scope.containing("case").nodes(of: EnumCaseDeclSyntax.self) { match in + let erased = match.node.elements.contains { element in + element.parameterClause?.parameters.contains { + ["Any", "Any?"].contains($0.type.trimmedDescription) + } ?? false + } + guard erased else { return false } + let trailing = match.node.lastToken(viewMode: .sourceAccurate)?.trailingTrivia ?? [] + return !trailing.contains { piece in + guard case .lineComment(let text) = piece else { return false } + let name = text.dropFirst(2).trimmingCharacters(in: .whitespaces) + return name.first?.isUppercase == true && name.contains(where: \.isLowercase) + && name.allSatisfy { $0.isLetter || $0.isNumber || $0 == "." } + } + } + } + + /// In the `switch` of a `description` property, `case .name(…)` whose first string literal does not start with + /// `"name: "`. Cases without a payload (`case .regular:`) are not checked. + static func descriptionsNamingAnotherCase(in scope: Scope) -> [Match] { + scope.containing("description").nodes(of: SwitchCaseSyntax.self) { match in + guard isInDescription(match.node), let name = payloadCaseName(match.node) else { return false } + guard let literal = match.node.statements.firstDescendant(of: StringLiteralExprSyntax.self), + let first = literal.segments.first?.as(StringSegmentSyntax.self) + else { return true } + return !first.content.text.hasPrefix("\(name): ") + } + } + + private static func isInDescription(_ node: some SyntaxProtocol) -> Bool { + sequence(first: Syntax(node), next: \.parent).contains { + $0.as(PatternBindingSyntax.self)?.pattern.trimmedDescription == "description" + } + } + + /// `name` for `case .name(let value):`; nil for anything else. + private static func payloadCaseName(_ node: SwitchCaseSyntax) -> String? { + guard let item = node.label.as(SwitchCaseLabelSyntax.self)?.caseItems.first, + let pattern = item.pattern.as(ExpressionPatternSyntax.self), + let call = pattern.expression.as(FunctionCallExprSyntax.self), + let member = call.calledExpression.as(MemberAccessExprSyntax.self), member.base == nil + else { return nil } + return member.declName.baseName.text + } +} + +extension SyntaxProtocol { + /// The first node of a type under this one, in source order. + fileprivate func firstDescendant(of type: Node.Type) -> Node? { + for child in children(viewMode: .sourceAccurate) { + if let node = child.as(Node.self) { return node } + if let node = child.firstDescendant(of: type) { return node } + } + return nil + } +} diff --git a/Architecture/Tests/ArchitectureTests/DetectorTests.swift b/Architecture/Tests/ArchitectureTests/DetectorTests.swift new file mode 100644 index 0000000..33f2380 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/DetectorTests.swift @@ -0,0 +1,153 @@ +import LLMCheck +import Testing + +/// Each detector on snippets: it finds what its rule forbids and nothing its rule allows. +@Suite struct DetectorTests { + func scope(_ source: String, at path: String = "Sources/EnvironmentVariationPreview/File.swift") -> Scope { + Scope(files: [SourceFile(path: path, source: source)]) + } + + @Test func unguardedCodeIsFound() { + let found = Detect.codeOutsideSimulatorGuard( + in: scope( + """ + import Foundation + #if targetEnvironment(simulator) + struct A {} + #else + struct B {} + #endif + #if os(iOS) + struct C {} + #endif + """)) + #expect(found.map(\.location.line) == [1, 2, 7]) + } + + @Test func guardedFilePasses() { + let found = Detect.codeOutsideSimulatorGuard( + in: scope( + """ + // A comment before the guard is fine. + #if targetEnvironment(simulator) + import SwiftUI + struct A {} + #endif + """)) + #expect(found.isEmpty) + } + + @Test func importsOverBudgetAreFound() { + let found = Detect.importsOverBudget( + in: scope( + """ + import Foundation + import SwiftUI + import CoreData + import UIKit + @testable import Combine + """)) + #expect(found.map(\.location.line) == [4, 5]) + } + + @Test func availabilityOffTheFloorIsFound() { + let found = Detect.availabilityOffTheFloor( + in: scope( + """ + @available(iOS 13.0, *) + extension A {} + @available(iOS 14.0, macOS 11.0, *) + struct B {} + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) + struct C {} + @available(*, deprecated, renamed: "d") + func e() {} + """), + floor: "iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *") + #expect(found.map(\.location.line) == [1, 3]) + } + + @Test func publicDeclarationsWithoutAvailabilityAreFound() { + let found = Detect.publicDeclarationsWithoutAvailability( + in: scope( + """ + public struct A { + public init() {} + } + @available(iOS 14.0, *) + public enum B {} + extension View { + public func c() {} + @available(iOS 14.0, *) + public func d() {} + func e() {} + } + @available(iOS 14.0, *) + extension B { + public var f: Int { 0 } + } + struct G {} + """)) + #expect(found.map(\.name) == ["A", "c"]) + } + + @Test func anyViewOutsideApplyIsFound() { + let found = Detect.anyViewOutsideApply( + in: scope( + """ + enum EnvironmentValueItem { + func apply(to content: V) -> some View { AnyView(content) } + } + struct Modifier: ViewModifier { + func body(content: Content) -> some View { AnyView(content) } + } + """)) + #expect(found.map(\.location.line) == [5]) + } + + @Test func erasedPayloadsWithoutCommentAreFound() { + let found = Detect.erasedPayloadsWithoutTypeComment( + in: scope( + """ + enum EnvironmentValueItem { + case dynamicTypeSize(Any) // DynamicTypeSize + case symbolRenderingMode(Any?) // SymbolRenderingMode + case controlSize(Any) + case menuOrder(Any) // TODO + case editMode(Binding?) + case colorScheme(ColorScheme) + } + """)) + #expect(found.map(\.location.line) == [4, 5]) + } + + @Test func descriptionsNamingAnotherCaseAreFound() { + let found = Detect.descriptionsNamingAnotherCase( + in: scope( + """ + enum EnvironmentValueItem { + var description: String { + switch self { + case .colorScheme(let value): return "colorScheme: \\(value)" + case .verticalSizeClass(let value): return "horizontalSizeClass: \\(value)" + case .font(let value): return "font \\(value)" + case .locale(let value): return String(describing: value) + } + } + var title: String { + switch self { + case .colorScheme(let value): return "anything" + } + } + } + extension LegibilityWeight { + public var description: String { + switch self { + case .regular: return "regular" + } + } + } + """)) + #expect(found.map(\.location.line) == [5, 6, 7]) + } +} diff --git a/Architecture/Tests/ArchitectureTests/Rules.swift b/Architecture/Tests/ArchitectureTests/Rules.swift new file mode 100644 index 0000000..a869394 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Rules.swift @@ -0,0 +1,138 @@ +import LLMCheck + +extension Rule { + static let sourcesAreSimulatorOnly = Rule( + id: "sources-are-simulator-only", + title: "Every file in `Sources` is wrapped, whole, in `#if targetEnvironment(simulator)`.", + category: .platforms, + rationale: """ + EnvironmentVariationPreview is a preview tool (CODING_STANDARDS.md, "Simulator only"): apps link it \ + from their UI modules, so whatever it compiles on a device ships in the App Store binary. Wrapping every \ + file keeps device and Mac builds empty, so the library costs nothing outside the simulator and the \ + canvas. A declaration outside the guard is compiled, and shipped, everywhere. + """, + howToFix: """ + Put the whole file, imports included, between `#if targetEnvironment(simulator)` on the first line and \ + `#endif` on the last, with no `#else`, like `Sources/EnvironmentVariationPreview/EnvironmentVariations.swift`. + """, + badExample: """ + import Foundation + + extension Locale { … } + """, + goodExample: """ + #if targetEnvironment(simulator) + import Foundation + + extension Locale { … } + #endif + """ + ) + + static let importsStayWithinBudget = Rule( + id: "imports-stay-within-budget", + title: "The library imports only Foundation, SwiftUI and CoreData.", + category: .platforms, + rationale: """ + The package has no dependencies and must build on every platform it lists (CODING_STANDARDS.md, \ + "No dependencies"). CoreData is there for the `managedObjectContext` environment value; UIKit or AppKit \ + would tie a file to one platform, and any other module is a new dependency for every client. + """, + howToFix: """ + Use SwiftUI or Foundation API. If an environment value needs a platform framework, wrap the case and its \ + import in `#if canImport(…)` and add the module to this rule's budget in the same pull request. + """, + badExample: "import UIKit", + goodExample: "import SwiftUI" + ) + + static let availabilityNamesThePackageFloor = Rule( + id: "availability-names-the-package-floor", + title: "Every `@available` that names platforms names the package floor: iOS 14, macOS 11, tvOS 14, watchOS 7.", + category: .platforms, + rationale: """ + The `platforms` in `Package.swift` are the floor, and the `@available` attributes repeat it so the DocC \ + pages and Xcode's quick help say where each API works. One attribute with another floor, such as \ + `@available(iOS 13.0, *)`, documents a version the package cannot be used on and forgets the other \ + platforms. Newer APIs are reached with `if #available` inside `EnvironmentValueItem.apply`, not with a \ + higher `@available` (CODING_STANDARDS.md, "One availability floor"). + """, + howToFix: "Write `@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)` exactly.", + badExample: "@available(iOS 13.0, *)\nextension LegibilityWeight: CustomStringConvertible {", + goodExample: """ + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) + extension LegibilityWeight: CustomStringConvertible { + """ + ) + + static let publicTypesDeclareAvailability = Rule( + id: "public-types-declare-availability", + title: "A public type, or a public member of an extension, carries `@available` itself or through its extension.", + category: .platforms, + rationale: """ + Without the attribute, DocC and quick help show the declaration as available everywhere, and the floor \ + in the generated documentation drifts from `Package.swift` (CODING_STANDARDS.md, "One availability \ + floor"). Members of a type that has the attribute inherit it. + """, + howToFix: "Add `@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)` to the type, extension or member.", + badExample: """ + extension View { + public func environmentVariations(_ variarions: EnvironmentValueItemList) -> some View { + """, + goodExample: """ + extension View { + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) + public func environmentVariations(_ variarions: EnvironmentValueItemList) -> some View { + """ + ) + + static let anyViewStaysInApply = Rule( + id: "any-view-stays-in-apply", + title: "`AnyView` appears only in `EnvironmentValueItem.apply(to:)`.", + category: .environmentValues, + rationale: """ + `apply(to:)` returns a different `.environment` type per case, and Swift's result builders cannot \ + return them from one `switch` without erasing, so that one function erases (CODING_STANDARDS.md, \ + "Type erasure in one place"). Anywhere else `AnyView` hides the view's identity from SwiftUI's diffing \ + and is avoidable with `some View` or `@ViewBuilder`. + """, + howToFix: "Return `some View`, or mark the function `@ViewBuilder` and let it build a `_ConditionalContent`.", + badExample: "func body(content: Content) -> some View { AnyView(content.padding()) }", + goodExample: "func body(content: Content) -> some View { content.padding() }" + ) + + static let erasedPayloadsNameTheirType = Rule( + id: "erased-payloads-name-their-type", + title: "An `EnvironmentValueItem` case whose payload is `Any` or `Any?` names the real type in a trailing comment.", + category: .environmentValues, + rationale: """ + Types newer than the floor, such as `DynamicTypeSize` (iOS 15), cannot appear in a case of an enum \ + available on iOS 14, so their payload is `Any` and `apply(to:)` casts it back under `if #available` \ + (CODING_STANDARDS.md, "Newer types as Any"). The comment is the only place that says what the cast \ + expects; a caller who passes anything else gets the content back unchanged, silently. + """, + howToFix: "End the case with `// TypeName`, the SwiftUI type that `apply(to:)` casts the payload to.", + badExample: "case dynamicTypeSize(Any)", + goodExample: "case dynamicTypeSize(Any) // DynamicTypeSize" + ) + + static let descriptionsNameTheirCase = Rule( + id: "descriptions-name-their-case", + title: "In a `description` switch, the string for `.name(let value)` starts with `\"name: \"`.", + category: .environmentValues, + rationale: """ + The description is the caption under each variation in the preview canvas, and the only thing that \ + tells two otherwise identical renders apart. A caption that names another case, such as one copied \ + from the line above, labels the screenshot wrong (CODING_STANDARDS.md, "Captions name the case"). + """, + howToFix: "Start the string with the case's name, a colon and a space, then interpolate the payload.", + badExample: "case .verticalSizeClass(let value): return \"horizontalSizeClass: \\(value.debugDescription)\"", + goodExample: "case .verticalSizeClass(let value): return \"verticalSizeClass: \\(value.debugDescription)\"" + ) +} + +/// Every rule, in the order `docs/architecture-rules.md` lists them. +let allRules: [Rule] = [ + .sourcesAreSimulatorOnly, .importsStayWithinBudget, .availabilityNamesThePackageFloor, + .publicTypesDeclareAvailability, .anyViewStaysInApply, .erasedPayloadsNameTheirType, .descriptionsNameTheirCase, +] diff --git a/Architecture/Tests/ArchitectureTests/Support.swift b/Architecture/Tests/ArchitectureTests/Support.swift new file mode 100644 index 0000000..f2027b9 --- /dev/null +++ b/Architecture/Tests/ArchitectureTests/Support.swift @@ -0,0 +1,22 @@ +import LLMCheck + +/// The EnvironmentVariationPreview repository, rooted where `.llm-check.yaml` is. Its file list and every parsed file +/// are shared by all suites, which Swift Testing runs in parallel. +func repository() throws -> Codebase { try Codebase() } + +/// The availability every public declaration names: the `platforms` floor in `Package.swift`. +let packageFloor = "iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *" + +extension RuleCategory { + static let platforms = RuleCategory( + "platforms", + description: """ + Simulator-only code, imports and availability. Read before you add a file, an `import` or an \ + `@available` to `Sources`. + """ + ) + static let environmentValues = RuleCategory( + "environment-values", + description: "`EnvironmentValueItem` and how it is applied. Read before you add or change an environment value." + ) +} diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md new file mode 100644 index 0000000..66d6cc3 --- /dev/null +++ b/CODING_STANDARDS.md @@ -0,0 +1,44 @@ +# Coding standards + +The conventions this library already follows, written down so a change keeps them. The mechanical ones are enforced +by the `Architecture/` package (`swift test --package-path Architecture`); see `docs/architecture-rules.md`. + +## Simulator only + +EnvironmentVariationPreview exists for SwiftUI previews and snapshot tests. Every file in `Sources` is wrapped, whole, +in `#if targetEnvironment(simulator)` … `#endif`, so device and Mac builds compile an empty module and an app that links +the library ships none of it. Tests are wrapped the same way and run on an iOS simulator. + +## No dependencies + +The package depends on nothing. The library imports Foundation, SwiftUI and CoreData (for `managedObjectContext`) +only. A platform framework (UIKit, AppKit) would tie a file to one platform. + +## One availability floor + +`Package.swift` sets the floor: iOS 14, macOS 11, tvOS 14, watchOS 7. Every public type, and every public member of +an extension, carries `@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)`, exactly. An API newer than the +floor is reached with `if #available` inside `EnvironmentValueItem.apply(to:)`, which falls back to the unchanged +content. + +## Newer types as `Any` + +An environment value whose type is newer than the floor (`DynamicTypeSize`, `Material`, `MenuOrder`…) cannot appear in +a case of an enum available on iOS 14. Its case takes `Any` (or `Any?`) and names the real type in a trailing comment: +`case dynamicTypeSize(Any) // DynamicTypeSize`. `apply(to:)` casts it back under `if #available`. + +## Type erasure in one place + +`EnvironmentValueItem.apply(to:)` returns a different `.environment` type per case, so it erases with `AnyView`. That +is the only `AnyView` in the library; everything else returns `some View`. + +## Captions name the case + +`EnvironmentValueItem.description` is the caption under each variation. The string for `.name(let value)` starts with +`"name: "`, followed by the value. + +## Style + +Two-space indentation, as in the existing files. Public API has a DocC comment (Swift Package Index builds the +documentation, see `.spi.yml`). The package keeps `swift-tools-version: 5.7.1`: `Architecture/` and `Benchmarks/` are +separate packages so they can use newer tools without raising it. Tests use XCTest, which every supported toolchain has. diff --git a/docs/architecture-rules.md b/docs/architecture-rules.md new file mode 100644 index 0000000..64b5d5f --- /dev/null +++ b/docs/architecture-rules.md @@ -0,0 +1,148 @@ +# Architecture rules + +The mechanical part of `CODING_STANDARDS.md`, enforced by the `Architecture/` package with [swift-llm-check](https://github.com/mackoj/swift-llm-check): `swift test --package-path Architecture` (macOS). Generated from its rules; do not edit by hand. + +## platforms + +Simulator-only code, imports and availability. Read before you add a file, an `import` or an `@available` to `Sources`. + +### Every file in `Sources` is wrapped, whole, in `#if targetEnvironment(simulator)`. + +`sources-are-simulator-only`: EnvironmentVariationPreview is a preview tool (CODING_STANDARDS.md, "Simulator only"): apps link it from their UI modules, so whatever it compiles on a device ships in the App Store binary. Wrapping every file keeps device and Mac builds empty, so the library costs nothing outside the simulator and the canvas. A declaration outside the guard is compiled, and shipped, everywhere. + +**How to fix:** Put the whole file, imports included, between `#if targetEnvironment(simulator)` on the first line and `#endif` on the last, with no `#else`, like `Sources/EnvironmentVariationPreview/EnvironmentVariations.swift`. + +Bad: + +```swift +import Foundation + +extension Locale { … } +``` + +Good: + +```swift +#if targetEnvironment(simulator) +import Foundation + +extension Locale { … } +#endif +``` + +### The library imports only Foundation, SwiftUI and CoreData. + +`imports-stay-within-budget`: The package has no dependencies and must build on every platform it lists (CODING_STANDARDS.md, "No dependencies"). CoreData is there for the `managedObjectContext` environment value; UIKit or AppKit would tie a file to one platform, and any other module is a new dependency for every client. + +**How to fix:** Use SwiftUI or Foundation API. If an environment value needs a platform framework, wrap the case and its import in `#if canImport(…)` and add the module to this rule's budget in the same pull request. + +Bad: + +```swift +import UIKit +``` + +Good: + +```swift +import SwiftUI +``` + +### Every `@available` that names platforms names the package floor: iOS 14, macOS 11, tvOS 14, watchOS 7. + +`availability-names-the-package-floor`: The `platforms` in `Package.swift` are the floor, and the `@available` attributes repeat it so the DocC pages and Xcode's quick help say where each API works. One attribute with another floor, such as `@available(iOS 13.0, *)`, documents a version the package cannot be used on and forgets the other platforms. Newer APIs are reached with `if #available` inside `EnvironmentValueItem.apply`, not with a higher `@available` (CODING_STANDARDS.md, "One availability floor"). + +**How to fix:** Write `@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)` exactly. + +Bad: + +```swift +@available(iOS 13.0, *) +extension LegibilityWeight: CustomStringConvertible { +``` + +Good: + +```swift +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension LegibilityWeight: CustomStringConvertible { +``` + +### A public type, or a public member of an extension, carries `@available` itself or through its extension. + +`public-types-declare-availability`: Without the attribute, DocC and quick help show the declaration as available everywhere, and the floor in the generated documentation drifts from `Package.swift` (CODING_STANDARDS.md, "One availability floor"). Members of a type that has the attribute inherit it. + +**How to fix:** Add `@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)` to the type, extension or member. + +Bad: + +```swift +extension View { + public func environmentVariations(_ variarions: EnvironmentValueItemList) -> some View { +``` + +Good: + +```swift +extension View { + @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) + public func environmentVariations(_ variarions: EnvironmentValueItemList) -> some View { +``` + +## environment-values + +`EnvironmentValueItem` and how it is applied. Read before you add or change an environment value. + +### `AnyView` appears only in `EnvironmentValueItem.apply(to:)`. + +`any-view-stays-in-apply`: `apply(to:)` returns a different `.environment` type per case, and Swift's result builders cannot return them from one `switch` without erasing, so that one function erases (CODING_STANDARDS.md, "Type erasure in one place"). Anywhere else `AnyView` hides the view's identity from SwiftUI's diffing and is avoidable with `some View` or `@ViewBuilder`. + +**How to fix:** Return `some View`, or mark the function `@ViewBuilder` and let it build a `_ConditionalContent`. + +Bad: + +```swift +func body(content: Content) -> some View { AnyView(content.padding()) } +``` + +Good: + +```swift +func body(content: Content) -> some View { content.padding() } +``` + +### An `EnvironmentValueItem` case whose payload is `Any` or `Any?` names the real type in a trailing comment. + +`erased-payloads-name-their-type`: Types newer than the floor, such as `DynamicTypeSize` (iOS 15), cannot appear in a case of an enum available on iOS 14, so their payload is `Any` and `apply(to:)` casts it back under `if #available` (CODING_STANDARDS.md, "Newer types as Any"). The comment is the only place that says what the cast expects; a caller who passes anything else gets the content back unchanged, silently. + +**How to fix:** End the case with `// TypeName`, the SwiftUI type that `apply(to:)` casts the payload to. + +Bad: + +```swift +case dynamicTypeSize(Any) +``` + +Good: + +```swift +case dynamicTypeSize(Any) // DynamicTypeSize +``` + +### In a `description` switch, the string for `.name(let value)` starts with `"name: "`. + +`descriptions-name-their-case`: The description is the caption under each variation in the preview canvas, and the only thing that tells two otherwise identical renders apart. A caption that names another case, such as one copied from the line above, labels the screenshot wrong (CODING_STANDARDS.md, "Captions name the case"). + +**How to fix:** Start the string with the case's name, a colon and a space, then interpolate the payload. + +Bad: + +```swift +case .verticalSizeClass(let value): return "horizontalSizeClass: \(value.debugDescription)" +``` + +Good: + +```swift +case .verticalSizeClass(let value): return "verticalSizeClass: \(value.debugDescription)" +``` From d2f319e44614e90957cca3509870ea050305c5bd Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:44:56 +0100 Subject: [PATCH 04/13] Add CI: host build, architecture rules, simulator tests, workflow lint --- .github/workflows/ci.yml | 52 +++++++++++++++++++++++++++++++++ .github/workflows/soundness.yml | 43 +++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/soundness.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..80d9a68 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,52 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + host: + name: macOS host + runs-on: macos-15 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + # Everything is simulator-only, so this builds an empty module: it checks the package and its guards. + - name: Build + run: swift build --build-tests + - name: Test + run: swift test + - name: Architecture rules + run: swift test --package-path Architecture + + simulators: + name: Simulators + runs-on: macos-15 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Test on an iOS simulator + run: | + udid=$(xcrun simctl list devices available --json \ + | jq -r '[.devices | to_entries[] | select(.key | contains("iOS")) | .value[] | select(.name | startswith("iPhone"))][0].udid') + echo "Testing on $udid" + xcodebuild test -scheme EnvironmentVariationPreview -destination "id=$udid" -quiet + - name: Build for tvOS, watchOS and visionOS simulators + run: | + for platform in "tvOS Simulator" "watchOS Simulator" "visionOS Simulator"; do + echo "::group::$platform" + xcodebuild build -scheme EnvironmentVariationPreview -destination "generic/platform=$platform" -quiet + echo "::endgroup::" + done diff --git a/.github/workflows/soundness.yml b/.github/workflows/soundness.yml new file mode 100644 index 0000000..b3410ac --- /dev/null +++ b/.github/workflows/soundness.yml @@ -0,0 +1,43 @@ +name: Soundness + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + actionlint: + name: Workflow lint + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Run actionlint + run: pipx run --spec actionlint-py==1.7.12.25 actionlint + + zizmor: + name: Workflow security audit + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Run zizmor + env: + # Online audits (impostor commits, known-vulnerable actions) read public repositories. + GH_TOKEN: ${{ github.token }} + run: pipx run --spec zizmor==1.30.1 zizmor --format github .github/workflows From 0cb9c73a19858b95f086dcc31fcf1fa8d8615476 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 02:53:05 +0100 Subject: [PATCH 05/13] Configure zizmor and actionlint: GitHub's own actions may be ref-pinned --- .github/actionlint.yaml | 5 +++++ .github/zizmor.yml | 6 ++++++ 2 files changed, 11 insertions(+) create mode 100644 .github/actionlint.yaml create mode 100644 .github/zizmor.yml diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000..a253ebe --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,5 @@ +# Every job runs on GitHub-hosted runners. +self-hosted-runner: + labels: [] +# The repository defines no configuration variables, so any `vars.*` reference is a typo. +config-variables: [] diff --git a/.github/zizmor.yml b/.github/zizmor.yml new file mode 100644 index 0000000..85df1f9 --- /dev/null +++ b/.github/zizmor.yml @@ -0,0 +1,6 @@ +rules: + unpinned-uses: + config: + policies: + # Setting policies replaces zizmor's defaults, so keep the default for GitHub's own actions. + "actions/*": ref-pin From 3f8bcde1e06e99fcc52987a927e23d3bb3e424da Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 03:01:02 +0100 Subject: [PATCH 06/13] Document why there is no benchmark package The library compiles to nothing on the host, where package-benchmark runs. Measured on an iPhone simulator instead: the library adds about 16 us to a 100 us render of eight variations, so there is no hot path to improve. --- docs/performance.md | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 docs/performance.md diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..c9d96ed --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,68 @@ +# Performance + +The short version: there is no hot path in EnvironmentVariationPreview, so there is no `Benchmarks/` package and no +performance change. This page records how that was checked, so the question does not need asking again. + +## Why there is no benchmark package + +The other mackoj packages measure with [package-benchmark](https://github.com/ordo-one/package-benchmark), which runs +a benchmark executable on the host: macOS or Linux. Every file in this library is wrapped in +`#if targetEnvironment(simulator)` (see `CODING_STANDARDS.md`), so on the host the module is empty: there is nothing +for a benchmark to call. A package-benchmark target cannot run inside the iOS simulator. + +## What the library does, measured where it runs + +The library's work is small and happens once per preview render: + +1. `EnvironmentValueItemList(arrayLiteral:)` wraps each `EnvironmentValueItem` in a `HashableEnvironmentValueItem`, + which makes one `UUID`. +2. `EnvironmentVariationsModifier.body` builds a `ForEach` of `VStack`s, one per item. +3. Per item, `EnvironmentValueItem.apply(to:)` wraps the content in one `.environment` modifier and one `AnyView`, and + `description` builds the caption string. + +Measured once, on an iPhone 17 simulator (iOS 27, Xcode 27.2, Debug build, Apple silicon), with a throwaway XCTest +that took the median of 200 runs (50 for the hosting rows). Eight variations: light, dark, right-to-left, three dynamic +type sizes, a locale and a legibility weight. + +| What | p50 | +| --- | ---: | +| Build an `EnvironmentValueItemList` of 8 items (8 `UUID`s) | 4.7 µs | +| Build the 8 captions (`description`) | 10.3 µs | +| Apply `.environmentVariations` to a `Text` (value construction only) | 4.6 µs | +| Host and lay out the 8 variations in a `UIHostingController` | 113 µs | +| Baseline: host and lay out 8 plain padded `Text`s, no library | 97 µs | + +The library adds about 16 µs to a render that SwiftUI itself spends about 100 µs on, and the preview canvas spends +milliseconds compiling and launching around it. Rewriting `apply(to:)` without `AnyView` or caching captions would +save microseconds nobody can see. + +## What has paid off + +Nothing yet: no change was made for speed or memory, because none would be measurable by a user. + +## Not changed on purpose + +`HashableEnvironmentValueItem` makes a new `UUID` every time a list is built, and `.environmentVariations()` builds its +default list on each call. So when a preview's parent re-evaluates its body, every variation gets a new identity and +SwiftUI rebuilds it rather than updating it, which also resets any `@State` inside the previewed view. Making the +identity stable (for example from the item's position) would change the public `id` and `Hashable` semantics of +`HashableEnvironmentValueItem`, so it is a behaviour change for a major or minor release, not a performance patch. In a +static preview, which is what the library is for, it costs nothing. + +## Measuring again + +If the library grows real work (say, generating combinations of values), add a `Benchmarks/` package that compiles the +pure part without the simulator guard, as the other mackoj packages do, and record the p50 table here. Until then, a +throwaway XCTest on a simulator, like the one above, is the honest tool: + +```swift +func p50(_ runs: Int = 200, _ body: () -> Void) -> Double { + var samples: [Double] = [] + for _ in 0.. Date: Sat, 14 Nov 2026 03:01:13 +0100 Subject: [PATCH 07/13] Add a GitHub Pages landing page --- .github/workflows/pages.yml | 41 +++++ site/index.html | 351 ++++++++++++++++++++++++++++++++++++ 2 files changed, 392 insertions(+) create mode 100644 .github/workflows/pages.yml create mode 100644 site/index.html diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..deef31c --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,41 @@ +name: Pages + +# Publishes site/, the project's landing page, to GitHub Pages when it changes on main. +on: + push: + branches: [main] + paths: [site/**, .github/workflows/pages.yml] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + deploy: + name: Deploy + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Configure Pages + uses: actions/configure-pages@v5 + - name: Upload site + uses: actions/upload-pages-artifact@v3 + with: + path: site + - name: Deploy + id: deployment + uses: actions/deploy-pages@v4 diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..ab9d5a7 --- /dev/null +++ b/site/index.html @@ -0,0 +1,351 @@ + + + + + +EnvironmentVariationPreview · every environment in one SwiftUI preview + + + + + + + + + + + +
+
+
+
    +
  • SwiftUI
  • iOS 14+ · tvOS · watchOS · visionOS
  • Zero dependencies
  • +
+

Every environment.
One preview.

+

One view modifier renders your SwiftUI view under every environment you care about, side by side and captioned: light and dark, right-to-left, the smallest and largest dynamic type, any locale, and 30 more environment values.

+ +
+
+
+
ProfileCard.swift
+
import SwiftUI
+import EnvironmentVariationPreview
+
+struct ProfileCard_Previews: PreviewProvider {
+  static var previews: some View {
+    ProfileCard()
+      .environmentVariations([
+        .colorScheme(.light),
+        .colorScheme(.dark),
+        .layoutDirection(.rightToLeft),
+        .dynamicTypeSize(DynamicTypeSize.xSmall),
+        .dynamicTypeSize(DynamicTypeSize.xxxLarge),
+        .locale(Locale(identifier: "fr_FR")),
+      ])
+  }
+}
+
+ +
+
+
+ +
+
+

The problem

+

Your view works. In one environment.

+

Each preview shows one combination of settings. The bugs live in the others: the label that truncates at the largest text size, the chevron that points the wrong way right-to-left, the gray-on-black that vanishes in dark mode.

+
+
12

Dynamic type sizes

From xSmall to accessibility5. Large text is where layouts break, and it is the setting you are least likely to have on.

+
2 × 2

Schemes and directions

Light and dark, left-to-right and right-to-left. A preview per combination means copying the same view four times.

+
40

Environment values

Locale, size classes, legibility weight, redaction, line limits, symbol variants… each one a .environment(\.key, value) you have to remember.

+
+
+
+ +
+
+

How it works

+

One modifier. One list. Captioned renders.

+
+
    +
  1. List the environments

    An array literal of EnvironmentValueItem cases: .colorScheme(.dark), .locale(…), .horizontalSizeClass(.compact).

  2. +
  3. Apply .environmentVariations

    On the view in your preview. With no argument it shows light and dark.

  4. +
  5. Read the canvas

    One render per value, each with a black caption naming the case and its value, on a background that follows its color scheme. Ready for a snapshot test, too.

  6. +
+
+
+
Defaults, alignment and spacing
+
// Light and dark, the default.
+ProfileCard().environmentVariations()
+
+// Leading-aligned captions, 16 points between view and caption.
+ProfileCard().environmentVariations(
+  [.horizontalSizeClass(.compact), .horizontalSizeClass(.regular)],
+  .leading,
+  16
+)
+
+// Values whose type is newer than iOS 14 take the type's name.
+ProfileCard().environmentVariations([
+  .dynamicTypeSize(DynamicTypeSize.accessibility5),
+  .legibilityWeight(.bold),
+  .redactionReasons(.placeholder),
+])
+
+
+
+
+
+ +
+
+

Why this library

+

Small, safe to depend on.

+
+

Nothing ships

Every file is wrapped in #if targetEnvironment(simulator). Device and Mac builds compile an empty module, so linking it from a UI package costs your App Store binary nothing.

+

Zero dependencies

Foundation, SwiftUI and CoreData (for managedObjectContext). Nothing else to resolve, audit or update.

+

iOS 14 and up

Values newer than the floor, like DynamicTypeSize or Material, apply under #available and fall back to the unchanged view on older systems.

+

Captions you can trust

Each render is labelled with its case and value, so screenshots and snapshot diffs say which environment broke.

+

Every Apple simulator

CI builds for iOS, tvOS, watchOS and visionOS simulators and runs the tests on an iPhone simulator.

+

Checked conventions

The library's rules (simulator guard, imports, availability, captions) run as swift-llm-check tests. Read them.

+
+
+
+ +
+
+

Supported values

+

40 environment values, one enum.

+

Each is a case of EnvironmentValueItem named after its EnvironmentValues key.

+
+

Appearance

    +
  • colorScheme
  • backgroundMaterial
  • backgroundStyle
  • displayScale
  • imageScale
  • symbolVariants
  • symbolRenderingMode
  • isLuminanceReduced
  • redactionReasons
  • +
+

Text

    +
  • dynamicTypeSize
  • font
  • legibilityWeight
  • lineLimit
  • lineSpacing
  • minimumScaleFactor
  • multilineTextAlignment
  • truncationMode
  • allowsTightening
  • textCase
  • +
+

Locale and layout

    +
  • locale
  • calendar
  • timeZone
  • layoutDirection
  • horizontalSizeClass
  • verticalSizeClass
  • defaultMinListRowHeight
  • defaultMinListHeaderHeight
  • headerProminence
  • +
+

Behaviour

    +
  • isEnabled
  • accessibilityEnabled
  • isScrollEnabled
  • autocorrectionDisabled
  • disableAutocorrection
  • scenePhase
  • openURL
  • managedObjectContext
  • menuOrder
  • contentTransition
  • contentTransitionAddsDrawingGroup
  • scrollDismissesKeyboardMode
  • +
+
+
+
+ +
+
+

Install

+

Add it with Swift Package Manager.

+
+
+
Package.swift
+
dependencies: [
+  .package(
+    url: "https://github.com/mackoj/EnvironmentVariationPreview.git",
+    from: "1.1.4"
+  ),
+],
+targets: [
+  .target(
+    name: "MyUI",
+    dependencies: ["EnvironmentVariationPreview"]
+  ),
+]
+
+
+

In Xcode

+

File › Add Package Dependencies…, paste https://github.com/mackoj/EnvironmentVariationPreview.git, and add the EnvironmentVariationPreview library to the target that holds your views.

+

Requirements

+

Swift 5.7.1 or later (Xcode 14.1+). iOS 14, macOS 11, tvOS 14, watchOS 7 or visionOS, running in a simulator or the preview canvas.

+
+
+

Simulator only, on purpose. Outside the simulator the module is empty, so a call to .environmentVariations belongs in a preview or a test, which only build for the simulator. Wrap any other use in #if targetEnvironment(simulator).

+
+
+ + + + From fa5fa898dc1c0692d00043a37838473eab0ac4f0 Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 03:03:57 +0100 Subject: [PATCH 08/13] Test the README and site snippets on the simulator --- .../EnvironmentVariationPreviewTests.swift | 17 +++++++ .../ReadmeTests.swift | 44 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 Tests/EnvironmentVariationPreviewTests/ReadmeTests.swift diff --git a/Tests/EnvironmentVariationPreviewTests/EnvironmentVariationPreviewTests.swift b/Tests/EnvironmentVariationPreviewTests/EnvironmentVariationPreviewTests.swift index 4d7cf6b..09bdabc 100644 --- a/Tests/EnvironmentVariationPreviewTests/EnvironmentVariationPreviewTests.swift +++ b/Tests/EnvironmentVariationPreviewTests/EnvironmentVariationPreviewTests.swift @@ -41,5 +41,22 @@ final class EnvironmentVariationPreviewTests: XCTestCase { let view = Text("Hello").environmentVariations() XCTAssertNotNil(view) } + + /// The captions drawn on site/index.html. + func testCaptionsShownOnTheSite() { + let list: EnvironmentValueItemList = [ + .colorScheme(.light), .colorScheme(.dark), .layoutDirection(.rightToLeft), + .dynamicTypeSize(DynamicTypeSize.xSmall), .dynamicTypeSize(DynamicTypeSize.xxxLarge), + ] + XCTAssertEqual(list.map(\.description), [ + "colorScheme: light", + "colorScheme: dark", + "layoutDirection: rightToLeft", + "dynamicTypeSize: xSmall", + "dynamicTypeSize: xxxLarge", + ]) + let locale: EnvironmentValueItemList = [.locale(Locale(identifier: "fr_FR"))] + XCTAssertTrue(locale[0].description.hasPrefix("locale: fr_FR"), locale[0].description) + } } #endif diff --git a/Tests/EnvironmentVariationPreviewTests/ReadmeTests.swift b/Tests/EnvironmentVariationPreviewTests/ReadmeTests.swift new file mode 100644 index 0000000..56c64cc --- /dev/null +++ b/Tests/EnvironmentVariationPreviewTests/ReadmeTests.swift @@ -0,0 +1,44 @@ +// Mirrors the snippets in README.md and site/index.html, so a snippet that stops compiling fails here. +#if targetEnvironment(simulator) +import SwiftUI +import XCTest +import EnvironmentVariationPreview + +private struct ProfileCard: View { + var body: some View { + HStack { + Circle().frame(width: 32, height: 32) + VStack(alignment: .leading) { + Text("Ada Lovelace").font(.headline) + Text(Date(timeIntervalSince1970: 1_680_000_000), style: .date) + } + } + } +} + +final class ReadmeTests: XCTestCase { + func testUsage() { + let view = ProfileCard() + .environmentVariations([ + .colorScheme(.light), + .colorScheme(.dark), + .layoutDirection(.rightToLeft), + .dynamicTypeSize(DynamicTypeSize.xSmall), + .dynamicTypeSize(DynamicTypeSize.large), + .dynamicTypeSize(DynamicTypeSize.xxxLarge), + .locale(Locale(identifier: "fr_FR")), + ]) + XCTAssertNotNil(view) + } + + func testDefaultsAlignmentAndSpacing() { + _ = ProfileCard().environmentVariations() + _ = ProfileCard().environmentVariations([.horizontalSizeClass(.compact), .horizontalSizeClass(.regular)], .leading, 16) + _ = ProfileCard().environmentVariations([ + .dynamicTypeSize(DynamicTypeSize.accessibility5), + .legibilityWeight(.bold), + .redactionReasons(.placeholder), + ]) + } +} +#endif From b13652dcee37c7b22e09edd53e2ef45e03675aed Mon Sep 17 00:00:00 2001 From: Jeffrey Macko Date: Sat, 14 Nov 2026 03:04:10 +0100 Subject: [PATCH 09/13] Rewrite the README: site link, compiling snippets, supported values The usage snippet wrote .dynamicTypeSize(.xSmall), which does not compile because the payload is Any. Install from 1.1.4, link the site and docs, list the supported values and the cases that are no-ops. --- README.md | 109 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 70 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 20a9835..7f6e139 100644 --- a/README.md +++ b/README.md @@ -1,83 +1,114 @@ +[![CI](https://github.com/mackoj/EnvironmentVariationPreview/actions/workflows/ci.yml/badge.svg)](https://github.com/mackoj/EnvironmentVariationPreview/actions/workflows/ci.yml) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fmackoj%2FEnvironmentVariationPreview%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/mackoj/EnvironmentVariationPreview) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fmackoj%2FEnvironmentVariationPreview%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/mackoj/EnvironmentVariationPreview) # EnvironmentVariationPreview -EnvironmentVariationPreview is a SwiftUI library designed to simplify the process of previewing your SwiftUI views in a variety of environments. The code of this library work exclusively with the simulator. +**[Website](https://mackoj.github.io/EnvironmentVariationPreview/)** · +**[Architecture rules](docs/architecture-rules.md)** · +**[Performance](docs/performance.md)** + +One SwiftUI view modifier, `.environmentVariations([...])`, that renders a view once per environment value, side by +side and captioned: light and dark, right-to-left, the smallest and largest dynamic type, any locale, and 30 more +environment values. It compiles only for the simulator, so it ships nothing in your app. | video | image | | --- | --- | -|