| 1 | // Adapted from Equipo's ChatMarkdownView (oficina/equipo 00d09aa7, |
| 2 | // native/apple/Sources/EquipoKit/Markdown/ChatMarkdownView.swift): the same |
| 3 | // tree, rows and inline runs, set in Base's type and colours, with links |
| 4 | // opening on the web only (Base's Assistant writes no task links). |
| 5 | import SwiftUI |
| 6 | #if os(macOS) |
| 7 | import AppKit |
| 8 | #else |
| 9 | import UIKit |
| 10 | #endif |
| 11 | |
| 12 | /// The Assistant's prose: the little Markdown it writes (lists, links, |
| 13 | /// bold, italics), parsed off the main thread as it streams. The source is |
| 14 | /// untrusted text; only absolute http(s) links are actionable. |
| 15 | /// Base: the person's own messages too (`person`), which keep each line |
| 16 | /// they typed and whose links keep the bubble's ink, as on the web. |
| 17 | struct BaseMarkdownView: View { |
| 18 | private let draft: Bool |
| 19 | private let person: Bool |
| 20 | private let stream: MarkdownStreamRenderer |
| 21 | private let request: MarkdownRenderCache.Request |
| 22 | private let initial: MarkdownRenderCache.Result |
| 23 | @Environment(\.colorScheme) private var scheme |
| 24 | @Environment(\.openURL) private var openURL |
| 25 | |
| 26 | private var nodes: [ChatMarkdownNode] { |
| 27 | initial.complete ? initial.tree : stream.visible(for: request) ?? initial.tree |
| 28 | } |
| 29 | |
| 30 | init(_ text: String, draft: Bool, id: String, transcript: MarkdownTranscript) { |
| 31 | self.draft = draft |
| 32 | person = false |
| 33 | request = MarkdownRenderCache.Request(messageID: id, text: text, draft: draft) |
| 34 | initial = MarkdownRenderCache.shared.initial(request) |
| 35 | stream = transcript.renderer(for: id) |
| 36 | } |
| 37 | |
| 38 | /// Base: the person's own message, already in the web's little subset |
| 39 | /// (PersonMarkdown), never streamed. |
| 40 | init(person nodes: [ChatMarkdownNode], id: String, transcript: MarkdownTranscript) { |
| 41 | draft = false |
| 42 | person = true |
| 43 | request = MarkdownRenderCache.Request(messageID: "person:" + id, text: "", draft: false) |
| 44 | initial = MarkdownRenderCache.Result(tree: nodes, complete: true) |
| 45 | stream = transcript.renderer(for: "person:" + id) |
| 46 | } |
| 47 | |
| 48 | var body: some View { |
| 49 | let p = Palette(scheme) |
| 50 | MarkdownRows(nodes: nodes) |
| 51 | .font(BaseFont.body(15)) |
| 52 | .foregroundStyle(p[.frost]) |
| 53 | .tint(person ? p[.frost] : p[.focus]) |
| 54 | .environment(\.markdownKeepsLines, person) |
| 55 | .textSelection(.enabled) |
| 56 | .onAppear { if !person { stream.submit(request, needsParsing: !initial.complete) } } |
| 57 | .onChange(of: request) { if !person { stream.submit(request, needsParsing: !initial.complete) } } |
| 58 | .environment(\.openURL, OpenURLAction { url in |
| 59 | guard let original = MarkdownActions.originalTarget(url, in: nodes), |
| 60 | case .external(let target)? = MarkdownActions.destination(original, origin: url) else { return .discarded } |
| 61 | openURL(target) |
| 62 | return .handled |
| 63 | }) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | private struct MarkdownRows: View { |
| 68 | let nodes: [ChatMarkdownNode] |
| 69 | @Environment(\.colorScheme) private var scheme |
| 70 | var body: some View { |
| 71 | VStack(alignment: .leading, spacing: 4) { |
| 72 | ForEach(MarkdownPresentation.rows(nodes)) { row in |
| 73 | HStack(alignment: .firstTextBaseline, spacing: 8) { |
| 74 | if let marker = row.marker { Text(verbatim: marker).monospacedDigit().accessibilityHidden(true) } |
| 75 | MarkdownBlock(node: row.node) |
| 76 | } |
| 77 | .padding(.leading, CGFloat(row.indentation) * 16) |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | extension EnvironmentValues { |
| 84 | /// Base: the text is as typed (the person's messages), where the |
| 85 | /// Assistant's runs of space and line breaks are one space, as |
| 86 | /// Markdown's are. |
| 87 | @Entry var markdownKeepsLines = false |
| 88 | } |
| 89 | |
| 90 | private struct MarkdownBlock: View { |
| 91 | let node: ChatMarkdownNode |
| 92 | @Environment(\.markdownKeepsLines) private var keepsLines |
| 93 | var body: some View { |
| 94 | switch node.kind { |
| 95 | case "paragraph", "inlineGroup": Text(inline(node.children)).fixedSize(horizontal: false, vertical: true) |
| 96 | case "plain": Text(verbatim: node.text ?? "").fixedSize(horizontal: false, vertical: true) |
| 97 | case "paste": MarkdownPaste(node: node) |
| 98 | case "codeBlock": MarkdownCode(text: node.text ?? "", wraps: false) |
| 99 | default: EmptyView() |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | private func prose(_ text: String) -> String { |
| 104 | // Base: the person's words are as typed, spaces and lines and all, |
| 105 | // as the web's pre-wrap draws them. |
| 106 | if keepsLines { return text } |
| 107 | return text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression) |
| 108 | } |
| 109 | |
| 110 | private func inline(_ nodes: [ChatMarkdownNode]) -> AttributedString { |
| 111 | struct Work { var node: ChatMarkdownNode; var bold = false; var italic = false; var link: String? } |
| 112 | var stack = nodes.reversed().map { Work(node: $0) } |
| 113 | var result = AttributedString() |
| 114 | while let work = stack.popLast() { |
| 115 | let node = work.node |
| 116 | if !["text", "code", "break"].contains(node.kind) { |
| 117 | for child in node.children.reversed() { |
| 118 | stack.append(Work(node: child, bold: work.bold || node.kind == "strong", italic: work.italic || node.kind == "emphasis", |
| 119 | link: node.kind == "link" ? node.target : work.link)) |
| 120 | } |
| 121 | continue |
| 122 | } |
| 123 | var part = AttributedString(node.kind == "break" ? "\n" : prose(node.text ?? "")) |
| 124 | if node.kind == "code" { part.font = BaseFont.body(15).monospaced() } |
| 125 | var intent: InlinePresentationIntent = [] |
| 126 | if work.bold { intent.insert(.stronglyEmphasized) } |
| 127 | if work.italic { intent.insert(.emphasized) } |
| 128 | part.inlinePresentationIntent = intent |
| 129 | // Base: italics by the face's italic instance, which the |
| 130 | // emphasized intent can't find (it lands on another cut), so |
| 131 | // the run is set in that font alone (BaseFont.body). |
| 132 | if work.italic, node.kind != "code" { |
| 133 | part.font = BaseFont.body(15, work.bold ? .bold : .regular, italic: true) |
| 134 | part.inlinePresentationIntent = nil |
| 135 | } |
| 136 | if let target = work.link, ChatMarkdown.allowsLink(target) { |
| 137 | part.link = MarkdownActions.linkURL(target) |
| 138 | part.underlineStyle = .single |
| 139 | } |
| 140 | if result.characters.last == " ", part.characters.first == " " { |
| 141 | part.removeSubrange(part.startIndex..<part.index(afterCharacter: part.startIndex)) |
| 142 | } |
| 143 | result.append(part) |
| 144 | } |
| 145 | return result |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | private struct MarkdownCode: View { |
| 150 | let text: String |
| 151 | let wraps: Bool |
| 152 | var body: some View { |
| 153 | if wraps { |
| 154 | Text(verbatim: text).fixedSize(horizontal: false, vertical: true) |
| 155 | .frame(maxWidth: .infinity, alignment: .leading).padding(12) |
| 156 | } else { |
| 157 | ScrollView(.horizontal) { |
| 158 | Text(verbatim: text).font(BaseFont.body(14).monospaced()).fixedSize().padding(12) |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | private struct MarkdownPaste: View { |
| 165 | let node: ChatMarkdownNode |
| 166 | @State private var copied = false |
| 167 | @Environment(\.colorScheme) private var scheme |
| 168 | var body: some View { |
| 169 | let p = Palette(scheme) |
| 170 | VStack(alignment: .leading, spacing: 0) { |
| 171 | HStack { |
| 172 | if let label = node.label { Text(verbatim: label).foregroundStyle(p[.haze]) } |
| 173 | Spacer(minLength: 8) |
| 174 | Button { |
| 175 | guard let value = MarkdownActions.copyText(node) else { return } |
| 176 | #if os(macOS) |
| 177 | NSPasteboard.general.clearContents() |
| 178 | copied = NSPasteboard.general.setString(value, forType: .string) |
| 179 | #else |
| 180 | UIPasteboard.general.string = value |
| 181 | copied = true |
| 182 | #endif |
| 183 | if copied { AccessibilityNotification.Announcement(node.copied ?? "").post() } |
| 184 | } label: { |
| 185 | Label(copied ? (node.copied ?? "") : (node.copy ?? ""), systemImage: copied ? "checkmark" : "doc.on.doc") |
| 186 | } |
| 187 | .buttonStyle(.plain) |
| 188 | .foregroundStyle(p[.focus]) |
| 189 | .disabled(node.copyEnabled != true) |
| 190 | } |
| 191 | .font(BaseFont.body(13, .medium, relativeTo: .footnote)) |
| 192 | .padding(.horizontal, 12).padding(.vertical, 8) |
| 193 | .background(p[.chip]) |
| 194 | MarkdownCode(text: node.text ?? "", wraps: node.wrap == true) |
| 195 | } |
| 196 | .background(p[.well]) |
| 197 | .clipShape(.rect(cornerRadius: 10)) |
| 198 | .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(p[.wellEdge], lineWidth: 1)) |
| 199 | .onChange(of: node.text) { _, _ in copied = false } |
| 200 | .task(id: copied) { |
| 201 | guard copied else { return } |
| 202 | do { try await Task.sleep(for: .milliseconds(1800)); copied = false } catch {} |
| 203 | } |
| 204 | .accessibilityElement(children: .contain) |
| 205 | .accessibilityLabel(Text(verbatim: MarkdownPresentation.pasteLabel(node))) |
| 206 | } |
| 207 | } |
| 208 | |