chore(lint): SwiftLint-Config + 0-Warnings-Pass + Swift-6-Concurrency-Fixes

Bringt cards-native auf 0 SwiftLint-Violations bei 75 Files. Build-Status
unverändert grün (xcodebuild iOS Debug).

.swiftlint.yml
- identifier_name excludes erweitert um math/index-Konventionen
  (i, j, n, m, x, y, w, h, r, g, b, a, c, d, s, f, p, q, t, l) —
  in algorithmischem Code klarer als verbose
- opening_brace disabled — kollidiert mit SwiftFormats
  wrapMultilineStatementBraces (SwiftFormat ist im Pre-Commit-Hook
  und gewinnt)

Code-Modernisierungen (real, nicht nur Annotations)
- Cloze.swift: regex-Tuple bekommt `swiftlint:disable large_tuple`-
  Region — Regex-Output-Type ist Builder-bedingt nicht reduzierbar
- Media.swift: `data(using: .utf8)` → `Data(s.utf8)` (non-failable),
  `String(data:as:)` → `String(bytes:encoding:)`
- CardsTheme.swift: HSL-Wert-Typ statt anonymes 3-Tupel —
  konkretere Call-Sites, kein `large_tuple`-Warning mehr
- MediaCache.swift: `CacheEntry`-Struct statt 3-Tupel im Prune-Pfad
- GradeQueue / MediaCache / StudySession / MarketplaceStore: OSLog-
  Interpolations auf lokale Variablen ziehen — fixt Swift-6-Strict-
  Concurrency-Fail bei Actor-isolated-Property-Zugriff aus
  @Sendable-Autoclosure
- DeckMutations.swift, MarketplaceModeration.swift: verschachtelte
  VersionInfo-Sub-Types auf Top-Level (`PullUpdateVersion`,
  `OwnedMarketplaceVersion`) — fixt `nesting`-Warning
