SPB Git

Repository Public

KnowledgeHealthScreen.swift 11.6 KB 210 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Knowledge/KnowledgeHealthScreen.swift3// Description: Knowledge health: what the server computed from real data (orphans, broken links, missing references,4//              potential duplicates, untitled pages, inactive projects, open tasks), each item leading to its page.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Observation10import SPNotesAPI11import SPNotesDesign12import SPNotesSync13import SwiftUI1415@Observable @MainActor16public final class KnowledgeHealthModel {17    public private(set) var health: KnowledgeHealth?18    public private(set) var phase: LoadPhase = .idle19    public private(set) var freshness: Freshness?2021    private let repository: KnowledgeRepository22    private weak var router: (any FeatureRouter)?2324    public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, now: @escaping @Sendable () -> Date = { Date() }) {25        repository = repositories.knowledge26        self.router = router27    }2829    public func load() async {30        phase = .loading31        do {32            let cached = try await repository.health()33            health = cached.value34            freshness = Freshness(cached)35            phase = .loaded36        } catch {37            phase = .failed(FeatureFailure(error))38        }39    }4041    /// Nothing to fix in any section.42    public var isHealthy: Bool { (health?.score.issues ?? 0) == 0 }4344    /// 0 … 1: the share of pages without an issue (never negative; 1 when the workspace is empty).45    public var ratio: Double {46        guard let score = health?.score, score.pages > 0 else { return 1 }47        return max(0, 1 - Double(score.issues) / Double(score.pages))48    }4950    public func open(pageId: String, blockId: String? = nil) { router?.openPage(id: pageId, blockId: blockId) }5152    public nonisolated static func brokenLinkReason(_ link: BrokenLink) -> String {53        switch link.reason {54        case "missing"?: return L("La cible n'existe plus")55        case "trashed"?: return L("La cible est dans la corbeille")56        case "block_missing"?: return L("Le bloc ciblé n'existe plus")57        default: return link.reason ?? L("Lien rompu")58        }59    }6061    public nonisolated static func duplicateReason(_ group: DuplicateGroup) -> String {62        switch group.reason {63        case "content"?: return L("Même texte")64        case "title"?: return L("Même titre")65        default: return group.reason ?? L("Doublon possible")66        }67    }68}6970public struct KnowledgeHealthScreen: View {71    @State private var model: KnowledgeHealthModel7273    public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil) {74        _model = State(initialValue: KnowledgeHealthModel(repositories: repositories, router: router))75    }7677    public init(model: KnowledgeHealthModel) { _model = State(initialValue: model) }7879    public var body: some View {80        FeatureScaffold(title: L("Santé des connaissances"), subtitle: L("Calculée par le serveur à partir de vos données réelles"), phase: model.phase, freshness: model.freshness,81                        retry: { Task { await model.load() } },82                        actions: { FeatureIconButton("arrow.clockwise", label: L("Actualiser")) { Task { await model.load() } } }) { sizeClass in83            FeaturePhaseView(phase: model.phase, hasData: model.health != nil, retry: { Task { await model.load() } }) {84                EmptyView()85            } content: {86                if let health = model.health {87                    ScrollView {88                        VStack(alignment: .leading, spacing: NVSpace.lg) {89                            summary(health, compact: sizeClass.isCompact)90                            if sizeClass.isCompact {91                                sections(health, column: nil)92                            } else {93                                HStack(alignment: .top, spacing: NVSpace.lg) {94                                    VStack(spacing: NVSpace.lg) { sections(health, column: 0) }95                                    VStack(spacing: NVSpace.lg) { sections(health, column: 1) }96                                }97                            }98                        }99                        .padding(.horizontal, sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)100                        .padding(.bottom, NVSpace.xl)101                    }102                }103            }104        }105        .task { if model.phase == .idle { await model.load() } }106    }107108    private func summary(_ health: KnowledgeHealth, compact: Bool) -> some View {109        HStack(alignment: .center, spacing: NVSpace.xl) {110            Group {111                if model.isHealthy {112                    Image(systemName: "checkmark.seal.fill").font(.system(size: 34)).foregroundStyle(NVColor.success)113                } else {114                    Text(String(health.score.issues)).nvFont(.h1).foregroundStyle(NVColor.accent)115                }116            }117            .frame(width: 72, height: 72)118            .background(model.isHealthy ? NVColor.success.opacity(0.12) : NVColor.accentSoft, in: Circle())119            .accessibilityHidden(true)120            VStack(alignment: .leading, spacing: NVSpace.xs) {121                Text(model.isHealthy ? L("Tout est en ordre") : LF("%lld point(s) à examiner", health.score.issues)).nvFont(.h3).foregroundStyle(NVColor.fg)122                Text(LF("%lld pages analysées", health.score.pages)).nvFont(.ui).foregroundStyle(NVColor.fgMuted)123                if let computedAt = health.computedAt { Text(LF("Calcul du %@", FeatureFormat.dayTime(computedAt))).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }124            }125            Spacer(minLength: 0)126        }127        .padding(NVSpace.lg)128        .frame(maxWidth: .infinity, alignment: .leading)129        .nvCard()130    }131132    /// The seven sections; `column` nil = all (compact), else the sections of that column (regular, two columns).133    @ViewBuilder134    private func sections(_ health: KnowledgeHealth, column: Int?) -> some View {135        if column != 1 {136            KnowledgeSection(title: L("Tâches ouvertes"), subtitle: LF("%lld en retard · %lld sans date", health.openTasks.overdue, health.openTasks.withoutDate),137                             count: health.openTasks.count, tone: health.openTasks.overdue > 0 ? .danger : .accent) {138                emptyNote(health.openTasks.items.isEmpty, L("Aucune tâche ouverte."))139                ForEach(health.openTasks.items.prefix(8)) { task in140                    KnowledgeRow(symbol: task.overdue == true ? "exclamationmark.circle" : "circle", tint: task.overdue == true ? NVColor.danger : NVColor.fgMuted, title: task.title,141                                 detail: [task.dueAt.map { LF("Échéance %@", FeatureFormat.day($0, timeZone: TimeZone(identifier: "UTC") ?? .current)) }, KnowledgeVocabulary.priorityTitle(task.priority)].compactMap { $0 }.joined(separator: " · "),142                                 action: task.pageId.map { id in { model.open(pageId: id) } })143                }144                more(health.openTasks.count, shown: 8)145            }146            KnowledgeSection(title: L("Liens rompus"), count: health.brokenLinks.count, tone: .danger) {147                emptyNote(health.brokenLinks.items.isEmpty, L("Aucun lien rompu."))148                ForEach(Array(health.brokenLinks.items.prefix(8).enumerated()), id: \.offset) { _, link in149                    KnowledgeRow(symbol: "link.badge.plus", tint: NVColor.danger, title: KnowledgeVocabulary.title(link.title), detail: KnowledgeHealthModel.brokenLinkReason(link),150                                 action: { model.open(pageId: link.pageId, blockId: link.blockId) })151                }152                more(health.brokenLinks.count, shown: 8)153            }154            KnowledgeSection(title: L("Références manquantes"), count: health.missingReferences.count, tone: .danger) {155                emptyNote(health.missingReferences.items.isEmpty, L("Toutes les citations pointent vers une référence."))156                ForEach(Array(health.missingReferences.items.prefix(8).enumerated()), id: \.offset) { _, reference in157                    KnowledgeRow(symbol: "book.closed", tint: NVColor.danger, title: KnowledgeVocabulary.title(reference.title), detail: L("Une citation pointe vers une référence supprimée"),158                                 action: { model.open(pageId: reference.pageId, blockId: reference.blockId) })159                }160                more(health.missingReferences.count, shown: 8)161            }162            KnowledgeSection(title: L("Projets inactifs"), subtitle: LF("Sans activité depuis %lld jours", health.inactiveDays), count: health.inactiveProjects.count, tone: .warning) {163                emptyNote(health.inactiveProjects.items.isEmpty, L("Tous les projets ont bougé récemment."))164                ForEach(health.inactiveProjects.items.prefix(8)) { project in165                    KnowledgeRow(symbol: "folder", icon: project.icon, title: KnowledgeVocabulary.title(project.title),166                                 detail: project.idleDays.map { LF("Inactif depuis %lld jours", $0) }, action: { model.open(pageId: project.id) })167                }168                more(health.inactiveProjects.count, shown: 8)169            }170        }171        if column != 0 {172            KnowledgeSection(title: L("Pages orphelines"), subtitle: L("Reliées à rien"), count: health.orphans.count, tone: .warning) {173                emptyNote(health.orphans.items.isEmpty, L("Aucune page orpheline."))174                ForEach(health.orphans.items.prefix(8)) { page in175                    KnowledgeRow(symbol: "doc.text", icon: page.icon, title: KnowledgeVocabulary.title(page.title), detail: page.updatedAt.map { LF("Modifiée le %@", FeatureFormat.day($0)) },176                                 action: { model.open(pageId: page.id) })177                }178                more(health.orphans.count, shown: 8)179            }180            KnowledgeSection(title: L("Doublons possibles"), count: health.potentialDuplicates.count, tone: .warning) {181                emptyNote(health.potentialDuplicates.items.isEmpty, L("Aucun doublon repéré."))182                ForEach(Array(health.potentialDuplicates.items.prefix(8).enumerated()), id: \.offset) { _, group in183                    KnowledgeRow(symbol: "doc.on.doc", title: KnowledgeVocabulary.title(group.title), detail: KnowledgeHealthModel.duplicateReason(group) + " · " + LF("%lld pages", group.pageIds.count),184                                 action: group.pageIds.first.map { id in { model.open(pageId: id) } })185                }186                more(health.potentialDuplicates.count, shown: 8)187            }188            KnowledgeSection(title: L("Pages sans titre"), count: health.untitled.count, tone: .warning) {189                emptyNote(health.untitled.items.isEmpty, L("Toutes les pages ont un titre."))190                ForEach(health.untitled.items.prefix(8)) { page in191                    KnowledgeRow(symbol: "textformat", title: L("Sans titre"),192                                 detail: [page.empty == true ? L("Vide") : nil, page.updatedAt.map { LF("Modifiée le %@", FeatureFormat.day($0)) }].compactMap { $0 }.joined(separator: " · "),193                                 action: { model.open(pageId: page.id) })194                }195                more(health.untitled.count, shown: 8)196            }197        }198    }199200    @ViewBuilder201    private func emptyNote(_ isEmpty: Bool, _ text: String) -> some View {202        if isEmpty { Label(text, systemImage: "checkmark.circle").nvFont(.ui).foregroundStyle(NVColor.fgMuted) }203    }204205    @ViewBuilder206    private func more(_ count: Int, shown: Int) -> some View {207        if count > shown { Text(LF("… et %lld de plus", count - shown)).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }208    }209}210
Files main
Menu

Theme