Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Notes/InspectorPanel.swift3// Description: Inspector of a note: tags, organisation, information, attachments with their local state, and the links of the note in both directions — what it points to (mentions, block references, typed relations) and what points to it (backlinks), all read from the local store.4import SwiftUI5import SPNotesCore6import SPNotesDocument7import SPNotesStore8import SPNotesAPI9import SPNotesDesign1011/// One link of a note, in either direction.12struct NoteLink: Identifiable, Equatable {13 enum Source: Equatable { case document, relation }14 let pageId: String, title: String15 var blockId: String?16 /// Relation type (`supports`, `contradicts`…); nil for a plain mention.17 var relType: String?18 /// The relation was suggested or created by a model: shown as such.19 var isAI = false20 var source: Source = .document21 var id: String { pageId + "#" + (blockId ?? "") + "#" + (relType ?? "") }22 var label: String? { relType.flatMap { NoteLinks.relationLabels[$0] } }23}2425/// Links of a page computed on this Mac: from its document, from the typed relations of the synced graph, and from the26/// documents of the other local notes that mention it.27@MainActor enum NoteLinks {28 static let relationLabels = ["related": "lié à", "supports": "appuie", "contradicts": "contredit", "extends": "prolonge", "example_of": "exemple de", "part_of": "partie de", "cites": "cite", "precedes": "précède", "follows": "suit", "about": "à propos de", "answers": "répond à", "duplicates": "doublon de"]29 /// Local notes scanned for mentions of a page (the most recently changed first).30 static let scanLimit = 6003132 static func outgoing(of doc: NoteDocument, pageId: String, env: AppEnvironment) async -> [NoteLink] {33 var out: [NoteLink] = []34 for id in doc.pageReferences().prefix(40) where id != pageId { if let p = try? await env.store.summary(id: id), p.deletedAt == nil { out.append(NoteLink(pageId: id, title: Format.title(p.title))) } }35 for r in (try? await env.repositories.graph.localRelations(touching: pageId)) ?? [] where r.fromId == pageId && r.status != "rejected" && r.targetKind == "page" {36 guard let p = try? await env.store.summary(id: r.toId) else { continue }37 let typed = r.relType == "related" && r.kind == "link" ? nil : r.relType38 if typed == nil, out.contains(where: { $0.pageId == r.toId }) { continue }39 out.append(NoteLink(pageId: r.toId, title: Format.title(p.title), blockId: r.targetBlockId, relType: typed, isAI: r.origin == "ai", source: .relation))40 }41 return out42 }4344 static func incoming(pageId: String, env: AppEnvironment) async -> [NoteLink] {45 var out: [NoteLink] = []46 for r in (try? await env.repositories.graph.localBacklinks(pageId: pageId)) ?? [] where r.sourceKind == "page" && r.fromId != pageId {47 guard let p = try? await env.store.summary(id: r.fromId), p.deletedAt == nil else { continue }48 out.append(NoteLink(pageId: r.fromId, title: Format.title(p.title), blockId: r.sourceBlockId, relType: r.relType == "related" ? nil : r.relType, isAI: r.origin == "ai", source: .relation))49 }50 // notes of this Mac whose document mentions the page (works without any server, and before the graph is synced)51 let needle = Data(pageId.utf8)52 for s in ((try? await env.store.summaries(list: .recent, limit: scanLimit)) ?? []) where s.id != pageId && !out.contains(where: { $0.pageId == s.id }) {53 guard let page = try? await env.store.page(id: s.id), page.content.range(of: needle) != nil, let doc = try? NoteDocument(json: page.content), doc.pageReferences().contains(pageId) else { continue }54 // the block that holds the mention, so that the link lands on it55 let block = doc.lines.first { NoteDocument(lines: [$0]).pageReferences().contains(pageId) }.flatMap { $0.attrs["id"]?.stringValue }56 out.append(NoteLink(pageId: s.id, title: Format.title(s.title), blockId: block))57 }58 return out59 }60}6162struct InspectorPanel: View {63 @Environment(AppEnvironment.self) private var env64 @Environment(WindowModel.self) private var window65 let session: NoteSession66 @State private var newTag = ""67 @State private var attachments: [AttachmentRecord] = []68 @State private var outgoing: [NoteLink] = []69 @State private var incoming: [NoteLink] = []70 @State private var linksLoaded = false71 @State private var path: [PageSummary] = []7273 var body: some View {74 ScrollView {75 VStack(alignment: .leading, spacing: NVSpace.xl) {76 PanelHeader(title: "Inspecteur", symbol: "sidebar.right")77 section("Tags") {78 FlowLayout(spacing: NVSpace.xs) {79 ForEach(session.page.tags, id: \.self) { t in NVChip("#" + t, systemImage: "xmark", tone: .accent) { setTags(session.page.tags.filter { $0 != t }) }.accessibilityLabel("Retirer le tag \(t)") }80 }81 TextField("Ajouter un tag", text: $newTag).textFieldStyle(.roundedBorder).controlSize(.small)82 .onSubmit { let t = newTag.trimmingCharacters(in: .whitespaces); newTag = ""; if !t.isEmpty { setTags(session.page.tags + [t]) } }83 .accessibilityIdentifier("tag-field")84 let suggestions = env.library.tags.map(\.name).filter { !session.page.tags.contains($0) && (newTag.isEmpty || $0.hasPrefix(newTag.lowercased())) }.prefix(6)85 if !suggestions.isEmpty { FlowLayout(spacing: NVSpace.xs) { ForEach(Array(suggestions), id: \.self) { t in NVChip("#" + t) { setTags(session.page.tags + [t]) } } } }86 }87 section("Liens") {88 linkGroup("Rétroliens", "arrow.down.left", incoming, empty: "Aucune note de ce Mac ne pointe vers celle-ci.").accessibilityIdentifier("backlinks")89 linkGroup("Liens sortants", "arrow.up.right", outgoing, empty: "Cette note ne pointe vers aucune autre. Tape « @ » pour en lier une.").accessibilityIdentifier("outgoing-links")90 }91 section("Organisation") {92 Toggle("Favori", isOn: Binding(get: { session.page.favorite }, set: { v in Task { await env.library.setFavorite(session.id, v) } }))93 Toggle("Épinglée en haut", isOn: Binding(get: { session.page.pinned }, set: { v in Task { await env.library.setPinned(session.id, v) } }))94 Toggle("Archivée", isOn: Binding(get: { session.page.archived }, set: { v in Task { await env.library.setArchived(session.id, v) } }))95 Toggle("Dossier (contient des notes)", isOn: Binding(get: { session.page.isFolder }, set: { v in Task { await env.library.setFolder(session.id, v) } }))96 if !path.isEmpty { Text(path.map { Format.title($0.title) }.joined(separator: " › ")).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }97 }.toggleStyle(.checkbox).controlSize(.small)98 section("Informations") {99 info("Créée", Format.long(session.page.createdAt)); info("Modifiée", Format.long(session.page.updatedAt))100 info("Longueur", Format.words(session.wordCount))101 info("Espace", LibraryModel.sections.first { $0.id == session.page.section }?.label ?? session.page.section)102 info("Synchronisation", syncText)103 if let e = session.page.syncError, !e.isEmpty { Text(e).nvFont(.micro).foregroundStyle(NVColor.dangerText) }104 }105 if !attachments.isEmpty {106 section("Pièces jointes") {107 ForEach(attachments) { a in108 Button { Task { await AttachmentService(env: env).preview(attachmentId: a.id, name: a.filename) } } label: {109 HStack(spacing: NVSpace.sm) {110 Image(systemName: a.mime.hasPrefix("image/") ? "photo" : a.mime == "application/pdf" ? "doc.richtext" : a.mime.hasPrefix("audio/") ? "waveform" : "doc").foregroundStyle(NVColor.fgMuted)111 VStack(alignment: .leading, spacing: NVSpace.xxs) { Text(a.filename).lineLimit(1).nvFont(.ui); Text(Format.bytes(a.size) + " · " + stateText(a.state)).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }112 Spacer()113 }.contentShape(Rectangle())114 }.buttonStyle(.plain).help("Coup d'œil")115 }116 }117 }118 }119 .padding(NVSpace.lg).frame(maxWidth: .infinity, alignment: .leading)120 }121 .task(id: "\(session.id)-\(session.page.editSeq)-\(session.page.rev)") { await load() }122 .accessibilityIdentifier("inspector")123 }124125 @ViewBuilder private func linkGroup(_ title: String, _ symbol: String, _ links: [NoteLink], empty: String) -> some View {126 VStack(alignment: .leading, spacing: NVSpace.xs) {127 Label("\(title) · \(links.count)", systemImage: symbol).nvFont(.uiStrong).foregroundStyle(NVColor.fg)128 if links.isEmpty { Text(linksLoaded ? empty : "…").nvFont(.micro).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true) }129 ForEach(links) { l in130 Button { window.open(Route(pageId: l.pageId, blockId: l.blockId)) } label: {131 HStack(spacing: NVSpace.sm) {132 Image(systemName: l.source == .relation ? "point.3.connected.trianglepath.dotted" : "doc.text").foregroundStyle(l.isAI ? NVColor.ai : NVColor.accent).frame(width: NVSpace.lg)133 VStack(alignment: .leading, spacing: 0) { Text(l.title).nvFont(.ui).lineLimit(1); if let label = l.label { Text(label).nvFont(.micro).foregroundStyle(NVColor.fgMuted) } }134 Spacer(minLength: 0)135 if l.isAI { NVAIBadge(style: .compact) }136 }.contentShape(Rectangle())137 }.buttonStyle(.plain).help(l.blockId == nil ? "Ouvrir la note" : "Ouvrir la note au bloc concerné")138 }139 }140 }141142 private var syncText: String {143 if env.account.phase == .local { return "Sur ce Mac seulement" }144 switch session.page.syncState { case .synced: return "À jour (version \(session.page.serverVersion))"; case .pending: return "En attente d'envoi"; case .conflict: return "Conflit à résoudre"; case .error: return "Envoi en échec" }145 }146 private func stateText(_ s: AttachmentState) -> String {147 switch s { case .remote: "sur le serveur"; case .downloading: "téléchargement…"; case .local: "sur ce Mac"; case .pendingUpload: "à envoyer"; case .uploading: "envoi…"; case .failed: "échec" }148 }149 private func setTags(_ tags: [String]) { Task { await env.library.setTags(session.id, tags) } }150 private func load() async {151 attachments = (try? await env.store.attachments(pageId: session.id)) ?? []152 path = (try? await env.store.ancestors(of: session.id)) ?? []153 outgoing = await NoteLinks.outgoing(of: session.editor.document(), pageId: session.id, env: env)154 incoming = await NoteLinks.incoming(pageId: session.id, env: env)155 linksLoaded = true156 }157 private func section<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {158 VStack(alignment: .leading, spacing: NVSpace.sm) { GroupLabel(title); content() }159 }160 private func info(_ k: String, _ v: String) -> some View { HStack(alignment: .firstTextBaseline) { Text(k).foregroundStyle(NVColor.fgMuted); Spacer(); Text(v).multilineTextAlignment(.trailing) }.nvFont(.ui) }161}162163/// Wrapping row of chips.164struct FlowLayout: Layout {165 var spacing: CGFloat = NVSpace.sm - NVSpace.xxs166 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {167 let width = proposal.width ?? 240; var x: CGFloat = 0, y: CGFloat = 0, rowH: CGFloat = 0168 for s in subviews { let size = s.sizeThatFits(.unspecified); if x + size.width > width, x > 0 { x = 0; y += rowH + spacing; rowH = 0 }; x += size.width + spacing; rowH = max(rowH, size.height) }169 return CGSize(width: width, height: y + rowH)170 }171 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {172 var x = bounds.minX, y = bounds.minY, rowH: CGFloat = 0173 for s in subviews { let size = s.sizeThatFits(.unspecified); if x + size.width > bounds.maxX, x > bounds.minX { x = bounds.minX; y += rowH + spacing; rowH = 0 }; s.place(at: CGPoint(x: x, y: y), proposal: .unspecified); x += size.width + spacing; rowH = max(rowH, size.height) }174 }175}176