Sources/Orgstar/ThemeColors.swift
68 lines · 3050 bytes
1import AppKit
2import OrgPresentation
3import SwiftUI
4
5extension EnvironmentValues {
6 /// The theme's colors, for the views around the editor.
7 @Entry var orgTheme: ThemeSpec = .default
8}
9
10extension ThemeSpec {
11 /// A color that follows the appearance, or nil when the theme leaves `key` to the system.
12 /// A key set for one appearance only leaves the other to the system.
13 func color(_ key: String) -> Color? {
14 guard light[key] != nil || dark[key] != nil else { return nil }
15 let (light, dark) = (light[key], dark[key])
16 let fallback = Self.systemColor(key)
17 return Color(nsColor: NSColor(name: nil) { appearance in
18 let isDark = appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
19 guard let c = isDark ? dark : light else { return fallback }
20 return NSColor(srgbRed: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
21 })
22 }
23
24 /// `key` in `scheme` only, nil where the theme leaves it to the system there, for
25 /// backgrounds that fall back to a material rather than a color.
26 func color(_ key: String, in scheme: ColorScheme) -> Color? {
27 color(key, dark: scheme == .dark).map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) }
28 }
29
30 /// A color that follows the appearance from a helper taking `dark:` (`todoColor`,
31 /// `statusColor`, …), or `fallback` where it gives none.
32 func dynamic(_ fallback: NSColor = .labelColor, _ pick: @escaping @Sendable (_ dark: Bool) -> RGBA?) -> Color {
33 Color(nsColor: NSColor(name: nil) { appearance in
34 let isDark = appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
35 guard let c = pick(isDark) else { return fallback }
36 return NSColor(srgbRed: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
37 })
38 }
39
40 /// What the system shows for a key the theme leaves unset in one appearance.
41 static func systemColor(_ key: String) -> NSColor {
42 switch key {
43 case "sidebar-background", "modeline-background": .windowBackgroundColor
44 case "agenda-background", "background": .textBackgroundColor
45 case "sidebar-header", "modeline-foreground", "agenda-time", "agenda-category", "tags": .secondaryLabelColor
46 case "accent": .controlAccentColor
47 default: .labelColor
48 }
49 }
50
51 /// A TODO keyword's color: its own from `[theme.todo]`, else the theme's TODO or DONE.
52 func keywordColor(_ keyword: String, done: Bool) -> Color {
53 if let c = todo[keyword] { return Color(.sRGB, red: c.red, green: c.green, blue: c.blue, opacity: c.alpha) }
54 return color(done ? "done" : "todo") ?? (done ? .green : .red)
55 }
56}
57
58extension View {
59 /// A list's background from the theme, or the system's when the theme has none.
60 @ViewBuilder
61 func themedListBackground(_ color: Color?) -> some View {
62 if let color {
63 scrollContentBackground(.hidden).background(color)
64 } else {
65 self
66 }
67 }
68}