diff --git a/README.md b/README.md index bce5826..e0d2ea1 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index 664b1f4..32df33b 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -182,18 +182,19 @@ final class BlockLayout: @unchecked Sendable { let gap = fixedHeight == nil ? style.lineSpacing : 0 func add(_ ctLine: CTLine, range: Range, 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 )) @@ -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.. 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 diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index aed0f7c..511e758 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -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() var open: [Entry] = [] var y: CGFloat = 0 @@ -91,7 +94,8 @@ 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 @@ -99,6 +103,15 @@ public final class DocumentLayout: @unchecked Sendable { } 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) } @@ -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 diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index 1415c8a..56235a3 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -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 @@ -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 diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 4782577..e03328b 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -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 diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 540b7e5..06c3880 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -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) } diff --git a/Tests/TranscriptKitTests/LineLimitTests.swift b/Tests/TranscriptKitTests/LineLimitTests.swift new file mode 100644 index 0000000..368c3d6 --- /dev/null +++ b/Tests/TranscriptKitTests/LineLimitTests.swift @@ -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) +}