Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Space themes with a light and a dark half that follow macOS, as Arc's appearanceBased themes (#155) (#163)

Victor Kildahl425d7b39705a
diff --git a/Packages/CraCore/Sources/CraCore/ArcThemeImport.swift b/Packages/CraCore/Sources/CraCore/ArcThemeImport.swift
index bbda8a1..c95f774 100644
--- a/Packages/CraCore/Sources/CraCore/ArcThemeImport.swift
+++ b/Packages/CraCore/Sources/CraCore/ArcThemeImport.swift
@@ -2,19 +2,24 @@ import Foundation
/// An Arc space's `customInfo.windowTheme` (StorableSidebar.json) as a Cra theme.
public enum ArcThemeImport {
- /// Arc's blendedGradient → SpaceTheme. Prefers the dark variant when one exists.
+ /// Arc's blendedGradient → SpaceTheme. An Auto theme (appearanceBased) keeps both halves and
+ /// follows macOS; Light and Dark ones (single) keep their one look.
public static func theme(from space: [String: Any]) -> SpaceTheme? {
guard let info = space["customInfo"] as? [String: Any], let wt = info["windowTheme"] as? [String: Any],
let bg = wt["background"] as? [String: Any] else { return nil }
- var variant: [String: Any]?
- var appearance = "auto"
if let ab = bg["appearanceBased"] as? [String: Any] {
- variant = (ab["dark"] as? [String: Any]) ?? (ab["light"] as? [String: Any])
- appearance = ab["dark"] != nil ? "dark" : "light"
- } else if let single = bg["single"] as? [String: Any] {
- variant = single["_0"] as? [String: Any]
+ let light = (ab["light"] as? [String: Any]).flatMap { theme(variant: $0, appearance: "light", windowTheme: wt) }
+ let dark = (ab["dark"] as? [String: Any]).flatMap { theme(variant: $0, appearance: "dark", windowTheme: wt) }
+ if let light, let dark { return SpaceTheme(light: light, dark: dark) }
+ return dark ?? light
}
- guard let v = variant else { return nil }
+ guard let single = (bg["single"] as? [String: Any])?["_0"] as? [String: Any] else { return nil }
+ return theme(variant: single, appearance: "auto", windowTheme: wt)
+ }
+
+ /// One half of `background`: its own `contentOverBackgroundAppearance` wins over `appearance`.
+ private static func theme(variant v: [String: Any], appearance: String, windowTheme wt: [String: Any]) -> SpaceTheme? {
+ var appearance = appearance
if let a = v["contentOverBackgroundAppearance"] as? String { appearance = a }
let vibrant = v["isVibrant"] as? Bool ?? false
func comp(_ c: [String: Any], _ k: String) -> Double { max(0, min(1, c[k] as? Double ?? 0)) }
diff --git a/Packages/CraCore/Sources/CraCore/SpaceTheme.swift b/Packages/CraCore/Sources/CraCore/SpaceTheme.swift
index db4f5a4..3611902 100644
--- a/Packages/CraCore/Sources/CraCore/SpaceTheme.swift
+++ b/Packages/CraCore/Sources/CraCore/SpaceTheme.swift
@@ -17,9 +17,36 @@ public struct SpaceTheme: Codable, Equatable {
/// Arc's one-colour theme (blendedSingleColor): a flat fill laid over a dark, slightly
/// see-through material, at `intensity` (SpacePalette.solidAlpha), not a gradient.
public var solid: Bool = false
+ /// Arc's Auto theme (background.appearanceBased): with `appearance` "auto" the space follows
+ /// macOS, the fields above are its light half and this is the half shown while macOS is dark.
+ /// nil on an "auto" theme from before 0.1.29: its colours are the half their brightness
+ /// suits, and the other half is derived (`resolved(systemDark:)`).
+ public var dark: Variant? = nil
+ /// The theme editor's pad colours the theme was built from (Arc: the editor's key colour and
+ /// the ones its wheel adds); nil for a preset or an import, whose own colours go on the pad.
+ public var key: [String]? = nil
+
+ /// One half of an Auto theme: everything but the appearance, which is the half's own.
+ public struct Variant: Codable, Equatable {
+ public var colors: [String]
+ public var intensity: Double
+ public var noise: Double
+ public var vibrant: Bool = false
+ public var accent: String? = nil
+ public var solid: Bool = false
+
+ public init(colors: [String], intensity: Double, noise: Double, vibrant: Bool = false, accent: String? = nil, solid: Bool = false) {
+ self.colors = colors
+ self.intensity = intensity
+ self.noise = noise
+ self.vibrant = vibrant
+ self.accent = accent
+ self.solid = solid
+ }
+ }
public init(colors: [String], intensity: Double, noise: Double, appearance: String, vibrant: Bool = false, accent: String? = nil,
- solid: Bool = false) {
+ solid: Bool = false, dark: Variant? = nil, key: [String]? = nil) {
self.colors = colors
self.intensity = intensity
self.noise = noise
@@ -27,6 +54,15 @@ public struct SpaceTheme: Codable, Equatable {
self.vibrant = vibrant
self.accent = accent
self.solid = solid
+ self.dark = dark
+ self.key = key
+ }
+
+ /// Arc's Auto: a light and a dark half, shown as macOS' appearance says.
+ public init(light: SpaceTheme, dark: SpaceTheme) {
+ self = light
+ appearance = "auto"
+ self.dark = dark.variant
}
public init(from decoder: Decoder) throws {
@@ -38,6 +74,31 @@ public struct SpaceTheme: Codable, Equatable {
vibrant = try c.decodeIfPresent(Bool.self, forKey: .vibrant) ?? false
accent = try c.decodeIfPresent(String.self, forKey: .accent)
solid = try c.decodeIfPresent(Bool.self, forKey: .solid) ?? false
+ dark = try c.decodeIfPresent(Variant.self, forKey: .dark)
+ key = try c.decodeIfPresent([String].self, forKey: .key)
+ }
+
+ var variant: Variant {
+ Variant(colors: colors, intensity: intensity, noise: noise, vibrant: vibrant, accent: accent, solid: solid)
+ }
+
+ /// Auto follows macOS; Light and Dark keep their look whatever macOS shows.
+ public var followsSystem: Bool { appearance == "auto" }
+
+ /// The theme as shown while macOS is dark or light: a Light or Dark theme as it is, an
+ /// Auto one as the matching half with that half's appearance.
+ public func resolved(systemDark: Bool) -> SpaceTheme {
+ guard followsSystem else { return self }
+ if let d = dark {
+ if !systemDark { var t = self; t.appearance = "light"; t.dark = nil; return t }
+ return SpaceTheme(colors: d.colors, intensity: d.intensity, noise: d.noise, appearance: "dark", vibrant: d.vibrant,
+ accent: d.accent, solid: d.solid)
+ }
+ // An Auto theme saved before both halves were kept shows as it always did on the side its
+ // colours suit, and as the derived other half on the other.
+ var t = self
+ t.appearance = isDark ? "dark" : "light"
+ return t.isDark == systemDark ? t : SpaceThemeVariants.flipped(t)
}
/// Dark first: colors borrowed from Victor's other projects (GhostWriter
diff --git a/Packages/CraCore/Sources/CraCore/SpaceThemeVariants.swift b/Packages/CraCore/Sources/CraCore/SpaceThemeVariants.swift
new file mode 100644
index 0000000..69fdb22
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/SpaceThemeVariants.swift
@@ -0,0 +1,74 @@
+import Foundation
+
+/// The light and dark halves of an Auto theme (Arc: SpaceStyleEditorState+WindowTheme, which builds
+/// `background.appearanceBased` from the editor's key colour).
+public enum SpaceThemeVariants {
+ /// What the theme editor makes of its pad: both halves for Auto, one for Light or Dark.
+ public static func theme(key: [String], intensity: Double, noise: Double, appearance: String) -> SpaceTheme {
+ var t: SpaceTheme
+ switch appearance {
+ case "light": t = light(key: key, intensity: intensity, noise: noise)
+ case "dark": t = dark(key: key, intensity: intensity, noise: noise)
+ default: t = SpaceTheme(light: light(key: key, intensity: intensity, noise: noise), dark: dark(key: key, intensity: intensity, noise: noise))
+ }
+ t.key = key
+ return t
+ }
+
+ /// The other half of a theme that has one: a dark theme's light half or a light theme's dark half.
+ public static func flipped(_ t: SpaceTheme) -> SpaceTheme {
+ t.isDark ? light(key: t.colors, intensity: t.intensity, noise: t.noise)
+ : dark(key: t.colors, intensity: t.intensity, noise: t.noise)
+ }
+
+ /// The half shown while macOS is light, from the pad's colours: the colours themselves (Arc
+ /// saves a colour picked in Light as that colour), lifted to Arc's default light half (HSL
+ /// lightness 0.9, #8389FF → #C8CAFF) when they would read as a dark theme.
+ public static func light(key: [String], intensity: Double, noise: Double) -> SpaceTheme {
+ var t = SpaceTheme(colors: key, intensity: intensity, noise: noise, appearance: "auto", accent: key.first)
+ if t.isDark { t.colors = key.map { shade($0, lightness: 0.9) }; t.accent = t.colors.first }
+ t.appearance = "light"
+ return t
+ }
+
+ /// The half shown while macOS is dark, from the pad's colours: Arc's default dark half keeps the
+ /// key's hue at HSL lightness ≈ 0.064 (#8389FF → #01021F).
+ public static func dark(key: [String], intensity: Double, noise: Double) -> SpaceTheme {
+ let base = key.map { shade($0, lightness: 0.064) }
+ // Drawn the way ArcThemeImport draws Arc's opaque dark halves: ~27% of the colour over #2B2632.
+ let colors = base.map { hex in
+ let k = HexColor.components(hex) ?? (0, 0, 0)
+ func ch(_ v: Double, _ b: Double) -> Int { Int((v * 255 * 0.27 + b).rounded()) }
+ return String(format: "#%02X%02X%02X", ch(k.r, 43), ch(k.g, 38), ch(k.b, 50))
+ }
+ return SpaceTheme(colors: colors, intensity: 1, noise: noise, appearance: "dark", accent: base.first)
+ }
+
+ /// The colour's HSL hue and saturation at another lightness.
+ static func shade(_ hex: String, lightness l: Double) -> String {
+ let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)
+ let mx = max(c.r, c.g, c.b), mn = min(c.r, c.g, c.b), d = mx - mn
+ let l0 = (mx + mn) / 2
+ let s = d == 0 ? 0 : d / (1 - abs(2 * l0 - 1))
+ var h = 0.0
+ if d > 0 {
+ if mx == c.r { h = ((c.g - c.b) / d).truncatingRemainder(dividingBy: 6) }
+ else if mx == c.g { h = (c.b - c.r) / d + 2 }
+ else { h = (c.r - c.g) / d + 4 }
+ h = (h / 6 + 1).truncatingRemainder(dividingBy: 1)
+ }
+ let q = (1 - abs(2 * l - 1)) * min(1, s)
+ let x = q * (1 - abs((h * 6).truncatingRemainder(dividingBy: 2) - 1)), m = l - q / 2
+ let (r, g, b): (Double, Double, Double)
+ switch Int(h * 6) % 6 {
+ case 0: (r, g, b) = (q, x, 0)
+ case 1: (r, g, b) = (x, q, 0)
+ case 2: (r, g, b) = (0, q, x)
+ case 3: (r, g, b) = (0, x, q)
+ case 4: (r, g, b) = (x, 0, q)
+ default: (r, g, b) = (q, 0, x)
+ }
+ func byte(_ v: Double) -> Int { Int((max(0, min(1, v + m)) * 255).rounded()) }
+ return String(format: "#%02X%02X%02X", byte(r), byte(g), byte(b))
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/ArcThemeImportTests.swift b/Packages/CraCore/Tests/CraCoreTests/ArcThemeImportTests.swift
index 250d520..3aa5b7f 100644
--- a/Packages/CraCore/Tests/CraCoreTests/ArcThemeImportTests.swift
+++ b/Packages/CraCore/Tests/CraCoreTests/ArcThemeImportTests.swift
@@ -44,10 +44,25 @@ struct ArcThemeImportTests {
appearance: "light", vibrant: true, accent: "#F8D558"))
}
- @Test func darkVariantOfAnAppearanceBasedGradient() throws {
+ /// Arc's Auto theme keeps both halves and follows macOS (#155; until 0.1.28 only the dark half came over).
+ @Test func appearanceBasedGradientKeepsBothHalves() throws {
let theme = try #require(Self.theme("gradientAppearanceBasedDark"))
- #expect(theme == SpaceTheme(colors: ["#2C273B", "#32263A"], intensity: 1, noise: 0,
- appearance: "dark", accent: "#010220"))
+ #expect(theme.appearance == "auto" && theme.followsSystem)
+ #expect(theme.resolved(systemDark: true) == SpaceTheme(colors: ["#2C273B", "#32263A"], intensity: 1, noise: 0,
+ appearance: "dark", accent: "#010220"))
+ #expect(theme.resolved(systemDark: false) == SpaceTheme(colors: ["#CDCDFC", "#FFE5E5"], intensity: 0.5, noise: 0,
+ appearance: "light", accent: "#C8CAFF"))
+ }
+
+ /// An appearance-based theme with one half shows that half whatever macOS shows.
+ @Test func appearanceBasedWithOneHalfKeepsIt() throws {
+ var space = Self.spaces["gradientAppearanceBasedDark"]!
+ var info = space["customInfo"] as! [String: Any], wt = info["windowTheme"] as! [String: Any]
+ var bg = wt["background"] as! [String: Any], ab = bg["appearanceBased"] as! [String: Any]
+ ab["light"] = nil
+ bg["appearanceBased"] = ab; wt["background"] = bg; info["windowTheme"] = wt; space["customInfo"] = info
+ let theme = try #require(ArcThemeImport.theme(from: space))
+ #expect(theme == SpaceTheme(colors: ["#2C273B", "#32263A"], intensity: 1, noise: 0, appearance: "dark", accent: "#010220"))
}
/// A style Cra can't read falls back to the mid tone of Arc's derived palette, which keeps the hue.
@@ -60,10 +75,11 @@ struct ArcThemeImportTests {
#expect(Self.theme("noWindowTheme") == nil)
}
- /// A fixture space with its background variant (single, or the appearance-based one read)
- /// changed: the same file, one field different.
+ /// A fixture space with its background variant (single, or an appearance-based theme's dark
+ /// half) changed: the same file, one field different. Returns the half that changed.
static func theme(_ name: String, changing change: (inout [String: Any]) -> Void) -> SpaceTheme? {
var space = spaces[name]!
+ var systemDark = false
var info = space["customInfo"] as! [String: Any]
var wt = info["windowTheme"] as! [String: Any]
var bg = wt["background"] as! [String: Any]
@@ -75,6 +91,7 @@ struct ArcThemeImportTests {
} else {
var ab = bg["appearanceBased"] as! [String: Any]
let key = ab["dark"] != nil ? "dark" : "light"
+ systemDark = key == "dark"
var v = ab[key] as! [String: Any]
change(&v)
ab[key] = v
@@ -83,7 +100,7 @@ struct ArcThemeImportTests {
wt["background"] = bg
info["windowTheme"] = wt
space["customInfo"] = info
- return ArcThemeImport.theme(from: space)
+ return ArcThemeImport.theme(from: space)?.resolved(systemDark: systemDark)
}
static func gradient(_ v: inout [String: Any], _ change: (inout [String: Any]) -> Void) {
@@ -96,7 +113,7 @@ struct ArcThemeImportTests {
/// Arc lets a gradient have one base colour; both stops then come from it.
@Test(arguments: ["gradientVibrantLight", "gradientAppearanceBasedDark"])
func oneBaseColourGradient(name: String) throws {
- let full = try #require(Self.theme(name))
+ let full = try #require(Self.theme(name) { _ in })
let theme = try #require(Self.theme(name) { v in
Self.gradient(&v) { g in g["baseColors"] = [(g["baseColors"] as! [[String: Any]])[0]] }
})
@@ -112,7 +129,7 @@ struct ArcThemeImportTests {
/// Only an opaque dark theme is darkened over Arc's #2B2632; a vibrant dark one keeps its stops.
@Test func vibrantDarkGradientIsNotDarkened() throws {
- let opaque = try #require(Self.theme("gradientAppearanceBasedDark"))
+ let opaque = try #require(Self.theme("gradientAppearanceBasedDark") { _ in })
let vibrant = try #require(Self.theme("gradientAppearanceBasedDark") { $0["isVibrant"] = true })
#expect(vibrant.vibrant && vibrant.colors != opaque.colors && vibrant.intensity != 1)
}
@@ -142,3 +159,61 @@ struct SpaceThemeTests {
#expect(SpaceTheme(colors: [hex, hex], intensity: 1, noise: 0, appearance: "auto").isDark == dark)
}
}
+
+/// An Auto theme follows macOS (Arc: background.appearanceBased), issue #155.
+struct SpaceThemeAppearanceTests {
+ static let light = SpaceTheme(colors: ["#CDCDFC", "#FFE5E5"], intensity: 0.5, noise: 0, appearance: "light", accent: "#C8CAFF")
+ static let dark = SpaceTheme(colors: ["#2C273B", "#32263A"], intensity: 1, noise: 0, appearance: "dark", accent: "#010220")
+
+ @Test func autoShowsTheHalfMacOSAsksFor() {
+ let theme = SpaceTheme(light: Self.light, dark: Self.dark)
+ #expect(theme.followsSystem)
+ #expect(theme.resolved(systemDark: false) == Self.light)
+ #expect(theme.resolved(systemDark: true) == Self.dark)
+ }
+
+ @Test(arguments: [false, true])
+ func lightAndDarkKeepTheirLook(systemDark: Bool) {
+ #expect(Self.light.resolved(systemDark: systemDark) == Self.light)
+ #expect(Self.dark.resolved(systemDark: systemDark) == Self.dark)
+ }
+
+ /// An Auto theme saved before 0.1.29 (one set of colours) looks as it did on the side its colours
+ /// suit and gets a derived half on the other.
+ @Test(arguments: ["#F8D558", "#2861B3"])
+ func olderAutoThemeKeepsItsSideAndDerivesTheOther(hex: String) {
+ let theme = SpaceTheme(colors: [hex, hex], intensity: 0.8, noise: 0.1, appearance: "auto")
+ let own = theme.resolved(systemDark: theme.isDark)
+ #expect(own.colors == theme.colors && own.isDark == theme.isDark)
+ let other = theme.resolved(systemDark: !theme.isDark)
+ #expect(other.isDark != theme.isDark && other.colors != theme.colors)
+ }
+
+ /// Both halves and the editor's colours are saved; a theme without them saves as before.
+ @Test func roundTripsBothHalves() throws {
+ var theme = SpaceTheme(light: Self.light, dark: Self.dark)
+ theme.key = ["#8389FF"]
+ #expect(try JSONDecoder().decode(SpaceTheme.self, from: JSONEncoder().encode(theme)) == theme)
+ let plain = String(decoding: try JSONEncoder().encode(Self.light), as: UTF8.self)
+ #expect(!plain.contains("\"dark\"") && !plain.contains("\"key\""))
+ }
+
+ /// The editor's Auto: the light half is the pad's colour (Arc saved the #7FB8D6 swatch picked in
+ /// Light as itself); the dark half keeps its hue near Arc's default dark half (key #8389FF → base
+ /// #01021F), drawn like an imported dark half.
+ @Test func editorHalves() throws {
+ func close(_ a: String?, _ b: String) -> Bool {
+ guard let a, let x = HexColor.components(a), let y = HexColor.components(b) else { return false }
+ return max(abs(x.r - y.r), abs(x.g - y.g), abs(x.b - y.b)) * 255 <= 6
+ }
+ let theme = SpaceThemeVariants.theme(key: ["#8389FF"], intensity: 0.5, noise: 0, appearance: "auto")
+ #expect(theme.followsSystem && theme.key == ["#8389FF"])
+ let light = theme.resolved(systemDark: false), dark = theme.resolved(systemDark: true)
+ #expect(light.colors == ["#8389FF"] && !light.isDark)
+ #expect(close(dark.accent, "#01021F") && dark.isDark)
+ #expect(SpaceThemeVariants.theme(key: ["#8389FF"], intensity: 0.5, noise: 0, appearance: "dark").dark == nil)
+ // A colour too dark for a light theme is lifted to Arc's default light half.
+ let lifted = SpaceThemeVariants.light(key: ["#0000F2"], intensity: 0.5, noise: 0)
+ #expect(!lifted.isDark && close(lifted.colors.first, "#CCCCFF"))
+ }
+}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index c949038..27284c4 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -43,6 +43,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
guard !bootstrapped else { return }
bootstrapped = true
NSApp.setActivationPolicy(.regular)
+ SystemAppearance.shared.start()
installURLEventHandler()
PerfCEF.install(app: self)
CraCEFRuntime.setChromeHosting(store.settings.chromeEngine)
@@ -605,6 +606,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
w.setFrame(NSRect(x: w.frame.minX, y: w.frame.maxY - size[1], width: size[0], height: size[1]), display: true)
return
}
+ // macOS' appearance as the app sees it (light, dark, or system to undo): Auto space
+ // themes switch halves without changing the Mac's own setting (#155).
+ if let v = dict["systemAppearance"] {
+ NSApp.appearance = v == "system" ? nil : NSAppearance(named: v == "dark" ? .darkAqua : .aqua)
+ return
+ }
if dict["relaunch"] != nil { relaunch(); return }
if dict["quit"] != nil { NSApp.terminate(nil); return }
if let t = dict["selectTab"].flatMap(UUID.init(uuidString:)) { store.selectTab(t, window: main.windowID); return }
@@ -625,6 +632,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
if let v = dict["banner"] { SoftwareUpdater.shared.debugUpdated(v == "none" ? nil : v); return }
if let v = dict["bannerReady"] { SoftwareUpdater.shared.debugReady(v == "none" ? nil : v); return }
if dict["switcher"] != nil { main.debugTabSwitcher(); return }
+ if dict["themeEditor"] != nil { main.showSpaceStyleEditor(space: store.focusedSpace); return }
if dict["jumpPill"] != nil { SpaceListView.jumpToSelected(for: main.sidebarUI, space: store.focusedSpaceID); return }
if let f = dict["folderPreview"] {
if let id = UUID(uuidString: f) { SpaceListView.debugFolderPreview(id, ui: main.sidebarUI) } else { FolderPreviewController.shared.close() }
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarView.swift b/Sources/Cra/UI/Sidebar/List/SidebarView.swift
index 24d2e12..9232ddf 100644
--- a/Sources/Cra/UI/Sidebar/List/SidebarView.swift
+++ b/Sources/Cra/UI/Sidebar/List/SidebarView.swift
@@ -20,6 +20,7 @@ final class SidebarView: NSView {
private var libraryHost: LibraryView?
private var palette: SpacePalette
private var lastSpaceID: UUID?
+ private var shownTheme: SpaceTheme?
private var shownLibrary: LibraryPage?
init(store: SidebarStore, ui: SidebarUIState, actions: SidebarActions, favicons: FaviconCache) {
@@ -53,12 +54,14 @@ final class SidebarView: NSView {
var bannerHeight: CGFloat = 0
let (space, library, trayOpen, recentCount) = withObservationTracking {
let space = store.focusedSpace(window: ui.windowID)
+ _ = SystemAppearance.shared.isDark
bannerHeight = UpdateBannerView.preferredHeight
return (space, ui.libraryPage, ui.downloadsListOpen, DownloadHistory.shared.recent.count)
} onChange: { [weak self] in
Task { @MainActor in self?.observe() }
}
- let paletteChanged = lastSpaceID == nil || space.theme != store.space(lastSpaceID ?? space.id)?.theme || space.id != lastSpaceID
+ let paletteChanged = lastSpaceID == nil || space.theme.shown != shownTheme || space.id != lastSpaceID
+ shownTheme = space.theme.shown
if space.id != lastSpaceID {
// A drag that hovered another space's icon carries the picks there; its end clears them.
if lastSpaceID != nil, ui.draggingID == nil { ui.clearPicks() }
@@ -69,8 +72,9 @@ final class SidebarView: NSView {
let colors = SidebarColors(palette)
trayHost.colors = colors
bannerHost.colors = colors
- bannerHost.themeColor = space.theme.accent ?? space.theme.colors.first
- player.setTheme(space.theme.accent ?? space.theme.colors.first, dark: palette.isDark)
+ let shown = space.theme.shown
+ bannerHost.themeColor = shown.accent ?? shown.colors.first
+ player.setTheme(shown.accent ?? shown.colors.first, dark: palette.isDark)
libraryHost?.palette = palette
}
self.bannerHeight = bannerHeight
diff --git a/Sources/Cra/UI/Theme.swift b/Sources/Cra/UI/Theme.swift
index 8653261..b488a6b 100644
--- a/Sources/Cra/UI/Theme.swift
+++ b/Sources/Cra/UI/Theme.swift
@@ -1,4 +1,5 @@
import AppKit
+import Observation
import SwiftUI
extension Color {
@@ -104,7 +105,14 @@ extension SpaceTheme {
return Color(.sRGB, red: o.0, green: o.1, blue: o.2, opacity: 1)
}
- var palette: SpacePalette {
+ /// The theme as macOS shows it now: an Auto theme's light or dark half. Read under
+ /// observation tracking, a switch of macOS' appearance redraws whatever showed the old half.
+ var shown: SpaceTheme { resolved(systemDark: SystemAppearance.shared.isDark) }
+
+ var palette: SpacePalette { shown.fixedPalette }
+
+ /// The palette of a resolved theme (its appearance is light or dark, or judged by colour).
+ private var fixedPalette: SpacePalette {
let dark = isDark
let base = colors.isEmpty ? ["#DDDDDD"] : colors
// Vibrant (Arc): raw colors at `intensity` opacity over the blur.
@@ -152,6 +160,28 @@ extension SpaceTheme {
}
}
+/// macOS' light or dark appearance, which an Auto space theme follows (Arc: appearanceBased).
+/// Cra never sets NSApp.appearance, so the app's effective appearance is the system's.
+@Observable
+final class SystemAppearance: @unchecked Sendable {
+ static let shared = SystemAppearance()
+ /// Written on the main thread only.
+ private(set) var isDark = false
+ @ObservationIgnored private var observation: NSKeyValueObservation?
+
+ @MainActor func start() {
+ update()
+ observation = NSApp.observe(\.effectiveAppearance) { [weak self] _, _ in
+ MainActor.assumeIsolated { self?.update() }
+ }
+ }
+
+ @MainActor private func update() {
+ let dark = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ if dark != isDark { isDark = dark }
+ }
+}
+
extension Color {
/// Mix toward another color in sRGB (amount 0...1).
func blendedToward(_ other: Color, _ amount: Double) -> Color {
diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swift
index 4847cc2..b365b99 100644
--- a/Sources/Cra/UI/Windows/LittleWindowController.swift
+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift
@@ -101,7 +101,8 @@ enum LittlePalette {
/// The space name in "Open in Victor": the target theme's light foreground
/// (Arc: semanticColorPalette.dark.foregroundPrimary; Victor → #FCEDBC).
static func spaceName(_ theme: SpaceTheme) -> Color {
- Color(hex: theme.accent ?? theme.colors.first ?? "#FFFFFF").blendedToward(.white, 0.72)
+ let theme = theme.shown
+ return Color(hex: theme.accent ?? theme.colors.first ?? "#FFFFFF").blendedToward(.white, 0.72)
}
}
@@ -1335,7 +1336,7 @@ final class LittleSpacesPopup: NSView, NSTextFieldDelegate {
tile.wantsLayer = true
tile.layer?.cornerRadius = 9
tile.layer?.cornerCurve = .continuous
- tile.layer?.backgroundColor = NSColor(hex: s.theme.accent ?? s.theme.colors.first ?? "#888888").cgColor
+ tile.layer?.backgroundColor = NSColor(hex: s.theme.shown.accent ?? s.theme.shown.colors.first ?? "#888888").cgColor
let emoji = NSTextField.sidebarLabel(size: 20)
emoji.stringValue = s.emoji
emoji.alignment = .center
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index ca28a64..7fa0474 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -323,6 +323,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
_ = store.prefs
_ = store.settings
_ = store.spaces
+ _ = SystemAppearance.shared.isDark
} onChange: { [weak self] in
Task { @MainActor in
self?.refresh()
@@ -341,8 +342,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// view rebuilds its whole SwiftUI tree, and a new window appearance or background redraws
// every view, so all of these follow the theme only when it changes. What the root
// views show beyond the palette they observe themselves.
- if shownTheme != space.theme {
- shownTheme = space.theme
+ if shownTheme != space.theme.shown {
+ shownTheme = space.theme.shown
// A swipe in the floating sidebar changes space under it (issue #12).
floatingSidebar?.refreshBackdrop()
shell.placeholderHost.wantsLayer = true
diff --git a/Sources/Cra/UI/Windows/ShinyToast.swift b/Sources/Cra/UI/Windows/ShinyToast.swift
index dfdba72..f53d84b 100644
--- a/Sources/Cra/UI/Windows/ShinyToast.swift
+++ b/Sources/Cra/UI/Windows/ShinyToast.swift
@@ -232,6 +232,7 @@ final class ShinyToast {
/// light (Victor's yellow/green) 220/226/184 → 208/218/163, outline 151/157/124; dark (the
/// default theme in dark mode) 43/24/102 → 33/19/79, outline 26/15/62, white text.
static func colors(_ theme: SpaceTheme) -> (top: NSColor, bottom: NSColor, outline: NSColor, text: NSColor) {
+ let theme = theme.shown
let comps = theme.colors.compactMap(HexColor.components)
let n = Double(max(comps.count, 1))
let mean = NSColor(srgbRed: comps.reduce(0) { $0 + $1.r } / n, green: comps.reduce(0) { $0 + $1.g } / n,
diff --git a/Sources/Cra/UI/Windows/SpaceStyleEditor.swift b/Sources/Cra/UI/Windows/SpaceStyleEditor.swift
index 03fb823..95a61ab 100644
--- a/Sources/Cra/UI/Windows/SpaceStyleEditor.swift
+++ b/Sources/Cra/UI/Windows/SpaceStyleEditor.swift
@@ -6,11 +6,21 @@ import SwiftUI
/// behind it darkened by ~58%; a 340 pt dotted colour pad with Auto / Light / Dark on top and − / +
/// (one to three colours) at the bottom; nine swatches between paging arrows (single colours, then
/// two-colour gradients); a wave slider for the intensity and a dotted dial for the grain. Every
-/// change shows in the space at once.
+/// change shows in the space at once. Like Arc's editor state it keeps the pad's colours, the
+/// intensity, the grain and Auto / Light / Dark, and builds the theme from them: Auto gets a light
+/// and a dark half and follows macOS, Light and Dark get one (SpaceThemeVariants).
struct SpaceStyleEditor: View {
- @State var theme: SpaceTheme
+ @State private var theme: SpaceTheme
+ @State private var pad: PadState
let onChange: (SpaceTheme) -> Void
+ init(theme: SpaceTheme, onChange: @escaping (SpaceTheme) -> Void) {
+ _theme = State(initialValue: theme)
+ _pad = State(initialValue: PadState(key: theme.key ?? theme.colors, intensity: theme.intensity, noise: theme.noise,
+ appearance: theme.appearance))
+ self.onChange = onChange
+ }
+
static let swatchPages: [[[String]]] = [
["#F1EAE5", "#E69FBA", "#9E749B", "#E1686F", "#EF8C62", "#F2D66D", "#73E59C", "#7FB8D6", "#666786"].map { [$0] },
[["#DCD2CF", "#C6BBBC"], ["#D397A2", "#BC89A8"], ["#976B86", "#7D617C"], ["#D07E6A", "#BA7087"], ["#DDA361", "#C88274"],
@@ -20,7 +30,7 @@ struct SpaceStyleEditor: View {
var body: some View {
VStack(spacing: 0) {
- ColorPad(theme: $theme)
+ ColorPad(pad: $pad)
.frame(width: 340, height: 340)
.padding(.top, 9)
HStack(spacing: 0) {
@@ -31,19 +41,16 @@ struct SpaceStyleEditor: View {
.fill(LinearGradient(colors: colors.map { Color(hex: $0) }, startPoint: .topLeading, endPoint: .bottomTrailing))
.frame(width: 24, height: 24)
.contentShape(Circle())
- .onTapGesture {
- theme.colors = colors
- theme.accent = colors.first
- }
+ .onTapGesture { pad.key = colors }
}
}
pageArrow("chevron.right", to: swatchPage + 1)
}
.padding(.top, 16.75)
HStack(spacing: 0) {
- WaveSlider(value: $theme.intensity).frame(width: 224, height: 50)
+ WaveSlider(value: $pad.intensity).frame(width: 224, height: 50)
Spacer(minLength: 0)
- GrainDial(value: $theme.noise).frame(width: 70, height: 70)
+ GrainDial(value: $pad.noise).frame(width: 70, height: 70)
}
.frame(height: 70)
.padding(.leading, 17)
@@ -61,7 +68,11 @@ struct SpaceStyleEditor: View {
.clipShape(RoundedRectangle(cornerRadius: 22, style: .continuous))
)
.environment(\.colorScheme, .dark)
- .onChange(of: theme) { _, t in onChange(t) }
+ // Opening the editor leaves the theme as it is; the first change rebuilds it from the pad.
+ .onChange(of: pad) { _, p in
+ theme = SpaceThemeVariants.theme(key: p.key, intensity: p.intensity, noise: p.noise, appearance: p.appearance)
+ onChange(theme)
+ }
}
private func pageArrow(_ symbol: String, to page: Int) -> some View {
@@ -74,11 +85,20 @@ struct SpaceStyleEditor: View {
}
}
+/// What the editor's controls set (Arc: SpaceStyleEditor.State's colours, factors and darkModeBiasSetting).
+struct PadState: Equatable {
+ var key: [String]
+ var intensity: Double
+ var noise: Double
+ /// "auto", "light" or "dark".
+ var appearance: String
+}
+
/// The dotted pad, a colour wheel: a handle's angle (clockwise from three o'clock) is its hue and its
/// distance from the centre its saturation (full at 153 pt), brightness 0.95. A second and third
/// colour follow the first 40° either side; dragging any handle turns the set.
private struct ColorPad: View {
- @Binding var theme: SpaceTheme
+ @Binding var pad: PadState
private static let reach: CGFloat = 153
private static let spread: CGFloat = 40
@@ -99,13 +119,13 @@ private struct ColorPad: View {
.contentShape(Rectangle())
// Arc: pressing anywhere on the pad brings the main colour there, and it follows the drag.
.gesture(DragGesture(minimumDistance: 0).onChanged { g in place(handle: 0, at: g.location, centre: centre) })
- if theme.colors.isEmpty {
+ if pad.key.isEmpty {
Text("Tap to pick a color for this space")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(.white.opacity(0.85))
.allowsHitTesting(false)
}
- ForEach(Array(theme.colors.prefix(3).enumerated()), id: \.offset) { i, hex in
+ ForEach(Array(pad.key.prefix(3).enumerated()), id: \.offset) { i, hex in
let main = i == 0
Circle()
.fill(Color(hex: hex))
@@ -116,11 +136,11 @@ private struct ColorPad: View {
.gesture(DragGesture(minimumDistance: 0).onChanged { g in place(handle: i, at: g.location, centre: centre) })
}
VStack {
- AppearanceToggles(appearance: $theme.appearance).padding(.top, 24)
+ AppearanceToggles(appearance: $pad.appearance).padding(.top, 24)
Spacer()
HStack(spacing: 16) {
- padButton("minus", enabled: theme.colors.count > 1) { theme.colors.removeLast() }
- padButton("plus", enabled: !theme.colors.isEmpty && theme.colors.count < 3) { addColor() }
+ padButton("minus", enabled: pad.key.count > 1) { pad.key.removeLast() }
+ padButton("plus", enabled: !pad.key.isEmpty && pad.key.count < 3) { addColor() }
}
.padding(.bottom, 20)
}
@@ -143,15 +163,14 @@ private struct ColorPad: View {
var angle = atan2(dy, dx) * 180 / .pi - Self.offset(i)
angle = (angle.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360)
let sat = min(1, hypot(dx, dy) / Self.reach)
- let count = max(1, theme.colors.count)
- theme.colors = (0..<count).map { Self.hex(hue: angle + Self.offset($0), saturation: sat) }
- theme.accent = theme.colors.first
+ let count = max(1, pad.key.count)
+ pad.key = (0..<count).map { Self.hex(hue: angle + Self.offset($0), saturation: sat) }
}
private func addColor() {
- guard let first = theme.colors.first else { return }
+ guard let first = pad.key.first else { return }
let (h, s) = Self.wheel(first)
- theme.colors.append(Self.hex(hue: h + Self.offset(theme.colors.count), saturation: s))
+ pad.key.append(Self.hex(hue: h + Self.offset(pad.key.count), saturation: s))
}
private static func offset(_ i: Int) -> CGFloat { i == 0 ? 0 : (i == 1 ? spread : -spread) }
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index 3a3a1ac..b3a9e3a 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -2604,3 +2604,29 @@ that waits 3 s before answering and then serves a page whose image takes 5 s.
Animation; a tab coming to the front shows its own state at once, without the widening or the finish. With no
margin (edge to edge, fullscreen) there is no bar; on light themes it is black at the same opacities. It slides
with the card when the sidebar hides or shows.
+
+## Light and dark space themes (Arc 1.171, 3 Nov 2026, issue #155, Swift metadata + offline Arc)
+- [O static] `WindowTheme.background` is `AppearanceBasedConfiguration<Background>`: `single(_0)` or
+ `appearanceBased(light:, dark:)`; `semanticColorPalette` and `windowAppearance` use the same wrapper. The editor's
+ state (`SpaceStyleEditor.State`) keeps `primaryColor`, `numberOfColors`, `wheel`, `intensityFactor`, `noiseFactor`,
+ `lightnessRange` and `darkModeBiasSetting = .value(Double) | .forceAppearance(light|dark)`; the toggles send
+ `didSetAutomaticAppearance` / `didSetLightAppearance` / `didSetDarkAppearance`. Strings: `sidebar-dark-mode-bias`.
+- [O live] An `appearanceBased` space (this Mac's JYSK) shows its light half under View ▸ Appearance ▸ Light, its dark
+ half under Dark, and the system's under Automatic, at once. Sidebar sampled at 2x: light 226/222/238 → 232/225/236,
+ dark 40/37/54 → 44/37/55 (Cra: 233/227/245 → 246/234/240 and 45/39/57 → 47/39/57; the light half's gap is Cra's
+ older pull toward white for opaque light themes, not this change).
+- [O live] Opened on that space, the editor shows Auto with "Tap to pick a color for this space": the two-half theme is
+ Arc's colourless default (base #C8CAFF / #FFE5E5 light at 0.5, #01021F / #1A001F dark at 0.8, key #8389FF). Both
+ halves keep the key's HSL hue; the light one sits at HSL lightness ≈ 0.9, the dark one at ≈ 0.064.
+- [O live] A swatch picked in Auto (offline Arc, menus and swatches pressed over AX: Spaces ▸ Edit Theme…, the swatch
+ buttons "Set space color to Catalog color: … ColorPickerBrandN") was written as one `single` vibrant light theme; Arc
+ writes StorableSidebar.json when the editor commits, not on every change. View ▸ Appearance is Arc's own
+ `appearance` default (cleared again after the run) and also turns the editor's toggles.
+- Cra: `SpaceTheme.dark` holds an Auto theme's dark half (top-level fields = light half) and `resolved(systemDark:)`
+ picks one; `SpaceTheme.palette` resolves through `SystemAppearance` (NSApp.effectiveAppearance, observed), so a macOS
+ switch redraws at once. Arc imports keep both halves. The editor builds halves from its pad (`SpaceTheme.key`) with
+ `SpaceThemeVariants`: the light half is the pad's colours (lifted to HSL lightness 0.9 only when they read dark),
+ the dark half keeps their hue at HSL lightness 0.064, drawn like an imported dark half (27 % over #2B2632). An
+ Auto theme saved before keeps its colours on the side they suit and derives the other.
+- [?] Not worked out: how Arc's editor maps a picked colour to its halves (the pad's `lightnessRange` and the bias
+ value). Cra's halves are fitted to Arc's default theme only.
diff --git a/docs/development.md b/docs/development.md
index faa0786..7327bd1 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -102,7 +102,9 @@ Scenario hooks for a command file (`cra://debug?…`): `checkStore=1` logs a fau
sidebar link, `pageJS=<js>` runs script in the focused page, `installExtension=<folder>` and
`removeExtension=<id>`, `extensionAction=<id>`, `fullscreen=1|0`, `windowSize=1280x800`,
`snapshot=<ViewClass[,n]>&out=<png>`, `sleepTabs=<seconds>`, `stall=<ms>` (blocks the main
-thread), `perfReport=<path>` (the recorder's perf.json now), `relaunch=1` and `quit=1`.
+thread), `perfReport=<path>` (the recorder's perf.json now), `systemAppearance=light|dark|system`
+(the appearance Auto space themes follow, without changing the Mac's), `themeEditor=1` (Edit
+Theme Color… for the focused space), `relaunch=1` and `quit=1`.
## Running a test instance