diff --git a/Sources/StableBar/Themes/ThemeEdits.swift b/Sources/StableBar/Themes/ThemeEdits.swift index 8f490aa1..82c46a6f 100644 --- a/Sources/StableBar/Themes/ThemeEdits.swift +++ b/Sources/StableBar/Themes/ThemeEdits.swift @@ -9,6 +9,36 @@ let widgetLookKeys: Set = ["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 = ["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. @@ -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] @@ -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`. @@ -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 + [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 }) } } @@ -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? +} diff --git a/Tests/Fixtures/widget-style-layout-colors/config.json b/Tests/Fixtures/widget-style-layout-colors/config.json new file mode 100644 index 00000000..1f3253a3 --- /dev/null +++ b/Tests/Fixtures/widget-style-layout-colors/config.json @@ -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" + } + ] +} diff --git a/Tests/StableBarTests/ThemeEditsTests.swift b/Tests/StableBarTests/ThemeEditsTests.swift index 29b67aed..b5ca4676 100644 --- a/Tests/StableBarTests/ThemeEditsTests.swift +++ b/Tests/StableBarTests/ThemeEditsTests.swift @@ -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"}], diff --git a/docs/settings.md b/docs/settings.md index 3f0875eb..efe9998a 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -27,7 +27,7 @@ Drag widgets in the bar preview or the list, within or between position groups, Choose **Edit Bar in Place** in **Settings → Bar**, or in the bar's right-click or menu-bar icon menu, to arrange widgets on every display. While setup is open, the right-click and menu-bar icon menus leave it out and **Settings → Bar** shows it dimmed, since setup saves its choices only when you finish; setup's last card offers it then. Widgets keep their look, size and order, and the bar keeps its height; the one under the pointer is shaded, and the pointer becomes a hand that grabs it while you drag. Each position becomes a softly outlined zone with a **+** at its inner end, including empty positions; the zones open when editing starts, and hovering a zone shows its name. Widgets hidden by their output or screen choice appear as named placeholders with a crossed-out eye; empty widgets show their names too. Other names appear in tooltips. Turned-off widgets aren't shown; turn one on again in **Settings → Bar**, or add a Store package again with **+**. Widgets that don't fit and normally wait behind **…** come onto the bar while you edit. A side of the bar too crowded for its widgets scrolls instead: swipe, use the scroll wheel, or click the arrow at a faded edge, which stays clear of the notch. At first it shows the end where its widgets stay when they don't all fit. Drag a widget within or between positions, like icons in the Dock: the other widgets slide aside to open a highlighted gap where it would land, and the zone under the pointer is highlighted and named in a tooltip below the bar. Hold a widget near a crowded side's edge to scroll it. The widget settles into the gap when you drop it. Grouped widgets move together. With Reduce Motion on, widgets move without sliding. **+** opens an **Add here** popover below it, or above it on a bar at the bottom, with search and a two-column choice of widgets. Adding puts the widget exactly where that **+** sits. With more than one kind of screen connected, the popover has an **Add to** checkbox for each; the widget shows on the checked ones, all by default. Packages with commands, permissions, hosts, required tools or secret settings are reviewed in the popover first. The **−** badge on a widget’s top-left corner removes it from the bar; a widget from a package takes its package off the bar, and a widget from an include is turned off. Click a widget to open its settings here. Its usual clicks, popups and mouse actions pause while editing, and it doesn't react to hovering. The update tile isn't shown while editing the bar. The widget's context menu also offers **Move Left**, **Move Right**, **Move To** and **Shows On**, with the same screen choices as in Settings, and the same **Add to Group**, **Group With** and **Leave Group** commands as there. A group started here stays on the bar; **Edit Group…** opens it in Settings to choose its look. With VoiceOver, use the widget's **Move left** and **Move right** accessibility actions. Changes save automatically. **Undo** and **Done** sit in a small panel below the bar, or above a bar at the bottom. Use **Undo**, or ⌘Z and ⇧⌘Z while the bar has focus, to undo and redo through the same history as Settings. **Esc** closes an open Add here popover first. **Done**, **Esc** while the bar has focus, **Finish Editing Bar** or an explicit or external configuration reload restores the normal bar. Automatic profile changes keep editing open. Temporary command-line changes stay separate and unsaved. -Widgets use your chosen IDs as names. Widgets added in Settings use their package name, short text or type, with numbers to tell matching names apart. A selected widget has **Content**, **Style** and **Behavior** inspector tabs. Content contains text, symbols, clock format, the [Display](create-a-widget.md#composing-widgets) of battery, sound and System monitor widgets, what a System monitor shows, and ordinary package settings; **Open package** opens shared settings and credentials in the Store. Style starts with the widget's state: **Follows Clear** while it has no style of its own, **Own style on Clear · 3 changes** when some of its style is an edit of the selected theme, counting the values it keeps under every theme too, or **Own style · 2 values** when its own style applies under every theme. **Reset style** removes all of it, so the widget takes its style from the theme again, and from its package when the package sets one. Below that, Style edits colors, app icons, font, text size, padding, corner radius, border, workspace presentation and the space between the icons Menu bar items shows on the bar. **Widget background**, **Popup background** and **Tooltip background** control [each surface separately](widgets.md#backgrounds); making the widget transparent leaves its popup and tooltip backgrounds alone. Behavior contains click actions, tooltip, popup-on-hover and position. **Shows on**, beside the widget's name, chooses its screens: **All screens**, **Only on** the selected screen, each kind of screen, **Other rules** for the active or main screen, external screens and screens with or without a notch, or **Hidden everywhere**, which turns the widget off and keeps its settings. Hidden widgets offer **Show here**; widgets with a problem offer **Troubleshoot…**. +Widgets use your chosen IDs as names. Widgets added in Settings use their package name, short text or type, with numbers to tell matching names apart. A selected widget has **Content**, **Style** and **Behavior** inspector tabs. Content contains text, symbols, clock format, the [Display](create-a-widget.md#composing-widgets) of battery, sound and System monitor widgets, what a System monitor shows, and ordinary package settings; **Open package** opens shared settings and credentials in the Store. Style starts with the widget's state: **Follows Clear** while it has no style of its own, **Own style on Clear · 3 changes** when some of its style is an edit of the selected theme, counting the values it keeps under every theme too, or **Own style · 2 values** when its own style applies under every theme. Colors that the widget's own `layout` in your configuration sets count too, unless it's a display Settings offers, such as **Countdown and Join**, whose colors belong to it. **Reset style** removes all of it, taking only the colors out of the layout, so the widget takes its style from the theme again, and from its package when the package sets one. Below that, Style edits colors, app icons, font, text size, padding, corner radius, border, workspace presentation and the space between the icons Menu bar items shows on the bar. **Widget background**, **Popup background** and **Tooltip background** control [each surface separately](widgets.md#backgrounds); making the widget transparent leaves its popup and tooltip backgrounds alone. Behavior contains click actions, tooltip, popup-on-hover and position. **Shows on**, beside the widget's name, chooses its screens: **All screens**, **Only on** the selected screen, each kind of screen, **Other rules** for the active or main screen, external screens and screens with or without a notch, or **Hidden everywhere**, which turns the widget off and keeps its settings. Hidden widgets offer **Show here**; widgets with a problem offer **Troubleshoot…**. Choose an app or web page to open on click. Workspaces offers **Show each window**, **Title length**, **Magnify on hover**, **Magnification**, **Dock badges**, **Hide apps** and **Hide workspaces**, and keeps its own clicks to switch workspaces or focus windows. App menus keeps its clicks to open menus; Spacer has no click control. The widget’s **More** menu offers **Edit as JSON…**, **Copy widget ID**, **Presentation role**, **Transition** where supported, **Troubleshoot…**, **Reset widget…** and **Remove from bar**. **Edit as JSON…** keeps quotes straight, undoes with ⌘Z, finds with ⌘F and selects the line of a syntax error. **Reset widget…** asks first, saying what stays, then takes a widget from a package or imported file back to how that file defines it, keeping its position and screens. For a widget defined in your configuration, it removes its style, background overrides, role, rules, transition, tooltip, click action, format and workspace options, and keeps what it shows and where it sits; a Quick toggles widget's tiles go back to the standard ones. Existing commands, menus and detailed layouts remain available through JSON. Each color shows a light and a dark swatch: click one to give that appearance a theme color, such as Text or Accent, or a custom color. A gradient or None applies to both. diff --git a/scenes/settings-widget-style-layout-colors.json b/scenes/settings-widget-style-layout-colors.json new file mode 100644 index 00000000..5d1deef1 --- /dev/null +++ b/scenes/settings-widget-style-layout-colors.json @@ -0,0 +1,9 @@ +{ + "$schema": "../scene.schema.json", + "configuration": "../Tests/Fixtures/widget-style-layout-colors/config.json", + "draw": "settings", + "widget": "date", + "tab": "style", + "appearances": ["dark"], + "height": 1250 +}