Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MarkdownMessageView.swift

1,236 lines45.6 KB

1import SwiftUI
2import UIKit
3​
4struct MarkdownImageContext: Equatable, @unchecked Sendable {
5 let threadID: String
6 let workspaceRoot: String
7 let resolver: any FeatureWorkspaceAssetResolving
8 var sourceFilePath: String? = nil
9​
10 static func == (lhs: Self, rhs: Self) -> Bool {
11 lhs.threadID == rhs.threadID
12 && lhs.workspaceRoot == rhs.workspaceRoot
13 && lhs.sourceFilePath == rhs.sourceFilePath
14 && ObjectIdentifier(lhs.resolver) == ObjectIdentifier(rhs.resolver)
15 }
17​
18/// Native chat Markdown with block-aware layout and Foundation inline parsing.
19struct MarkdownMessageView: View {
20 private struct RenderRequest: Hashable {
21 let revision: MarkdownContentRevision
22 let isStreaming: Bool
23 }
24​
25 private let source: String
26 private let revision: MarkdownContentRevision
27 private let isStreaming: Bool
28 private let copyActionTitle: String
29 private let imageContext: MarkdownImageContext?
30 private let skills: [FeatureProviderSkill]
31 private let clipboardSource: ComposerContextClipboardFragment.Source?
32 private let messageContext: OrchestrationMessageContext?
33 private let copyText: String?
34 @State private var copyError: String?
35 @State private var selectionSource: MarkdownSelectionSource
36 @State private var renderedDocument: MarkdownRenderedDocument?
37 @State private var streamingRenderer = StreamingMarkdownRenderer()
38​
39 init(
40 _ source: String,
41 isStreaming: Bool = false,
42 copyActionTitle: String = "Copy message",
43 imageContext: MarkdownImageContext? = nil,
44 skills: [FeatureProviderSkill] = [],
45 clipboardSource: ComposerContextClipboardFragment.Source? = nil,
46 messageContext: OrchestrationMessageContext? = nil,
47 copyText: String? = nil
48 ) {
49 self.source = source
50 self.isStreaming = isStreaming
51 self.copyActionTitle = copyActionTitle
52 self.imageContext = imageContext
53 self.skills = skills
54 self.clipboardSource = clipboardSource
55 self.messageContext = messageContext
56 self.copyText = copyText
57 _selectionSource = State(initialValue: MarkdownSelectionSource(source))
58 let revision = MarkdownContentRevision(source)
59 self.revision = revision
60 let initialDocument = if isStreaming {
61 MarkdownRenderCache.shared.cachedDocument(for: revision)
62 } else {
63 MarkdownRenderCache.shared.documentImmediately(for: revision)
64 }
65 _renderedDocument = State(
66 initialValue: initialDocument
67 )
68 }
69​
70 var body: some View {
71 let selectionContext = selectionContext
72 Group {
73 if let displayDocument {
74 MarkdownBlocksView(
75 blocks: displayDocument.blocks,
76 selectionContext: selectionContext,
77 imageContext: imageContext
78 )
79 } else {
80 // Parsing waits briefly so token-by-token streaming cancels stale revisions
81 // instead of scheduling work for content the user will never see.
82 Text(verbatim: source)
83 .font(T3Typography.threadBody)
84 .lineSpacing(4)
85 .fixedSize(horizontal: false, vertical: true)
86 }
87 }
88 .accessibilityAction(named: copyActionTitle) {
89 selectionSource.copyMessage()
90 }
91 .alert("Could not copy context", isPresented: Binding(
92 get: { copyError != nil }, set: { if !$0 { copyError = nil } }
93 )) {
94 Button("OK") { copyError = nil }
95 } message: { Text(copyError ?? "") }
96 .task(id: RenderRequest(revision: revision, isStreaming: isStreaming)) {
97 if !isStreaming {
98 streamingRenderer.cancel()
99 // Streaming -> complete usually keeps the final text; promote
100 // the last streamed render instead of reparsing synchronously.
101 if let renderedDocument, renderedDocument.revision == revision {
102 MarkdownRenderCache.shared.promote(renderedDocument)
103 return
104 }
105 renderedDocument = MarkdownRenderCache.shared.documentImmediately(for: revision)
106 return
107 }
108​
109 if let cached = MarkdownRenderCache.shared.cachedDocument(for: revision) {
110 renderedDocument = cached
111 return
112 }
113​
114 // Hand the revision to a renderer that outlives this task. The
115 // task modifier cancels on every revision, so rendering inside it
116 // starves as soon as parsing is slower than the publish cadence;
117 // the renderer instead keeps one render running and always picks
118 // up the newest revision when it finishes (latest wins).
119 streamingRenderer.submit(revision) { renderedDocument = $0 }
120 }
121 .onDisappear {
122 streamingRenderer.cancel()
123 }
124 }
125​
126 private var displayDocument: MarkdownRenderedDocument? {
127 if let renderedDocument, renderedDocument.revision == revision {
128 return renderedDocument
129 }
130 // While streaming, a slightly stale document is better than flashing
131 // back to plain text between renders. Streamed content only appends,
132 // so require the stale document to be a prefix of the current source:
133 // that accepts earlier snapshots of this message and rejects leftovers
134 // from a recycled cell showing a different message.
135 if isStreaming {
136 if let renderedDocument,
137 renderedDocument.revision.utf8Count <= revision.utf8Count,
138 source.utf8.starts(with: renderedDocument.revision.source.utf8) {
139 return renderedDocument
140 }
141 return nil
142 }
143 return MarkdownRenderCache.shared.documentImmediately(for: revision)
144 }
145​
146 private var selectionContext: MarkdownSelectionContext {
147 selectionSource.text = source
148 selectionSource.originalText = copyText ?? source
149 selectionSource.clipboardSource = clipboardSource
150 selectionSource.messageContext = messageContext
151 selectionSource.onCopyError = { copyError = $0 }
152 return MarkdownSelectionContext(
153 source: selectionSource,
154 copyActionTitle: copyActionTitle,
155 skills: skills
156 )
157 }
159​
160/// Renders streaming revisions outside SwiftUI's task lifecycle so a render
161/// in progress is never cancelled by the next revision arriving. One render
162/// runs at a time; newer revisions replace the pending slot (latest wins) and
163/// a 150ms throttle bounds the render cadence.
164@MainActor
165private final class StreamingMarkdownRenderer {
166 private let throttle: Duration = .milliseconds(150)
167 private var pending: MarkdownContentRevision?
168 private var deliver: ((MarkdownRenderedDocument) -> Void)?
169 private var renderTask: Task<Void, Never>?
170 private var generation = 0
171 private var lastRenderAt: Date?
172​
173 func submit(
174 _ revision: MarkdownContentRevision,
175 deliver: @escaping (MarkdownRenderedDocument) -> Void
176 ) {
177 pending = revision
178 self.deliver = deliver
179 guard renderTask == nil else { return }
180 generation += 1
181 let generation = generation
182 renderTask = Task { [weak self] in
183 await self?.drain(generation: generation)
184 }
185 }
186​
187 func cancel() {
188 generation += 1
189 renderTask?.cancel()
190 renderTask = nil
191 pending = nil
192 deliver = nil
193 }
194​
195 private func drain(generation: Int) async {
196 // A cancelled drain can unwind after a replacement was already
197 // started; only the current generation may clear the shared slot or
198 // deliver, so two drains can never race or regress the document.
199 defer {
200 if self.generation == generation { renderTask = nil }
201 }
202 while self.generation == generation, let revision = pending {
203 pending = nil
204 if let lastRenderAt {
205 let elapsed = Duration.seconds(-lastRenderAt.timeIntervalSinceNow)
206 if elapsed < throttle {
207 try? await Task.sleep(for: throttle - elapsed)
208 }
209 }
210 guard !Task.isCancelled else { return }
211 // Render the newest revision available after the throttle wait.
212 let target = pending ?? revision
213 pending = nil
214 guard let document = await MarkdownRenderCache.shared.document(
215 for: target,
216 isIntermediate: true
217 ) else { continue }
218 guard !Task.isCancelled, self.generation == generation else { return }
219 lastRenderAt = .now
220 deliver?(document)
221 }
222 }
224​
225private final class MarkdownSelectionSource: @unchecked Sendable {
226 var text: String
227 var originalText: String
228 var clipboardSource: ComposerContextClipboardFragment.Source?
229 var messageContext: OrchestrationMessageContext?
230 var onCopyError: ((String) -> Void)?
231​
232 init(_ text: String) {
233 self.text = text
234 originalText = text
235 }
236​
237 @MainActor func copyMessage() {
238 do {
239 if try !FeatureContextClipboard.write(text: originalText, source: clipboardSource, context: messageContext) {
240 UIPasteboard.general.string = originalText
241 }
242 } catch { onCopyError?(error.localizedDescription) }
243 }
245​
246private struct MarkdownSelectionContext: Equatable, Sendable {
247 let source: MarkdownSelectionSource
248 let copyActionTitle: String
249 let skills: [FeatureProviderSkill]
250​
251 static func == (lhs: Self, rhs: Self) -> Bool {
252 lhs.source === rhs.source
253 && lhs.copyActionTitle == rhs.copyActionTitle
254 && lhs.skills == rhs.skills
255 }
257​
258private enum MarkdownTextColor: Equatable, Sendable {
259 case primary
260 case secondary
261​
262 var uiColor: UIColor {
263 switch self {
264 case .primary: T3Colors.uiTextPrimary
265 case .secondary: T3Colors.uiTextSecondary
266 }
267 }
269​
270private struct MarkdownBlocksView: View {
271 let blocks: [MarkdownRenderedBlock]
272 let selectionContext: MarkdownSelectionContext
273 let imageContext: MarkdownImageContext?
274 var spacing: CGFloat = 12
275 var textColor: MarkdownTextColor = .primary
276​
277 var body: some View {
278 VStack(alignment: .leading, spacing: spacing) {
279 ForEach(blocks.indices, id: \.self) { index in
280 // Unchanged blocks share inline runs by reference across
281 // streaming revisions, so equatable comparison skips their
282 // body and layout entirely; only the changed tail re-renders.
283 MarkdownBlockView(
284 block: blocks[index],
285 selectionContext: selectionContext,
286 imageContext: imageContext,
287 textColor: textColor
288 )
289 .equatable()
290 }
291 }
292 }
294​
295private struct MarkdownBlockView: View, Equatable {
296 let block: MarkdownRenderedBlock
297 let selectionContext: MarkdownSelectionContext
298 let imageContext: MarkdownImageContext?
299 let textColor: MarkdownTextColor
300​
301 @ViewBuilder
302 var body: some View {
303 switch block {
304 case let .paragraph(inline):
305 MarkdownInlineText(
306 inline,
307 selectionContext: selectionContext,
308 lineSpacing: 4,
309 textColor: textColor
310 )
311​
312 case let .image(image):
313 MarkdownImageView(image: image, context: imageContext)
314​
315 case let .heading(level, inline):
316 MarkdownInlineText(
317 inline,
318 selectionContext: selectionContext,
319 textColor: textColor
320 )
321 .padding(.top, level <= 2 ? 3 : 1)
322​
323 case let .unorderedList(items):
324 MarkdownListView(
325 items: items,
326 start: nil,
327 selectionContext: selectionContext,
328 imageContext: imageContext,
329 textColor: textColor
330 )
331​
332 case let .orderedList(start, items):
333 MarkdownListView(
334 items: items,
335 start: start,
336 selectionContext: selectionContext,
337 imageContext: imageContext,
338 textColor: textColor
339 )
340​
341 case let .blockquote(blocks):
342 MarkdownBlocksView(
343 blocks: blocks,
344 selectionContext: selectionContext,
345 imageContext: imageContext,
346 spacing: 9,
347 textColor: .secondary
348 )
349 .foregroundStyle(T3Colors.textSecondary)
350 .padding(.leading, 14)
351 .overlay(alignment: .leading) {
352 Rectangle()
353 .fill(T3Colors.textTertiary)
354 .frame(width: 2)
355 }
356​
357 case let .table(table):
358 MarkdownTableView(
359 table: table,
360 selectionContext: selectionContext,
361 textColor: textColor
362 )
363​
364 case let .codeBlock(language, code, renderedCode):
365 MarkdownCodeBlockView(
366 language: language,
367 code: code,
368 renderedCode: renderedCode,
369 selectionContext: selectionContext
370 )
371​
372 case let .artifactTemplate(template):
373 CodexArtifactTemplateView(template: template)
374​
375 case .thematicBreak:
376 Rectangle()
377 .fill(T3Colors.separator)
378 .frame(height: 1)
379 .padding(.vertical, 2)
380 .accessibilityHidden(true)
381 }
382 }
384​
385private struct MarkdownTableView: View {
386 let table: MarkdownRenderedTable
387 let selectionContext: MarkdownSelectionContext
388 let textColor: MarkdownTextColor
389​
390 private var columnWidths: [CGFloat] { table.columnWidths }
391​
392 var body: some View {
393 ScrollView(.horizontal) {
394 Grid(horizontalSpacing: 0, verticalSpacing: 0) {
395 tableRow(table.header, isHeader: true)
396 ForEach(table.rows.indices, id: \.self) { rowIndex in
397 tableRow(table.rows[rowIndex], isHeader: false)
398 }
399 }
400 // A horizontal ScrollView still proposes the viewport width to its child.
401 // Preserve the grid's measured column widths so it overflows and scrolls
402 // instead of compressing prose columns into unreadable slivers.
403 .fixedSize(horizontal: true, vertical: true)
404 .background(T3Colors.surface)
405 .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
406 .overlay {
407 RoundedRectangle(cornerRadius: 8, style: .continuous)
408 .stroke(T3Colors.border, lineWidth: 1)
409 }
410 }
411 .scrollIndicators(.visible)
412 .accessibilityElement(children: .contain)
413 .accessibilityLabel("Table with \(table.header.count) columns and \(table.rows.count) rows")
414 }
415​
416 private func tableRow(
417 _ cells: [MarkdownRenderedInline],
418 isHeader: Bool
419 ) -> some View {
420 GridRow(alignment: .top) {
421 ForEach(cells.indices, id: \.self) { columnIndex in
422 MarkdownInlineText(
423 cells[columnIndex],
424 selectionContext: selectionContext,
425 lineSpacing: 3,
426 textColor: textColor
427 )
428 .frame(
429 width: columnWidths[columnIndex],
430 alignment: alignment(for: columnIndex)
431 )
432 .frame(
433 minHeight: 44,
434 maxHeight: .infinity,
435 alignment: alignment(for: columnIndex)
436 )
437 .padding(.horizontal, 11)
438 .padding(.vertical, 8)
439 .overlay(alignment: .trailing) {
440 if columnIndex < cells.count - 1 {
441 Rectangle()
442 .fill(T3Colors.separator)
443 .frame(width: 1)
444 }
445 }
446 }
447 }
448 .background(isHeader ? T3Colors.surfaceRaised : T3Colors.surface)
449 .overlay(alignment: .bottom) {
450 Rectangle()
451 .fill(T3Colors.separator)
452 .frame(height: 1)
453 }
454 }
455​
456 private func alignment(for columnIndex: Int) -> Alignment {
457 guard table.alignments.indices.contains(columnIndex) else { return .leading }
458 return switch table.alignments[columnIndex] {
459 case .natural, .leading: .leading
460 case .center: .center
461 case .trailing: .trailing
462 }
463 }
464​
466​
467private struct MarkdownListView: View {
468 let items: [MarkdownRenderedListItem]
469 let start: Int?
470 let selectionContext: MarkdownSelectionContext
471 let imageContext: MarkdownImageContext?
472 let textColor: MarkdownTextColor
473​
474 var body: some View {
475 VStack(alignment: .leading, spacing: 8) {
476 ForEach(items.indices, id: \.self) { offset in
477 let item = items[offset]
478 HStack(alignment: .top, spacing: 8) {
479 marker(for: item, offset: offset)
480 .frame(width: 24, height: 24, alignment: .trailing)
481 MarkdownBlocksView(
482 blocks: item.blocks,
483 selectionContext: selectionContext,
484 imageContext: imageContext,
485 spacing: 7,
486 textColor: textColor
487 )
488 }
489 .accessibilityElement(children: .contain)
490 }
491 }
492 }
493​
494 @ViewBuilder
495 private func marker(for item: MarkdownRenderedListItem, offset: Int) -> some View {
496 if let task = item.task {
497 Image(systemName: task == .complete ? "checkmark.square.fill" : "square")
498 .font(T3Typography.control)
499 .foregroundStyle(
500 task == .complete ? T3Colors.success : T3Colors.textSecondary
501 )
502 .accessibilityLabel(task == .complete ? "Completed" : "Not completed")
503 } else if let start {
504 Text("\(start + offset).")
505 .font(T3Typography.supporting.monospaced())
506 .foregroundStyle(T3Colors.textSecondary)
507 .accessibilityLabel("Item \(start + offset)")
508 } else {
509 Text("•")
510 .font(T3Typography.threadBody.weight(.semibold))
511 .foregroundStyle(T3Colors.textSecondary)
512 .accessibilityHidden(true)
513 }
514 }
516​
517private struct MarkdownImageView: View {
518 private struct Request: Equatable {
519 let image: MarkdownImage
520 let context: MarkdownImageContext?
521 let maximumPixelSize: Int
522 }
523​
524 let image: MarkdownImage
525 let context: MarkdownImageContext?
526​
527 @SwiftUI.Environment(\.openURL) private var openURL
528 @SwiftUI.Environment(\.displayScale) private var displayScale
529 @State private var loadedImage: MarkdownDecodedImage?
530 @State private var activeRequest: Request?
531 @State private var knownSize: CGSize?
532 @State private var previewURL: URL?
533 @State private var failed = false
534​
535 private var request: Request {
536 Request(image: image, context: context, maximumPixelSize: min(2_048, max(512, Int(ceil(480 * displayScale)))))
537 }
538​
539 private var classifiedSource: MarkdownImageSource {
540 let basePath = context?.sourceFilePath.map {
541 let isWindows = $0.contains("\\")
542 let normalized = $0.replacingOccurrences(of: "\\", with: "/")
543 let parent = (normalized as NSString).deletingLastPathComponent
544 return isWindows ? parent.replacingOccurrences(of: "/", with: "\\") : parent
545 } ?? context?.workspaceRoot
546 return MarkdownImageSource.classify(image.source, workspaceRoot: basePath)
547 }
548​
549 var body: some View {
550 if classifiedSource != .blocked {
551 let currentRequest = activeRequest == request
552 let decoded = currentRequest ? loadedImage : nil
553 MarkdownImageLayout(sourceSize: decoded?.sourceSize ?? (currentRequest ? knownSize : nil)) {
554 if let decoded {
555 Image(uiImage: decoded.image)
556 .resizable()
557 .scaledToFit()
558 } else {
559 Image(systemName: currentRequest && failed ? "exclamationmark.triangle" : "photo")
560 .font(.title2)
561 .foregroundStyle(T3Colors.textSecondary)
562 .frame(maxWidth: .infinity, maxHeight: .infinity)
563 .background(T3Colors.surfaceRaised)
564 }
565 }
566 .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
567 .accessibilityLabel(image.alternativeText.isEmpty ? "Image" : image.alternativeText)
568 .accessibilityAddTraits(.isButton)
569 .contentShape(Rectangle())
570 .onTapGesture {
571 if currentRequest, let previewURL { openURL(previewURL) }
572 }
573 .task(id: request) {
574 await loadImage()
575 }
576 }
577 }
578​
579 @MainActor
580 private func loadImage() async {
581 let loadingRequest = request
582 activeRequest = loadingRequest
583 loadedImage = nil
584 knownSize = nil
585 failed = false
586 previewURL = nil
587 do {
588 let url: URL
589 switch classifiedSource {
590 case let .direct(directURL):
591 url = directURL
592 if directURL.scheme == "http" || directURL.scheme == "https" {
593 previewURL = directURL
594 }
595 case let .workspaceFile(path):
596 guard let context else { return }
597 var components = URLComponents()
598 components.scheme = "t3code"
599 components.host = "media-preview"
600 components.path = "/open"
601 components.queryItems = [
602 URLQueryItem(name: "path", value: path),
603 URLQueryItem(name: "kind", value: "image"),
604 ]
605 previewURL = components.url
606 let asset = try await context.resolver.mediaAsset(
607 threadID: context.threadID,
608 path: path
609 )
610 try Task.checkCancellation()
611 knownSize = MarkdownImageGeometry.sourceSize(asset.imageDimensions)
612 url = asset.url
613 case .blocked:
614 return
615 }
616 let decoded = try await MarkdownImageLoader.load(url, maximumPixelSize: loadingRequest.maximumPixelSize)
617 try Task.checkCancellation()
618 loadedImage = decoded
619 } catch is CancellationError {
620 return
621 } catch {
622 guard !Task.isCancelled else { return }
623 failed = true
624 }
625 }
627​
628private struct CodexArtifactTemplateView: View {
629 let template: CodexArtifactTemplate
630 @SwiftUI.Environment(\.openURL) private var openURL
631​
632 var body: some View {
633 HStack(spacing: 10) {
634 VStack(alignment: .leading, spacing: 2) {
635 Text(template.displayName)
636 .font(T3Typography.threadBody.weight(.medium))
637 .foregroundStyle(T3Colors.textPrimary)
638 Text(template.kind.label)
639 .font(T3Typography.supporting)
640 .foregroundStyle(T3Colors.textSecondary)
641 }
642 Spacer(minLength: 8)
643 Button("Use") {
644 if let url = template.useURL { openURL(url) }
645 }
646 .buttonStyle(.bordered)
647 }
648 .padding(.vertical, 4)
649 }
651​
652@MainActor
653private enum MarkdownImageLoader {
654 private final class CachedImage {
655 let decoded: MarkdownDecodedImage
656 init(_ decoded: MarkdownDecodedImage) { self.decoded = decoded }
657 }
658​
659 private static let cache: NSCache<NSString, CachedImage> = {
660 let cache = NSCache<NSString, CachedImage>()
661 cache.countLimit = 64
662 cache.totalCostLimit = 32 * 1_024 * 1_024
663 return cache
664 }()
665​
666 private static let session: URLSession = {
667 let configuration = URLSessionConfiguration.ephemeral
668 configuration.httpShouldSetCookies = false
669 configuration.httpCookieStorage = nil
670 configuration.urlCredentialStorage = nil
671 return URLSession(configuration: configuration)
672 }()
673​
674 static func load(_ url: URL, maximumPixelSize: Int) async throws -> MarkdownDecodedImage {
675 let cacheKey = "\(url.absoluteString)#\(maximumPixelSize)" as NSString
676 if let cached = cache.object(forKey: cacheKey) {
677 return cached.decoded
678 }
679​
680 let data: Data
681 if url.scheme?.lowercased() == "data" {
682 guard let comma = url.absoluteString.firstIndex(of: ","),
683 url.absoluteString[..<comma].lowercased().contains(";base64"),
684 let decoded = Data(base64Encoded: String(url.absoluteString[url.absoluteString.index(after: comma)...])) else {
685 throw MarkdownImageLoadingError.invalidImage
686 }
687 data = decoded
688 } else {
689 let response: URLResponse
690 (data, response) = try await session.data(from: url)
691 if let httpResponse = response as? HTTPURLResponse,
692 !(200...299).contains(httpResponse.statusCode) {
693 throw MarkdownImageLoadingError.invalidResponse
694 }
695 }
696 try Task.checkCancellation()
697 let decoded = try await Task.detached(priority: .utility) {
698 try MarkdownImageDecoder.decode(data, maximumPixelSize: maximumPixelSize)
699 }.value
700 try Task.checkCancellation()
701 let cost = decoded.image.cgImage.map { $0.bytesPerRow * $0.height } ?? data.count
702 cache.setObject(CachedImage(decoded), forKey: cacheKey, cost: cost)
703 return decoded
704 }
706​
707private struct MarkdownCodeBlockView: View {
708 let language: String?
709 let code: String
710 let renderedCode: MarkdownRenderedInline
711 let selectionContext: MarkdownSelectionContext
712 @State private var wrapOverride: Bool?
713​
714 private var wrapsLines: Bool {
715 wrapOverride ?? MarkdownCodeBlockWrapping.wrapsByDefault(language: language)
716 }
717​
718 var body: some View {
719 VStack(alignment: .leading, spacing: 0) {
720 HStack(spacing: 8) {
721 if let language, !language.isEmpty {
722 Text(language.uppercased())
723 .font(T3Typography.supportingStrong)
724 .foregroundStyle(T3Colors.textTertiary)
725 } else {
726 Text("CODE")
727 .font(T3Typography.supportingStrong)
728 .foregroundStyle(T3Colors.textTertiary)
729 }
730 Spacer(minLength: 8)
731 Button {
732 wrapOverride = !wrapsLines
733 } label: {
734 Label("Wrap", systemImage: "arrow.turn.down.left")
735 .font(T3Typography.control)
736 .foregroundStyle(wrapsLines ? T3Colors.accent : T3Colors.textSecondary)
737 .frame(minHeight: 32)
738 }
739 .buttonStyle(.plain)
740 .accessibilityValue(wrapsLines ? "On" : "Off")
741 .accessibilityHint("Toggles line wrapping for this code block")
742 Button {
743 UIPasteboard.general.string = code
744 } label: {
745 Label("Copy", systemImage: "doc.on.doc")
746 .font(T3Typography.control)
747 .foregroundStyle(T3Colors.textSecondary)
748 .frame(minHeight: 32)
749 }
750 .buttonStyle(.plain)
751 .accessibilityHint("Copies this code block")
752 }
753 .padding(.horizontal, 13)
754 .frame(minHeight: 40)
755​
756 Rectangle()
757 .fill(T3Colors.separator)
758 .frame(height: 1)
759​
760 Group {
761 if wrapsLines {
762 MarkdownInlineText(
763 renderedCode,
764 selectionContext: selectionContext,
765 lineSpacing: 3,
766 wrapsLines: true
767 )
768 .frame(maxWidth: .infinity, alignment: .leading)
769 .padding(13)
770 } else {
771 ScrollView(.horizontal) {
772 MarkdownInlineText(
773 renderedCode,
774 selectionContext: selectionContext,
775 lineSpacing: 3,
776 wrapsLines: false
777 )
778 .fixedSize(horizontal: true, vertical: true)
779 .padding(13)
780 }
781 .scrollIndicators(.hidden)
782 }
783 }
784 .t3CodeTextSize()
785 }
786 .background(T3Colors.surfaceRaised)
787 .clipShape(RoundedRectangle(cornerRadius: 10))
788 .overlay {
789 RoundedRectangle(cornerRadius: 10)
790 .stroke(T3Colors.border, lineWidth: 1)
791 }
792 }
794​
795enum MarkdownCodeBlockWrapping {
796 private static let proseLanguages: Set<String> = [
797 "markdown",
798 "md",
799 "plain",
800 "plaintext",
801 "text",
802 "text/plain",
803 "txt",
804 ]
805​
806 static func wrapsByDefault(language: String?) -> Bool {
807 guard let language else { return false }
808 return proseLanguages.contains(language.lowercased())
809 }
811​
812private struct MarkdownInlineText: UIViewRepresentable {
813 @SwiftUI.Environment(\.dynamicTypeSize) private var dynamicTypeSize
814 @SwiftUI.Environment(\.openURL) private var openURL
815​
816 let rendered: MarkdownRenderedInline
817 let selectionContext: MarkdownSelectionContext
818 let lineSpacing: CGFloat
819 let textColor: MarkdownTextColor
820 let wrapsLines: Bool
821​
822 init(
823 _ rendered: MarkdownRenderedInline,
824 selectionContext: MarkdownSelectionContext,
825 lineSpacing: CGFloat = 0,
826 textColor: MarkdownTextColor = .primary,
827 wrapsLines: Bool = true
828 ) {
829 self.rendered = rendered
830 self.selectionContext = selectionContext
831 self.lineSpacing = lineSpacing
832 self.textColor = textColor
833 self.wrapsLines = wrapsLines
834 }
835​
836 func makeCoordinator() -> Coordinator {
837 Coordinator()
838 }
839​
840 func makeUIView(context: Context) -> UITextView {
841 let textView = FeatureInlineSkillTextView()
842 textView.backgroundColor = .clear
843 textView.isEditable = false
844 textView.isSelectable = true
845 textView.isScrollEnabled = false
846 textView.showsHorizontalScrollIndicator = false
847 textView.showsVerticalScrollIndicator = false
848 textView.textContainerInset = .zero
849 textView.textContainer.lineFragmentPadding = 0
850 textView.textContainer.widthTracksTextView = true
851 textView.textContainer.lineBreakMode = wrapsLines ? .byWordWrapping : .byClipping
852 textView.adjustsFontForContentSizeCategory = true
853 textView.linkTextAttributes = [
854 .foregroundColor: T3Colors.uiAccent,
855 .underlineStyle: 0,
856 ]
857 textView.accessibilityTraits = .staticText
858 textView.delegate = context.coordinator
859 textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
860 textView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
861 return textView
862 }
863​
864 func updateUIView(_ textView: UITextView, context: Context) {
865 let attributedText = context.coordinator.attributedText(
866 from: rendered,
867 lineSpacing: lineSpacing,
868 textColor: textColor,
869 dynamicTypeSize: dynamicTypeSize,
870 wrapsLines: wrapsLines,
871 skills: selectionContext.skills,
872 traits: textView.traitCollection
873 )
874 if context.coordinator.shouldApply(attributedText) {
875 let previousText = context.coordinator.lastAppliedText
876 let previousSelection = textView.selectedRange
877 textView.attributedText = attributedText
878 textView.selectedRange = MarkdownSelectionRestoration.range(
879 previousText: previousText,
880 previousRange: previousSelection,
881 newText: attributedText.string
882 )
883 context.coordinator.didApply(attributedText)
884 }
885 context.coordinator.selectionContext = selectionContext
886 if let textView = textView as? FeatureInlineSkillTextView {
887 let source = selectionContext.source
888 textView.onCopySelection = { selected in
889 try FeatureContextClipboard.write(
890 text: FeatureContextClipboard.selectionText(selected, originalSource: source.originalText),
891 source: source.clipboardSource, context: source.messageContext
892 )
893 }
894 textView.onCopyError = source.onCopyError
895 }
896 context.coordinator.onOpenURL = { url in
897 openURL(url)
898 }
899 textView.accessibilityCustomActions = context.coordinator.accessibilityActions(
900 title: selectionContext.copyActionTitle
901 )
902 }
903​
904 func sizeThatFits(
905 _ proposal: ProposedViewSize,
906 uiView: UITextView,
907 context: Context
908 ) -> CGSize? {
909 guard let proposedWidth = proposal.width,
910 proposedWidth.isFinite,
911 proposedWidth > 0
912 else {
913 return wrapsLines ? nil : context.coordinator.unwrappedSize(for: uiView)
914 }
915 return context.coordinator.size(
916 for: uiView,
917 proposedWidth: proposedWidth,
918 wrapsLines: wrapsLines
919 )
920 }
921​
922 final class Coordinator: NSObject, UITextViewDelegate {
923 private struct CacheKey: Equatable {
924 let lineSpacing: CGFloat
925 let textColor: MarkdownTextColor
926 let dynamicTypeSize: DynamicTypeSize
927 let wrapsLines: Bool
928 let skills: [FeatureProviderSkill]
929 let userInterfaceStyle: UIUserInterfaceStyle
930 }
931​
932 private struct SizeKey: Hashable {
933 let proposedWidth: CGFloat
934 let wrapsLines: Bool
935 }
936​
937 var selectionContext = MarkdownSelectionContext(
938 source: MarkdownSelectionSource(""),
939 copyActionTitle: "Copy message",
940 skills: []
941 )
942 var onOpenURL: ((URL) -> Void)?
943 private var cacheKey: CacheKey?
944 private var cachedRendered: MarkdownRenderedInline?
945 private var cachedAttributedText: NSAttributedString?
946 private var cachedSizes: [SizeKey: CGSize] = [:]
947 private var lastAppliedAttributedText: NSAttributedString?
948 private var cachedAccessibilityTitle: String?
949 private var cachedAccessibilityActions: [UIAccessibilityCustomAction] = []
950​
951 func attributedText(
952 from rendered: MarkdownRenderedInline,
953 lineSpacing: CGFloat,
954 textColor: MarkdownTextColor,
955 dynamicTypeSize: DynamicTypeSize,
956 wrapsLines: Bool,
957 skills: [FeatureProviderSkill],
958 traits: UITraitCollection
959 ) -> NSAttributedString {
960 let key = CacheKey(
961 lineSpacing: lineSpacing,
962 textColor: textColor,
963 dynamicTypeSize: dynamicTypeSize,
964 wrapsLines: wrapsLines,
965 skills: skills,
966 userInterfaceStyle: traits.userInterfaceStyle
967 )
968 if cachedRendered === rendered, key == cacheKey, let cachedAttributedText {
969 return cachedAttributedText
970 }
971 let attributedText = MarkdownSelectableTextAttributes.make(
972 from: rendered,
973 lineSpacing: lineSpacing,
974 foregroundColor: textColor.uiColor,
975 dynamicTypeSize: dynamicTypeSize,
976 wrapsLines: wrapsLines,
977 skills: skills,
978 traits: traits
979 )
980 cacheKey = key
981 cachedRendered = rendered
982 cachedAttributedText = attributedText
983 cachedSizes.removeAll(keepingCapacity: true)
984 return attributedText
985 }
986​
987 var lastAppliedText: String {
988 lastAppliedAttributedText?.string ?? ""
989 }
990​
991 func shouldApply(_ attributedText: NSAttributedString) -> Bool {
992 lastAppliedAttributedText !== attributedText
993 }
994​
995 func didApply(_ attributedText: NSAttributedString) {
996 lastAppliedAttributedText = attributedText
997 }
998​
999 func size(
1000 for textView: UITextView,
1001 proposedWidth: CGFloat,
1002 wrapsLines: Bool
1003 ) -> CGSize {
1004 let key = SizeKey(proposedWidth: proposedWidth, wrapsLines: wrapsLines)
1005 if let cached = cachedSizes[key] {
1006 return cached
1008 let bounds = textView.attributedText.boundingRect(
1009 with: CGSize(width: proposedWidth, height: .greatestFiniteMagnitude),
1010 options: [.usesLineFragmentOrigin, .usesFontLeading],
1011 context: nil
1013 let width = min(proposedWidth, max(1, ceil(bounds.width)))
1014 let fittingSize = textView.sizeThatFits(
1015 CGSize(width: width, height: .greatestFiniteMagnitude)
1017 let size = CGSize(width: width, height: max(1, ceil(fittingSize.height)))
1018 cachedSizes[key] = size
1019 return size
1021​
1022 func unwrappedSize(for textView: UITextView) -> CGSize {
1023 let key = SizeKey(proposedWidth: .infinity, wrapsLines: false)
1024 if let cached = cachedSizes[key] {
1025 return cached
1027 let longestLineLength = textView.attributedText.string
1028 .split(separator: "\n", omittingEmptySubsequences: false)
1029 .map(\.utf16.count)
1030 .max() ?? 0
1031 var largestFontPointSize: CGFloat = 0
1032 textView.attributedText.enumerateAttribute(
1033 .font,
1034 in: NSRange(location: 0, length: textView.attributedText.length)
1035 ) { value, _, _ in
1036 largestFontPointSize = max(
1037 largestFontPointSize,
1038 (value as? UIFont)?.pointSize ?? 0
1041 let perCharacterWidth = max(16, largestFontPointSize * 1.5)
1042 let maximumWidth = max(2_048, CGFloat(longestLineLength) * perCharacterWidth)
1043 let bounds = textView.attributedText.boundingRect(
1044 with: CGSize(width: maximumWidth, height: .greatestFiniteMagnitude),
1045 options: [.usesLineFragmentOrigin, .usesFontLeading],
1046 context: nil
1048 let fittingSize = textView.sizeThatFits(
1049 CGSize(width: max(1, ceil(bounds.width)), height: .greatestFiniteMagnitude)
1051 let size = CGSize(
1052 width: max(1, ceil(bounds.width)),
1053 height: max(1, ceil(fittingSize.height))
1055 cachedSizes[key] = size
1056 return size
1058​
1059 func accessibilityActions(title: String) -> [UIAccessibilityCustomAction] {
1060 if cachedAccessibilityTitle == title {
1061 return cachedAccessibilityActions
1063 cachedAccessibilityTitle = title
1064 cachedAccessibilityActions = [
1065 UIAccessibilityCustomAction(
1066 name: title
1067 ) { [weak self] _ in
1068 self?.copyMessage()
1069 return true
1070 },
1072 return cachedAccessibilityActions
1074​
1075 func textView(
1076 _ textView: UITextView,
1077 editMenuForTextIn range: NSRange,
1078 suggestedActions: [UIMenuElement]
1079 ) -> UIMenu? {
1080 let copyMessage = UIAction(
1081 title: selectionContext.copyActionTitle,
1082 image: UIImage(systemName: "doc.on.doc")
1083 ) { [weak self] _ in
1084 self?.copyMessage()
1086 return UIMenu(children: suggestedActions + [copyMessage])
1088​
1089 func textView(
1090 _ textView: UITextView,
1091 primaryActionFor textItem: UITextItem,
1092 defaultAction: UIAction
1093 ) -> UIAction? {
1094 guard case let .link(url) = textItem.content else { return defaultAction }
1095 return UIAction { [weak self] _ in
1096 self?.onOpenURL?(url)
1099​
1100 private func copyMessage() {
1101 selectionContext.source.copyMessage()
1105​
1106enum MarkdownSelectableTextAttributes {
1107 @MainActor
1108 static func make(
1109 from rendered: MarkdownRenderedInline,
1110 lineSpacing: CGFloat,
1111 foregroundColor: UIColor = T3Colors.uiTextPrimary,
1112 dynamicTypeSize: DynamicTypeSize = .large,
1113 wrapsLines: Bool = true,
1114 skills: [FeatureProviderSkill] = [],
1115 traits: UITraitCollection = .current
1116 ) -> NSAttributedString {
1117 let result = NSMutableAttributedString()
1118 let paragraphStyle = NSMutableParagraphStyle()
1119 paragraphStyle.lineSpacing = lineSpacing
1120 paragraphStyle.lineBreakMode = wrapsLines ? .byWordWrapping : .byClipping
1121​
1122 for run in rendered.attributedText.runs {
1123 let intent = run.inlinePresentationIntent
1124 var attributes: [NSAttributedString.Key: Any] = [
1125 .font: font(
1126 for: rendered.style,
1127 intent: intent,
1128 dynamicTypeSize: dynamicTypeSize
1129 ),
1130 .foregroundColor: foregroundColor,
1131 .paragraphStyle: paragraphStyle,
1133 if intent?.contains(.code) == true {
1134 attributes[.backgroundColor] = T3Colors.uiSurfaceRaised
1136 if intent?.contains(.strikethrough) == true {
1137 attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue
1139 if let link = run.link {
1140 attributes[.link] = link
1142 let runText = String(rendered.attributedText[run.range].characters)
1143 let hasLeadingBoundary = run.range.lowerBound == rendered.attributedText.startIndex
1144 || rendered.attributedText.characters[
1145 rendered.attributedText.characters.index(before: run.range.lowerBound)
1146 ].isWhitespace
1147 let hasTrailingBoundary = run.range.upperBound == rendered.attributedText.endIndex
1148 || rendered.attributedText.characters[run.range.upperBound].isWhitespace
1149 let runLength = (runText as NSString).length
1150 let descriptors = rendered.style == .code
1151 || intent?.contains(.code) == true
1152 || run.link != nil
1153 ? []
1154 : FeatureInlineSkillParser.descriptors(
1155 in: runText,
1156 skills: skills,
1157 allowsEndBoundary: true
1158 ).filter { descriptor in
1159 (descriptor.range.location > 0 || hasLeadingBoundary)
1160 && (NSMaxRange(descriptor.range) < runLength || hasTrailingBoundary)
1162 result.append(
1163 FeatureInlineSkillPillRenderer.attributedText(
1164 source: runText,
1165 descriptors: descriptors,
1166 baseAttributes: attributes,
1167 font: attributes[.font] as? UIFont
1168 ?? rendered.style.uiFont(dynamicTypeSize: dynamicTypeSize),
1169 traits: traits
1173​
1174 return result
1176​
1177 @MainActor
1178 private static func font(
1179 for style: MarkdownInlineStyle,
1180 intent: InlinePresentationIntent?,
1181 dynamicTypeSize: DynamicTypeSize
1182 ) -> UIFont {
1183 var font = style.uiFont(dynamicTypeSize: dynamicTypeSize)
1184 if intent?.contains(.code) == true, style != .code {
1185 font = UIFont.monospacedSystemFont(
1186 ofSize: font.pointSize,
1187 weight: .regular
1190​
1191 let addsBold = intent?.contains(.stronglyEmphasized) == true
1192 let addsItalic = intent?.contains(.emphasized) == true
1193 guard addsBold || addsItalic else { return font }
1194​
1195 var traits = font.fontDescriptor.symbolicTraits
1196 if addsBold {
1197 traits.insert(.traitBold)
1199 if addsItalic {
1200 traits.insert(.traitItalic)
1202 if let descriptor = font.fontDescriptor.withSymbolicTraits(traits) {
1203 font = UIFont(descriptor: descriptor, size: 0)
1205 return font
1208​
1209enum MarkdownSelectionRestoration {
1210 static func range(
1211 previousText: String,
1212 previousRange: NSRange,
1213 newText: String
1214 ) -> NSRange {
1215 guard newText.utf16.starts(with: previousText.utf16),
1216 NSMaxRange(previousRange) <= (newText as NSString).length
1217 else {
1218 return NSRange(location: 0, length: 0)
1220 return previousRange
1223​
1224enum MarkdownInlineFormatter {
1225 static func format(_ source: String) -> AttributedString {
1227 try? AttributedString(
1228 markdown: source,
1229 options: AttributedString.MarkdownParsingOptions(
1230 interpretedSyntax: .inlineOnlyPreservingWhitespace,
1231 failurePolicy: .returnPartiallyParsedIfPossible
1234 ) ?? AttributedString(source)