feat(ios): render rich markdown messages

This commit is contained in:
Theo Browne committed 2026-08-09 20:52:49 -07:00
1 parent 7cd72c515a
commit b19c18b293
4 files changed
+854 -5

No files matched your search

@@ -0,0 +1,463 @@
import Foundation
/// A small block-level Markdown model used by chat messages.
///
/// Foundation already provides a strong inline Markdown parser. This layer only
/// separates the block structures that `Text` otherwise flattens, keeping chat
/// rendering native and dependency-free.
struct MarkdownDocument: Equatable, Sendable {
let blocks: [MarkdownBlock]
init(parsing source: String) {
var parser = MarkdownBlockParser(source: source)
blocks = parser.parse()
}
fileprivate init(blocks: [MarkdownBlock]) {
self.blocks = blocks
}
}
indirect enum MarkdownBlock: Equatable, Sendable {
case paragraph(String)
case heading(level: Int, text: String)
case unorderedList([MarkdownListItem])
case orderedList(start: Int, items: [MarkdownListItem])
case blockquote(MarkdownDocument)
case codeBlock(language: String?, code: String)
case thematicBreak
}
struct MarkdownListItem: Equatable, Sendable {
let task: MarkdownTaskState?
let blocks: [MarkdownBlock]
}
enum MarkdownTaskState: Equatable, Sendable {
case incomplete
case complete
}
private struct MarkdownBlockParser {
private let lines: [String]
private var index = 0
init(source: String) {
let normalized = source
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
lines = normalized.components(separatedBy: "\n")
}
mutating func parse() -> [MarkdownBlock] {
var blocks: [MarkdownBlock] = []
while index < lines.count {
if lines[index].isMarkdownBlank {
index += 1
continue
}
if let fence = fenceMarker(in: lines[index]) {
blocks.append(parseCodeBlock(opening: fence))
continue
}
if let heading = atxHeading(in: lines[index]) {
blocks.append(.heading(level: heading.level, text: heading.text))
index += 1
continue
}
if let level = setextHeadingLevel(after: index) {
blocks.append(.heading(level: level, text: lines[index].markdownTrimmed))
index += 2
continue
}
if blockquoteContent(in: lines[index]) != nil {
blocks.append(parseBlockquote())
continue
}
if let marker = listMarker(in: lines[index]) {
blocks.append(parseList(opening: marker))
continue
}
if isThematicBreak(lines[index]) {
blocks.append(.thematicBreak)
index += 1
continue
}
blocks.append(parseParagraph())
}
return blocks
}
private mutating func parseCodeBlock(opening: FenceMarker) -> MarkdownBlock {
index += 1
var codeLines: [String] = []
while index < lines.count {
let line = lines[index]
if isClosingFence(line, matching: opening) {
index += 1
break
}
codeLines.append(line)
index += 1
}
return .codeBlock(language: opening.language, code: codeLines.joined(separator: "\n"))
}
private mutating func parseBlockquote() -> MarkdownBlock {
var quotedLines: [String] = []
while index < lines.count, let content = blockquoteContent(in: lines[index]) {
quotedLines.append(content)
index += 1
}
var parser = MarkdownBlockParser(source: quotedLines.joined(separator: "\n"))
return .blockquote(MarkdownDocument(blocks: parser.parse()))
}
private mutating func parseList(opening: ListMarker) -> MarkdownBlock {
var items: [MarkdownListItem] = []
let ordered = opening.number != nil
while index < lines.count,
let marker = listMarker(in: lines[index]),
marker.indent == opening.indent,
(marker.number != nil) == ordered {
index += 1
var itemLines = [marker.content]
while index < lines.count {
let line = lines[index]
if line.isMarkdownBlank {
let next = nextNonblankLine(after: index)
guard let next else {
index = lines.count
break
}
if let nextMarker = listMarker(in: lines[next]),
nextMarker.indent == opening.indent,
(nextMarker.number != nil) == ordered {
index = next
break
}
if lines[next].markdownLeadingSpaces > opening.indent {
itemLines.append("")
index += 1
continue
}
index = next
break
}
if let nextMarker = listMarker(in: line), nextMarker.indent == opening.indent {
break
}
let leadingSpaces = line.markdownLeadingSpaces
if leadingSpaces > opening.indent {
let continuationIndent = min(
leadingSpaces,
max(opening.indent + 2, marker.contentIndent)
)
itemLines.append(line.droppingLeadingSpaces(continuationIndent))
index += 1
continue
}
if isBlockStarter(line) {
break
}
// CommonMark permits a paragraph continuation without indentation.
itemLines.append(line)
index += 1
}
let task = taskState(in: itemLines.first ?? "")
if task != nil, !itemLines.isEmpty {
itemLines[0] = removingTaskMarker(from: itemLines[0])
}
var itemParser = MarkdownBlockParser(source: itemLines.joined(separator: "\n"))
items.append(MarkdownListItem(task: task, blocks: itemParser.parse()))
guard index < lines.count,
let nextMarker = listMarker(in: lines[index]),
nextMarker.indent == opening.indent,
(nextMarker.number != nil) == ordered else {
break
}
}
if let start = opening.number {
return .orderedList(start: start, items: items)
}
return .unorderedList(items)
}
private mutating func parseParagraph() -> MarkdownBlock {
var paragraphLines: [String] = []
while index < lines.count, !lines[index].isMarkdownBlank {
if !paragraphLines.isEmpty, isBlockStarter(lines[index]) {
break
}
paragraphLines.append(lines[index].markdownTrimmedTrailing)
index += 1
}
return .paragraph(paragraphLines.joined(separator: "\n"))
}
private func isBlockStarter(_ line: String) -> Bool {
fenceMarker(in: line) != nil
|| atxHeading(in: line) != nil
|| blockquoteContent(in: line) != nil
|| listMarker(in: line) != nil
|| isThematicBreak(line)
}
private func nextNonblankLine(after position: Int) -> Int? {
var candidate = position + 1
while candidate < lines.count {
if !lines[candidate].isMarkdownBlank {
return candidate
}
candidate += 1
}
return nil
}
private func atxHeading(in line: String) -> (level: Int, text: String)? {
let characters = Array(line)
let indent = min(line.markdownLeadingSpaces, characters.count)
guard indent <= 3, indent < characters.count, characters[indent] == "#" else {
return nil
}
var cursor = indent
while cursor < characters.count, characters[cursor] == "#" {
cursor += 1
}
let level = cursor - indent
guard level <= 6,
cursor == characters.count || characters[cursor].isMarkdownWhitespace else {
return nil
}
while cursor < characters.count, characters[cursor].isMarkdownWhitespace {
cursor += 1
}
var content = String(characters[cursor..<characters.endIndex]).markdownTrimmed
if let closingHashes = content.range(
of: #"[ \t]+#+[ \t]*$"#,
options: .regularExpression
) {
content.removeSubrange(closingHashes)
content = content.markdownTrimmedTrailing
}
return (level, content)
}
private func setextHeadingLevel(after position: Int) -> Int? {
guard position + 1 < lines.count, !lines[position].isMarkdownBlank else {
return nil
}
let underline = lines[position + 1].markdownTrimmed
guard !underline.isEmpty else { return nil }
if underline.allSatisfy({ $0 == "=" }) {
return 1
}
if underline.allSatisfy({ $0 == "-" }) {
return 2
}
return nil
}
private func blockquoteContent(in line: String) -> String? {
let characters = Array(line)
let indent = min(line.markdownLeadingSpaces, characters.count)
guard indent <= 3, indent < characters.count, characters[indent] == ">" else {
return nil
}
var cursor = indent + 1
if cursor < characters.count, characters[cursor].isMarkdownWhitespace {
cursor += 1
}
return cursor < characters.count ? String(characters[cursor...]) : ""
}
private func listMarker(in line: String) -> ListMarker? {
let characters = Array(line)
let indent = min(line.markdownLeadingSpaces, characters.count)
guard indent <= 3, indent < characters.count else { return nil }
var cursor = indent
var number: Int?
if ["-", "+", "*"].contains(characters[cursor]) {
cursor += 1
} else if characters[cursor].isNumber {
let numberStart = cursor
while cursor < characters.count,
characters[cursor].isNumber,
cursor - numberStart < 9 {
cursor += 1
}
guard cursor > numberStart,
cursor < characters.count,
characters[cursor] == "." || characters[cursor] == ")",
let parsedNumber = Int(String(characters[numberStart..<cursor])) else {
return nil
}
number = parsedNumber
cursor += 1
} else {
return nil
}
guard cursor < characters.count, characters[cursor].isMarkdownWhitespace else {
return nil
}
while cursor < characters.count, characters[cursor].isMarkdownWhitespace {
cursor += 1
}
return ListMarker(
indent: indent,
contentIndent: cursor,
number: number,
content: cursor < characters.count ? String(characters[cursor...]) : ""
)
}
private func taskState(in line: String) -> MarkdownTaskState? {
let characters = Array(line)
guard characters.count >= 3,
characters[0] == "[",
characters[2] == "]",
[" ", "x", "X"].contains(characters[1]),
characters.count == 3 || characters[3].isMarkdownWhitespace else {
return nil
}
return characters[1] == " " ? .incomplete : .complete
}
private func removingTaskMarker(from line: String) -> String {
let characters = Array(line)
var cursor = min(3, characters.count)
while cursor < characters.count, characters[cursor].isMarkdownWhitespace {
cursor += 1
}
return cursor < characters.count ? String(characters[cursor...]) : ""
}
private func isThematicBreak(_ line: String) -> Bool {
let trimmed = line.markdownTrimmed
guard let marker = trimmed.first, ["-", "_", "*"].contains(marker) else {
return false
}
let visible = trimmed.filter { !$0.isMarkdownWhitespace }
return visible.count >= 3 && visible.allSatisfy { $0 == marker }
}
private func fenceMarker(in line: String) -> FenceMarker? {
let characters = Array(line)
let indent = min(line.markdownLeadingSpaces, characters.count)
guard indent <= 3,
indent < characters.count,
characters[indent] == "`" || characters[indent] == "~" else {
return nil
}
let character = characters[indent]
var cursor = indent
while cursor < characters.count, characters[cursor] == character {
cursor += 1
}
let length = cursor - indent
guard length >= 3 else { return nil }
let info = cursor < characters.count
? String(characters[cursor...]).markdownTrimmed
: ""
guard character != "`" || !info.contains("`") else { return nil }
return FenceMarker(
character: character,
length: length,
language: info.split(whereSeparator: { $0.isWhitespace }).first.map(String.init)
)
}
private func isClosingFence(_ line: String, matching opening: FenceMarker) -> Bool {
let characters = Array(line)
let indent = min(line.markdownLeadingSpaces, characters.count)
guard indent <= 3,
indent < characters.count,
characters[indent] == opening.character else {
return false
}
var cursor = indent
while cursor < characters.count, characters[cursor] == opening.character {
cursor += 1
}
guard cursor - indent >= opening.length else { return false }
return characters[cursor..<characters.endIndex].allSatisfy { $0.isMarkdownWhitespace }
}
}
private struct FenceMarker {
let character: Character
let length: Int
let language: String?
}
private struct ListMarker {
let indent: Int
let contentIndent: Int
let number: Int?
let content: String
}
private extension String {
var isMarkdownBlank: Bool {
allSatisfy { $0.isMarkdownWhitespace }
}
var markdownLeadingSpaces: Int {
prefix { $0 == " " }.count
}
var markdownTrimmed: String {
trimmingCharacters(in: .whitespaces)
}
var markdownTrimmedTrailing: String {
replacingOccurrences(of: #"[ \t]+$"#, with: "", options: .regularExpression)
}
func droppingLeadingSpaces(_ count: Int) -> String {
String(dropFirst(Swift.min(count, markdownLeadingSpaces)))
}
}
private extension Character {
var isMarkdownWhitespace: Bool {
self == " " || self == "\t"
}
}
@@ -0,0 +1,234 @@
import SwiftUI
import UIKit
/// Native chat Markdown with block-aware layout and Foundation inline parsing.
struct MarkdownMessageView: View {
private let source: String
private let document: MarkdownDocument
init(_ source: String) {
self.source = source
document = MarkdownDocument(parsing: source)
}
var body: some View {
MarkdownBlocksView(blocks: document.blocks)
.textSelection(.enabled)
.contextMenu {
Button {
UIPasteboard.general.string = source
} label: {
Label("Copy message", systemImage: "doc.on.doc")
}
}
.accessibilityAction(named: "Copy message") {
UIPasteboard.general.string = source
}
}
}
private struct MarkdownBlocksView: View {
let blocks: [MarkdownBlock]
var spacing: CGFloat = 10
var body: some View {
VStack(alignment: .leading, spacing: spacing) {
ForEach(blocks.indices, id: \.self) { index in
MarkdownBlockView(block: blocks[index])
}
}
}
}
private struct MarkdownBlockView: View {
let block: MarkdownBlock
@ViewBuilder
var body: some View {
switch block {
case let .paragraph(text):
MarkdownInlineText(text, font: .body)
.lineSpacing(3)
case let .heading(level, text):
MarkdownInlineText(text, font: headingFont(level))
.padding(.top, level <= 2 ? 3 : 1)
case let .unorderedList(items):
MarkdownListView(items: items, start: nil)
case let .orderedList(start, items):
MarkdownListView(items: items, start: start)
case let .blockquote(document):
MarkdownBlocksView(blocks: document.blocks, spacing: 7)
.foregroundStyle(T3Colors.textSecondary)
.padding(.leading, 12)
.overlay(alignment: .leading) {
Rectangle()
.fill(T3Colors.textTertiary.opacity(0.75))
.frame(width: 2)
}
case let .codeBlock(language, code):
MarkdownCodeBlockView(language: language, code: code)
case .thematicBreak:
Rectangle()
.fill(T3Colors.separator)
.frame(height: 1)
.padding(.vertical, 2)
.accessibilityHidden(true)
}
}
private func headingFont(_ level: Int) -> Font {
switch level {
case 1: .title3.weight(.bold)
case 2: .headline.weight(.bold)
case 3: .subheadline.weight(.bold)
default: .body.weight(.semibold)
}
}
}
private struct MarkdownListView: View {
let items: [MarkdownListItem]
let start: Int?
var body: some View {
VStack(alignment: .leading, spacing: 6) {
ForEach(items.indices, id: \.self) { offset in
let item = items[offset]
HStack(alignment: .top, spacing: 7) {
marker(for: item, offset: offset)
.frame(width: 22, height: 21, alignment: .trailing)
MarkdownBlocksView(blocks: item.blocks, spacing: 5)
}
.accessibilityElement(children: .contain)
}
}
}
@ViewBuilder
private func marker(for item: MarkdownListItem, offset: Int) -> some View {
if let task = item.task {
Image(systemName: task == .complete ? "checkmark.square.fill" : "square")
.font(.system(size: 14, weight: .medium))
.foregroundStyle(
task == .complete ? T3Colors.success : T3Colors.textSecondary
)
.accessibilityLabel(task == .complete ? "Completed" : "Not completed")
} else if let start {
Text("\(start + offset).")
.font(.callout.monospacedDigit())
.foregroundStyle(T3Colors.textSecondary)
.accessibilityLabel("Item \(start + offset)")
} else {
Text("•")
.font(.body.weight(.semibold))
.foregroundStyle(T3Colors.textSecondary)
.accessibilityHidden(true)
}
}
}
private struct MarkdownCodeBlockView: View {
let language: String?
let code: String
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 8) {
if let language, !language.isEmpty {
Text(language.uppercased())
.font(.caption2.weight(.semibold))
.foregroundStyle(T3Colors.textTertiary)
} else {
Text("CODE")
.font(.caption2.weight(.semibold))
.foregroundStyle(T3Colors.textTertiary)
}
Spacer(minLength: 8)
Button {
UIPasteboard.general.string = code
} label: {
Label("Copy", systemImage: "doc.on.doc")
.font(.caption.weight(.medium))
.foregroundStyle(T3Colors.textSecondary)
.frame(minHeight: 28)
}
.buttonStyle(.plain)
.accessibilityHint("Copies this code block")
}
.padding(.horizontal, 11)
.frame(minHeight: 34)
Rectangle()
.fill(T3Colors.separator)
.frame(height: 1)
ScrollView(.horizontal) {
Text(verbatim: code)
.font(.system(.callout, design: .monospaced))
.foregroundStyle(T3Colors.textPrimary.opacity(0.9))
.lineSpacing(2)
.textSelection(.enabled)
.fixedSize(horizontal: true, vertical: true)
.padding(11)
}
.scrollIndicators(.hidden)
}
.background(T3Colors.surfaceRaised)
.clipShape(RoundedRectangle(cornerRadius: 8))
.overlay {
RoundedRectangle(cornerRadius: 8)
.stroke(T3Colors.border, lineWidth: 1)
}
}
}
private struct MarkdownInlineText: View {
private let attributedText: AttributedString
private let font: Font
init(_ source: String, font: Font) {
self.font = font
attributedText = MarkdownInlineFormatter.format(source, baseFont: font)
}
var body: some View {
Text(attributedText)
.font(font)
.fixedSize(horizontal: false, vertical: true)
}
}
enum MarkdownInlineFormatter {
static func format(_ source: String, baseFont: Font = .body) -> AttributedString {
var attributed = (
try? AttributedString(
markdown: source,
options: AttributedString.MarkdownParsingOptions(
interpretedSyntax: .inlineOnlyPreservingWhitespace,
failurePolicy: .returnPartiallyParsedIfPossible
)
)
) ?? AttributedString(source)
let styles = attributed.runs.map { run in
(run.range, run.inlinePresentationIntent, run.link)
}
for (range, intent, link) in styles {
if intent?.contains(.code) == true {
attributed[range].font = baseFont.monospaced()
attributed[range].foregroundColor = T3Colors.textPrimary.opacity(0.9)
attributed[range].backgroundColor = T3Colors.surfaceRaised
}
if link != nil {
attributed[range].foregroundColor = T3Colors.accent
}
}
return attributed
}
}
@@ -417,8 +417,7 @@ struct FeatureMessageView: View {
VStack(alignment: .leading, spacing: 8) {
FeatureMessageAttachmentsView(attachments: message.attachments)
if !message.text.isEmpty {
Text(.init(message.text))
.textSelection(.enabled)
MarkdownMessageView(message.text)
}
}
.padding(.horizontal, 13)
@@ -438,9 +437,8 @@ struct FeatureMessageView: View {
.foregroundStyle(.secondary)
FeatureMessageAttachmentsView(attachments: message.attachments)
if !message.text.isEmpty {
Text(.init(message.text))
.textSelection(.enabled)
.lineSpacing(3)
MarkdownMessageView(message.text)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
@@ -0,0 +1,154 @@
import Foundation
import Testing
@testable import T3Code
@Suite("Chat Markdown")
struct MarkdownDocumentTests {
@Test
func separatesHeadingsParagraphsAndListKinds() {
let document = MarkdownDocument(
parsing: """
# Release notes
Includes **important** details.
- First
- [x] Shipped
- [ ] Follow up
3. Third
4. Fourth
"""
)
#expect(
document.blocks == [
.heading(level: 1, text: "Release notes"),
.paragraph("Includes **important** details."),
.unorderedList([
MarkdownListItem(task: nil, blocks: [.paragraph("First")]),
MarkdownListItem(task: .complete, blocks: [.paragraph("Shipped")]),
MarkdownListItem(task: .incomplete, blocks: [.paragraph("Follow up")]),
]),
.orderedList(
start: 3,
items: [
MarkdownListItem(task: nil, blocks: [.paragraph("Third")]),
MarkdownListItem(task: nil, blocks: [.paragraph("Fourth")]),
]
),
]
)
}
@Test
func preservesNestedStructureInsideQuotesAndLists() {
let document = MarkdownDocument(
parsing: """
> ## Heads up
> Read this first.
>
> - Quoted item
- Parent
- Nested child
"""
)
guard case let .blockquote(quote) = document.blocks.first else {
Issue.record("Expected a block quote")
return
}
#expect(
quote.blocks == [
.heading(level: 2, text: "Heads up"),
.paragraph("Read this first."),
.unorderedList([
MarkdownListItem(task: nil, blocks: [.paragraph("Quoted item")]),
]),
]
)
guard case let .unorderedList(items) = document.blocks.last else {
Issue.record("Expected an unordered list")
return
}
#expect(
items == [
MarkdownListItem(
task: nil,
blocks: [
.paragraph("Parent"),
.unorderedList([
MarkdownListItem(task: nil, blocks: [.paragraph("Nested child")]),
]),
]
),
]
)
}
@Test
func fencedCodeKeepsLanguageAndContentsLiteral() {
let document = MarkdownDocument(
parsing: """
```swift
let value = "**not emphasis**"
print(value)
```
"""
)
#expect(
document.blocks == [
.codeBlock(
language: "swift",
code: "let value = \"**not emphasis**\"\n print(value)"
),
]
)
}
@Test
func unclosedFenceConsumesTheRemainingMessage() {
let document = MarkdownDocument(
parsing: """
~~~console
pnpm test
no closing fence
"""
)
#expect(
document.blocks == [
.codeBlock(language: "console", code: "pnpm test\nno closing fence"),
]
)
}
@Test
func parsesSetextHeadingsAndNormalizesWindowsNewlines() {
let document = MarkdownDocument(parsing: "Heading\r\n=======\r\n\r\nBody")
#expect(
document.blocks == [
.heading(level: 1, text: "Heading"),
.paragraph("Body"),
]
)
}
@Test
func inlineFormatterRetainsEmphasisCodeAndLinks() {
let formatted = MarkdownInlineFormatter.format(
"Use **bold**, *emphasis*, `code`, and [docs](https://example.com)."
)
let runs = Array(formatted.runs)
#expect(String(formatted.characters) == "Use bold, emphasis, code, and docs.")
#expect(runs.contains { $0.inlinePresentationIntent?.contains(.stronglyEmphasized) == true })
#expect(runs.contains { $0.inlinePresentationIntent?.contains(.emphasized) == true })
#expect(runs.contains { $0.inlinePresentationIntent?.contains(.code) == true })
#expect(runs.contains { $0.link == URL(string: "https://example.com") })
}
}