Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 59 additions & 4 deletions Sources/StableBar/Themes/ThemeEdits.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,36 @@ let widgetLookKeys: Set<String> = ["style", "background", "popupBackground", "to
let widgetStyleKeys = ["foreground", "background", "accent", "accentText", "shadowColor", "appIcons", "fontName", "fontWeight", "fontSize",
"paddingHorizontal", "paddingVertical", "paddingLeading", "paddingTrailing", "paddingTop", "paddingBottom",
"cornerRadius", "borderWidth", "borderColor", "spacing"]
/// The colors of a style. In a widget's own layout they replace the theme's under every theme, unlike its sizes and fonts,
/// which are part of how the layout is built.
let styleColorKeys: Set<String> = ["foreground", "background", "hoverForeground", "hoverBackground", "accent", "accentText",
"borderColor", "shadowColor"]

/// `layout` without the colors its blocks' styles and their states set, and how many it had. A layout Settings offers
/// by name keeps its colors, which are part of that choice.
func layoutRemovingColors(_ layout: ConfigurationValue) -> (layout: ConfigurationValue, colors: Int) {
let offered = (WidgetLayoutChoice.clock + WidgetLayoutChoice.calendar).map(\.layout)
guard !offered.contains(layout) else { return (layout, 0) }
var colors = 0
func withoutColors(_ value: ConfigurationValue) -> ConfigurationValue? {
guard case var .object(properties) = value else { return value }
for key in styleColorKeys where properties.removeValue(forKey: key) != nil { colors += 1 }
if case let .object(states)? = properties["states"] {
let kept = states.compactMapValues(withoutColors)
properties["states"] = kept.isEmpty ? nil : .object(kept)
}
return properties.isEmpty ? nil : .object(properties)
}
func block(_ value: ConfigurationValue) -> ConfigurationValue {
guard case var .object(node) = value else { return value }
if let style = node["style"] { node["style"] = withoutColors(style) }
if let row = node["row"] { node["row"] = block(row) }
if case let .array(children)? = node["children"] { node["children"] = .array(children.map(block)) }
return .object(node)
}
let result = block(layout)
return (result, colors)
}

extension ProfileConditions {
/// The theme a profile holds edits for: its only condition is the theme.
Expand Down Expand Up @@ -63,8 +93,11 @@ struct ThemeEdits {
let profile: String?
let changes: [ThemeEdit]
let everyTheme: [ThemeEdit]
/// How many style values each widget keeps under every theme, in its definition or the main file's overrides.
/// How many style values each widget keeps under every theme, in its definition or the main file's overrides,
/// counting the colors its own layout sets.
let widgetStyles: [String: Int]
/// The own layout of each widget whose layout sets colors, without them.
let layoutsWithoutColors: [String: ConfigurationValue]
private let configuration: [String: ConfigurationValue]
private let profileNames: [String]

Expand Down Expand Up @@ -92,10 +125,18 @@ struct ThemeEdits {
for definition in definitions {
if case let .string(id)? = definition["id"] { own[id] = definition }
}
for (id, override) in overrides { own[id, default: [:]].merge(override) { $1 } }
for (id, override) in overrides { own[id, default: [:]].merge(override) { $1.overriding($0) } }
// Several profiles can define a widget, and an edit of it changes the first one, active or not, so a widget
// that a profile defines keeps its layout as it is.
let profiles = (try? main["profiles"]?.decoded([ConfigurationProfileWidgets].self)) ?? []
let profileWidgets = Set(profiles.flatMap { $0.configuration?.widgets ?? [] }.compactMap(\.id))
let mainWidgets = Set(definitions.compactMap { try? $0["id"]?.decoded(String.self) })
let layouts = own.filter { mainWidgets.contains($0.key) || !profileWidgets.contains($0.key) }
.compactMapValues { $0["layout"].map(layoutRemovingColors) }.filter { $0.value.colors > 0 }
layoutsWithoutColors = layouts.mapValues(\.layout)
widgetStyles = own.mapValues { widget in
widget.filter { widgetLookKeys.contains($0.key) }.reduce(0) { $0 + lookLeaves($1.value, path: [$1.key]).count }
}
}.merging(layouts.mapValues(\.colors)) { $0 + $1 }
}

/// The main file's profile whose only condition is `themeID`.
Expand Down Expand Up @@ -386,9 +427,16 @@ extension ConfigurationEditor {
let style = ConfigurationValue.object(Dictionary(uniqueKeysWithValues: widgetStyleKeys.map { ($0, ConfigurationValue.null) })
.merging(HoverBackgroundRow.reset) { $1 })
let edits = themeEdits()
// Setting a layout merges it into the old one, so the old one goes first, from the widget's definition and from
// an override of it, whose colors would otherwise still win.
let layout = edits.layoutsWithoutColors[widget.id].map { layout in
Comment thread
M4n0x marked this conversation as resolved.
Resolved
[ConfigurationEdit(action: .unset, id: widget.id, properties: ["layout": .null]),
ConfigurationEdit(action: .unset, properties: ["widgetOverrides": .object([widget.id: .object(["layout": .null])])]),
ConfigurationEdit(action: .set, id: widget.id, properties: ["layout": layout])]
} ?? []
change([ConfigurationEdit(action: .unset, id: widget.id, properties: [
"style": style, "background": .null, "popupBackground": .null, "tooltipBackground": .null
])] + [edits.removal(of: edits.widgetChanges(widget.id))].compactMap { $0 })
])] + layout + [edits.removal(of: edits.widgetChanges(widget.id))].compactMap { $0 })
}
}

