diff --git a/Tests/StackNudgePanelCoreTests/SettingsChoicesTests.swift b/Tests/StackNudgePanelCoreTests/SettingsChoicesTests.swift new file mode 100644 index 0000000..1c71e8b --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/SettingsChoicesTests.swift @@ -0,0 +1,51 @@ +import XCTest + +@testable import StackNudgePanelCore + +// A list row's click menu and its arrow keys read one list. These never pick: +// picking writes the user's real ~/.stack-nudge/config. +@MainActor +final class SettingsChoicesTests: XCTestCase { + + private static let listRows: [SettingsRow] = [ + .muteDuration, .remindUnanswered, .stalledSessions, .widgetCorner, .widgetOpacity, + .widgetContent, .mascot, .theme, .agentDoneSound, .permissionSound, .alertThreshold, + .pollFrequency, .contextAlert, .slackIdle, .historyPerSession, + ] + + func testEveryListRowOffersItsOptionsWithTheCurrentOneTicked() { + let nav = PanelNav() + for row in Self.listRows { + guard let choices = nav.choices(for: row) else { return XCTFail("\(row) has no options") } + XCTAssertGreaterThan(choices.labels.count, 1, "\(row)") + XCTAssertNotNil(choices.current, "\(row): the default value isn't one of its options") + } + } + + func testLabelsReadAsTheRowShowsThem() { + let nav = PanelNav() + XCTAssertEqual(nav.choices(for: .theme)?.labels, AccentTheme.allCases.map(\.label)) + XCTAssertEqual(nav.choices(for: .widgetOpacity)?.labels.last, "100%") + XCTAssertEqual(nav.choices(for: .contextAlert)?.labels.first, "Off") + } + + // Toggles, actions, hotkey recorders and ranges are not lists. + func testOnlyListRowsHaveOptions() { + let nav = PanelNav() + for row: SettingsRow in [.banner, .hotkey, .voiceSpeed, .piApiBudget, .openConfig, .quit] { + XCTAssertNil(nav.choices(for: row), "\(row)") + } + } + + // Stepping is what the arrows do: wrap at either end, start from the + // fallback when the current value is foreign. + func testSteppingWrapsAndStartsFromTheFallback() { + var picked: [Int] = [] + let choices = SettingChoices(labels: ["a", "b", "c"], current: 2, fallback: 0) { picked.append($0) } + choices.step(forward: true) + choices.step(forward: false) + let foreign = SettingChoices(labels: ["a", "b", "c"], current: nil, fallback: 1) { picked.append($0) } + foreign.step(forward: true) + XCTAssertEqual(picked, [0, 1, 2]) + } +} diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 20acf09..4415b08 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -2534,7 +2534,15 @@ final class PanelNav: ObservableObject { } private func applyCycle(forward: Bool) { + // List rows step through the same options their click menu offers. + if let row = selectedRow, let choices = choices(for: row) { + choices.step(forward: forward) + return + } switch selectedRow { + case .muteDuration, .remindUnanswered, .stalledSessions, .widgetCorner, .widgetOpacity, .widgetContent, .mascot, .theme, .agentDoneSound, .permissionSound, .voice, .alertThreshold, .pollFrequency, .contextAlert, .slackIdle, .historyPerSession, .updateChannel: + // A list row whose options aren't available (voices still loading). + break case .banner: bannerEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_BANNER", value: bannerEnabled ? "true" : "false") @@ -2550,27 +2558,6 @@ final class PanelNav: ObservableObject { // menu-bar badge (muteFor / resumeNotifications). Uses the current // default duration, same as the header bell and the M shortcut. if isMuted { actions?.resumeNotifications() } else { actions?.muteFor(muteDurationMinutes) } - case .muteDuration: - let list = Self.muteDurationOptions - let idx = list.firstIndex(of: muteDurationMinutes) ?? 1 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - muteDurationMinutes = list[next] - ConfigFile.write(key: "STACKNUDGE_MUTE_DURATION_MIN", value: String(muteDurationMinutes)) - case .remindUnanswered: - let list = AttentionPolicy.reminderMinuteOptions - let idx = list.firstIndex(of: remindMinutes) ?? 0 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - remindMinutes = list[next] - ConfigFile.write(key: "STACKNUDGE_REMIND_MIN", value: String(remindMinutes)) - case .stalledSessions: - let list = AttentionPolicy.stalledMinuteOptions - let idx = list.firstIndex(of: stalledMinutes) ?? 0 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - stalledMinutes = list[next] - ConfigFile.write(key: "STACKNUDGE_STALLED_MIN", value: String(stalledMinutes)) - // Clearing the threshold must clear the flags too — nothing else - // recomputes them once the tick stops evaluating. - if stalledMinutes == 0 { stalledSessionKeys = [] } case .pinPanel: panelPinned.toggle() ConfigFile.write(key: "STACKNUDGE_PANEL_PIN", value: panelPinned ? "true" : "false") @@ -2606,30 +2593,6 @@ final class PanelNav: ObservableObject { compactSnap.toggle() ConfigFile.write(key: "STACKNUDGE_COMPACT_SNAP", value: compactSnap ? "true" : "false") - case .widgetCorner: - let list = CompactCorner.allCases - let idx = list.firstIndex(of: compactCorner) ?? 0 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - compactCorner = list[next] - ConfigFile.write(key: "STACKNUDGE_COMPACT_CORNER", value: compactCorner.rawValue) - case .widgetOpacity: - let list = Self.compactAlphaOptions - let idx = list.firstIndex(of: compactAlpha) ?? (list.count - 1) - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - compactAlpha = list[next] - ConfigFile.write(key: "STACKNUDGE_COMPACT_ALPHA", value: String(format: "%.2f", compactAlpha)) - case .widgetContent: - let list = CompactContent.allCases - let idx = list.firstIndex(of: compactContent) ?? 0 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - compactContent = list[next] - ConfigFile.write(key: "STACKNUDGE_COMPACT_CONTENT", value: compactContent.rawValue) - case .mascot: - let list = MascotKind.allCases - let idx = list.firstIndex(of: mascot) ?? 0 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - mascot = list[next] - ConfigFile.write(key: "STACKNUDGE_MASCOT", value: mascot.rawValue) case .companionBadge: companionBadge.toggle() ConfigFile.write(key: "STACKNUDGE_COMPANION_BADGE", value: companionBadge ? "true" : "false") @@ -2642,29 +2605,12 @@ final class PanelNav: ObservableObject { let idx = list.firstIndex(of: companionSize) ?? 0 let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count setCompanionSize(list[next]) - case .theme: - let list = AccentTheme.allCases - let idx = list.firstIndex(of: theme) ?? 0 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - theme = list[next] - ConfigFile.write(key: "STACKNUDGE_THEME", value: theme.rawValue) case .soundEnabled: soundEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_SOUND", value: soundEnabled ? "true" : "false") - case .agentDoneSound: - soundStop = step(soundStop, in: Self.macSounds, forward: forward, key: "STACKNUDGE_SOUND_STOP", preview: true) - case .permissionSound: - soundPermission = step(soundPermission, in: Self.macSounds, forward: forward, key: "STACKNUDGE_SOUND_PERMISSION", preview: true) case .voiceEnabled: voiceEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_VOICE", value: voiceEnabled ? "true" : "false") - case .voice: - // Only reachable when the model is cached (otherwise the row is - // .downloadVoiceModel), so there's no download branch here. - guard !voicesLoading, !voicesAvailable.isEmpty else { return } - voice = step(voice, in: voicesAvailable, forward: forward, key: "STACKNUDGE_VOICE_NAME", preview: false) - let phrase = Self.voicePreviewPhrases.randomElement() ?? "Hello." - Speaker.speak(phrase, voice: voice, speed: String(format: "%.2f", voiceSpeed)) case .voiceSpeed: let next = forward ? voiceSpeed + Self.speedStep : voiceSpeed - Self.speedStep voiceSpeed = max(Self.speedMin, min(Self.speedMax, (next * 100).rounded() / 100)) @@ -2674,12 +2620,6 @@ final class PanelNav: ObservableObject { case .quotaAlerts: quotaAlertsEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_QUOTA_ALERTS", value: quotaAlertsEnabled ? "true" : "false") - case .alertThreshold: - let list = Self.quotaThresholds - let idx = list.firstIndex(of: quotaAlertThreshold) ?? 2 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - quotaAlertThreshold = list[next] - ConfigFile.write(key: "STACKNUDGE_QUOTA_THRESHOLD", value: String(quotaAlertThreshold)) case .piApiBudget: setPiBudget(apiDaily: Self.stepBudget(piApiBudgetDaily, forward: forward), localDaily: piLocalBudgetDaily) @@ -2688,18 +2628,6 @@ final class PanelNav: ObservableObject { setPiBudget(apiDaily: piApiBudgetDaily, localDaily: Self.stepBudget(piLocalBudgetDaily, forward: forward)) ConfigFile.write(key: "STACKNUDGE_PI_LOCAL_BUDGET", value: String(piLocalBudgetDaily)) - case .pollFrequency: - let list = Self.quotaPollMinuteOptions - let idx = list.firstIndex(of: quotaPollMinutes) ?? 2 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - quotaPollMinutes = list[next] - ConfigFile.write(key: "STACKNUDGE_USAGE_POLL_MIN", value: String(quotaPollMinutes)) - case .contextAlert: - let list = Self.contextAlertThresholdOptions - let idx = list.firstIndex(of: contextAlertThresholdK) ?? 0 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - contextAlertThresholdK = list[next] - ConfigFile.write(key: "STACKNUDGE_CONTEXT_ALERT_THRESHOLD", value: String(contextAlertThresholdK)) case .showRemaining: quotaShowRemaining.toggle() ConfigFile.write(key: "STACKNUDGE_QUOTA_SHOW_REMAINING", value: quotaShowRemaining ? "true" : "false") @@ -2717,12 +2645,6 @@ final class PanelNav: ObservableObject { case .slackEnabled: slackEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_SLACK", value: slackEnabled ? "true" : "false") - case .slackIdle: - let list = SlackDelivery.idleMinuteOptions - let idx = list.firstIndex(of: slackIdleMinutes) ?? 1 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - slackIdleMinutes = list[next] - ConfigFile.write(key: "STACKNUDGE_SLACK_IDLE_MIN", value: String(slackIdleMinutes)) case .slackDetail: slackIncludeDetail.toggle() ConfigFile.write(key: "STACKNUDGE_SLACK_DETAIL", @@ -2736,14 +2658,6 @@ final class PanelNav: ObservableObject { ConfigFile.write(key: "STACKNUDGE_EVENT_HISTORY", value: eventHistoryEnabled ? "true" : "false") actions?.applyEventHistorySetting() - case .historyPerSession: - let list = Self.eventsPerSessionOptions - let idx = list.firstIndex(of: eventsPerSession) ?? 1 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - eventsPerSession = list[next] - ConfigFile.write(key: "STACKNUDGE_EVENTS_PER_SESSION", value: String(eventsPerSession)) - case .updateChannel: - setUpdateChannel(updateChannel == .stable ? .nightly : .stable) case .mcpWrites: mcpWritesEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_MCP_WRITES", value: mcpWritesEnabled ? "true" : "false") @@ -2935,16 +2849,6 @@ final class PanelNav: ObservableObject { onExtensionConfigChanged(id) } - private func step(_ current: String, in list: [String], forward: Bool, key: String, preview: Bool) -> String { - guard !list.isEmpty else { return current } - let idx = list.firstIndex(of: current) ?? 0 - let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count - let value = list[next] - ConfigFile.write(key: key, value: value) - if preview { NSSound(named: NSSound.Name(value))?.play() } - return value - } - // MARK: - Hotkey recording func startRecordingHotkey() { diff --git a/panel/Settings.swift b/panel/Settings.swift index b367b80..bdffff7 100644 --- a/panel/Settings.swift +++ b/panel/Settings.swift @@ -1228,15 +1228,29 @@ struct SettingsView: View { .id(nav.index(of: id)) .onTapGesture { nav.selectedSettingIndex = nav.index(of: id) - // For actions, single-click is enough. For toggles/cycles a click - // on the row also acts so mouse users don't have to keyboard. The - // mute row acts in place too, so it clicks like an action. - // Remove is the exception: ⏎ never removes, but a click on the - // row is as deliberate as the old page's Remove button was. + // Every row acts on a click, so the mouse needs no keyboard: an + // action runs, a toggle flips, and a list row opens its options to + // pick from. A dimmed value row is gated off by another setting, so + // a click leaves it alone. + // Remove is the exception among actions: ⏎ never removes, but a + // click on the row is as deliberate as the old page's Remove + // button was. if case .extensionRemove(let extensionID) = id { nav.onRemoveExtension(extensionID) - } else if kind == .action || kind == .toggle || kind == .mute || kind == .destructive { + return + } + switch kind { + case .action, .toggle, .mute, .destructive: nav.activate() + case .cycle where enabled: + if let choices = nav.choices(for: id) { + SettingChoicesMenu.show(choices) + } else if id == .hotkey || id == .speakHotkey { + nav.activate() // records a new combo, as ⏎ does + } + // A range (voice speed, pi budgets) keeps its arrows. + case .cycle: + break } } } diff --git a/panel/SettingsChoices.swift b/panel/SettingsChoices.swift new file mode 100644 index 0000000..eb20a2e --- /dev/null +++ b/panel/SettingsChoices.swift @@ -0,0 +1,162 @@ +import AppKit + +// The options of a value row, in one place for both ways of changing it: the +// arrow keys step through them, and a click opens them as a menu to pick from. +// A row with ten options is one click away from any of them, not ten. +struct SettingChoices { + let labels: [String] + // Index of the current value; nil when it isn't one of the options + // (a hand-edited config), in which case nothing is ticked. + let current: Int? + // Where an arrow starts from when the current value isn't in the list. + let fallback: Int + let pick: (Int) -> Void + + func step(forward: Bool) { + guard !labels.isEmpty else { return } + let idx = current ?? fallback + pick(forward ? (idx + 1) % labels.count : (idx - 1 + labels.count) % labels.count) + } +} + +extension PanelNav { + + // nil for rows that aren't a list: toggles, actions, the hotkey recorders, + // and the ranges (voice speed, pi budgets), which keep stepping by arrow. + func choices(for row: SettingsRow) -> SettingChoices? { + switch row { + case .muteDuration: + return list(Self.muteDurationOptions, current: muteDurationMinutes, fallback: 1, label: { "\($0) min" }) { + self.muteDurationMinutes = $0 + ConfigFile.write(key: "STACKNUDGE_MUTE_DURATION_MIN", value: String($0)) + } + case .remindUnanswered: + return list(AttentionPolicy.reminderMinuteOptions, current: remindMinutes, label: AttentionPolicy.minuteLabel) { + self.remindMinutes = $0 + ConfigFile.write(key: "STACKNUDGE_REMIND_MIN", value: String($0)) + } + case .stalledSessions: + return list(AttentionPolicy.stalledMinuteOptions, current: stalledMinutes, label: AttentionPolicy.minuteLabel) { + self.stalledMinutes = $0 + ConfigFile.write(key: "STACKNUDGE_STALLED_MIN", value: String($0)) + // Clearing the threshold must clear the flags too — nothing else + // recomputes them once the tick stops evaluating. + if $0 == 0 { self.stalledSessionKeys = [] } + } + case .widgetCorner: + return list(CompactCorner.allCases, current: compactCorner, label: \.label) { + self.compactCorner = $0 + ConfigFile.write(key: "STACKNUDGE_COMPACT_CORNER", value: $0.rawValue) + } + case .widgetOpacity: + let options = Self.compactAlphaOptions + return list(options, current: compactAlpha, fallback: options.count - 1, label: { "\(Int($0 * 100))%" }) { + self.compactAlpha = $0 + ConfigFile.write(key: "STACKNUDGE_COMPACT_ALPHA", value: String(format: "%.2f", $0)) + } + case .widgetContent: + return list(CompactContent.allCases, current: compactContent, label: \.label) { + self.compactContent = $0 + ConfigFile.write(key: "STACKNUDGE_COMPACT_CONTENT", value: $0.rawValue) + } + case .mascot: + return list(MascotKind.allCases, current: mascot, label: \.label) { + self.mascot = $0 + ConfigFile.write(key: "STACKNUDGE_MASCOT", value: $0.rawValue) + } + case .theme: + return list(AccentTheme.allCases, current: theme, label: \.label) { + self.theme = $0 + ConfigFile.write(key: "STACKNUDGE_THEME", value: $0.rawValue) + } + case .agentDoneSound: + return list(Self.macSounds, current: soundStop, label: { $0 }) { + self.soundStop = $0 + ConfigFile.write(key: "STACKNUDGE_SOUND_STOP", value: $0) + NSSound(named: NSSound.Name($0))?.play() + } + case .permissionSound: + return list(Self.macSounds, current: soundPermission, label: { $0 }) { + self.soundPermission = $0 + ConfigFile.write(key: "STACKNUDGE_SOUND_PERMISSION", value: $0) + NSSound(named: NSSound.Name($0))?.play() + } + case .voice: + // Only reachable when the model is cached (otherwise the row is + // .downloadVoiceModel); nothing to offer while voices load. + guard !voicesLoading, !voicesAvailable.isEmpty else { return nil } + return list(voicesAvailable, current: voice, label: { $0 }) { + self.voice = $0 + ConfigFile.write(key: "STACKNUDGE_VOICE_NAME", value: $0) + let phrase = Self.voicePreviewPhrases.randomElement() ?? "Hello." + Speaker.speak(phrase, voice: $0, speed: String(format: "%.2f", self.voiceSpeed)) + } + case .alertThreshold: + return list(Self.quotaThresholds, current: quotaAlertThreshold, fallback: 2, label: { "\($0)%" }) { + self.quotaAlertThreshold = $0 + ConfigFile.write(key: "STACKNUDGE_QUOTA_THRESHOLD", value: String($0)) + } + case .pollFrequency: + return list(Self.quotaPollMinuteOptions, current: quotaPollMinutes, fallback: 2, label: { "\($0) min" }) { + self.quotaPollMinutes = $0 + ConfigFile.write(key: "STACKNUDGE_USAGE_POLL_MIN", value: String($0)) + } + case .contextAlert: + return list(Self.contextAlertThresholdOptions, current: contextAlertThresholdK, + label: { $0 == 0 ? "Off" : "\($0)K" }) { + self.contextAlertThresholdK = $0 + ConfigFile.write(key: "STACKNUDGE_CONTEXT_ALERT_THRESHOLD", value: String($0)) + } + case .slackIdle: + return list(SlackDelivery.idleMinuteOptions, current: slackIdleMinutes, fallback: 1, + label: SlackDelivery.idleLabel) { + self.slackIdleMinutes = $0 + ConfigFile.write(key: "STACKNUDGE_SLACK_IDLE_MIN", value: String($0)) + } + case .historyPerSession: + return list(Self.eventsPerSessionOptions, current: eventsPerSession, fallback: 1, label: { "\($0)" }) { + self.eventsPerSession = $0 + ConfigFile.write(key: "STACKNUDGE_EVENTS_PER_SESSION", value: String($0)) + } + case .updateChannel: + return list(UpdateChannel.allCases, current: updateChannel, label: \.label) { + self.setUpdateChannel($0) + } + default: + return nil + } + } + + private func list(_ options: [T], current: T, fallback: Int = 0, + label: (T) -> String, set: @escaping (T) -> Void) -> SettingChoices { + SettingChoices(labels: options.map(label), current: options.firstIndex(of: current), + fallback: fallback, pick: { set(options[$0]) }) + } +} + +// The click side: a value row's options as a menu at the pointer, the current +// one ticked. NSMenu rather than a SwiftUI Menu so the row keeps its look and +// the whole row, not just the value, opens it. +enum SettingChoicesMenu { + static func show(_ choices: SettingChoices) { + let menu = NSMenu() + let targets = choices.labels.indices.map { index in ChoiceTarget { choices.pick(index) } } + for (index, label) in choices.labels.enumerated() { + let item = NSMenuItem(title: label, action: #selector(ChoiceTarget.fire), keyEquivalent: "") + item.target = targets[index] + item.state = index == choices.current ? .on : .off + menu.addItem(item) + } + // popUp blocks until the menu closes, which keeps `targets` alive for + // as long as an item can still fire. + withExtendedLifetime(targets) { + _ = menu.popUp(positioning: menu.items.first { $0.state == .on }, at: NSEvent.mouseLocation, in: nil) + } + } + + private final class ChoiceTarget: NSObject { + let action: () -> Void + init(_ action: @escaping () -> Void) { self.action = action } + @objc func fire() { action() } + } +}