SPB Git

Repository Public

GraphScreen.swift 28.3 KB 546 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Knowledge/GraphScreen.swift3// Description: The knowledge graph screen (SPEC §8): seven views, typed relations, insights. Regular = interactive canvas4//              + inspector; compact = a focus card, the neighbours as a list and a mini-graph (a phone design, not a5//              shrunken canvas).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesAPI10import SPNotesDesign11import SPNotesSync12import SwiftUI1314public struct GraphScreen: View {15    @State private var model: GraphModel16    @State private var showsInsights = false1718    public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, view: String = GraphView.global, pageId: String? = nil) {19        _model = State(initialValue: GraphModel(repositories: repositories, router: router, view: view, pageId: pageId))20    }2122    /// - Parameter showsInsights: opens the inspector on the insights tab (regular layout).23    public init(model: GraphModel, showsInsights: Bool = false) {24        _model = State(initialValue: model)25        _showsInsights = State(initialValue: showsInsights)26    }2728    public var body: some View {29        FeatureScaffold(title: L("Graphe"), subtitle: subtitle, phase: model.phase, freshness: model.freshness,30                        retry: { Task { await model.load() } },31                        actions: {32                            FeatureIconButton("arrow.clockwise", label: L("Actualiser")) { Task { await model.load(); await model.loadInsights() } }33                        }) { sizeClass in34            VStack(alignment: .leading, spacing: 0) {35                GraphViewPicker(model: model)36                if let failure = model.actionFailure {37                    FeatureStatusBanner(failure: failure, freshness: nil).padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)38                }39                if sizeClass.isCompact { GraphCompactBody(model: model) } else { GraphRegularBody(model: model, showsInsights: $showsInsights) }40            }41        }42        .task {43            if model.phase == .idle { await model.load() }44            if model.insightsPhase == .idle { await model.loadInsights() }45        }46        #if os(iOS)47        .sheet(isPresented: Binding(get: { model.form != nil }, set: { if !$0 { model.form = nil } })) {48            ScrollView { GraphRelationFormView(model: model).padding(NVSpace.lg) }.background(NVColor.bg).presentationDetents([.medium, .large])49        }50        #endif51    }5253    private var subtitle: String? {54        guard let stats = model.graph?.stats else { return nil }55        var parts = [LF("%lld éléments", model.nodes.count), LF("%lld liens", stats.edges)]56        if let suggested = stats.suggested, suggested > 0 { parts.append(LF("%lld suggestion(s)", suggested)) }57        return parts.joined(separator: " · ")58    }59}6061/// The seven views + the two display options.62struct GraphViewPicker: View {63    @Environment(\.featureSizeClass) private var sizeClass64    @Bindable var model: GraphModel6566    var body: some View {67        ScrollView(.horizontal, showsIndicators: false) {68            HStack(spacing: NVSpace.sm) {69                ForEach(GraphView.all, id: \.self) { view in70                    NVChip(KnowledgeVocabulary.viewTitle(view), systemImage: KnowledgeVocabulary.viewSymbol(view), tone: .accent, isSelected: model.view == view) {71                        Task { await model.setView(view) }72                    }73                    .accessibilityAddTraits(model.view == view ? .isSelected : [])74                }75                Divider().frame(height: 18)76                NVChip(L("Suggestions"), systemImage: "sparkles", tone: .ai, isSelected: model.includeSuggestions) {77                    Task { await model.setIncludeSuggestions(!model.includeSuggestions) }78                }79                .accessibilityLabel(model.includeSuggestions ? L("Masquer les suggestions de l'IA") : L("Afficher les suggestions de l'IA"))80                NVChip(L("Sans orphelins"), systemImage: "circle.dotted", isSelected: model.hideOrphans) {81                    Task { await model.setHideOrphans(!model.hideOrphans) }82                }83            }84            .padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)85            .padding(.bottom, NVSpace.md)86        }87    }88}8990// MARK: - Regular9192struct GraphRegularBody: View {93    @Bindable var model: GraphModel94    @Binding var showsInsights: Bool9596    var body: some View {97        HStack(alignment: .top, spacing: NVSpace.lg) {98            VStack(spacing: NVSpace.md) {99                FeaturePhaseView(phase: model.phase, hasData: !model.isEmpty, retry: { Task { await model.load() } }) {100                    GraphEmptyState(model: model)101                } content: {102                    ZStack(alignment: .bottomTrailing) {103                        GraphSurface(scene: GraphScene.make(nodes: model.nodes, edges: model.edges, positions: model.positions, selectedNodeId: model.selectedNodeId,104                                                            selectedEdgeId: model.selectedEdgeId, labelLimit: 14),105                                     viewport: model.viewport, generation: model.layoutGeneration,106                                     onTap: { model.tap(at: $0, in: $1) }, onPan: { model.pan(by: $0) }, onZoom: { model.zoom(by: $0, anchor: $1, in: $2) },107                                     accessibilitySummary: LF("Graphe de %lld éléments et %lld liens. Utilisez la liste de l'inspecteur pour parcourir les voisins.", model.nodes.count, model.edges.count))108                        GeometryReader { proxy in109                            NVToolbarGlass {110                                FeatureIconButton("minus.magnifyingglass", label: L("Zoom arrière")) { model.zoom(by: 1 / 1.3, anchor: CGPoint(x: proxy.size.width / 2, y: proxy.size.height / 2), in: proxy.size) }111                                FeatureIconButton("plus.magnifyingglass", label: L("Zoom avant")) { model.zoom(by: 1.3, anchor: CGPoint(x: proxy.size.width / 2, y: proxy.size.height / 2), in: proxy.size) }112                                FeatureIconButton("arrow.up.left.and.arrow.down.right", label: L("Tout afficher")) { model.resetViewport() }113                            }114                            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)115                            .padding(NVSpace.md)116                        }117                        GraphLegend().frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading).padding(NVSpace.md).allowsHitTesting(false)118                    }119                }120                .frame(maxWidth: .infinity, maxHeight: .infinity)121                .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.lg))122                .overlay(NVRadius.shape(NVRadius.lg).strokeBorder(NVColor.line, lineWidth: 1))123                .clipShape(NVRadius.shape(NVRadius.lg))124                if model.view == GraphView.timeline, let buckets = model.graph?.buckets, !buckets.isEmpty {125                    GraphBucketsStrip(buckets: buckets, range: model.graph?.range)126                }127            }128            VStack(alignment: .leading, spacing: NVSpace.md) {129                HStack(spacing: NVSpace.sm) {130                    NVChip(L("Sélection"), systemImage: "scope", tone: .accent, isSelected: !showsInsights) { showsInsights = false }131                    NVChip(insightsTitle, systemImage: "lightbulb", tone: .accent, isSelected: showsInsights) { showsInsights = true }132                }133                ScrollView {134                    if showsInsights { GraphInsightsPanel(model: model) } else if model.form != nil { GraphRelationFormView(model: model) } else { GraphSelectionPanel(model: model) }135                }136            }137            .frame(width: 340)138        }139        .padding(.horizontal, NVSpace.xl)140        .padding(.bottom, NVSpace.xl)141    }142143    private var insightsTitle: String {144        let count = model.insights?.insights.count ?? 0145        return count > 0 ? LF("Constats (%lld)", count) : L("Constats")146    }147}148149struct GraphLegend: View {150    var body: some View {151        VStack(alignment: .leading, spacing: NVSpace.xs) {152            legend(NVColor.accent, L("Page"), dashed: false, line: false)153            legend(NVColor.warning, L("Concept"), dashed: false, line: false)154            legend(NVColor.success, L("Référence"), dashed: false, line: false)155            legend(NVColor.accent, L("Relation typée"), dashed: false, line: true)156            legend(NVColor.ai, L("Suggestion de l'IA"), dashed: true, line: true)157        }158        .padding(NVSpace.sm)159        .background(NVColor.bg.opacity(0.85), in: NVRadius.shape(NVRadius.sm))160        .accessibilityElement(children: .combine)161    }162163    private func legend(_ colour: Color, _ text: String, dashed: Bool, line: Bool) -> some View {164        HStack(spacing: NVSpace.sm) {165            if line {166                Rectangle().fill(.clear).frame(width: 18, height: 2)167                    .overlay(Line().stroke(colour, style: StrokeStyle(lineWidth: 2, dash: dashed ? [4, 3] : [])))168            } else {169                Circle().fill(colour).frame(width: 9, height: 9).frame(width: 18)170            }171            Text(text).nvFont(.micro).foregroundStyle(NVColor.fgMuted)172        }173    }174175    private struct Line: Shape {176        func path(in rect: CGRect) -> Path {177            var path = Path()178            path.move(to: CGPoint(x: rect.minX, y: rect.midY))179            path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))180            return path181        }182    }183}184185/// Activity per day of the `timeline` view (pages created / updated, edges).186struct GraphBucketsStrip: View {187    let buckets: [GraphBucket]188    let range: GraphRange?189190    var body: some View {191        let peak = max(1, buckets.map { $0.created + $0.updated + $0.edges }.max() ?? 1)192        VStack(alignment: .leading, spacing: NVSpace.xs) {193            HStack {194                Text(L("Activité par jour")).nvFont(.uiStrong).foregroundStyle(NVColor.fg)195                Spacer()196                if let range { Text(FeatureFormat.day(range.from) + " – " + FeatureFormat.day(range.to)).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }197            }198            HStack(alignment: .bottom, spacing: 2) {199                ForEach(buckets, id: \.date) { bucket in200                    let total = bucket.created + bucket.updated + bucket.edges201                    RoundedRectangle(cornerRadius: 2, style: .continuous)202                        .fill(total == 0 ? NVColor.line : NVColor.accent)203                        .frame(height: max(2, 44 * CGFloat(total) / CGFloat(peak)))204                        .frame(maxWidth: .infinity)205                        .accessibilityLabel(LF("%@ : %lld créées, %lld modifiées, %lld liens", bucket.date, bucket.created, bucket.updated, bucket.edges))206                }207            }208            .frame(height: 44, alignment: .bottom)209        }210        .padding(NVSpace.md)211        .nvCard()212    }213}214215struct GraphEmptyState: View {216    let model: GraphModel217    var body: some View {218        if model.needsFocus {219            NVEmptyState(systemImage: "scope", title: L("Choisissez une page"),220                         message: L("Cette vue part d'une page : sélectionnez un élément dans la vue globale, puis revenez ici."))221        } else {222            NVEmptyState(systemImage: "circle.grid.cross", title: L("Rien à relier pour l'instant"),223                         message: L("Les liens entre vos pages, vos références et vos concepts apparaîtront ici."))224        }225    }226}227228// MARK: - Compact229230struct GraphCompactBody: View {231    @Bindable var model: GraphModel232233    var body: some View {234        FeaturePhaseView(phase: model.phase, hasData: !model.isEmpty, retry: { Task { await model.load() } }) {235            GraphEmptyState(model: model)236        } content: {237            ScrollView {238                VStack(alignment: .leading, spacing: NVSpace.lg) {239                    GraphSurface(scene: GraphScene.make(nodes: model.nodes, edges: model.edges, positions: model.positions, selectedNodeId: model.focusNode?.id,240                                                        selectedEdgeId: nil, labelLimit: 0),241                                 viewport: GraphViewport(), generation: model.layoutGeneration, showsLabels: false, nodeScale: 0.6,242                                 onTap: { location, size in243                                     if let id = GraphViewport().hitTest(location, positions: model.positions, in: size, tolerance: 28) { model.select(nodeId: id) }244                                 },245                                 accessibilitySummary: LF("Mini-graphe de %lld éléments. Touchez un point pour le mettre au centre de la liste.", model.nodes.count))246                        .frame(height: 210)247                        .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.lg))248                        .overlay(NVRadius.shape(NVRadius.lg).strokeBorder(NVColor.line, lineWidth: 1))249                    if model.view == GraphView.timeline, let buckets = model.graph?.buckets, !buckets.isEmpty {250                        GraphBucketsStrip(buckets: buckets, range: model.graph?.range)251                    }252                    GraphSelectionPanel(model: model, focusFallback: true)253                    GraphInsightsPanel(model: model)254                }255                .padding(.horizontal, NVSpace.lg)256                .padding(.bottom, NVSpace.xl)257            }258        }259    }260}261262// MARK: - Selection panel (focus node + neighbours)263264struct GraphSelectionPanel: View {265    @Bindable var model: GraphModel266    /// Compact: shows the focus node (centre / best connected) when nothing is selected.267    var focusFallback = false268269    var body: some View {270        let node = focusFallback ? model.focusNode : model.selectedNode271        VStack(alignment: .leading, spacing: NVSpace.lg) {272            if let node {273                focusCard(node)274                neighbours(node)275            } else {276                NVEmptyState(systemImage: "hand.tap", title: L("Aucune sélection"), message: L("Touchez un élément du graphe pour voir ses liens et créer une relation."))277                    .frame(maxWidth: .infinity)278                    .padding(.vertical, NVSpace.xl)279                if let stats = model.graph?.stats { statsCard(stats) }280            }281        }282        .nvAnimation(.fast, value: node?.id)283    }284285    private func focusCard(_ node: GraphNode) -> some View {286        VStack(alignment: .leading, spacing: NVSpace.md) {287            HStack(alignment: .top, spacing: NVSpace.md) {288                Group {289                    if let icon = node.icon, !icon.isEmpty { Text(icon).font(.system(size: 22)) }290                    else { Image(systemName: KnowledgeVocabulary.nodeSymbol(node.kind)).font(.system(size: 18, weight: .medium)).foregroundStyle(KnowledgeVocabulary.nodeColor(node.kind)) }291                }292                .frame(width: 30)293                .accessibilityHidden(true)294                VStack(alignment: .leading, spacing: NVSpace.xs) {295                    Text(KnowledgeVocabulary.title(node.title)).nvFont(.h3).foregroundStyle(NVColor.fg)296                    HStack(spacing: NVSpace.sm) {297                        NVChip(KnowledgeVocabulary.nodeKindTitle(node.kind))298                        if node.origin == KnowledgeOrigin.ai { NVAIBadge(style: .compact) }299                        Text(LF("%lld lien(s)", node.degree ?? model.neighbours(of: node.id).count)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)300                    }301                }302                Spacer(minLength: 0)303            }304            HStack(spacing: NVSpace.sm) {305                if GraphModel.canOpen(node) { FeatureButton(L("Ouvrir"), systemImage: "arrow.up.forward.square", kind: .primary) { model.open(node) } }306                if GraphModel.canRelate(node) { FeatureButton(L("Relier…"), systemImage: "arrow.triangle.branch") { model.beginRelation(from: node) } }307                if GraphModel.entityKind(node) == GraphEntityKind.page, model.view != GraphView.local {308                    FeatureButton(L("Vue locale"), systemImage: "scope") { Task { await model.focus(pageId: node.entityUUID); await model.setView(GraphView.local) } }309                }310            }311        }312        .padding(NVSpace.lg)313        .frame(maxWidth: .infinity, alignment: .leading)314        .nvCard()315    }316317    @ViewBuilder318    private func neighbours(_ node: GraphNode) -> some View {319        let list = model.neighbours(of: node.id)320        KnowledgeSection(title: L("Voisins"), count: list.count) {321            if list.isEmpty {322                Text(L("Aucun lien : cet élément est isolé dans cette vue.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)323            }324            ForEach(list) { neighbour in325                GraphNeighbourRow(model: model, neighbour: neighbour)326                if neighbour.id != list.last?.id { Divider() }327            }328        }329    }330331    private func statsCard(_ stats: GraphStats) -> some View {332        HStack(alignment: .top) {333            KnowledgeStat(value: String(stats.pages), label: L("pages"))334            KnowledgeStat(value: String(stats.edges), label: L("liens"))335            if let concepts = stats.concepts { KnowledgeStat(value: String(concepts), label: L("concepts")) }336            if let suggested = stats.suggested { KnowledgeStat(value: String(suggested), label: L("suggestions"), tint: NVColor.ai) }337        }338        .padding(NVSpace.lg)339        .nvCard()340    }341}342343struct GraphNeighbourRow: View {344    @Bindable var model: GraphModel345    let neighbour: GraphNeighbour346347    var body: some View {348        let edge = neighbour.edge349        VStack(alignment: .leading, spacing: NVSpace.xs) {350            KnowledgeRow(symbol: KnowledgeVocabulary.nodeSymbol(neighbour.node.kind), icon: neighbour.node.icon, tint: KnowledgeVocabulary.nodeColor(neighbour.node.kind),351                         title: KnowledgeVocabulary.title(neighbour.node.title), detail: detail(edge), action: { model.select(nodeId: neighbour.node.id) }) {352                if GraphModel.isAI(edge) { NVAIBadge(model: edge.model, style: .compact) }353            }354            if let rationale = edge.rationale, !rationale.isEmpty, GraphModel.isAI(edge) {355                Text(rationale).nvFont(.ui).foregroundStyle(NVColor.fgMuted).padding(.leading, 38)356            }357            if GraphModel.isDecidable(edge) || GraphModel.isEditable(edge) {358                HStack(spacing: NVSpace.sm) {359                    if GraphModel.isDecidable(edge) {360                        FeatureButton(L("Accepter"), systemImage: "checkmark", kind: .ai) { Task { await model.accept(edge) } }361                        FeatureButton(L("Refuser"), systemImage: "xmark") { Task { await model.reject(edge) } }362                    }363                    if GraphModel.isEditable(edge) {364                        FeatureButton(L("Modifier"), systemImage: "pencil") { model.beginEditing(edge) }365                        FeatureButton(L("Supprimer"), systemImage: "trash", kind: .destructive) { Task { await model.delete(edge) } }366                    }367                }368                .padding(.leading, 38)369                .disabled(model.isWorking)370            }371        }372    }373374    private func detail(_ edge: GraphEdge) -> String {375        var parts: [String] = []376        let relation = edge.kind == GraphEdgeKind.typed || edge.relType != nil ? KnowledgeVocabulary.relationTitle(edge.relType) : KnowledgeVocabulary.edgeKindTitle(edge.kind)377        parts.append((neighbour.outgoing ? "→ " : "← ") + relation)378        if GraphModel.isSuggestion(edge) { parts.append(L("suggestion à décider")) }379        if let confidence = edge.confidence { parts.append(LF("confiance %lld %%", Int((confidence * 100).rounded()))) }380        if let note = edge.note, !note.isEmpty { parts.append(note) }381        return parts.joined(separator: " · ")382    }383}384385// MARK: - Relation form386387/// Create or edit a typed relation. Inline in the inspector (regular) or in a sheet (compact).388public struct GraphRelationFormView: View {389    @Bindable var model: GraphModel390391    public init(model: GraphModel) { self.model = model }392393    public var body: some View {394        if let form = model.form {395            VStack(alignment: .leading, spacing: NVSpace.lg) {396                Text(form.relationId == nil ? L("Nouvelle relation") : L("Modifier la relation")).nvFont(.h3).foregroundStyle(NVColor.fg)397                labelled(L("De")) {398                    Text(KnowledgeVocabulary.title(model.node(form.fromId)?.title)).nvFont(.body).foregroundStyle(NVColor.fg)399                }400                labelled(L("Type")) {401                    Picker(L("Type de relation"), selection: Binding(get: { form.relType }, set: { model.form?.relType = $0 })) {402                        ForEach(RelationType.all, id: \.self) { Text(KnowledgeVocabulary.relationTitle($0)).tag($0) }403                    }404                    .labelsHidden()405                }406                labelled(L("Vers")) {407                    if form.relationId != nil {408                        Text(KnowledgeVocabulary.title(model.node(form.toId)?.title)).nvFont(.body).foregroundStyle(NVColor.fg)409                    } else {410                        Picker(L("Cible de la relation"), selection: Binding(get: { form.toId }, set: { model.form?.toId = $0 })) {411                            Text(L("Choisir…")).tag("")412                            ForEach(model.relationTargets(for: form.fromId)) { Text(KnowledgeVocabulary.title($0.title)).tag($0.id) }413                        }414                        .labelsHidden()415                    }416                }417                labelled(L("Note")) {418                    TextField(L("Pourquoi ce lien ? (facultatif)"), text: Binding(get: { form.note }, set: { model.form?.note = $0 }), axis: .vertical)419                        .textFieldStyle(.roundedBorder)420                        .lineLimit(2 ... 5)421                }422                if let failure = model.actionFailure { FeatureStatusBanner(failure: failure, freshness: nil) }423                HStack(spacing: NVSpace.sm) {424                    FeatureButton(form.relationId == nil ? L("Créer la relation") : L("Enregistrer"), systemImage: "checkmark", kind: .primary) { Task { await model.submitForm() } }425                        .disabled(model.isWorking || (form.relationId == nil && form.toId.isEmpty))426                    FeatureButton(L("Annuler")) { model.form = nil }427                }428                Text(L("Les relations s'enregistrent sur le serveur : il faut être en ligne.")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)429            }430            .padding(NVSpace.lg)431            .frame(maxWidth: .infinity, alignment: .leading)432            .nvCard()433        }434    }435436    private func labelled<Content: View>(_ label: String, @ViewBuilder _ content: () -> Content) -> some View {437        VStack(alignment: .leading, spacing: NVSpace.xs) {438            Text(label).nvFont(.micro).foregroundStyle(NVColor.fgMuted)439            content()440        }441    }442}443444// MARK: - Insights panel445446public struct GraphInsightsPanel: View {447    @Bindable var model: GraphModel448449    public init(model: GraphModel) { self.model = model }450451    public var body: some View {452        VStack(alignment: .leading, spacing: NVSpace.lg) {453            FeatureStatusBanner(failure: model.insightsPhase.failure, freshness: model.insightsFreshness, retry: { Task { await model.loadInsights() } })454            analysisCard455            if let intelligence = model.insights?.intelligence { intelligenceCard(intelligence) }456            let findings = model.insights?.insights ?? []457            KnowledgeSection(title: L("Constats à décider"), count: findings.count, tone: .accent) {458                if findings.isEmpty {459                    Text(model.insightsPhase.isLoading ? L("Chargement…") : L("Aucun constat en attente. Lancez une analyse pour en chercher."))460                        .nvFont(.ui).foregroundStyle(NVColor.fgMuted)461                }462                ForEach(findings) { insight in463                    GraphInsightRow(model: model, insight: insight)464                    if insight.id != findings.last?.id { Divider() }465                }466            }467        }468    }469470    private var analysisCard: some View {471        VStack(alignment: .leading, spacing: NVSpace.md) {472            Text(L("Analyser le graphe")).nvFont(.uiStrong).foregroundStyle(NVColor.fg)473            Text(L("L'analyse déterministe (regroupements, sujets récurrents, doublons) est calculée par le serveur sans modèle : elle est gratuite."))474                .nvFont(.ui).foregroundStyle(NVColor.fgMuted)475            FeatureButton(L("Analyser (gratuit)"), systemImage: "wand.and.rays", kind: .primary) { Task { await model.runDeterministicInsights() } }476            Divider()477            HStack(spacing: NVSpace.sm) { NVAIBadge(style: .compact); Text(L("Contradictions et questions ouvertes")).nvFont(.uiStrong).foregroundStyle(NVColor.fg) }478            Text(L("Cette analyse appelle un modèle d'IA une fois (payant). Ses constats restent des suggestions tant que vous ne les acceptez pas."))479                .nvFont(.ui).foregroundStyle(NVColor.fgMuted)480            FeatureButton(L("Lancer l'analyse IA (payant)"), systemImage: "sparkles", kind: .ai) { Task { await model.runAIInsights() } }481            if let summary = model.lastRunSummary { Text(summary).nvFont(.ui).foregroundStyle(NVColor.fg) }482        }483        .disabled(model.isWorking)484        .padding(NVSpace.lg)485        .frame(maxWidth: .infinity, alignment: .leading)486        .nvCard()487    }488489    @ViewBuilder490    private func intelligenceCard(_ intelligence: GraphIntelligence) -> some View {491        if let stats = intelligence.stats {492            HStack(alignment: .top) {493                KnowledgeStat(value: String(stats.clusters), label: L("regroupements"))494                KnowledgeStat(value: String(stats.orphans), label: L("orphelines"), tint: stats.orphans > 0 ? NVColor.warningText : NVColor.fg)495                KnowledgeStat(value: String(stats.concepts), label: L("concepts"))496            }497            .padding(NVSpace.lg)498            .nvCard()499        }500        if !intelligence.centralPages.isEmpty {501            KnowledgeSection(title: L("Pages centrales"), subtitle: L("Les mieux reliées (calcul du serveur)")) {502                ForEach(intelligence.centralPages.prefix(5)) { page in503                    KnowledgeRow(symbol: "doc.text", icon: page.icon, tint: NVColor.accent, title: KnowledgeVocabulary.title(page.title),504                                 detail: LF("%lld lien(s)", page.degree ?? 0), action: { model.openPage(id: page.id) })505                }506            }507        }508        if !intelligence.recurringTopics.isEmpty {509            KnowledgeSection(title: L("Sujets récurrents")) {510                ForEach(intelligence.recurringTopics.prefix(6)) { topic in511                    KnowledgeRow(symbol: topic.kind == "tag" ? "number" : "lightbulb", title: topic.name, detail: LF("%lld page(s)", topic.pages ?? topic.pageIds.count))512                }513            }514        }515    }516}517518struct GraphInsightRow: View {519    @Bindable var model: GraphModel520    let insight: KnowledgeInsight521522    var body: some View {523        VStack(alignment: .leading, spacing: NVSpace.sm) {524            HStack(alignment: .top, spacing: NVSpace.sm) {525                Image(systemName: KnowledgeVocabulary.insightSymbol(insight.kind)).foregroundStyle(insight.isAI ? NVColor.ai : NVColor.accent).frame(width: 22).accessibilityHidden(true)526                VStack(alignment: .leading, spacing: NVSpace.xxs) {527                    HStack(spacing: NVSpace.sm) {528                        Text(KnowledgeVocabulary.insightTitle(insight.kind)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)529                        if insight.isAI { NVAIBadge(model: insight.model, style: .compact) }530                    }531                    Text(insight.title ?? KnowledgeVocabulary.insightTitle(insight.kind)).nvFont(.body).foregroundStyle(NVColor.fg)532                    if let detail = insight.detail, !detail.isEmpty { Text(detail).nvFont(.ui).foregroundStyle(NVColor.fgMuted) }533                }534            }535            HStack(spacing: NVSpace.sm) {536                FeatureButton(L("Accepter"), systemImage: "checkmark", kind: insight.isAI ? .ai : .primary) { Task { await model.decide(insight, accept: true) } }537                FeatureButton(L("Écarter"), systemImage: "xmark") { Task { await model.decide(insight, accept: false) } }538                if !insight.pageIds.isEmpty { FeatureButton(L("Voir"), systemImage: "arrow.up.forward.square") { model.openPages(of: insight) } }539            }540            .padding(.leading, 30)541            .disabled(model.isWorking)542        }543        .padding(.vertical, NVSpace.xs)544    }545}546
Files main
Menu

Theme