Expand All @@ -403,3 +451,10 @@ extension BarStore {
return edits + [ConfigurationEdit(action: .unset, properties: ["profiles": .object([profile: .null])])]
}
}

/// The IDs of the widgets a profile defines.
private struct ConfigurationProfileWidgets: Decodable {
struct Configuration: Decodable { let widgets: [Widget]? }
struct Widget: Decodable { let id: String? }
let configuration: Configuration?
}
33 changes: 33 additions & 0 deletions Tests/Fixtures/widget-style-layout-colors/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"theme": {
"id": "leman"
},
"widgets": [
{
"id": "apple",
"type": "appleMenu",
"position": "left"
},
{
"id": "date",
"type": "clock",
"position": "right",
"format": "EEE d MMM",
"role": "secondary",
"layout": {
"type": "field",
"field": "text",
"style": {
"foreground": "@token.track"
}
}
},
{
"id": "clock",
"type": "clock",
"position": "right",
"format": "HH:mm",
"role": "time"
}
]
}
76 changes: 76 additions & 0 deletions Tests/StableBarTests/ThemeEditsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,82 @@ struct ThemeEditsTests {
#expect(store.customizationHistory.undoSteps.count == 1)
}

@Test func colorsInAWidgetsOwnLayoutAreItsOwnStyleAndResetStyleRemovesOnlyThem() async throws {
let (fixture, store, editor) = try await editor(#"""
{"theme":{"id":"test-theme","version":"1"},"widgets":[{"id":"date","type":"clock","position":"right","style":{"fontSize":13},
"layout":{"type":"row","style":{"spacing":2,"background":{"light":"#ffffff","dark":"#000000"}},"children":[
{"type":"field","field":"date","style":{"foreground":"@token.track","fontWeight":"bold"}},
{"type":"field","field":"time","style":{"states":{"hover":{"foreground":"#ff0000"}}}}]}}]}
"""#)
defer { fixture.close(); store.stop() }
let date = try #require(store.configuration?.widgets.first)
#expect(editor.ownStyle(of: date) == (everyTheme: 4, onTheme: 0))

editor.resetStyle(of: date)

let widget = try #require(try fixture.document()["widgets"]?.decoded([[String: ConfigurationValue]].self).first)
#expect(widget["style"] == nil)
#expect(widget["layout"] == .object(["type": .string("row"), "style": .object(["spacing": .number(2)]), "children": .array([
.object(["type": .string("field"), "field": .string("date"), "style": .object(["fontWeight": .string("bold")])]),
.object(["type": .string("field"), "field": .string("time")])
])]))
#expect(store.customizationHistory.undoSteps.count == 1)
}

@Test func resetStyleTakesTheColorsOutOfALayoutThatAnOverrideChanges() async throws {
let (fixture, store, editor) = try await editor(#"""
{"theme":{"id":"test-theme","version":"1"},
"widgets":[{"id":"date","type":"clock","position":"right","layout":{"type":"field","field":"text","style":{"fontWeight":"bold"}}}],
"widgetOverrides":{"date":{"layout":{"style":{"foreground":"#ff0000"}}}}}
"""#)
defer { fixture.close(); store.stop() }
let date = try #require(store.configuration?.widgets.first)
#expect(editor.ownStyle(of: date) == (everyTheme: 1, onTheme: 0))

editor.resetStyle(of: date)

let document = try fixture.document()
#expect(document["widgetOverrides"] == nil)
#expect(try document["widgets"]?.decoded([[String: ConfigurationValue]].self).first?["layout"]
== .object(["type": .string("field"), "field": .string("text"), "style": .object(["fontWeight": .string("bold")])]))
#expect(store.customizationHistory.undoSteps.count == 1)
}

@Test func resetStyleLeavesTheLayoutOfAWidgetProfilesDefine() async throws {
let layout = #"{"type":"field","field":"text","style":{"fontWeight":"bold"}}"#
let (fixture, store, editor) = try await editor(#"""
{"theme":{"id":"test-theme","version":"1"},"widgets":[],
"profiles":[{"name":"Light","when":{"appearance":"light"},"configuration":{"widgets":[
{"id":"date","type":"clock","position":"right","layout":\#(layout)}]}},
{"name":"Dark","when":{"appearance":"dark"},"configuration":{"widgets":[
{"id":"date","type":"clock","position":"left","layout":\#(layout)}]}}],
"widgetOverrides":{"date":{"layout":{"style":{"foreground":"#ff0000","spacing":2}}}}}
"""#)
defer { fixture.close(); store.stop() }
let before = try fixture.document()
let date = try #require(store.configuration?.widgets.first)
#expect(editor.ownStyle(of: date) == (everyTheme: 0, onTheme: 0))

editor.resetStyle(of: date)

#expect(try fixture.document()["widgetOverrides"] == before["widgetOverrides"])
#expect(try fixture.document()["profiles"] == before["profiles"])
}

@Test func aLayoutSettingsOffersKeepsItsColorsAndIsNoOwnStyle() async throws {
let layout = String(decoding: try JSONEncoder().encode(WidgetLayoutChoice.countdownAndJoin.layout), as: UTF8.self)
let (fixture, store, editor) = try await editor(#"""
{"theme":{"id":"test-theme","version":"1"},"widgets":[{"id":"meeting","type":"clock","position":"right","layout":\#(layout)}]}
"""#)
defer { fixture.close(); store.stop() }
let meeting = try #require(store.configuration?.widgets.first)
#expect(editor.ownStyle(of: meeting) == (everyTheme: 0, onTheme: 0))

editor.resetStyle(of: meeting)
#expect(try fixture.document()["widgets"]?.decoded([[String: ConfigurationValue]].self).first?["layout"]
== WidgetLayoutChoice.countdownAndJoin.layout)
}

@Test func aWidgetJoiningTheThemesGroupIsAnEditButNotAStyleAndEveryThemeGetsTheGroup() async throws {
let (fixture, store, editor) = try await editor(#"""
{"theme":{"id":"test-theme","version":"1"},"widgets":[{"id":"clock","type":"clock","position":"right"}],
Expand Down
Loading
Loading