diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e96ba68..a3e7ef5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/Package.swift b/Package.swift index 20382f8..4e8d8ef 100644 --- a/Package.swift +++ b/Package.swift @@ -10,5 +10,6 @@ let package = Package( targets: [ .target(name: "TranscriptKit"), .testTarget(name: "TranscriptKitTests", dependencies: ["TranscriptKit"]), + .testTarget(name: "TranscriptKitViewTests", dependencies: ["TranscriptKit"]), ] ) diff --git a/README.md b/README.md index 17c85d3..39fbb22 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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=' -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 | diff --git a/Tests/TranscriptKitViewTests/TranscriptTextTests.swift b/Tests/TranscriptKitViewTests/TranscriptTextTests.swift new file mode 100644 index 0000000..ced339e --- /dev/null +++ b/Tests/TranscriptKitViewTests/TranscriptTextTests.swift @@ -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 diff --git a/Tests/TranscriptKitViewTests/TranscriptTextViewTests.swift b/Tests/TranscriptKitViewTests/TranscriptTextViewTests.swift new file mode 100644 index 0000000..0ba9b9a --- /dev/null +++ b/Tests/TranscriptKitViewTests/TranscriptTextViewTests.swift @@ -0,0 +1,277 @@ +#if canImport(UIKit) && !os(watchOS) +import Testing +import UIKit +@testable import TranscriptKit + +private let longParagraph = String(repeating: "Words that wrap onto several lines. ", count: 8) +private let linked = "Read [the guide](https://example.com/guide) before you start." + +@MainActor +private func makeView(_ markdown: String, width: CGFloat = 320, style: TranscriptStyle = .init(), + in window: UIWindow? = nil) -> TranscriptTextView { + let view = TranscriptTextView(frame: .zero) + // A style set while the view has a width lays out the empty text at + // once, and the text set after it then comes from the background. + view.style = style + view.frame = CGRect(x: 0, y: 0, width: width, height: 400) + window?.addSubview(view) + view.document = MarkdownStreamParser.document(from: markdown) + return view +} + +/// The height that the view must have: the layout's own, at the same width and style. +private func expectedHeight(_ markdown: String, width: CGFloat, style: TranscriptStyle = .init()) -> CGFloat { + ceil(DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: width, style: style).height) +} + +private func limited(_ limit: Int?) -> TranscriptStyle { + var style = TranscriptStyle() + style.lineLimit = limit + return style +} + +@MainActor +private func textRange(_ range: Range, in view: TranscriptTextView) throws -> UITextRange { + let start = try #require(view.position(from: view.beginningOfDocument, offset: range.lowerBound)) + let end = try #require(view.position(from: view.beginningOfDocument, offset: range.upperBound)) + return try #require(view.textRange(from: start, to: end)) +} + +/// The middle of the first line of `range` on screen. +@MainActor +private func center(of range: Range, in view: TranscriptTextView) throws -> CGPoint { + let rect = view.firstRect(for: try textRange(range, in: view)) + return CGPoint(x: rect.midX, y: rect.midY) +} + +@MainActor +private func documentLength(of view: TranscriptTextView) -> Int { + view.offset(from: view.beginningOfDocument, to: view.endOfDocument) +} + +@MainActor +private func hasTextInteraction(_ view: TranscriptTextView) -> Bool { + view.interactions.contains { $0 is UITextInteraction } +} + +@Suite(.serialized, .timeLimit(.minutes(1))) @MainActor +struct TranscriptTextViewTests { + /// Windows of a fixed size, so that no test depends on the screen. Each + /// test has its own, and they last as long as the test. + let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 640)) + let otherWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 640)) + + // MARK: Sizing + + @Test func aSizedViewIsAsTallAsItsLayout() { + let view = makeView(longParagraph, width: 300) + let height = expectedHeight(longParagraph, width: 300) + #expect(height > 0) + #expect(view.intrinsicContentSize.height == height) + #expect(view.sizeThatFits(CGSize(width: 300, height: CGFloat.greatestFiniteMagnitude)) == CGSize(width: 300, height: height)) + } + + @Test func anUnsizedViewMeasuresAtTheProposedWidth() { + let view = TranscriptTextView(frame: .zero) + view.document = MarkdownStreamParser.document(from: longParagraph) + let wide = view.sizeThatFits(CGSize(width: 300, height: CGFloat.greatestFiniteMagnitude)) + let narrow = view.sizeThatFits(CGSize(width: 150, height: CGFloat.greatestFiniteMagnitude)) + #expect(wide == CGSize(width: 300, height: expectedHeight(longParagraph, width: 300))) + #expect(narrow == CGSize(width: 150, height: expectedHeight(longParagraph, width: 150))) + #expect(narrow.height > wide.height) + } + + @Test func emptyTextHasNoHeight() async { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 400)) + #expect(view.sizeThatFits(CGSize(width: 320, height: CGFloat.greatestFiniteMagnitude)).height == 0) + #expect(!view.hasText) + + view.document = MarkdownStreamParser.document(from: "Hello") + #expect(view.intrinsicContentSize.height > 0) + view.document = TranscriptDocument() + await view.contentSettled() + #expect(view.intrinsicContentSize.height == 0) + #expect(view.sizeThatFits(CGSize(width: 320, height: CGFloat.greatestFiniteMagnitude)).height == 0) + #expect(!view.hasText) + } + + @Test func aNewWidthLaysOutAgain() { + let view = makeView(longParagraph, width: 300) + view.frame.size.width = 150 + view.layoutIfNeeded() + #expect(view.intrinsicContentSize.height == expectedHeight(longParagraph, width: 150)) + } + + // MARK: First layout + + @Test func theFirstLayoutOfPlainTextIsSynchronous() { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 400)) + let document = MarkdownStreamParser.document(from: longParagraph) + view.document = document + #expect(view.hasText) + #expect(documentLength(of: view) == DocumentLayout(document: document, width: 320).length) + #expect(view.intrinsicContentSize.height == expectedHeight(longParagraph, width: 320)) + } + + @Test func theFirstLayoutOfAStreamIsSynchronous() { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 400)) + view.stream = TranscriptStream(markdown: longParagraph) + #expect(view.hasText) + #expect(view.intrinsicContentSize.height == expectedHeight(longParagraph, width: 320)) + } + + @Test func aStreamedAppendArrivesLater() async { + let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 400)) + window.addSubview(view) + let stream = TranscriptStream(markdown: "First paragraph.\n\n") + view.stream = stream + let before = view.intrinsicContentSize.height + view.select(0..<5) + + stream.append(longParagraph) + stream.finish() + stream.flush() + await view.contentSettled() + + let markdown = "First paragraph.\n\n" + longParagraph + #expect(view.intrinsicContentSize.height == expectedHeight(markdown, width: 320)) + #expect(view.intrinsicContentSize.height > before) + #expect(documentLength(of: view) == DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: 320).length) + #expect(view.selectedRange == 0..<5) + } + + // MARK: Line limit + + @Test func aLineLimitCutsTheHeightAndTheText() { + let view = makeView(longParagraph, width: 200, style: limited(2)) + let full = DocumentLayout(document: MarkdownStreamParser.document(from: longParagraph), width: 200) + let cut = DocumentLayout(document: MarkdownStreamParser.document(from: longParagraph), width: 200, style: limited(2)) + #expect(cut.length < full.length) + #expect(view.intrinsicContentSize.height == ceil(cut.height)) + #expect(view.intrinsicContentSize.height < ceil(full.height)) + #expect(view.sizeThatFits(CGSize(width: 200, height: CGFloat.greatestFiniteMagnitude)).height == ceil(cut.height)) + + view.selectAll(nil) + #expect(view.selectedRange == 0..?] = [] + view.onSelectionChange = { changes.append($0) } + + view.select(6..<10) + view.select(6..<10) + #expect(view.selectedRange == 6..<10) + #expect(view.selectedText == "that") + #expect(hasTextInteraction(view)) + + view.select(nil) + #expect(view.selectedRange == nil) + #expect(view.selectedText == nil) + #expect(changes == [6..<10, nil]) + } + + @Test func selectKeepsTheRangeInTheText() { + let view = makeView("Hello") + view.select(2..<1000) + #expect(view.selectedRange == 2..<5) + view.select(3..<3) + #expect(view.selectedRange == nil) + } + + @Test func selectAllSelectsTheWholeText() { + let view = makeView(linked) + #expect(view.canPerformAction(#selector(UIResponderStandardEditActions.selectAll(_:)), withSender: nil)) + #expect(!view.canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil)) + + view.selectAll(nil) + #expect(view.selectedRange == 0..?] = [] + first.onSelectionChange = { firstChanges.append($0) } + + first.select(0..<5) + elsewhere.select(0..<5) + try #require(second.becomeFirstResponder()) + second.select(6..<10) + + #expect(first.selectedRange == nil) + #expect(firstChanges == [0..<5, nil]) + #expect(second.selectedRange == 6..<10) + #expect(elsewhere.selectedRange == 0..<5) + } + + @Test func aViewThatLeavesItsWindowClearsItsSelection() { + let view = makeView(longParagraph, in: window) + var changes: [Range?] = [] + view.onSelectionChange = { changes.append($0) } + view.select(0..<5) + + view.removeFromSuperview() + #expect(view.window == nil) + #expect(view.selectedRange == nil) + #expect(changes == [0..<5, nil]) + } + + // MARK: Hit testing + + @Test func aSelectableViewTakesEveryTouchInside() throws { + let view = makeView(linked) + #expect(!hasTextInteraction(view)) + let word = try center(of: 0..<4, in: view) + #expect(view.point(inside: word, with: nil)) + #expect(hasTextInteraction(view)) + #expect(view.point(inside: CGPoint(x: view.bounds.maxX - 1, y: view.bounds.maxY - 1), with: nil)) + #expect(!view.point(inside: CGPoint(x: -1, y: -1), with: nil)) + } + + @Test func anUnselectableViewTakesOnlyTouchesOnLinks() throws { + let view = makeView(linked) + view.isSelectable = false + let document = MarkdownStreamParser.document(from: linked) + let span = try #require(document.block(at: 0).spans.first { $0.link != nil }) + #expect(document.text(in: span.range) == "the guide") + + #expect(view.point(inside: try center(of: span.range, in: view), with: nil)) + #expect(!view.point(inside: try center(of: 0..<4, in: view), with: nil)) + #expect(!view.point(inside: CGPoint(x: view.bounds.maxX - 1, y: view.bounds.maxY - 1), with: nil)) + #expect(!hasTextInteraction(view)) + } +} +#endif