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
74 changes: 73 additions & 1 deletion Demo/TranscriptDemo/DemoApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import TranscriptKit
struct DemoApp: App {
var body: some Scene {
WindowGroup {
ContentView()
if ProcessInfo.processInfo.arguments.contains("-replacementCheck") {
ReplacementCheckView()
} else {
ContentView()
}
}
}
}
Expand Down Expand Up @@ -213,6 +217,74 @@ enum Sample {
"""
}

/// Launch with `-replacementCheck` to replace the text of a card every two
/// seconds, with a short text and a long one in turn. Add `-crossfade` to lay
/// out each new text at once and crossfade to it. Add `-animatedSwap` to
/// swap inside `withAnimation`, so that the card's height animates. Each swap
/// logs when it happened, and each change of the card's height logs when
/// SwiftUI saw it.
struct ReplacementCheckView: View {
@State private var showsLong = false
@State private var swap = 0
@State private var swapTime: CFTimeInterval = 0
private let crossfades = ProcessInfo.processInfo.arguments.contains("-crossfade")
private let animatesSwap = ProcessInfo.processInfo.arguments.contains("-animatedSwap")

var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
Text(crossfades ? "Crossfade, laid out at once" : "Laid out in the background")
.font(.footnote.monospaced())
.padding(.bottom, 8)
TranscriptText(MarkdownStreamParser.document(from: showsLong ? Self.long : Self.short))
.crossfadesReplacedText(crossfades, duration: 0.6)
.padding(12)
.background(Color.yellow.opacity(0.35))
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height in
let delay = (CACurrentMediaTime() - swapTime) * 1000
print("replacement-check swap=\(swap) height=\(height) after=\(String(format: "%.1f", delay)) ms")
}
Rectangle()
.fill(.red)
.frame(height: 8)
}
.padding(16)
}
.task {
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(2))
swap += 1
swapTime = CACurrentMediaTime()
print("replacement-check swap=\(swap) long=\(!showsLong)")
if animatesSwap {
withAnimation(.easeInOut(duration: 0.6)) { showsLong.toggle() }
} else {
showsLong.toggle()
}
}
}
}

static let short = """
## Summary

The build has **two steps**. The details come in two seconds.
"""

static let long = """
## Details

The first step compiles the package. The second step runs the tests on the device, and each step writes its \
log to the `build` folder.

1. Compile the package.
2. Run the tests.
3. Read the log, and run a step again with `--verbose` if it fails.

> A step that fails twice needs a look at the [guide](https://example.com/guide).
"""
}

/// Launch with `-demoSelection` to select a range that starts in the heading
/// and ends inside the code block, without touching the screen. Useful for
/// screenshots and for checking the selection path from the command line.
Expand Down
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,36 @@ and Core Animation plays each fade, so the main thread does no work for each fra
underline and strikethrough fade in. Backgrounds, images and formulas show at once. A tag that starts its animation
ends the fades. The fade is off with Reduce Motion, and with a line limit.

### Replacing the text

By default, a new document is laid out in the background, also when it replaces the text on screen. Until that
layout is ready, the view shows the old text and reports the old height. An app that swaps one complete text for
another, for example a summary for its details, can lay out the new text at once and crossfade to it:

```swift
TranscriptText(showsSummary ? summary : details)
.crossfadesReplacedText(duration: 0.25)
```

The view then lays out the new document on the main thread in the same SwiftUI update, so SwiftUI gets the new
height at once. The old drawing crossfades to the new one, as a `UITextView` does in a `.transitionCrossDissolve`
transition. While the crossfade plays, the drawing is clipped to the view's bounds and the space that tags' shapes
may draw in, so the old text does not show below a view that got shorter. A duration of zero shows the new text at
once. A document that only adds text to the one before (the same blocks with more text, or more blocks) still goes
to the background, and so do the updates of a stream. The crossfade has no motion, so it also plays with Reduce
Motion. In UIKit, set `replacementCrossfadeDuration` on `TranscriptTextView`.

Block ids decide what adds to the text. A summary that is the start of its details, parsed with the same id prefix,
gives the details the ids of the summary's blocks, so the switch to the details only adds text: it goes to the
background, with no crossfade. Parse the two texts with different prefixes to crossfade both ways:

```swift
let summary = MarkdownStreamParser.document(from: summaryText, idPrefix: "summary")
let details = MarkdownStreamParser.document(from: detailsText, idPrefix: "details")
```

The first text after an empty document also only adds text, so it goes to the background too.

### Images

Images in the text show their alt text unless you provide a loader. The library never fetches anything itself, so
Expand Down
29 changes: 29 additions & 0 deletions Sources/TranscriptKit/Layout/DocumentUpdate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import Foundation

/// How a view takes a document that the app sets directly.
enum DocumentUpdate: Equatable {
/// Laid out on the layout queue, as each update of a stream is. The
/// view shows the old layout until the new one is ready.
case background
/// Laid out on the main thread at once, so the view's size is the new
/// one before the app measures it. The view crossfades from the old
/// drawing for this many seconds, or shows the new one at once for zero.
case now(crossfade: TimeInterval)

/// What the view does when the app replaces `old` with `new`.
///
/// - Parameters:
/// - isLaidOut: the view shows a layout and has a width, so it can
/// lay out the new document now.
/// - crossfade: the view's `replacementCrossfadeDuration`. Nil keeps
/// every document on the background path.
/// - Returns: `.now` only for a document that does not add to `old`. A
/// document that adds to it (longer text in the last block, or more
/// blocks) goes to the background, as a stream's updates do. So does
/// the first text after an empty document.
static func choose(replacing old: TranscriptDocument, with new: TranscriptDocument, isLaidOut: Bool,
crossfade: TimeInterval?) -> DocumentUpdate {
guard isLaidOut, let crossfade, !new.extends(old) else { return .background }
return .now(crossfade: max(crossfade, 0))
}
}
23 changes: 18 additions & 5 deletions Sources/TranscriptKit/Layout/LayoutEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import QuartzCore
/// main run loop.
///
/// The main thread lays out synchronously only when it cannot wait: the
/// first layout, and a change of width or style. It does so through
/// first layout, a change of width or style, and a replaced document when
/// the view's `replacementCrossfadeDuration` asks for it. It does so through
/// `queue.sync`, so the engine's state is only ever touched on its queue.
///
/// While text is being appended, the engine also draws the end of the
Expand Down Expand Up @@ -94,6 +95,8 @@ final class LayoutEngine: @unchecked Sendable {
// Guarded by `lock`.
private let lock = NSLock()
private var pending: Request?
/// `pending` waits for `relayout` on the main thread: a drain leaves it.
private var pendingIsForMain = false
private var drainScheduled = false
/// Layouts are made at most this often: a document that arrives sooner
/// waits, and is replaced by any newer one that arrives meanwhile. More
Expand Down Expand Up @@ -235,6 +238,7 @@ final class LayoutEngine: @unchecked Sendable {
lock.withLock {
isShutDown = true
pending = nil
pendingIsForMain = false
mailbox = nil
onOutput = nil
}
Expand All @@ -252,8 +256,13 @@ final class LayoutEngine: @unchecked Sendable {

/// Asks for `request` to be laid out. Any thread. Returns false once the
/// engine has shut down, so a stream can stop sending to it.
///
/// - Parameter schedulesLayout: false when the caller calls `relayout`
/// at once, which lays out the request on the main thread. The queue
/// then does not lay it out first, also when a drain is already
/// scheduled.
@discardableResult
func submit(_ request: Request) -> Bool {
func submit(_ request: Request, schedulesLayout: Bool = true) -> Bool {
var accepted = true
let delay: CFTimeInterval? = lock.withLock {
guard !isShutDown else { accepted = false; return nil }
Expand All @@ -265,7 +274,8 @@ final class LayoutEngine: @unchecked Sendable {
guard request.sequence > lastSequence else { return nil }
lastSequence = request.sequence
pending = request
if drainScheduled { return nil }
pendingIsForMain = !schedulesLayout
if drainScheduled || !schedulesLayout { return nil }
drainScheduled = true
return max(lastDrain + frameInterval - CACurrentMediaTime(), 0)
}
Expand All @@ -282,7 +292,10 @@ final class LayoutEngine: @unchecked Sendable {

private func takePending() -> Request? {
lock.withLock { () -> Request? in
defer { pending = nil }
defer {
pending = nil
pendingIsForMain = false
}
return pending
}
}
Expand All @@ -301,7 +314,7 @@ final class LayoutEngine: @unchecked Sendable {
private func drain() {
let next: Request? = lock.withLock {
drainScheduled = false
guard let request = pending else { return nil }
guard let request = pending, !pendingIsForMain else { return nil }
pending = nil
lastDrain = CACurrentMediaTime()
return request
Expand Down
24 changes: 23 additions & 1 deletion Sources/TranscriptKit/iOS/TranscriptText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import UIKit
/// and laid out in the background and go straight to the view, and SwiftUI
/// only re-measures the view when its height changes. With
/// `init(_ document:)`, every new document goes through a full SwiftUI
/// update (layout still happens in the background).
/// update (layout still happens in the background, unless
/// `crossfadesReplacedText(_:duration:)` lays out a replaced one at once).
public struct TranscriptText: UIViewRepresentable {
private enum Source {
case document(TranscriptDocument)
Expand All @@ -25,6 +26,7 @@ public struct TranscriptText: UIViewRepresentable {
private var mathAccessibilityLabel: ((TranscriptMath) -> String)?
private var animatesTags = true
private var textFadeInDuration: TimeInterval?
private var replacementCrossfadeDuration: TimeInterval?
private var animationTiming: TranscriptAnimationTiming = .immediately
private var animatesFirstText = false
private var isSelectable = true
Expand Down Expand Up @@ -109,6 +111,25 @@ public struct TranscriptText: UIViewRepresentable {
return copy
}

/// Lays out a document that replaces the one before at once, so that
/// SwiftUI gets its new height in the same update, and crossfades from
/// the old text to the new one; see
/// `TranscriptTextView.replacementCrossfadeDuration`. A document that
/// only adds text to the one before is laid out in the background, as
/// before. That includes a text that starts with the old one, parsed
/// with the same `idPrefix`, and the first text after an empty
/// document. Off by default.
///
/// ```swift
/// TranscriptText(showsSummary ? summary : details)
/// .crossfadesReplacedText(duration: 0.25)
/// ```
public func crossfadesReplacedText(_ crossfades: Bool = true, duration: TimeInterval = 0.25) -> TranscriptText {
var copy = self
copy.replacementCrossfadeDuration = crossfades ? duration : nil
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 @@ -213,6 +234,7 @@ public struct TranscriptText: UIViewRepresentable {
view.animatesTags = animatesTags
view.animatesTagsInFirstText = animatesFirstText
view.textFadeInDuration = textFadeInDuration
view.replacementCrossfadeDuration = replacementCrossfadeDuration
view.tagAnimationTiming = animationTiming
view.isSelectable = isSelectable
view.showsWritingTools = showsWritingTools
Expand Down
Loading
Loading