SPB Git

Repository Public

SemanticZoom.swift 13.1 KB 281 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Knowledge/SemanticZoom.swift3// Description: Semantic zoom of a page (API-NEXT §4.9): level 1 = AI synopsis (read from the server's cache by default;4//              generated only on an explicit action), level 2 = outline computed without a model, level 3 = the full5//              page (the host's editor). `SemanticZoomControl` is the level switch, `PageOutlineView` renders levels 16//              and 2 and hands level 3 back to the host.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPNotesAPI13import SPNotesDesign14import SPNotesSync15import SwiftUI1617public enum SemanticZoomLevel: Int, Sendable, Hashable, CaseIterable, Identifiable {18    case synopsis = 1, outline = 2, full = 319    public var id: Int { rawValue }2021    public var title: String {22        switch self {23        case .synopsis: return L("Synopsis")24        case .outline: return L("Plan")25        case .full: return L("Page")26        }27    }2829    public var symbol: String {30        switch self {31        case .synopsis: return "text.quote"32        case .outline: return "list.bullet.indent"33        case .full: return "doc.plaintext"34        }35    }36}3738@Observable @MainActor39public final class SemanticZoomModel {40    public let pageId: String41    public private(set) var level: SemanticZoomLevel42    public private(set) var outline: PageZoom?43    public private(set) var outlinePhase: LoadPhase = .idle44    public private(set) var outlineFreshness: Freshness?45    public private(set) var synopsis: ZoomSynopsis?46    public private(set) var synopsisPhase: LoadPhase = .idle47    public private(set) var synopsisFreshness: Freshness?48    public private(set) var isGenerating = false49    public var actionFailure: FeatureFailure?5051    private let repository: KnowledgeRepository52    private weak var router: (any FeatureRouter)?5354    public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, pageId: String, level: SemanticZoomLevel = .outline, now: @escaping @Sendable () -> Date = { Date() }) {55        repository = repositories.knowledge56        self.router = router57        self.pageId = pageId58        self.level = level59    }6061    public var sections: [ZoomSection] { outline?.sections ?? [] }62    /// The phase of what the current level shows.63    public var phase: LoadPhase { level == .synopsis ? synopsisPhase : (level == .outline ? outlinePhase : .loaded) }64    public var freshness: Freshness? { level == .synopsis ? synopsisFreshness : (level == .outline ? outlineFreshness : nil) }65    public var hasSynopsis: Bool { synopsis?.status == SynopsisStatus.ready && !(synopsis?.synopsis ?? "").isEmpty }6667    public func load() async { await load(level) }6869    public func setLevel(_ newLevel: SemanticZoomLevel) async {70        level = newLevel71        await load(newLevel)72    }7374    private func load(_ level: SemanticZoomLevel) async {75        switch level {76        case .full: break77        case .outline:78            outlinePhase = .loading79            do {80                let cached = try await repository.zoom(pageId: pageId, level: 2)81                outline = cached.value82                outlineFreshness = Freshness(cached)83                outlinePhase = .loaded84            } catch { outlinePhase = .failed(FeatureFailure(error)) }85        case .synopsis:86            // Never spends: only what the server already has.87            synopsisPhase = .loading88            do {89                let cached = try await repository.synopsis(pageId: pageId, cachedOnly: true)90                synopsis = cached.value91                synopsisFreshness = Freshness(cached)92                synopsisPhase = .loaded93            } catch { synopsisPhase = .failed(FeatureFailure(error)) }94        }95    }9697    /// Asks the server to write the synopsis: **one model call, only from the explicit button**.98    @discardableResult99    public func generateSynopsis() async -> Bool {100        guard !isGenerating else { return false }101        isGenerating = true102        actionFailure = nil103        defer { isGenerating = false }104        do {105            let cached = try await repository.synopsis(pageId: pageId, cachedOnly: false, policy: .networkOnly)106            synopsis = cached.value107            synopsisFreshness = Freshness(cached)108            synopsisPhase = .loaded109            return true110        } catch {111            actionFailure = FeatureFailure(error)112            return false113        }114    }115116    public func open(_ section: ZoomSection) { router?.openPage(id: pageId, blockId: section.blockId) }117}118119/// The three-level switch. Put it in the editor's toolbar; `onChange` lets the host show its editor at level 3.120public struct SemanticZoomControl: View {121    private let level: SemanticZoomLevel122    private let onChange: (SemanticZoomLevel) -> Void123124    public init(level: SemanticZoomLevel, onChange: @escaping (SemanticZoomLevel) -> Void) {125        self.level = level126        self.onChange = onChange127    }128129    public var body: some View {130        HStack(spacing: NVSpace.xxs) {131            ForEach(SemanticZoomLevel.allCases) { item in132                Button { onChange(item) } label: {133                    HStack(spacing: NVSpace.xs) {134                        Image(systemName: item.symbol).accessibilityHidden(true)135                        Text(item.title)136                    }137                    .nvFont(.uiStrong)138                    .foregroundStyle(item == level ? NVColor.accentFg : NVColor.fgMuted)139                    .padding(.horizontal, NVSpace.md)140                    .frame(minHeight: 32)141                    .background(item == level ? NVColor.accent : Color.clear, in: NVRadius.shape(NVRadius.sm))142                    .contentShape(Rectangle())143                }144                .buttonStyle(.plain)145                .accessibilityLabel(LF("Niveau de zoom : %@", item.title))146                .accessibilityAddTraits(item == level ? .isSelected : [])147            }148        }149        .padding(NVSpace.xxs)150        .background(NVColor.bgSunken, in: NVRadius.shape(NVRadius.md))151        .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.line, lineWidth: 1))152        .nvAnimation(.fast, value: level)153    }154}155156/// Levels 1 and 2 of a page, with the control on top. At level 3 it shows `full` (the host's editor) or, without one,157/// a button that opens the page.158public struct PageOutlineView<Full: View>: View {159    @State private var model: SemanticZoomModel160    private let showsControl: Bool161    private let full: () -> Full162163    public init(model: SemanticZoomModel, showsControl: Bool = true, @ViewBuilder full: @escaping () -> Full) {164        _model = State(initialValue: model)165        self.showsControl = showsControl166        self.full = full167    }168169    public var body: some View {170        FeatureLayoutReader { sizeClass in171            VStack(alignment: .leading, spacing: NVSpace.md) {172                if showsControl {173                    SemanticZoomControl(level: model.level) { level in Task { await model.setLevel(level) } }174                }175                FeatureStatusBanner(failure: model.phase.failure, freshness: model.freshness, retry: { Task { await model.load() } })176                NVSemanticZoom(level: model.level) { level in177                    switch level {178                    case .synopsis: synopsis179                    case .outline: outline180                    case .full: full()181                    }182                }183            }184            .padding(sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)185            .background(NVColor.bg)186        }187        .task { if model.phase == .idle { await model.load() } }188    }189190    @ViewBuilder191    private var synopsis: some View {192        ScrollView {193            VStack(alignment: .leading, spacing: NVSpace.md) {194                if model.hasSynopsis, let synopsis = model.synopsis {195                    FeatureAICard(model: synopsis.model, title: L("Synopsis")) {196                        Text(synopsis.synopsis ?? "").nvFont(.reading).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)197                        HStack {198                            if let at = synopsis.generatedAt { Text(LF("Rédigé le %@", FeatureFormat.dayTime(at))).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }199                            Spacer()200                        }201                    }202                } else if model.synopsisPhase.isLoading || model.synopsisPhase == .idle {203                    NVProgressDots().frame(maxWidth: .infinity).padding(.vertical, NVSpace.xl)204                } else if model.synopsisPhase.failure == nil {205                    VStack(alignment: .leading, spacing: NVSpace.sm) {206                        HStack(spacing: NVSpace.sm) { NVAIBadge(style: .compact); Text(L("Pas encore de synopsis")).nvFont(.uiStrong).foregroundStyle(NVColor.fg) }207                        Text(model.synopsis?.status == SynopsisStatus.empty ? L("La page est vide : il n'y a rien à résumer.")208                            : L("Le synopsis est rédigé par un modèle d'IA, une fois, puis conservé tant que la page ne change pas. Il n'est demandé que sur votre action."))209                            .nvFont(.ui).foregroundStyle(NVColor.fgMuted)210                        if model.synopsis?.status != SynopsisStatus.empty {211                            if model.isGenerating { NVProgressDots(tone: .ai) } else { FeatureButton(L("Générer le synopsis (IA, payant)"), systemImage: "sparkles", kind: .ai) { Task { await model.generateSynopsis() } } }212                        }213                    }214                    .padding(NVSpace.lg)215                    .frame(maxWidth: .infinity, alignment: .leading)216                    .nvCard()217                }218                if let failure = model.actionFailure { FeatureStatusBanner(failure: failure, freshness: nil) }219            }220            .frame(maxWidth: NVSpace.readingMeasure, alignment: .leading)221        }222    }223224    @ViewBuilder225    private var outline: some View {226        if model.sections.isEmpty {227            if model.outlinePhase.isLoading || model.outlinePhase == .idle {228                NVProgressDots().frame(maxWidth: .infinity).padding(.vertical, NVSpace.xl)229            } else if model.outlinePhase.failure == nil {230                NVEmptyState(systemImage: "list.bullet.indent", title: L("Aucun plan"), message: L("Cette page n'a pas encore de titres ni de texte."))231            }232        } else {233            ScrollView {234                VStack(alignment: .leading, spacing: NVSpace.xs) {235                    if let title = model.outline?.title { Text(KnowledgeVocabulary.title(title)).nvFont(.h2).foregroundStyle(NVColor.fg).padding(.bottom, NVSpace.sm) }236                    ForEach(Array(model.sections.enumerated()), id: \.offset) { index, section in237                        Button { model.open(section) } label: {238                            VStack(alignment: .leading, spacing: NVSpace.xxs) {239                                Text(section.heading ?? L("Introduction"))240                                    .nvFont(section.level <= 1 ? .h3 : .uiStrong)241                                    .foregroundStyle(section.heading == nil ? NVColor.fgMuted : NVColor.fg)242                                    .multilineTextAlignment(.leading)243                                if let sentence = section.firstSentence, !sentence.isEmpty {244                                    Text(sentence).nvFont(.body).foregroundStyle(NVColor.fgMuted).lineLimit(3).multilineTextAlignment(.leading)245                                }246                                if let words = section.words { Text(LF("%lld mots", words)).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }247                            }248                            .padding(.leading, CGFloat(max(0, section.level - 1)) * NVSpace.lg)249                            .padding(.vertical, NVSpace.sm)250                            .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)251                            .contentShape(Rectangle())252                        }253                        .buttonStyle(.plain)254                        .nvBlockReveal(index: index)255                        .accessibilityHint(L("Ouvre la page à cette section"))256                        if index < model.sections.count - 1 { Divider() }257                    }258                }259                .frame(maxWidth: NVSpace.readingMeasure, alignment: .leading)260            }261        }262    }263}264265public extension PageOutlineView where Full == PageOutlineOpenButton {266    /// Without an editor to show at level 3: a button that opens the page through the router.267    init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, pageId: String, level: SemanticZoomLevel = .outline) {268        self.init(model: SemanticZoomModel(repositories: repositories, router: router, pageId: pageId, level: level)) {269            PageOutlineOpenButton { router?.openPage(id: pageId, blockId: nil) }270        }271    }272}273274public struct PageOutlineOpenButton: View {275    let action: @MainActor () -> Void276    public init(action: @escaping @MainActor () -> Void) { self.action = action }277    public var body: some View {278        NVEmptyState(systemImage: "doc.plaintext", title: L("Page complète"), message: L("Le texte intégral s'ouvre dans l'éditeur."), actionTitle: L("Ouvrir la page"), action: { action() })279    }280}281
Files main
Menu

Theme