| 1 | import SwiftUI |
| 2 | #if os(macOS) |
| 3 | import AppKit |
| 4 | #else |
| 5 | import UIKit |
| 6 | #endif |
| 7 | |
| 8 | /// Native chat prose. Both platforms use the same tree and the same actions. |
| 9 | /// The source is untrusted text; only the web's link vocabulary is actionable. |
| 10 | public struct ChatMarkdownView: View { |
| 11 | private let text: String |
| 12 | private let draft: Bool |
| 13 | private let origin: URL |
| 14 | private let openTask: (String) -> Void |
| 15 | @Environment(\.openURL) private var openURL |
| 16 | private let stream: MarkdownStreamRenderer |
| 17 | private let request: MarkdownRenderCache.Request |
| 18 | private let initial: MarkdownRenderCache.Result |
| 19 | private var nodes: [ChatMarkdownNode] { |
| 20 | initial.complete ? initial.tree : stream.visible(for: request) ?? initial.tree |
| 21 | } |
| 22 | private let prepared: Bool |
| 23 | private let onHeightChange: () -> Void |
| 24 | |
| 25 | |
| 26 | |
| 27 | public init(_ text: String, draft: Bool = false, messageID: String? = nil, origin: URL, transcript: MarkdownTranscript, openTask: @escaping (String) -> Void, onHeightChange: @escaping () -> Void = {}) { |
| 28 | self.text = text; self.draft = draft; self.origin = origin; self.openTask = openTask |
| 29 | self.prepared = false; self.onHeightChange = onHeightChange |
| 30 | request = MarkdownRenderCache.Request(messageID: origin.absoluteString + "/" + (messageID ?? text), text: text, draft: draft) |
| 31 | initial = MarkdownRenderCache.shared.initial(request) |
| 32 | stream = transcript.renderer(for: request.messageID) |
| 33 | } |
| 34 | // Tests render the completed background parse without needing a live host. |
| 35 | init(rendered nodes: [ChatMarkdownNode], origin: URL, openTask: @escaping (String) -> Void) { |
| 36 | text = ""; draft = false; self.origin = origin; self.openTask = openTask |
| 37 | prepared = true; onHeightChange = {} |
| 38 | stream = MarkdownStreamRenderer() |
| 39 | request = MarkdownRenderCache.Request(messageID: "prepared", text: "", draft: false) |
| 40 | initial = MarkdownRenderCache.Result(tree: nodes, complete: true) |
| 41 | } |
| 42 | public var body: some View { |
| 43 | MarkdownBlocks(nodes: nodes) |
| 44 | .font(MarkdownTypography.prose).foregroundStyle(Palette.text).tint(Palette.accent) |
| 45 | .textSelection(.enabled) |
| 46 | .onAppear { |
| 47 | guard !prepared else { return } |
| 48 | stream.submit(request, needsParsing: !initial.complete) |
| 49 | } |
| 50 | .onChange(of: request) { |
| 51 | guard !prepared else { return } |
| 52 | stream.submit(request, needsParsing: !initial.complete) |
| 53 | } |
| 54 | .onGeometryChange(for: CGFloat.self, of: { $0.size.height }) { _, _ in onHeightChange() } |
| 55 | .environment(\.openURL, OpenURLAction { url in |
| 56 | guard let original = MarkdownActions.originalTarget(url, in: nodes), let destination = MarkdownActions.destination(original, origin: origin) else { return .discarded } |
| 57 | switch destination { |
| 58 | case .task(let id): openTask(id) |
| 59 | case .external(let target): openURL(target) |
| 60 | } |
| 61 | return .handled |
| 62 | }) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | enum MarkdownTypography { |
| 67 | static let macPointSize: CGFloat = 14 |
| 68 | static var prose: Font { |
| 69 | #if os(macOS) |
| 70 | .system(size: macPointSize) // MacType.line, as before native Markdown. |
| 71 | #else |
| 72 | .body |
| 73 | #endif |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | private struct MarkdownBlocks: View { |
| 78 | let nodes: [ChatMarkdownNode] |
| 79 | var body: some View { |
| 80 | VStack(alignment: .leading, spacing: 12) { |
| 81 | ForEach(MarkdownPresentation.rows(nodes)) { row in |
| 82 | HStack(alignment: .top, spacing: 8) { |
| 83 | if let marker = row.marker { Text(verbatim: marker).monospacedDigit().accessibilityHidden(true) } |
| 84 | MarkdownBlockView(node: row.node) |
| 85 | } |
| 86 | .padding(.leading, CGFloat(row.indentation) * 16) |
| 87 | } |
| 88 | }.frame(maxWidth: .infinity, alignment: .leading) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | private struct MarkdownBlockView: View { |
| 93 | let node: ChatMarkdownNode |
| 94 | var body: some View { |
| 95 | switch node.kind { |
| 96 | case "paragraph", "inlineGroup": |
| 97 | Text(inline(node.children)).fixedSize(horizontal: false, vertical: true) |
| 98 | case "plain": Text(verbatim: node.text ?? "").fixedSize(horizontal: false, vertical: true) |
| 99 | case "paste": MarkdownPasteBox(node: node) |
| 100 | case "codeBlock": MarkdownCode(text: node.text ?? "", wraps: false) |
| 101 | default: EmptyView() |
| 102 | } |
| 103 | } |
| 104 | private func prose(_ text: String) -> String { |
| 105 | text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression) |
| 106 | } |
| 107 | private func inline(_ nodes: [ChatMarkdownNode]) -> AttributedString { |
| 108 | struct Work { var node: ChatMarkdownNode; var bold = false; var italic = false; var link: String? } |
| 109 | var stack = nodes.reversed().map { Work(node: $0) } |
| 110 | var result = AttributedString() |
| 111 | while let work = stack.popLast() { |
| 112 | let node = work.node |
| 113 | if !["text", "code", "break"].contains(node.kind) { |
| 114 | for child in node.children.reversed() { |
| 115 | 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)) |
| 116 | } |
| 117 | continue |
| 118 | } |
| 119 | var part = AttributedString(node.kind == "break" ? "\n" : prose(node.text ?? "")) |
| 120 | if node.kind == "code" { part.font = MarkdownTypography.prose.monospaced() } |
| 121 | var intent: InlinePresentationIntent = [] |
| 122 | if work.bold { intent.insert(.stronglyEmphasized) } |
| 123 | if work.italic { intent.insert(.emphasized) } |
| 124 | part.inlinePresentationIntent = intent |
| 125 | if let target = work.link, ChatMarkdown.allowsLink(target) { part.link = MarkdownActions.linkURL(target) } |
| 126 | if result.characters.last == " ", part.characters.first == " " { part.removeSubrange(part.startIndex..<part.index(afterCharacter: part.startIndex)) } |
| 127 | result.append(part) |
| 128 | } |
| 129 | return result |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | private struct MarkdownCode: View { |
| 134 | let text: String |
| 135 | let wraps: Bool |
| 136 | var body: some View { |
| 137 | if wraps { |
| 138 | Text(verbatim: text).font(MarkdownTypography.prose) |
| 139 | .fixedSize(horizontal: false, vertical: true) |
| 140 | .frame(maxWidth: .infinity, alignment: .leading).padding(12) |
| 141 | } else { |
| 142 | ScrollView(.horizontal) { |
| 143 | Text(verbatim: text).font(MarkdownTypography.prose.monospaced()).fixedSize() |
| 144 | .padding(12) |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | private struct MarkdownPasteBox: View { |
| 151 | let node: ChatMarkdownNode |
| 152 | @State private var copied = false |
| 153 | var body: some View { |
| 154 | VStack(alignment: .leading, spacing: 0) { |
| 155 | HStack { |
| 156 | if let label = node.label { Text(verbatim: label).foregroundStyle(Palette.secondary) } |
| 157 | Spacer(minLength: 8) |
| 158 | Button { |
| 159 | guard let value = MarkdownActions.copyText(node) else { return } |
| 160 | #if os(macOS) |
| 161 | NSPasteboard.general.clearContents() |
| 162 | copied = NSPasteboard.general.setString(value, forType: .string) |
| 163 | #else |
| 164 | UIPasteboard.general.string = value |
| 165 | copied = true |
| 166 | #endif |
| 167 | if copied { AccessibilityNotification.Announcement(node.copied ?? "").post() } |
| 168 | } label: { |
| 169 | Label(copied ? (node.copied ?? "") : (node.copy ?? ""), systemImage: copied ? "checkmark" : "doc.on.doc") |
| 170 | } |
| 171 | .buttonStyle(.plain) |
| 172 | .foregroundStyle(Palette.accent) |
| 173 | .disabled(node.copyEnabled != true) |
| 174 | } |
| 175 | .font(.callout).padding(.horizontal, 12).padding(.vertical, 8) |
| 176 | .background(Palette.surface2) |
| 177 | MarkdownCode(text: node.text ?? "", wraps: node.wrap == true) |
| 178 | } |
| 179 | .background(Palette.surface) |
| 180 | .clipShape(.rect(cornerRadius: 10)) |
| 181 | .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Palette.border, lineWidth: 1)) |
| 182 | .onChange(of: node.text) { _, _ in copied = false } |
| 183 | .task(id: copied) { |
| 184 | guard copied else { return } |
| 185 | do { try await Task.sleep(for: .milliseconds(1800)); copied = false } catch {} |
| 186 | } |
| 187 | .accessibilityElement(children: .contain) |
| 188 | .accessibilityLabel(Text(verbatim: MarkdownPresentation.pasteLabel(node))) |
| 189 | } |
| 190 | } |
| 191 | |