diff --git a/README.md b/README.md index da3fe0b..cbd2f35 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,25 @@ let tags = [ let stream = TranscriptStream(tags: tags) ``` +A tag can also show a small image before its text, such as an icon in a pill. The image takes room after the tag's +padding, so the tag's shapes surround it, and it is centred on the text's cap height. A tint fills the shape of a +template image, such as a symbol: + +```swift +TranscriptTag("chip") { attributes in + TranscriptDecoration( + padding: 6, + shapes: [.pill(fill: TranscriptColor(UIColor.systemGray6))], + image: attributes["symbol"].flatMap { name in + myIcons.cgImage(named: name).map { + TranscriptTagImage($0, size: CGSize(width: 14, height: 14), gap: 4, + tint: TranscriptColor(UIColor.secondaryLabel)) + } + } + ) +} +``` + Tags the app doesn't define show as written. For a shape of your own, implement `TranscriptShapeRecipe`. It returns paths for each line the tag's text is on and may draw a little outside the text, up to 12 points to the sides, past the view's edges. The chat sample has two such shapes, `Zigzag` and `SoftUnderline`, in diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index 511e758..a77356c 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -402,6 +402,34 @@ public final class DocumentLayout: @unchecked Sendable { context.restoreGState() } + /// A line's tag images, clipped like its shapes. + func drawTagImages(of line: BlockLayout.Line, in entry: Entry) { + guard let decorations = line.decorations, !decorations.images.isEmpty else { return } + context.saveGState() + let side = TranscriptPath.maximumSideOverhang + context.clip(to: CGRect(x: -side, y: entry.y + line.frame.minY - decorations.inkAbove, width: entry.layout.width + 2 * side, + height: line.frame.height + decorations.inkAbove + decorations.inkBelow)) + context.translateBy(x: line.frame.minX, y: entry.y + line.baseline) + for item in decorations.images { + if !hiding.isEmpty, let owner = item.tag, hiding.hidesShapes(of: owner) { continue } + context.saveGState() + // The context is y-down; CGContext draws images y-up. + context.translateBy(x: item.rect.minX, y: item.rect.maxY) + context.scaleBy(x: 1, y: -1) + let box = CGRect(origin: .zero, size: item.rect.size) + context.interpolationQuality = .high + if let tint = item.image.tint { + context.clip(to: box, mask: item.image.image) + context.setFillColor(tint.cgColor(dark: dark)) + context.fill(box) + } else { + context.draw(item.image.image, in: box) + } + context.restoreGState() + } + context.restoreGState() + } + /// A line's tag shapes on one layer, clipped to what the line may /// draw, as invalidation knows it. func drawShapes(of line: BlockLayout.Line, in entry: Entry, over: Bool) { @@ -494,7 +522,10 @@ public final class DocumentLayout: @unchecked Sendable { // Behind the text: tags' shapes, so that none covers a glyph of // the line above; then the text; then shapes over it. - for index in visible { drawShapes(of: lines[index], in: entry, over: false) } + for index in visible { + drawShapes(of: lines[index], in: entry, over: false) + drawTagImages(of: lines[index], in: entry) + } switch layout.marker { case .text(let line, let origin)?: diff --git a/Sources/TranscriptKit/Layout/TagDecorations.swift b/Sources/TranscriptKit/Layout/TagDecorations.swift index ee8d11a..a51052b 100644 --- a/Sources/TranscriptKit/Layout/TagDecorations.swift +++ b/Sources/TranscriptKit/Layout/TagDecorations.swift @@ -15,6 +15,8 @@ struct DecoratedTags { let order: Int var padding: CGFloat { tag.decoration.padding } + /// The space before the text: the padding, and the image after it. + var leadingRoom: CGFloat { padding + (tag.decoration.image?.room ?? 0) } } /// Outer tags first. @@ -49,11 +51,11 @@ struct DecoratedTags { 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) tags.append(tag) - guard tag.padding > 0 else { continue } + guard tag.leadingRoom > 0 else { continue } let before = span.range.lowerBound - 1 - if before >= 0, text.character(at: before) != 0x0A { kerns[before, default: 0] += tag.padding } - if textEnd > span.range.lowerBound { kerns[textEnd - 1, default: 0] += tag.padding } - startPadding[span.range.lowerBound, default: 0] += tag.padding + 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 } + startPadding[span.range.lowerBound, default: 0] += tag.leadingRoom } self.tags = tags self.kerns = kerns @@ -69,7 +71,7 @@ struct DecoratedTags { /// The padding a tag's box has at its start: its own and that of the /// tags inside it that start with it. func startPadding(of tag: Tag) -> CGFloat { - tags.reduce(0) { $0 + ($1.range.lowerBound == tag.range.lowerBound && isWithin($1, tag) ? $1.padding : 0) } + tags.reduce(0) { $0 + ($1.range.lowerBound == tag.range.lowerBound && isWithin($1, tag) ? $1.leadingRoom : 0) } } /// The same at its end. @@ -139,9 +141,12 @@ final class LineDecorations: @unchecked Sendable { /// Linked tags with padding, by their box: a tap on the padding belongs /// to the tag, not to the character the spacing was added to. let links: [(rect: CGRect, link: String)] + /// Tag images, where they are drawn, and the animated tag each belongs to. + let images: [(rect: CGRect, image: TranscriptTagImage, tag: TagKey?)] private init(behind: [TranscriptPath], over: [TranscriptPath], behindTags: [TagKey?], overTags: [TagKey?], - animated: [AnimatedFragment], inkAbove: CGFloat, inkBelow: CGFloat, links: [(rect: CGRect, link: String)]) { + animated: [AnimatedFragment], inkAbove: CGFloat, inkBelow: CGFloat, links: [(rect: CGRect, link: String)], + images: [(rect: CGRect, image: TranscriptTagImage, tag: TagKey?)]) { self.behind = behind self.over = over self.behindTags = behindTags @@ -150,6 +155,7 @@ final class LineDecorations: @unchecked Sendable { self.inkAbove = inkAbove self.inkBelow = inkBelow self.links = links + self.images = images } /// The text of the tags in `hidden` on this line, in block offsets. @@ -182,6 +188,7 @@ final class LineDecorations: @unchecked Sendable { var keyed: [(over: Bool, index: Int, key: TagKey)] = [] var animated: [AnimatedFragment] = [] var links: [(rect: CGRect, link: String)] = [] + var images: [(rect: CGRect, image: TranscriptTagImage, tag: TagKey?)] = [] var inkTop = top var inkBottom = bottom for tag in tags.tags where tag.range.lowerBound < range.upperBound && tag.textEnd > range.lowerBound { @@ -242,11 +249,20 @@ final class LineDecorations: @unchecked Sendable { if isOver { over.append(path) } else { behind.append(path) } } } - if let link = tag.tag.decoration.link, tag.padding > 0 { + if let link = tag.tag.decoration.link, tag.leadingRoom > 0 { links.append((rect, link)) } + 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, + width: image.size.width, height: image.size.height) + images.append((imageRect, image, key)) + inkTop = min(inkTop, imageRect.minY) + inkBottom = max(inkBottom, imageRect.maxY) + } } - guard !behind.isEmpty || !over.isEmpty || !links.isEmpty || !animated.isEmpty else { return nil } + guard !behind.isEmpty || !over.isEmpty || !links.isEmpty || !animated.isEmpty || !images.isEmpty else { return nil } var behindTags: [TagKey?] = [] var overTags: [TagKey?] = [] if !keyed.isEmpty { @@ -257,7 +273,8 @@ final class LineDecorations: @unchecked Sendable { } } return LineDecorations(behind: behind, over: over, behindTags: behindTags, overTags: overTags, animated: animated, - inkAbove: min(max(top - inkTop, 0), cap), inkBelow: min(max(inkBottom - bottom, 0), cap), links: links) + inkAbove: min(max(top - inkTop, 0), cap), inkBelow: min(max(inkBottom - bottom, 0), cap), links: links, + images: images) } } diff --git a/Sources/TranscriptKit/Model/TranscriptTag.swift b/Sources/TranscriptKit/Model/TranscriptTag.swift index 53a9aef..0293481 100644 --- a/Sources/TranscriptKit/Model/TranscriptTag.swift +++ b/Sources/TranscriptKit/Model/TranscriptTag.swift @@ -102,9 +102,13 @@ public struct TranscriptDecoration: Equatable, Sendable { /// `TranscriptAnimationRecipe`. Until then the tag's text shows without /// its shapes. public var animation: Animation? + /// A small image before the text, such as an icon in a pill. It sits in + /// the space where the tag starts, after `padding`, so shapes surround it. + public var image: TranscriptTagImage? public init(traits: InlineSpan.Traits = [], foreground: TranscriptColor? = nil, background: TranscriptColor? = nil, - link: String? = nil, padding: CGFloat = 0, shapes: [Shape] = [], animation: Animation? = nil) { + link: String? = nil, padding: CGFloat = 0, shapes: [Shape] = [], animation: Animation? = nil, + image: TranscriptTagImage? = nil) { self.traits = traits self.foreground = foreground self.background = background @@ -112,10 +116,39 @@ public struct TranscriptDecoration: Equatable, Sendable { self.padding = max(padding, 0) self.shapes = shapes self.animation = animation + self.image = image } /// Whether layout has to do anything for it beyond styling the text. - var shapesText: Bool { padding > 0 || !shapes.isEmpty || animation != nil } + var shapesText: Bool { padding > 0 || !shapes.isEmpty || animation != nil || image != nil } +} + +/// A small image before a custom tag's text; see `TranscriptDecoration.image`. +/// It is centred on the text's cap height. A tag with an animation shows its +/// image when it shows its shapes: once the animation has played. +public struct TranscriptTagImage: Equatable, @unchecked Sendable { + public var image: CGImage + /// How large it is drawn, in points. + public var size: CGSize + /// The space between the image and the tag's text. + public var gap: CGFloat + /// A color to fill the image's shape with, for a template image such as + /// a symbol, or nil to draw the image's own colors. + public var tint: TranscriptColor? + + public init(_ image: CGImage, size: CGSize, gap: CGFloat = 4, tint: TranscriptColor? = nil) { + self.image = image + self.size = size + self.gap = max(gap, 0) + self.tint = tint + } + + /// The space the image takes before the text. + var room: CGFloat { size.width + gap } + + public static func == (a: TranscriptTagImage, b: TranscriptTagImage) -> Bool { + a.image === b.image && a.size == b.size && a.gap == b.gap && a.tint == b.tint + } } /// A color for decorations, with a value for light and one for dark diff --git a/Tests/TranscriptKitTests/TagImageTests.swift b/Tests/TranscriptKitTests/TagImageTests.swift new file mode 100644 index 0000000..6e80218 --- /dev/null +++ b/Tests/TranscriptKitTests/TagImageTests.swift @@ -0,0 +1,98 @@ +import CoreGraphics +import CoreText +import Foundation +import Testing +@testable import TranscriptKit + +/// A square of one color. +private func square(_ color: CGColor, side: Int = 28) -> CGImage { + let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: side * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setFillColor(color) + context.fill(CGRect(x: 0, y: 0, width: side, height: side)) + return context.makeImage()! +} + +private func layout(_ markdown: String, image: TranscriptTagImage?, padding: CGFloat = 0) -> DocumentLayout { + let tag = TranscriptTag("chip", TranscriptDecoration(padding: padding, image: image)) + var parser = MarkdownStreamParser(tags: [tag]) + parser.append(markdown) + return DocumentLayout(document: parser.document, width: 300, style: TranscriptStyle()) +} + +/// Where the glyph of UTF-16 offset `offset` starts in `line`, from the line's +/// origin. Not the caret offset: Core Text puts the caret halfway through the +/// spacing added after the character before, which is where a tag's room is. +private func glyphStart(_ line: BlockLayout.Line, at offset: Int) -> CGFloat { + for run in CTLineGetGlyphRuns(line.ctLine) as! [CTRun] { + let count = CTRunGetGlyphCount(run) + var indices = [CFIndex](repeating: 0, count: count) + var positions = [CGPoint](repeating: .zero, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: count), &indices) + CTRunGetPositions(run, CFRange(location: 0, length: count), &positions) + if let found = indices.firstIndex(of: offset - line.indexBase) { return positions[found].x } + } + return .nan +} + +/// The same in the layout's coordinates, on the first line. +private func glyphX(_ layout: DocumentLayout, at offset: Int) -> CGFloat { + let line = layout.entry(at: 0).layout.lines[0] + return line.frame.minX + glyphStart(line, at: offset) +} + +@Test func aTagImageMakesRoomBeforeTheText() { + let image = TranscriptTagImage(square(CGColor(red: 1, green: 0, blue: 0, alpha: 1)), size: CGSize(width: 14, height: 14), gap: 4) + let plain = layout("See Friday soon", image: nil, padding: 2) + let withImage = layout("See Friday soon", image: image, padding: 2) + // "Friday" starts at offset 4. + #expect(abs(glyphX(withImage, at: 4) - glyphX(plain, at: 4) - 18) < 0.5) +} + +@Test func aTagImageSitsBeforeTheTextOnItsCapHeight() throws { + 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) + let line = laidOut.entry(at: 0).layout.lines[0] + let decorations = try #require(line.decorations) + #expect(decorations.images.count == 1) + let rect = decorations.images[0].rect + let textStart = glyphStart(line, at: 4) + #expect(abs(rect.maxX + 4 - textStart) < 1) + #expect(rect.size == CGSize(width: 14, height: 14)) + let capHeight = CTFontGetCapHeight(TranscriptStyle().font(for: .paragraph)) + #expect(abs(rect.midY + capHeight / 2) < 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) + let line = laidOut.entry(at: 0).layout.lines[0] + let rect = line.decorations!.images[0].rect + let scale: CGFloat = 2 + let width = Int((laidOut.width * scale).rounded()) + let height = Int((laidOut.height * scale).rounded()) + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setFillColor(CGColor(gray: 1, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + context.translateBy(x: 0, y: CGFloat(height)) + context.scaleBy(x: scale, y: -scale) + laidOut.draw(in: context, dirtyRect: CGRect(x: 0, y: 0, width: laidOut.width, height: laidOut.height), + text: CGColor(gray: 0, alpha: 1), codeBackground: CGColor(gray: 0.9, alpha: 1), + accent: CGColor(gray: 0.6, alpha: 1), dark: false) + let bytes = UnsafeRawBufferPointer(start: context.data!, count: width * height * 4) + // The image's centre, in the layout, then in the bitmap (rows from the top). + let x = Int(((line.frame.minX + rect.midX) * scale).rounded()) + let y = Int(((laidOut.entry(at: 0).y + line.baseline + rect.midY) * scale).rounded()) + let index = (y * width + x) * 4 + #expect(bytes[index] > 200 && bytes[index + 1] < 60 && bytes[index + 2] < 60) +} + +@Test func aTintedTagImageTakesTheTint() { + let blue = TranscriptColor(red: 0, green: 0, blue: 1) + let image = TranscriptTagImage(square(CGColor(red: 1, green: 0, blue: 0, alpha: 1)), size: CGSize(width: 14, height: 14), tint: blue) + #expect(image.tint == blue) + #expect(image != TranscriptTagImage(image.image, size: image.size)) +}