Open source CapCut alternative.
TypeScript
fix(ios): prompter lines fill the width they are drawn in
David Leae365f45988b
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swiftindex 61a530b7..21a34d5e 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Teleprompter.swift@@ -16,37 +16,53 @@ nonisolated public struct TeleprompterSettings: Equatable, Codable, Sendable {}}-/// Prompter copy from a raw note. Spacing is the prompter's job: runs of-/// spaces collapse, the writer's own line breaks hold as paragraph breaks,-/// and a long unbroken paragraph wraps into short lines at clause boundaries-/// so the eye has a rhythm to follow. Nobody has to format a note to read it.-nonisolated public func pacedScript(_ raw: String) -> String {+/// Prompter copy from a raw note, broken into the lines the screen draws.+///+/// Spacing is the prompter's job: runs of spaces collapse and the writer's+/// own line breaks hold as paragraph breaks, so nobody has to format a note+/// to read it. Inside a paragraph, words stay together while they fit — a+/// line ends where the next word would run off the picture, and a short+/// clause shares its line with what follows it.+///+/// The measurer belongs to the caller, so the words are measured on the face+/// and the size they will be drawn in. `room` is the width they are drawn in,+/// in whatever unit that measurer answers in.+nonisolated public func pacedScript(+ _ raw: String,+ room: Double,+ measure: (String) -> Double+) -> String {let paragraphs = raw.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: "\n", omittingEmptySubsequences: true)- .map { pacedParagraph(String($0)) }+ .map { pacedParagraph(String($0), room: room, measure: measure) }.filter { !$0.isEmpty }return paragraphs.joined(separator: "\n\n")}-/// Words a line holds before it breaks anyway.-private nonisolated let lineWordCap = 6-/// Words after which a clause end (comma, period, dash…) takes the break.-private nonisolated let clauseBreakMin = 2--private nonisolated func pacedParagraph(_ text: String) -> String {+private nonisolated func pacedParagraph(+ _ text: String,+ room: Double,+ measure: (String) -> Double+) -> String {let words = text.split(whereSeparator: { $0.isWhitespace }).map(String.init)+ // No room to speak of: the paragraph is one line and the screen decides+ // where it falls.+ guard room > 0 else { return words.joined(separator: " ") }var lines: [String] = []- var line: [String] = []+ var line = ""for word in words {- line.append(word)- let clauseEnd = word.last.map { ",.;:!?—".contains($0) } ?? false- if line.count >= lineWordCap || (clauseEnd && line.count >= clauseBreakMin) {- lines.append(line.joined(separator: " "))- line = []+ let candidate = line.isEmpty ? word : "\(line) \(word)"+ // A word wider than the room takes its own line whole; breaking it+ // would leave the reader with half a word.+ if !line.isEmpty, measure(candidate) > room {+ lines.append(line)+ line = word+ } else {+ line = candidate}}- if !line.isEmpty { lines.append(line.joined(separator: " ")) }+ if !line.isEmpty { lines.append(line) }return lines.joined(separator: "\n")}@@ -73,8 +89,11 @@ nonisolated public struct TeleprompterState: Equatable, Sendable {!script.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty}- /// The text the overlay renders: the raw script, paced.- public var displayScript: String { pacedScript(script) }+ /// The text the overlay renders: the raw script, broken to the room the+ /// screen gives it.+ public func displayScript(room: Double, measure: (String) -> Double) -> String {+ pacedScript(script, room: room, measure: measure)+ }/// Seconds the whole script takes at the set pace.public var duration: TimeInterval { readDuration(of: script, wordsPerMinute: settings.wordsPerMinute) }diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swiftindex fa890e60..b99cc1d3 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/CameraScreen.swift@@ -586,11 +586,30 @@ struct TeleprompterOverlay: View {/// Breathing room between one pass of the script and the next, as a share/// of the prompter's height.private static var gapShare: Double { 0.3 }- /// Room kept at the foot of the screen for the record button and the tabs.- private static var controlsInset: Double { 190 }+ /// Room kept at the foot of the screen, clear of the home indicator. The+ /// script only ever runs on a clear stage, so it takes the screen; the+ /// controls a tap brings back float over the words for their few seconds.+ private static var footRoom: Double { 40 }+ /// Margin each side of the script.+ private static var sidePadding: Double { 24 }++ /// The script broken to the width it is drawn in, measured on the very+ /// face and size it will be drawn in. A line holds as many words as the+ /// picture has room for, so a short clause reads on one line with what+ /// follows it. The last point of the width is left to the layout, so a+ /// line measured here as fitting is never broken again as it draws.+ private func script(room: Double) -> String {+ let font = UIFont.systemFont(+ ofSize: camera.teleprompter.settings.textSize,+ weight: .heavy+ )+ return camera.teleprompter.displayScript(room: room - 1) { line in+ (line as NSString).size(withAttributes: [.font: font]).width+ }+ }- private var scriptText: some View {- Text(camera.teleprompter.displayScript)+ private func scriptText(_ text: String) -> some View {+ Text(text).font(.system(size: camera.teleprompter.settings.textSize, weight: .heavy)).foregroundStyle(.white).lineSpacing(4)@@ -606,16 +625,17 @@ struct TeleprompterOverlay: View {var body: some View {GeometryReader { geometry in// The script gets the screen, stopping short of the controls.- let height = max(geometry.size.height - Self.controlsInset, 0)+ let height = max(geometry.size.height - Self.footRoom, 0)let gap = height * Self.gapShare+ let lines = script(room: geometry.size.width - Self.sidePadding * 2)TimelineView(.animation) { context inlet elapsed = elapsed(at: context.date)// Two passes, one behind the other: the script runs without// ever leaving the screen empty, in a take as in a preview.VStack(alignment: .leading, spacing: gap) {- scriptText+ scriptText(lines).onGeometryChange(for: Double.self, of: { $0.size.height }) { textHeight = $0 }- scriptText+ scriptText(lines)}.offset(y: camera.teleprompter.scrollOffset(@@ -625,7 +645,7 @@ struct TeleprompterOverlay: View {gap: gap) + dragged + dragging)- .padding(.horizontal, 24)+ .padding(.horizontal, Self.sidePadding)}.frame(height: height, alignment: .top).clipped()diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swiftindex 22158473..747d39cc 100644--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift@@ -105,24 +105,50 @@ import Testing#expect(readDuration(of: "", wordsPerMinute: 150) == 0)}+ /// A stand-in face: every character ten points wide, spaces included.+ /// Enough to pin down where a line ends without a screen.+ func measure(_ line: String) -> Double { Double(line.count) * 10 }+@Test func pacingRespectsUserNewlines() {- let paced = pacedScript("First thought\nSecond thought")+ let paced = pacedScript("First thought\nSecond thought", room: 1000, measure: measure)#expect(paced == "First thought\n\nSecond thought")}@Test func pacingCollapsesSpaceRuns() {- #expect(pacedScript("hello there friend") == "hello there friend")+ #expect(pacedScript("hello there friend", room: 1000, measure: measure) == "hello there friend")+ }++ @Test func wordsShareALineWhileThePictureHasRoom() {+ let script = "Hey everyone, welcome back"+ // 26 characters at ten points each, with room to spare.+ #expect(pacedScript(script, room: 400, measure: measure) == script)}- @Test func pacingWrapsLongParagraphsAtClauses() {- let paced = pacedScript("Hey everyone, welcome back to the channel where we talk about editing")+ @Test func aLineEndsWhereTheNextWordWouldRunOff() {+ let paced = pacedScript(+ "Hey everyone, welcome back to the channel where we talk about editing",+ room: 200,+ measure: measure+ )let lines = paced.split(separator: "\n").map(String.init)- // The clause end takes the first break; no line outruns the word cap.- #expect(lines.first == "Hey everyone,")- #expect(lines.allSatisfy { $0.split(separator: " ").count <= 6 })+ #expect(lines.allSatisfy { measure($0) <= 200 })+ // Each line is full: the first word of the next one would not have fit.+ for (line, next) in zip(lines, lines.dropFirst()) {+ let word = next.split(separator: " ").first.map(String.init) ?? ""+ #expect(measure("\(line) \(word)") > 200)+ }// Every word survives the wrap.#expect(paced.split(whereSeparator: { $0.isWhitespace }).count == 12)}++ @Test func aWordWiderThanTheRoomKeepsItsOwnLine() {+ let paced = pacedScript("a supercalifragilistic b", room: 60, measure: measure)+ #expect(paced == "a\nsupercalifragilistic\nb")+ }++ @Test func noRoomToSpeakOfLeavesTheParagraphWhole() {+ #expect(pacedScript("keep me together", room: 0, measure: measure) == "keep me together")+ }}@MainActor