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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,20 @@ TranscriptText(document)

In UIKit, set `isSelectable` on `TranscriptTextView`.

### Line limit and alignment

For short text in cards and list rows, set a line limit and an alignment. When text is left out, the last line shown
ends in "…", and selection and copying cover only what is shown. `TranscriptText` also takes SwiftUI's modifiers:

```swift
TranscriptText(document)
.lineLimit(2)
.multilineTextAlignment(.center)
```

The same values are `lineLimit` and `textAlignment` on `TranscriptStyle`. The alignment moves paragraphs and headings;
lists, quotes, code and tables stay at the leading edge. A table is shown whole or not at all.

### Styling

`TranscriptStyle` sets the body size, line, block and list spacing, indents, padding and the maximum image height.
Expand Down
79 changes: 77 additions & 2 deletions Sources/TranscriptKit/Layout/BlockLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -182,18 +182,19 @@ final class BlockLayout: @unchecked Sendable {
let gap = fixedHeight == nil ? style.lineSpacing : 0
func add(_ ctLine: CTLine, range: Range<Int>, indexBase: Int, leading: CGFloat = 0, text: NSAttributedString? = nil) {
let metrics = fitted(lineMetrics(ctLine, isEmpty: range.isEmpty, font: font), to: fixedHeight)
let x = insets.leading + leading + alignmentOffset(block, style: style, width: metrics.width, room: available - leading)
var decorations: LineDecorations?
if let decorated, let text {
decorations = LineDecorations.make(line: ctLine, range: range, indexBase: indexBase, visibleWidth: metrics.width,
top: -metrics.ascent, bottom: metrics.height - metrics.ascent,
lineX: insets.leading + leading, blockWidth: blockWidth, block: block.id,
lineX: x, blockWidth: blockWidth, block: block.id,
tags: decorated, text: text, textBase: indexBase)
}
lines.append(Line(
ctLine: ctLine,
indexBase: indexBase,
range: range,
frame: CGRect(x: insets.leading + leading, y: y, width: metrics.width, height: metrics.height),
frame: CGRect(x: x, y: y, width: metrics.width, height: metrics.height),
baseline: y + metrics.ascent,
decorations: decorations
))
Expand Down Expand Up @@ -232,6 +233,80 @@ final class BlockLayout: @unchecked Sendable {
return (metrics.width, height, metrics.ascent + ((height - metrics.height) / 2).rounded())
}

/// How far a line `width` wide moves right in `room` for the style's
/// alignment. Only paragraphs and headings outside lists and quotes move.
static func alignmentOffset(_ block: TranscriptBlock, style: TranscriptStyle, width: CGFloat, room: CGFloat) -> CGFloat {
guard isAligned(block, style: style) else { return 0 }
let slack = max(room - width, 0)
switch style.textAlignment {
case .leading: return 0
case .center: return (slack / 2).rounded(.down)
case .trailing: return slack
}
}

/// Whether the block's lines follow the style's alignment rather than the leading edge.
static func isAligned(_ block: TranscriptBlock, style: TranscriptStyle) -> Bool {
guard style.textAlignment != .leading, block.containers.isEmpty else { return false }
switch block.kind {
case .paragraph, .heading: return true
case .code, .rule, .table: return false
}
}

/// The first `count` lines of `original`, for a line limit. With
/// `ellipsis`, the last of them ends in "…": it is typeset again from the
/// rest of the block and truncated, or "…" is added when the block ends
/// there but more text follows it.
init(_ original: BlockLayout, keepingLines count: Int, ellipsis: Bool) {
block = original.block
width = original.width
style = original.style
contentLeading = original.contentLeading
marker = original.marker
table = original.table
imageRevision = original.imageRevision
definedReferences = original.definedReferences
let count = min(max(count, 1), original.lines.count)
var kept = original.lines.prefix(count)
let insets = style.insets(for: block)
if ellipsis, let last = kept.last {
_ = kept.removeLast()
kept.append(Self.withEllipsis(last, block: block, style: style, insets: insets, width: original.width))
}
lines = kept
let bottom = kept.last.map { $0.frame.maxY } ?? 0
height = bottom + insets.vertical
length = kept.last?.range.upperBound ?? 0
attachments = original.attachments.filter { $0.rect.minY < bottom }
}

private static func withEllipsis(_ line: Line, block: TranscriptBlock, style: TranscriptStyle,
insets: TranscriptStyle.Insets, width: CGFloat) -> Line {
let available = max(width - insets.leading - insets.trailing, 1)
let rest = NSMutableAttributedString(attributedString: style.attributedString(for: block, range: line.range.lowerBound..<block.utf16Count))
let attributes = rest.length > 0 ? rest.attributes(at: rest.length - 1, effectiveRange: nil) : style.attributes(for: block.kind)
// Trailing line breaks would end the line before the ellipsis.
while rest.length > 0, (rest.string as NSString).character(at: rest.length - 1) == 0x0A {
rest.deleteCharacters(in: NSRange(location: rest.length - 1, length: 1))
}
if line.range.upperBound >= block.utf16Count {
rest.append(NSAttributedString(string: "…", attributes: attributes))
}
let token = CTLineCreateWithAttributedString(NSAttributedString(string: "…", attributes: attributes))
let full = CTLineCreateWithAttributedString(rest)
let aligned = isAligned(block, style: style)
let start = aligned ? insets.leading : line.frame.minX
let room = max(insets.leading + available - start, 1)
let ctLine = CTLineCreateTruncatedLine(full, Double(room), .end, token) ?? full
let font = style.font(for: block.kind)
let metrics = lineMetrics(ctLine, isEmpty: false, font: font)
let x = aligned ? insets.leading + alignmentOffset(block, style: style, width: metrics.width, room: available) : start
return Line(ctLine: ctLine, indexBase: line.range.lowerBound, range: line.range,
frame: CGRect(x: x, y: line.frame.minY, width: metrics.width, height: line.frame.height),
baseline: line.baseline, decorations: nil)
}

private static func lineMetrics(_ ctLine: CTLine, isEmpty: Bool, font: CTFont) -> (width: CGFloat, height: CGFloat, ascent: CGFloat) {
var ascent: CGFloat = 0
var descent: CGFloat = 0
Expand Down
18 changes: 16 additions & 2 deletions Sources/TranscriptKit/Layout/DocumentLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ public final class DocumentLayout: @unchecked Sendable {
let imageRevision = images?.revision ?? 0
self.imageRevision = imageRevision

let previous = previous.flatMap { $0.width == width && $0.style == style ? $0 : nil }
// A line-limited layout may hold a block cut short, so it is not reused.
let previous = style.lineLimit == nil ? previous.flatMap { $0.width == width && $0.style == style ? $0 : nil } : nil
let limit = style.lineLimit.map { max($0, 1) }
var shownLines = 0
var settled = SharedList<Entry>()
var open: [Entry] = []
var y: CGFloat = 0
Expand Down Expand Up @@ -91,14 +94,24 @@ public final class DocumentLayout: @unchecked Sendable {
// Blocks keep their position from one update to the next, so the
// previous layout for index i is the candidate for block i.
let candidate = previous.flatMap { index < $0.entryCount ? $0.entry(at: index).layout : nil }
let layout: BlockLayout
if let limit, shownLines >= limit { break }
var layout: BlockLayout
if let candidate, candidate.block == block, candidate.imageRevision == nil || candidate.imageRevision == imageRevision,
candidate.definedReferences == nil || candidate.definedReferences == BlockLayout.definedReferences(of: block, in: definitions) {
layout = candidate
reused += 1
} else {
layout = BlockLayout(block: block, width: width, style: style, reusing: candidate, images: images, definitions: definitions)
}
var reachedLimit = false
if let limit, layout.table == nil {
let remaining = limit - shownLines
if layout.lines.count > remaining || (layout.lines.count == remaining && index + 1 < document.count) {
layout = BlockLayout(layout, keepingLines: remaining, ellipsis: true)
reachedLimit = true
}
}
shownLines += layout.lines.count
if let previousBlock {
y += Self.spacing(between: previousBlock, and: block, style: style)
}
Expand All @@ -111,6 +124,7 @@ public final class DocumentLayout: @unchecked Sendable {
previousBlock = block
y += layout.height
start += layout.length + 1
if reachedLimit { break }
}

self.settled = settled
Expand Down
15 changes: 15 additions & 0 deletions Sources/TranscriptKit/Layout/TranscriptStyle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ import CoreGraphics
import CoreText
import Foundation

/// Where lines sit in their column; see `TranscriptStyle.textAlignment`.
public enum TranscriptTextAlignment: Hashable, Sendable {
case leading
case center
case trailing
}

/// Typography and spacing for a transcript.
public struct TranscriptStyle: Equatable, Sendable {
/// The font of paragraphs, list items, quotes and tables. Nil uses the
Expand Down Expand Up @@ -47,6 +54,14 @@ public struct TranscriptStyle: Equatable, Sendable {

public init() {}

/// The most lines to show, or nil for all of them. When text is left out,
/// the last line shown ends in "…". Selection and copying cover only the
/// text that is shown. Tables are shown whole or not at all.
public var lineLimit: Int?
/// Where the lines of paragraphs and headings sit in their column. Lists,
/// quotes, code and tables stay at the leading edge.
public var textAlignment: TranscriptTextAlignment = .leading

struct Insets {
var leading: CGFloat = 0
var trailing: CGFloat = 0
Expand Down
10 changes: 9 additions & 1 deletion Sources/TranscriptKit/iOS/TranscriptText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,17 @@ public struct TranscriptText: UIViewRepresentable {
}

public func updateUIView(_ view: TranscriptTextView, context: Context) {
view.style = style.scalesWithDynamicType
var style = style.scalesWithDynamicType
? style.scaled(for: UIContentSizeCategory(context.environment.dynamicTypeSize))
: style
// SwiftUI's `.lineLimit(_:)` and `.multilineTextAlignment(_:)` win over the style's.
if let limit = context.environment.lineLimit { style.lineLimit = limit }
switch context.environment.multilineTextAlignment {
case .center: style.textAlignment = .center
case .trailing: style.textAlignment = .trailing
case .leading: break
}
view.style = style
view.animatesTags = animatesTags
view.tagAnimationTiming = animationTiming
view.isSelectable = isSelectable
Expand Down
4 changes: 3 additions & 1 deletion Sources/TranscriptKit/iOS/TranscriptTextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,9 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD
/// its screen's scale, or not at all outside a window.
private func updateTailStyle() {
if let window { engine.setFramesPerSecond(Self.framesPerSecond(on: window.screen)) }
let enabled = window != nil && TranscriptDiagnostics.drawsTailOffMainThread
// With a line limit, the end of a stream is past the last line shown,
// and a tail surface would draw it below the view.
let enabled = window != nil && TranscriptDiagnostics.drawsTailOffMainThread && style.lineLimit == nil
engine.setTailStyle(colors: enabled ? resolvedColors() : nil, scale: traitCollection.displayScale)
}

Expand Down
88 changes: 88 additions & 0 deletions Tests/TranscriptKitTests/LineLimitTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import CoreText
import Foundation
import Testing
@testable import TranscriptKit

private let longParagraph = String(repeating: "Words that wrap onto several lines. ", count: 8)

/// Whether the line draws an ellipsis glyph.
private func endsInEllipsis(_ line: CTLine) -> Bool {
let runs = CTLineGetGlyphRuns(line) as! [CTRun]
guard let run = runs.last, CTRunGetGlyphCount(run) > 0 else { return false }
let font = (CTRunGetAttributes(run) as NSDictionary)[kCTFontAttributeName] as! CTFont
var character: UniChar = 0x2026
var ellipsis: CGGlyph = 0
guard CTFontGetGlyphsForCharacters(font, &character, &ellipsis, 1) else { return false }
var last: CGGlyph = 0
CTRunGetGlyphs(run, CFRange(location: CTRunGetGlyphCount(run) - 1, length: 1), &last)
return last == ellipsis
}

private func limited(_ limit: Int?) -> TranscriptStyle {
var style = TranscriptStyle()
style.lineLimit = limit
return style
}

@Test func aLineLimitKeepsTheFirstLinesOfAParagraph() {
let document = MarkdownStreamParser.document(from: longParagraph)
let full = DocumentLayout(document: document, width: 200, style: limited(nil))
let cut = DocumentLayout(document: document, width: 200, style: limited(2))
let fullLines = full.entry(at: 0).layout.lines
let cutLines = cut.entry(at: 0).layout.lines
#expect(fullLines.count > 3)
#expect(cutLines.count == 2)
#expect(cut.height == cutLines[1].frame.maxY)
#expect(cut.length == fullLines[1].range.upperBound)
#expect(cutLines[0].frame == fullLines[0].frame)
#expect(cutLines[1].range == fullLines[1].range)
#expect(!endsInEllipsis(cutLines[0].ctLine))
#expect(endsInEllipsis(cutLines[1].ctLine))
#expect(cutLines[1].frame.maxX <= 200)
}

@Test func aLineLimitStopsBeforeLaterBlocks() {
let document = MarkdownStreamParser.document(from: "First.\n\nSecond.\n\nThird.")
let cut = DocumentLayout(document: document, width: 300, style: limited(2))
#expect(cut.entryCount == 2)
let second = cut.entry(at: 1)
// More text follows, so the last line shown gains an ellipsis and is wider.
let plain = DocumentLayout(document: document, width: 300, style: limited(nil)).entry(at: 1)
#expect(second.layout.lines[0].frame.width > plain.layout.lines[0].frame.width)
#expect(endsInEllipsis(second.layout.lines[0].ctLine))
#expect(!endsInEllipsis(cut.entry(at: 0).layout.lines[0].ctLine))
#expect(cut.length == second.end)
}

@Test func textWithinTheLimitIsUnchanged() {
let document = MarkdownStreamParser.document(from: "First.\n\nSecond.")
let cut = DocumentLayout(document: document, width: 300, style: limited(5))
let full = DocumentLayout(document: document, width: 300, style: limited(nil))
#expect(cut.entryCount == 2)
#expect(cut.height == full.height)
#expect(cut.length == full.length)
#expect(cut.entry(at: 1).layout.lines[0].frame == full.entry(at: 1).layout.lines[0].frame)
}

@Test func centredAndTrailingLinesMoveInTheirColumn() {
let document = MarkdownStreamParser.document(from: "Short line")
var centre = TranscriptStyle()
centre.textAlignment = .center
var trailing = TranscriptStyle()
trailing.textAlignment = .trailing
let leadingLine = DocumentLayout(document: document, width: 300, style: TranscriptStyle()).entry(at: 0).layout.lines[0]
let centredLine = DocumentLayout(document: document, width: 300, style: centre).entry(at: 0).layout.lines[0]
let trailingLine = DocumentLayout(document: document, width: 300, style: trailing).entry(at: 0).layout.lines[0]
#expect(leadingLine.frame.minX == 0)
#expect(abs(centredLine.frame.midX - 150) <= 1)
#expect(abs(trailingLine.frame.maxX - 300) <= 1)
}

@Test func listItemsStayAtTheLeadingEdge() {
let document = MarkdownStreamParser.document(from: "- An item")
var centre = TranscriptStyle()
centre.textAlignment = .center
let leading = DocumentLayout(document: document, width: 300, style: TranscriptStyle()).entry(at: 0).layout.lines[0]
let centred = DocumentLayout(document: document, width: 300, style: centre).entry(at: 0).layout.lines[0]
#expect(centred.frame.minX == leading.frame.minX)
}