- Tests/UnitTests/*.swift: alle `""".data(using: .utf8)!` migriert auf
  `Data("""…""".utf8)`; force-cast `as!` in MutationEncodingTests
  durch guard-let + throw ersetzt

Pragmatische Disables (mit Doc-Comment-Begründung)
- DeckEditorView / MarketplacePublishView / DeckDetailView /
  PublicDeckView / DeckListView / CardEditorView / CardsAPI:
  `swiftlint:disable type_body_length` (+ teilweise file_length)
  als Region-Disable mit `enable` nach dem Struct. Begründung im
  Doc-Comment: Multi-State-Maschinen mit shared Toolbar + Sheets;
  Aufspalten würde nur @Binding-Plumbing produzieren

Auto-Format-Aufräumung
- Redundante `Sendable`-Conformance entfernt (Swift 6 leitet das
  bei Wert-Typen mit Sendable-Mitgliedern automatisch ab)
- EnvironmentValues nutzt jetzt @Entry-Macro statt manueller
  EnvironmentKey-Boilerplate
- Brace-Reformatting + Import-Sortierung auf allen 75 Files

Ergebnis: 80 Warnings + 3 Errors → 0 / 0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Till JS 2026-05-14 02:04:29 +02:00
parent 73f9081fa1
commit aece169360
37 changed files with 489 additions and 349 deletions

View file

@ -2,7 +2,7 @@ import Foundation
/// Card-DTO. Wire-Format aus `cards/apps/api/src/lib/dto.ts:toCardDto`
/// und `cards/packages/cards-domain/src/schemas/card.ts`.
struct Card: Codable, Identifiable, Hashable, Sendable {
struct Card: Codable, Identifiable, Hashable {
let id: String
let deckId: String
let userId: String
@ -29,7 +29,7 @@ struct Card: Codable, Identifiable, Hashable, Sendable {
/// Card-Type-Enum. Vollständig aus `CardTypeSchema`. In β-2 rendern
/// wir nur `basic`, `basic-reverse`, `cloze`. Die anderen Types
/// kommen in β-3 und β-4 dazu, sind aber jetzt schon decodierbar.
enum CardType: String, Codable, Sendable, CaseIterable {
enum CardType: String, Codable, CaseIterable {
case basic
case basicReverse = "basic-reverse"
case cloze
@ -43,7 +43,7 @@ enum CardType: String, Codable, Sendable, CaseIterable {
/// Server liefert nur 4 Felder (id, deckId, type, fields) als Drizzle-
/// Joined-Subset Achtung: `deckId` hier in **camelCase**, nicht
/// snake_case wie sonst.
struct ReviewCard: Codable, Hashable, Sendable {
struct ReviewCard: Codable, Hashable {
let id: String
let deckId: String
let type: CardType

View file

@ -10,7 +10,7 @@ import Foundation
/// - multiple-choice: `front`, `answer`
/// - image-occlusion: `image_ref`, `mask_regions` (β-4)
/// - audio-front: `audio_ref`, `back` (β-4)
struct CardCreateBody: Encodable, Sendable {
struct CardCreateBody: Encodable {
let deckId: String
let type: CardType
let fields: [String: String]
@ -26,7 +26,7 @@ struct CardCreateBody: Encodable, Sendable {
/// Body für `PATCH /api/v1/cards/:id`. Nur `fields` und `media_refs`
/// Type und deck_id sind immutable (Server-Schema).
struct CardUpdateBody: Encodable, Sendable {
struct CardUpdateBody: Encodable {
var fields: [String: String]?
var mediaRefs: [String]?

View file

@ -12,12 +12,18 @@ import Foundation
/// 1-basierte Cluster-ID. Mehrere Cluster pro Karte mehrere
/// Sub-Index-Reviews.
enum Cloze {
// swiftlint:disable large_tuple
/// Pattern für `{{cN::answer(::hint)?}}`. Pro Call konstruiert,
/// weil `Regex` unter Strict-Concurrency nicht Sendable ist.
/// Tuple-Output (whole-match, id, answer, hint?) ist Regex-Builder-
/// bedingt Lint-Regel `large_tuple` greift hier nicht.
private static var clusterPattern: Regex<(Substring, Substring, Substring, Substring?)> {
#/\{\{c(\d+)::([^}]*?)(?:::([^}]*?))?\}\}/#
}
// swiftlint:enable large_tuple
/// Distinct Cluster-IDs, sortiert.
static func extractClusterIds(_ text: String) -> [Int] {
var ids = Set<Int>()

View file

@ -2,7 +2,7 @@ import Foundation
/// Deck-DTO. Wire-Format aus `cards/apps/api/src/lib/dto.ts:toDeckDto`.
/// snake_case-Felder via `CodingKeys`, Optionals explizit nullable.
struct Deck: Codable, Identifiable, Hashable, Sendable {
struct Deck: Codable, Identifiable, Hashable {
let id: String
let userId: String
let name: String
@ -41,14 +41,14 @@ struct Deck: Codable, Identifiable, Hashable, Sendable {
}
}
enum DeckVisibility: String, Codable, Sendable {
enum DeckVisibility: String, Codable {
case `private`
case space
case `public`
}
/// Aus `cards/packages/cards-domain/src/schemas/deck.ts:DECK_CATEGORY_IDS`.
enum DeckCategory: String, Codable, Sendable, CaseIterable {
enum DeckCategory: String, Codable, CaseIterable {
case language
case medicine
case science
@ -82,7 +82,7 @@ enum DeckCategory: String, Codable, Sendable, CaseIterable {
/// FSRS-Settings Native bleibt schematisch agnostisch, FSRS rechnet
/// nur der Server. Wir behalten die Felder als roh-JSON, damit eine
/// neue Setting auf dem Server uns nicht bricht.
struct FsrsSettings: Codable, Sendable, Hashable {
struct FsrsSettings: Codable, Hashable {
let requestRetention: Double?
let maximumInterval: Int?
let enableFuzz: Bool?
@ -114,23 +114,23 @@ struct FsrsSettings: Codable, Sendable, Hashable {
}
/// Server-Response von `GET /api/v1/decks`.
struct DeckListResponse: Decodable, Sendable {
struct DeckListResponse: Decodable {
let decks: [Deck]
let total: Int
}
/// Server-Response von `GET /api/v1/cards?deck_id=...`.
struct CardListResponse: Decodable, Sendable {
struct CardListResponse: Decodable {
let cards: [Card]
let total: Int
}
/// Server-Response von `GET /api/v1/reviews/due?deck_id=...`.
struct DueReviewsResponse: Decodable, Sendable {
struct DueReviewsResponse: Decodable {
let total: Int
}
/// Server-Response von `GET /api/v1/decks/:deckId/distractors`.
struct DistractorsResponse: Decodable, Sendable {
struct DistractorsResponse: Decodable {
let distractors: [String]
}

View file

@ -1,7 +1,7 @@
import Foundation
/// Browse-Eintrag aus `/api/v1/marketplace/decks` und `.../explore`.
struct PublicDeckEntry: Codable, Hashable, Sendable, Identifiable {
struct PublicDeckEntry: Codable, Hashable, Identifiable {
let slug: String
let title: String
let description: String?
@ -16,7 +16,9 @@ struct PublicDeckEntry: Codable, Hashable, Sendable, Identifiable {
let createdAt: Date
let owner: PublicDeckOwner
var id: String { slug }
var id: String {
slug
}
enum CodingKeys: String, CodingKey {
case slug, title, description, language, category, license
@ -29,10 +31,12 @@ struct PublicDeckEntry: Codable, Hashable, Sendable, Identifiable {
case owner
}
var isPaid: Bool { priceCredits > 0 }
var isPaid: Bool {
priceCredits > 0
}
}
struct PublicDeckOwner: Codable, Hashable, Sendable {
struct PublicDeckOwner: Codable, Hashable {
let slug: String
let displayName: String
let verifiedMana: Bool
@ -62,19 +66,19 @@ struct PublicDeckOwner: Codable, Hashable, Sendable {
}
/// Response von `GET /api/v1/marketplace/explore`.
struct ExploreResponse: Decodable, Sendable {
struct ExploreResponse: Decodable {
let featured: [PublicDeckEntry]
let trending: [PublicDeckEntry]
}
/// Response von `GET /api/v1/marketplace/decks`.
struct BrowseResponse: Decodable, Sendable {
struct BrowseResponse: Decodable {
let items: [PublicDeckEntry]
let total: Int
}
/// Vollständiges Public-Deck aus `GET /api/v1/marketplace/decks/:slug`.
struct PublicDeck: Codable, Hashable, Sendable, Identifiable {
struct PublicDeck: Codable, Hashable, Identifiable {
let id: String
let slug: String
let title: String
@ -100,7 +104,7 @@ struct PublicDeck: Codable, Hashable, Sendable, Identifiable {
}
}
struct PublicDeckVersion: Codable, Hashable, Sendable, Identifiable {
struct PublicDeckVersion: Codable, Hashable, Identifiable {
let id: String
let deckId: String
let semver: String
@ -123,7 +127,7 @@ struct PublicDeckVersion: Codable, Hashable, Sendable, Identifiable {
}
/// Response von `GET /api/v1/marketplace/decks/:slug`.
struct PublicDeckDetail: Decodable, Sendable {
struct PublicDeckDetail: Decodable {
let deck: PublicDeck
let latestVersion: PublicDeckVersion?
let owner: PublicDeckOwner?
@ -136,7 +140,7 @@ struct PublicDeckDetail: Decodable, Sendable {
}
/// Response von `POST /api/v1/marketplace/decks/:slug/subscribe`.
struct SubscribeResponse: Decodable, Sendable {
struct SubscribeResponse: Decodable {
let subscribed: Bool
let deckSlug: String
let currentVersionId: String?
@ -151,7 +155,7 @@ struct SubscribeResponse: Decodable, Sendable {
}
/// Browse-Sort-Optionen aus `BrowseQuerySchema`.
enum MarketplaceSort: String, Sendable, CaseIterable {
enum MarketplaceSort: String, CaseIterable {
case recent
case popular
case trending

View file

@ -1,7 +1,7 @@
import Foundation
/// Response von `POST /api/v1/media/upload`.
struct MediaUploadResponse: Decodable, Sendable {
struct MediaUploadResponse: Decodable {
let id: String
let url: String
let mimeType: String
@ -19,7 +19,7 @@ struct MediaUploadResponse: Decodable, Sendable {
}
}
enum MediaKind: String, Codable, Sendable {
enum MediaKind: String, Codable {
case image
case audio
case video
@ -29,7 +29,7 @@ enum MediaKind: String, Codable, Sendable {
/// Image-Occlusion-Mask-Region.
/// `mask_regions`-Feld ist ein JSON-Array-**String** in `fields`,
/// nicht ein Object Server-Schema-Constraint (`fields: Record<string,string>`).
struct MaskRegion: Codable, Hashable, Sendable, Identifiable {
struct MaskRegion: Codable, Hashable, Identifiable {
let id: String
let x: Double // 0..1 relativ
let y: Double
@ -53,7 +53,7 @@ enum MaskRegions {
/// Bei Parse- oder Schema-Fehler: leere Liste. Sortiert nach ID
/// (lexikographisch, gleich wie Server-Sortierung).
static func parse(_ json: String) -> [MaskRegion] {
guard let data = json.data(using: .utf8) else { return [] }
let data = Data(json.utf8)
guard let regions = try? JSONDecoder().decode([MaskRegion].self, from: data) else { return [] }
return regions.sorted { $0.id < $1.id }
}
@ -73,8 +73,10 @@ enum MaskRegions {
static func encode(_ regions: [MaskRegion]) -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
guard let data = try? encoder.encode(regions) else { return "[]" }
return String(decoding: data, as: UTF8.self)
guard let data = try? encoder.encode(regions),
let json = String(bytes: data, encoding: .utf8)
else { return "[]" }
return json
}
}
@ -88,7 +90,7 @@ extension CardFieldsBuilder {
) -> [String: String] {
var fields: [String: String] = [
"image_ref": imageRef,
"mask_regions": MaskRegions.encode(regions),
"mask_regions": MaskRegions.encode(regions)
]
if let note, !note.isEmpty {
fields["note"] = note

View file

@ -2,7 +2,7 @@ import Foundation
/// Rating-Werte für `POST /reviews/:cardId/:subIndex/grade`.
/// Aus `cards/packages/cards-domain/src/schemas/review.ts:RatingSchema`.
enum Rating: String, Codable, Sendable, CaseIterable {
enum Rating: String, Codable, CaseIterable {
case again
case hard
case good
@ -30,7 +30,7 @@ enum Rating: String, Codable, Sendable, CaseIterable {
}
/// FSRS-Review-State. Aus `ReviewStateSchema`.
enum ReviewState: String, Codable, Sendable {
enum ReviewState: String, Codable {
case new
case learning
case review
@ -38,7 +38,7 @@ enum ReviewState: String, Codable, Sendable {
}
/// Review-DTO. Wire-Format aus `cards/apps/api/src/routes/reviews.ts:toReviewDto`.
struct Review: Codable, Hashable, Sendable {
struct Review: Codable, Hashable {
let cardId: String
let subIndex: Int
let userId: String
@ -71,11 +71,13 @@ struct Review: Codable, Hashable, Sendable {
}
/// Eintrag aus `/reviews/due?deck_id=X` Review + zugehörige Card.
struct DueReview: Codable, Hashable, Sendable, Identifiable {
struct DueReview: Codable, Hashable, Identifiable {
let review: Review
let card: ReviewCard
var id: String { "\(review.cardId)-\(review.subIndex)" }
var id: String {
"\(review.cardId)-\(review.subIndex)"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
@ -96,13 +98,13 @@ struct DueReview: Codable, Hashable, Sendable, Identifiable {
}
/// Wrapper-Response von `GET /api/v1/reviews/due?deck_id=X`.
struct DueReviewsListResponse: Decodable, Sendable {
struct DueReviewsListResponse: Decodable {
let reviews: [DueReview]
let total: Int
}
/// Body für `POST /reviews/:cardId/:subIndex/grade`.
struct GradeReviewBody: Encodable, Sendable {
struct GradeReviewBody: Encodable {
let rating: Rating
let reviewedAt: Date

View file

@ -5,7 +5,7 @@ import Foundation
/// Normalisierung (lowercase, trim, NFD-Diakritika-Stripping),
/// dann exact-match `correct`. Sonst Levenshtein-Distanz mit
/// Threshold `max(1, floor(answer.length * 0.2))` `close`.
enum TypingMatch: Sendable, Equatable {
enum TypingMatch: Equatable {
case correct
case close
case wrong

View file

@ -29,7 +29,7 @@ struct CardsAppShortcuts: AppShortcutsProvider {
phrases: [
"Karten lernen mit \(.applicationName)",
"Mit \(.applicationName) lernen",
"\(.applicationName) öffnen",
"\(.applicationName) öffnen"
],
shortTitle: "Karten lernen",
systemImageName: "rectangle.stack"

View file

@ -8,7 +8,7 @@ import UserNotifications
@MainActor
@Observable
final class NotificationManager {
enum AuthorizationStatus: Sendable {
enum AuthorizationStatus {
case unknown
case authorized
case denied

View file

@ -30,8 +30,9 @@ final class GradeQueue {
)
context.insert(grade)
try? context.save()
let rawRating = rating.rawValue
Log.study.info(
"Queued grade for \(cardId, privacy: .public)/\(subIndex, privacy: .public): \(rating.rawValue, privacy: .public)"
"Queued grade \(cardId, privacy: .public)/\(subIndex, privacy: .public): \(rawRating, privacy: .public)"
)
await drain()
}
@ -73,8 +74,10 @@ final class GradeQueue {
grade.lastError = msg
try? context.save()
lastDrainError = msg
let cid = grade.cardId
let sub = grade.subIndex
Log.study.notice(
"Drain stopped for \(grade.cardId, privacy: .public)/\(grade.subIndex, privacy: .public): \(msg, privacy: .public)"
"Drain stopped \(cid, privacy: .public)/\(sub, privacy: .public): \(msg, privacy: .public)"
)
return
}

View file

@ -35,10 +35,16 @@ actor MediaCache {
/// Direktes Lesen für UI-Komponenten, die `Data` brauchen (z.B. AVAudioPlayer).
func data(for mediaId: String) async throws -> Data {
try Data(contentsOf: try await localURL(for: mediaId))
try await Data(contentsOf: localURL(for: mediaId))
}
/// LRU-Eviction: bei Überschreitung des Limits ältesten zuerst löschen.
private struct CacheEntry {
let url: URL
let size: Int
let date: Date
}
private func pruneIfNeeded() async throws {
let resourceKeys: Set<URLResourceKey> = [.fileSizeKey, .contentModificationDateKey]
guard let items = try? FileManager.default.contentsOfDirectory(
@ -46,10 +52,10 @@ actor MediaCache {
includingPropertiesForKeys: Array(resourceKeys)
) else { return }
let withMeta = items.compactMap { url -> (url: URL, size: Int, date: Date)? in
let withMeta = items.compactMap { url -> CacheEntry? in
let values = try? url.resourceValues(forKeys: resourceKeys)
guard let size = values?.fileSize, let date = values?.contentModificationDate else { return nil }
return (url, size, date)
return CacheEntry(url: url, size: size, date: date)
}
let totalBytes = withMeta.reduce(0) { $0 + $1.size }
@ -61,7 +67,9 @@ actor MediaCache {
if remaining <= maxBytes { break }
try? FileManager.default.removeItem(at: item.url)
remaining -= item.size
Log.sync.info("MediaCache evicted \(item.url.lastPathComponent, privacy: .public) (\(item.size, privacy: .public)B)")
let name = item.url.lastPathComponent
let size = item.size
Log.sync.info("MediaCache evicted \(name, privacy: .public) (\(size, privacy: .public)B)")
}
}

View file

@ -1,15 +1,5 @@
import SwiftUI
/// Environment-Key, der den shared `MediaCache` durch die View-Hierarchie
/// reicht. App-Entrypoint setzt den Wert; Views lesen via
/// `@Environment(\.mediaCache)`.
private struct MediaCacheKey: EnvironmentKey {
static let defaultValue: MediaCache? = nil
}
extension EnvironmentValues {
var mediaCache: MediaCache? {
get { self[MediaCacheKey.self] }
set { self[MediaCacheKey.self] = newValue }
}
@Entry var mediaCache: MediaCache?
}

View file

@ -3,7 +3,7 @@ import Foundation
/// Inbox für Share-Extension. Die Extension persistiert hier, die
/// Haupt-App liest beim Start und zeigt einen Banner mit
/// " Als Karte speichern". Shared App-Group-Container.
struct PendingShare: Codable, Identifiable, Hashable, Sendable {
struct PendingShare: Codable, Identifiable, Hashable {
let id: String
let text: String
let sourceURL: String?

View file

@ -6,13 +6,13 @@ import Foundation
///
/// Wire ist bewusst stabil + schmal nur was das Widget rendert.
/// Neue Felder dürfen additiv dazukommen, alte Felder bleiben.
struct WidgetSnapshot: Codable, Sendable {
struct WidgetSnapshot: Codable {
let updatedAt: Date
let totalDueCount: Int
let topDecks: [Entry]
struct Entry: Codable, Sendable, Identifiable {
let id: String // deck-id
struct Entry: Codable, Identifiable {
let id: String // deck-id
let name: String
let dueCount: Int
let colorHex: String?

View file

@ -11,16 +11,16 @@ import SwiftUI
/// - Background hsl(--color-surface)
/// - Aspect-Ratio 5/7 für `.md` und `.hero`, fix für `.lg`
struct CardSurface<Content: View>: View {
enum Size: Sendable {
case md // Deck-Tile in der Liste (max-width 18rem)
case lg // Fan-Detail (12rem x 16.8rem)
case hero // Study-Lernkarte (max-width 24rem)
enum Size {
case md // Deck-Tile in der Liste (max-width 18rem)
case lg // Fan-Detail (12rem x 16.8rem)
case hero // Study-Lernkarte (max-width 24rem)
}
enum Elevation: Sendable {
case flat // Subtle shadow
enum Elevation {
case flat // Subtle shadow
case standard // Default Karten-Shadow
case raised // Study-Hero
case raised // Study-Hero
}
let size: Size
@ -73,9 +73,9 @@ struct CardSurface<Content: View>: View {
private var maxWidth: CGFloat? {
switch size {
case .md: 288 // 18rem
case .lg: 192 // 12rem
case .hero: 384 // 24rem
case .md: 288 // 18rem
case .lg: 192 // 12rem
case .hero: 384 // 24rem
}
}

View file

@ -1,11 +1,13 @@
import SwiftUI
#if canImport(UIKit)
import UIKit
private typealias PlatformColorType = UIColor
import UIKit
private typealias PlatformColorType = UIColor
#elseif canImport(AppKit)
import AppKit
private typealias PlatformColorType = NSColor
import AppKit
private typealias PlatformColorType = NSColor
#endif
/// Forest-Theme aus `mana/packages/themes/src/variants/forest.css`.
@ -16,56 +18,67 @@ private typealias PlatformColorType = NSColor
/// `mana/docs/MANA_SWIFT.md` bis dahin lebt forest hier.
enum CardsTheme {
/// Page-Hintergrund
static let background = dynamic(light: (0, 0, 100), dark: (142, 30, 8))
static let background = dynamic(light: HSL(0, 0, 100), dark: HSL(142, 30, 8))
/// Standard-Text
static let foreground = dynamic(light: (142, 30, 12), dark: (142, 15, 95))
static let foreground = dynamic(light: HSL(142, 30, 12), dark: HSL(142, 15, 95))
/// Card, Panel, Modal
static let surface = dynamic(light: (142, 25, 98), dark: (142, 25, 12))
static let surface = dynamic(light: HSL(142, 25, 98), dark: HSL(142, 25, 12))
/// Hover-State auf Surface
static let surfaceHover = dynamic(light: (142, 20, 95), dark: (142, 20, 16))
static let surfaceHover = dynamic(light: HSL(142, 20, 95), dark: HSL(142, 20, 16))
/// Disabled-Felder, Skeleton
static let muted = dynamic(light: (142, 15, 93), dark: (142, 18, 18))
static let muted = dynamic(light: HSL(142, 15, 93), dark: HSL(142, 18, 18))
/// Sekundär-Text, Placeholder
static let mutedForeground = dynamic(light: (142, 10, 42), dark: (142, 12, 65))
static let mutedForeground = dynamic(light: HSL(142, 10, 42), dark: HSL(142, 12, 65))
/// Rahmen, Trennlinien
static let border = dynamic(light: (142, 15, 88), dark: (142, 18, 22))
static let border = dynamic(light: HSL(142, 15, 88), dark: HSL(142, 18, 22))
/// Cards-Brand-Grün Tiefgrün im Light, leuchtender im Dark
static let primary = dynamic(light: (142, 76, 28), dark: (142, 71, 45))
static let primary = dynamic(light: HSL(142, 76, 28), dark: HSL(142, 71, 45))
/// Text auf Primary
static let primaryForeground = dynamic(light: (0, 0, 100), dark: (142, 30, 8))
static let primaryForeground = dynamic(light: HSL(0, 0, 100), dark: HSL(142, 30, 8))
static let error = dynamic(light: (0, 84, 60), dark: (0, 63, 55))
static let success = dynamic(light: (142, 71, 45), dark: (142, 71, 45))
static let warning = dynamic(light: (38, 92, 50), dark: (48, 96, 53))
static let error = dynamic(light: HSL(0, 84, 60), dark: HSL(0, 63, 55))
static let success = dynamic(light: HSL(142, 71, 45), dark: HSL(142, 71, 45))
static let warning = dynamic(light: HSL(38, 92, 50), dark: HSL(48, 96, 53))
// MARK: - HSL Helper
private static func dynamic(
light: (Double, Double, Double),
dark: (Double, Double, Double)
) -> Color {
let lightColor = fromHSL(light.0, light.1, light.2)
let darkColor = fromHSL(dark.0, dark.1, dark.2)
/// Hue/Saturation/Lightness als Wert-Typ. HSL ist konkreter als ein
/// 3-Tupel und macht die Call-Sites lesbar.
struct HSL {
let hue: Double
let saturation: Double
let lightness: Double
init(_ hue: Double, _ saturation: Double, _ lightness: Double) {
self.hue = hue
self.saturation = saturation
self.lightness = lightness
}
}
private static func dynamic(light: HSL, dark: HSL) -> Color {
let lightColor = fromHSL(light.hue, light.saturation, light.lightness)
let darkColor = fromHSL(dark.hue, dark.saturation, dark.lightness)
#if canImport(UIKit)
return Color(uiColor: UIColor { trait in
trait.userInterfaceStyle == .dark ? darkColor : lightColor
})
return Color(uiColor: UIColor { trait in
trait.userInterfaceStyle == .dark ? darkColor : lightColor
})
#elseif canImport(AppKit)
return Color(nsColor: NSColor(name: nil) { appearance in
let isDark = appearance.bestMatch(from: [.darkAqua, .vibrantDark]) != nil
return isDark ? darkColor : lightColor
})
return Color(nsColor: NSColor(name: nil) { appearance in
let isDark = appearance.bestMatch(from: [.darkAqua, .vibrantDark]) != nil
return isDark ? darkColor : lightColor
})
#else
return Color(red: 0, green: 0, blue: 0)
return Color(red: 0, green: 0, blue: 0)
#endif
}