Files
coucou/NotchBuddy/Sources/App/FlowHub.swift
LouisandClaude a03feac166 Mochi editor: nothing cut on the sides (#1289)
The editor's content could grow wider than the sheet (a row of pills measured on one line), and
the whole page was cut on the left and the right. The content now keeps the sheet's width, and
HubWrap never reports an infinite width.


Claude-Session: https://claude.ai/code/session_01LJm3SRL9k3gBPaVtfPhwcT

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-03 20:32:59 +00:00

1001 lines
42 KiB
Swift

#if !APPSTORE
import AppKit
import Carbon
import SwiftUI
/// The pages of the Coucou window: what Coucou does (Flow, Mail, Mochis, Memory) in the sidebar,
/// and every setting in one place, behind the sidebar's Settings button.
enum HubPage: String, CaseIterable, Identifiable {
case dictation, notes, insights, dictionary, snippets, styles
/// Every screenshot taken with ⌘⇧S and ⌘⇧2.
case captures
/// The texts you copy, to keep (ClipKeeper.swift).
case clips
case mailOverview
case memorySearch, memoryGraph, memoryRecurrences, memoryUsage
case mochisTeam, mochisResults, mochisCloud
/// Your Mochis in a Telegram chat (TelegramLink.swift).
case mochisTelegram
/// The offers, compared (the lit button at the top of the sidebar).
case plans
// Settings
case app, general, pills, shortcuts, voice, privacy, devices
/// Flow's dictation settings (the key, the AI, the permission, the recognition).
case settings, notetakerSettings
case agentClaude, agentCodex, agentGemini, agentAntigravity, agentCopilot, agentMuse, agentOpenCode, agentAmp, agentHermes
/// Every agent on one page (kept for links from the notch; the Settings menu lists them one by one).
case agents
case chat, integrations
case mailRules, mailBanned, mailVIP
case memorySettings
var id: String { rawValue }
static let flowPages: [HubPage] = [.dictation, .notes, .insights, .dictionary, .snippets, .styles]
static let mailPages: [HubPage] = [.mailOverview]
static let memoryPages: [HubPage] = [.memorySearch, .memoryGraph, .memoryRecurrences, .captures, .clips, .memoryUsage]
static let mochiPages: [HubPage] = [.mochisTeam, .mochisResults, .mochisCloud, .mochisTelegram]
static let agentPages: [HubPage] = [.agentClaude, .agentCodex, .agentGemini, .agentAntigravity, .agentCopilot,
.agentMuse, .agentOpenCode, .agentAmp, .agentHermes]
/// A page of the Settings menu: the sidebar shows the Settings menu while it is open.
var isSettings: Bool { HubSettingsGroup.all.contains { $0.pages.contains(self) } || self == .agents }
/// The section of Settings this page shows ("agents.codex": the Codex box of the agents).
var settingsSection: String? {
switch self {
case .general: return "general.notch"
case .app: return "general.app"
case .devices: return "general.devices"
case .pills: return "activepills"
case .agents: return "agents"
case .agentClaude: return "agents.claude"
case .agentCodex: return "agents.codex"
case .agentGemini: return "agents.gemini"
case .agentAntigravity: return "agents.antigravity"
case .agentCopilot: return "agents.copilot"
case .agentMuse: return "agents.muse"
case .agentOpenCode: return "agents.opencode"
case .agentAmp: return "agents.amp"
case .agentHermes: return "agents.hermes"
case .chat: return "chat"
case .integrations: return "integrations"
case .voice: return "voice"
case .shortcuts: return "shortcuts"
default: return nil
}
}
/// The page showing a section of Settings ("chat", "voice"…), for the notch's links.
static func forSettings(_ section: String) -> HubPage {
switch section {
case "general": return .general
case "activepills": return .pills
case "agents": return .agentClaude
case "chat": return .chat
case "integrations": return .integrations
case "voice": return .voice
case "shortcuts": return .shortcuts
default: return allCases.first { $0.settingsSection == section } ?? .general
}
}
/// The colour of an agent's dot in the Settings menu (its pill's colour).
var agentColor: String? {
switch self {
case .agentClaude: return "#D97757"
case .agentCodex: return "#2DD4BF"
case .agentGemini: return "#8AB4F8"
case .agentAntigravity: return "#E879F9"
case .agentCopilot: return "#818CF8"
case .agentMuse: return "#38BDF8"
case .agentOpenCode: return "#4ADE80"
case .agentAmp: return "#F59E0B"
case .agentHermes: return "#C084FC"
default: return nil
}
}
var title: String {
switch self {
case .app: return String(localized: "hub.settings.app")
case .general: return String(localized: "hub.section.notch")
case .privacy: return String(localized: "hub.settings.privacy")
case .devices: return String(localized: "hub.settings.devices")
case .notetakerSettings: return String(localized: "hub.page.notes")
case .agentClaude: return "Claude Code"
case .agentCodex: return "Codex"
case .agentGemini: return "Gemini CLI"
case .agentAntigravity: return "Antigravity"
case .agentCopilot: return "Copilot CLI"
case .agentMuse: return "Muse Code"
case .agentOpenCode: return "OpenCode"
case .agentAmp: return "Amp"
case .agentHermes: return "Hermes"
case .pills: return String(localized: "Active pills")
case .agents: return String(localized: "Agents")
case .chat: return String(localized: "Chat")
case .integrations: return String(localized: "Integrations")
case .voice: return String(localized: "Voice")
case .shortcuts: return String(localized: "Shortcuts")
case .dictation: return String(localized: "hub.page.dictation")
case .notes: return String(localized: "hub.page.notes")
case .insights: return String(localized: "hub.page.insights")
case .dictionary: return String(localized: "hub.page.dictionary")
case .snippets: return String(localized: "hub.page.snippets")
case .styles: return String(localized: "hub.page.styles")
case .captures: return String(localized: "hub.page.captures")
case .clips: return String(localized: "hub.page.clips")
case .settings: return String(localized: "hub.page.dictation")
case .mailOverview: return String(localized: "hub.mail.overview")
case .mailRules: return String(localized: "hub.mail.rules")
case .mailBanned: return String(localized: "hub.mail.banned")
case .mailVIP: return String(localized: "hub.mail.vip")
case .memorySearch: return String(localized: "hub.page.memory-search")
case .memoryGraph: return String(localized: "hub.page.memory-graph")
case .memoryRecurrences: return String(localized: "hub.page.memory-recurrences")
case .mochisTeam: return String(localized: "hub.page.mochis-team")
case .mochisResults: return String(localized: "hub.page.mochis-results")
case .mochisCloud: return String(localized: "hub.page.mochis-cloud")
case .mochisTelegram: return String(localized: "hub.page.mochis-telegram")
case .plans: return String(localized: "hub.page.plans")
case .memoryUsage: return String(localized: "hub.page.memory-usage")
case .memorySettings: return String(localized: "hub.page.memory-settings")
}
}
var symbol: String {
switch self {
case .dictation: return "mic"
case .notes: return "record.circle"
case .insights: return "chart.bar"
case .dictionary: return "book.closed"
case .snippets: return "bolt"
case .styles: return "textformat"
case .captures: return "camera.viewfinder"
case .clips: return "doc.on.clipboard"
case .settings: return "mic"
case .notetakerSettings: return "record.circle"
case .app: return "macwindow"
case .privacy: return "hand.raised"
case .devices: return "iphone"
case .agentClaude, .agentCodex, .agentGemini, .agentAntigravity, .agentCopilot,
.agentMuse, .agentOpenCode, .agentAmp, .agentHermes: return "terminal"
case .general: return "rectangle.topthird.inset.filled"
case .pills: return "square.grid.2x2"
case .agents: return "terminal"
case .chat: return "bubble.left.and.bubble.right"
case .integrations: return "puzzlepiece.extension"
case .voice: return "waveform"
case .shortcuts: return "keyboard"
case .mailOverview: return "tray"
case .mailRules: return "line.3.horizontal.decrease"
case .mailBanned: return "nosign"
case .mailVIP: return "star"
case .memorySearch: return "magnifyingglass"
case .memoryGraph: return "point.3.connected.trianglepath.dotted"
case .memoryRecurrences: return "arrow.trianglehead.2.counterclockwise.rotate.90"
case .mochisTeam: return "person.2" // only where an SF Symbol is required; lists draw MochiCrewIcon
case .mochisResults: return "tray.full"
case .mochisCloud: return "cloud"
case .mochisTelegram: return "paperplane"
case .plans: return "sparkles"
case .memoryUsage: return "chart.bar.xaxis"
case .memorySettings: return "archivebox"
}
}
}
/// The colors of the Coucou Flow window: the island's dark, with Coucou's orange.
enum HubTheme {
/// OLED black: the window and the sidebar.
static let window = Color.black
static let sidebar = Color.black
/// The big card on the right, where the pages are.
static let panel = Color(hex: "#0E0F11")
static let card = Color(hex: "#18191C")
static let field = Color(hex: "#1F2024")
static let line = Color.white.opacity(0.07)
static let text = Color(hex: "#F5F6F8")
static let body = Color(hex: "#E1E3E6")
static let secondary = Color(hex: "#8E939C")
static let muted = Color(hex: "#6B7079")
static let accent = Color(hex: "#FB923C")
static let onAccent = Color(hex: "#170C04")
static let green = Color(hex: "#34D399")
static let red = Color(hex: "#FF453A")
/// One color per person in a call: you first, then the others.
static let speakers: [Color] = ["#3B9EFF", "#34D399", "#A78BFA", "#F7B32B", "#F472B6", "#22D3EE"].map { Color(hex: $0) }
static func speaker(_ index: Int) -> Color { speakers[max(0, index) % speakers.count] }
}
private struct HubPageKey: EnvironmentKey {
static let defaultValue: HubPage = .dictation
}
extension EnvironmentValues {
/// The page shown, for the colour and the Mochis of its top band.
var hubPage: HubPage {
get { self[HubPageKey.self] }
set { self[HubPageKey.self] = newValue }
}
}
extension HubPage {
/// The line under the title of the notch's pages.
static func notchSubtitle(_ page: HubPage) -> String? {
switch page {
case .general: return String(localized: "hub.notch.general")
case .pills: return String(localized: "hub.notch.pills")
case .agents: return String(localized: "hub.notch.agents")
case .chat: return String(localized: "hub.notch.chat")
case .integrations: return String(localized: "hub.notch.integrations")
case .voice: return String(localized: "hub.notch.voice")
case .shortcuts: return String(localized: "hub.notch.shortcuts")
default: return nil
}
}
}
@MainActor
final class HubRouter: ObservableObject {
@Published var page: HubPage = .dictation {
didSet { if page.isSettings { lastSettings = page } else { lastContent = page } }
}
/// Where the Settings menu's back arrow returns, and where its button opens.
private(set) var lastContent: HubPage = .dictation
private(set) var lastSettings: HubPage = .app
}
/// Opens the Coucou Flow window: the history of the dictations, the Notetaker, the numbers, the
/// dictionary, the snippets, the styles and the settings of the dictation.
@MainActor
final class FlowHubController {
static let shared = FlowHubController()
let router = HubRouter()
let windowState = HubWindowState()
private var window: NSWindow?
static let showInDockKey = "coucouShowInDock"
static let openAtLaunchKey = "coucouOpenAtLaunch"
/// Coucou in the Dock, like a regular app (on by default in the GitHub build).
static var showInDock: Bool {
get { UserDefaults.standard.object(forKey: showInDockKey) as? Bool ?? true }
set {
UserDefaults.standard.set(newValue, forKey: showInDockKey)
NSApp.setActivationPolicy(newValue ? .regular : .accessory)
if newValue { NSApp.activate(ignoringOtherApps: true) }
}
}
/// The window opens when Coucou is opened by hand (never at login).
static var openAtLaunch: Bool {
get { UserDefaults.standard.object(forKey: openAtLaunchKey) as? Bool ?? true }
set { UserDefaults.standard.set(newValue, forKey: openAtLaunchKey) }
}
/// Whether macOS opened Coucou at login, rather than you from the Finder, the Dock or Spotlight.
static func launchedAtLogin() -> Bool {
if let event = NSAppleEventManager.shared().currentAppleEvent,
event.paramDescriptor(forKeyword: AEKeyword(keyAEPropData))?.enumCodeValue == OSType(keyAELaunchedAsLogInItem) {
return true
}
// A login item started by launchd may come without that flag: the first minutes after
// the Mac starts count as a login.
return ProcessInfo.processInfo.systemUptime < 180
}
func show(_ page: HubPage? = nil) {
if let page { router.page = page }
if let window {
window.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
return
}
let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 720),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
win.title = "Coucou"
win.titlebarAppearsTransparent = true
win.titleVisibility = .hidden
win.appearance = NSAppearance(named: .darkAqua)
win.backgroundColor = .black
win.contentView = NSHostingView(rootView: FlowHubView(router: router, windowState: windowState))
windowState.watch(win)
win.contentMinSize = NSSize(width: 940, height: 600)
win.isReleasedWhenClosed = false
win.setFrameAutosaveName("CoucouFlowWindow")
if !win.setFrameUsingName("CoucouFlowWindow") { win.center() }
window = win
win.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
}
}
struct FlowHubView: View {
@ObservedObject var router: HubRouter
@ObservedObject var windowState: HubWindowState
var body: some View {
HStack(spacing: 0) {
HubSidebar(router: router)
// The pages sit in one big card, like Wispr Flow's window.
page
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.background(
RoundedRectangle(cornerRadius: 20, style: .continuous)
.fill(HubTheme.panel)
)
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
.overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).strokeBorder(Color.white.opacity(0.07)))
.padding(.top, 10)
.padding(.bottom, 10)
.padding(.trailing, 10)
}
.background(HubTheme.window)
.foregroundColor(HubTheme.text)
.preferredColorScheme(.dark)
.tint(HubTheme.accent)
.environment(\.hubVisible, windowState.visible)
.environment(\.hubPage, router.page)
}
@ViewBuilder private var page: some View {
switch router.page {
case .dictation: HubHomePage(router: router)
case .notes: HubNotesPage()
case .insights: HubInsightsPage()
case .dictionary: HubDictionaryPage()
case .snippets: HubSnippetsPage()
case .styles: HubStylesPage(router: router)
case .captures: HubCapturesPage()
case .clips: HubClipsPage()
case .settings: HubSettingsPage(part: .dictation)
case .notetakerSettings: HubSettingsPage(part: .notetaker)
case .privacy: HubSettingsPage(part: .privacy)
case .mailOverview: HubMailOverviewPage()
case .mailRules: HubMailRulesPage()
case .mailBanned: HubMailBannedPage()
case .mailVIP: HubMailVIPPage()
#if !APPSTORE
case .memorySearch: HubMemorySearchPage()
case .memoryGraph: HubMemoryGraphPage()
case .memoryRecurrences: HubMemoryRecurrencesPage(router: router)
case .mochisTeam: HubMochisTeamPage(router: router)
case .mochisResults: HubMochisResultsPage()
case .mochisCloud: HubMochisCloudPage(router: router)
case .mochisTelegram: HubMochisTelegramPage()
case .plans: HubPlansPage(router: router)
case .memoryUsage: HubMemoryUsagePage()
case .memorySettings: HubMemorySettingsPage()
#endif
default:
if let section = router.page.settingsSection {
VStack(alignment: .leading, spacing: 0) {
HubHero(page: router.page, title: router.page.title, subtitle: HubPage.notchSubtitle(router.page))
.padding(.horizontal, 28)
.padding(.top, 24)
if router.page == .app {
// Coucou's window and its onboarding, above the app's startup, updates and language
SettingsView(embeddedSection: section, top: AnyView(HubAppCard()))
.id(section)
} else {
SettingsView(embeddedSection: section)
.id(section)
}
}
}
}
}
}
// MARK: - Sidebar
private struct HubSidebar: View {
@ObservedObject var router: HubRouter
@ObservedObject private var flow = FlowDictation.shared
@ObservedObject private var search = SettingsSearch.shared
/// The open section ("flow", "mochis", "mail", "memory"; "" = all closed). A @State, so
/// opening and closing ride the click's animation (a change of @AppStorage arrives outside it,
/// and the group would snap shut); kept between launches through UserDefaults.
@State private var openSection = UserDefaults.standard.string(forKey: "hub.sidebar.open-section") ?? "flow"
/// The same, for the groups of the Settings menu.
@State private var openGroup = UserDefaults.standard.string(forKey: "hub.sidebar.open-settings-group") ?? "general"
private var inSettings: Bool { router.page.isSettings }
var body: some View {
VStack(alignment: .leading, spacing: 3) {
HStack(spacing: 10) {
// The scene draws Mochi a little below its middle (room for his
// hops and hats): lifted so his body lines up with the name.
HubLiveMochi(size: 28)
.offset(y: -4)
Text(verbatim: "Coucou")
.font(.system(size: 18, weight: .bold))
.lineLimit(1)
.fixedSize()
#if !APPSTORE
Spacer(minLength: 6)
HubPlansButton(router: router)
#endif
}
.padding(.horizontal, 8)
// Halfway between the window's buttons and "FLOW".
.padding(.top, 25)
.padding(.bottom, 16)
HubSearchField()
.padding(.bottom, 14)
ScrollView {
if !search.query.trimmingCharacters(in: .whitespaces).isEmpty {
HubSearchResults(router: router)
} else if inSettings {
settingsMenu
.transition(.move(edge: .trailing).combined(with: .opacity))
} else {
// One section open at a time: a click on a section's name opens it and closes the others.
sections(HubSidebarSection.all, open: $openSection)
.transition(.move(edge: .leading).combined(with: .opacity))
}
}
.scrollIndicators(.never)
.clipped()
if !inSettings {
// Apart from the sections: every setting of Coucou, in one place.
HubSidebarSettingsButton { withAnimation(HubSidebarMotion.slide) { router.page = router.lastSettings } }
.padding(.top, 6)
.transition(.opacity)
}
status
.padding(.top, 6)
}
.padding(.horizontal, 12)
.padding(.bottom, 14)
.frame(width: 228)
.frame(maxHeight: .infinity)
.background(HubTheme.sidebar)
.animation(HubSidebarMotion.slide, value: inSettings)
.onChange(of: openSection) { UserDefaults.standard.set(openSection, forKey: "hub.sidebar.open-section") }
.onChange(of: openGroup) { UserDefaults.standard.set(openGroup, forKey: "hub.sidebar.open-settings-group") }
.onChange(of: router.page, initial: true) {
if let section = HubSidebarSection.all.first(where: { $0.pages.contains(router.page) }), section.id != openSection {
withAnimation(HubSidebarMotion.open) { openSection = section.id }
}
if let group = HubSettingsGroup.all.first(where: { $0.pages.contains(router.page) }), group.id != openGroup {
withAnimation(HubSidebarMotion.open) { openGroup = group.id }
}
}
}
/// The Settings menu: the way back, then the settings by what they belong to.
private var settingsMenu: some View {
VStack(alignment: .leading, spacing: 2) {
HubSidebarBack(title: String(localized: "hub.page.settings")) {
withAnimation(HubSidebarMotion.slide) { router.page = router.lastContent }
}
.padding(.bottom, 8)
sections(HubSettingsGroup.all.map { HubSidebarSection(id: $0.id, title: $0.title, pages: $0.pages) }, open: $openGroup)
}
}
private func sections(_ list: [HubSidebarSection], open: Binding<String>) -> some View {
VStack(alignment: .leading, spacing: 2) {
ForEach(Array(list.enumerated()), id: \.element.id) { index, section in
HubSidebarHeader(text: section.title, open: open.wrappedValue == section.id) {
withAnimation(HubSidebarMotion.open) {
open.wrappedValue = open.wrappedValue == section.id ? "" : section.id
}
}
.padding(.top, index == 0 ? 0 : 8)
HubSidebarGroup(open: open.wrappedValue == section.id) {
ForEach(Array(section.pages.enumerated()), id: \.element) { i, page in
HubSidebarItem(page: page, selected: router.page == page) { router.page = page }
.modifier(HubSidebarReveal(open: open.wrappedValue == section.id, index: i, count: section.pages.count))
}
}
}
}
}
@ViewBuilder private var status: some View {
let ready = flow.isEnabled && flow.trusted
Button { withAnimation(HubSidebarMotion.slide) { router.page = .settings } } label: {
HStack(spacing: 8) {
Circle()
.fill(ready ? HubTheme.green : (flow.isEnabled ? HubTheme.accent : HubTheme.muted))
.frame(width: 7, height: 7)
Text(ready ? String(format: String(localized: "hub.status-ready %@"), flow.key.label)
: (flow.isEnabled ? String(localized: "hub.status-access") : String(localized: "hub.status-off")))
.font(.system(size: 12))
.foregroundColor(Color(hex: "#A4A9B1"))
.lineLimit(2)
.multilineTextAlignment(.leading)
Spacer(minLength: 0)
}
.padding(10)
.background(RoundedRectangle(cornerRadius: 10).fill(HubTheme.card))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Color.white.opacity(0.06)))
}
.buttonStyle(.plain)
}
}
/// The sections of the sidebar, in order.
private struct HubSidebarSection: Identifiable {
let id: String
let title: String
let pages: [HubPage]
static var all: [HubSidebarSection] {
var list = [
HubSidebarSection(id: "flow", title: "Flow", pages: HubPage.flowPages),
HubSidebarSection(id: "mail", title: "Mail", pages: HubPage.mailPages),
]
#if !APPSTORE
list.append(HubSidebarSection(id: "mochis", title: "Mochis", pages: HubPage.mochiPages))
list.append(HubSidebarSection(id: "memory", title: String(localized: "hub.section.memory"), pages: HubPage.memoryPages))
#endif
return list
}
}
/// The groups of the Settings menu, in order: every setting of Coucou, by what it belongs to.
struct HubSettingsGroup: Identifiable {
let id: String
let title: String
let pages: [HubPage]
static let all: [HubSettingsGroup] = [
HubSettingsGroup(id: "general", title: String(localized: "General"),
pages: [.app, .general, .pills, .shortcuts, .voice, .privacy, .devices]),
HubSettingsGroup(id: "flow", title: "Flow", pages: [.settings, .notetakerSettings]),
HubSettingsGroup(id: "agents", title: String(localized: "Agents"), pages: HubPage.agentPages + [.chat]),
HubSettingsGroup(id: "integrations", title: String(localized: "Integrations"), pages: [.integrations]),
HubSettingsGroup(id: "mail", title: "Mail", pages: [.mailRules, .mailBanned, .mailVIP]),
HubSettingsGroup(id: "memory", title: String(localized: "hub.section.memory"), pages: [.memorySettings]),
]
}
/// "Settings", at the foot of the sidebar, set apart from the sections.
private struct HubSidebarSettingsButton: View {
let action: () -> Void
@State private var hover = false
var body: some View {
Button(action: action) {
HStack(spacing: 10) {
Image(systemName: "gearshape")
.font(.system(size: 14, weight: .medium))
.frame(width: 20)
Text(String(localized: "hub.page.settings"))
.font(.system(size: 14))
Spacer(minLength: 0)
Image(systemName: "chevron.right")
.font(.system(size: 9, weight: .bold))
.opacity(hover ? 1 : 0.5)
}
.foregroundColor(hover ? HubTheme.text : Color(hex: "#B7BBC2"))
.padding(.horizontal, 10)
.frame(height: 34)
.background(RoundedRectangle(cornerRadius: 9).fill(Color.white.opacity(hover ? 0.05 : 0)))
.overlay(alignment: .top) { Rectangle().fill(HubTheme.line).frame(height: 1).offset(y: -4) }
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { hover = $0 }
}
}
/// The top of the Settings menu: the way back to the pages.
private struct HubSidebarBack: View {
let title: String
let action: () -> Void
@State private var hover = false
var body: some View {
Button(action: action) {
HStack(spacing: 8) {
Image(systemName: "chevron.left")
.font(.system(size: 12, weight: .semibold))
.frame(width: 20)
Text(title)
.font(.system(size: 15, weight: .semibold))
Spacer(minLength: 0)
}
.foregroundColor(hover ? HubTheme.text : Color(hex: "#D5D8DD"))
.padding(.horizontal, 10)
.frame(height: 32)
.background(RoundedRectangle(cornerRadius: 9).fill(Color.white.opacity(hover ? 0.05 : 0)))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { hover = $0 }
}
}
/// A section's pages, unfolding: the group's height grows from 0 to its full height (measured,
/// so the pages below slide down with it), and the pages appear one after the other.
private enum HubSidebarMotion {
static var open: Animation { .spring(response: 0.38, dampingFraction: 0.86) }
/// Into the Settings menu and back.
static var slide: Animation { .spring(response: 0.42, dampingFraction: 0.9) }
}
private struct HubSidebarGroup<Content: View>: View {
let open: Bool
@ViewBuilder var content: () -> Content
@State private var height: CGFloat = 0
var body: some View {
VStack(alignment: .leading, spacing: 2) { content() }
.padding(.top, 2)
.fixedSize(horizontal: false, vertical: true)
.background(GeometryReader { g in
Color.clear.preference(key: HubSidebarHeightKey.self, value: g.size.height)
})
.onPreferenceChange(HubSidebarHeightKey.self) { height = $0 }
.frame(height: open ? height : 0, alignment: .top)
.clipped()
.animation(HubSidebarMotion.open, value: open)
.allowsHitTesting(open)
.accessibilityHidden(!open)
}
}
private struct HubSidebarHeightKey: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) }
}
/// Each page of an opening section fades in and drops into place a beat after the one above it;
/// closing, they leave together, bottom first.
private struct HubSidebarReveal: ViewModifier {
let open: Bool
let index: Int
let count: Int
func body(content: Content) -> some View {
content
.opacity(open ? 1 : 0)
.offset(y: open ? 0 : -8)
.scaleEffect(open ? 1 : 0.97, anchor: .topLeading)
.animation(open
? .spring(response: 0.36, dampingFraction: 0.82).delay(0.04 + Double(index) * 0.028)
: .easeIn(duration: 0.2).delay(Double(count - 1 - index) * 0.02),
value: open)
}
}
/// "FLOW", "NOTCH": the small capitals above a group of pages. A click opens or closes the group;
/// the chevron says which.
private struct HubSidebarHeader: View {
let text: String
var open = false
var action: () -> Void = {}
@State private var hover = false
var body: some View {
Button(action: action) {
HStack(spacing: 6) {
Text(text.uppercased(with: .current))
.font(.system(size: 10.5, weight: .bold))
.tracking(1.2)
Spacer(minLength: 0)
Image(systemName: "chevron.right")
.font(.system(size: 9, weight: .bold))
.rotationEffect(.degrees(open ? 90 : 0))
.opacity(hover || open ? 1 : 0.6)
}
.foregroundColor(open || hover ? Color(hex: "#B7BBC2") : HubTheme.muted)
.padding(.horizontal, 10)
.frame(height: 26)
.background(RoundedRectangle(cornerRadius: 7).fill(Color.white.opacity(hover ? 0.03 : 0)))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { hover = $0 }
.accessibilityAddTraits(.isHeader)
.accessibilityValue(open ? String(localized: "hub.section.open") : String(localized: "hub.section.closed"))
}
}
private struct HubSidebarItem: View {
let page: HubPage
let selected: Bool
let action: () -> Void
@State private var hover = false
var body: some View {
Button(action: action) {
HStack(spacing: 10) {
if let dot = page.agentColor {
// an agent: its pill's colour
Circle().fill(Color(hex: dot)).frame(width: 8, height: 8).frame(width: 20)
} else {
page.icon(size: 14)
.frame(width: 20)
}
Text(page.title)
.font(.system(size: 14, weight: selected ? .semibold : .regular))
Spacer(minLength: 0)
}
.foregroundColor(selected ? HubTheme.text : Color(hex: "#B7BBC2"))
.padding(.horizontal, 10)
.frame(height: 32)
.background(RoundedRectangle(cornerRadius: 9)
.fill(Color.white.opacity(selected ? 0.08 : (hover ? 0.04 : 0))))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.onHover { hover = $0 }
}
}
// MARK: - Shared pieces
extension HubPage {
/// The page's icon in lists: an SF Symbol, or for Mochis a little crew of Mochis drawn in the
/// same line weight.
@ViewBuilder
func icon(size: CGFloat) -> some View {
if self == .mochisTeam {
MochiCrewIcon().frame(width: size * 1.45, height: size * 1.05)
} else {
Image(systemName: symbol).font(.system(size: size, weight: .medium))
}
}
}
/// Two Mochis: a big one in outline and a little solid one beside it, both with their eyes — the
/// icon of the Mochis page. Drawn in the current foreground colour, like an SF Symbol.
struct MochiCrewIcon: View {
var body: some View {
Canvas { ctx, size in
let k = size.width / 20, line = max(1.2, 1.45 * k)
func eyes(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat, _ eyeW: CGFloat, _ eyeH: CGFloat) -> Path {
var p = Path()
let cy = (y + h * 0.5) * k, gap = w * 0.18 * k
for dx in [-gap, gap] {
p.addRoundedRect(in: CGRect(x: (x + w / 2) * k + dx - eyeW * k / 2, y: cy - eyeH * k / 2, width: eyeW * k, height: eyeH * k),
cornerSize: CGSize(width: eyeW * k / 2, height: eyeW * k / 2))
}
return p
}
func body(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) -> Path {
Path(roundedRect: CGRect(x: x * k, y: y * k, width: w * k, height: h * k), cornerRadius: h * 0.4 * k, style: .continuous)
}
// the big one: outline + eyes
ctx.stroke(body(0.9, 2.5, 11.6, 9.4), with: .foreground, lineWidth: line)
ctx.fill(eyes(0.9, 2.5, 11.6, 9.4, 1.5, 2.7), with: .foreground)
// the little one: solid, its eyes cut out
ctx.drawLayer { l in
l.fill(body(13.6, 5.8, 6.2, 5.4), with: .foreground)
l.blendMode = .destinationOut
l.fill(eyes(13.6, 5.8, 6.2, 5.4, 1.1, 1.8), with: .color(.black))
}
}
}
}
/// Mochi as a small logo: the white body and its two eyes.
struct HubMochi: View {
var size: CGFloat = 28
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: size * 0.33, style: .continuous)
.fill(LinearGradient(colors: [.white, Color(hex: "#C9CBD1")], startPoint: .top, endPoint: .bottom))
HStack(spacing: size * 0.2) {
Capsule().fill(Color(hex: "#1A1412")).frame(width: size * 0.11, height: size * 0.22)
Capsule().fill(Color(hex: "#1A1412")).frame(width: size * 0.11, height: size * 0.22)
}
}
.frame(width: size, height: size * 0.72)
}
}
/// A page: its title, an optional line under it, and the content, scrolling.
struct HubPageScaffold<Trailing: View, Content: View>: View {
let title: String
var subtitle: String? = nil
@ViewBuilder var trailing: () -> Trailing
@ViewBuilder var content: () -> Content
@Environment(\.hubPage) private var page
var body: some View {
ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading, spacing: 22) {
HubHero(page: page, title: title, subtitle: subtitle, trailing: trailing)
content()
}
.padding(.horizontal, 28)
.padding(.top, 24)
.padding(.bottom, 28)
.frame(maxWidth: 1100, alignment: .leading)
}
.scrollIndicators(.automatic)
.settingsSearchScroll(proxy)
}
}
}
extension HubPageScaffold where Trailing == EmptyView {
init(title: String, subtitle: String? = nil, @ViewBuilder content: @escaping () -> Content) {
self.title = title
self.subtitle = subtitle
self.trailing = { EmptyView() }
self.content = content
}
}
/// A dark rounded card.
struct HubCard<Content: View>: View {
var padding: CGFloat = 18
@ViewBuilder var content: () -> Content
var body: some View {
VStack(alignment: .leading, spacing: 12) { content() }
.padding(padding)
.frame(maxWidth: .infinity, alignment: .leading)
.background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(HubTheme.card))
.overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(HubTheme.line))
}
}
/// "AUJOURD'HUI": the small capitals above a list.
struct HubLabel: View {
let text: String
init(_ text: String) { self.text = text }
var body: some View {
Text(text.uppercased(with: .current))
.font(.system(size: 11.5, weight: .bold))
.tracking(1.3)
.foregroundColor(HubTheme.muted)
}
}
/// A row of a settings card: the label on the left, the control on the right.
struct HubRow<Control: View>: View {
let title: String
var detail: String? = nil
@ViewBuilder var control: () -> Control
var body: some View {
HStack(alignment: .center, spacing: 16) {
VStack(alignment: .leading, spacing: 3) {
Text(title).font(.system(size: 13.5, weight: .medium))
if let detail {
Text(detail)
.font(.system(size: 12))
.foregroundColor(HubTheme.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
Spacer(minLength: 8)
control()
}
.padding(.vertical, 2)
}
}
struct HubDivider: View {
var body: some View { Rectangle().fill(Color.white.opacity(0.06)).frame(height: 1) }
}
/// Orange (primary) or dark (secondary) button.
struct HubButtonStyle: ButtonStyle {
var primary = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 13, weight: primary ? .bold : .semibold))
.foregroundColor(primary ? HubTheme.onAccent : HubTheme.text)
.padding(.horizontal, 14)
.frame(height: 34)
.background(RoundedRectangle(cornerRadius: 9, style: .continuous)
.fill(primary ? HubTheme.accent : Color(hex: "#1D1E22")))
.overlay(RoundedRectangle(cornerRadius: 9, style: .continuous)
.strokeBorder(primary ? Color.clear : Color.white.opacity(0.1)))
.opacity(configuration.isPressed ? 0.75 : 1)
.contentShape(Rectangle())
}
}
/// A small square icon button (copy, delete).
struct HubIconButton: View {
let symbol: String
let help: String
let action: () -> Void
@State private var hover = false
var body: some View {
Button(action: action) {
Image(systemName: symbol)
.font(.system(size: 12, weight: .medium))
.foregroundColor(hover ? HubTheme.text : Color(hex: "#A4A9B1"))
.frame(width: 28, height: 28)
.background(RoundedRectangle(cornerRadius: 7).fill(Color.white.opacity(hover ? 0.1 : 0.05)))
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.help(help)
.accessibilityLabel(help)
.onHover { hover = $0 }
}
}
/// A text field drawn like the rest of the window.
struct HubField: View {
let placeholder: String
@Binding var text: String
var onSubmit: () -> Void = {}
var body: some View {
TextField(placeholder, text: $text)
.textFieldStyle(.plain)
.font(.system(size: 13))
.padding(.horizontal, 12)
.frame(height: 34)
.background(RoundedRectangle(cornerRadius: 9, style: .continuous).fill(HubTheme.field))
.overlay(RoundedRectangle(cornerRadius: 9, style: .continuous).strokeBorder(Color.white.opacity(0.1)))
.onSubmit(onSubmit)
}
}
/// Lays its children out in rows, wrapping to the next row when one is full (the dictionary's words).
struct HubWrap: Layout {
var spacing: CGFloat = 8
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let width = proposal.width ?? .infinity
var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, widest: CGFloat = 0
for view in subviews {
let size = view.sizeThatFits(.unspecified)
if x > 0, x + size.width > width {
x = 0
y += rowHeight + spacing
rowHeight = 0
}
x += size.width + spacing
rowHeight = max(rowHeight, size.height)
widest = max(widest, x - spacing)
}
// asked for its ideal size (no width, or an infinite one): its widest row, never infinity
let given = proposal.width.flatMap { $0.isFinite ? $0 : nil }
return CGSize(width: given ?? widest, height: y + rowHeight)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
var x = bounds.minX, y = bounds.minY, rowHeight: CGFloat = 0
for view in subviews {
let size = view.sizeThatFits(.unspecified)
if x > bounds.minX, x + size.width > bounds.maxX {
x = bounds.minX
y += rowHeight + spacing
rowHeight = 0
}
view.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size))
x += size.width + spacing
rowHeight = max(rowHeight, size.height)
}
}
}
extension NSPasteboard {
/// Copies plain text, as the copy buttons of the window do.
@MainActor static func copyText(_ text: String) {
general.clearContents()
general.setString(text, forType: .string)
}
}
#endif