SPB Git

Repository Public

AtomRenderer+Cards.swift 4.7 KB 93 lines swift

1// SP Notes iOS2// File: Editor/AtomRenderer+Cards.swift3// Description: The 3.0 atoms of the renderer: block cards (built by `BlockCardBuilder`, painted by `BlockCardPainter`, cached by4//              card value + width + appearance + Dynamic Type size) and the inline citation chip.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import UIKit1011@MainActor12enum BlockCardCache {13    struct Key: Hashable {14        var card: BlockCard15        var width: Int16        var dark: Bool17        var category: String18        var scale: Int19    }20    private static var images: [Key: UIImage] = [:]21    private static var order: [Key] = []22    private static var bytes = 023    /// Budget of the cache: decoded bitmaps are large (a card at 3× is a few megabytes).24    static let byteBudget = 64 << 2025    /// Number of bitmaps actually painted (tests check that an unchanged card is not painted twice).26    private(set) static var paintCount = 027    private static var memoryObserver: NSObjectProtocol?2829    private static func cost(_ image: UIImage) -> Int { Int(image.size.width * image.scale) * Int(image.size.height * image.scale) * 4 }3031    static func image(for card: BlockCard, width: CGFloat, traits: UITraitCollection) -> UIImage {32        let key = Key(card: card, width: Int((width * 2).rounded()), dark: traits.userInterfaceStyle == .dark,33                      category: traits.preferredContentSizeCategory.rawValue, scale: Int(traits.displayScale))34        if let cached = images[key] { return cached }35        if memoryObserver == nil {36            memoryObserver = NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: .main) { _ in37                MainActor.assumeIsolated { removeAll(); ChartSnapshot.removeAll() }38            }39        }40        let image = BlockCardPainter.image(card, width: width, traits: traits)41        image.accessibilityLabel = card.accessibilityText   // what VoiceOver reads for the attachment42        paintCount += 143        images[key] = image44        order.append(key)45        bytes += cost(image)46        // the oldest bitmaps go first; the attachments that show them keep their own reference47        while bytes > byteBudget, order.count > 1 {48            let oldest = order.removeFirst()49            if let removed = images.removeValue(forKey: oldest) { bytes -= cost(removed) }50        }51        return image52    }5354    static func removeAll() { images.removeAll(); order.removeAll(); bytes = 0 }55    static var cachedBytes: Int { bytes }56}5758extension AtomRenderer {59    /// The card of a 3.0 block, or the neutral card of an unknown block.60    func renderCard(_ node: PMNode, width: CGFloat) -> UIImage? {61        let traits = self.traits ?? .current62        // a block of a type this app does not know: the same card design, neutral and read-only63        guard let typed = node.typed else { return BlockCardCache.image(for: BlockCardBuilder.unknown(node), width: width, traits: traits) }64        let provider = imageProvider65        cards.imageProvider = provider66        guard let card = BlockCardBuilder.card(for: typed, width: width, traits: traits, store: cards) else { return nil }67        return BlockCardCache.image(for: card, width: width, traits: traits)68    }6970    /// The description of the card of a block, for accessibility and tests.71    func card(for node: PMNode, width: CGFloat = 360) -> BlockCard? {72        guard let typed = node.typed else { return nil }73        cards.imageProvider = imageProvider74        return BlockCardBuilder.card(for: typed, width: width, traits: traits ?? .current, store: cards)75    }7677    /// `[label, locator]` in an accent chip: an inline citation (tappable like every atom).78    func citationChip(_ node: PMNode, font: UIFont) -> (UIImage, CGFloat) {79        let text = "[" + (CitationInline(node: node)?.displayText ?? "?") + "]"80        let chipFont = font.withSize(max(11, font.pointSize * 0.86))81        let attributes: [NSAttributedString.Key: Any] = [.font: chipFont, .foregroundColor: NVUIColor.accent]82        let textSize = (text as NSString).size(withAttributes: attributes)83        let size = CGSize(width: ceil(textSize.width) + 10, height: ceil(font.lineHeight))84        let format = UIGraphicsImageRendererFormat(for: traits ?? .current)85        let image = UIGraphicsImageRenderer(size: size, format: format).image { _ in86            NVUIColor.accentSoft.setFill()87            UIBezierPath(roundedRect: CGRect(origin: .zero, size: size).insetBy(dx: 0, dy: 1.5), cornerRadius: 6).fill()88            (text as NSString).draw(at: CGPoint(x: 5, y: (size.height - textSize.height) / 2), withAttributes: attributes)89        }90        return (image, -font.descender)91    }92}93
Files main
Menu

Theme