SPB Git

Repository Public

MainWindow.swift 16.6 KB 298 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/MainWindow.swift3// Description: Main window: sidebar, then either the notes (list and editor) or a feature screen chosen through a typed destination; per-window state (selection, destination, route to a block), restored by the system; lock screen, command center, toasts; the blocking screen when the database cannot be opened.4import SwiftUI5import SPNotesStore6import SPNotesDesign78/// State of one window. Windows share the store and the note sessions; each has its own sidebar selection, note list,9/// search, destination and note selection.10@Observable final class WindowModel: FeatureRouting {11    var selectedNotes: Set<String> = [] { didSet { if selectedNotes != oldValue { selectionChanged() } } }12    private(set) var session: NoteSession?13    /// What the detail area shows: the notes, or a feature screen.14    var destination: Destination = .notes15    /// This window's library view (sidebar selection, list, search). The shared `env.library` serves the application-level actions.16    let library: LibraryModel17    /// Which side panel is open beside the editor.18    enum SidePanel: String { case inspector, assistant }19    var sidePanel: SidePanel?20    var showInspector: Bool { get { sidePanel == .inspector } set { sidePanel = newValue ? .inspector : (sidePanel == .inspector ? nil : sidePanel) } }21    var showAssistant: Bool { get { sidePanel == .assistant } set { sidePanel = newValue ? .assistant : (sidePanel == .assistant ? nil : sidePanel) } }22    var showPalette = false23    var paletteMode: PaletteMode = .commands24    var showHistory = false25    var showAccount = false26    var focusSearch = 027    var focusTitle = 028    /// What the database, canvas and graph destinations show (nil = their own list / the whole workspace).29    var databaseId: String?30    var canvasPageId: String?31    var graphPageId: String?32    /// Page whose timeline and time machine are shown in a sheet.33    var pageTimeline: String?34    /// Model chosen for the assistant in this window (nil = automatic routing).35    var assistantModel: String?36    var assistantModelName: String?37    /// Block to scroll to and flash once the selected note is on screen.38    private(set) var pendingBlock: String?39    /// Bumped each time a note is opened: the title of the list row morphs into the title of the page (Fluid Navigation).40    private(set) var openCount = 041    @ObservationIgnored weak var env: AppEnvironment?42    @ObservationIgnored private var loading: Task<Void, Never>?43    enum PaletteMode { case commands, open }4445    init(env: AppEnvironment) {46        self.env = env47        library = LibraryModel(store: env.store, preferences: env.preferences); library.env = env; library.notifiesSessions = false48        sidePanel = env.preferences.showInspector ? .inspector : nil49    }5051    var currentNoteId: String? { selectedNotes.count == 1 ? selectedNotes.first : nil }5253    private func selectionChanged() {54        loading?.cancel()55        let previous = session56        guard let id = currentNoteId, let env else { session = nil; Task { await previous?.saveNow(reason: nil) }; return }57        if session?.id == id { applyPendingBlock(); return }58        loading = Task { [weak self] in59            await previous?.saveNow(reason: nil)60            let s = await env.session(for: id)61            guard !Task.isCancelled, let self, self.currentNoteId == id else { return }62            self.session = s; self.openCount += 163            try? await env.store.markOpened(id: id)64            self.applyPendingBlock()65        }66    }67    func open(_ id: String) { open(Route(pageId: id)) }68    /// Shows a page in this window, at a block when the route names one.69    func open(_ route: Route) {70        destination = .notes71        pendingBlock = route.blockId72        if selectedNotes == [route.pageId] { applyPendingBlock() } else { selectedNotes = [route.pageId] }73    }74    private func applyPendingBlock() {75        guard let block = pendingBlock, let s = session, s.id == currentNoteId else { return }76        pendingBlock = nil77        // the editor is laid out by the time the window has shown the note78        Task { [weak self] in79            try? await Task.sleep(for: .milliseconds(120))80            if !s.editor.textView.scrollToBlock(id: block) { self?.env?.toasts.show("Ce bloc n'existe plus dans la note.", symbol: "questionmark.circle") }81        }82    }83    /// The selected note was not in the local store yet (it arrives with the synchronisation): try again.84    func retryIfNeeded() { if session == nil, currentNoteId != nil { selectionChanged() } }8586    func newNote(asFolder: Bool = false) {87        guard let env, !env.isBlocked else { return }88        Task {89            if let id = await library.newNote(asFolder: asFolder) {90                if case .list(let l) = library.selection, l == .trash || l == .archived || l == .inbox { library.selection = .list(.all) }91                await library.reloadNotes()92                open(id); focusTitle += 193            }94        }95    }9697    // MARK: FeatureRouting9899    func openPage(id: String, blockId: String?) { open(Route(pageId: id, blockId: blockId)) }100    func openURL(_ url: URL) {101        if let link = DeepLink(url), case .page(let r) = link { open(r); return }102        guard let scheme = url.scheme?.lowercased(), ["https", "http", "mailto"].contains(scheme) else { presentError("Ce lien n'est pas une adresse web : il n'a pas été ouvert."); return }103        NSWorkspace.shared.open(url)104    }105    func presentError(_ message: String) { env?.toasts.show(message, isError: true) }106}107108struct MainWindow: View {109    @Environment(AppEnvironment.self) private var env110    let initialNote: String?111112    var body: some View {113        // the local database could not be opened: nothing but the explanation is reachable (no editor, no command)114        switch Self.root(for: env) {115        case .storeFailure(let failure): StoreFailureView(error: failure).frame(minWidth: 720, minHeight: 520).preferredColorScheme(env.preferences.appearance.colorScheme)116        case .library: LibraryWindow(initialNote: initialNote, window: WindowModel(env: env))117        }118    }119    /// What a window shows. A database that could not be opened leaves one possibility only.120    enum Root: Equatable { case storeFailure(StoreOpenError), library }121    static func root(for env: AppEnvironment) -> Root { env.storeFailure.map(Root.storeFailure) ?? .library }122}123124private struct LibraryWindow: View {125    @Environment(AppEnvironment.self) private var env126    @Environment(\.openWindow) private var openWindow127    @Environment(\.accessibilityReduceMotion) private var reduceMotion128    let initialNote: String?129    @State var window: WindowModel130    @State private var columns: NavigationSplitViewVisibility = .all131    @State private var didAutoSelect = false132    @State private var restored = false133    // restored by the system with the window (each window keeps its own place)134    @SceneStorage("sp.destination") private var storedDestination = Destination.notes.rawValue135    @SceneStorage("sp.sidebar") private var storedSidebar = ""136    @SceneStorage("sp.note") private var storedNote = ""137    /// Shown until the owner signs in or chooses to stay local; never when a session exists or ended (notes are already here).138    private var showWelcome: Bool { env.account.phase == .local && !env.preferences.welcomeDone && !env.options.isUITest && env.account.isReady }139140    var body: some View {141        ZStack {142            Group {143                if window.destination == .notes {144                    NavigationSplitView(columnVisibility: $columns) {145                        SidebarView().navigationSplitViewColumnWidth(min: 200, ideal: 232, max: 320)146                    } content: {147                        NoteListView().navigationSplitViewColumnWidth(min: 250, ideal: 310, max: 460)148                    } detail: {149                        NoteDetailView()150                    }151                } else {152                    NavigationSplitView(columnVisibility: $columns) {153                        SidebarView().navigationSplitViewColumnWidth(min: 200, ideal: 232, max: 320)154                    } detail: {155                        FeatureDetail(destination: window.destination)156                    }157                }158            }159            .disabled(env.lock.isLocked || showWelcome)160            .blur(radius: env.lock.isLocked ? NVSpace.xl : 0)161            if env.lock.isLocked { LockScreen() }162            else if showWelcome { WelcomeView { env.preferences.welcomeDone = true }.transition(.opacity) }163            if window.showPalette { CommandCenter().transition(NVTransition.captureScaleIn(reduceMotion: reduceMotion)) }164            ToastOverlay()165        }166        .animation(NVMotion.animation(.fast, reduceMotion: reduceMotion), value: window.showPalette)167        .environment(window)168        .focusedSceneValue(\.windowModel, window)169        .tint(NVColor.accent)170        .preferredColorScheme(env.preferences.appearance.colorScheme)171        .frame(minWidth: 900, minHeight: 540)172        .sheet(isPresented: Binding(get: { window.showAccount }, set: { window.showAccount = $0 })) { AccountSheet().environment(env).environment(window) }173        .task {174            MainWindowOpener.open = { openWindow(id: "main") }175            await env.start()176            await window.library.start()177            restore()178            if let id = initialNote ?? env.options.openNote { window.open(id) }179            else if window.selectedNotes.isEmpty, window.destination == .notes, let first = window.library.notes.first, env.options.route == nil { window.open(first.id) }180            switch env.options.route {181            case "assistant": window.showAssistant = true; openForPanel()182            case "inspector": window.showInspector = true; openForPanel()183            case "palette": window.showPalette = true184            case "account": window.showAccount = true185            case let r?: if let d = Destination(rawValue: r) { go(d) }186            case nil: break187            }188        }189        .onChange(of: window.library.notes.first?.id) { _, first in if window.selectedNotes.isEmpty, window.session == nil, window.destination == .notes, let first, !didAutoSelect, env.options.route == nil { didAutoSelect = true; window.open(first) } }190        .onChange(of: window.library.notes.count) { _, _ in window.retryIfNeeded() }191        .onChange(of: env.navigationRequest) { _, req in192            guard let req, NSApp.keyWindow == nil || isFrontWindow else { return }193            switch req.target { case .page(let r): window.open(r); case .destination(let d): if env.features.isAvailable(d, env: env) { window.destination = d } }194            if !env.options.noActivate { NSApp.activate(ignoringOtherApps: true) }195        }196        .onChange(of: env.account.phase) { _, phase in if phase == .signedIn { env.preferences.welcomeDone = true } }197        .onChange(of: env.serverMeta) { _, _ in if let d = pendingDestination, env.features.isAvailable(d, env: env) { pendingDestination = nil; window.destination = d } }198        .onChange(of: window.sidePanel) { _, v in env.preferences.showInspector = v == .inspector }199        .onChange(of: window.destination) { _, d in storedDestination = d.rawValue }200        .onChange(of: window.library.selection) { _, s in storedSidebar = s.stored }201        .onChange(of: window.currentNoteId) { _, id in storedNote = id ?? "" }202        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in env.lock.applicationBecameActive(); env.syncMonitor.syncNow() }203        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didResignActiveNotification)) { _ in env.lock.applicationResigned(); Task { await env.flushAll() } }204        .background(WindowAccessor { hostWindow = $0 })205    }206    @State private var hostWindow: NSWindow?207    /// A screen asked before the server said what it supports (launch, restoration): shown as soon as it is known to exist.208    @State private var pendingDestination: Destination?209    private func go(_ d: Destination) { if env.features.isAvailable(d, env: env) { window.destination = d } else { pendingDestination = d } }210    /// A side panel asked at launch needs a note beside it.211    private func openForPanel() {212        guard window.selectedNotes.isEmpty else { return }213        #if DEBUG214        if env.options.demo { window.open(DemoLibrary.noteId); return }215        #endif216        if let first = window.library.notes.first { window.open(first.id) }217    }218    /// A navigation request (deep link, quick note, Spotlight) goes to the window in front, not to every window.219    private var isFrontWindow: Bool { hostWindow == nil || hostWindow === NSApp.keyWindow || hostWindow === NSApp.mainWindow || NSApp.windows.filter({ $0.isVisible && $0.canBecomeMain }).first === hostWindow }220221    /// Puts the window back where the system saved it: destination, sidebar selection, open note.222    private func restore() {223        guard !restored else { return }; restored = true224        guard initialNote == nil, env.options.openNote == nil, env.options.route == nil else { return }225        if let item = SidebarItem(stored: storedSidebar) { window.library.selection = item }226        if let d = Destination(rawValue: storedDestination), d != .notes { go(d) }227        if !storedNote.isEmpty { didAutoSelect = true; window.selectedNotes = [storedNote] }228    }229}230231/// The feature screen of a destination, from the hosting layer.232struct FeatureDetail: View {233    @Environment(AppEnvironment.self) private var env234    @Environment(WindowModel.self) private var window235    @Environment(\.accessibilityReduceMotion) private var reduceMotion236    let destination: Destination237    var body: some View {238        Group {239            if let screen = env.features.screen(for: destination, env: env, window: window) { screen }240            else { EmptyState(symbol: destination.symbol, title: destination.title, message: "Cet écran n'est pas disponible dans cette version.") }241        }242        .id("\(destination.rawValue)-\(window.databaseId ?? "")-\(window.canvasPageId ?? "")-\(window.graphPageId ?? "")")243        .transition(.opacity)244        .animation(NVMotion.animation(.fast, reduceMotion: reduceMotion), value: destination)245        .navigationTitle(destination.title)246        .background(NVColor.bg)247        .accessibilityIdentifier("feature-" + destination.rawValue)248    }249}250251/// Gives the hosting NSWindow of a SwiftUI view.252struct WindowAccessor: NSViewRepresentable {253    let onWindow: (NSWindow?) -> Void254    func makeNSView(context: Context) -> NSView { let v = NSView(); DispatchQueue.main.async { onWindow(v.window) }; return v }255    func updateNSView(_ nsView: NSView, context: Context) { DispatchQueue.main.async { onWindow(nsView.window) } }256}257258enum MainWindowOpener { @MainActor static var open: (() -> Void)? }259260struct WindowModelKey: FocusedValueKey { typealias Value = WindowModel }261extension FocusedValues { var windowModel: WindowModel? { get { self[WindowModelKey.self] } set { self[WindowModelKey.self] = newValue } } }262263struct LockScreen: View {264    @Environment(AppEnvironment.self) private var env265    var body: some View {266        VStack(spacing: NVSpace.lg) {267            Image(systemName: "lock.fill").font(.system(size: NVFont.Style.display.size(), weight: .light)).foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)268            Text("SP Notes est verrouillé").nvFont(.h2)269            Text("Tes notes restent sur ce Mac. Déverrouille avec \(env.lock.biometryName).").nvFont(.body).foregroundStyle(NVColor.fgMuted)270            Button("Déverrouiller") { Task { await env.lock.unlock() } }.buttonStyle(.borderedProminent).controlSize(.large).keyboardShortcut(.defaultAction).disabled(env.lock.isAuthenticating)271            if let m = env.lock.message { Text(m).nvFont(.ui).foregroundStyle(NVColor.dangerText) }272        }273        .padding(NVSpace.xxxl).frame(maxWidth: .infinity, maxHeight: .infinity).background(.ultraThinMaterial)274        .task { await env.lock.unlock() }275        .accessibilityIdentifier("lock-screen")276    }277}278279extension AppEnvironment {280    /// Idempotent launch sequence shared by every window.281    func start() async {282        guard !started, !options.isHostedTest, !isBlocked else { return }283        started = true284        ImageCache.shared.onFilesChanged = { [weak self] in for s in self?.openSessions ?? [] { s.editor.textView.refreshAtoms() } }285        try? await store.resetTransientAttachmentStates()286        try? await store.releaseAllOpLeases()287        await account.start()288        #if DEBUG289        if options.demo { await DemoLibrary.seed(self) }290        #endif291        await library.start()292        await tasks.start(); await inbox.start()293        await refreshServerFeatures()294        platform.start()295        syncMonitor.start()296    }297}298
Files main
Menu

Theme