Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut
- **Markdown:**
- headings, paragraphs, emphasis, strikethrough and inline code;
- nested lists, task lists and quotes;
- fenced and indented code blocks and tables;
- fenced and indented code blocks, colored by a highlighter your app provides, and tables;
- links, bare URLs and email addresses, and reference links;
- images, drawn by a loader your app provides;
- HTML entities and a few HTML tags.
Expand Down Expand Up @@ -186,6 +186,25 @@ TranscriptText(stream: stream)
.imageLoader { image in await myImageCache.cgImage(for: image.source) }
```

### Code highlighting

Code blocks show in the text color unless you provide a highlighter. It gets each code block's text and the fence's
language, and returns colored ranges in UTF-16 offsets of the code, with bold or italic if you want them. It is
called off the main thread, at most once at a time for each block, so a slow or async highlighter is fine: while
code streams in, a block keeps its newest colors on the text they were made for.

```swift
TranscriptText(stream: stream)
.codeHighlighter { code, language in
await myHighlighter.tokens(in: code, language: language).map { token in
TranscriptCodeHighlight(range: token.range, color: TranscriptColor(token.color))
}
}
```

In UIKit, set `codeHighlighter` on `TranscriptTextView`. Colors are `TranscriptColor`s, so give them a light and a dark
value when the theme has both.

### Selection

The text is selectable by default. Turn selection off for text inside a view that reacts to taps, such as a card or a
Expand Down
4 changes: 3 additions & 1 deletion Sources/TranscriptKit/Layout/BlockLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ final class BlockLayout: @unchecked Sendable {
let insets = style.insets(for: block)
let available = max(width - insets.leading - insets.trailing, 1)
let hasImages = block.spans.contains { $0.image != nil }
let revision = hasImages ? (images?.revision ?? 0) : nil
// Laid out again when the store's pictures or code colors change.
let usesStore = hasImages || (block.kind.isCode && images?.hasHighlighter == true)
let revision = usesStore ? (images?.revision ?? 0) : nil
let contentLeading = style.contentLeading(for: block.containers)
let defined = Self.definedReferences(of: block, in: definitions)
self.definedReferences = defined
Expand Down
80 changes: 79 additions & 1 deletion Sources/TranscriptKit/Layout/ImageStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import CoreGraphics
import Foundation

/// Loads the pictures for images in the text with the loader the app gave
/// the view, and keeps them. Any thread.
/// the view, and keeps them, and the colors of code blocks from the app's
/// highlighter. Any thread.
///
/// Nothing is fetched unless the app sets a loader: an image URL written by
/// a model can carry data out of the conversation when it is fetched.
Expand All @@ -17,6 +18,15 @@ final class TranscriptImageStore: @unchecked Sendable {
private var generation = 0
private var _revision = 0

private var highlightGeneration = 0
/// The app's highlighter, and for each code block (by id) the colors for
/// the last text it was asked about, which block is being highlighted,
/// and the newest text waiting for its turn.
private var highlighter: TranscriptCodeHighlighter?
private var highlights: [String: (text: String, language: String?, marks: [TranscriptCodeHighlight])] = [:]
private var highlighting: Set<String> = []
private var waitingCode: [String: (text: String, language: String?)] = [:]

/// Goes up each time a picture arrives; layouts made at an older
/// revision may show placeholders where pictures now are.
var revision: Int { lock.withLock { _revision } }
Expand All @@ -35,6 +45,74 @@ final class TranscriptImageStore: @unchecked Sendable {
}
}

/// Sets what to call (on any thread) when a picture or colors arrive.
func setOnChange(_ onChange: (@Sendable () -> Void)?) {
lock.withLock { self.onChange = onChange }
}

var hasHighlighter: Bool { lock.withLock { highlighter != nil } }

/// Sets the highlighter. Colors from an earlier one are dropped, and the
/// revision goes up so that code blocks are laid out again.
func setHighlighter(_ highlighter: TranscriptCodeHighlighter?) {
lock.withLock {
self.highlighter = highlighter
highlightGeneration += 1
_revision += 1
highlights = [:]
highlighting = []
waitingCode = [:]
}
}

/// The colors for a code block's `text`. When they are not there yet,
/// highlighting starts (or waits for the block's current one to end), and
/// the colors for the block's last text are given meanwhile: while text
/// streams in, they still fit the part of it they were made for.
func highlights(for block: String, text: String, language: String?) -> [TranscriptCodeHighlight] {
let (marks, start): ([TranscriptCodeHighlight], (TranscriptCodeHighlighter, Int)?) = lock.withLock {
guard let highlighter else { return ([], nil) }
let known = highlights[block]
if let known, known.text == text, known.language == language { return (known.marks, nil) }
let stale = known?.marks ?? []
if highlighting.contains(block) {
waitingCode[block] = (text, language)
return (stale, nil)
}
highlighting.insert(block)
return (stale, (highlighter, highlightGeneration))
}
if let (highlighter, generation) = start {
highlight(block, text: text, language: language, with: highlighter, generation: generation)
}
return marks
}

private func highlight(_ block: String, text: String, language: String?, with highlighter: @escaping TranscriptCodeHighlighter,
generation: Int) {
Task.detached { [weak self] in
let marks = await highlighter(text, language)
self?.finishHighlight(block, text: text, language: language, marks: marks, generation: generation)
}
}

private func finishHighlight(_ block: String, text: String, language: String?, marks: [TranscriptCodeHighlight], generation: Int) {
let (handler, next): ((@Sendable () -> Void)?, (TranscriptCodeHighlighter, String, String?)?) = lock.withLock {
guard generation == highlightGeneration else { return (nil, nil) }
highlights[block] = (text, language, marks)
_revision += 1
if let waiting = waitingCode.removeValue(forKey: block), let highlighter, waiting.text != text || waiting.language != language {
return (onChange, (highlighter, waiting.text, waiting.language))
}
highlighting.remove(block)
return (onChange, nil)
}
if let (highlighter, text, language) = next {
highlight(block, text: text, language: language, with: highlighter, generation: generation)
}
handler?()
}

/// The picture for `image` if it has arrived. Starts loading it if not.
func picture(for image: TranscriptImage) -> CGImage? {
let (picture, load, generation): (CGImage?, Loader?, Int) = lock.withLock {
Expand Down
12 changes: 12 additions & 0 deletions Sources/TranscriptKit/Layout/TranscriptStyle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,18 @@ public struct TranscriptStyle: Equatable, Sendable {
if !extraTraits.isEmpty { base[Self.fontKey] = font(for: block.kind, traits: extraTraits) }
let result = NSMutableAttributedString(string: text, attributes: base)
let length = result.length
if case .code(let language) = block.kind, let store = images?.store {
// The app's highlighter's colors, drawn like a tag's color.
for mark in store.highlights(for: block.id, text: block.text, language: language) {
let lower = min(max(mark.range.lowerBound - start, 0), length)
let upper = min(max(mark.range.upperBound - start, 0), length)
guard lower < upper else { continue }
let range = NSRange(location: lower, length: upper - lower)
result.addAttribute(Self.foregroundKey, value: mark.color, range: range)
let traits = mark.traits.intersection([.bold, .italic])
if !traits.isEmpty { result.addAttribute(Self.fontKey, value: font(for: block.kind, traits: traits), range: range) }
}
}
// Spans shifted into the substring's coordinates, dropping any outside it.
let spans = block.spans.compactMap { span -> InlineSpan? in
let lower = min(max(span.range.lowerBound - start, 0), length)
Expand Down
21 changes: 21 additions & 0 deletions Sources/TranscriptKit/Model/TranscriptCodeHighlight.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Foundation

/// A colored stretch of a code block, from the app's highlighter; see
/// `TranscriptTextView.codeHighlighter`.
public struct TranscriptCodeHighlight: Equatable, Sendable {
/// UTF-16 offsets in the code block's text.
public var range: Range<Int>
public var color: TranscriptColor
/// `.bold` and `.italic` are used; other traits are ignored.
public var traits: InlineSpan.Traits

public init(range: Range<Int>, color: TranscriptColor, traits: InlineSpan.Traits = []) {
self.range = range
self.color = color
self.traits = traits
}
}

/// Colors the code of a code block: its text and the fence's language, or
/// nil. Called off the main thread, at most once at a time for each block.
public typealias TranscriptCodeHighlighter = @Sendable (_ code: String, _ language: String?) async -> [TranscriptCodeHighlight]
10 changes: 10 additions & 0 deletions Sources/TranscriptKit/iOS/TranscriptText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public struct TranscriptText: UIViewRepresentable {
private let source: Source
private let style: TranscriptStyle
private var loader: (@Sendable (TranscriptImage) async -> CGImage?)?
private var highlighter: TranscriptCodeHighlighter?
private var animatesTags = true
private var animationTiming: TranscriptAnimationTiming = .immediately
private var isSelectable = true
Expand Down Expand Up @@ -54,6 +55,14 @@ public struct TranscriptText: UIViewRepresentable {
return copy
}

/// Colors the code in code blocks; see `TranscriptTextView.codeHighlighter`.
/// Read once, when the view is created.
public func codeHighlighter(_ highlighter: @escaping TranscriptCodeHighlighter) -> TranscriptText {
var copy = self
copy.highlighter = highlighter
return copy
}

/// Whether custom tags with an animation play it when they finish
/// arriving; see `TranscriptTextView.animatesTags`. On by default.
public func animatesTags(_ animates: Bool) -> TranscriptText {
Expand Down Expand Up @@ -117,6 +126,7 @@ public struct TranscriptText: UIViewRepresentable {
let view = TranscriptTextView()
view.setContentHuggingPriority(.required, for: .vertical)
if let loader { view.imageLoader = loader }
if let highlighter { view.codeHighlighter = highlighter }
return view
}

Expand Down
17 changes: 17 additions & 0 deletions Sources/TranscriptKit/iOS/TranscriptTextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,23 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD
}
}

/// Colors the code in code blocks, as a syntax highlighter does. It is
/// called off the main thread with each code block's text and language,
/// at most once at a time for each block, and a block shows its newest
/// colors meanwhile. Code is drawn in the text color until its colors
/// arrive. Not set by default.
public var codeHighlighter: TranscriptCodeHighlighter? {
didSet {
engine.images.setOnChange { [weak self] in
DispatchQueue.main.async {
MainActor.assumeIsolated { self?.relayoutNow() }
}
}
engine.images.setHighlighter(codeHighlighter)
relayoutNow()
}
}

private let engine = LayoutEngine()

/// Holds the tiles, and the tail layer above them, below the system's
Expand Down
126 changes: 126 additions & 0 deletions Tests/TranscriptKitTests/CodeHighlightTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import CoreText
import Foundation
import Testing
@testable import TranscriptKit

private let red = TranscriptColor(red: 1, green: 0, blue: 0)

/// Colors every "let" red.
private func letHighlighter(_ code: String) -> [TranscriptCodeHighlight] {
var marks: [TranscriptCodeHighlight] = []
let text = code as NSString
var search = NSRange(location: 0, length: text.length)
while true {
let found = text.range(of: "let", options: [], range: search)
guard found.location != NSNotFound else { break }
marks.append(TranscriptCodeHighlight(range: found.location..<(found.location + found.length), color: red, traits: .bold))
let next = found.location + found.length
search = NSRange(location: next, length: text.length - next)
}
return marks
}

/// Records what the highlighter was asked, in order.
private final class Calls: @unchecked Sendable {
private let lock = NSLock()
private var items: [(String, String?)] = []
func add(_ code: String, _ language: String?) { lock.withLock { items.append((code, language)) } }
var all: [(String, String?)] { lock.withLock { items } }
}

/// Waits until `condition` holds, for at most two seconds.
private func waitUntil(_ condition: () -> Bool) async {
for _ in 0..<200 where !condition() {
try? await Task.sleep(for: .milliseconds(10))
}
}

private func codeColor(_ text: NSAttributedString, at offset: Int) -> TranscriptColor? {
text.attribute(TranscriptStyle.foregroundKey, at: offset, effectiveRange: nil) as? TranscriptColor
}

@Test func codeBlocksTakeTheHighlightersColorsWhenTheyArrive() async {
let store = TranscriptImageStore()
let calls = Calls()
store.setHighlighter { code, language in
calls.add(code, language)
return letHighlighter(code)
}
let block = MarkdownStreamParser.document(from: "```swift\nlet a = 1\nvar b = 2\n```").blocks[0]
let style = TranscriptStyle()
let sizing = ImageSizing(store: store, maximumWidth: 300)
let revision = store.revision
// The first layout asks for colors and draws the code plainly.
#expect(codeColor(style.attributedString(for: block, images: sizing), at: 0) == nil)
await waitUntil { store.revision > revision }
#expect(store.revision > revision)
let colored = style.attributedString(for: block, images: sizing)
#expect(codeColor(colored, at: 0) == red)
#expect(codeColor(colored, at: 10) == nil)
#expect(calls.all.count == 1)
#expect(calls.all.first?.1 == "swift")
// Bold from the highlighter changes the font.
let font = colored.attribute(TranscriptStyle.fontKey, at: 0, effectiveRange: nil) as! CTFont
#expect(CTFontGetSymbolicTraits(font).contains(.traitBold))
}

@Test func aCodeBlockIsLaidOutAgainWhenColorsArrive() async {
let store = TranscriptImageStore()
store.setHighlighter { code, _ in letHighlighter(code) }
let document = MarkdownStreamParser.document(from: "```\nlet a = 1\n```\n\nPlain text.")
let revision = store.revision
let first = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: nil, images: store)
#expect(first.entry(at: 0).layout.imageRevision != nil)
#expect(first.entry(at: 1).layout.imageRevision == nil)
await waitUntil { store.revision > revision }
#expect(store.revision > revision)
let second = DocumentLayout(document: document, width: 300, style: TranscriptStyle(), reusing: first, images: store)
#expect(second.entry(at: 0).layout !== first.entry(at: 0).layout)
#expect(second.entry(at: 1).layout === first.entry(at: 1).layout)
}

@Test func streamingCodeKeepsItsLastColorsAndHighlightsOneTextAtATime() async {
let store = TranscriptImageStore()
let calls = Calls()
store.setHighlighter { code, language in
calls.add(code, language)
try? await Task.sleep(for: .milliseconds(100))
return letHighlighter(code)
}
let texts = ["let a = 1\n", "let a = 1\nlet b", "let a = 1\nlet b = 2\nlet c"]
// A block of the same id whose text grows, as while streaming.
var block = MarkdownStreamParser.document(from: "```\n" + texts[0] + "```").blocks[0]
_ = store.highlights(for: block.id, text: texts[0], language: nil)
_ = store.highlights(for: block.id, text: texts[1], language: nil)
_ = store.highlights(for: block.id, text: texts[2], language: nil)
await waitUntil { calls.all.count == 2 && store.highlights(for: block.id, text: texts[2], language: nil).count == 3 }
// The middle text was replaced by the newest while the first was highlighted.
#expect(calls.all.map(\.0) == [texts[0], texts[2]])
// While a newer text waits, the last colors are given for it.
block.text = texts[2] + " = 3"
let stale = store.highlights(for: block.id, text: block.text, language: nil)
#expect(stale.count == 3)
}

@Test func withoutAHighlighterCodeIsNotColored() {
let store = TranscriptImageStore()
let block = MarkdownStreamParser.document(from: "```\nlet a = 1\n```").blocks[0]
let text = TranscriptStyle().attributedString(for: block, images: ImageSizing(store: store, maximumWidth: 300))
#expect(codeColor(text, at: 0) == nil)
#expect(!store.hasHighlighter)
}

@Test func settingAHighlighterKeepsImagesThatAreLoading() async {
let store = TranscriptImageStore()
store.setLoader({ _ in
try? await Task.sleep(for: .milliseconds(100))
let context = CGContext(data: nil, width: 4, height: 4, bitsPerComponent: 8, bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
return context.makeImage()
}, onChange: nil)
let image = TranscriptImage(source: "https://example.com/a.png", alt: "a")
#expect(store.picture(for: image) == nil)
store.setHighlighter { code, _ in letHighlighter(code) }
await waitUntil { store.picture(for: image) != nil }
#expect(store.picture(for: image) != nil)
}