From 579afa7ca68b17ef535346c34f1d5a437a8896fb Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:08:29 -0800 Subject: [PATCH 01/14] Find the base direction of a text from its first strong character DirectionScan finds the direction of the first strong character, as the Unicode bidirectional algorithm does. It also records if the text has a right-to-left character. The scan continues from where it stopped, so streamed text is not read again. The styled text of a block can now carry a base direction for Core Text. Co-Authored-By: Claude Opus 5.5 --- .../Layout/TranscriptStyle.swift | 13 +- .../Layout/WritingDirection.swift | 126 ++++++++++++++++++ .../WritingDirectionTests.swift | 63 +++++++++ 3 files changed, 198 insertions(+), 4 deletions(-) create mode 100644 Sources/TranscriptKit/Layout/WritingDirection.swift create mode 100644 Tests/TranscriptKitTests/WritingDirectionTests.swift diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index 69af107..e6bc265 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -192,6 +192,7 @@ public struct TranscriptStyle: Equatable, Sendable { static let foregroundKey = NSAttributedString.Key("TranscriptKit.foreground") static let backgroundKey = NSAttributedString.Key("TranscriptKit.background") private static let kernKey = NSAttributedString.Key(kCTKernAttributeName as String) + static let paragraphStyleKey = NSAttributedString.Key(kCTParagraphStyleAttributeName as String) func attributes(for kind: TranscriptBlock.Kind) -> [NSAttributedString.Key: Any] { var attributes: [NSAttributedString.Key: Any] = [ @@ -205,21 +206,25 @@ public struct TranscriptStyle: Equatable, Sendable { /// The styled text of `block` from UTF-16 offset `start` to its end. func attributedString(for block: TranscriptBlock, from start: Int = 0, images: ImageSizing? = nil, - definitions: [String: String] = [:], kerns: [Int: CGFloat] = [:]) -> NSAttributedString { - attributedString(for: block, range: start.. NSAttributedString { + attributedString(for: block, range: start.., extraTraits: InlineSpan.Traits = [], images: ImageSizing? = nil, definitions: [String: String] = [:], - kerns: [Int: CGFloat] = [:]) -> NSAttributedString { + kerns: [Int: CGFloat] = [:], direction: WritingDirection? = nil) -> NSAttributedString { let start = range.lowerBound let text = range == 0.. CTParagraphStyle { + var value = direction + return withUnsafeBytes(of: &value) { bytes in + var setting = CTParagraphStyleSetting(spec: .baseWritingDirection, valueSize: MemoryLayout.size, + value: bytes.baseAddress!) + return CTParagraphStyleCreate(&setting, 1) + } + } +} + +/// What a scan of a text found about its direction, so far: the direction +/// of its first strong character (the natural base direction, as the +/// Unicode bidirectional algorithm finds it), and whether it holds any +/// right-to-left character. +/// +/// A scan goes on from where it stopped, so text that grows by appends is +/// not read again. +struct DirectionScan: Equatable, Sendable { + private(set) var firstStrong: WritingDirection? + private(set) var hasRightToLeft = false + /// The UTF-16 length of the text scanned. + private(set) var length = 0 + /// How many isolates (U+2066 to U+2068) are open: the first strong + /// character is not looked for inside them. + private var isolates = 0 + + init() {} + + init(_ text: String) { + scan(text) + } + + /// The direction to set on the text when it is typeset: nil when it has + /// no right-to-left character, as Core Text then lays it out from the + /// left without being told. + var paragraphDirection: WritingDirection? { + hasRightToLeft ? (firstStrong ?? .leftToRight) : nil + } + + /// Scans `text` from `length`, the end of the text scanned before. The + /// text before it must not have changed. + mutating func scan(_ text: String) { + let utf16 = text.utf16 + guard utf16.count > length else { return } + guard firstStrong == nil || !hasRightToLeft else { + length = utf16.count + return + } + var index = utf16.index(utf16.startIndex, offsetBy: length) + while index < utf16.endIndex { + var value = UInt32(utf16[index]) + utf16.formIndex(after: &index) + if UTF16.isLeadSurrogate(UInt16(value)), index < utf16.endIndex, UTF16.isTrailSurrogate(utf16[index]) { + value = 0x10000 + ((value - 0xD800) << 10) + (UInt32(utf16[index]) - 0xDC00) + utf16.formIndex(after: &index) + } + guard let scalar = Unicode.Scalar(value) else { continue } + if Self.isRightToLeftCharacter(scalar) { hasRightToLeft = true } + if firstStrong == nil { + switch value { + case 0x2066...0x2068: isolates += 1 + case 0x2069: isolates = max(isolates - 1, 0) + default: + if isolates == 0 { firstStrong = Self.strongDirection(of: scalar) } + } + } + if firstStrong != nil, hasRightToLeft { break } + } + length = utf16.count + } + + /// Whether the scalar belongs to a right-to-left script, or is a mark or + /// control that makes text right-to-left. + static func isRightToLeftCharacter(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.value { + case 0x0590...0x08FF, 0xFB1D...0xFDFF, 0xFE70...0xFEFF, 0x10800...0x10FFF, 0x1E800...0x1EFFF: return true + case 0x200F, 0x202B, 0x202E, 0x2067: return true + default: return false + } + } + + /// The direction of a strong character, or nil for one that takes its + /// direction from the text around it: digits, punctuation, spaces, + /// symbols and marks. + static func strongDirection(of scalar: Unicode.Scalar) -> WritingDirection? { + switch scalar.value { + case 0x200E: return .leftToRight + case 0x200F, 0x061C: return .rightToLeft + // Arabic punctuation and signs that are weak or neutral. + case 0x0600...0x0605, 0x0609, 0x060A, 0x060C, 0x066A...0x066C, 0x06DD, 0x06E9, 0x08E2: return nil + default: break + } + let category = scalar.properties.generalCategory + if isRightToLeftCharacter(scalar) { + switch category { + case .nonspacingMark, .enclosingMark, .decimalNumber, .format, .control: return nil + default: return .rightToLeft + } + } + switch category { + case .uppercaseLetter, .lowercaseLetter, .titlecaseLetter, .modifierLetter, .otherLetter, .spacingMark: + return .leftToRight + default: + return nil + } + } +} diff --git a/Tests/TranscriptKitTests/WritingDirectionTests.swift b/Tests/TranscriptKitTests/WritingDirectionTests.swift new file mode 100644 index 0000000..67035b1 --- /dev/null +++ b/Tests/TranscriptKitTests/WritingDirectionTests.swift @@ -0,0 +1,63 @@ +import CoreText +import Foundation +import Testing +@testable import TranscriptKit + +@Test(arguments: [ + ("Hello", WritingDirection?.some(.leftToRight)), + ("שלום", .rightToLeft), + ("مرحبا", .rightToLeft), + ("123 שלום", .rightToLeft), + ("(\"שלום\") hello", .rightToLeft), + ("hello שלום", .leftToRight), + ("١٢٣ abc", .leftToRight), + ("\u{05B0}abc", .leftToRight), + ("\u{2067}abc\u{2069} שלום", .rightToLeft), + ("\u{200F}123", .rightToLeft), + ("日本語", .leftToRight), + ("123 !?", nil), + ("", nil), +]) +func firstStrongCharacterSetsTheDirection(text: String, expected: WritingDirection?) { + #expect(DirectionScan(text).firstStrong == expected) +} + +@Test func onlyTextWithRightToLeftCharactersGetsADirection() { + #expect(DirectionScan("Plain text, 123.").paragraphDirection == nil) + #expect(DirectionScan("Some שלום inside").paragraphDirection == .leftToRight) + #expect(DirectionScan("שלום and more").paragraphDirection == .rightToLeft) + // No strong character before the first right-to-left one. + #expect(DirectionScan("12 \u{0661}\u{0662}").paragraphDirection == .leftToRight) +} + +@Test func scanGoesOnFromWhereItStopped() { + var scan = DirectionScan("12. ") + #expect(scan.firstStrong == nil) + scan.scan("12. שלום") + #expect(scan.firstStrong == .rightToLeft) + #expect(scan == DirectionScan("12. שלום")) + + var grown = DirectionScan("Text") + grown.scan("Text and 😀 then עברית") + #expect(grown.paragraphDirection == .leftToRight) + #expect(grown.length == "Text and 😀 then עברית".utf16.count) +} + +/// Each run's string range and position, in the order Core Text draws them. +private func runLayout(_ text: String, direction: WritingDirection?) -> [[Double]] { + var attributes: [NSAttributedString.Key: Any] = [TranscriptStyle.fontKey: CTFontCreateUIFontForLanguage(.system, 17, nil)!] + if let direction { attributes[TranscriptStyle.paragraphStyleKey] = direction.paragraphStyle } + let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: attributes)) + return (CTLineGetGlyphRuns(line) as! [CTRun]).map { run in + let range = CTRunGetStringRange(run) + var position = CGPoint.zero + CTRunGetPositions(run, CFRange(location: 0, length: 1), &position) + return [Double(range.location), Double(range.length), position.x.rounded()] + } +} + +@Test(arguments: ["שלום עולם ", "123 שלום", "hello שלום world ", "(\"مرحبا\") hello", "١٢٣ abc", "\u{2067}abc\u{2069} שלום"]) +func scanFindsTheDirectionThatCoreTextFinds(text: String) { + let direction = DirectionScan(text).firstStrong + #expect(runLayout(text, direction: nil) == runLayout(text, direction: direction)) +} From 17db982fb26322fee6567939e0993f828feb1476 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:38:52 -0800 Subject: [PATCH 02/14] Lay out right-to-left paragraphs from the right edge Each block gets the base direction of its first strong character. A block that has right-to-left characters is typeset with that direction, so a line typeset from the middle of the block keeps it. A block with no right-to-left character is typeset as before. Code stays left to right. In a right-to-left block: - Lines start at the right edge. The text alignment counts from there. - The indents of lists and quotes, the list markers and the quote bars are on the right. A number marker shows its period on the side of the text. - A table puts its first column on the right. - A truncated last line keeps the full width. A streamed block does not scan its text again. It drops its earlier lines when its direction changes, and the gap above it is drawn again. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/BlockLayout.swift | 111 +++++++++---- .../TranscriptKit/Layout/DocumentLayout.swift | 38 +++-- .../RightToLeftLayoutTests.swift | 156 ++++++++++++++++++ 3 files changed, 261 insertions(+), 44 deletions(-) create mode 100644 Tests/TranscriptKitTests/RightToLeftLayoutTests.swift diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index bc0291d..7f42ddc 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -39,7 +39,9 @@ final class BlockLayout: @unchecked Sendable { /// A table's grid. Its lines are in text order: row by row, cell by cell. struct Table { - /// Left edge of each column, then the right edge of the last one. + /// Left edge of each column, then the right edge of the last one, + /// from left to right. In a right-to-left table, the first column + /// is the one on the right. let columnX: [CGFloat] /// Top of each row, then the bottom of the last one. let rowY: [CGFloat] @@ -79,6 +81,16 @@ final class BlockLayout: @unchecked Sendable { /// For a block with reference links: those whose label was defined when /// it was laid out, and so styled as links. let definedReferences: Set? + /// What the block's text says about its direction. + let directionScan: DirectionScan + /// The base direction that the text was typeset with, or nil for Core + /// Text's natural one, when the text has no right-to-left character. + /// Code is always left to right. + let paragraphDirection: WritingDirection? + + /// Whether the lines start at the right: the indents of the block's + /// containers, its list marker and its quote bars are on the right too. + var isRightToLeft: Bool { paragraphDirection == .rightToLeft } /// The labels of `block`'s reference links that `definitions` defines, /// or nil if it has none. @@ -117,15 +129,22 @@ final class BlockLayout: @unchecked Sendable { let contentLeading = style.contentLeading(for: block.containers) let defined = Self.definedReferences(of: block, in: definitions) self.definedReferences = defined - // Earlier lines can be kept only if they were styled the same way. - let previous = previous.flatMap { $0.definedReferences == defined ? $0 : nil } + // Earlier lines can be kept only if the block grew from them and + // they were styled the same way. + let grown = previous.flatMap { $0.definedReferences == defined && $0.block.isStyledPrefix(of: block) ? $0 : nil } + var scan = grown?.directionScan ?? DirectionScan() + scan.scan(block.text) + let direction = block.kind.isCode ? (scan.hasRightToLeft ? .leftToRight : nil) : scan.paragraphDirection + self.directionScan = scan + self.paragraphDirection = direction + let previous = grown.flatMap { $0.paragraphDirection == direction ? $0 : nil } self.imageRevision = revision self.contentLeading = contentLeading let lines: SharedList if let model = block.kind.table { let laidOut = Self.layOutTable(model, block: block, style: style, x: contentLeading, available: available, - blockWidth: width, images: images, definitions: definitions, + blockWidth: width, direction: direction, images: images, definitions: definitions, reusing: previous.flatMap { $0.width == width && $0.style == style && $0.imageRevision == revision ? $0 : nil }) lines = laidOut.lines self.height = laidOut.height @@ -133,21 +152,23 @@ final class BlockLayout: @unchecked Sendable { } else { let sizing = ImageSizing(store: images, maximumWidth: available) let laidOut = Self.layOutText(block, style: style, insets: insets, available: available, blockWidth: width, - sizing: sizing, definitions: definitions, + direction: direction, sizing: sizing, definitions: definitions, reusing: previous.flatMap { $0.width == width && $0.imageRevision == revision ? $0 : nil }) lines = laidOut.lines self.height = laidOut.height self.table = nil } self.lines = lines - self.marker = Self.makeMarker(for: block, style: style, firstLine: lines.first) + self.marker = Self.makeMarker(for: block, style: style, firstLine: lines.first, width: width, + rightToLeft: direction == .rightToLeft) self.attachments = hasImages ? Self.findAttachments(in: lines) : [] } // MARK: Text private static func layOutText(_ block: TranscriptBlock, style: TranscriptStyle, insets: TranscriptStyle.Insets, - available: CGFloat, blockWidth: CGFloat, sizing: ImageSizing, definitions: [String: String], + available: CGFloat, blockWidth: CGFloat, direction: WritingDirection?, sizing: ImageSizing, + definitions: [String: String], reusing previous: BlockLayout?) -> (lines: SharedList, height: CGFloat) { let length = block.utf16Count let font = style.font(for: block.kind) @@ -155,7 +176,7 @@ final class BlockLayout: @unchecked Sendable { var lines = SharedList() var y = insets.vertical var restart = 0 - if let previous, previous.style == style, previous.block.isStyledPrefix(of: block), previous.lines.count > 1 { + if let previous, previous.style == style, previous.lines.count > 1 { // Line breaks are chosen greedily, so appended text can only // change the last line and what follows it. var keep = previous.lines.count - 1 @@ -186,9 +207,10 @@ final class BlockLayout: @unchecked Sendable { && block.text.trimmingCharacters(in: .whitespacesAndNewlines) == "\u{FFFC}" 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 + (isDisplayMath + let x = place(insets.leading + leading + (isDisplayMath ? max(((available - leading - metrics.width) / 2).rounded(.down), 0) - : alignmentOffset(block, style: style, width: metrics.width, room: available - leading)) + : alignmentOffset(block, style: style, width: metrics.width, room: available - leading)), + width: metrics.width, in: blockWidth, direction: direction) var decorations: LineDecorations? if let decorated, let text { decorations = LineDecorations.make(line: ctLine, range: range, indexBase: indexBase, visibleWidth: metrics.width, @@ -209,7 +231,7 @@ final class BlockLayout: @unchecked Sendable { if restart < length { let attributed = style.attributedString(for: block, from: restart, images: sizing, definitions: definitions, - kerns: decorated?.kerns ?? [:]) + kerns: decorated?.kerns ?? [:], direction: direction) let typesetter = CTTypesetterCreateWithAttributedString(attributed) var start = restart while start < length { @@ -239,8 +261,16 @@ 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. + /// Where a line `width` wide starts in a block `blockWidth` wide, if it + /// starts `leading` from the block's leading edge: the left edge, or the + /// right edge in right-to-left text. + static func place(_ leading: CGFloat, width: CGFloat, in blockWidth: CGFloat, direction: WritingDirection?) -> CGFloat { + direction == .rightToLeft ? blockWidth - leading - width : leading + } + + /// How far a line `width` wide moves from the leading edge 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) @@ -273,12 +303,15 @@ final class BlockLayout: @unchecked Sendable { table = original.table imageRevision = original.imageRevision definedReferences = original.definedReferences + directionScan = original.directionScan + paragraphDirection = original.paragraphDirection 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)) + kept.append(Self.withEllipsis(last, block: block, style: style, insets: insets, width: original.width, + direction: original.paragraphDirection)) } lines = kept let bottom = kept.last.map { $0.frame.maxY } ?? 0 @@ -288,9 +321,10 @@ final class BlockLayout: @unchecked Sendable { } private static func withEllipsis(_ line: Line, block: TranscriptBlock, style: TranscriptStyle, - insets: TranscriptStyle.Insets, width: CGFloat) -> Line { + insets: TranscriptStyle.Insets, width: CGFloat, direction: WritingDirection?) -> 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 { @@ -302,12 +336,14 @@ final class BlockLayout: @unchecked Sendable { 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 + // From the leading edge. + let start = aligned ? insets.leading : (direction == .rightToLeft ? width - line.frame.maxX : 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 + let x = place(aligned ? insets.leading + alignmentOffset(block, style: style, width: metrics.width, room: available) : start, + width: metrics.width, in: width, direction: direction) 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) @@ -341,7 +377,8 @@ final class BlockLayout: @unchecked Sendable { /// neither measured nor typeset again, and keep their lines if the /// columns did not change, so only the row being written is redrawn. private static func layOutTable(_ model: TranscriptTable, block: TranscriptBlock, style: TranscriptStyle, x: CGFloat, - available: CGFloat, blockWidth: CGFloat, images: TranscriptImageStore?, definitions: [String: String], + available: CGFloat, blockWidth: CGFloat, direction: WritingDirection?, + images: TranscriptImageStore?, definitions: [String: String], reusing previous: BlockLayout?) -> (lines: SharedList, height: CGFloat, table: Table) { let columns = max(model.columnCount, 1) let padding = style.tableCellPadding @@ -357,7 +394,7 @@ final class BlockLayout: @unchecked Sendable { var kept = 0 var old: Table? if let previous, let oldTable = previous.table, let oldModel = previous.block.kind.table, - oldModel.alignments == model.alignments, previous.block.isStyledPrefix(of: block) { + oldModel.alignments == model.alignments { let limit = min(oldModel.rows.count - 1, model.rows.count) while kept < limit, oldModel.rows[kept] == model.rows[kept] { kept += 1 } old = oldTable @@ -367,7 +404,7 @@ final class BlockLayout: @unchecked Sendable { func makeCells(_ row: Int) -> [Cell] { model.rows[row].prefix(columns).map { range in let text = style.attributedString(for: block, range: range, extraTraits: row == 0 ? .bold : [], images: sizing, - definitions: definitions, kerns: decorated?.kerns ?? [:]) + definitions: definitions, kerns: decorated?.kerns ?? [:], direction: direction) return (text, CTTypesetterCreateWithAttributedString(text), range) } } @@ -390,7 +427,8 @@ final class BlockLayout: @unchecked Sendable { let isBreak = index == start + count || [0x20, 0x09, 0x0A].contains(string.character(at: index)) guard isBreak else { continue } if index > wordStart { - let width = CTLineGetOffsetForStringIndex(line, index, nil) - CTLineGetOffsetForStringIndex(line, wordStart, nil) + // Negative in right-to-left text. + let width = abs(CTLineGetOffsetForStringIndex(line, index, nil) - CTLineGetOffsetForStringIndex(line, wordStart, nil)) longestWord = max(longestWord, width) } wordStart = index + 1 @@ -440,14 +478,16 @@ final class BlockLayout: @unchecked Sendable { } } } + // From the leading edge; mirrored once the table is laid out, if it is right to left. var columnX = [x] for width in widths { columnX.append(columnX[columnX.count - 1] + width) } + let shownColumnX = direction == .rightToLeft ? columnX.reversed().map { blockWidth - $0 } : columnX var lines = SharedList() var rowY: [CGFloat] = [0] var cellLines: [[Range]] = [] var firstRow = 0 - if kept > 0, let old, let previous, old.columnX == columnX { + if kept > 0, let old, let previous, old.columnX == shownColumnX { // Same columns: the kept rows look exactly as before. lines = previous.lines.prefix(old.cellLines[kept - 1].last?.upperBound ?? 0) rowY = Array(old.rowY[...kept]) @@ -472,6 +512,7 @@ final class BlockLayout: @unchecked Sendable { case .center: offset = (slack / 2).rounded() case .trailing: offset = slack } + let lineX = place(columnX[column] + padding + offset, width: metrics.width, in: blockWidth, direction: direction) var decorations: LineDecorations? if let decorated { // A tag at the start of a cell gets no room on its left: it @@ -479,13 +520,13 @@ final class BlockLayout: @unchecked Sendable { decorations = LineDecorations.make(line: ctLine, range: range, indexBase: cell.range.lowerBound, visibleWidth: metrics.width, top: -metrics.ascent, bottom: metrics.height - metrics.ascent, - lineX: columnX[column] + padding + offset, blockWidth: blockWidth, + lineX: lineX, blockWidth: blockWidth, block: block.id, tags: decorated, text: cell.text, textBase: cell.range.lowerBound) } lines.append(Line( ctLine: ctLine, indexBase: cell.range.lowerBound, range: range, - frame: CGRect(x: columnX[column] + padding + offset, y: y, width: metrics.width, height: metrics.height), + frame: CGRect(x: lineX, y: y, width: metrics.width, height: metrics.height), baseline: y + metrics.ascent, decorations: decorations )) @@ -509,13 +550,14 @@ final class BlockLayout: @unchecked Sendable { rowY.append(ceil(bottom)) cellLines.append(rowLines) } - let table = Table(columnX: columnX, rowY: rowY, cellLines: cellLines, naturalWidths: rowNaturals, minimumWidths: rowMinimums) + let table = Table(columnX: shownColumnX, rowY: rowY, cellLines: cellLines, naturalWidths: rowNaturals, minimumWidths: rowMinimums) return (lines, rowY[rowY.count - 1], table) } // MARK: Markers and images - private static func makeMarker(for block: TranscriptBlock, style: TranscriptStyle, firstLine: Line?) -> Marker? { + private static func makeMarker(for block: TranscriptBlock, style: TranscriptStyle, firstLine: Line?, width: CGFloat, + rightToLeft: Bool) -> Marker? { guard let kind = block.marker, let firstLine, let item = block.containers.lastIndex(of: .listItem) else { return nil } // The marker sits in the gutter of the innermost list item. let gutterEnd = style.contentLeading(for: Array(block.containers[...item])) @@ -524,7 +566,8 @@ final class BlockLayout: @unchecked Sendable { case .task(let checked): let side = (style.effectiveBodySize * 0.82).rounded() let middle = firstLine.baseline - CTFontGetCapHeight(font) / 2 - return .checkbox(CGRect(x: gutterEnd - side - 6, y: (middle - side / 2).rounded(), width: side, height: side), checked: checked) + let x = rightToLeft ? width - gutterEnd + 6 : gutterEnd - side - 6 + return .checkbox(CGRect(x: x, y: (middle - side / 2).rounded(), width: side, height: side), checked: checked) case .bullet, .number: let text: String if case .number(let number) = kind { @@ -533,9 +576,13 @@ final class BlockLayout: @unchecked Sendable { let depth = block.listLevel text = depth <= 1 ? "•" : (depth == 2 ? "◦" : "▪") } - let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: style.attributes(for: .paragraph))) + var attributes = style.attributes(for: .paragraph) + // So that a number's period is on the side of the text: ".1". + if rightToLeft { attributes[TranscriptStyle.paragraphStyleKey] = WritingDirection.rightToLeft.paragraphStyle } + let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: attributes)) let markerWidth = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) - return .text(line, origin: CGPoint(x: max(gutterEnd - markerWidth - 7, 0), y: firstLine.baseline)) + let x = rightToLeft ? min(width - gutterEnd + 7, width - markerWidth) : max(gutterEnd - markerWidth - 7, 0) + return .text(line, origin: CGPoint(x: x, y: firstLine.baseline)) } } @@ -584,7 +631,9 @@ final class BlockLayout: @unchecked Sendable { // The cell under the point, or the nearest one. let row = min(max((table.rowY.lastIndex { $0 <= point.y } ?? 0), 0), table.cellLines.count - 1) guard row >= 0, !table.cellLines[row].isEmpty else { return 0 } - let column = min(max((table.columnX.lastIndex { $0 <= point.x } ?? 0), 0), table.cellLines[row].count - 1) + var column = table.columnX.lastIndex { $0 <= point.x } ?? 0 + if isRightToLeft { column = table.columnX.count - 2 - column } + column = min(max(column, 0), table.cellLines[row].count - 1) return closestOffset(to: point, amongLines: table.cellLines[row][column]) } diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index 73f623e..ab92958 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -165,6 +165,27 @@ public final class DocumentLayout: @unchecked Sendable { a.containers.count > index && b.containers.count > index && a.containers[...index] == b.containers[...index] } + /// The quote bars drawn beside the block at `index`, one for each quote + /// it is in: on the left, or on the right of right-to-left text. A bar + /// runs on through the gap from the block above when that block is in + /// the same quote. + func quoteBars(at index: Int) -> [CGRect] { + let entry = entry(at: index) + let layout = entry.layout + let above = index > 0 ? self.entry(at: index - 1) : nil + var bars: [CGRect] = [] + var x: CGFloat = 0 + for (depth, container) in layout.block.containers.enumerated() { + if container == .quote { + var top = entry.y + if let above, Self.shareQuote(above.layout.block, layout.block, at: depth) { top = above.frame.maxY } + bars.append(CGRect(x: layout.isRightToLeft ? layout.width - x - 3 : x, y: top, width: 3, height: entry.frame.maxY - top)) + } + x += style.width(of: container) + } + return bars + } + // MARK: Offsets and geometry /// The last entry whose `key` is at most `value`, by binary search; @@ -296,6 +317,8 @@ public final class DocumentLayout: @unchecked Sendable { index += 1 continue } + // The marker and the quote bars, which reach into the gap, moved to the other side. + if new.layout.isRightToLeft != old.layout.isRightToLeft { return min(gapAbove(index, in: self), gapAbove(index, in: earlier)) } if new.layout.table != nil || old.layout.table != nil { return new.y + Self.firstChangedY(in: new.layout, since: old.layout) } @@ -471,19 +494,8 @@ public final class DocumentLayout: @unchecked Sendable { let layout = entry.layout let block = layout.block - // Quote bars, run on through the gap from the block above when it - // is in the same quote. - let above = index > 0 ? self.entry(at: index - 1) : nil - var x: CGFloat = 0 - for (depth, container) in block.containers.enumerated() { - if container == .quote { - var top = frame.minY - if let above, Self.shareQuote(above.layout.block, block, at: depth) { top = above.frame.maxY } - // Square ends, so that segments of one bar meet cleanly. - fill(CGRect(x: x, y: top, width: 3, height: frame.maxY - top), radius: 0, color: accent) - } - x += style.width(of: container) - } + // Square ends, so that segments of one bar meet cleanly. + for bar in quoteBars(at: index) { fill(bar, radius: 0, color: accent) } if frame.minY - overhang > dirtyRect.maxY { break } let box = CGRect(x: layout.contentLeading, y: frame.minY, width: max(frame.width - layout.contentLeading, 0), height: frame.height) diff --git a/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift b/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift new file mode 100644 index 0000000..ad3f605 --- /dev/null +++ b/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift @@ -0,0 +1,156 @@ +import CoreGraphics +import CoreText +import Foundation +import Testing +@testable import TranscriptKit + +private let hebrew = String(repeating: "שלום עולם, זה משפט ארוך בעברית. ", count: 5) +private let arabic = "مرحبا بالعالم" + +private func layout(_ markdown: String, width: CGFloat = 300, style: TranscriptStyle = .init()) -> DocumentLayout { + DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: width, style: style) +} + +/// Each line's text range and frame, for comparing two layouts. +private func lineSummary(_ layout: BlockLayout) -> [String] { + layout.lines.map { "\($0.range) \($0.frame) \($0.baseline)" } +} + +// MARK: Lines + +@Test func rightToLeftParagraphLinesEndAtTheRightEdge() { + let block = layout(hebrew).entry(at: 0).layout + #expect(block.isRightToLeft) + #expect(block.lines.count > 2) + for line in block.lines { + #expect(abs(line.frame.maxX - 300) < 0.01) + // The first character of the line is at its right end. + #expect(abs(block.caretRect(atOffset: line.range.lowerBound).midX - line.frame.maxX) < 1) + } +} + +@Test func leftToRightTextGetsNoDirection() { + let block = layout("Plain text that wraps onto more than one line of the layout, with digits 123.").entry(at: 0).layout + #expect(block.paragraphDirection == nil) + #expect(!block.isRightToLeft) + #expect(block.lines.allSatisfy { $0.frame.minX == 0 }) + let text = TranscriptStyle().attributedString(for: block.block) + #expect(text.attribute(TranscriptStyle.paragraphStyleKey, at: 0, effectiveRange: nil) == nil) +} + +@Test func eachParagraphHasItsOwnDirection() { + let document = layout("Hello world\n\n\(arabic)\n\nThe word \(arabic) in English") + #expect((0..<3).map { document.entry(at: $0).layout.isRightToLeft } == [false, true, false]) + #expect(document.entry(at: 2).layout.paragraphDirection == .leftToRight) + #expect(document.entry(at: 2).layout.lines[0].frame.minX == 0) +} + +@Test func alignmentIsFromTheLeadingEdgeOfTheParagraph() { + var style = TranscriptStyle() + style.textAlignment = .trailing + let trailing = layout(arabic, style: style).entry(at: 0).layout.lines[0] + #expect(trailing.frame.minX == 0) + style.textAlignment = .center + let centered = layout(arabic, style: style).entry(at: 0).layout.lines[0] + #expect(abs((300 - centered.frame.maxX) - centered.frame.minX) <= 1) +} + +@Test func codeStaysLeftToRight() { + let block = layout("```\nlet name = \"\(arabic)\"\n```").entry(at: 0).layout + #expect(block.paragraphDirection == .leftToRight) + #expect(!block.isRightToLeft) + #expect(block.lines[0].frame.minX == TranscriptStyle().codePadding) +} + +@Test func truncatedRightToLeftLineKeepsItsWidth() { + var style = TranscriptStyle() + style.lineLimit = 1 + let line = layout(hebrew, style: style).entry(at: 0).layout.lines[0] + #expect(abs(line.frame.maxX - 300) < 0.01) + #expect(line.frame.width > 250) +} + +// MARK: Lists and quotes + +@Test func listMarkersAndQuoteBarsGoOnTheRight() { + let style = TranscriptStyle() + let document = layout("- \(arabic)\n- [ ] \(arabic)\n\n> \(arabic)\n\n1. \(arabic)") + let bullet = document.entry(at: 0).layout + guard case .text(_, let origin)? = bullet.marker else { Issue.record("no bullet"); return } + #expect(bullet.lines[0].frame.maxX == 300 - style.listIndent) + #expect(origin.x > bullet.lines[0].frame.maxX) + #expect(origin.x < 300) + + guard case .checkbox(let box, _)? = document.entry(at: 1).layout.marker else { Issue.record("no checkbox"); return } + #expect(box.minX > document.entry(at: 1).layout.lines[0].frame.maxX) + #expect(box.maxX <= 300) + + let quote = document.entry(at: 2).layout + #expect(quote.lines[0].frame.maxX == 300 - style.quoteIndent) + #expect(document.quoteBars(at: 2).map(\.minX) == [297]) + + // The number's period is on the side of the text. + guard case .text(let number, _)? = document.entry(at: 3).layout.marker else { Issue.record("no number"); return } + let runs = CTLineGetGlyphRuns(number) as! [CTRun] + #expect(CTRunGetStringRange(runs[0]).location == 1) +} + +@Test func leftToRightQuoteBarsStayOnTheLeft() { + let document = layout("> quoted\n>\n> > nested") + #expect(document.quoteBars(at: 0).map(\.minX) == [0]) + #expect(document.quoteBars(at: 1).map(\.minX) == [0, TranscriptStyle().quoteIndent]) +} + +// MARK: Tables + +@Test func rightToLeftTableStartsOnTheRight() { + let document = layout("| \(arabic) | ب |\n|---|---|\n| א | ב |") + let block = document.entry(at: 0).layout + #expect(block.isRightToLeft) + guard let table = block.table else { Issue.record("no table"); return } + #expect(table.columnX == table.columnX.sorted()) + #expect(table.columnX.last == 300) + let first = block.lines[table.cellLines[0][0].lowerBound] + let second = block.lines[table.cellLines[0][1].lowerBound] + #expect(first.frame.minX > second.frame.minX) + // A point in the right column hits the first cell. + let offset = block.closestOffset(to: CGPoint(x: first.frame.midX, y: first.frame.midY)) + #expect(first.range.contains(offset) || offset == first.range.upperBound) + #expect(table.minimumWidths[0].allSatisfy { $0 > TranscriptStyle().tableCellPadding * 2 }) +} + +// MARK: Streaming + +private func streamed(_ markdown: String, chunk: Int, width: CGFloat = 300) -> (grown: DocumentLayout, fresh: DocumentLayout) { + var parser = MarkdownStreamParser(idPrefix: "s") + var layout: DocumentLayout? + var text = Substring(markdown) + while !text.isEmpty { + parser.append(String(text.prefix(chunk))) + text = text.dropFirst(chunk) + layout = DocumentLayout(document: parser.document, width: width, reusing: layout) + } + return (layout!, DocumentLayout(document: parser.document, width: width)) +} + +@Test(arguments: [hebrew, "2024: " + hebrew, "Some English first, then " + hebrew, "- " + hebrew, "> 12 " + hebrew]) +func streamedRightToLeftTextIsLaidOutAsAWhole(markdown: String) { + let (grown, fresh) = streamed(markdown, chunk: 7) + #expect(grown.entryCount == fresh.entryCount) + for index in 0.. 12 ") + let second = MarkdownStreamParser.document(from: "Intro\n\n> 12 \(arabic)") + let earlier = DocumentLayout(document: first, width: 300) + let later = DocumentLayout(document: second, width: 300, reusing: earlier) + #expect(!earlier.entry(at: 1).layout.isRightToLeft) + #expect(later.entry(at: 1).layout.isRightToLeft) + #expect(later.changes(since: earlier).top <= earlier.entry(at: 0).frame.maxY) +} From 25a42d174c01335ae4eed3c556b40a603e812807 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:38:59 -0800 Subject: [PATCH 03/14] Select and hit-test right-to-left text by its glyph runs A line with right-to-left text gets one selection rect for each stretch of glyphs that go the same way. Thus a selection in text of mixed direction can have several rects on one line. Each part records its direction and if it holds the start or the end of the selection. A link tap in a right-to-left run finds the character under the point from the glyphs. Lines that are all left to right keep the code that they used before. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/BlockLayout.swift | 119 +++++++++++++++++- .../TranscriptKit/Layout/DocumentLayout.swift | 35 +++++- .../TranscriptKit/Layout/FadeRenderer.swift | 6 +- .../RightToLeftSelectionTests.swift | 96 ++++++++++++++ 4 files changed, 241 insertions(+), 15 deletions(-) create mode 100644 Tests/TranscriptKitTests/RightToLeftSelectionTests.swift diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index 7f42ddc..a00aac7 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -22,6 +22,11 @@ final class BlockLayout: @unchecked Sendable { /// The top of what is drawn for the line, its tags' shapes included. var inkTop: CGFloat { frame.minY - (decorations?.inkAbove ?? 0) } + + /// Whether Core Text drew some of the line's text right to left. + var hasRightToLeftRuns: Bool { + (CTLineGetGlyphRuns(ctLine) as! [CTRun]).contains { CTRunGetStatus($0).contains(.rightToLeft) } + } } /// What marks a list item, drawn in the gutter of its first line. @@ -659,6 +664,11 @@ final class BlockLayout: @unchecked Sendable { guard let line = lines.first(where: { $0.frame.minY <= point.y && point.y < $0.frame.maxY && point.x >= $0.frame.minX && point.x < $0.frame.maxX }), !line.range.isEmpty else { return nil } + if line.hasRightToLeftRuns { + let x = point.x - line.frame.minX + guard let glyph = glyphs(of: line).first(where: { $0.minX <= x && x < $0.maxX }) else { return nil } + return line.range.contains(glyph.character) ? glyph.character : nil + } let localBoundary = CTLineGetStringIndexForPosition(line.ctLine, CGPoint(x: point.x - line.frame.minX, y: 0)) guard localBoundary != kCFNotFound else { return nil } let boundary = localBoundary + line.indexBase @@ -679,21 +689,120 @@ final class BlockLayout: @unchecked Sendable { return nil } - /// One rect per line touched by `range`. Left-to-right only for now. + /// A part of a selection on one line: the glyphs of one or more runs + /// next to each other that go the same way. + struct SelectionSegment: Equatable { + var rect: CGRect + var isRightToLeft: Bool + /// The first and the last of its selected characters, in block offsets. + var characters: ClosedRange + /// Whether it holds the first selected character, where the start + /// handle goes, and the last one, where the end handle goes. + var containsStart = false + var containsEnd = false + } + + /// One rect per line touched by `range`, in lines that are all left to + /// right. A line with right-to-left text gets one rect for each stretch + /// of glyphs that go the same way, from left to right, so a selection in + /// text of mixed direction can have several rects on a line. func selectionRects(for range: Range) -> [CGRect] { + selectionSegments(for: range).map(\.rect) + } + + func selectionSegments(for range: Range) -> [SelectionSegment] { guard !range.isEmpty else { return [] } - var rects: [CGRect] = [] + var segments: [SelectionSegment] = [] let first = lineIndex(forOffset: range.lowerBound) for index in first..= range.upperBound { break } - let startX = x(forOffset: max(range.lowerBound, line.range.lowerBound), in: line) let continuesPastLine = range.upperBound >= line.range.upperBound && index < lines.count - 1 + let lower = max(range.lowerBound, line.range.lowerBound) + if isRightToLeft || line.hasRightToLeftRuns { + segments += runSegments(of: line, selecting: range, continuesPastLine: continuesPastLine) + continue + } + let startX = x(forOffset: lower, in: line) let endX = continuesPastLine ? max(line.frame.maxX, startX) : x(forOffset: range.upperBound, in: line) if endX > startX || continuesPastLine { - rects.append(CGRect(x: startX, y: line.frame.minY, width: max(endX - startX, 4), height: line.frame.height)) + let last = max(min(range.upperBound, line.range.upperBound) - 1, lower) + segments.append(SelectionSegment( + rect: CGRect(x: startX, y: line.frame.minY, width: max(endX - startX, 4), height: line.frame.height), + isRightToLeft: false, characters: lower...last)) + } + } + if let start = segments.indices.min(by: { segments[$0].characters.lowerBound < segments[$1].characters.lowerBound }) { + segments[start].containsStart = true + } + if let last = segments.map(\.characters.upperBound).max(), + let end = segments.indices.last(where: { segments[$0].characters.upperBound == last }) { + segments[end].containsEnd = true + } + return segments + } + + /// The selected glyphs of a line, as rects of the runs they are in. + /// Whitespace at the end of a line, which Core Text puts outside the + /// line box, is left out. + private func runSegments(of line: Line, selecting range: Range, continuesPastLine: Bool) -> [SelectionSegment] { + var segments: [SelectionSegment] = [] + var current: (run: Int, minX: CGFloat, maxX: CGFloat, characters: ClosedRange, rightToLeft: Bool)? + func flush() { + guard let part = current else { return } + current = nil + let rect = CGRect(x: line.frame.minX + part.minX, y: line.frame.minY, width: part.maxX - part.minX, height: line.frame.height) + if let last = segments.last, last.isRightToLeft == part.rightToLeft, abs(last.rect.maxX - rect.minX) < 0.5 { + segments[segments.count - 1].rect = last.rect.union(rect) + segments[segments.count - 1].characters = min(last.characters.lowerBound, part.characters.lowerBound) + ... max(last.characters.upperBound, part.characters.upperBound) + } else { + segments.append(SelectionSegment(rect: rect, isRightToLeft: part.rightToLeft, characters: part.characters)) + } + } + for glyph in glyphs(of: line) where range.contains(glyph.character) && line.range.contains(glyph.character) { + let minX = max(glyph.minX, 0) + let maxX = min(glyph.maxX, line.frame.width) + guard maxX > minX else { continue } + if let part = current, part.run == glyph.run { + current = (part.run, min(part.minX, minX), max(part.maxX, maxX), + min(part.characters.lowerBound, glyph.character)...max(part.characters.upperBound, glyph.character), + part.rightToLeft) + } else { + flush() + current = (glyph.run, minX, maxX, glyph.character...glyph.character, glyph.rightToLeft) } } - return rects + flush() + if segments.isEmpty, continuesPastLine { + // Only a line break or spaces: a sliver at the caret shows that they are selected. + let lower = max(range.lowerBound, line.range.lowerBound) + let x = x(forOffset: lower, in: line) + segments.append(SelectionSegment(rect: CGRect(x: isRightToLeft ? x - 4 : x, y: line.frame.minY, width: 4, height: line.frame.height), + isRightToLeft: isRightToLeft, characters: lower...lower)) + } + return segments + } + + /// The glyphs of a line from left to right, with the character each + /// stands for (a block offset) and its left and right edges in the line. + private func glyphs(of line: Line) -> [(character: Int, minX: CGFloat, maxX: CGFloat, rightToLeft: Bool, run: Int)] { + var result: [(character: Int, minX: CGFloat, maxX: CGFloat, rightToLeft: Bool, run: Int)] = [] + for (runIndex, run) in (CTLineGetGlyphRuns(line.ctLine) as! [CTRun]).enumerated() { + let count = CTRunGetGlyphCount(run) + guard count > 0 else { continue } + var indices = [CFIndex](repeating: 0, count: count) + var positions = [CGPoint](repeating: .zero, count: count) + var advances = [CGSize](repeating: .zero, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: 0), &indices) + CTRunGetPositions(run, CFRange(location: 0, length: 0), &positions) + CTRunGetAdvances(run, CFRange(location: 0, length: 0), &advances) + let rightToLeft = CTRunGetStatus(run).contains(.rightToLeft) + for glyph in 0..) -> [CGRect] { + selectionSegments(for: range).map(\.rect) + } + + /// The parts of the selection of `range`, line by line, with their + /// direction. One holds the start of the range, and one the end. + func selectionSegments(for range: Range) -> [BlockLayout.SelectionSegment] { guard !range.isEmpty, let first = entryIndex(forOffset: range.lowerBound) else { return [] } - var rects: [CGRect] = [] + var segments: [BlockLayout.SelectionSegment] = [] + var start: Int? + var end: Int? for index in first..= range.upperBound { break } let lower = max(range.lowerBound - entry.start, 0) let upper = min(range.upperBound - entry.start, entry.layout.length) guard lower < upper else { continue } - for rect in entry.layout.selectionRects(for: lower.. Bool { + guard let index = entryIndex(forOffset: backward ? max(offset - 1, 0) : offset) else { return false } + return entry(at: index).layout.isRightToLeft } /// The top of the first line that differs between `earlier` and this diff --git a/Sources/TranscriptKit/Layout/FadeRenderer.swift b/Sources/TranscriptKit/Layout/FadeRenderer.swift index a77c58d..c9354c3 100644 --- a/Sources/TranscriptKit/Layout/FadeRenderer.swift +++ b/Sources/TranscriptKit/Layout/FadeRenderer.swift @@ -82,7 +82,7 @@ final class FadeRenderer { func pixel(_ value: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { (value * scale).rounded(rule) / scale } let lines = layout.lines(from: from) - let rightToLeft = lines.map { Self.hasRightToLeftText($0.line.ctLine) } + let rightToLeft = lines.map { $0.line.hasRightToLeftRuns } let definitions = layout.document.linkDefinitions.count var pieces: [FadeFrame.Piece] = [] for fade in fades { @@ -156,8 +156,4 @@ final class FadeRenderer { in: context, text: colors.text, dark: colors.dark) return context.makeImage() } - - private static func hasRightToLeftText(_ line: CTLine) -> Bool { - (CTLineGetGlyphRuns(line) as! [CTRun]).contains { CTRunGetStatus($0).contains(.rightToLeft) } - } } diff --git a/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift b/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift new file mode 100644 index 0000000..1c3ad85 --- /dev/null +++ b/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift @@ -0,0 +1,96 @@ +import CoreGraphics +import Foundation +import Testing +@testable import TranscriptKit + +private let hebrew = String(repeating: "שלום עולם, זה משפט ארוך בעברית. ", count: 5) + +private func layout(_ markdown: String, width: CGFloat = 300) -> DocumentLayout { + DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: width) +} + +// MARK: Selection and hit testing + +@Test func directionIsFoundByOffset() { + let document = layout("Hello world\n\nمرحبا بالعالم") + let start = document.entry(at: 1).start + #expect(document.isRightToLeft(at: start)) + #expect(!document.isRightToLeft(at: start, backward: true)) + #expect(document.isRightToLeft(at: start + 1, backward: true)) + #expect(!document.isRightToLeft(at: 0)) +} + +@Test func caretsHitTestBackInRightToLeftText() { + let document = layout(hebrew) + for offset in stride(from: 0, to: document.length, by: 5) { + let rect = document.caretRect(at: offset) + let hit = document.closestOffset(to: CGPoint(x: rect.midX, y: rect.midY)) + #expect(abs(hit - offset) <= 1, "offset \(offset) hit-tested to \(hit)") + } + // Right of a line is its start; left of it is its end. + let line = document.entry(at: 0).layout.lines[0] + #expect(document.closestOffset(to: CGPoint(x: 299, y: line.frame.midY)) == 0) + #expect(document.closestOffset(to: CGPoint(x: 1, y: line.frame.midY)) == line.range.upperBound - 1) +} + +@Test func rightToLeftSelectionStartsOnTheRight() { + let document = layout(hebrew) + let line = document.entry(at: 0).layout.lines[0] + let segments = document.selectionSegments(for: 0..<4) + #expect(segments.count == 1) + #expect(segments[0].isRightToLeft) + #expect(abs(segments[0].rect.maxX - line.frame.maxX) < 0.5) + #expect(segments[0].containsStart && segments[0].containsEnd) + + let all = document.selectionSegments(for: 0..= line.frame.minX && $0.rect.maxX <= line.frame.maxX + 0.5 }) + // The first Hebrew word is drawn at the right of the Hebrew, so the + // second word lies between the two rects. + #expect(abs(segments[1].rect.minX - document.caretRect(at: 8).midX) < 1) + #expect(segments[1].rect.minX - segments[0].rect.maxX > 10) + #expect(segments[0].containsStart && segments[1].containsEnd) + #expect(document.selectionRects(for: range) == segments.map(\.rect)) +} + +@Test func leftToRightSelectionIsOneRectPerLine() { + let document = layout(String(repeating: "The quick brown fox jumps over the lazy dog. ", count: 4)) + let segments = document.selectionSegments(for: 3.. Date: Mon, 23 Nov 2026 17:39:13 -0800 Subject: [PATCH 04/14] Report the writing direction of the text through UITextInput - baseWritingDirection(for:in:) gives the direction of the paragraph at the position. - Each selection rect gives the direction of its glyphs. The start and end flags go to the rects that hold the first and the last selected character. - firstRect(for:) is the union of the rects on the first line. - In a right-to-left paragraph, left and right are swapped for caret moves and for ranges that extend a position. Co-Authored-By: Claude Opus 5.5 --- .../iOS/TranscriptTextView.swift | 36 +++++++++++++------ 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index fdb641f..bf20d30 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -1345,9 +1345,20 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD return TranscriptTextPosition(offset: target) } + /// `.left` and `.right` swapped in a right-to-left paragraph, where the + /// text goes on to the left: then `.right` goes back in the text. + private func textDirection(_ direction: UITextLayoutDirection, at offset: Int) -> UITextLayoutDirection { + guard currentLayout.isRightToLeft(at: offset) else { return direction } + switch direction { + case .left: return .right + case .right: return .left + default: return direction + } + } + public func position(from position: UITextPosition, in direction: UITextLayoutDirection, offset: Int) -> UITextPosition? { let start = self.offset(of: position) - switch direction { + switch textDirection(direction, at: start) { case .left: return TranscriptTextPosition(offset: clamp(start - offset)) case .right: return TranscriptTextPosition(offset: clamp(start + offset)) case .up, .down: @@ -1371,7 +1382,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public func position(within range: UITextRange, farthestIn direction: UITextLayoutDirection) -> UITextPosition? { let range = self.range(of: range) - switch direction { + switch textDirection(direction, at: range.lowerBound) { case .left, .up: return TranscriptTextPosition(offset: range.lowerBound) case .right, .down: return TranscriptTextPosition(offset: range.upperBound) @unknown default: return nil @@ -1380,7 +1391,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public func characterRange(byExtending position: UITextPosition, in direction: UITextLayoutDirection) -> UITextRange? { let start = offset(of: position) - switch direction { + switch textDirection(direction, at: start) { case .left, .up: return TranscriptTextRange(range: clamp(start - 1).. CGRect { let range = self.range(of: range) - return currentLayout.selectionRects(for: range).first ?? currentLayout.caretRect(at: range.lowerBound) + let segments = currentLayout.selectionSegments(for: range) + guard let first = segments.first else { return currentLayout.caretRect(at: range.lowerBound) } + // All of the first line, which text of mixed direction splits into several rects. + return segments.prefix { $0.rect.minY == first.rect.minY }.reduce(first.rect) { $0.union($1.rect) } } public func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { - let rects = currentLayout.selectionRects(for: self.range(of: range)) - return rects.enumerated().map { index, rect in - TranscriptSelectionRect(rect: rect, containsStart: index == 0, containsEnd: index == rects.count - 1) + currentLayout.selectionSegments(for: self.range(of: range)).map { segment in + TranscriptSelectionRect(rect: segment.rect, writingDirection: segment.isRightToLeft ? .rightToLeft : .leftToRight, + containsStart: segment.containsStart, containsEnd: segment.containsEnd) } } @@ -1436,7 +1450,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } public func baseWritingDirection(for position: UITextPosition, in direction: UITextStorageDirection) -> NSWritingDirection { - .leftToRight + currentLayout.isRightToLeft(at: clamp(offset(of: position)), backward: direction == .backward) ? .rightToLeft : .leftToRight } public func setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {} @@ -1509,18 +1523,20 @@ final class TranscriptTextRange: UITextRange { final class TranscriptSelectionRect: UITextSelectionRect { private let storedRect: CGRect + private let storedWritingDirection: NSWritingDirection private let storedContainsStart: Bool private let storedContainsEnd: Bool - init(rect: CGRect, containsStart: Bool, containsEnd: Bool) { + init(rect: CGRect, writingDirection: NSWritingDirection, containsStart: Bool, containsEnd: Bool) { storedRect = rect + storedWritingDirection = writingDirection storedContainsStart = containsStart storedContainsEnd = containsEnd super.init() } override var rect: CGRect { storedRect } - override var writingDirection: NSWritingDirection { .leftToRight } + override var writingDirection: NSWritingDirection { storedWritingDirection } override var containsStart: Bool { storedContainsStart } override var containsEnd: Bool { storedContainsEnd } override var isVertical: Bool { false } From b0696658d48b57ef385e9e2e9225254339e52d84 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:39:31 -0800 Subject: [PATCH 05/14] Document right-to-left text The README tells how a block gets its direction, and what moves to the right in a right-to-left block. The doc comments of the text alignment, the list indent and the quote indent tell about the right side. Co-Authored-By: Claude Opus 5.5 --- README.md | 15 +++++++++++++++ .../TranscriptKit/Layout/TranscriptStyle.swift | 9 ++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 15e4433..cc2335e 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ text streaming in at hundreds of characters a second doesn't make scrolling stut marker) are built in, and you can draw shapes of your own, and animate a tag's letters and shapes when it finishes arriving. - **Fade-in.** Optionally, text fades in as it streams in. Core Animation plays the fades. +- **Right-to-left text.** Paragraphs in Arabic, Hebrew and other right-to-left scripts start at the right edge, and + selection follows the glyphs in text of mixed direction. - **SwiftUI and UIKit.** `TranscriptText` for SwiftUI, `TranscriptTextView` for UIKit. ## Requirements @@ -291,6 +293,19 @@ TranscriptText(document) 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. +### Right-to-left text + +Each block takes its direction from its first strong character, such as a letter. Digits, punctuation and spaces do +not count. So a paragraph that starts with a word in Arabic or Hebrew is right to left, and a paragraph that starts with +an English word is left to right, also when it holds words in other scripts. + +In a right-to-left block, the leading edge is on the right. Lines start there, and `textAlignment` counts from there: +`.trailing` puts the lines at the left. The indents of lists and quotes, list markers and quote bars are on the right, +and a table puts its first column on the right. Code blocks are always left to right. + +A selection follows the glyphs. In text of mixed direction, one line can have several selection rects, and the +handles go to the ends of the selected text. Copy gives the text in the order it was written. + ### Styling `TranscriptStyle` sets the body size, line, block and list spacing, indents, padding and the maximum image height. diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index e6bc265..08f0131 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -32,9 +32,11 @@ public struct TranscriptStyle: Equatable, Sendable { /// Spacing above a list item that follows other list content. public var listItemSpacing: CGFloat = 6 public var codePadding: CGFloat = 12 - /// Indent added by each list item; the marker sits inside it. + /// Indent added by each list item; the marker sits inside it, on the + /// right of right-to-left text. public var listIndent: CGFloat = 24 - /// Indent added by each block quote; its bar sits at the left of it. + /// Indent added by each block quote; its bar sits at the left of it, or + /// at the right of right-to-left text. public var quoteIndent: CGFloat = 14 /// Space between a table cell's border and its text. public var tableCellPadding: CGFloat = 8 @@ -59,7 +61,8 @@ public struct TranscriptStyle: Equatable, Sendable { /// 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. + /// quotes, code and tables stay at the leading edge. The leading edge is + /// the left edge, or the right edge of a right-to-left paragraph. public var textAlignment: TranscriptTextAlignment = .leading struct Insets { From 12c7eedf758f968c2965ed76888c909b69c4d8c0 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:47:46 -0800 Subject: [PATCH 06/14] Typeset each table cell in the direction of its own text A table cell is typeset on its own, as before. Core Text gives it the direction of its own text, so an Arabic cell in an English table keeps its punctuation in the correct place. The direction of the table sets only the order and the side of the columns. A test streams a right-to-left table, so the rows that it keeps use the mirrored columns. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Layout/BlockLayout.swift | 4 +++- .../RightToLeftLayoutTests.swift | 14 +++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index a00aac7..beffc8b 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -406,10 +406,12 @@ final class BlockLayout: @unchecked Sendable { } typealias Cell = (text: NSAttributedString, typesetter: CTTypesetter, range: Range) + // Each cell is typeset on its own, so Core Text gives it the direction + // of its own text. The table's direction sets the order of the columns. func makeCells(_ row: Int) -> [Cell] { model.rows[row].prefix(columns).map { range in let text = style.attributedString(for: block, range: range, extraTraits: row == 0 ? .bold : [], images: sizing, - definitions: definitions, kerns: decorated?.kerns ?? [:], direction: direction) + definitions: definitions, kerns: decorated?.kerns ?? [:]) return (text, CTTypesetterCreateWithAttributedString(text), range) } } diff --git a/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift b/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift index ad3f605..88918ee 100644 --- a/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift +++ b/Tests/TranscriptKitTests/RightToLeftLayoutTests.swift @@ -119,6 +119,16 @@ private func lineSummary(_ layout: BlockLayout) -> [String] { #expect(table.minimumWidths[0].allSatisfy { $0 > TranscriptStyle().tableCellPadding * 2 }) } +@Test func eachTableCellKeepsTheDirectionOfItsOwnText() { + let block = layout("| Word | Meaning |\n|---|---|\n| \(arabic)! | hello |").entry(at: 0).layout + #expect(!block.isRightToLeft) + guard let table = block.table else { Issue.record("no table"); return } + // In right-to-left text, the "!" at the end is drawn at the left. + let cell = block.lines[table.cellLines[1][0].lowerBound] + let runs = CTLineGetGlyphRuns(cell.ctLine) as! [CTRun] + #expect(CTRunGetStringRange(runs[0]).location == (arabic as NSString).length) +} + // MARK: Streaming private func streamed(_ markdown: String, chunk: Int, width: CGFloat = 300) -> (grown: DocumentLayout, fresh: DocumentLayout) { @@ -133,7 +143,9 @@ private func streamed(_ markdown: String, chunk: Int, width: CGFloat = 300) -> ( return (layout!, DocumentLayout(document: parser.document, width: width)) } -@Test(arguments: [hebrew, "2024: " + hebrew, "Some English first, then " + hebrew, "- " + hebrew, "> 12 " + hebrew]) +private let hebrewTable = "| מילה | פירוש |\n|---|---|\n" + (1...8).map { "| שורה \($0) | \(String(repeating: "מילה ", count: $0)) |" }.joined(separator: "\n") + +@Test(arguments: [hebrew, "2024: " + hebrew, "Some English first, then " + hebrew, "- " + hebrew, "> 12 " + hebrew, hebrewTable]) func streamedRightToLeftTextIsLaidOutAsAWhole(markdown: String) { let (grown, fresh) = streamed(markdown, chunk: 7) #expect(grown.entryCount == fresh.entryCount) From a951825f551600dc27646fd45957b86c853424e5 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:47:46 -0800 Subject: [PATCH 07/14] Test the streamed tail and the fades with right-to-left text The tail frames and the fade pieces must give the same pixels as a drawing from scratch. The text has right-to-left paragraphs, a list, a table, and a quote that turns right to left when its first letter arrives. Co-Authored-By: Claude Opus 5.5 --- Tests/TranscriptKitTests/FadeTests.swift | 31 +++++++++++++++ .../TailRendererTests.swift | 39 +++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/Tests/TranscriptKitTests/FadeTests.swift b/Tests/TranscriptKitTests/FadeTests.swift index 2a8b437..49ec773 100644 --- a/Tests/TranscriptKitTests/FadeTests.swift +++ b/Tests/TranscriptKitTests/FadeTests.swift @@ -187,6 +187,37 @@ func fadePiecesAndTheDrawingMakeUpTheText(chunk: Int, centered: Bool) { #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") } +/// Fades in right-to-left text, and in a block that turns right to left +/// when its first letter arrives, make up the text as it is drawn. +@Test(arguments: [3, 8]) +func fadePiecesMakeUpRightToLeftText(chunk: Int) { + let markdown = """ + # כותרת בעברית + + שלום עולם, זה משפט ארוך בעברית עם **מילה מודגשת** שעובר לשורה הבאה ברוחב הזה. + + > 2024: ציטוט ארוך בעברית שעובר לשורה השנייה + + English, then עברית at the end of the line. + + """ + var checked = 0 + var mismatches: [String] = [] + var step = 0 + streamFades(markdown, chunk: chunk) { output in + step += 1 + guard step % 2 == 0 else { return } + let document = documentDifference(output, scale: 2) + let tail = tailDifference(output, scale: 2) ?? (0, 0) + if document.count + tail.count > 0, mismatches.count < 3 { + mismatches.append("step \(step), fading from \(output.hidden.fadingFrom.map(String.init) ?? "-"): document \(document), tail \(tail)") + } + checked += 1 + } + #expect(checked > 10) + #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") +} + @Test func theFrontierMovesALineAtATimeAndItsRowsAreDrawnAgain() { var froms: [Int?] = [] var redraws = 0 diff --git a/Tests/TranscriptKitTests/TailRendererTests.swift b/Tests/TranscriptKitTests/TailRendererTests.swift index b6a68af..050bdb9 100644 --- a/Tests/TranscriptKitTests/TailRendererTests.swift +++ b/Tests/TranscriptKitTests/TailRendererTests.swift @@ -214,6 +214,45 @@ func tailFramesMatchWithTablesAndContainers(chunk: Int) { #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") } +/// Right-to-left text, and a block that turns right to left when its first +/// letter arrives, stream into the tail as they draw from scratch. +@Test(arguments: [2, 7]) +func tailFramesMatchInRightToLeftText(chunk: Int) { + let markdown = """ + שלום עולם, זה משפט ארוך בעברית שעובר לשורה הבאה ברוחב הזה. + + > 2024: מרחבא בעולם, וזה ציטוט ארוך + + - פריט ראשון ברשימה + - [ ] משימה פתוחה + + | מילה | פירוש | + | --- | --- | + | אחת | ראשונה | + + English, then עברית at the end. + + """ + let scale: CGFloat = 2 + var checked = 0 + var mismatches: [String] = [] + var frameIndex = 0 + streamTail(markdown, chunk: chunk, scale: scale) { layout, frame in + frameIndex += 1 + let width = Int(((layout.width + 2 * TailRenderer.sideMargin) * scale).rounded()) + let height = Int((TailRenderer.height * scale).rounded()) + let actual = pixels(of: frame.surface, width: width, height: height) + let expected = expectedPixels(layout, top: frame.top, scale: scale) + let differing = zip(actual, expected).filter { abs(Int($0) - Int($1)) > 2 }.count + if differing > 0, mismatches.count < 3 { + mismatches.append("frame \(frameIndex), top \(frame.top): \(differing) bytes differ") + } + checked += 1 + } + #expect(checked > 10) + #expect(mismatches.isEmpty, "\(mismatches.joined(separator: "\n"))") +} + /// Rows already written keep their lines while a table streams, as long as /// the columns stay the same. @Test func streamingTableKeepsFinishedRows() throws { From 1d8ce50de33ffa3c6a7f3dfb86bfcfc82de037ad Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:47:46 -0800 Subject: [PATCH 08/14] Do not say in the README where the selection handles go No test shows it yet. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cc2335e..8b41bc4 100644 --- a/README.md +++ b/README.md @@ -303,8 +303,8 @@ In a right-to-left block, the leading edge is on the right. Lines start there, a `.trailing` puts the lines at the left. The indents of lists and quotes, list markers and quote bars are on the right, and a table puts its first column on the right. Code blocks are always left to right. -A selection follows the glyphs. In text of mixed direction, one line can have several selection rects, and the -handles go to the ends of the selected text. Copy gives the text in the order it was written. +A selection follows the glyphs. In text of mixed direction, one line can have several selection rects. Copy gives the +text in the order it was written. ### Styling From fe0fe427c2cd0e0926822c24da0e3821836947df Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:27:26 -0800 Subject: [PATCH 09/14] Select each character of a ligature on its own A glyph now stands for its character and for the characters after it up to the next glyph of the run. A selection takes the part of the glyph that its characters have, so one character of a ligature gets a rect. A tap on a ligature finds the character under the point. Lines of a block without a right-to-left character skip the check of their glyph runs. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/BlockLayout.swift | 103 ++++++++++++++---- .../RightToLeftSelectionTests.swift | 51 +++++++++ 2 files changed, 135 insertions(+), 19 deletions(-) diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index beffc8b..cdc4a08 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -666,10 +666,15 @@ final class BlockLayout: @unchecked Sendable { guard let line = lines.first(where: { $0.frame.minY <= point.y && point.y < $0.frame.maxY && point.x >= $0.frame.minX && point.x < $0.frame.maxX }), !line.range.isEmpty else { return nil } - if line.hasRightToLeftRuns { + if hasRightToLeftText(line) { let x = point.x - line.frame.minX guard let glyph = glyphs(of: line).first(where: { $0.minX <= x && x < $0.maxX }) else { return nil } - return line.range.contains(glyph.character) ? glyph.character : nil + // In a ligature, the character whose part of the glyph is under the point. + let character = glyph.characters.first { offset in + let part = glyph.part(offset..<(offset + 1), in: line) + return part.minX <= x && x < part.maxX + } ?? glyph.characters.lowerBound + return line.range.contains(character) ? character : nil } let localBoundary = CTLineGetStringIndexForPosition(line.ctLine, CGPoint(x: point.x - line.frame.minX, y: 0)) guard localBoundary != kCFNotFound else { return nil } @@ -691,6 +696,7 @@ final class BlockLayout: @unchecked Sendable { return nil } + /// A part of a selection on one line: the glyphs of one or more runs /// next to each other that go the same way. struct SelectionSegment: Equatable { @@ -698,6 +704,8 @@ final class BlockLayout: @unchecked Sendable { var isRightToLeft: Bool /// The first and the last of its selected characters, in block offsets. var characters: ClosedRange + /// The index of its line in the block. + var line: Int /// Whether it holds the first selected character, where the start /// handle goes, and the last one, where the end handle goes. var containsStart = false @@ -721,8 +729,8 @@ final class BlockLayout: @unchecked Sendable { if line.range.lowerBound >= range.upperBound { break } let continuesPastLine = range.upperBound >= line.range.upperBound && index < lines.count - 1 let lower = max(range.lowerBound, line.range.lowerBound) - if isRightToLeft || line.hasRightToLeftRuns { - segments += runSegments(of: line, selecting: range, continuesPastLine: continuesPastLine) + if hasRightToLeftText(line) { + segments += runSegments(of: line, at: index, selecting: range, continuesPastLine: continuesPastLine) continue } let startX = x(forOffset: lower, in: line) @@ -731,7 +739,7 @@ final class BlockLayout: @unchecked Sendable { let last = max(min(range.upperBound, line.range.upperBound) - 1, lower) segments.append(SelectionSegment( rect: CGRect(x: startX, y: line.frame.minY, width: max(endX - startX, 4), height: line.frame.height), - isRightToLeft: false, characters: lower...last)) + isRightToLeft: false, characters: lower...last, line: index)) } } if let start = segments.indices.min(by: { segments[$0].characters.lowerBound < segments[$1].characters.lowerBound }) { @@ -744,10 +752,17 @@ final class BlockLayout: @unchecked Sendable { return segments } + /// Whether Core Text can have drawn some of the line right to left. A + /// block without a right-to-left character has no such line. + private func hasRightToLeftText(_ line: Line) -> Bool { + isRightToLeft || (paragraphDirection != nil && line.hasRightToLeftRuns) + } + /// The selected glyphs of a line, as rects of the runs they are in. /// Whitespace at the end of a line, which Core Text puts outside the /// line box, is left out. - private func runSegments(of line: Line, selecting range: Range, continuesPastLine: Bool) -> [SelectionSegment] { + private func runSegments(of line: Line, at lineIndex: Int, selecting range: Range, + continuesPastLine: Bool) -> [SelectionSegment] { var segments: [SelectionSegment] = [] var current: (run: Int, minX: CGFloat, maxX: CGFloat, characters: ClosedRange, rightToLeft: Bool)? func flush() { @@ -759,20 +774,27 @@ final class BlockLayout: @unchecked Sendable { segments[segments.count - 1].characters = min(last.characters.lowerBound, part.characters.lowerBound) ... max(last.characters.upperBound, part.characters.upperBound) } else { - segments.append(SelectionSegment(rect: rect, isRightToLeft: part.rightToLeft, characters: part.characters)) + segments.append(SelectionSegment(rect: rect, isRightToLeft: part.rightToLeft, characters: part.characters, + line: lineIndex)) } } - for glyph in glyphs(of: line) where range.contains(glyph.character) && line.range.contains(glyph.character) { - let minX = max(glyph.minX, 0) - let maxX = min(glyph.maxX, line.frame.width) + for glyph in glyphs(of: line) { + let lower = max(range.lowerBound, line.range.lowerBound, glyph.characters.lowerBound) + let upper = min(range.upperBound, line.range.upperBound, glyph.characters.upperBound) + guard lower < upper else { continue } + let selected = lower.. minX else { continue } + let characters = selected.lowerBound...(selected.upperBound - 1) if let part = current, part.run == glyph.run { current = (part.run, min(part.minX, minX), max(part.maxX, maxX), - min(part.characters.lowerBound, glyph.character)...max(part.characters.upperBound, glyph.character), + min(part.characters.lowerBound, characters.lowerBound)...max(part.characters.upperBound, characters.upperBound), part.rightToLeft) } else { flush() - current = (glyph.run, minX, maxX, glyph.character...glyph.character, glyph.rightToLeft) + current = (glyph.run, minX, maxX, characters, glyph.rightToLeft) } } flush() @@ -781,15 +803,48 @@ final class BlockLayout: @unchecked Sendable { let lower = max(range.lowerBound, line.range.lowerBound) let x = x(forOffset: lower, in: line) segments.append(SelectionSegment(rect: CGRect(x: isRightToLeft ? x - 4 : x, y: line.frame.minY, width: 4, height: line.frame.height), - isRightToLeft: isRightToLeft, characters: lower...lower)) + isRightToLeft: isRightToLeft, characters: lower...lower, line: lineIndex)) } return segments } - /// The glyphs of a line from left to right, with the character each - /// stands for (a block offset) and its left and right edges in the line. - private func glyphs(of line: Line) -> [(character: Int, minX: CGFloat, maxX: CGFloat, rightToLeft: Bool, run: Int)] { - var result: [(character: Int, minX: CGFloat, maxX: CGFloat, rightToLeft: Bool, run: Int)] = [] + /// A glyph of a line: the characters it stands for (block offsets), and + /// its left and right edges in the line. + private struct Glyph { + /// More than one character for a ligature. + let characters: Range + let minX: CGFloat + let maxX: CGFloat + let rightToLeft: Bool + let run: Int + + /// The left and right edges of the part of the glyph that stands for + /// the characters of `range`. + func part(_ range: Range, in line: Line) -> (minX: CGFloat, maxX: CGFloat) { + let lower = max(range.lowerBound, characters.lowerBound) + let upper = min(range.upperBound, characters.upperBound) + guard lower > characters.lowerBound || upper < characters.upperBound else { return (minX, maxX) } + let a = edge(before: lower, in: line) + let b = edge(before: upper, in: line) + return (min(a, b), max(a, b)) + } + + /// Where the caret before character `offset` is in the glyph: from + /// Core Text if it puts it inside the glyph, else at an even share. + private func edge(before offset: Int, in line: Line) -> CGFloat { + let start = rightToLeft ? maxX : minX + let end = rightToLeft ? minX : maxX + if offset <= characters.lowerBound { return start } + if offset >= characters.upperBound { return end } + let x = CTLineGetOffsetForStringIndex(line.ctLine, offset - line.indexBase, nil) + if x > minX + 0.01, x < maxX - 0.01 { return x } + return start + (end - start) * CGFloat(offset - characters.lowerBound) / CGFloat(characters.count) + } + } + + /// The glyphs of a line from left to right. + private func glyphs(of line: Line) -> [Glyph] { + var result: [Glyph] = [] for (runIndex, run) in (CTLineGetGlyphRuns(line.ctLine) as! [CTRun]).enumerated() { let count = CTRunGetGlyphCount(run) guard count > 0 else { continue } @@ -800,9 +855,19 @@ final class BlockLayout: @unchecked Sendable { CTRunGetPositions(run, CFRange(location: 0, length: 0), &positions) CTRunGetAdvances(run, CFRange(location: 0, length: 0), &advances) let rightToLeft = CTRunGetStatus(run).contains(.rightToLeft) + let runRange = CTRunGetStringRange(run) + // A glyph stands for its character and those after it up to the + // next one that a glyph of the run starts at. + let starts = Set(indices).sorted() + var ends: [CFIndex: CFIndex] = [:] + for (position, start) in starts.enumerated() { + ends[start] = position + 1 < starts.count ? starts[position + 1] : max(runRange.location + runRange.length, start + 1) + } for glyph in 0.. DocumentLayout let before = (block.caretRect(atOffset: 2).midX + block.caretRect(atOffset: 3).midX) / 2 #expect(document.link(at: CGPoint(x: before, y: block.lines[0].frame.midY)) == nil) } + +// MARK: Ligatures + +/// Checks that each character of a ligature that starts at `start` and is +/// `count` characters long gets its own part of the glyph, and that a tap on +/// that part finds the character. +private func expectLigatureParts(_ document: DocumentLayout, start: Int, count: Int, rightToLeft: Bool) { + let block = document.entry(at: 0).layout + let whole = document.selectionRects(for: start..<(start + count)) + #expect(whole.count == 1) + var parts: [CGRect] = [] + for offset in start..<(start + count) { + let rects = document.selectionRects(for: offset..<(offset + 1)) + #expect(rects.count == 1, "offset \(offset) has \(rects.count) rects") + guard let rect = rects.first else { return } + parts.append(rect) + #expect(block.characterOffset(at: CGPoint(x: rect.midX, y: rect.midY)) == offset) + } + guard let first = whole.first, parts.count == count else { return } + let ordered = rightToLeft ? parts.reversed() : parts + #expect(abs(ordered.first!.minX - first.minX) < 0.5) + #expect(abs(ordered.last!.maxX - first.maxX) < 0.5) + for (left, right) in zip(ordered, ordered.dropFirst()) { + #expect(abs(left.maxX - right.minX) < 0.5) + } +} + +@Test func eachCharacterOfAnArabicLigatureIsSelectedOnItsOwn() { + // Lam and alef are drawn as one glyph. + let document = layout("لا بأس") + expectLigatureParts(document, start: 0, count: 2, rightToLeft: true) +} + +@Test func eachCharacterOfALatinLigatureNextToHebrewIsSelectedOnItsOwn() { + var style = TranscriptStyle() + style.bodyFont = TranscriptFont(name: "Times-Roman", size: 17) + let document = DocumentLayout(document: MarkdownStreamParser.document(from: "office שלום"), width: 300, style: style) + let line = document.entry(at: 0).layout.lines[0] + let runs = CTLineGetGlyphRuns(line.ctLine) as! [CTRun] + // Only a test of something if the font joins "ffi" or "fi". + let glyphCount = runs.reduce(0) { $0 + CTRunGetGlyphCount($1) } + #expect(glyphCount < "office שלום".utf16.count) + for offset in 0..<6 { + #expect(document.selectionRects(for: offset..<(offset + 1)).count == 1, "offset \(offset)") + } + let rects = (0..<6).compactMap { document.selectionRects(for: $0..<($0 + 1)).first } + for (left, right) in zip(rects, rects.dropFirst()) { + #expect(abs(left.maxX - right.minX) < 0.5) + } +} From ec0a51f4e7da1e73c4d5f29e57540a3335d1b504 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:29:50 -0800 Subject: [PATCH 10/14] Move the caret left and right by where the carets are drawn In a line with right-to-left text, a move to the right now goes to the nearest caret on the right of the screen, and a move to the left to the nearest caret on the left. This is also correct in a left-to-right run inside a right-to-left paragraph, and the reverse. At the end of the line, the caret goes on to the next or the previous line. Lines with no right-to-left text move by one character, as before. The far end of a range on one line is found from its carets. The first rect of a range is the union of the rects of its first line, not of all the rects at the same height, so a range across table cells gives the first cell only. The UITextInput methods call DocumentLayout helpers that the macOS tests reach. New tests cover the moves, the first rect and copy of right-to-left and mixed text. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/BlockLayout.swift | 25 +++++++ .../TranscriptKit/Layout/DocumentLayout.swift | 51 +++++++++++++ .../iOS/TranscriptTextView.swift | 39 ++++------ .../RightToLeftSelectionTests.swift | 73 +++++++++++++++++++ 4 files changed, 164 insertions(+), 24 deletions(-) diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index cdc4a08..b4896b0 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -633,6 +633,31 @@ final class BlockLayout: @unchecked Sendable { return CGRect(x: x(forOffset: offset, in: line) - 1, y: line.frame.minY, width: 2, height: line.frame.height) } + /// Where a caret at `offset` goes when it moves one stop to the right, + /// or to the left, in a line with right-to-left text: to the nearest + /// caret on that side, else to the end of the line on that side. Nil in + /// other lines, where a stop is one character, or when the caret is at + /// that end of the line already. + func visualStep(from offset: Int, right: Bool) -> Int? { + guard offset >= 0, offset <= length else { return nil } + let index = lineIndex(forOffset: offset) + let line = lines[index] + guard !line.range.isEmpty, hasRightToLeftText(line) else { return nil } + // The end of a line that wraps is a caret on the next line. + let last = index == lines.count - 1 ? line.range.upperBound : line.range.upperBound - 1 + let text = block.text as NSString + let x = self.x(forOffset: offset, in: line) + var best: (offset: Int, distance: CGFloat)? + for candidate in line.range.lowerBound...max(last, line.range.lowerBound) where candidate != offset { + if candidate < text.length, text.rangeOfComposedCharacterSequence(at: candidate).location != candidate { continue } + let distance = (self.x(forOffset: candidate, in: line) - x) * (right ? 1 : -1) + if distance > 0.5, best.map({ distance < $0.distance }) ?? true { best = (candidate, distance) } + } + if let best { return best.offset } + let end = right != isRightToLeft ? line.range.upperBound : line.range.lowerBound + return end == offset ? nil : end + } + func closestOffset(to point: CGPoint) -> Int { guard let table else { return closestOffset(to: point, amongLines: 0..) -> CGRect? { + guard !range.isEmpty, let first = entryIndex(forOffset: range.lowerBound) else { return nil } + for index in first..= range.upperBound { break } + let lower = max(range.lowerBound - entry.start, 0) + let upper = min(range.upperBound - entry.start, entry.layout.length) + guard lower < upper else { continue } + let segments = entry.layout.selectionSegments(for: lower.. Int { + let right = count < 0 ? !right : right + var offset = offset + for _ in 0.., right: Bool) -> Int { + let lower = caretRect(at: range.lowerBound) + let upper = caretRect(at: range.upperBound) + if abs(lower.minY - upper.minY) < 0.5, abs(lower.midX - upper.midX) > 0.5 { + return (upper.midX > lower.midX) == right ? range.upperBound : range.lowerBound + } + return right != isRightToLeft(at: range.lowerBound) ? range.upperBound : range.lowerBound + } + /// Whether the text at `offset` is in a right-to-left paragraph. /// `backward` asks about the character before `offset`. func isRightToLeft(at offset: Int, backward: Bool = false) -> Bool { diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index bf20d30..1d13b36 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -1345,22 +1345,11 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD return TranscriptTextPosition(offset: target) } - /// `.left` and `.right` swapped in a right-to-left paragraph, where the - /// text goes on to the left: then `.right` goes back in the text. - private func textDirection(_ direction: UITextLayoutDirection, at offset: Int) -> UITextLayoutDirection { - guard currentLayout.isRightToLeft(at: offset) else { return direction } - switch direction { - case .left: return .right - case .right: return .left - default: return direction - } - } - public func position(from position: UITextPosition, in direction: UITextLayoutDirection, offset: Int) -> UITextPosition? { let start = self.offset(of: position) - switch textDirection(direction, at: start) { - case .left: return TranscriptTextPosition(offset: clamp(start - offset)) - case .right: return TranscriptTextPosition(offset: clamp(start + offset)) + switch direction { + case .left, .right: + return TranscriptTextPosition(offset: currentLayout.offset(from: clamp(start), movingRight: direction == .right, by: offset)) case .up, .down: let caret = currentLayout.caretRect(at: start) let step = caret.height * CGFloat(offset) * (direction == .up ? -1 : 1) @@ -1382,18 +1371,23 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public func position(within range: UITextRange, farthestIn direction: UITextLayoutDirection) -> UITextPosition? { let range = self.range(of: range) - switch textDirection(direction, at: range.lowerBound) { - case .left, .up: return TranscriptTextPosition(offset: range.lowerBound) - case .right, .down: return TranscriptTextPosition(offset: range.upperBound) + switch direction { + case .left, .right: + return TranscriptTextPosition(offset: currentLayout.farthestOffset(in: range, right: direction == .right)) + case .up: return TranscriptTextPosition(offset: range.lowerBound) + case .down: return TranscriptTextPosition(offset: range.upperBound) @unknown default: return nil } } public func characterRange(byExtending position: UITextPosition, in direction: UITextLayoutDirection) -> UITextRange? { let start = offset(of: position) - switch textDirection(direction, at: start) { - case .left, .up: return TranscriptTextRange(range: clamp(start - 1).. CGRect { let range = self.range(of: range) - let segments = currentLayout.selectionSegments(for: range) - guard let first = segments.first else { return currentLayout.caretRect(at: range.lowerBound) } - // All of the first line, which text of mixed direction splits into several rects. - return segments.prefix { $0.rect.minY == first.rect.minY }.reduce(first.rect) { $0.union($1.rect) } + return currentLayout.firstLineRect(for: range) ?? currentLayout.caretRect(at: range.lowerBound) } public func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { diff --git a/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift b/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift index e35d2e3..e1b131a 100644 --- a/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift +++ b/Tests/TranscriptKitTests/RightToLeftSelectionTests.swift @@ -145,3 +145,76 @@ private func expectLigatureParts(_ document: DocumentLayout, start: Int, count: #expect(abs(left.maxX - right.minX) < 0.5) } } + +// MARK: Caret moves, first rect and copy + +@Test func leftAndRightMovesFollowTheScreen() { + // "abc" is drawn left to right at the left of a right-to-left line. + let mixed = layout("שלום abc") + #expect(mixed.offset(from: 6, movingRight: true) == 7) + #expect(mixed.offset(from: 6, movingRight: false) == 5) + #expect(mixed.offset(from: 2, movingRight: true) == 1) + #expect(mixed.offset(from: 2, movingRight: false) == 3) + + let plain = layout("Hello world") + #expect(plain.offset(from: 2, movingRight: true) == 3) + #expect(plain.offset(from: 2, movingRight: false) == 1) + #expect(plain.offset(from: 2, movingRight: true, by: 3) == 5) + #expect(plain.offset(from: 2, movingRight: true, by: -1) == 1) + #expect(plain.offset(from: 0, movingRight: false) == 0) +} + +@Test(arguments: ["Say שלום עולם to all", "שלום abc def עולם"]) +func rightMovesGoRightAcrossALineOfMixedText(text: String) { + let document = layout(text, width: 400) + let line = document.entry(at: 0).layout.lines[0] + // From the caret at the left end of the line. + var offset = (0...document.length).min { document.caretRect(at: $0).midX < document.caretRect(at: $1).midX }! + var visited = [offset] + while visited.count <= document.length { + let next = document.offset(from: offset, movingRight: true) + guard next != offset, document.caretRect(at: next).midX > document.caretRect(at: offset).midX + 0.5 else { break } + offset = next + visited.append(offset) + } + // Every caret stop of the line is visited, from left to right. + let stops = Set((0...document.length).map { document.caretRect(at: $0).midX.rounded() }) + #expect(visited.count == stops.count, "visited \(visited)") + #expect(abs(document.caretRect(at: offset).midX - line.frame.maxX) < 2) +} + +@Test func farthestEndOfARangeIsFoundOnTheScreen() { + let document = layout("שלום abc") + #expect(document.farthestOffset(in: 0..<4, right: true) == 0) + #expect(document.farthestOffset(in: 0..<4, right: false) == 4) + #expect(document.farthestOffset(in: 5..<7, right: true) == 7) + let plain = layout("Hello world") + #expect(plain.farthestOffset(in: 1..<4, right: true) == 4) + #expect(plain.farthestOffset(in: 1..<4, right: false) == 1) +} + +@Test func firstLineRectCoversTheRectsOfTheFirstLine() { + let mixed = layout("Say שלום עולם to all", width: 400) + let segments = mixed.selectionSegments(for: 2..<8) + #expect(segments.count == 2) + #expect(mixed.firstLineRect(for: 2..<8) == segments[0].rect.union(segments[1].rect)) + + // The cells of a row start at the same height, but each has its own line. + let table = layout("| a | b |\n|---|---|\n| c | d |") + let block = table.entry(at: 0).layout + let row = block.table!.cellLines[1] + let range = block.lines[row[0].lowerBound].range.lowerBound.. Date: Mon, 23 Nov 2026 18:31:19 -0800 Subject: [PATCH 11/14] Find the first strong character by its bidirectional class The general category does not give the bidirectional class of every character. Roman numerals, regional indicators, private use characters and the digits of Indic scripts are left to right, and some modifier letters are neutral. A table of these exceptions, from Unicode 16.0, now corrects the category rule. A block that starts with such a character and then holds Hebrew is left to right, as Core Text finds. U+FEFF (zero width no-break space) no longer counts as a right-to-left character. Co-Authored-By: Claude Opus 5.5 --- .../Layout/WritingDirection.swift | 109 +++++++++++++++++- .../WritingDirectionTests.swift | 9 +- 2 files changed, 115 insertions(+), 3 deletions(-) diff --git a/Sources/TranscriptKit/Layout/WritingDirection.swift b/Sources/TranscriptKit/Layout/WritingDirection.swift index b5a4ba9..d8daca2 100644 --- a/Sources/TranscriptKit/Layout/WritingDirection.swift +++ b/Sources/TranscriptKit/Layout/WritingDirection.swift @@ -92,7 +92,7 @@ struct DirectionScan: Equatable, Sendable { /// control that makes text right-to-left. static func isRightToLeftCharacter(_ scalar: Unicode.Scalar) -> Bool { switch scalar.value { - case 0x0590...0x08FF, 0xFB1D...0xFDFF, 0xFE70...0xFEFF, 0x10800...0x10FFF, 0x1E800...0x1EFFF: return true + case 0x0590...0x08FF, 0xFB1D...0xFDFF, 0xFE70...0xFEFE, 0x10800...0x10FFF, 0x1E800...0x1EFFF: return true case 0x200F, 0x202B, 0x202E, 0x2067: return true default: return false } @@ -100,8 +100,10 @@ struct DirectionScan: Equatable, Sendable { /// The direction of a strong character, or nil for one that takes its /// direction from the text around it: digits, punctuation, spaces, - /// symbols and marks. + /// symbols and marks. This is the bidirectional class of the character + /// (L, or R and AL). static func strongDirection(of scalar: Unicode.Scalar) -> WritingDirection? { + if let exception = exception(for: scalar.value) { return exception.direction } switch scalar.value { case 0x200E: return .leftToRight case 0x200F, 0x061C: return .rightToLeft @@ -123,4 +125,107 @@ struct DirectionScan: Equatable, Sendable { return nil } } + private static func exception(for value: UInt32) -> (lower: UInt32, upper: UInt32, direction: WritingDirection?)? { + var low = 0 + var high = exceptions.count - 1 + while low <= high { + let mid = (low + high) / 2 + let entry = exceptions[mid] + if value < entry.lower { + high = mid - 1 + } else if value > entry.upper { + low = mid + 1 + } else { + return entry + } + } + return nil + } + + /// The assigned characters, in ranges, whose bidirectional class in + /// Unicode 16.0 is not the one that `strongDirection(of:)` finds from + /// the general category: for example Roman numerals, regional + /// indicators, private use characters and the digits of Indic scripts + /// are L, and some modifier letters are neutral. + private static let exceptions: [(lower: UInt32, upper: UInt32, direction: WritingDirection?)] = [ + (0x02B9, 0x02BA, nil), (0x02C6, 0x02CF, nil), (0x02EC, 0x02EC, nil), (0x0374, 0x0374, nil), + (0x0482, 0x0482, .leftToRight), (0x055A, 0x055F, .leftToRight), (0x0589, 0x0589, .leftToRight), (0x0606, 0x0607, nil), + (0x060E, 0x060F, nil), (0x06DE, 0x06DE, nil), (0x070F, 0x070F, .rightToLeft), (0x07C0, 0x07C9, .rightToLeft), + (0x07F6, 0x07F9, nil), (0x0964, 0x0970, .leftToRight), (0x09E6, 0x09EF, .leftToRight), (0x09F4, 0x09FA, .leftToRight), + (0x09FD, 0x09FD, .leftToRight), (0x0A66, 0x0A6F, .leftToRight), (0x0A76, 0x0A76, .leftToRight), + (0x0AE6, 0x0AF0, .leftToRight), (0x0B66, 0x0B70, .leftToRight), (0x0B72, 0x0B77, .leftToRight), + (0x0BE6, 0x0BF2, .leftToRight), (0x0C66, 0x0C6F, .leftToRight), (0x0C77, 0x0C77, .leftToRight), + (0x0C7F, 0x0C7F, .leftToRight), (0x0C84, 0x0C84, .leftToRight), (0x0CBF, 0x0CBF, .leftToRight), + (0x0CC6, 0x0CC6, .leftToRight), (0x0CE6, 0x0CEF, .leftToRight), (0x0D4F, 0x0D4F, .leftToRight), + (0x0D58, 0x0D5E, .leftToRight), (0x0D66, 0x0D79, .leftToRight), (0x0DE6, 0x0DEF, .leftToRight), + (0x0DF4, 0x0DF4, .leftToRight), (0x0E4F, 0x0E5B, .leftToRight), (0x0ED0, 0x0ED9, .leftToRight), + (0x0F01, 0x0F17, .leftToRight), (0x0F1A, 0x0F34, .leftToRight), (0x0F36, 0x0F36, .leftToRight), + (0x0F38, 0x0F38, .leftToRight), (0x0F85, 0x0F85, .leftToRight), (0x0FBE, 0x0FC5, .leftToRight), + (0x0FC7, 0x0FCC, .leftToRight), (0x0FCE, 0x0FDA, .leftToRight), (0x1040, 0x104F, .leftToRight), + (0x1090, 0x1099, .leftToRight), (0x109E, 0x109F, .leftToRight), (0x10FB, 0x10FB, .leftToRight), + (0x1360, 0x137C, .leftToRight), (0x166D, 0x166E, .leftToRight), (0x16EB, 0x16F0, .leftToRight), + (0x1735, 0x1736, .leftToRight), (0x17D4, 0x17D6, .leftToRight), (0x17D8, 0x17DA, .leftToRight), + (0x17E0, 0x17E9, .leftToRight), (0x1810, 0x1819, .leftToRight), (0x1946, 0x194F, .leftToRight), + (0x19D0, 0x19DA, .leftToRight), (0x1A1E, 0x1A1F, .leftToRight), (0x1A80, 0x1A89, .leftToRight), + (0x1A90, 0x1A99, .leftToRight), (0x1AA0, 0x1AA6, .leftToRight), (0x1AA8, 0x1AAD, .leftToRight), + (0x1B4E, 0x1B6A, .leftToRight), (0x1B74, 0x1B7F, .leftToRight), (0x1BB0, 0x1BB9, .leftToRight), + (0x1BFC, 0x1BFF, .leftToRight), (0x1C3B, 0x1C49, .leftToRight), (0x1C50, 0x1C59, .leftToRight), + (0x1C7E, 0x1C7F, .leftToRight), (0x1CC0, 0x1CC7, .leftToRight), (0x1CD3, 0x1CD3, .leftToRight), + (0x214F, 0x214F, .leftToRight), (0x2160, 0x2182, .leftToRight), (0x2185, 0x2188, .leftToRight), + (0x2336, 0x237A, .leftToRight), (0x2395, 0x2395, .leftToRight), (0x249C, 0x24E9, .leftToRight), + (0x26AC, 0x26AC, .leftToRight), (0x2800, 0x28FF, .leftToRight), (0x2D70, 0x2D70, .leftToRight), (0x2E2F, 0x2E2F, nil), + (0x3007, 0x3007, .leftToRight), (0x3021, 0x3029, .leftToRight), (0x3038, 0x303A, .leftToRight), + (0x3190, 0x319F, .leftToRight), (0x3200, 0x321C, .leftToRight), (0x3220, 0x324F, .leftToRight), + (0x3260, 0x327B, .leftToRight), (0x327F, 0x32B0, .leftToRight), (0x32C0, 0x32CB, .leftToRight), + (0x32D0, 0x3376, .leftToRight), (0x337B, 0x33DD, .leftToRight), (0x33E0, 0x33FE, .leftToRight), + (0xA4FE, 0xA4FF, .leftToRight), (0xA620, 0xA629, .leftToRight), (0xA67F, 0xA67F, nil), (0xA6E6, 0xA6EF, .leftToRight), + (0xA6F2, 0xA6F7, .leftToRight), (0xA717, 0xA71F, nil), (0xA788, 0xA788, nil), (0xA789, 0xA78A, .leftToRight), + (0xA830, 0xA837, .leftToRight), (0xA8CE, 0xA8D9, .leftToRight), (0xA8F8, 0xA8FA, .leftToRight), + (0xA8FC, 0xA8FC, .leftToRight), (0xA900, 0xA909, .leftToRight), (0xA92E, 0xA92F, .leftToRight), + (0xA95F, 0xA95F, .leftToRight), (0xA9C1, 0xA9CD, .leftToRight), (0xA9D0, 0xA9D9, .leftToRight), + (0xA9DE, 0xA9DF, .leftToRight), (0xA9F0, 0xA9F9, .leftToRight), (0xAA50, 0xAA59, .leftToRight), + (0xAA5C, 0xAA5F, .leftToRight), (0xAA77, 0xAA79, .leftToRight), (0xAADE, 0xAADF, .leftToRight), + (0xAAF0, 0xAAF1, .leftToRight), (0xAB5B, 0xAB5B, .leftToRight), (0xABEB, 0xABEB, .leftToRight), + (0xABF0, 0xABF9, .leftToRight), (0xE000, 0xF8FF, .leftToRight), (0xFB29, 0xFB29, nil), (0xFD3E, 0xFD4F, nil), + (0xFDCF, 0xFDCF, nil), (0xFDFD, 0xFDFF, nil), (0x10100, 0x10100, .leftToRight), (0x10102, 0x10102, .leftToRight), + (0x10107, 0x10133, .leftToRight), (0x10137, 0x1013F, .leftToRight), (0x1018D, 0x1018E, .leftToRight), + (0x101D0, 0x101FC, .leftToRight), (0x10320, 0x10323, .leftToRight), (0x10341, 0x10341, .leftToRight), + (0x1034A, 0x1034A, .leftToRight), (0x1039F, 0x1039F, .leftToRight), (0x103D0, 0x103D5, .leftToRight), + (0x104A0, 0x104A9, .leftToRight), (0x1056F, 0x1056F, .leftToRight), (0x1091F, 0x1091F, nil), (0x10B39, 0x10B3F, nil), + (0x10D6E, 0x10D6E, nil), (0x10E60, 0x10E7E, nil), (0x11047, 0x1104D, .leftToRight), (0x11066, 0x1106F, .leftToRight), + (0x110BB, 0x110C1, .leftToRight), (0x110CD, 0x110CD, .leftToRight), (0x110F0, 0x110F9, .leftToRight), + (0x11136, 0x11143, .leftToRight), (0x11174, 0x11175, .leftToRight), (0x111C5, 0x111C8, .leftToRight), + (0x111CD, 0x111CD, .leftToRight), (0x111D0, 0x111D9, .leftToRight), (0x111DB, 0x111DB, .leftToRight), + (0x111DD, 0x111DF, .leftToRight), (0x111E1, 0x111F4, .leftToRight), (0x11238, 0x1123D, .leftToRight), + (0x112A9, 0x112A9, .leftToRight), (0x112F0, 0x112F9, .leftToRight), (0x113D4, 0x113D5, .leftToRight), + (0x113D7, 0x113D8, .leftToRight), (0x1144B, 0x1145B, .leftToRight), (0x1145D, 0x1145D, .leftToRight), + (0x114C6, 0x114C6, .leftToRight), (0x114D0, 0x114D9, .leftToRight), (0x115C1, 0x115D7, .leftToRight), + (0x11641, 0x11643, .leftToRight), (0x11650, 0x11659, .leftToRight), (0x116B9, 0x116B9, .leftToRight), + (0x116C0, 0x116C9, .leftToRight), (0x116D0, 0x116E3, .leftToRight), (0x11730, 0x1173F, .leftToRight), + (0x1183B, 0x1183B, .leftToRight), (0x118E0, 0x118F2, .leftToRight), (0x11944, 0x11946, .leftToRight), + (0x11950, 0x11959, .leftToRight), (0x119E2, 0x119E2, .leftToRight), (0x11A07, 0x11A08, .leftToRight), + (0x11A3F, 0x11A46, .leftToRight), (0x11A9A, 0x11A9C, .leftToRight), (0x11A9E, 0x11AA2, .leftToRight), + (0x11B00, 0x11B09, .leftToRight), (0x11BE1, 0x11BE1, .leftToRight), (0x11BF0, 0x11BF9, .leftToRight), + (0x11C3F, 0x11C3F, .leftToRight), (0x11C41, 0x11C45, .leftToRight), (0x11C50, 0x11C6C, .leftToRight), + (0x11C70, 0x11C71, .leftToRight), (0x11D50, 0x11D59, .leftToRight), (0x11DA0, 0x11DA9, .leftToRight), + (0x11EF7, 0x11EF8, .leftToRight), (0x11F43, 0x11F59, .leftToRight), (0x11FC0, 0x11FD4, .leftToRight), + (0x11FFF, 0x11FFF, .leftToRight), (0x12400, 0x1246E, .leftToRight), (0x12470, 0x12474, .leftToRight), + (0x12FF1, 0x12FF2, .leftToRight), (0x13430, 0x1343F, .leftToRight), (0x16130, 0x16139, .leftToRight), + (0x16A60, 0x16A69, .leftToRight), (0x16A6E, 0x16A6F, .leftToRight), (0x16AC0, 0x16AC9, .leftToRight), + (0x16AF5, 0x16AF5, .leftToRight), (0x16B37, 0x16B3F, .leftToRight), (0x16B44, 0x16B45, .leftToRight), + (0x16B50, 0x16B59, .leftToRight), (0x16B5B, 0x16B61, .leftToRight), (0x16D6D, 0x16D79, .leftToRight), + (0x16E80, 0x16E9A, .leftToRight), (0x1BC9C, 0x1BC9C, .leftToRight), (0x1BC9F, 0x1BC9F, .leftToRight), + (0x1CCD6, 0x1CCEF, .leftToRight), (0x1CF50, 0x1CFC3, .leftToRight), (0x1D000, 0x1D0F5, .leftToRight), + (0x1D100, 0x1D126, .leftToRight), (0x1D129, 0x1D164, .leftToRight), (0x1D16A, 0x1D16C, .leftToRight), + (0x1D183, 0x1D184, .leftToRight), (0x1D18C, 0x1D1A9, .leftToRight), (0x1D1AE, 0x1D1E8, .leftToRight), + (0x1D2C0, 0x1D2D3, .leftToRight), (0x1D2E0, 0x1D2F3, .leftToRight), (0x1D360, 0x1D378, .leftToRight), + (0x1D800, 0x1D9FF, .leftToRight), (0x1DA37, 0x1DA3A, .leftToRight), (0x1DA6D, 0x1DA74, .leftToRight), + (0x1DA76, 0x1DA83, .leftToRight), (0x1DA85, 0x1DA8B, .leftToRight), (0x1E140, 0x1E149, .leftToRight), + (0x1E14F, 0x1E14F, .leftToRight), (0x1E2F0, 0x1E2F9, .leftToRight), (0x1E4F0, 0x1E4F9, .leftToRight), + (0x1E5F1, 0x1E5FA, .leftToRight), (0x1E5FF, 0x1E5FF, .leftToRight), (0x1E950, 0x1E959, .rightToLeft), + (0x1EEF0, 0x1EEF1, nil), (0x1F110, 0x1F12E, .leftToRight), (0x1F130, 0x1F169, .leftToRight), + (0x1F170, 0x1F1AC, .leftToRight), (0x1F1E6, 0x1F202, .leftToRight), (0x1F210, 0x1F23B, .leftToRight), + (0x1F240, 0x1F248, .leftToRight), (0x1F250, 0x1F251, .leftToRight), (0xF0000, 0xFFFFD, .leftToRight), + (0x100000, 0x10FFFD, .leftToRight) + ] } diff --git a/Tests/TranscriptKitTests/WritingDirectionTests.swift b/Tests/TranscriptKitTests/WritingDirectionTests.swift index 67035b1..0d2f2d4 100644 --- a/Tests/TranscriptKitTests/WritingDirectionTests.swift +++ b/Tests/TranscriptKitTests/WritingDirectionTests.swift @@ -15,6 +15,11 @@ import Testing ("\u{2067}abc\u{2069} שלום", .rightToLeft), ("\u{200F}123", .rightToLeft), ("日本語", .leftToRight), + ("Ⅳ שלום", .leftToRight), + ("🇺🇸 שלום", .leftToRight), + ("😀 שלום", .rightToLeft), + ("\u{02B9}שלום", .rightToLeft), + ("१२ שלום", .leftToRight), ("123 !?", nil), ("", nil), ]) @@ -28,6 +33,8 @@ func firstStrongCharacterSetsTheDirection(text: String, expected: WritingDirecti #expect(DirectionScan("שלום and more").paragraphDirection == .rightToLeft) // No strong character before the first right-to-left one. #expect(DirectionScan("12 \u{0661}\u{0662}").paragraphDirection == .leftToRight) + // A zero width no-break space is not right to left. + #expect(DirectionScan("\u{FEFF}Plain text").paragraphDirection == nil) } @Test func scanGoesOnFromWhereItStopped() { @@ -56,7 +63,7 @@ private func runLayout(_ text: String, direction: WritingDirection?) -> [[Double } } -@Test(arguments: ["שלום עולם ", "123 שלום", "hello שלום world ", "(\"مرحبا\") hello", "١٢٣ abc", "\u{2067}abc\u{2069} שלום"]) +@Test(arguments: ["שלום עולם ", "123 שלום", "Ⅳ שלום", "🇺🇸 שלום", "😀 שלום", "hello שלום world ", "(\"مرحبا\") hello", "١٢٣ abc", "\u{2067}abc\u{2069} שלום"]) func scanFindsTheDirectionThatCoreTextFinds(text: String) { let direction = DirectionScan(text).firstStrong #expect(runLayout(text, direction: nil) == runLayout(text, direction: direction)) From 997969d7e87c9c95fff19b9e57c0bd436ff29eb9 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:33:06 -0800 Subject: [PATCH 12/14] Keep a table column aligned to a side on that side The delimiter cells ":---" and "---:" align a column to the left and to the right of the screen. A right-to-left table mirrored them, so ":---" showed at the right. The parser now records the columns with a colon on one side only. A right-to-left table keeps their alignment on that side. A column with no colon still starts at the leading edge. Left-to-right tables and copy do not change. The README describes table columns and the arrow keys in right-to-left text. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 ++++-- .../TranscriptKit/Layout/BlockLayout.swift | 8 +++-- .../TranscriptKit/Markdown/BlockParser.swift | 21 ++++++++------ .../Markdown/MarkdownStreamParser.swift | 9 +++--- .../Model/TranscriptDocument.swift | 6 +++- .../RightToLeftLayoutTests.swift | 29 +++++++++++++++++++ 6 files changed, 63 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 8b41bc4..7d9f795 100644 --- a/README.md +++ b/README.md @@ -301,10 +301,13 @@ an English word is left to right, also when it holds words in other scripts. In a right-to-left block, the leading edge is on the right. Lines start there, and `textAlignment` counts from there: `.trailing` puts the lines at the left. The indents of lists and quotes, list markers and quote bars are on the right, -and a table puts its first column on the right. Code blocks are always left to right. +and a table puts its first column on the right. A table column with no colon in its delimiter cell (`---`) starts at +the leading edge. A colon on one side (`:---` or `---:`) puts the column's text at the left or at the right, in both +directions. Code blocks are always left to right. -A selection follows the glyphs. In text of mixed direction, one line can have several selection rects. Copy gives the -text in the order it was written. +A selection follows the glyphs. In text of mixed direction, one line can have several selection rects. In a line with +right-to-left text, the left and right arrow keys move the caret to the next caret on that side of the screen. Copy +gives the text in the order it was written. ### Styling diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index b4896b0..a91207a 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -399,7 +399,7 @@ final class BlockLayout: @unchecked Sendable { var kept = 0 var old: Table? if let previous, let oldTable = previous.table, let oldModel = previous.block.kind.table, - oldModel.alignments == model.alignments { + oldModel.alignments == model.alignments, oldModel.sidedColumns == model.sidedColumns { let limit = min(oldModel.rows.count - 1, model.rows.count) while kept < limit, oldModel.rows[kept] == model.rows[kept] { kept += 1 } old = oldTable @@ -514,7 +514,11 @@ final class BlockLayout: @unchecked Sendable { let metrics = fitted(lineMetrics(ctLine, isEmpty: range.isEmpty, font: font), to: fixedHeight) let slack = max(textWidth - metrics.width, 0) let offset: CGFloat - switch column < model.alignments.count ? model.alignments[column] : .leading { + var alignment = column < model.alignments.count ? model.alignments[column] : .leading + if direction == .rightToLeft, model.sidedColumns.contains(column) { + alignment = alignment == .leading ? .trailing : .leading + } + switch alignment { case .leading: offset = 0 case .center: offset = (slack / 2).rounded() case .trailing: offset = slack diff --git a/Sources/TranscriptKit/Markdown/BlockParser.swift b/Sources/TranscriptKit/Markdown/BlockParser.swift index 4ef128f..febdca2 100644 --- a/Sources/TranscriptKit/Markdown/BlockParser.swift +++ b/Sources/TranscriptKit/Markdown/BlockParser.swift @@ -16,7 +16,7 @@ enum BlockParser { /// `fence` is nil for an indented code block. case code(language: String?, fence: Character?, fenceLength: Int, indent: Int, closed: Bool) case rule - case table(alignments: [TranscriptTable.Alignment]) + case table(alignments: [TranscriptTable.Alignment], sided: Set) /// Display math that a line starting with `\[` or `$$` opened, until /// `closer` ends it. Its lines are kept as written. case math(closer: String, closed: Bool) @@ -102,9 +102,9 @@ enum BlockParser { } /// Turns a one-line paragraph into a table with that line as its header. - mutating func becomeTable(alignments: [TranscriptTable.Alignment]) { + mutating func becomeTable(alignments: [TranscriptTable.Alignment], sided: Set) { let header = lastLine ?? "" - kind = .table(alignments: alignments) + kind = .table(alignments: alignments, sided: sided) committedSource = [] lastLine = nil lastLineUnits = [] @@ -465,9 +465,9 @@ enum BlockParser { return } if canContinue, sameContext, let last = blocks.last, last.couldBecomeTable, - let alignments = BlockParser.delimiterRow(leaf), - alignments.count == BlockParser.tableCells(last.lastLine ?? "").count { - blocks[blocks.count - 1].becomeTable(alignments: alignments) + let delimiters = BlockParser.delimiterRow(leaf), + delimiters.alignments.count == BlockParser.tableCells(last.lastLine ?? "").count { + blocks[blocks.count - 1].becomeTable(alignments: delimiters.alignments, sided: delimiters.sided) canContinue = false tableOpen = true return @@ -1057,18 +1057,21 @@ enum BlockParser { } /// The column alignments if `content` is a delimiter row such as - /// "| --- | :---: | ---: |". - static func delimiterRow(_ content: Substring) -> [TranscriptTable.Alignment]? { + /// "| --- | :---: | ---: |", and the columns with a colon on one side + /// only (see `TranscriptTable.sidedColumns`). + static func delimiterRow(_ content: Substring) -> (alignments: [TranscriptTable.Alignment], sided: Set)? { guard content.utf8.contains(UInt8(ascii: "-")), content.allSatisfy({ "|:- \t".contains($0) }) else { return nil } let cells = tableCells(String(content)) var alignments: [TranscriptTable.Alignment] = [] + var sided = Set() for cell in cells { let core = trimmingSpaceAndTab(Substring(cell)) guard core.utf8.contains(UInt8(ascii: "-")), core.dropFirst().dropLast().allSatisfy({ $0 == "-" }) || core.count <= 2 else { return nil } let left = core.hasPrefix(":") let right = core.hasSuffix(":") + if left != right { sided.insert(alignments.count) } alignments.append(left && right ? .center : (right ? .trailing : .leading)) } - return alignments.isEmpty ? nil : alignments + return alignments.isEmpty ? nil : (alignments, sided) } } diff --git a/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift b/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift index 39b6054..cf42307 100644 --- a/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift +++ b/Sources/TranscriptKit/Markdown/MarkdownStreamParser.swift @@ -158,8 +158,8 @@ public struct MarkdownStreamParser: Sendable { containers: raw.containers, marker: raw.marker) case .rule: return TranscriptBlock(id: id, kind: .rule, text: "", containers: raw.containers, marker: raw.marker) - case .table(let alignments): - return makeTable(&raw, id: id, alignments: alignments, open: open, completeRows: completeRows) + case .table(let alignments, let sided): + return makeTable(&raw, id: id, alignments: alignments, sided: sided, open: open, completeRows: completeRows) case .math(let closer, let closed): let source = raw.mathLines.joined(separator: "\n") let tex = closed ? source.dropFirst(2).dropLast(closer.count).trimmingCharacters(in: .whitespacesAndNewlines) : "" @@ -192,7 +192,7 @@ public struct MarkdownStreamParser: Sendable { /// rows are padded or cut to the column count; a row still being written /// shows only the cells it has so far, so its text only grows. private func makeTable(_ raw: inout BlockParser.RawBlock, id: String, alignments: [TranscriptTable.Alignment], - open: Bool, completeRows: Int) -> TranscriptBlock { + sided: Set, open: Bool, completeRows: Int) -> TranscriptBlock { let columns = alignments.count var text: [UInt16] = [] var spans: [InlineSpan] = [] @@ -228,7 +228,8 @@ public struct MarkdownStreamParser: Sendable { } rows.append(ranges) } - let table = TranscriptTable(alignments: alignments, rows: rows) + var table = TranscriptTable(alignments: alignments, rows: rows) + table.sidedColumns = sided return TranscriptBlock(id: id, kind: .table(table), text: String(decoding: text, as: UTF16.self), spans: spans, containers: raw.containers, marker: raw.marker) } diff --git a/Sources/TranscriptKit/Model/TranscriptDocument.swift b/Sources/TranscriptKit/Model/TranscriptDocument.swift index 459e858..a1d6dbf 100644 --- a/Sources/TranscriptKit/Model/TranscriptDocument.swift +++ b/Sources/TranscriptKit/Model/TranscriptDocument.swift @@ -132,6 +132,10 @@ public struct TranscriptTable: Equatable, Sendable { public var alignments: [Alignment] /// Cell ranges, row by row; the first row is the header. public var rows: [[Range]] + /// The columns whose delimiter cell has a colon on one side only, as in + /// ":---" or "---:". Their alignment is a side of the screen, the left + /// or the right, so a right-to-left table does not mirror it. + var sidedColumns: Set = [] public init(alignments: [Alignment], rows: [[Range]]) { self.alignments = alignments @@ -144,7 +148,7 @@ public struct TranscriptTable: Equatable, Sendable { /// end, and the last cell perhaps longer: the structure of a table whose /// text grew at its end. func isExtended(by newer: TranscriptTable) -> Bool { - guard alignments == newer.alignments, newer.rows.count >= rows.count else { return false } + guard alignments == newer.alignments, sidedColumns == newer.sidedColumns, newer.rows.count >= rows.count else { return false } guard let lastRow = rows.indices.last else { return true } for index in 0.. [String] { #expect(table.minimumWidths[0].allSatisfy { $0 > TranscriptStyle().tableCellPadding * 2 }) } +@Test func columnAlignedToASideKeepsThatSideInRightToLeftText() { + let padding = TranscriptStyle().tableCellPadding + // ":---" is left, "---:" is right, and "---" is the leading edge: the right. + let markdown = "| א | ב | ג |\n|:---|---:|---|\n| אחת ארוכה מאוד | שתיים ארוכה מאוד | שלוש ארוכה מאוד |" + let block = layout(markdown, width: 400).entry(at: 0).layout + #expect(block.isRightToLeft) + guard let table = block.table else { Issue.record("no table"); return } + let count = table.columnX.count + func cell(_ column: Int) -> (line: BlockLayout.Line, left: CGFloat, right: CGFloat) { + (block.lines[table.cellLines[0][column].lowerBound], table.columnX[count - 2 - column], table.columnX[count - 1 - column]) + } + let left = cell(0) + #expect(abs(left.line.frame.minX - (left.left + padding)) < 0.5) + #expect(left.line.frame.maxX < left.right - padding - 1) + let right = cell(1) + #expect(abs(right.line.frame.maxX - (right.right - padding)) < 0.5) + #expect(right.line.frame.minX > right.left + padding + 1) + let leading = cell(2) + #expect(abs(leading.line.frame.maxX - (leading.right - padding)) < 0.5) + + // The same marks in left-to-right text. + let english = layout("| a | b |\n|:---|---:|\n| one long text | two long text |", width: 400).entry(at: 0).layout + guard let grid = english.table else { Issue.record("no table"); return } + let first = english.lines[grid.cellLines[0][0].lowerBound] + let second = english.lines[grid.cellLines[0][1].lowerBound] + #expect(abs(first.frame.minX - (grid.columnX[0] + padding)) < 0.5) + #expect(abs(second.frame.maxX - (grid.columnX[2] - padding)) < 0.5) +} + @Test func eachTableCellKeepsTheDirectionOfItsOwnText() { let block = layout("| Word | Meaning |\n|---|---|\n| \(arabic)! | hello |").entry(at: 0).layout #expect(!block.isRightToLeft) From aa4d46dfad24b5b64119e4f4bd781a25a66fc207 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:40:41 -0800 Subject: [PATCH 13/14] Draw custom tag shapes, padding and images in right-to-left text In right-to-left text, a tag fragment had its start on the left of its end, so layout skipped it, and tag pills and underlines were missing. A tag in a block with right-to-left text now takes the direction of its first strong character: - The text rect of a right-to-left tag comes from the left and right edges of its glyphs. - Core Text adds the extra advance of a character on its right, in both directions. So the room on the right of a tag goes on its rightmost character, and the room on its left goes on the character to its left. - The padding before a right-to-left tag and its image are on the right. - TranscriptFragment has a new isRightToLeft property, false by default. The built-in pill and marker shapes use it to close the correct side of a tag that wraps. Blocks without a right-to-left character do not change. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 + .../TranscriptKit/Layout/BlockLayout.swift | 4 +- .../TranscriptKit/Layout/TagDecorations.swift | 89 +++++++++++++++---- .../Model/TranscriptShapes.swift | 30 ++++--- .../DecorationShapeTests.swift | 81 +++++++++++++++++ Tests/TranscriptKitTests/TagImageTests.swift | 22 +++++ 6 files changed, 200 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 7d9f795..8d27c4a 100644 --- a/README.md +++ b/README.md @@ -305,6 +305,10 @@ and a table puts its first column on the right. A table column with no colon in the leading edge. A colon on one side (`:---` or `---:`) puts the column's text at the left or at the right, in both directions. Code blocks are always left to right. +A custom tag takes the direction of its first strong character. A right-to-left tag starts at the right: its padding +and its image before the text are on the right, and the built-in shapes are open on the correct side where the tag +wraps. `TranscriptFragment.isRightToLeft` tells a shape of your own the same. + A selection follows the glyphs. In text of mixed direction, one line can have several selection rects. In a line with right-to-left text, the left and right arrow keys move the caret to the next caret on that side of the screen. Copy gives the text in the order it was written. diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index a91207a..dbdb99c 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -204,7 +204,7 @@ final class BlockLayout: @unchecked Sendable { } // Only the tags on the lines laid out again; the others' lines are kept. - let decorated = hasDecorations ? DecoratedTags(block, from: restart) : nil + let decorated = hasDecorations ? DecoratedTags(block, from: restart, direction: direction) : nil let fixedHeight = style.lineHeight(for: block.kind) let gap = fixedHeight == nil ? style.lineSpacing : 0 @@ -391,7 +391,7 @@ final class BlockLayout: @unchecked Sendable { let font = style.font(for: block.kind) let fixedHeight = style.lineHeight(for: block.kind) let gap = fixedHeight == nil ? style.lineSpacing : 0 - let decorated = DecoratedTags(block) + let decorated = DecoratedTags(block, direction: direction) let sizing = ImageSizing(store: images, maximumWidth: max(available / CGFloat(columns) - padding * 2, 20)) let minimumWidth = padding * 2 + style.effectiveBodySize diff --git a/Sources/TranscriptKit/Layout/TagDecorations.swift b/Sources/TranscriptKit/Layout/TagDecorations.swift index 3514f98..f80fe37 100644 --- a/Sources/TranscriptKit/Layout/TagDecorations.swift +++ b/Sources/TranscriptKit/Layout/TagDecorations.swift @@ -13,6 +13,8 @@ struct DecoratedTags { let tag: InlineSpan.CustomTag /// Its place among the block's spans, where outer tags come first. let order: Int + /// Whether its text is right to left: it starts at the right. + let isRightToLeft: Bool var padding: CGFloat { tag.decoration.padding } /// The space before the text: the padding, and the image after it. @@ -26,10 +28,15 @@ struct DecoratedTags { /// line break), and its padding after it on its last character. Kept /// even while the tag is open, so its end acts like a wider last glyph: /// only the word being written can wrap because of it. + /// + /// Core Text puts the extra advance of a character on its right, also + /// in right-to-left text. So in a block with right-to-left text, a + /// right-to-left tag has the padding before it on its first character, + /// and the character to the left of a tag gets the padding on that side. let kerns: [Int: CGFloat] /// The padding of the tags that start at an offset, added up: a line /// that starts there is moved right by it, since there is no character - /// before it on the line to carry it. + /// before it on the line to carry it. Not in a right-to-left paragraph. let startPadding: [Int: CGFloat] /// Whether any of the block's tags take padding or draw shapes. @@ -37,9 +44,12 @@ struct DecoratedTags { block.spans.contains { $0.customTag?.shapesText == true } } - /// - Parameter start: only tags that reach this offset or past it are - /// kept: a streaming update lays out only the lines from there on. - init?(_ block: TranscriptBlock, from start: Int = 0) { + /// - Parameters: + /// - start: only tags that reach this offset or past it are kept: a + /// streaming update lays out only the lines from there on. + /// - direction: the direction that the block is typeset with. A tag + /// takes the direction of its first strong character, or this one. + init?(_ block: TranscriptBlock, from start: Int = 0, direction: WritingDirection? = nil) { guard Self.appear(in: block) else { return nil } let text = block.text as NSString var tags: [Tag] = [] @@ -49,9 +59,29 @@ struct DecoratedTags { guard let custom = span.customTag, custom.shapesText else { continue } var textEnd = span.range.upperBound while textEnd > span.range.lowerBound, text.character(at: textEnd - 1) == 0x0A { textEnd -= 1 } - let tag = Tag(range: span.range, textEnd: textEnd, tag: custom, order: order) + var isRightToLeft = false + if let direction { + let tagText = text.substring(with: NSRange(location: span.range.lowerBound, length: span.range.count)) + isRightToLeft = (DirectionScan(tagText).firstStrong ?? direction) == .rightToLeft + } + let tag = Tag(range: span.range, textEnd: textEnd, tag: custom, order: order, isRightToLeft: isRightToLeft) tags.append(tag) guard tag.leadingRoom > 0 else { continue } + if let direction { + // The room on the right of the tag goes on its rightmost + // character. The room on its left goes on the character to + // its left: the one after it in a right-to-left paragraph. + let rightRoom = isRightToLeft ? tag.leadingRoom : tag.padding + let leftRoom = isRightToLeft ? tag.padding : tag.leadingRoom + let rightmost = isRightToLeft ? span.range.lowerBound : textEnd - 1 + let leftNeighbor = direction == .rightToLeft ? textEnd : span.range.lowerBound - 1 + if textEnd > span.range.lowerBound, rightRoom > 0 { kerns[rightmost, default: 0] += rightRoom } + if leftRoom > 0, leftNeighbor >= 0, leftNeighbor < text.length, text.character(at: leftNeighbor) != 0x0A { + kerns[leftNeighbor, default: 0] += leftRoom + } + if direction == .leftToRight, leftRoom > 0 { startPadding[span.range.lowerBound, default: 0] += leftRoom } + continue + } let before = span.range.lowerBound - 1 if before >= 0, text.character(at: before) != 0x0A { kerns[before, default: 0] += tag.leadingRoom } if textEnd > span.range.lowerBound, tag.padding > 0 { kerns[textEnd - 1, default: 0] += tag.padding } @@ -200,14 +230,24 @@ final class LineDecorations: @unchecked Sendable { guard end > start, start - textBase >= 0, start - textBase < text.length else { continue } let isStart = tag.range.lowerBound >= range.lowerBound let isEnd = tag.textEnd <= range.upperBound - // From the glyphs: Core Text puts the caret halfway through - // spacing added after a character, which is where padding is. - let minX = glyphs.start(at: start - indexBase) ?? CTLineGetOffsetForStringIndex(line, start - indexBase, nil) - // At the tag's end, the spacing after its last character is padding, not text. - let maxX = isEnd - ? (glyphs.end(through: end - 1 - indexBase) ?? CTLineGetOffsetForStringIndex(line, end - indexBase, nil)) - - (tags.kerns[end - 1] ?? 0) - : visibleWidth + let minX: CGFloat + let maxX: CGFloat + if tag.isRightToLeft { + // The glyphs of its text, without the spacing on its first + // character, which is padding. Whitespace at the end of the line is left out. + guard let extent = glyphs.extent(of: (start - indexBase)..<(end - indexBase)) else { continue } + minX = max(extent.minX, 0) + maxX = min(extent.maxX - (tags.kerns[start] ?? 0), visibleWidth) + } else { + // From the glyphs: Core Text puts the caret halfway through + // spacing added after a character, which is where padding is. + minX = glyphs.start(at: start - indexBase) ?? CTLineGetOffsetForStringIndex(line, start - indexBase, nil) + // At the tag's end, the spacing after its last character is padding, not text. + maxX = isEnd + ? (glyphs.end(through: end - 1 - indexBase) ?? CTLineGetOffsetForStringIndex(line, end - indexBase, nil)) + - (tags.kerns[end - 1] ?? 0) + : visibleWidth + } guard maxX > minX else { continue } // The tag's own font, which a fallback font for an emoji doesn't change. let font = text.attribute(TranscriptStyle.fontKey, at: start - textBase, effectiveRange: nil).map { $0 as! CTFont } @@ -215,8 +255,10 @@ final class LineDecorations: @unchecked Sendable { let ascent = CTFontGetAscent(font) let descent = CTFontGetDescent(font) let textRect = CGRect(x: minX, y: -ascent, width: maxX - minX, height: ascent + descent) - let left = minX - (isStart ? tags.startPadding(of: tag) : 0) - let right = maxX + (isEnd ? tags.endPadding(of: tag) : 0) + let startPadding = isStart ? tags.startPadding(of: tag) : 0 + let endPadding = isEnd ? tags.endPadding(of: tag) : 0 + let left = minX - (tag.isRightToLeft ? endPadding : startPadding) + let right = maxX + (tag.isRightToLeft ? startPadding : endPadding) let rect = CGRect(x: left, y: -ascent, width: right - left, height: ascent + descent) // An animated tag shows its shapes once it has closed, when its // animation brings them in; until then it is plain text. @@ -235,7 +277,7 @@ final class LineDecorations: @unchecked Sendable { ascent: ascent, descent: descent, xHeight: CTFontGetXHeight(font), capHeight: CTFontGetCapHeight(font), underlineOffset: -CTFontGetUnderlinePosition(font), underlineThickness: CTFontGetUnderlineThickness(font), seed: stableHash(tag.tag.name, tag.range.lowerBound, start), - visibleRect: visible, glyphs: glyphBoxes + visibleRect: visible, glyphs: glyphBoxes, isRightToLeft: tag.isRightToLeft ) let showsShapes = animation == nil || !tag.tag.isOpen if let animation, let key, showsShapes { @@ -258,7 +300,8 @@ final class LineDecorations: @unchecked Sendable { if let image = tag.tag.decoration.image, isStart, showsShapes { // Just before the text, centred on its cap height. let capHeight = CTFontGetCapHeight(font) - let imageRect = CGRect(x: minX - image.gap - image.size.width, y: -capHeight / 2 - image.size.height / 2, + let imageX = tag.isRightToLeft ? maxX + image.gap : minX - image.gap - image.size.width + let imageRect = CGRect(x: imageX, y: -capHeight / 2 - image.size.height / 2, width: image.size.width, height: image.size.height) images.append((imageRect, image, key)) inkTop = min(inkTop, imageRect.minY) @@ -329,6 +372,18 @@ private struct GlyphTable { return found.sorted { $0.stringIndex < $1.stringIndex } } + /// The left edge of the leftmost glyph for a string index in `range`, + /// and the right edge of the rightmost one, its advance included. + func extent(of range: Range) -> (minX: CGFloat, maxX: CGFloat)? { + var result: (minX: CGFloat, maxX: CGFloat)? + for glyph in indices.indices where range.contains(indices[glyph]) { + let minX = positions[glyph] + let maxX = positions[glyph] + advances[glyph] + result = result.map { (min($0.minX, minX), max($0.maxX, maxX)) } ?? (minX, maxX) + } + return result + } + /// The left edge of the first glyph for string index `index` or later. func start(at index: Int) -> CGFloat? { var best: (index: Int, x: CGFloat)? diff --git a/Sources/TranscriptKit/Model/TranscriptShapes.swift b/Sources/TranscriptKit/Model/TranscriptShapes.swift index fa5951b..8d3597c 100644 --- a/Sources/TranscriptKit/Model/TranscriptShapes.swift +++ b/Sources/TranscriptKit/Model/TranscriptShapes.swift @@ -92,11 +92,18 @@ public struct TranscriptFragment: Sendable, Equatable { /// The glyphs of the tag's text on this line, in order, for a tag with /// an animation; empty for other tags. public let glyphs: [TranscriptGlyph] + /// Whether the tag's text is right to left. Then the tag starts at the + /// right end of `rect` and ends at its left end. + public let isRightToLeft: Bool + + /// Whether the tag starts or ends at the left end of `rect`, and at its right end. + var closesLeft: Bool { isRightToLeft ? isEnd : isStart } + var closesRight: Bool { isRightToLeft ? isStart : isEnd } /// Made by layout; public so apps can test their recipes. public init(textRect: CGRect, rect: CGRect, isStart: Bool, isEnd: Bool, ascent: CGFloat, descent: CGFloat, xHeight: CGFloat, capHeight: CGFloat, underlineOffset: CGFloat, underlineThickness: CGFloat, seed: UInt64, - visibleRect: CGRect = .infinite, glyphs: [TranscriptGlyph] = []) { + visibleRect: CGRect = .infinite, glyphs: [TranscriptGlyph] = [], isRightToLeft: Bool = false) { self.textRect = textRect self.rect = rect self.isStart = isStart @@ -110,6 +117,7 @@ public struct TranscriptFragment: Sendable, Equatable { self.seed = seed self.visibleRect = visibleRect self.glyphs = glyphs + self.isRightToLeft = isRightToLeft } } @@ -258,17 +266,17 @@ struct PillRecipe: TranscriptShapeRecipe { // The outline's middle runs half its width inside the box, so the // whole pill stays in `outer`. let box = outer.insetBy(dx: 0, dy: inset) - let left = fragment.isStart ? box.minX + inset : box.minX - let right = fragment.isEnd ? box.maxX - inset : box.maxX + let left = fragment.closesLeft ? box.minX + inset : box.minX + let right = fragment.closesRight ? box.maxX - inset : box.maxX let shape = CGRect(x: left, y: box.minY, width: max(right - left, 0), height: box.height) let radius = min(cornerRadius ?? shape.height / 2, shape.height / 2, shape.width / 2) if let fill { - result.append(TranscriptPath(Self.outline(of: shape, radius: radius, closedLeft: fragment.isStart, - closedRight: fragment.isEnd, forFill: true), fill: fill)) + result.append(TranscriptPath(Self.outline(of: shape, radius: radius, closedLeft: fragment.closesLeft, + closedRight: fragment.closesRight, forFill: true), fill: fill)) } if let border, borderWidth > 0 { - result.append(TranscriptPath(Self.outline(of: shape, radius: radius, closedLeft: fragment.isStart, - closedRight: fragment.isEnd, forFill: false), + result.append(TranscriptPath(Self.outline(of: shape, radius: radius, closedLeft: fragment.closesLeft, + closedRight: fragment.closesRight, forFill: false), stroke: border, lineWidth: borderWidth)) } return result @@ -375,8 +383,8 @@ struct UnderlineRecipe: TranscriptShapeRecipe { let bottom = fragment.descent * 0.55 + offset let top = bottom - height // Overshoots the text a little at the tag's ends, as a quick stroke does. - let start = text.minX - (fragment.isStart ? 2 : 0) - let end = text.maxX + (fragment.isEnd ? 2 : 0) + let start = text.minX - (fragment.closesLeft ? 2 : 0) + let end = text.maxX + (fragment.closesRight ? 2 : 0) let length = max(end - start, 0) let slant: CGFloat = min(3, length / 3) let phase1 = CGFloat(fragment.seed & 0xFFFF) / 0xFFFF * 2 * .pi @@ -396,8 +404,8 @@ struct UnderlineRecipe: TranscriptShapeRecipe { } distances.append(length) let path = CGMutablePath() - let startSlant = fragment.isStart ? slant : 0 - let endSlant = fragment.isEnd ? slant : 0 + let startSlant = fragment.closesLeft ? slant : 0 + let endSlant = fragment.closesRight ? slant : 0 path.move(to: CGPoint(x: start + startSlant, y: topEdge(0))) for d in distances.dropFirst() { path.addLine(to: CGPoint(x: start + min(d, length), y: topEdge(d))) diff --git a/Tests/TranscriptKitTests/DecorationShapeTests.swift b/Tests/TranscriptKitTests/DecorationShapeTests.swift index 478206d..61ff767 100644 --- a/Tests/TranscriptKitTests/DecorationShapeTests.swift +++ b/Tests/TranscriptKitTests/DecorationShapeTests.swift @@ -364,3 +364,84 @@ private struct VisibleArea: TranscriptShapeRecipe { #expect(abs(area.minY - (line.frame.minY - line.baseline - TranscriptPath.maximumOverhang)) < 0.01) } } + +// MARK: Right-to-left text + +@Test func rightToLeftPaddingMakesRoomAndPillsGetTheirBox() throws { + let padded = layout("שאל אנה עכשיו") + let plain = layout("שאל אנה עכשיו") + let line = padded.entry(at: 0).layout.lines[0] + let plainLine = plain.entry(at: 0).layout.lines[0] + #expect(abs(line.frame.width - plainLine.frame.width - 12) < 0.01) + let decorations = try #require(line.decorations) + #expect(decorations.behind.count == 2) + let box = decorations.behind[0].path.boundingBoxOfPath + // Without padding, the name is from the caret after it, on the left, + // to the caret before it, on the right. + let left = CTLineGetOffsetForStringIndex(plainLine.ctLine, 7, nil) + let right = CTLineGetOffsetForStringIndex(plainLine.ctLine, 4, nil) + #expect(abs(box.minX - left) <= 1) + #expect(abs(box.maxX - (right + 12)) <= 1) + let y = line.frame.midY + #expect(padded.link(at: CGPoint(x: line.frame.minX + box.minX + 1, y: y)) == "app://ana") + #expect(padded.link(at: CGPoint(x: line.frame.minX + box.maxX - 1, y: y)) == "app://ana") +} + +@Test func rightToLeftTagInLeftToRightTextGetsRoomOnBothSides() throws { + let padded = layout("Ask אנה now") + let plain = layout("Ask אנה now") + let line = padded.entry(at: 0).layout.lines[0] + let plainLine = plain.entry(at: 0).layout.lines[0] + #expect(abs(line.frame.width - plainLine.frame.width - 12) < 0.01) + let box = try #require(line.decorations).behind[0].path.boundingBoxOfPath + // The glyphs of the name in the line without padding. + var glyphs: [CGFloat] = [] + for run in CTLineGetGlyphRuns(plainLine.ctLine) as! [CTRun] { + let count = CTRunGetGlyphCount(run) + var indices = [CFIndex](repeating: 0, count: count) + var positions = [CGPoint](repeating: .zero, count: count) + var advances = [CGSize](repeating: .zero, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: 0), &indices) + CTRunGetPositions(run, CFRange(location: 0, length: 0), &positions) + CTRunGetAdvances(run, CFRange(location: 0, length: 0), &advances) + for glyph in 0..\(words)סוף זנב", width: 200) + let lines = layout.entry(at: 0).layout.lines.filter { $0.decorations != nil } + try #require(lines.count >= 3) + let rects = lines.map { $0.decorations!.behind[0].path.boundingBoxOfPath } + let fills = lines.compactMap { $0.decorations!.behind[0].fill } + #expect(fills.first == FragmentProbe.start) + #expect(fills.last == FragmentProbe.end) + // The tag starts at the right of its first line and goes on to its left end. + #expect(rects[0].minX < 1) + #expect(rects[0].maxX < lines[0].frame.width - 20) + // It ends on the last line, from the right end of the line. + #expect(abs(rects[rects.count - 1].maxX - lines[lines.count - 1].frame.width) < 1) + #expect(rects[rects.count - 1].minX > 20) +} + +@Test func pillsCloseTheSideWhereARightToLeftTagStarts() { + let rect = CGRect(x: 0, y: -14, width: 40, height: 18) + func fragment(rightToLeft: Bool) -> TranscriptFragment { + TranscriptFragment(textRect: rect, rect: rect, isStart: true, isEnd: false, ascent: 14, descent: 4, xHeight: 8, + capHeight: 11, underlineOffset: 2, underlineThickness: 1, seed: 1, isRightToLeft: rightToLeft) + } + #expect(fragment(rightToLeft: false).closesLeft && !fragment(rightToLeft: false).closesRight) + #expect(fragment(rightToLeft: true).closesRight && !fragment(rightToLeft: true).closesLeft) + let pill = TranscriptDecoration.Shape.pill(fill: indigo) + let ltr = pill.paths(for: fragment(rightToLeft: false))[0].path + let rtl = pill.paths(for: fragment(rightToLeft: true))[0].path + // The closed end is round: its corner is not filled. + #expect(!ltr.contains(CGPoint(x: 0.5, y: -13.5)) && ltr.contains(CGPoint(x: 39.5, y: -13.5))) + #expect(!rtl.contains(CGPoint(x: 39.5, y: -13.5)) && rtl.contains(CGPoint(x: 0.5, y: -13.5))) +} diff --git a/Tests/TranscriptKitTests/TagImageTests.swift b/Tests/TranscriptKitTests/TagImageTests.swift index 6e80218..631394d 100644 --- a/Tests/TranscriptKitTests/TagImageTests.swift +++ b/Tests/TranscriptKitTests/TagImageTests.swift @@ -64,6 +64,28 @@ private func glyphX(_ layout: DocumentLayout, at offset: Int) -> CGFloat { #expect(abs(rect.midY + capHeight / 2) < 0.5) } +@Test func aTagImageSitsOnTheRightOfRightToLeftText() throws { + let image = TranscriptTagImage(square(CGColor(red: 1, green: 0, blue: 0, alpha: 1)), size: CGSize(width: 14, height: 14), gap: 4) + let plain = layout("ראה שישי בקרוב", image: nil) + let laidOut = layout("ראה שישי בקרוב", image: image) + let line = laidOut.entry(at: 0).layout.lines[0] + let rect = try #require(line.decorations?.images.first).rect + // "שישי" starts at offset 4, with its rightmost glyph. The image is + // after that glyph, on its right, past the gap. + let plainLine = plain.entry(at: 0).layout.lines[0] + var advance = CGSize.zero + for run in CTLineGetGlyphRuns(plainLine.ctLine) as! [CTRun] { + let count = CTRunGetGlyphCount(run) + var indices = [CFIndex](repeating: 0, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: count), &indices) + if let found = indices.firstIndex(of: 4) { CTRunGetAdvances(run, CFRange(location: found, length: 1), &advance) } + } + #expect(advance.width > 0) + #expect(abs(rect.minX - (glyphStart(line, at: 4) + advance.width + 4)) < 0.5) + // The room for the image is there: the line is wider by it. + #expect(abs(line.frame.width - plainLine.frame.width - 18) < 0.5) +} + @Test func aTagImageIsDrawn() { let image = TranscriptTagImage(square(CGColor(red: 1, green: 0, blue: 0, alpha: 1)), size: CGSize(width: 14, height: 14), gap: 4) let laidOut = layout("See Friday soon", image: image) From f176cbb737390af9aeb2c82fcc38482f09550990 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:49:33 -0800 Subject: [PATCH 14/14] Keep the shapes of a tag with text in both directions The first and the last character of a tag with text in both directions can be anywhere in it on the screen. Then the edges of its glyphs give its fragment, so its shapes are not dropped. A new test also checks that a streamed right-to-left block with tags is laid out as a block made at once. Co-Authored-By: Claude Opus 5.5 --- .../TranscriptKit/Layout/TagDecorations.swift | 14 ++++++-- .../DecorationShapeTests.swift | 33 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/Sources/TranscriptKit/Layout/TagDecorations.swift b/Sources/TranscriptKit/Layout/TagDecorations.swift index f80fe37..2405f27 100644 --- a/Sources/TranscriptKit/Layout/TagDecorations.swift +++ b/Sources/TranscriptKit/Layout/TagDecorations.swift @@ -38,6 +38,8 @@ struct DecoratedTags { /// that starts there is moved right by it, since there is no character /// before it on the line to carry it. Not in a right-to-left paragraph. let startPadding: [Int: CGFloat] + /// Whether the block has right-to-left text. + let hasRightToLeftText: Bool /// Whether any of the block's tags take padding or draw shapes. static func appear(in block: TranscriptBlock) -> Bool { @@ -90,6 +92,7 @@ struct DecoratedTags { self.tags = tags self.kerns = kerns self.startPadding = startPadding + hasRightToLeftText = direction != nil } /// Whether `inner` is `outer` or inside it. @@ -230,8 +233,8 @@ final class LineDecorations: @unchecked Sendable { guard end > start, start - textBase >= 0, start - textBase < text.length else { continue } let isStart = tag.range.lowerBound >= range.lowerBound let isEnd = tag.textEnd <= range.upperBound - let minX: CGFloat - let maxX: CGFloat + var minX: CGFloat + var maxX: CGFloat if tag.isRightToLeft { // The glyphs of its text, without the spacing on its first // character, which is padding. Whitespace at the end of the line is left out. @@ -247,6 +250,13 @@ final class LineDecorations: @unchecked Sendable { ? (glyphs.end(through: end - 1 - indexBase) ?? CTLineGetOffsetForStringIndex(line, end - indexBase, nil)) - (tags.kerns[end - 1] ?? 0) : visibleWidth + // A tag with text in both directions: its first and last + // characters can be anywhere in it. + if maxX <= minX, tags.hasRightToLeftText, + let extent = glyphs.extent(of: (start - indexBase)..<(end - indexBase)) { + minX = max(extent.minX, 0) + maxX = min(extent.maxX, visibleWidth) + } } guard maxX > minX else { continue } // The tag's own font, which a fallback font for an emoji doesn't change. diff --git a/Tests/TranscriptKitTests/DecorationShapeTests.swift b/Tests/TranscriptKitTests/DecorationShapeTests.swift index 61ff767..acd1f39 100644 --- a/Tests/TranscriptKitTests/DecorationShapeTests.swift +++ b/Tests/TranscriptKitTests/DecorationShapeTests.swift @@ -445,3 +445,36 @@ private struct VisibleArea: TranscriptShapeRecipe { #expect(!ltr.contains(CGPoint(x: 0.5, y: -13.5)) && ltr.contains(CGPoint(x: 39.5, y: -13.5))) #expect(!rtl.contains(CGPoint(x: 39.5, y: -13.5)) && rtl.contains(CGPoint(x: 0.5, y: -13.5))) } + +private let hebrewWords = String(repeating: "מילה ", count: 20) +private let streamedTags: [String] = [ + "פתח \(hebrewWords)סוף זנב ועוד מילים", + "Lead \(hebrewWords)סוף tail", + "פתח abc \(hebrewWords) זנב", +] + +@Test(arguments: streamedTags) +func streamedRightToLeftTagsAreLaidOutAsAWhole(markdown: String) { + var parser = MarkdownStreamParser(idPrefix: "d", tags: shapeTags) + var layout: DocumentLayout? + var text = Substring(markdown) + while !text.isEmpty { + parser.append(String(text.prefix(5))) + text = text.dropFirst(5) + layout = DocumentLayout(document: parser.document, width: 200, reusing: layout) + } + let fresh = DocumentLayout(document: parser.document, width: 200) + func summary(_ layout: DocumentLayout) -> [String] { + layout.entry(at: 0).layout.lines.map { line in + "\(line.range) \(line.frame) " + (line.decorations?.behind.map { "\($0.path.boundingBoxOfPath)" } ?? []).joined() + } + } + #expect(summary(layout!) == summary(fresh)) +} + +@Test func aTagWithTextInBothDirectionsKeepsItsShapes() throws { + let layout = layout("שלום abc אבג וכולם") + let decorations = try #require(layout.entry(at: 0).layout.lines[0].decorations) + #expect(!decorations.behind.isEmpty) + #expect(decorations.behind[0].path.boundingBoxOfPath.width > 20) +}