diff --git a/DECISIONS.md b/DECISIONS.md index fc1af84e..f667abc5 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -23,6 +23,7 @@ Add an entry when a pull request sets a rule, a policy or a choice not to do som ## Code +- **Sliders may take a role implicitly** (2026-11-17). Sliders with neither `filled` nor another role follow a nonempty `slider` role, so themes can style controls without owning widget layouts. Explicit `filled` choices retain their behavior, and an empty role retains the native control. Other blocks still require explicit roles. - **Window managers own their gaps** (2026-11-13). StableBar does not turn macOS menu-bar auto-hide off to reserve space: that changes the usable screen area underneath existing window-manager gaps, and the reserved height does not follow StableBar’s height. Keep windows clear remains a correction for ordinary windows after a drag. - **Architecture rules are tests** (2026-11-08, [#484]). `ArchitectureRulesTests` caps `BarStore`'s stored state, a number that only goes down, allows no `unowned` reference ([#493]) and keeps private macOS API in `PrivateAPI.swift` ([#490]). - **Private macOS API is a maintainer's call** (2026-11-08, [#484], [#490]). Every call lives in `PrivateAPI.swift` and is looked up at runtime, never with `@_silgen_name`, so a macOS without one turns off only its feature. diff --git a/Sources/StableBar/AppearanceView.swift b/Sources/StableBar/AppearanceView.swift index 96232d60..348008ec 100644 --- a/Sources/StableBar/AppearanceView.swift +++ b/Sources/StableBar/AppearanceView.swift @@ -476,9 +476,12 @@ struct ThemeAdvancedSheet: View { role.color("Accent", "accent") role.number("Border width", "borderWidth", default: 0) role.number("Corner radius", "cornerRadius", default: 0) + if selectedRole == .slider { role.number("Height", "height", default: 28) } role.number("Horizontal padding", "paddingHorizontal", default: 0) role.number("Vertical padding", "paddingVertical", default: 0) - Text("Only widgets and layout blocks explicitly assigned this role use it. A bar widget’s role does not style its popup.") + Text(selectedRole == .slider + ? "Sliders follow this role unless they set filled or another role. An empty role keeps the native slider." + : "Only widgets and layout blocks explicitly assigned this role use it. A bar widget’s role does not style its popup.") .font(.callout).foregroundStyle(.secondary) } } diff --git a/Sources/StableBar/BarInspector.swift b/Sources/StableBar/BarInspector.swift index a4054fba..2d0c1d96 100644 --- a/Sources/StableBar/BarInspector.swift +++ b/Sources/StableBar/BarInspector.swift @@ -187,7 +187,10 @@ struct BarInspector: View { if $0 != (widget.role?.rawValue ?? "") { editor.set(["role": $0.isEmpty ? .null : .string($0)], for: widget.id) } })) { Text("None").tag("") - ForEach(PresentationRole.allCases, id: \.rawValue) { Text($0.rawValue.capitalized).tag($0.rawValue) } + // The slider role styles slider blocks, not a whole widget. + ForEach(PresentationRole.allCases.filter { $0 != .slider || widget.role == .slider }, id: \.rawValue) { + Text($0.rawValue.capitalized).tag($0.rawValue) + } } if widget.drawsTransitions { Picker("Transition", selection: string("transition", for: widget, diff --git a/Sources/StableBar/BarStore.swift b/Sources/StableBar/BarStore.swift index 294b526c..c24981a6 100644 --- a/Sources/StableBar/BarStore.swift +++ b/Sources/StableBar/BarStore.swift @@ -854,7 +854,7 @@ final class BarStore: NSObject { let script = scripts[widget.id] let base = resolveStyle(widgetStyleLayers(widget, defaults: configuration.defaults, overrides: overrides, own: script?.output, role: configuration.roleStyle(widget.role))) - let usesMode = base.usesModeStates || widget.layout?.usesModeStates(roles: configuration.roles) == true + let usesMode = base.usesModeStates || configuration.usesSliderModeStates(widget) || widget.layout?.usesModeStates(roles: configuration.roles) == true || widget.hoverLayout?.usesModeStates(roles: configuration.roles) == true || widget.overlay?.usesModeStates(roles: configuration.roles) == true || script?.output.styles?.values.contains(where: \.usesModeStates) == true @@ -871,8 +871,12 @@ final class BarStore: NSObject { let base = resolveStyle(widgetStyleLayers(own, defaults: look.defaults, overrides: screenOverrides[kind]!, own: script?.output, role: look.roleStyle(own.role))) let screenStates = widgetDataStates(script?.output, widget: own, providers: configuration.providers) + let screenUsesMode = usesMode || base.usesModeStates || look.usesSliderModeStates(own) + || own.layout?.usesModeStates(roles: look.roles) == true + || own.hoverLayout?.usesModeStates(roles: look.roles) == true + || own.overlay?.usesModeStates(roles: look.roles) == true screenStyles[kind] = ResolvedWidgetStyle(base: base, state: screenStates.widget, parts: screenStates.parts, - mode: usesMode ? modePresentation(on: ScreenKind(rawValue: kind)!) : ModePresentation()) + mode: screenUsesMode ? modePresentation(on: ScreenKind(rawValue: kind)!) : ModePresentation()) } presentations[widget.id]?.update(style: ResolvedWidgetStyle(base: base, state: states.widget, parts: states.parts, mode: usesMode ? mode : ModePresentation()), diff --git a/Sources/StableBar/BarView.swift b/Sources/StableBar/BarView.swift index 39fd35d2..c11034b6 100644 --- a/Sources/StableBar/BarView.swift +++ b/Sources/StableBar/BarView.swift @@ -869,6 +869,7 @@ struct WidgetView: View { case .provider where isSound && inlineHoverControls: SoundWidgetView(widget: widget, store: store, monitor: monitor, style: resolution.layoutStyle(configured: false, hovered: hovered, open: open), + sliderStates: resolution.blockStates(open: open), hovered: hovered, motion: motion, runAction: blockAction) case .spacer where widget.layout == nil: Spacer(minLength: resolution.base.minWidth ?? 0) @@ -900,9 +901,10 @@ struct WidgetView: View { if let layout = widget.hoverLayout { WidgetBlocks(widget: widget, store: store, style: LayoutStyle(inherited: style, states: resolution.blockStates(open: false), tracksHover: true), - block: layout, motion: motion, runAction: blockAction) + block: layout, inline: false, motion: motion, runAction: blockAction) } else { - VolumeSlider(widget: widget, store: store, appearance: WidgetAppearance(style, defaults: WidgetStyle()), width: 120) + VolumeSlider(widget: widget, store: store, + style: LayoutStyle(inherited: style, states: resolution.blockStates(open: false), tracksHover: true), width: 120) } } .controlSize(.small) @@ -935,6 +937,7 @@ struct WidgetBlocks: View { let store: BarStore let style: LayoutStyle var block: PopupBlock? + var inline = true var date = Date.now var fillsWidth = false var motion = BlockMotion() @@ -952,6 +955,7 @@ struct WidgetBlocks: View { menu: script?.output.menu ?? widget.menu ?? [], values: script?.output.values ?? [:], targets: script?.output.targets ?? [:], styles: script?.output.styles ?? [:], series: script?.output.series ?? [:], roles: store.configuration?.look(on: screenKind).roles ?? [:], + inlineControlHeight: inline ? style.inherited.inlineControlHeight : nil, fillsWidth: fillsWidth, open: { if store.barEditing.allowsWidgetActions { $0.open() } }, quit: { if store.barEditing.allowsWidgetActions { confirmQuit($0) } }, pressMenuBarItem: { if store.barEditing.allowsWidgetActions { store.appMenu.press($0) } }, diff --git a/Sources/StableBar/FilledSlider.swift b/Sources/StableBar/FilledSlider.swift index 28fc67fa..7ad5a946 100644 --- a/Sources/StableBar/FilledSlider.swift +++ b/Sources/StableBar/FilledSlider.swift @@ -66,7 +66,7 @@ struct FilledSliderTrack: Equatable { /// A slider drawn as a bar in the block's style rather than macOS's control: its background is the track, the /// accent fills it from the leading edge, and an optional symbol sits on the fill in the accent's text color. An end /// stop follows a notch at its trailing end and fills the whole bar. Clicking or dragging anywhere sets the value. It -/// sends its value when the drag ends, as the native slider does. +/// sends its value when the drag ends, or continuously for the built-in volume control. struct FilledSlider: View { let title: String let value: Double @@ -79,6 +79,7 @@ struct FilledSlider: View { /// Whether the block draws no track of its own, so the slider draws a faint one. let drawsTrack: Bool let appearance: WidgetAppearance + var continuous = false let onChange: (Double) -> Void @State private var dragged: FilledSliderTrack.Stop? @State private var editing = false @@ -186,11 +187,12 @@ struct FilledSlider: View { } else { dragged = stop } + if continuous { onChange(sent(stop)) } } private func finish() { editing = false - if let dragged { onChange(sent(dragged)) } + if !continuous, let dragged { onChange(sent(dragged)) } } /// A keyboard or VoiceOver step, which applies at once. diff --git a/Sources/StableBar/PopupConfiguration.swift b/Sources/StableBar/PopupConfiguration.swift index b5d64f19..c73428f1 100644 --- a/Sources/StableBar/PopupConfiguration.swift +++ b/Sources/StableBar/PopupConfiguration.swift @@ -145,6 +145,9 @@ indirect enum PopupContent: Sendable { struct PopupBlock: Decodable, Sendable { let content: PopupContent + /// An omitted choice lets the slider role decide; explicit false keeps the native control. + private(set) var sliderFilled: Bool? + private(set) var sliderIcon: String? let role: PresentationRole? let style: WidgetStyle let alignment: PopupAlignment @@ -332,15 +335,17 @@ struct PopupBlock: Decodable, Sendable { if let endStop, (minimum...maximum).contains(endStop.value) { throw DecodingError.dataCorruptedError(forKey: .endStop, in: values, debugDescription: "An end stop's value must be outside min…max, so the slider can tell it from a step.") } - let filled = try values.decodeIfPresent(Bool.self, forKey: .filled) ?? false + let filled = try values.decodeIfPresent(Bool.self, forKey: .filled) let icon = try values.decodeIfPresent(String.self, forKey: .icon) - if icon != nil, !filled { - throw DecodingError.dataCorruptedError(forKey: .icon, in: values, debugDescription: "Only a filled slider shows an icon; add \"filled\": true.") + if icon != nil, filled == false { + throw DecodingError.dataCorruptedError(forKey: .icon, in: values, debugDescription: "Only a filled slider shows an icon; remove \"filled\": false to follow the slider role, or set it to true.") } + sliderFilled = filled + sliderIcon = icon let title = try values.decode(String.self, forKey: .title) let source = try values.decode(String.self, forKey: .source) let action = try controlAction([.volume]) - content = filled + content = filled == true ? .filledSlider(title: title, source: source, minimum: minimum, maximum: maximum, step: step, endStop: endStop, icon: icon, action: action) : .slider(title: title, source: source, minimum: minimum, maximum: maximum, step: step, endStop: endStop, action: action) diff --git a/Sources/StableBar/PopupView.swift b/Sources/StableBar/PopupView.swift index bf9c768e..39abc6be 100644 --- a/Sources/StableBar/PopupView.swift +++ b/Sources/StableBar/PopupView.swift @@ -187,6 +187,9 @@ struct BlockContext { var styles: [String: WidgetStyle] = [:] var series: [String: [Double]] = [:] var roles: [String: WidgetStyle] = [:] + /// Nil in popups and tooltips; bar controls must fit the widget's content area. + var inlineControlHeight: Double? + var continuousSliders = false /// Popup layouts fill their width; bar layouts take their content's width. var fillsWidth = true /// Opens an `open` or `openField` block's target; a popup's also closes the popup when its actions dismiss it. @@ -332,10 +335,10 @@ struct PopupBlockView: View { } private var styledContent: some View { - let resting = block.resolvedStyle(inherited: inheritedStyle, styles: context.styles, fields: fields, states: context.states, roles: context.roles) + let resting = resolvedStyle(states: context.states) var hovering = context.states hovering.hover = true - let current = hovered ? block.resolvedStyle(inherited: inheritedStyle, styles: context.styles, fields: fields, states: hovering, roles: context.roles) : resting + let current = hovered ? resolvedStyle(states: hovering) : resting let stacksBlocks = if topLevel, case .column = block.content { true } else { false } var box = current.box var drawn = resting @@ -344,6 +347,7 @@ struct PopupBlockView: View { box.background = nil drawn = current } + if block.automaticallyFillsSlider(roles: context.roles) { drawn = current } let appearance = WidgetAppearance(drawn.text, defaults: WidgetStyle(spacing: stacksBlocks ? PopupConfiguration.blockSpacing : nil)) let alignment: Alignment = switch block.alignment { case .leading: .leading @@ -421,6 +425,12 @@ struct PopupBlockView: View { .frame(maxWidth: block.fitsWidth && context.fillsWidth ? .infinity : nil, alignment: alignment) } + private func resolvedStyle(states: StyleStates) -> BlockStyle { + let style = block.resolvedStyle(inherited: inheritedStyle, styles: context.styles, fields: fields, states: states, roles: context.roles) + return block.automaticallyFillsSlider(roles: context.roles) + ? style.limitingSliderHeight(to: context.inlineControlHeight) : style + } + private func fieldText(_ text: String) -> Text { block.markdown ? MarkdownBlocks.inline(text) : Text(text) } @@ -460,7 +470,13 @@ struct PopupBlockView: View { /// A child block, built as a concrete view so SwiftUI diffs it without type erasure. private func child(_ block: PopupBlock, of style: BlockStyle, fields: [String: String]) -> PopupBlockView { - PopupBlockView(block: block, inheritedStyle: style.inherited, fields: fields, context: context) + var context = context + if let limit = context.inlineControlHeight { + // Negative padding lets a child overflow its box, but an inline control still stays within the widget. + let inset = max(style.box.paddingTop ?? style.box.paddingVertical ?? 0, 0) + max(style.box.paddingBottom ?? style.box.paddingVertical ?? 0, 0) + context.inlineControlHeight = max(min(limit, style.box.height ?? limit) - inset, 1) + } + return PopupBlockView(block: block, inheritedStyle: style.inherited, fields: fields, context: context) } @ViewBuilder @@ -559,7 +575,10 @@ struct PopupBlockView: View { .modifier(FocusRing(cornerRadius: appearance.cornerRadius)) case let .slider(title, source, minimum, maximum, step, endStop, action): let value = context.values[source] ?? Double(fields[source] ?? "") ?? minimum - if let endStop { + if block.automaticallyFillsSlider(roles: context.roles) { + filledSlider(title: title, value: value, minimum: minimum, maximum: maximum, step: step, + endStop: endStop, icon: block.sliderIcon, action: action, style: style, appearance: appearance) + } else if let endStop { EndStopSlider(title: title, value: value, minimum: minimum, maximum: maximum, step: step, endStop: endStop) { context.runAction(action, ["VALUE": String($0)]) } @@ -570,12 +589,8 @@ struct PopupBlockView: View { } case let .filledSlider(title, source, minimum, maximum, step, endStop, icon, action): let value = context.values[source] ?? Double(fields[source] ?? "") ?? minimum - let inset = (style.box.paddingTop ?? style.box.paddingVertical ?? 0) + (style.box.paddingBottom ?? style.box.paddingVertical ?? 0) - FilledSlider(title: title, value: value, minimum: minimum, maximum: maximum, step: step, endStop: endStop, icon: icon, - height: max((style.box.height ?? 28) - inset, 1), drawsTrack: style.box.background == nil, - appearance: appearance) { - context.runAction(action, ["VALUE": String($0)]) - } + filledSlider(title: title, value: value, minimum: minimum, maximum: maximum, step: step, + endStop: endStop, icon: icon, action: action, style: style, appearance: appearance) case let .toggle(title, source, action): PopupToggle(title: title, value: fields[source] == "true" || fields[source] == "1" || context.values[source] == 1) { context.runAction(action, ["VALUE": $0 ? "true" : "false"]) @@ -685,6 +700,19 @@ struct PopupBlockView: View { } } +extension PopupBlockView { + private func filledSlider(title: String, value: Double, minimum: Double, maximum: Double, step: Double, + endStop: SliderEndStop?, icon: String?, action: BlockAction, style: BlockStyle, + appearance: WidgetAppearance) -> some View { + let inset = (style.box.paddingTop ?? style.box.paddingVertical ?? 0) + (style.box.paddingBottom ?? style.box.paddingVertical ?? 0) + return FilledSlider(title: title, value: value, minimum: minimum, maximum: maximum, step: step, endStop: endStop, icon: icon, + height: max((style.box.height ?? 28) - inset, 1), drawsTrack: style.box.background == nil, + appearance: appearance, continuous: context.continuousSliders) { + context.runAction(action, ["VALUE": String($0)]) + } + } +} + struct ControlEditingPreference: PreferenceKey { static let defaultValue = false diff --git a/Sources/StableBar/PresentationConfiguration.swift b/Sources/StableBar/PresentationConfiguration.swift index 5101effe..12be3901 100644 --- a/Sources/StableBar/PresentationConfiguration.swift +++ b/Sources/StableBar/PresentationConfiguration.swift @@ -1,7 +1,7 @@ import Foundation enum PresentationRole: String, Decodable, CaseIterable, Sendable { - case time, primary, secondary, key, value, heading, button, meter, separator + case time, primary, secondary, key, value, heading, button, meter, separator, slider } /// Only presentation belongs in workspace defaults. Workspace visibility and local app-glyph diff --git a/Sources/StableBar/SliderPresentation.swift b/Sources/StableBar/SliderPresentation.swift new file mode 100644 index 00000000..0dc20f90 --- /dev/null +++ b/Sources/StableBar/SliderPresentation.swift @@ -0,0 +1,51 @@ +import AppKit + +extension PopupBlock { + func automaticallyFillsSlider(roles: [String: WidgetStyle]) -> Bool { + guard case .slider = content, sliderFilled == nil, role == nil || role == .slider else { return false } + return roles[PresentationRole.slider.rawValue].map { $0 != WidgetStyle() } ?? false + } + + func effectiveRole(roles: [String: WidgetStyle]) -> PresentationRole? { + automaticallyFillsSlider(roles: roles) ? .slider : role + } +} + +extension WidgetStyle { + /// The bar owns its height. A theme's control height must fit inside its vertical padding. + @MainActor var inlineControlHeight: Double { + if let height { + let top = paddingTop ?? paddingVertical ?? 6 + let bottom = paddingBottom ?? paddingVertical ?? 6 + return max(height - top - bottom, 1) + } + let size = fontSize ?? 13 + let font = fontName.flatMap { NSFont(name: $0, size: size) } ?? NSFont.systemFont(ofSize: size) + return ceil(NSLayoutManager().defaultLineHeight(for: font)) + } + + func limitingSliderHeight(to limit: Double?) -> WidgetStyle { + guard let limit else { return self } + var box = self + let height = max(min(self.height ?? 28, limit), 1) + let top = max(paddingTop ?? paddingVertical ?? 0, 0) + let bottom = max(paddingBottom ?? paddingVertical ?? 0, 0) + let scale = top + bottom > 0 ? min((height - 1) / (top + bottom), 1) : 1 + box.height = height + box.paddingTop = top * scale + box.paddingBottom = bottom * scale + return box + } +} + +extension BlockStyle { + func limitingSliderHeight(to limit: Double?) -> BlockStyle { + BlockStyle(inherited: inherited, text: text, box: box.limitingSliderHeight(to: limit)) + } +} + +extension Configuration { + func usesSliderModeStates(_ widget: WidgetConfiguration) -> Bool { + widget.layout == nil && providerType(of: widget) == "audio" && roleStyle(.slider).usesModeStates + } +} diff --git a/Sources/StableBar/SoundWidgetView.swift b/Sources/StableBar/SoundWidgetView.swift index 77ebf1c3..48bdfeb6 100644 --- a/Sources/StableBar/SoundWidgetView.swift +++ b/Sources/StableBar/SoundWidgetView.swift @@ -9,6 +9,8 @@ struct SoundWidgetView: View { let store: BarStore let monitor: Int let style: LayoutStyle + /// The widget's block states, so a themed slider follows its role's hover and mode states. + var sliderStates = StyleStates() let hovered: Bool let motion: BlockMotion let runAction: (BlockAction, [String: String]) -> Void @@ -32,7 +34,9 @@ struct SoundWidgetView: View { Group { if volume != nil { HoverExpansionLayout(expansion: expanded ? 1 : 0, spacing: appearance.spacing, controlsBefore: Self.opensBeforeIcon(widget.position)) { - VolumeSlider(widget: widget, store: store, appearance: appearance, width: 72) + VolumeSlider(widget: widget, store: store, + style: LayoutStyle(inherited: style.inherited, states: sliderStates, tracksHover: true), + width: 72, inline: true) .controlSize(.mini) .allowsHitTesting(expanded) .accessibilityHidden(!expanded) @@ -58,24 +62,48 @@ struct SoundWidgetView: View { struct VolumeSlider: View { let widget: WidgetConfiguration let store: BarStore - let appearance: WidgetAppearance + let style: LayoutStyle let width: CGFloat + var inline = false /// The slider's value while it is dragged, ahead of the volume the source reads back. @State private var level: Double? @State private var dragging = false + @Environment(\.screenKind) private var screenKind + + private static let slider = PopupBlock(content: .slider(title: "Volume", source: "volume", minimum: 0, maximum: 1, + step: 0.01, endStop: nil, action: .set(.volume))) var body: some View { if let volume = store.scripts[widget.id]?.output.values?["volume"] { let shown = level ?? volume + let appearance = WidgetAppearance(style.inherited, defaults: WidgetStyle()) + let roles = store.configuration?.look(on: screenKind).roles ?? [:] HStack(spacing: appearance.spacing) { - // A line of text tall, so opening the slider doesn't make the widget taller. - Text(" ").hidden().frame(width: width).overlay { - Slider(value: Binding(get: { shown }, set: { set($0) }), in: 0...1) { editing in - dragging = editing - if !editing { level = nil } + if Self.slider.automaticallyFillsSlider(roles: roles) { + PopupBlockView(block: Self.slider, inheritedStyle: style.inherited, fields: [:], + context: BlockContext(values: ["volume": shown], roles: roles, + inlineControlHeight: inline ? style.inherited.inlineControlHeight : nil, + continuousSliders: true, fillsWidth: false, open: { _ in }, + states: style.states, tracksHover: style.tracksHover, + runAction: { _, values in + if let value = values["VALUE"].flatMap(Double.init) { set(value) } + })) + .frame(width: width) + // The HStack's own preference below replaces the slider's, so pass the drag on through it. + .onPreferenceChange(ControlEditingPreference.self) { editing in + dragging = editing + if !editing { level = nil } + } + } else { + // A line of text tall, so opening the slider doesn't make the widget taller. + Text(" ").hidden().frame(width: width).overlay { + Slider(value: Binding(get: { shown }, set: { set($0) }), in: 0...1) { editing in + dragging = editing + if !editing { level = nil } + } + .tint(appearance.accent) + .accessibilityLabel("Volume") } - .tint(appearance.accent) - .accessibilityLabel("Volume") } // As wide as 100% at any volume, so dragging doesn't move the bar. ZStack(alignment: .trailing) { @@ -87,6 +115,8 @@ struct VolumeSlider: View { } .font(appearance.font) .foregroundStyle(appearance.foreground) + // Keyboard and VoiceOver changes set the volume without a drag, so only a drag keeps its value over the source's. + .onChange(of: volume) { if !dragging { level = nil } } .preference(key: ControlEditingPreference.self, value: dragging) } } diff --git a/Sources/StableBar/StyleResolution.swift b/Sources/StableBar/StyleResolution.swift index 35d10f07..1b0837e5 100644 --- a/Sources/StableBar/StyleResolution.swift +++ b/Sources/StableBar/StyleResolution.swift @@ -226,7 +226,7 @@ extension PopupBlock { var usesModeStates: Bool { usesModeStates(roles: [:]) } func usesModeStates(roles: [String: WidgetStyle]) -> Bool { - if style.usesModeStates || role.flatMap({ roles[$0.rawValue] })?.usesModeStates == true { return true } + if style.usesModeStates || effectiveRole(roles: roles).flatMap({ roles[$0.rawValue] })?.usesModeStates == true { return true } switch content { case let .row(children), let .column(children), let .ring(_, _, _, children): return children.contains { $0.usesModeStates(roles: roles) } case let .list(_, row, _), let .search(_, _, _, row): return row.usesModeStates(roles: roles) @@ -239,7 +239,7 @@ extension PopupBlock { func resolvedStyle(inherited: WidgetStyle, styles: [String: WidgetStyle], fields: [String: String], states: StyleStates, roles: [String: WidgetStyle] = [:]) -> BlockStyle { let name = styleField.flatMap { fields[$0] } ?? styleSource - let role = role.flatMap { roles[$0.rawValue] } ?? WidgetStyle() + let role = effectiveRole(roles: roles).flatMap { roles[$0.rawValue] } ?? WidgetStyle() let output = name.flatMap { styles[$0] } ?? WidgetStyle() let own = resolveStyle([role, style, output]) let merged = resolveStyle([inherited, own]) @@ -258,11 +258,11 @@ extension PopupConfiguration { extension Configuration { var needsModeConnection: Bool { - subscribedEvents.contains(BuiltInEvent.aerospaceMode.rawValue) || bar.style.usesModeStates + screenLooks.values.contains(where: \.needsModeConnection) || subscribedEvents.contains(BuiltInEvent.aerospaceMode.rawValue) || bar.style.usesModeStates || defaults.usesModeStates || popupDefaults.usesModeStates || popups.values.contains { $0.usesModeStates(roles: roles) } || widgets.contains { widget in - widget.enabled && (widget.style.usesModeStates || roleStyle(widget.role).usesModeStates + widget.enabled && (widget.style.usesModeStates || roleStyle(widget.role).usesModeStates || usesSliderModeStates(widget) || widget.layout?.usesModeStates(roles: roles) == true || widget.hoverLayout?.usesModeStates(roles: roles) == true || widget.overlay?.usesModeStates(roles: roles) == true || widget.workspace?.usesModeStates == true diff --git a/Sources/StableBar/WidgetPopup.swift b/Sources/StableBar/WidgetPopup.swift index 29687873..172fd8cf 100644 --- a/Sources/StableBar/WidgetPopup.swift +++ b/Sources/StableBar/WidgetPopup.swift @@ -496,6 +496,8 @@ final class WidgetPopup { .foregroundStyle(appearance.foreground) .padding(.horizontal, appearance.paddingHorizontal) .padding(.vertical, appearance.paddingVertical) + // Its blocks read this screen's look, such as its slider role, not the laptop's. + .environment(\.screenKind, kind) } .modifier(PopupBackground(style: style, glass: bar.glass, backgrounds: backgrounds)) .padding(shadowInset) diff --git a/Tests/StableBarTests/DefaultLayoutTests.swift b/Tests/StableBarTests/DefaultLayoutTests.swift index 7de41aba..f8ff06e4 100644 --- a/Tests/StableBarTests/DefaultLayoutTests.swift +++ b/Tests/StableBarTests/DefaultLayoutTests.swift @@ -467,10 +467,11 @@ func listEntriesDrawInOrderWithTheirSpacing(direction: (property: String, type: } } -@Test @MainActor func hoveringTheSoundWidgetOpensAVolumeSliderOnTheDisplayItIsOn() throws { +@Test(arguments: [false, true]) @MainActor func hoveringTheSoundWidgetOpensAVolumeSliderOnTheDisplayItIsOn(themed: Bool) throws { let store = BarStore(configurationURL: FileManager.default.temporaryDirectory.appending(path: "\(UUID().uuidString).json")) + let roles = themed ? #"{"slider":{"cornerRadius":20,"height":40}}"# : "{}" store.configuration = try decode(Configuration.self, #""" - {"widgets":[{"id":"sound","type":"audio","position":"right"},{"id":"fixed","type":"audio","position":"left"}]} + {"roles":\#(roles),"widgets":[{"id":"sound","type":"audio","position":"right"},{"id":"fixed","type":"audio","position":"left"}]} """#) store.preparePresentations() for (id, json) in [("sound", #"{"text":"62%","icon":"speaker.wave.2","value":0.62,"values":{"volume":0.62}}"#), @@ -520,10 +521,11 @@ func hoverExpansionKeepsControlsOutsideTheLabelThroughoutTheAnimation(controlsBe } } -@Test @MainActor func hoverLayoutsMeasureTheirExpandedWidthOnOnlyTheHoveredDisplay() throws { +@Test(arguments: [false, true]) @MainActor func hoverLayoutsMeasureTheirExpandedWidthOnOnlyTheHoveredDisplay(themed: Bool) throws { let store = BarStore(configurationURL: FileManager.default.temporaryDirectory.appending(path: "\(UUID().uuidString).json")) + let roles = themed ? #"{"slider":{"cornerRadius":20,"height":40}}"# : "{}" store.configuration = try decode(Configuration.self, #""" - {"widgets":[{"id":"timer","type":"text","text":"60m","position":"right", + {"roles":\#(roles),"widgets":[{"id":"timer","type":"text","text":"60m","position":"right", "hoverLayout":{"type":"slider","title":"Minutes","source":"duration","min":15,"max":240,"step":15, "onChange":"set-duration","style":{"width":100,"height":16}}}]} """#) diff --git a/Tests/StableBarTests/FilledSliderTests.swift b/Tests/StableBarTests/FilledSliderTests.swift index bf8e7b00..b6a4fd4f 100644 --- a/Tests/StableBarTests/FilledSliderTests.swift +++ b/Tests/StableBarTests/FilledSliderTests.swift @@ -33,11 +33,13 @@ private func volume(_ slider: String) -> String { } } -@Test func anIconWithoutAFilledSliderNamesItsProblem() throws { +@Test func anIconOnAnExplicitNativeSliderNamesItsProblem() throws { let url = FileManager.default.temporaryDirectory.appending(path: "filled-slider.json") var loader = ConfigurationLoader() - let error = #expect(throws: (any Error).self) { try loader.load(url, data: Data(volume(#""icon":"speaker.fill""#).utf8)) } - #expect(error.map(errorMessage) == #"widgets.sound: popup.layout.icon: Only a filled slider shows an icon; add "filled": true."#) + let error = #expect(throws: (any Error).self) { try loader.load(url, data: Data(volume(#""filled":false,"icon":"speaker.fill""#).utf8)) } + #expect(error.map(errorMessage) == #"widgets.sound: popup.layout.icon: Only a filled slider shows an icon; remove "filled": false to follow the slider role, or set it to true."#) + let automatic = try loader.load(url, data: Data(volume(#""icon":"speaker.fill""#).utf8)) + #expect(automatic.widgets.first?.popup?.layout.sliderIcon == "speaker.fill") } /// A 288-point bar, 40 points tall, over 0–1 in hundredths. diff --git a/Tests/StableBarTests/ModuleConfigurationTests.swift b/Tests/StableBarTests/ModuleConfigurationTests.swift index 7e176ac1..e4a3424a 100644 --- a/Tests/StableBarTests/ModuleConfigurationTests.swift +++ b/Tests/StableBarTests/ModuleConfigurationTests.swift @@ -486,6 +486,21 @@ private func schemaProperties(_ definition: ConfigurationValue?) throws -> Set PopupBlock { + try JSONDecoder().decode(PopupBlock.self, from: Data(#"{"type":"slider","title":"Volume","source":"volume","onChange":"set"\#(properties)}"#.utf8)) +} + +@Test func sliderRolesRespectExplicitChoicesAndOtherwiseFollowTheComposedStyle() throws { + let roles = ["slider": WidgetStyle(background: .color(HexColor(0x112233ff)), height: 40), + "value": WidgetStyle(fontSize: 17)] + let automatic = try sliderBlock() + #expect(automatic.automaticallyFillsSlider(roles: roles)) + #expect(automatic.effectiveRole(roles: roles) == .slider) + #expect(!automatic.automaticallyFillsSlider(roles: [:])) + #expect(!automatic.automaticallyFillsSlider(roles: ["slider": WidgetStyle()])) + #expect(automatic.effectiveRole(roles: [:]) == nil) + #expect(automatic.automaticallyFillsSlider(roles: ["slider": WidgetStyle(cornerRadius: 0)])) + for properties in [#", "filled":false"#, #", "filled":true"#, #", "role":"value""#] { + let explicit = try sliderBlock(properties) + #expect(!explicit.automaticallyFillsSlider(roles: roles)) + let style = explicit.resolvedStyle(inherited: WidgetStyle(), styles: [:], fields: [:], states: StyleStates(), roles: roles) + #expect(style.box.background == nil, "An explicit choice does not acquire the implicit slider role") + } + #expect(try sliderBlock(#", "role":"slider""#).automaticallyFillsSlider(roles: roles)) + let explicit = try sliderBlock(#", "role":"slider", "filled":true"#) + #expect(explicit.resolvedStyle(inherited: WidgetStyle(), styles: [:], fields: [:], states: StyleStates(), roles: roles).box.height == 40) +} + +@Test func automaticSliderStylesPreserveTheCascadeAndSubscribeToModeOnlyWhenUsed() throws { + let roles = ["slider": WidgetStyle(height: 40, states: ["mode.command": WidgetStyle(accent: HexColor(0xff0000ff))])] + let slider = try sliderBlock(#", "style":{"height":32}, "styleSource":"live""#) + let style = slider.resolvedStyle(inherited: WidgetStyle(fontSize: 13), styles: ["live": WidgetStyle(height: 24)], fields: [:], + states: StyleStates(mode: ModePresentation(mode: "tailing", aliases: ["tailing": "command"])), roles: roles) + #expect(style.box.height == 24) + #expect(style.text.fontSize == 13) + #expect(style.text.accent == HexColor(0xff0000ff)) + #expect(slider.usesModeStates(roles: roles)) + #expect(!slider.usesModeStates(roles: [:])) + #expect(try !sliderBlock(#", "filled":false"#).usesModeStates(roles: roles)) + #expect(try !sliderBlock(#", "filled":true"#).usesModeStates(roles: roles)) +} + +@Test @MainActor func sliderRolesComposeThroughIncludesTemplatesProfilesAndScreenLooks() throws { + let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try Data(#"{"roles":{"slider":{"height":40}},"templates":{"control":{"type":"text","text":"Volume","position":"right","hoverLayout":{"type":"slider","title":"Volume","source":"volume","set":"volume"}}}}"#.utf8) + .write(to: directory.appending(path: "base.json")) + let json = #""" + {"includes":["base.json"],"widgets":[{"id":"control","template":"control"},{"id":"sound","type":"audio","position":"left"}], + "profiles":[{"name":"p","configuration":{"roles":{"slider":{"cornerRadius":20}}}}], + "screens":{"monitor":{"roles":{"slider":null}}, + "laptop":{"roles":{"slider":{"states":{"mode.command":{"height":30}}}}}}} + """# + var loader = ConfigurationLoader() + let config = try loader.load(directory.appending(path: "config.json"), data: Data(json.utf8)) + let slider = try #require(config.widgets.first?.hoverLayout) + #expect(config.roleStyle(.slider).height == 40) + #expect(config.roleStyle(.slider).cornerRadius == 20) + #expect(slider.automaticallyFillsSlider(roles: config.roles)) + #expect(config.look(on: .monitor).roleStyle(.slider).height == nil) + #expect(config.look(on: .monitor).roleStyle(.slider).cornerRadius == 20, "Profiles compose after screen look overrides") + let withoutProfile = try loader.load(directory.appending(path: "config.json"), + data: Data(json.replacingOccurrences(of: #""name":"p""#, with: #""name":"p","enabled":false"#).utf8)) + #expect(!slider.automaticallyFillsSlider(roles: withoutProfile.look(on: .monitor).roles)) + #expect(config.needsModeConnection, "A role used only by one screen still subscribes to mode changes") + #expect(config.look(on: .laptop).usesSliderModeStates(config.widgets[1])) + #expect(!config.usesSliderModeStates(config.widgets[1])) +} + +@Test @MainActor func automaticInlineSlidersFitTheirWholeBoxAndTooltipsKeepTheirHeight() throws { + let style = WidgetStyle(paddingVertical: 3, height: 30, paddingTop: 4, paddingBottom: 6) + #expect(style.inlineControlHeight == 20) + #expect(WidgetStyle().inlineControlHeight > 0) + #expect(WidgetStyle(paddingVertical: 4, height: 0).limitingSliderHeight(to: 20).paddingTop == 0) + let slider = try sliderBlock() + let roles = ["slider": WidgetStyle(paddingVertical: 12, height: 40)] + let resolved = slider.resolvedStyle(inherited: WidgetStyle(), styles: [:], fields: [:], states: StyleStates(), roles: roles) + let limited = resolved.limitingSliderHeight(to: style.inlineControlHeight).box + #expect(limited.height == 20) + #expect((limited.paddingTop ?? 0) + (limited.paddingBottom ?? 0) == 19) + let popup = NSHostingView(rootView: PopupBlockView(block: slider, inheritedStyle: WidgetStyle(), fields: [:], + context: BlockContext(roles: roles, fillsWidth: false, open: { _ in }, runAction: { _, _ in })).frame(width: 100)) + let inline = NSHostingView(rootView: PopupBlockView(block: slider, inheritedStyle: WidgetStyle(), fields: [:], + context: BlockContext(roles: roles, inlineControlHeight: 20, fillsWidth: false, open: { _ in }, runAction: { _, _ in })).frame(width: 100)) + #expect(popup.fittingSize.height == 40) + #expect(inline.fittingSize.height == 20) + let nested = try JSONDecoder().decode(PopupBlock.self, from: Data(#"{"type":"row","style":{"paddingVertical":3},"children":[{"type":"slider","title":"Volume","source":"volume","set":"volume"}]}"#.utf8)) + let wrapper = NSHostingView(rootView: PopupBlockView(block: nested, inheritedStyle: WidgetStyle(), fields: [:], + context: BlockContext(roles: roles, inlineControlHeight: 20, fillsWidth: false, open: { _ in }, runAction: { _, _ in })).frame(width: 100)) + #expect(wrapper.fittingSize.height == 20, "A padded wrapper shares the inline height budget") + let overflowing = try JSONDecoder().decode(PopupBlock.self, from: Data(#"{"type":"row","style":{"paddingVertical":-3},"children":[{"type":"slider","title":"Volume","source":"volume","set":"volume"}]}"#.utf8)) + let negative = NSHostingView(rootView: PopupBlockView(block: overflowing, inheritedStyle: WidgetStyle(), fields: [:], + context: BlockContext(roles: roles, inlineControlHeight: 20, fillsWidth: false, open: { _ in }, runAction: { _, _ in })).frame(width: 100)) + #expect(negative.fittingSize.height == 14, "Negative padding doesn't let the inline slider grow past the widget") +} + +@MainActor @Observable private final class SliderInteraction { + var value = 0.2 + var sent: [Double] = [] + var editing = false + var disabled = false +} + +@Test(arguments: [false, true]) @MainActor +func filledSlidersDeliverContinuouslyOnlyWhenRequested(continuous: Bool) async throws { + let state = SliderInteraction() + struct Control: View { + let state: SliderInteraction + let continuous: Bool + var body: some View { + FilledSlider(title: "Volume", value: state.value, minimum: 0, maximum: 1, step: 0.1, endStop: nil, icon: nil, + height: 20, drawsTrack: true, appearance: WidgetAppearance(WidgetStyle(), defaults: WidgetStyle()), + continuous: continuous) { + state.sent.append($0) + state.value = $0 + } + .disabled(state.disabled) + .onPreferenceChange(ControlEditingPreference.self) { state.editing = $0 } + .frame(width: 100, height: 20) + } + } + let host = NSHostingView(rootView: Control(state: state, continuous: continuous)) + _ = NSApplication.shared + let window = NSWindow(contentRect: CGRect(x: 0, y: 0, width: 100, height: 20), styleMask: [.borderless], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.alphaValue = 0 + window.contentView = host + window.orderFrontRegardless() + defer { window.close() } + func poll(_ condition: () -> Bool) async -> Bool { + for _ in 0..<100 { + host.layoutSubtreeIfNeeded() + if condition() { return true } + await Task.yield() + } + return false + } + func send(_ type: NSEvent.EventType, x: Double) throws { + let event = try #require(NSEvent.mouseEvent(with: type, location: CGPoint(x: x, y: 10), modifierFlags: [], timestamp: 0, + windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)) + window.sendEvent(event) + } + try #require(await poll { window.isVisible && host.hitTest(CGPoint(x: 26, y: 10)) != nil }) + try send(.leftMouseDown, x: 26) + try send(.leftMouseDragged, x: 70) + try #require(await poll { state.editing }) + #expect(continuous ? !state.sent.isEmpty : state.sent.isEmpty) + try send(.leftMouseUp, x: 70) + try #require(await poll { !state.editing }) + #expect(state.sent.count == 1, "The final event does not duplicate a continuous update") + #expect(abs((state.sent.last ?? 0) - 0.8) < 1e-9) + let sent = state.sent.count + try send(.leftMouseDown, x: 70) + try send(.leftMouseDragged, x: 40) + try #require(await poll { state.editing }) + state.disabled = true + try #require(await poll { !state.editing }) + #expect(continuous ? state.sent.count > sent : state.sent.count == sent) +} diff --git a/docs/create-a-widget.md b/docs/create-a-widget.md index b1171c5d..99dd58d1 100644 --- a/docs/create-a-widget.md +++ b/docs/create-a-widget.md @@ -192,6 +192,8 @@ With `bar.inlineHoverControls` (**Open hover controls inline** in **Settings → } ``` +Sound’s built-in hover slider and sliders in `hoverLayout` follow the [slider presentation role](styling.md#presentation-roles-and-workspace-defaults). A themed inline slider fits the widget’s content height. + Provide the current slider value in script output `values.duration`; `onChange` receives `VALUE` when the drag ends. Control labels are hidden, with their titles kept for accessibility. Set a width on sliders to give them space. Add `"endStop": { "value": 0, "label": "∞" }` for one more stop past `max`, set apart by a notch: dragging past 240 snaps the knob onto it, and `onChange` receives `0` (see [`slider`](popups.md)). A widget with `hoverLayout` runs its `onClick` command when clicked, even when it also has a popup. Without `onClick`, clicking still opens its popup. Tooltips stay hidden while hover controls are available. Add or edit `hoverLayout` through the widget's **Edit as JSON…** action or the CLI; includes, templates, profiles, and package overrides merge it like `layout`. Set it to `null` to remove it. diff --git a/docs/popups.md b/docs/popups.md index 862402e2..e63a30e2 100644 --- a/docs/popups.md +++ b/docs/popups.md @@ -54,7 +54,7 @@ Layout blocks: | `graph` | `height` | The widget's existing 60 samples on the 0–1 scale, the newest at the right edge; optional `source` reads `series[source]` instead and `lineWidth` sets stroke width | | `list` | `source`, `row` | Repeat the `row` block for each object in `lists[source]`, in source order. `orientation` is `vertical` by default (also when null); set `"orientation": "horizontal"` to place entries side by side. `style.spacing` separates entries in either direction. Horizontal lists in popups scroll when their entries exceed the available width; `maxHeight` scrolls a vertical list past that height in points, as a chat does: it opens at its end, follows what grows there until you scroll away, and brings a new entry into view. | | `button` | `title`, `onClick` | Run a command and close the popup | -| `slider` | `title`, `source`, `onChange` or `set` | Native slider; reads `values[source]` or numeric `fields[source]`. `min`, `max`, `step` default to 0, 1, 0.01. `endStop` adds one more stop past `max`, set apart by a notch, such as `{ "value": 0, "label": "∞" }` for a timer that can also run without end. Dragging past `max` holds the knob there, then snaps it onto the end stop, which sends its `value`; the arrow keys and VoiceOver reach it too. The label shows under the end stop, and a `source` equal to its value puts the knob there, so the value must be outside `min`…`max`. `"filled": true` draws a bar in the block's style instead of macOS's slider: its `background` is the track, or a faint one without it, `accent` fills it from the leading edge, `cornerRadius` rounds both, and `height` sets its height, 28 by default. `icon` names an SF Symbol drawn on the fill at its leading end in `accentText`; the fill is never narrower than the bar is tall, so the symbol stays on it. A filled slider asks for twice its height in width, and with an end stop three times its height plus 14 points; given less, such as a narrower `width`, the start of the fill narrows so every step still shows. Click or drag anywhere on the bar to set the value. With an `endStop`, the steps end at a notch before the end stop, whose label sits on the bar, and choosing the end stop fills the whole bar. VoiceOver reads its `title`, which it doesn't show. | +| `slider` | `title`, `source`, `onChange` or `set` | Slider; reads `values[source]` or numeric `fields[source]`. `min`, `max`, `step` default to 0, 1, 0.01. `endStop` adds one more stop past `max`, set apart by a notch, such as `{ "value": 0, "label": "∞" }` for a timer that can also run without end. Dragging past `max` holds the knob there, then snaps it onto the end stop, which sends its `value`; the arrow keys and VoiceOver reach it too. The label shows under the end stop, and a `source` equal to its value puts the knob there, so the value must be outside `min`…`max`. `"filled": true` draws a bar in the block's style instead of macOS's slider: its `background` is the track, or a faint one without it, `accent` fills it from the leading edge, `cornerRadius` rounds both, and `height` sets its height, 28 by default. `icon` names an SF Symbol drawn on the fill at its leading end in `accentText`; the fill is never narrower than the bar is tall, so the symbol stays on it. A filled slider asks for twice its height in width, and with an end stop three times its height plus 14 points; given less, such as a narrower `width`, the start of the fill narrows so every step still shows. Click or drag anywhere on the bar to set the value. With an `endStop`, the steps end at a notch before the end stop, whose label sits on the bar, and choosing the end stop fills the whole bar. VoiceOver reads its `title`, which it doesn't show. | | `toggle` | `title`, `source`, `onChange` or `set` | Native toggle; true for `"true"`/`"1"` in fields or 1 in values. | | `segmented` | `title`, `source`, `options`, `onChange` | Native segmented picker. Options are `{ "title": "Label", "value": "id" }`; selection reads `fields[source]`. | | `chooser` | `title`, `source`, `groupsSource`, `optionsSource`, `onChange` | A pill naming the chosen group, option and level, which opens a panel to change them, as AI apps choose a model. The panel lists the rows of `lists[groupsSource]` (`value`, `title`, and optionally `icon`, `detail`, `option`, `level` and `levelsTitle`). Beside them it shows the chosen group's options, the rows of `lists[optionsSource]` whose `group` names it (`value`, `title`, optional `detail`), and a bar of its levels from `levelsSource`, whose rows have `group`, `value` and `title`. `fields[source]` is the chosen group, and each group row's `option` and `level` are its current choices. A choice shows at once and runs `onChange` with the group in `VALUE`, the option in `OPTION` and the level in `LEVEL`. With `starsSource` and `onStar`, a star beside each option saves it with its group's current level as a preset: the rows of `lists[starsSource]` (`group`, `option`, `level`) show under **Starred** above the panel's groups, and as chips in place of the pill with the chosen one highlighted. Click a chip or press ⌘1 to ⌘9 to choose one; clicking the chosen one opens the panel. Starring or unstarring runs `onStar` with the preset in `VALUE`, `OPTION` and `LEVEL`, and `STARRED` set to `true` or `false`. | @@ -69,6 +69,13 @@ Layout blocks: | `equalizer` | — | Four bars that bounce in the text color while `source` is on, for `"true"`/`"1"` in fields or 1 in values, and settle low when it's off; without `source` they always bounce. `height` defaults to 12. Reduce Motion keeps them still. | | `battery` | — | A battery like the one in the macOS menu bar, sized by `style.iconSize` and drawn in the text color. Its fill shows `values[source]`, or a 0–1 number in `fields[source]`; `source` defaults to `percent`. A `state` field of `charging` adds a bolt and `charged` a plug, and a `health` field of `service` adds an orange badge. On battery power the fill turns red at 10 % or less. | +Sliders without `filled` follow a nonempty [`slider` presentation role](styling.md#presentation-roles-and-workspace-defaults), +unless they name another role. Set `filled` to false for the native control or true for an +explicitly filled bar. An `icon` is allowed when `filled` is true or omitted, and is visible only +when the slider draws filled. Automatically themed sliders fit the widget's content height +inline; popup and tooltip sliders use their styled height, 28 points by default. + + Every block accepts `style` and `alignment` (`leading`, `center`, `trailing`). Fonts, text color, accent and spacing inherit from the containing block. Width, padding, background, hover background and border apply only when set on that block. Set a width on numeric fields and their headings to align columns. Blocks without a width use the available space. `minWidth` and `maxWidth` limit a block that has no fixed `width`: in the bar it takes its content's width within them, and in a popup the available space up to `maxWidth`. Set `"fitWidth": true` to give a block in a popup its content's width too, up to `maxWidth`, placed by its `alignment`, as a chat bubble. Text and field blocks can set `"shimmer": true` to sweep light across their text, as while something works; pair it with `hideWhenEmpty` to show it only then. Reduce Motion keeps it still. Text and field blocks can set `scrollSpeed` in points per second with a fixed `style.width`, or with a `style.maxWidth` so that text that fits takes only its own width instead of leaving a gap after it. Overflow scrolls back and forth with a pause at each end; fitting text and Reduce Motion do not scroll. `hideWhenEmpty` names a field: the block occupies no space when that field is absent or empty, which is useful for optional list-row headings and pipeline details. diff --git a/docs/styling.md b/docs/styling.md index a366bba1..2c306446 100644 --- a/docs/styling.md +++ b/docs/styling.md @@ -63,7 +63,7 @@ An unmapped non-main mode activates only `mode`. Aliases start with a letter and ## Presentation roles and workspace defaults -`role` is an explicit annotation on a widget or any layout/popup block. The allowed names are `time`, `primary`, `secondary`, `key`, `value`, `heading`, `button`, `meter` and `separator`; unknown names are errors. Nothing selects widgets by type or ID. In particular, two `clock` widgets can use `time` and `secondary` independently. Omitting a role keeps the existing style; Built-in supplies an empty fallback for each role. +`role` is an explicit annotation on a widget or any layout/popup block. The allowed names are `time`, `primary`, `secondary`, `key`, `value`, `heading`, `button`, `meter`, `separator` and `slider`; unknown names are errors. Sliders have the default role described below; other blocks and widgets are not selected by type or ID. In particular, two `clock` widgets can use `time` and `secondary` independently. Built-in supplies an empty fallback for each role. ```json { @@ -83,6 +83,21 @@ An unmapped non-main mode activates only `mode`. Aliases start with a letter and A selected theme can style any subset of roles. Configuration files, includes and profiles can override those styles. Widget packages (including command-capable packages) may annotate widgets and blocks, but cannot define global `roles`, `workspaceDefaults` or `modeAliases`. Role styles accept only style properties: they cannot change actions, providers, visibility, display filters or the row/column structure of a layout. +A slider without `filled` or an explicit role follows `roles.slider` when that role sets a style +property. It then draws as a filled bar, with `background` as its track and `accent` as its fill. +An empty or missing role keeps macOS's slider; `"roles": { "slider": null }` clears a theme's +slider style. `"filled": false` always keeps the native control. `"filled": true` always draws +filled in the block's own style and takes a role only when explicitly assigned. An explicit +role other than `slider` also keeps the native control when `filled` is omitted. + +This applies to popup sliders, hover layouts and Sound's built-in hover control. Automatically +styled sliders fit the widget's content height inline, or a line of text when it has no fixed +height. Popups and hover tooltips use the role's height, 28 points by default. Existing explicit +filled sliders keep their configured sizing. + +[Themed sliders](../examples/themed-sliders.json) styles Sound's popup and built-in hover control +without adding `filled` or an explicit role to either slider. + Layers apply from lowest to highest: | Element | Base layers | diff --git a/docs/themes.md b/docs/themes.md index fdd67b0e..bdb09e1b 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -95,6 +95,12 @@ Popups inherit `popupDefaults` and then `defaults`, except padding and spacing, A reference to a token that no layer defines is an error. Built-in defines all of these, so your own widgets can use them under any theme. Their names are reserved for colors: Built-in's `defaults` use `text`, `surface`, `surfaceRaised` and `accent`, so a token of yours with one of these names replaces the theme's color and must be a color. A widget package should still define fallback values for the shared tokens it uses, so it passes review on its own; Built-in and any other theme replace them. StableBar also rejects references nested more than 64 levels deep, references whose expansion is too large, and references that need more tracking than StableBar allows. +A theme can style sliders in popups, hover controls and the built-in Sound widget through +`roles.slider`. A nonempty style makes plain sliders filled bars; an empty role leaves the +native control. Widgets can opt out with `"filled": false` or keep an explicit filled style +with `"filled": true`. See [presentation roles](styling.md#presentation-roles-and-workspace-defaults). +Widget layouts and their Display choices remain part of the widget configuration. + ## Liquid Glass `bar.glass` is experimental. It draws backgrounds as native Liquid Glass, the material of the macOS 26 Dock, on top of any theme: diff --git a/examples/themed-sliders.json b/examples/themed-sliders.json new file mode 100644 index 00000000..7f2d4d0f --- /dev/null +++ b/examples/themed-sliders.json @@ -0,0 +1,27 @@ +{ + "$schema": "../stablebar.schema.json", + "roles": { + "slider": { + "height": 40, + "cornerRadius": 20, + "background": "@token.surfaceRaised" + } + }, + "widgets": [ + { + "id": "sound", + "type": "audio", + "position": "right", + "popup": { + "style": { "width": 280 }, + "layout": { + "type": "slider", + "title": "Volume", + "source": "volume", + "set": "volume", + "icon": "speaker.wave.2.fill" + } + } + } + ] +} diff --git a/scenes/themed-slider-inline.json b/scenes/themed-slider-inline.json new file mode 100644 index 00000000..0df6d070 --- /dev/null +++ b/scenes/themed-slider-inline.json @@ -0,0 +1,45 @@ +{ + "$schema": "../scene.schema.json", + "configuration": { + "bar": {"height": 40}, + "defaults": {"height": 28, "paddingVertical": 4}, + "roles": {"slider": {"height": 40, "cornerRadius": 20, "background": "@token.track"}}, + "widgets": [ + { + "id": "auto", + "type": "script", + "command": "true", + "position": "left", + "layout": {"type": "slider", "title": "Volume", "source": "volume", "onChange": "true", "style": {"width": 120}} + }, + { + "id": "native", + "type": "script", + "command": "true", + "position": "left", + "layout": {"type": "slider", "title": "Volume", "source": "volume", "onChange": "true", "filled": false, "style": {"width": 120}} + }, + { + "id": "explicit", + "type": "script", + "command": "true", + "position": "left", + "layout": { + "type": "slider", + "title": "Volume", + "source": "volume", + "onChange": "true", + "filled": true, + "style": {"width": 120, "height": 20, "cornerRadius": 10} + } + } + ] + }, + "outputs": { + "auto": {"text": "", "values": {"volume": 0.62}}, + "native": {"text": "", "values": {"volume": 0.62}}, + "explicit": {"text": "", "values": {"volume": 0.62}} + }, + "draw": "bar", + "width": 640 +} diff --git a/scenes/themed-slider-popup.json b/scenes/themed-slider-popup.json new file mode 100644 index 00000000..e634b4b7 --- /dev/null +++ b/scenes/themed-slider-popup.json @@ -0,0 +1,49 @@ +{ + "$schema": "../scene.schema.json", + "configuration": { + "roles": {"slider": {"height": 40, "cornerRadius": 20, "background": "@token.surfaceRaised", "accent": "@token.accent"}}, + "widgets": [ + { + "id": "sliders", + "type": "script", + "command": "true", + "position": "right", + "popup": { + "style": {"width": 340}, + "layout": { + "type": "column", + "children": [ + {"type": "text", "text": "Theme slider role", "role": "heading"}, + {"type": "slider", "title": "Volume", "source": "volume", "onChange": "true", "icon": "speaker.wave.2.fill"}, + {"type": "text", "text": "Native opt-out", "role": "key"}, + {"type": "slider", "title": "Volume", "source": "volume", "onChange": "true", "filled": false}, + {"type": "text", "text": "Explicit filled style", "role": "key"}, + { + "type": "slider", + "title": "Volume", + "source": "volume", + "onChange": "true", + "filled": true, + "style": {"height": 24, "cornerRadius": 4, "accent": "#5285ac"} + }, + {"type": "text", "text": "End stop", "role": "key"}, + { + "type": "slider", + "title": "Minutes", + "source": "minutes", + "min": 15, + "max": 240, + "step": 15, + "endStop": {"value": 0, "label": "∞"}, + "onChange": "true" + } + ] + } + } + } + ] + }, + "outputs": {"sliders": {"text": "Sliders", "values": {"volume": 0.62, "minutes": 0}}}, + "draw": "popup", + "widget": "sliders" +} diff --git a/stablebar.schema.json b/stablebar.schema.json index f3facd75..9d4153a4 100644 --- a/stablebar.schema.json +++ b/stablebar.schema.json @@ -126,6 +126,13 @@ "type": "null" } ] + }, + "slider": { + "anyOf": [ + { "$ref": "#/definitions/style" }, + { "$ref": "#/definitions/reference" }, + { "type": "null" } + ] } } }, @@ -971,7 +978,7 @@ "type": "object", "additionalProperties": false, "properties": { - "role": {"anyOf": [{"enum": ["time", "primary", "secondary", "key", "value", "heading", "button", "meter", "separator"]}, {"$ref": "#/definitions/reference"}, {"type": "null"}]}, + "role": {"anyOf": [{"enum": ["time", "primary", "secondary", "key", "value", "heading", "button", "meter", "separator", "slider"]}, {"$ref": "#/definitions/reference"}, {"type": "null"}]}, "type": { "anyOf": [ { @@ -1189,11 +1196,11 @@ }, "filled": { "$ref": "#/definitions/boolean", - "description": "For sliders: draw a bar in the block's style instead of macOS's slider. The background is the track, the accent fills it, and clicking or dragging anywhere sets the value. An endStop sits past a notch at the end and fills the whole bar." + "description": "For sliders: true draws a filled bar in the block's own style; false keeps macOS's slider. Omit to follow a nonempty slider role, unless another role is assigned. The background is the track and accent is the fill. Automatically themed sliders fit the widget's content height inline; popups and tooltips default to 28 points. An endStop follows a notch and fills the whole bar." }, "icon": { "$ref": "#/definitions/string", - "description": "For filled sliders: an SF Symbol drawn on the fill at its leading end, in accentText." + "description": "For sliders: an SF Symbol drawn on the fill at its leading end, in accentText. Allowed when filled is true or omitted; hidden when the slider draws natively." }, "options": { "type": "array", @@ -1542,7 +1549,7 @@ "description": "Clock time zone identifier. Omit to follow the Mac.", "$ref": "#/definitions/string" }, - "role": {"anyOf": [{"enum": ["time", "primary", "secondary", "key", "value", "heading", "button", "meter", "separator"]}, {"$ref": "#/definitions/reference"}, {"type": "null"}]}, + "role": {"anyOf": [{"enum": ["time", "primary", "secondary", "key", "value", "heading", "button", "meter", "separator", "slider"]}, {"$ref": "#/definitions/reference"}, {"type": "null"}]}, "id": { "$ref": "#/definitions/string", "description": "Stable, unique widget identifier." @@ -2085,7 +2092,7 @@ } ] }, - "role": {"anyOf": [{"enum": ["time", "primary", "secondary", "key", "value", "heading", "button", "meter", "separator"]}, {"$ref": "#/definitions/reference"}, {"type": "null"}]}, + "role": {"anyOf": [{"enum": ["time", "primary", "secondary", "key", "value", "heading", "button", "meter", "separator", "slider"]}, {"$ref": "#/definitions/reference"}, {"type": "null"}]}, "id": { "type": "string", "description": "A widget ID, such as one a package fixes."