// Adapted from Equipo's ChatMarkdownView (oficina/equipo 00d09aa7, // native/apple/Sources/EquipoKit/Markdown/ChatMarkdownView.swift): the same // tree, rows and inline runs, set in Base's type and colours, with links // opening on the web only (Base's Assistant writes no task links). import SwiftUI #if os(macOS) import AppKit #else import UIKit #endif /// The Assistant's prose: the little Markdown it writes (lists, links, /// bold, italics), parsed off the main thread as it streams. The source is /// untrusted text; only absolute http(s) links are actionable. /// Base: the person's own messages too (`person`), which keep each line /// they typed and whose links keep the bubble's ink, as on the web. struct BaseMarkdownView: View { private let draft: Bool private let person: Bool private let stream: MarkdownStreamRenderer private let request: MarkdownRenderCache.Request private let initial: MarkdownRenderCache.Result @Environment(\.colorScheme) private var scheme @Environment(\.openURL) private var openURL private var nodes: [ChatMarkdownNode] { initial.complete ? initial.tree : stream.visible(for: request) ?? initial.tree } init(_ text: String, draft: Bool, id: String, transcript: MarkdownTranscript) { self.draft = draft person = false request = MarkdownRenderCache.Request(messageID: id, text: text, draft: draft) initial = MarkdownRenderCache.shared.initial(request) stream = transcript.renderer(for: id) } /// Base: the person's own message, already in the web's little subset /// (PersonMarkdown), never streamed. init(person nodes: [ChatMarkdownNode], id: String, transcript: MarkdownTranscript) { draft = false person = true request = MarkdownRenderCache.Request(messageID: "person:" + id, text: "", draft: false) initial = MarkdownRenderCache.Result(tree: nodes, complete: true) stream = transcript.renderer(for: "person:" + id) } var body: some View { let p = Palette(scheme) MarkdownRows(nodes: nodes) .font(BaseFont.body(15)) .foregroundStyle(p[.frost]) .tint(person ? p[.frost] : p[.focus]) .environment(\.markdownKeepsLines, person) .textSelection(.enabled) .onAppear { if !person { stream.submit(request, needsParsing: !initial.complete) } } .onChange(of: request) { if !person { stream.submit(request, needsParsing: !initial.complete) } } .environment(\.openURL, OpenURLAction { url in guard let original = MarkdownActions.originalTarget(url, in: nodes), case .external(let target)? = MarkdownActions.destination(original, origin: url) else { return .discarded } openURL(target) return .handled }) } } private struct MarkdownRows: View { let nodes: [ChatMarkdownNode] @Environment(\.colorScheme) private var scheme var body: some View { VStack(alignment: .leading, spacing: 4) { ForEach(MarkdownPresentation.rows(nodes)) { row in HStack(alignment: .firstTextBaseline, spacing: 8) { if let marker = row.marker { Text(verbatim: marker).monospacedDigit().accessibilityHidden(true) } MarkdownBlock(node: row.node) } .padding(.leading, CGFloat(row.indentation) * 16) } } } } extension EnvironmentValues { /// Base: the text is as typed (the person's messages), where the /// Assistant's runs of space and line breaks are one space, as /// Markdown's are. @Entry var markdownKeepsLines = false } private struct MarkdownBlock: View { let node: ChatMarkdownNode @Environment(\.markdownKeepsLines) private var keepsLines var body: some View { switch node.kind { case "paragraph", "inlineGroup": Text(inline(node.children)).fixedSize(horizontal: false, vertical: true) case "plain": Text(verbatim: node.text ?? "").fixedSize(horizontal: false, vertical: true) case "paste": MarkdownPaste(node: node) case "codeBlock": MarkdownCode(text: node.text ?? "", wraps: false) default: EmptyView() } } private func prose(_ text: String) -> String { // Base: the person's words are as typed, spaces and lines and all, // as the web's pre-wrap draws them. if keepsLines { return text } return text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression) } private func inline(_ nodes: [ChatMarkdownNode]) -> AttributedString { struct Work { var node: ChatMarkdownNode; var bold = false; var italic = false; var link: String? } var stack = nodes.reversed().map { Work(node: $0) } var result = AttributedString() while let work = stack.popLast() { let node = work.node if !["text", "code", "break"].contains(node.kind) { for child in node.children.reversed() { stack.append(Work(node: child, bold: work.bold || node.kind == "strong", italic: work.italic || node.kind == "emphasis", link: node.kind == "link" ? node.target : work.link)) } continue } var part = AttributedString(node.kind == "break" ? "\n" : prose(node.text ?? "")) if node.kind == "code" { part.font = BaseFont.body(15).monospaced() } var intent: InlinePresentationIntent = [] if work.bold { intent.insert(.stronglyEmphasized) } if work.italic { intent.insert(.emphasized) } part.inlinePresentationIntent = intent // Base: italics by the face's italic instance, which the // emphasized intent can't find (it lands on another cut), so // the run is set in that font alone (BaseFont.body). if work.italic, node.kind != "code" { part.font = BaseFont.body(15, work.bold ? .bold : .regular, italic: true) part.inlinePresentationIntent = nil } if let target = work.link, ChatMarkdown.allowsLink(target) { part.link = MarkdownActions.linkURL(target) part.underlineStyle = .single } if result.characters.last == " ", part.characters.first == " " { part.removeSubrange(part.startIndex..