SPB Git

Repository Public

HostedSection.swift 7.7 KB 185 lines swift

1// SP Notes iOS2// File: Features/Sections/HostedSection.swift3// Description: The hosting layer for the sections whose screens come from `SPNotesFeatures` (databases, graph, timeline,4//              health, brief, research, canvas, ask): a small protocol, a registry consulted by the sidebar, the « Plus » list,5//              the command palette and ⌘1…9, and the router the screens navigate with. A section is shown only when its screen6//              is registered AND the server has the feature it needs — never a placeholder.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Observation11import SPNotesCore12import SwiftUI1314/// What a hosted screen can ask the shell to do (the shape of `SPNotesFeatures.FeatureRouter`; `ShellFeatureRouter` implements it).15@MainActor16protocol SectionRouting: AnyObject {17    func openPage(id: String, blockId: String?)18    func openDatabase(id: String)19    func openCanvas(pageId: String)20    func openURL(_ url: URL)21    func presentError(_ error: Error)22}2324/// How a hosted section sits in the iPad window.25enum HostedSectionLayout: Sendable, Equatable {26    /// In the middle column, a note opening in the detail column (lists: research, health, brief…).27    case list28    /// The whole area right of the sidebar (graph, canvas, timeline, databases).29    case wide30}3132@MainActor33protocol HostedSection {34    /// Stable identifier (`graph`, `timeline`, `databases`, `health`, `brief`, `research`, `canvas`, `ask`…): routes, storage, ⌘ keys.35    var id: String { get }36    var title: String { get }37    var symbol: String { get }38    /// The `ServerFeature` the section needs; nil = works with any server and offline.39    var requiredFeature: String? { get }40    var layout: HostedSectionLayout { get }41    /// Position in the lists (smaller first; ties by registration order).42    var order: Int { get }43    func makeView(router: any SectionRouting) -> AnyView44}4546extension HostedSection {47    var requiredFeature: String? { nil }48    var layout: HostedSectionLayout { .wide }49    var order: Int { 100 }5051    /// Available when no feature is needed, or when the server is KNOWN to have it (unknown = not shown: nothing to show yet).52    func isAvailable(features: ServerMeta?) -> Bool {53        guard let requiredFeature else { return true }54        return features?.has(requiredFeature) == true55    }56}5758/// A section defined by values (the usual way to register one).59struct HostedSectionEntry: HostedSection {60    let id: String61    let title: String62    let symbol: String63    var requiredFeature: String?64    var layout: HostedSectionLayout = .wide65    var order: Int = 10066    let content: @MainActor (any SectionRouting) -> AnyView6768    init<Content: View>(id: String, title: String, symbol: String, requiredFeature: String? = nil, layout: HostedSectionLayout = .wide, order: Int = 100,69                        @ViewBuilder content: @escaping @MainActor (any SectionRouting) -> Content) {70        self.id = id; self.title = title; self.symbol = symbol; self.requiredFeature = requiredFeature; self.layout = layout; self.order = order71        self.content = { AnyView(content($0)) }72    }7374    func makeView(router: any SectionRouting) -> AnyView { content(router) }75}7677/// The sections registered by the app (`HostedSectionRegistry.shared.register(…)` at launch, once their screens exist).78@MainActor79@Observable80final class HostedSectionRegistry {81    static let shared = HostedSectionRegistry()8283    private(set) var sections: [any HostedSection] = []84    /// The server features last read (`app.repositories.features()`); refreshed by the shell.85    private(set) var features: ServerMeta?8687    init() {}8889    /// Registers a section (a second registration with the same id replaces the first).90    func register(_ section: any HostedSection) {91        sections.removeAll { $0.id == section.id }92        sections.append(section)93        let indexed = sections.enumerated().sorted { ($0.element.order, $0.offset) < ($1.element.order, $1.offset) }94        sections = indexed.map(\.element)95    }9697    func unregister(id: String) { sections.removeAll { $0.id == id } }9899    func update(features: ServerMeta?) { if features != self.features { self.features = features } }100101    /// The sections to show now, in order. Empty registry → nothing anywhere.102    var available: [any HostedSection] { sections.filter { $0.isAvailable(features: features) } }103104    func section(id: String) -> (any HostedSection)? { available.first { $0.id == id } }105    /// True when a registered section can show a database page (until then a database page keeps its 1.0 screen).106    var showsDatabases: Bool { section(id: HostedSectionID.databases) != nil }107}108109/// The identifiers the app itself refers to.110enum HostedSectionID {111    static let databases = "databases"112    static let canvas = "canvas"113}114115/// The router given to hosted screens, over the window's navigation state.116@MainActor117final class ShellFeatureRouter: SectionRouting {118    private let shell: ShellState119    private let app: AppModel?120    /// What happened last, for the tests.121    private(set) var lastError: String?122    private(set) var lastURL: URL?123    var openExternal: @MainActor (URL) -> Void = { UIApplication.shared.open($0) }124125    init(shell: ShellState, app: AppModel?) {126        self.shell = shell127        self.app = app128    }129130    func openPage(id: String, blockId: String?) { shell.open(note: id, blockId: blockId) }131132    /// A database opens in the database section when one is registered; otherwise as a page (its 1.0 screen: « Ouvrir sur le web »).133    func openDatabase(id: String) {134        if shell.sections.showsDatabases { shell.pendingHostedItem = HostedItem(section: HostedSectionID.databases, id: id); shell.go(to: .hosted(HostedSectionID.databases)) }135        else { shell.open(note: id) }136    }137138    func openCanvas(pageId: String) {139        if shell.sections.section(id: HostedSectionID.canvas) != nil { shell.pendingHostedItem = HostedItem(section: HostedSectionID.canvas, id: pageId); shell.go(to: .hosted(HostedSectionID.canvas)) }140        else { shell.open(note: pageId) }141    }142143    /// Links to pages of the app navigate; anything else goes to the system (never a web view).144    func openURL(_ url: URL) {145        lastURL = url146        if let link = DeepLink(url: url), let route = AppModel.route(for: link) {147            if case .note(let id, let blockId) = route { shell.open(note: id, blockId: blockId); return }148            if let app { app.routes.dispatch(route); return }149        }150        openExternal(url)151    }152153    func presentError(_ error: Error) {154        let message = AppModel.describe(error)155        lastError = message156        if let app { app.banner = message } else { shell.show(message) }157    }158}159160/// The item a hosted section should show when it appears (a database, a canvas page).161struct HostedItem: Equatable, Sendable {162    var section: String163    var id: String164}165166/// Shows a hosted section, or nothing more than an explanation when it went away (the server lost the feature).167struct HostedSectionView: View {168    let id: String169    @Environment(AppModel.self) private var app170    @Environment(ShellState.self) private var shell171172    var body: some View {173        if let section = shell.sections.section(id: id) {174            section.makeView(router: shell.featureRouter(app: app))175                // the shared screens draw their own title row (FEATURES.md §1.2): no second, large title above it176                .navigationTitle(section.title)177                .navigationBarTitleDisplayMode(.inline)178                .accessibilityElement(children: .contain)179                .accessibilityIdentifier("hosted-\(id)")180        } else {181            EmptyStateView(symbol: "square.dashed", title: "Section indisponible", message: "Cette section n’est pas proposée par le serveur auquel tu es connecté.")182        }183    }184}185
Files main
Menu

Theme