Repository Public
1// SP Notes iOS2// File: Editor/BlockCard.swift3// Description: The designed card every 3.0 block atom is drawn as inside the text (SPEC §2, §5): a value describing the card4// (icon tile, kicker, title, body items, metadata) and the drawing of that value into a bitmap for a width, an5// appearance and a Dynamic Type size. What goes in a card is decided by `BlockCardBuilder`.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import UIKit1011/// What a block card shows. A value: two equal cards draw the same bitmap (the cache key).12struct BlockCard: Hashable {13 enum Tone: Hashable { case accent, ai, neutral, danger, warning }14 enum TextStyle: Hashable { case body, muted, mono, monoDanger }1516 struct Row: Hashable {17 var leading: String?18 var text: String19 var trailing: String?20 var tone: Tone = .neutral21 }2223 enum Item: Hashable {24 case text(String, style: TextStyle, maxLines: Int)25 /// A picture scaled to the card width (a render, a chart, a page thumbnail). `framed` draws it on a sunken plate.26 case picture(UIImage, maxHeight: CGFloat, framed: Bool)27 /// A tinted line that states a limit or a state (« rendu à mettre à jour depuis le Web »).28 case notice(String, symbol: String, tone: Tone)29 case rows([Row])30 case grid(columns: [String], rows: [[String]])31 case chips([String])32 /// What a tap does, in the accent colour.33 case action(String)34 }3536 var symbol: String37 /// The kind of block, above the title.38 var kicker: String39 var title: String40 var tone: Tone = .accent41 var items: [Item] = []42 /// Small facts under the body, joined with « · ».43 var meta: [String] = []4445 /// Text read by VoiceOver for the attachment.46 var accessibilityText: String {47 var parts = [kicker, title].filter { !$0.isEmpty }48 for item in items {49 switch item {50 case .text(let text, _, _): parts.append(text)51 case .notice(let text, _, _): parts.append(text)52 case .rows(let rows): parts.append(contentsOf: rows.map(\.text))53 case .action(let text): parts.append(text)54 default: break55 }56 }57 parts.append(contentsOf: meta)58 return parts.joined(separator: ", ")59 }60}6162/// Draws cards. Fonts follow the content size of `traits`; colours are the NV tokens resolved for `traits`.63@MainActor64enum BlockCardPainter {65 private struct Fonts {66 let kicker: UIFont, title: UIFont, body: UIFont, small: UIFont, smallBold: UIFont, mono: UIFont67 init(_ traits: UITraitCollection) {68 func style(_ s: UIFont.TextStyle) -> UIFont { UIFont.preferredFont(forTextStyle: s, compatibleWith: traits) }69 kicker = UIFontMetrics(forTextStyle: .caption2).scaledFont(for: .systemFont(ofSize: 11, weight: .semibold), compatibleWith: traits)70 title = UIFontMetrics(forTextStyle: .subheadline).scaledFont(for: .systemFont(ofSize: 15, weight: .semibold), compatibleWith: traits)71 body = style(.subheadline)72 small = style(.caption1)73 smallBold = UIFontMetrics(forTextStyle: .caption1).scaledFont(for: .systemFont(ofSize: 12, weight: .semibold), compatibleWith: traits)74 mono = UIFontMetrics(forTextStyle: .footnote).scaledFont(for: .monospacedSystemFont(ofSize: 12.5, weight: .regular), compatibleWith: traits)75 }76 }7778 private static let padding: CGFloat = 1479 private static let gap: CGFloat = 1080 private static let tile: CGFloat = 3481 private static let radius: CGFloat = 1482 /// Vertical breathing room around the card inside its paragraph.83 private static let outerMargin: CGFloat = 58485 private static func foreground(_ tone: BlockCard.Tone) -> UIColor {86 switch tone {87 case .accent: NVUIColor.accent88 case .ai: NVUIColor.ai89 case .neutral: NVUIColor.fgMuted90 case .danger: NVUIColor.dangerText91 case .warning: NVUIColor.warningText92 }93 }94 private static func soft(_ tone: BlockCard.Tone) -> UIColor {95 switch tone {96 case .accent: NVUIColor.accentSoft97 case .ai: NVUIColor.aiSoft98 case .neutral, .warning: NVUIColor.bgSunken99 case .danger: NVUIColor.danger.withAlphaComponent(0.10)100 }101 }102103 private static func paragraph(_ mode: NSLineBreakMode = .byWordWrapping) -> NSParagraphStyle {104 let p = NSMutableParagraphStyle()105 p.lineBreakMode = mode106 return p107 }108109 private static func attributed(_ text: String, font: UIFont, color: UIColor, mode: NSLineBreakMode = .byWordWrapping) -> NSAttributedString {110 NSAttributedString(string: text, attributes: [.font: font, .foregroundColor: color, .paragraphStyle: paragraph(mode)])111 }112113 private static func height(of string: NSAttributedString, width: CGFloat, maxLines: Int, font: UIFont) -> CGFloat {114 // a little more than n line heights (line fragments carry leading), never enough for n + 1 lines115 let limit = ceil(font.lineHeight * (CGFloat(max(1, maxLines)) + 0.45)) + 1116 let bounds = string.boundingRect(with: CGSize(width: max(10, width), height: limit), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine], context: nil)117 return min(limit, ceil(bounds.height))118 }119120 private static func draw(_ string: NSAttributedString, in rect: CGRect) {121 string.draw(with: rect, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine], context: nil)122 }123124 private static func textAttributes(_ style: BlockCard.TextStyle, _ fonts: Fonts) -> (UIFont, UIColor, NSLineBreakMode) {125 switch style {126 case .body: (fonts.body, NVUIColor.fg, .byWordWrapping)127 case .muted: (fonts.small, NVUIColor.fgMuted, .byWordWrapping)128 case .mono: (fonts.mono, NVUIColor.fg, .byCharWrapping)129 case .monoDanger: (fonts.mono, NVUIColor.dangerText, .byCharWrapping)130 }131 }132133 private static func pictureSize(_ image: UIImage, width: CGFloat, maxHeight: CGFloat) -> CGSize {134 let natural = image.size135 guard natural.width > 0, natural.height > 0 else { return .zero }136 var size = natural.width > width ? CGSize(width: width, height: natural.height * width / natural.width) : natural137 if size.height > maxHeight { size = CGSize(width: size.width * maxHeight / size.height, height: maxHeight) }138 return CGSize(width: max(1, size.width.rounded()), height: max(1, size.height.rounded()))139 }140141 private static func rowHeight(_ fonts: Fonts) -> CGFloat { ceil(fonts.body.lineHeight) + 10 }142 private static func gridRowHeight(_ fonts: Fonts) -> CGFloat { ceil(fonts.small.lineHeight) + 10 }143 private static func chipHeight(_ fonts: Fonts) -> CGFloat { ceil(fonts.smallBold.lineHeight) + 8 }144145 private static func height(of item: BlockCard.Item, width: CGFloat, fonts: Fonts) -> CGFloat {146 switch item {147 case .text(let text, let style, let maxLines):148 let (font, color, mode) = textAttributes(style, fonts)149 let inset: CGFloat = (style == .mono || style == .monoDanger) ? 10 : 0150 return height(of: attributed(text, font: font, color: color, mode: mode), width: width - 2 * inset, maxLines: maxLines, font: font) + 2 * inset151 case .picture(let image, let maxHeight, let framed):152 return pictureSize(image, width: width - (framed ? 16 : 0), maxHeight: maxHeight).height + (framed ? 16 : 0)153 case .notice(let text, _, _):154 return height(of: attributed(text, font: fonts.small, color: NVUIColor.fgMuted), width: width - 20 - 22, maxLines: 4, font: fonts.small) + 14155 case .rows(let rows):156 return CGFloat(rows.count) * rowHeight(fonts)157 case .grid(_, let rows):158 return CGFloat(rows.count + 1) * gridRowHeight(fonts)159 case .chips:160 return chipHeight(fonts)161 case .action:162 return ceil(fonts.title.lineHeight)163 }164 }165166 static func image(_ card: BlockCard, width: CGFloat, traits: UITraitCollection) -> UIImage {167 var result = UIImage()168 traits.performAsCurrent {169 let fonts = Fonts(traits)170 let inner = max(60, width - 2 * padding)171 let headWidth = inner - tile - 10172 let kicker = attributed(card.kicker.uppercased(with: .current), font: fonts.kicker, color: foreground(card.tone == .ai ? .ai : .neutral), mode: .byTruncatingTail)173 let title = attributed(card.title, font: fonts.title, color: NVUIColor.fg, mode: .byWordWrapping)174 let kickerHeight = card.kicker.isEmpty ? 0 : ceil(fonts.kicker.lineHeight)175 let titleHeight = card.title.isEmpty ? 0 : height(of: title, width: headWidth, maxLines: 2, font: fonts.title)176 let headHeight = max(tile, kickerHeight + (kickerHeight > 0 && titleHeight > 0 ? 2 : 0) + titleHeight)177 let itemHeights = card.items.map { height(of: $0, width: inner, fonts: fonts) }178 let meta = attributed(card.meta.joined(separator: " · "), font: fonts.small, color: NVUIColor.fgMuted)179 let metaHeight = card.meta.isEmpty ? 0 : height(of: meta, width: inner, maxLines: 3, font: fonts.small)180 var total = padding + headHeight181 for h in itemHeights { total += gap + h }182 if metaHeight > 0 { total += gap + metaHeight }183 total += padding184 let size = CGSize(width: width, height: ceil(total) + 2 * outerMargin)185 let format = UIGraphicsImageRendererFormat(for: traits)186 format.opaque = false187 result = UIGraphicsImageRenderer(size: size, format: format).image { context in188 let cg = context.cgContext189 let frame = CGRect(x: 0.5, y: outerMargin + 0.5, width: width - 1, height: ceil(total) - 1)190 let shape = UIBezierPath(roundedRect: frame, cornerRadius: radius)191 // card elevation: a 1 px shadow under the hairline192 cg.saveGState()193 cg.setShadow(offset: CGSize(width: 0, height: 1), blur: 2, color: UIColor.black.withAlphaComponent(traits.userInterfaceStyle == .dark ? 0.35 : 0.06).cgColor)194 NVUIColor.bgElevated.setFill(); shape.fill()195 cg.restoreGState()196 NVUIColor.line.setStroke(); shape.lineWidth = 1; shape.stroke()197198 let left = padding199 var y = outerMargin + padding200 // icon tile201 let tileRect = CGRect(x: left, y: y, width: tile, height: tile)202 soft(card.tone).setFill()203 UIBezierPath(roundedRect: tileRect, cornerRadius: 9).fill()204 let tint = foreground(card.tone)205 if let icon = UIImage(systemName: card.symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 15, weight: .semibold))?.withTintColor(tint, renderingMode: .alwaysOriginal) {206 icon.draw(at: CGPoint(x: tileRect.midX - icon.size.width / 2, y: tileRect.midY - icon.size.height / 2))207 }208 // kicker + title, centred on the tile when shorter209 let textX = left + tile + 10210 var textY = y + max(0, (headHeight - (kickerHeight + (kickerHeight > 0 && titleHeight > 0 ? 2 : 0) + titleHeight)) / 2)211 if kickerHeight > 0 { draw(kicker, in: CGRect(x: textX, y: textY, width: headWidth, height: kickerHeight)); textY += kickerHeight + (titleHeight > 0 ? 2 : 0) }212 if titleHeight > 0 { draw(title, in: CGRect(x: textX, y: textY, width: headWidth, height: titleHeight)) }213 y += headHeight214215 for (item, itemHeight) in zip(card.items, itemHeights) {216 y += gap217 draw(item, in: CGRect(x: left, y: y, width: inner, height: itemHeight), fonts: fonts, context: cg)218 y += itemHeight219 }220 if metaHeight > 0 {221 y += gap222 draw(meta, in: CGRect(x: left, y: y, width: inner, height: metaHeight))223 }224 }225 }226 return result227 }228229 private static func draw(_ item: BlockCard.Item, in rect: CGRect, fonts: Fonts, context cg: CGContext) {230 switch item {231 case .text(let text, let style, _):232 let (font, color, mode) = textAttributes(style, fonts)233 if style == .mono || style == .monoDanger {234 (style == .monoDanger ? soft(.danger) : NVUIColor.bgSunken).setFill()235 UIBezierPath(roundedRect: rect, cornerRadius: 8).fill()236 draw(attributed(text, font: font, color: color, mode: mode), in: rect.insetBy(dx: 10, dy: 10))237 } else {238 draw(attributed(text, font: font, color: color, mode: mode), in: rect)239 }240 case .picture(let image, let maxHeight, let framed):241 let available = rect.width - (framed ? 16 : 0)242 let size = pictureSize(image, width: available, maxHeight: maxHeight)243 if framed {244 NVUIColor.bgSunken.setFill()245 UIBezierPath(roundedRect: rect, cornerRadius: 10).fill()246 }247 let target = CGRect(x: rect.minX + (rect.width - size.width) / 2, y: rect.minY + (framed ? 8 : 0), width: size.width, height: size.height)248 cg.saveGState()249 UIBezierPath(roundedRect: target, cornerRadius: framed ? 4 : 8).addClip()250 image.draw(in: target)251 cg.restoreGState()252 case .notice(let text, let symbol, let tone):253 soft(tone).setFill()254 UIBezierPath(roundedRect: rect, cornerRadius: 8).fill()255 let color = tone == .neutral ? NVUIColor.fgMuted : foreground(tone)256 if let icon = UIImage(systemName: symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 12, weight: .semibold))?.withTintColor(color, renderingMode: .alwaysOriginal) {257 icon.draw(at: CGPoint(x: rect.minX + 10, y: rect.minY + 7 + (fonts.small.lineHeight - icon.size.height) / 2))258 }259 draw(attributed(text, font: fonts.small, color: tone == .ai ? NVUIColor.ai : NVUIColor.fgMuted), in: CGRect(x: rect.minX + 30, y: rect.minY + 7, width: rect.width - 42, height: rect.height - 14))260 case .rows(let rows):261 let h = rowHeight(fonts)262 for (index, row) in rows.enumerated() {263 let rowRect = CGRect(x: rect.minX, y: rect.minY + CGFloat(index) * h, width: rect.width, height: h)264 if index > 0 { NVUIColor.line.setFill(); UIRectFill(CGRect(x: rowRect.minX, y: rowRect.minY, width: rowRect.width, height: 1)) }265 var x = rowRect.minX266 var right = rowRect.maxX267 if let leading = row.leading, !leading.isEmpty {268 let lead = attributed(leading, font: fonts.mono, color: row.tone == .ai ? NVUIColor.ai : NVUIColor.fgMuted, mode: .byTruncatingTail)269 let w = min(rect.width * 0.3, ceil(lead.size().width))270 draw(lead, in: CGRect(x: x, y: rowRect.midY - fonts.mono.lineHeight / 2, width: w, height: ceil(fonts.mono.lineHeight)))271 x += w + 8272 }273 if let trailing = row.trailing, !trailing.isEmpty {274 let trail = attributed(trailing, font: fonts.small, color: NVUIColor.fgMuted, mode: .byTruncatingTail)275 let w = min(rect.width * 0.4, ceil(trail.size().width))276 draw(trail, in: CGRect(x: right - w, y: rowRect.midY - fonts.small.lineHeight / 2, width: w, height: ceil(fonts.small.lineHeight)))277 right -= w + 8278 }279 let color: UIColor = row.tone == .ai ? NVUIColor.ai : (row.tone == .danger ? NVUIColor.dangerText : NVUIColor.fg)280 draw(attributed(row.text, font: fonts.body, color: color, mode: .byTruncatingTail), in: CGRect(x: x, y: rowRect.midY - fonts.body.lineHeight / 2, width: max(10, right - x), height: ceil(fonts.body.lineHeight)))281 }282 case .grid(let columns, let rows):283 let h = gridRowHeight(fonts)284 let count = max(1, columns.count)285 let columnWidth = rect.width / CGFloat(count)286 NVUIColor.bgSunken.setFill()287 UIBezierPath(roundedRect: CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: h), cornerRadius: 6).fill()288 for (c, name) in columns.enumerated() {289 draw(attributed(name, font: fonts.smallBold, color: NVUIColor.fgMuted, mode: .byTruncatingTail), in: CGRect(x: rect.minX + CGFloat(c) * columnWidth + 8, y: rect.minY + 5, width: columnWidth - 12, height: ceil(fonts.smallBold.lineHeight)))290 }291 for (r, row) in rows.enumerated() {292 let y = rect.minY + CGFloat(r + 1) * h293 if r > 0 { NVUIColor.line.setFill(); UIRectFill(CGRect(x: rect.minX, y: y, width: rect.width, height: 1)) }294 for c in 0..<count where c < row.count {295 draw(attributed(row[c], font: fonts.small, color: NVUIColor.fg, mode: .byTruncatingTail), in: CGRect(x: rect.minX + CGFloat(c) * columnWidth + 8, y: y + 5, width: columnWidth - 12, height: ceil(fonts.small.lineHeight)))296 }297 }298 case .chips(let chips):299 var x = rect.minX300 for chip in chips {301 let text = attributed(chip, font: fonts.smallBold, color: NVUIColor.fgMuted, mode: .byTruncatingTail)302 let w = min(ceil(text.size().width) + 16, rect.maxX - x)303 guard w > 28 else { break }304 let chipRect = CGRect(x: x, y: rect.minY, width: w, height: rect.height)305 NVUIColor.bgSunken.setFill()306 UIBezierPath(roundedRect: chipRect, cornerRadius: rect.height / 2).fill()307 draw(text, in: CGRect(x: chipRect.minX + 8, y: chipRect.minY + 4, width: w - 16, height: ceil(fonts.smallBold.lineHeight)))308 x += w + 6309 }310 case .action(let text):311 let label = attributed(text, font: fonts.title, color: NVUIColor.accent, mode: .byTruncatingTail)312 let w = min(ceil(label.size().width), rect.width - 18)313 draw(label, in: CGRect(x: rect.minX, y: rect.minY, width: w, height: rect.height))314 if let chevron = UIImage(systemName: "chevron.right", withConfiguration: UIImage.SymbolConfiguration(pointSize: 11, weight: .semibold))?.withTintColor(NVUIColor.accent, renderingMode: .alwaysOriginal) {315 chevron.draw(at: CGPoint(x: rect.minX + w + 5, y: rect.midY - chevron.size.height / 2))316 }317 }318 }319}320