Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Components/MarkdownView.swift3// Description: Native rendering of the agent's Markdown reports: headings, paragraphs, lists, tables, code, quotes, figures fetched from the server, report markers.4import SwiftUI5import VQuantCore67struct MarkdownView: View {8 let app: AppEnvironment9 let blocks: [MarkdownBlock]1011 init(app: AppEnvironment, source: String) { self.app = app; blocks = MarkdownParser.parse(source) }12 init(app: AppEnvironment, blocks: [MarkdownBlock]) { self.app = app; self.blocks = blocks }1314 var body: some View {15 VStack(alignment: .leading, spacing: 10) {16 ForEach(Array(blocks.enumerated()), id: \.offset) { _, b in block(b) }17 }18 .textSelection(.enabled)19 .frame(maxWidth: .infinity, alignment: .leading)20 .environment(\.openURL, OpenURLAction { url in21 // files the agent generated on the server (CSV, Excel…) are fetched with the session and saved where the person chooses22 if url.host == nil, url.path.hasPrefix("/api/download/") {23 let path = url.path24 Task { if let d = await app.images.data(path) { SavePanel.save(d, name: (path as NSString).lastPathComponent, types: [.data]) } else { app.toasts.show("This file is no longer on the server.", error: true) } }25 return .handled26 }27 // only web links leave the app28 return url.scheme == "https" || url.scheme == "http" ? .systemAction : .discarded29 })30 }3132 @ViewBuilder private func block(_ b: MarkdownBlock) -> some View {33 switch b {34 case .heading(let level, let text):35 InlineText(text).font(level == 1 ? .title.weight(.bold) : level == 2 ? .title2.weight(.semibold) : level == 3 ? .title3.weight(.semibold) : .headline)36 .padding(.top, level <= 2 ? 8 : 4)37 .accessibilityAddTraits(.isHeader)38 case .paragraph(let t): InlineText(t).lineSpacing(3)39 case .list(let items):40 VStack(alignment: .leading, spacing: 4) {41 ForEach(Array(items.enumerated()), id: \.offset) { _, it in42 HStack(alignment: .firstTextBaseline, spacing: 6) {43 Text(it.marker).foregroundStyle(.secondary).monospacedDigit().frame(minWidth: 14, alignment: .trailing)44 InlineText(it.text).lineSpacing(2)45 }46 .padding(.leading, CGFloat(it.depth) * 18)47 }48 }49 case .table(let header, let rows, let aligns): MarkdownTable(header: header, rows: rows, alignments: aligns)50 case .code(let lang, let text): CodeBlock(language: lang, text: text)51 case .math(let src):52 Text(src).font(.system(.callout, design: .monospaced)).padding(10).frame(maxWidth: .infinity, alignment: .leading)53 .background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 6))54 .help("Formula shown as TeX source")55 case .image(let alt, let url): FigureView(app: app, path: url, caption: alt)56 case .quote(let t):57 InlineText(t).foregroundStyle(.secondary).padding(.leading, 10)58 .overlay(alignment: .leading) { Rectangle().fill(Color.accentColor.opacity(0.6)).frame(width: 3) }59 case .rule: Divider().padding(.vertical, 4)60 }61 }62}6364/// Inline Markdown (emphasis, code, links) with the agent's `:marker:` badges drawn as symbols.65struct InlineText: View {66 let pieces: [ReportMarkers.Piece]67 init(_ s: String) { pieces = ReportMarkers.split(s) }6869 var body: some View {70 pieces.reduce(Text("")) { acc, p in71 switch p {72 case .text(let s): return acc + Text(Self.attributed(s))73 case .marker(let name):74 let m = ReportMarkers.symbols[name]75 return acc + Text(Image(systemName: m?.symbol ?? "circle.fill")).foregroundStyle(Self.color(name)).accessibilityLabel(m?.label ?? name)76 }77 }78 }7980 static func attributed(_ s: String) -> AttributedString {81 (try? AttributedString(markdown: s, options: .init(allowsExtendedAttributes: false, interpretedSyntax: .inlineOnlyPreservingWhitespace, failurePolicy: .returnPartiallyParsedIfPossible))) ?? AttributedString(s)82 }83 static func color(_ name: String) -> Color {84 switch name {85 case "gold": Color(red: 0.95, green: 0.65, blue: 0.05); case "silver": .gray; case "bronze": Color(red: 0.76, green: 0.44, blue: 0.23)86 case "up", "bull", "check": Palette.green; case "down", "bear", "cross", "risk": Palette.red87 case "warn", "idea": Palette.amber; case "flat", "clock": .secondary88 default: .accentColor89 }90 }91}9293private struct MarkdownTable: View {94 let header: [String]95 let rows: [[String]]96 let alignments: [MarkdownBlock.Alignment]9798 var body: some View {99 ScrollView(.horizontal, showsIndicators: rows.first.map { $0.count > 6 } ?? false) {100 Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {101 GridRow { ForEach(header.indices, id: \.self) { c in cell(header[c], c, header: true) } }102 .background(Color.secondary.opacity(0.10))103 ForEach(rows.indices, id: \.self) { r in104 Divider().gridCellUnsizedAxes(.horizontal)105 GridRow { ForEach(header.indices, id: \.self) { c in cell(c < rows[r].count ? rows[r][c] : "", c, header: false) } }106 .background(r % 2 == 1 ? Color.secondary.opacity(0.04) : .clear)107 }108 }109 .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Palette.hairline))110 .clipShape(RoundedRectangle(cornerRadius: 6))111 }112 }113114 private func cell(_ s: String, _ c: Int, header: Bool) -> some View {115 let a = c < alignments.count ? alignments[c] : .leading116 return InlineText(s).font(header ? .callout.weight(.semibold) : .callout).monospacedDigit()117 .multilineTextAlignment(a == .trailing ? .trailing : a == .center ? .center : .leading)118 .frame(maxWidth: 420, alignment: a == .trailing ? .trailing : a == .center ? .center : .leading)119 .padding(.horizontal, 10).padding(.vertical, 5)120 .gridColumnAlignment(a == .trailing ? .trailing : a == .center ? .center : .leading)121 }122}123124struct CodeBlock: View {125 let language: String?126 let text: String127 var body: some View {128 VStack(alignment: .leading, spacing: 0) {129 HStack {130 Text(language ?? "code").font(.caption).foregroundStyle(.secondary)131 Spacer()132 Button { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(text, forType: .string) } label: { Label("Copy", systemImage: "doc.on.doc").labelStyle(.iconOnly) }133 .buttonStyle(.borderless).help("Copy")134 }135 .padding(.horizontal, 10).padding(.vertical, 4).background(Color.secondary.opacity(0.10))136 ScrollView(.horizontal) {137 Text(text).font(.system(size: 12, design: .monospaced)).textSelection(.enabled).padding(10).frame(maxWidth: .infinity, alignment: .leading)138 }139 }140 .background(Color.secondary.opacity(0.06))141 .clipShape(RoundedRectangle(cornerRadius: 6))142 .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Palette.hairline))143 }144}145146/// A figure of a report. Server figures (`/figures/…`, `/plots/…`) are fetched with the session and cached; any other147/// address is shown as a link — the app never loads images from third-party sites on its own.148struct FigureView: View {149 let app: AppEnvironment150 let path: String151 let caption: String152 @State private var image: NSImage?153 @State private var failed = false154155 private var isServerAsset: Bool { path.hasPrefix("/figures/") || path.hasPrefix("/plots/") }156157 var body: some View {158 VStack(alignment: .leading, spacing: 4) {159 if isServerAsset {160 if let image {161 Image(nsImage: image).resizable().interpolation(.high).aspectRatio(contentMode: .fit)162 .frame(maxWidth: min(image.size.width, 900))163 .clipShape(RoundedRectangle(cornerRadius: 6))164 .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Palette.hairline))165 .contextMenu {166 Button("Copy Image") { NSPasteboard.general.clearContents(); NSPasteboard.general.writeObjects([image]) }167 Button("Save Image…") { Task { if let d = await app.images.data(path) { SavePanel.save(d, name: (path as NSString).lastPathComponent, types: [.png]) } } }168 }169 .accessibilityLabel(caption.isEmpty ? "Figure" : caption)170 } else if failed {171 Label("Figure unavailable (the server no longer has this file)", systemImage: "photo").font(.callout).foregroundStyle(.secondary)172 .padding(12).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 6))173 } else {174 RoundedRectangle(cornerRadius: 6).fill(Color.secondary.opacity(0.06)).frame(height: 220).overlay { ProgressView() }175 }176 } else if let url = URL(string: path), url.scheme == "https" {177 Link(destination: url) { Label(caption.isEmpty ? path : caption, systemImage: "photo") }.font(.callout)178 }179 if isServerAsset, !caption.isEmpty { Text(caption).font(.caption).foregroundStyle(.secondary) }180 }181 .task(id: path) {182 guard isServerAsset, image == nil else { return }183 if let img = await app.images.image(path) { image = img } else { failed = true }184 }185 }186}187