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
32 changes: 32 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,35 @@ jobs:
run: >
xcodebuild build -project Benchmark/TranscriptBench.xcodeproj -scheme TranscriptBench
-destination 'generic/platform=iOS' -skipMacroValidation CODE_SIGNING_ALLOWED=NO

ios-view-tests:
name: iOS view tests
runs-on: macos-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Show the Xcode version
run: xcodebuild -version
- name: Pick a simulator
run: |
sdk=$(xcrun --sdk iphonesimulator --show-sdk-version)
udid=$(xcrun simctl list devices available --json | python3 -c '
import json, sys
devices = json.load(sys.stdin)["devices"]
sdk = [int(part) for part in sys.argv[1].split(".")]
def version(runtime):
return [int(part) for part in runtime.rsplit("iOS-", 1)[1].split("-")]
runtimes = sorted((r for r in devices if ".SimRuntime.iOS-" in r and version(r) <= sdk), key=version, reverse=True)
phones = [(r, d) for r in runtimes for d in devices[r] if ".iPhone-" in d["deviceTypeIdentifier"]]
if not phones:
sys.exit("No iPhone simulator is available.")
runtime, device = phones[0]
print(device["name"], runtime, file=sys.stderr)
print(device["udid"])
' "$sdk")
echo "SIMULATOR_UDID=$udid" >> "$GITHUB_ENV"
- name: Run the view tests
run: >
xcodebuild test -scheme TranscriptKit
-destination "platform=iOS Simulator,id=$SIMULATOR_UDID"
-only-testing:TranscriptKitViewTests
1 change: 1 addition & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ let package = Package(
targets: [
.target(name: "TranscriptKit"),
.testTarget(name: "TranscriptKitTests", dependencies: ["TranscriptKit"]),
.testTarget(name: "TranscriptKitViewTests", dependencies: ["TranscriptKit"]),
]
)
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut
## Requirements

iOS 17 or later, Swift 6 (Xcode 16 or later). The parser and document model also build on macOS 14, which is where
the tests run.
most of the tests run.

## Installation

Expand Down Expand Up @@ -376,6 +376,7 @@ waited for, so turn off `textFadeInDuration` and `animatesTags` to compare pixel
| --- | --- |
| `Sources/TranscriptKit` | The library |
| `Tests/TranscriptKitTests` | Unit, layout and pixel tests: `swift test` |
| `Tests/TranscriptKitViewTests` | Tests of `TranscriptTextView` and `TranscriptText` on iOS: `xcodebuild test -scheme TranscriptKit -destination 'platform=iOS Simulator,name=<an iPhone>' -only-testing:TranscriptKitViewTests` |
| [`Examples/ChatSample`](Examples/ChatSample) | A chat app that mixes streamed TranscriptKit text with native SwiftUI views (cards, charts, photos), custom tags and text beside other views |
| `Demo` | A small app for trying selection and streaming |
| `Benchmark` | A benchmark app and script that compare TranscriptKit with other renderers on the simulator and on phones, with results and notes |
Expand Down
116 changes: 116 additions & 0 deletions Tests/TranscriptKitViewTests/TranscriptTextTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#if canImport(UIKit) && !os(watchOS)
import SwiftUI
import Testing
import UIKit
@testable import TranscriptKit

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

@MainActor
private func textViews(in view: UIView) -> [TranscriptTextView] {
view.subviews.flatMap { subview in
(subview as? TranscriptTextView).map { [$0] } ?? textViews(in: subview)
}
}

/// The views that SwiftUI has placed: they have a width.
@MainActor
private func placedTextViews(in root: UIView) -> [TranscriptTextView] {
root.layoutIfNeeded()
return textViews(in: root).filter { $0.bounds.width > 0 }
}

/// Lays out `root` until `condition` holds, for at most two seconds.
@MainActor
private func waitUntil(_ root: UIView, _ condition: () -> Bool) async {
for _ in 0..<200 {
root.layoutIfNeeded()
if condition() { return }
try? await Task.sleep(for: .milliseconds(10))
}
}

@MainActor
private func fittingHeight(of view: TranscriptTextView) -> CGFloat {
view.sizeThatFits(CGSize(width: view.bounds.width, height: CGFloat.greatestFiniteMagnitude)).height
}

@MainActor
private func isAsTallAsItsText(_ view: TranscriptTextView) -> Bool {
view.bounds.height == fittingHeight(of: view)
}

@Suite(.serialized, .timeLimit(.minutes(1))) @MainActor
struct TranscriptTextTests {
/// A window of a fixed size, so that no test depends on the screen. Each
/// test has its own, and it lasts as long as the test.
let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 640))

/// Shows `content` in the window, and returns the view that holds it.
private func show(_ content: some View) -> UIView {
let controller = UIHostingController(rootView: content)
window.rootViewController = controller
window.isHidden = false
controller.view.frame = window.bounds
controller.view.layoutIfNeeded()
return controller.view
}

@Test func rowsInALazyStackAreAsTallAsTheirText() async throws {
let messages = (0..<100).map { "Message \($0). " + String(repeating: "More words that wrap. ", count: $0 % 7) }
let root = show(ScrollView {
LazyVStack(spacing: 8) {
ForEach(messages, id: \.self) { TranscriptText(MarkdownStreamParser.document(from: $0)) }
}
})
await waitUntil(root) { !placedTextViews(in: root).isEmpty }
let views = placedTextViews(in: root)
try #require(!views.isEmpty)
#expect(views.count < messages.count)
for view in views {
await view.contentSettled()
#expect(view.bounds.width > 0)
#expect(view.bounds.height > 0)
#expect(isAsTallAsItsText(view))
}
}

@Test func aStreamedRowInALazyStackGrowsWithItsText() async throws {
let stream = TranscriptStream(markdown: "The first words.")
let root = show(ScrollView {
LazyVStack(spacing: 8) {
Text(verbatim: "A row above")
TranscriptText(stream: stream)
Text(verbatim: "A row below")
}
})
await waitUntil(root) { placedTextViews(in: root).count == 1 }
let view = try #require(placedTextViews(in: root).first)
let before = view.bounds.height
#expect(before > 0)

stream.append("\n\n" + longParagraph)
stream.finish()
stream.flush()
await view.contentSettled()
await waitUntil(root) { view.bounds.height > before && isAsTallAsItsText(view) }
#expect(view.bounds.height > before)
#expect(isAsTallAsItsText(view))
}

@Test func theLineLimitOfTheEnvironmentWins() async throws {
let document = MarkdownStreamParser.document(from: longParagraph)
let root = show(VStack {
TranscriptText(document).lineLimit(2)
Spacer()
})
await waitUntil(root) { placedTextViews(in: root).count == 1 }
let view = try #require(placedTextViews(in: root).first)
await view.contentSettled()
#expect(view.style.lineLimit == 2)
let cut = DocumentLayout(document: document, width: view.bounds.width, style: view.style)
#expect(view.bounds.height == ceil(cut.height))
#expect(cut.height < DocumentLayout(document: document, width: view.bounds.width).height)
}
}
#endif
Loading
Loading