Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Hosting/FeaturesHost.swift3// Description: Hosts the cross-platform screens of SPNotesFeatures in the macOS shell: the window is the FeatureRouter, each sidebar destination maps to a library screen (brief, databases, canvas, graph, constellation, timeline, health, research, ask) or to this app's own Tasks / Inbox / Search screens, and a destination is listed only when the server announces its feature.4import SwiftUI5import SPNotesCore6import SPNotesAPI7import SPNotesStore8import SPNotesSync9import SPNotesDesign10import SPNotesFeatures1112/// The window is the router of the screens it hosts (SPEC §8): they never navigate by themselves.13extension WindowModel: FeatureRouter {14 func openDatabase(id: String) { databaseId = id; destination = .databases }15 func openCanvas(pageId: String) { canvasPageId = pageId; destination = .canvas }16 func presentError(_ error: Error) { presentError(FeatureFailure(error).message) }17}1819struct FeaturesHost: FeatureHosting {20 /// The server feature a destination needs; nil = works from the local store alone.21 static func requirement(_ d: Destination) -> String? {22 switch d {23 case .notes, .tasks, .inbox, .search: nil24 case .today: ServerFeature.brief25 case .graph: ServerFeature.graphV226 case .constellation: ServerFeature.graphV227 case .timeline: ServerFeature.events28 case .health: ServerFeature.health29 case .canvas: ServerFeature.canvas30 // routes that exist since 2.x: shown as soon as a server is known at all31 case .databases, .research, .ask: ""32 }33 }3435 func isAvailable(_ destination: Destination, env: AppEnvironment) -> Bool {36 guard let need = Self.requirement(destination) else { return true }37 // a screen fed by the server is listed once that server said it has it (the answer is remembered offline)38 guard let meta = env.serverMeta, env.account.phase != .local else { return false }39 if destination == .ask, !env.preferences.aiEnabled { return false }40 return need.isEmpty || meta.has(need)41 }4243 func screen(for destination: Destination, env: AppEnvironment, window: WindowModel) -> AnyView? {44 guard isAvailable(destination, env: env) else { return nil }45 let repos = env.repositories46 switch destination {47 case .notes: return nil48 case .tasks: return AnyView(SPNotes.TasksScreen(model: env.tasks, router: window))49 case .inbox: return AnyView(SPNotes.InboxScreen(model: env.inbox, router: window))50 case .search: return AnyView(SearchScreen(router: window))51 case .today: return AnyView(DailyBriefScreen(repositories: repos, router: window))52 case .graph: return AnyView(GraphScreen(repositories: repos, router: window, view: window.graphPageId == nil ? GraphView.global : GraphView.local, pageId: window.graphPageId))53 case .constellation: return AnyView(ConstellationScreen(repositories: repos, router: window))54 case .timeline: return AnyView(TimelineScreen(repositories: repos, router: window, scope: .workspace))55 case .health: return AnyView(KnowledgeHealthScreen(repositories: repos, router: window))56 case .research: return AnyView(ResearchScreen(repositories: repos, router: window, scope: .library))57 case .ask: return AnyView(AskScreen(repositories: repos, router: window, context: Self.askContext(window)))58 case .databases:59 if let id = window.databaseId { return AnyView(DatabaseHost(databaseId: id)) }60 return AnyView(DatabaseList())61 case .canvas:62 if let id = window.canvasPageId { return AnyView(CanvasHost(pageId: id)) }63 return AnyView(CanvasList())64 }65 }6667 func badge(for destination: Destination, env: AppEnvironment) -> Int? {68 switch destination {69 case .tasks: env.tasks.openCount > 0 ? env.tasks.openCount : nil70 case .inbox: env.library.counts.inbox > 0 ? env.library.counts.inbox : nil71 default: nil72 }73 }7475 /// The note in front (and its selection) become the page and selection scopes of « Demander ».76 static func askContext(_ window: WindowModel) -> AskContext {77 guard let s = window.session else { return AskContext() }78 let v = s.editor.textView; let sel = v.selectedRange()79 let selection = sel.length > 0 ? String(v.selectedMarkdown().trimmingCharacters(in: .whitespacesAndNewlines).prefix(20_000)) : nil80 return AskContext(pageId: s.id, pageTitle: Format.title(s.title), selection: selection, selectionBlockId: sel.length > 0 ? v.paraStyle(at: sel.location).blockID : nil)81 }82}8384extension AppEnvironment {85 /// Files of the feature screens and block views: read from this Mac (downloaded when missing); new files are stored86 /// on this Mac first and uploaded by the synchronisation, so a drawing or a recording can be made offline.87 func attachmentLoader(pageId: String?) -> FeatureAttachmentLoader {88 let standard = FeatureAttachmentLoader.standard(repositories: repositories, files: files)89 return FeatureAttachmentLoader(load: { id in try await standard.data(id: id) }, upload: { [weak self] data, filename, _, page in90 guard let self, let target = page ?? pageId else { return try await standard.upload(data, filename: filename, mimeType: "application/octet-stream", pageId: page) }91 return try await MainActor.run { self }.storeLocally(data, filename: filename, pageId: target)92 })93 }94 fileprivate func storeLocally(_ data: Data, filename: String, pageId: String) async throws -> String {95 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spn-new-\(UUID().uuidString)", isDirectory: true)96 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true); defer { try? FileManager.default.removeItem(at: dir) }97 let url = dir.appendingPathComponent(AttachmentService.sanitizedName(filename)); try data.write(to: url)98 return try await AttachmentService(env: self).importFile(url, pageId: pageId).id99 }100}101102/// A database: the library screen, with a way back to the list.103struct DatabaseHost: View {104 @Environment(AppEnvironment.self) private var env105 @Environment(WindowModel.self) private var window106 let databaseId: String107 var body: some View {108 DatabaseScreen(repositories: env.repositories, databaseId: databaseId, router: window)109 .toolbar { ToolbarItem(placement: .navigation) { Button { window.databaseId = nil } label: { Label("Toutes les bases", systemImage: "chevron.left") }.help("Toutes les bases de données") } }110 .accessibilityIdentifier("database-screen")111 }112}113114/// The databases of the workspace (local copy, readable offline).115struct DatabaseList: View {116 @Environment(AppEnvironment.self) private var env117 @Environment(WindowModel.self) private var window118 @State private var databases: [DatabaseInfo] = []119 @State private var loaded = false120 var body: some View {121 VStack(spacing: 0) {122 PanelHeader(title: "Bases de données", subtitle: databases.isEmpty ? nil : databases.count == 1 ? "1 base" : "\(databases.count) bases").padding(.horizontal, NVSpace.xl).padding(.top, NVSpace.xl).padding(.bottom, NVSpace.md)123 Divider().overlay(NVColor.line)124 if databases.isEmpty, loaded { NVEmptyState(systemImage: "tablecells", title: "Aucune base de données", message: "Les bases se créent sur le Web (« / » puis « Base de données ») et arrivent ici avec la synchronisation ; elles se consultent hors ligne et se modifient en ligne.").frame(maxHeight: .infinity) }125 else {126 ScrollView { LazyVStack(spacing: NVSpace.sm) { ForEach(Array(databases.enumerated()), id: \.element.id) { i, d in127 Button { window.databaseId = d.id } label: {128 HStack(spacing: NVSpace.md) { Text(d.icon ?? "🗂️"); VStack(alignment: .leading, spacing: NVSpace.xxs) { Text(d.name.isEmpty ? "Sans titre" : d.name).nvFont(.h3); if let t = d.description, !t.isEmpty { Text(t).nvFont(.ui).foregroundStyle(NVColor.fgMuted).lineLimit(2) } }; Spacer(); Image(systemName: "chevron.right").foregroundStyle(NVColor.fgMuted) }129 .padding(NVSpace.lg).nvCard(radius: NVRadius.md).contentShape(Rectangle())130 }.buttonStyle(.plain).nvBlockReveal(index: i).accessibilityIdentifier("database-row")131 } }.padding(NVSpace.xl).frame(maxWidth: NVSpace.readingMeasure + NVSpace.huge).frame(maxWidth: .infinity) }132 }133 }134 .background(NVColor.bg)135 .task { databases = (try? await env.repositories.databases.list()) ?? []; loaded = true }136 .accessibilityIdentifier("database-list")137 }138}139140/// A canvas page in the library's infinite canvas.141struct CanvasHost: View {142 @Environment(AppEnvironment.self) private var env143 @Environment(WindowModel.self) private var window144 let pageId: String145 var body: some View {146 CanvasScreen(repositories: env.repositories, pageId: pageId, router: window, attachments: env.attachmentLoader(pageId: pageId))147 .toolbar { ToolbarItem(placement: .navigation) { Button { window.canvasPageId = nil } label: { Label("Tous les canvas", systemImage: "chevron.left") }.help("Tous les canvas") } }148 .accessibilityIdentifier("canvas-screen")149 }150}151152struct CanvasList: View {153 @Environment(AppEnvironment.self) private var env154 @Environment(WindowModel.self) private var window155 @State private var canvases: [PageSummary] = []156 @State private var loaded = false157 @State private var creating = false158 var body: some View {159 VStack(spacing: 0) {160 PanelHeader(title: "Canvas", subtitle: canvases.isEmpty ? nil : canvases.count == 1 ? "1 canvas" : "\(canvases.count) canvas") {161 Button { Task { await create() } } label: { Label("Nouveau canvas", systemImage: "plus") }.disabled(creating).accessibilityIdentifier("canvas-new")162 }.padding(.horizontal, NVSpace.xl).padding(.top, NVSpace.xl).padding(.bottom, NVSpace.md)163 Divider().overlay(NVColor.line)164 if canvases.isEmpty, loaded { NVEmptyState(systemImage: "square.on.square.dashed", title: "Aucun canvas", message: "Un canvas est une page libre : cartes de texte, notes, images, liens et flèches. Il se modifie hors ligne et se fusionne à la synchronisation.", actionTitle: "Nouveau canvas") { Task { await create() } }.frame(maxHeight: .infinity) }165 else {166 ScrollView { LazyVStack(spacing: NVSpace.sm) { ForEach(Array(canvases.enumerated()), id: \.element.id) { i, c in167 Button { window.canvasPageId = c.id } label: {168 HStack(spacing: NVSpace.md) { Image(systemName: "square.on.square.dashed").foregroundStyle(NVColor.accent); Text(Format.title(c.title)).nvFont(.h3); Spacer(); Text(Format.short(c.updatedAt)).nvFont(.micro).foregroundStyle(NVColor.fgMuted); SyncDot(state: c.syncState) }169 .padding(NVSpace.lg).nvCard(radius: NVRadius.md).contentShape(Rectangle())170 }.buttonStyle(.plain).nvBlockReveal(index: i).accessibilityIdentifier("canvas-row")171 } }.padding(NVSpace.xl).frame(maxWidth: NVSpace.readingMeasure + NVSpace.huge).frame(maxWidth: .infinity) }172 }173 }174 .background(NVColor.bg)175 .task(id: env.library.counts.all) { canvases = ((try? await env.store.summaries(list: .all, limit: 5000)) ?? []).filter { $0.type == "canvas" }; loaded = true }176 .accessibilityIdentifier("canvas-list")177 }178 private func create() async {179 creating = true; defer { creating = false }180 do { let id = try await env.repositories.canvases.create(title: "Nouveau canvas"); env.syncMonitor.localChange(); window.canvasPageId = id }181 catch { window.presentError(error) }182 }183}184