Repository Public
1// SP Notes iOS2// File: Features/Sections/FeatureSections.swift3// Description: Hosts the cross-platform screens of `SPNotesFeatures` (SPEC §8) in the shell: one hosted section per screen4// (brief, ask, server search, databases, graph, constellation, timeline, knowledge health, research, canvas),5// the `FeatureRouter` implemented over the shell's router, the attachment loader, and the PencilKit editor6// plugged into the canvas. A section is listed only when the server is known to offer what it needs.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Observation11import SPNotesCore12import SPNotesDesign13import SPNotesFeatures14import SwiftUI1516extension ShellFeatureRouter: FeatureRouter {}1718extension AppModel {19 /// Bytes of an attachment for the feature screens: the local file first, the server otherwise.20 var featureAttachments: FeatureAttachmentLoader { .standard(repositories: repositories, files: files) }21}2223enum FeatureSectionID {24 static let brief = "brief", ask = "ask", search = "search-server", graph = "graph", constellation = "constellation"25 static let timeline = "timeline", health = "health", research = "research"26}2728@MainActor29enum FeatureSections {30 /// Registers every hosted section. Called once when the application model exists (`AppRuntime`).31 static func install(in registry: HostedSectionRegistry = .shared, app: AppModel) {32 let repos = app.repositories33 func features(_ router: any SectionRouting) -> (any FeatureRouter)? { router as? ShellFeatureRouter }34 let sections: [HostedSectionEntry] = [35 HostedSectionEntry(id: FeatureSectionID.brief, title: String(localized: "Brief du jour"), symbol: "sun.max", requiredFeature: ServerFeature.brief, layout: .list, order: 10) {36 DailyBriefScreen(repositories: repos, router: features($0))37 },38 HostedSectionEntry(id: FeatureSectionID.ask, title: String(localized: "Demander"), symbol: "sparkles", requiredFeature: ServerFeature.nodesV3, layout: .wide, order: 20) {39 AskScreen(repositories: repos, router: features($0))40 },41 HostedSectionEntry(id: FeatureSectionID.search, title: String(localized: "Recherche sur le serveur"), symbol: "text.magnifyingglass", requiredFeature: ServerFeature.entities, layout: .list, order: 30) {42 UnifiedSearchScreen(repositories: repos, router: features($0))43 },44 HostedSectionEntry(id: HostedSectionID.databases, title: String(localized: "Bases de données"), symbol: "tablecells", requiredFeature: ServerFeature.entities, layout: .wide, order: 40) {45 DatabasesHost(repositories: repos, router: features($0))46 },47 HostedSectionEntry(id: HostedSectionID.canvas, title: String(localized: "Canvas"), symbol: "rectangle.3.group", requiredFeature: ServerFeature.canvas, layout: .wide, order: 50) {48 CanvasHost(app: app, router: features($0))49 },50 HostedSectionEntry(id: FeatureSectionID.graph, title: String(localized: "Graphe"), symbol: "point.3.connected.trianglepath.dotted", requiredFeature: ServerFeature.graphV2, layout: .wide, order: 60) {51 GraphScreen(repositories: repos, router: features($0))52 },53 HostedSectionEntry(id: FeatureSectionID.constellation, title: String(localized: "Constellation (Labs)"), symbol: "sparkle", requiredFeature: ServerFeature.graphV2, layout: .wide, order: 70) {54 ConstellationScreen(repositories: repos, router: features($0))55 },56 HostedSectionEntry(id: FeatureSectionID.timeline, title: String(localized: "Chronologie"), symbol: "clock.arrow.circlepath", requiredFeature: ServerFeature.events, layout: .list, order: 80) {57 TimelineScreen(repositories: repos, router: features($0))58 },59 HostedSectionEntry(id: FeatureSectionID.health, title: String(localized: "Santé des connaissances"), symbol: "heart.text.square", requiredFeature: ServerFeature.health, layout: .list, order: 90) {60 KnowledgeHealthScreen(repositories: repos, router: features($0))61 },62 HostedSectionEntry(id: FeatureSectionID.research, title: String(localized: "Références"), symbol: "books.vertical", requiredFeature: ServerFeature.entities, layout: .list, order: 100) {63 ResearchScreen(repositories: repos, router: features($0))64 },65 ]66 sections.forEach(registry.register)67 }68}6970// MARK: - Databases7172/// The databases of the workspace (local copy), then one database in `DatabaseScreen`.73struct DatabasesHost: View {74 let repositories: NotesRepositories75 let router: (any FeatureRouter)?76 @Environment(AppModel.self) private var app77 @Environment(ShellState.self) private var shell78 @State private var databases: [DatabaseInfo] = []79 @State private var selected: String?80 @State private var loaded = false8182 var body: some View {83 Group {84 if let selected {85 DatabaseScreen(repositories: repositories, databaseId: selected, router: router)86 .id(selected)87 // one back control: ours returns to the list of databases, the system's comes back with the list88 .navigationBarBackButtonHidden(true)89 .toolbar {90 ToolbarItem(placement: .topBarLeading) {91 Button { self.selected = nil } label: { Label("Toutes les bases", systemImage: "chevron.left") }.accessibilityIdentifier("databases-back")92 }93 }94 } else if databases.isEmpty {95 NVEmptyState(systemImage: "tablecells", title: String(localized: "Aucune base de données"),96 message: loaded ? String(localized: "Les bases créées sur le Web apparaissent ici après la synchronisation.") : String(localized: "Chargement…"))97 } else {98 List(databases) { database in99 Button { selected = database.id } label: {100 Label(database.name.isEmpty ? String(localized: "Sans titre") : database.name, systemImage: "tablecells").foregroundStyle(NVColor.fg)101 }102 .accessibilityIdentifier("database-\(database.id)")103 }104 .scrollContentBackground(.hidden)105 }106 }107 .background(NVColor.bg)108 .task(id: app.feed.entities("database") &+ app.feed.resetGeneration) {109 databases = (try? await repositories.databases.list()) ?? []110 loaded = true111 consumePending()112 }113 .onChange(of: shell.pendingHostedItem) { _, _ in consumePending() }114 }115116 private func consumePending() {117 guard let item = shell.pendingHostedItem, item.section == HostedSectionID.databases else { return }118 shell.pendingHostedItem = nil119 selected = item.id120 }121}122123// MARK: - Canvas124125/// The PencilKit editor of the app plugged into the canvas of SPNotesFeatures (`CanvasDrawingEditorProvider`): the canvas asks,126/// the host presents `DrawingBlockScreen` full screen, and the ink attachment it saved goes back to the canvas.127@MainActor128@Observable129final class CanvasPencilBridge {130 struct Session: Identifiable {131 let id = UUID()132 let request: CanvasDrawingEditRequest133 let node: PMNode134 }135 var session: Session?136 @ObservationIgnored private var continuation: CheckedContinuation<CanvasDrawingEditResult?, Never>?137 @ObservationIgnored private var result: CanvasDrawingEditResult?138139 /// The node handed to the PencilKit screen for a canvas drawing (pure, tested).140 static func node(for request: CanvasDrawingEditRequest) -> PMNode {141 var block = DrawingBlock(background: "white")142 if let ink = request.inkAttachmentId { block[attr: "ink"] = .string(ink) }143 block.width = Double(request.size.width)144 block.height = Double(request.size.height)145 return block.node()146 }147148 /// What goes back to the canvas for the node the PencilKit screen committed (nil = nothing drawn).149 static func result(for node: PMNode?) -> CanvasDrawingEditResult? {150 guard let node, let block = DrawingBlock(node: node), let ink = block.ink else { return nil }151 return CanvasDrawingEditResult(inkAttachmentId: ink)152 }153154 func edit(_ request: CanvasDrawingEditRequest) async -> CanvasDrawingEditResult? {155 finish() // one drawing at a time156 result = nil157 return await withCheckedContinuation { continuation in158 self.continuation = continuation159 session = Session(request: request, node: Self.node(for: request))160 }161 }162163 func commit(_ node: PMNode?) { result = Self.result(for: node) ?? result }164165 func finish() {166 session = nil167 continuation?.resume(returning: result)168 continuation = nil169 }170}171172/// The canvases of the workspace (pages of type `canvas`), then one canvas in `CanvasScreen`.173struct CanvasHost: View {174 let app: AppModel175 let router: (any FeatureRouter)?176 @Environment(ShellState.self) private var shell177 @State private var canvases: [PageSummary] = []178 @State private var selected: String?179 @State private var bridge = CanvasPencilBridge()180 @State private var loaded = false181182 var body: some View {183 Group {184 if let selected {185 CanvasScreen(repositories: app.repositories, pageId: selected, router: router, attachments: app.featureAttachments,186 drawingEditor: { [bridge] request in await bridge.edit(request) })187 .id(selected)188 .navigationBarBackButtonHidden(true)189 .toolbar {190 ToolbarItem(placement: .topBarLeading) {191 Button { self.selected = nil } label: { Label("Tous les canvas", systemImage: "chevron.left") }.accessibilityIdentifier("canvas-back")192 }193 }194 } else {195 List {196 ForEach(canvases) { page in197 Button { selected = page.id } label: {198 Label(AppModel.displayTitle(page.title), systemImage: "rectangle.3.group").foregroundStyle(NVColor.fg)199 }200 .accessibilityIdentifier("canvas-\(page.id)")201 }202 Button {203 Task {204 await app.attempt {205 selected = try await app.repositories.canvases.create(title: String(localized: "Nouveau canvas"))206 app.syncNow()207 }208 }209 } label: { Label("Nouveau canvas", systemImage: "plus") }210 .accessibilityIdentifier("canvas-new")211 }212 .scrollContentBackground(.hidden)213 .overlay { if loaded, canvases.isEmpty { EmptyView() } }214 }215 }216 .background(NVColor.bg)217 .task(id: app.feed.structure &+ app.feed.canvases) {218 canvases = ((try? await app.store.summaries(list: .all, limit: 500)) ?? []).filter { $0.type == "canvas" && $0.deletedAt == nil }219 loaded = true220 consumePending()221 }222 .onChange(of: shell.pendingHostedItem) { _, _ in consumePending() }223 .fullScreenCover(item: Binding(get: { bridge.session }, set: { if $0 == nil { bridge.finish() } })) { session in224 DrawingBlockScreen(node: session.node, context: BlockDetailContext(225 app: app, noteId: session.request.pageId, isEditable: true,226 commit: { bridge.commit($0) }, insertMarkdownBelow: { _ in }, open: { _ in }, dismiss: { bridge.finish() }))227 }228 }229230 private func consumePending() {231 guard let item = shell.pendingHostedItem, item.section == HostedSectionID.canvas else { return }232 shell.pendingHostedItem = nil233 selected = item.id234 }235}236