Repository Public
1// SP Notes iOS2// File: Editor/EditorLayoutFragment.swift3// Description: TextKit 2 layout fragment that draws what is not text around a paragraph: list markers and checkboxes, quote bars,4// callout and code-block backgrounds. Everything is derived from the paragraph's LineStyle attribute.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import UIKit9import SPNotesCore1011final class EditorLayoutFragment: NSTextLayoutFragment {12 var theme = EditorTheme.shared13 /// Style of the neighbouring paragraphs, so boxes (callout, code) join into one shape across paragraphs.14 var joinsPrevious = false15 var joinsNext = false1617 private var paragraphAttributes: (style: LineStyle, ordinal: Int?, isHead: Bool, font: UIFont)? {18 guard let paragraph = textElement as? NSTextParagraph, paragraph.attributedString.length > 0 else { return nil }19 let string = paragraph.attributedString20 guard let style = (string.attribute(.spnLine, at: 0, effectiveRange: nil) as? LineBox)?.style else { return nil }21 let ordinal = (string.attribute(.spnOrdinal, at: 0, effectiveRange: nil) as? NSNumber)?.intValue22 let head = string.attribute(.spnItemHead, at: 0, effectiveRange: nil) != nil23 let font = string.attribute(.font, at: 0, effectiveRange: nil) as? UIFont ?? theme.body24 return (style, ordinal, head, font)25 }2627 /// Decorations are drawn left of the text and across the full width: the surface must cover them.28 override var renderingSurfaceBounds: CGRect {29 let base = super.renderingSurfaceBounds30 let width = max(base.maxX, textLayoutManager?.textContainer?.size.width ?? base.maxX)31 return CGRect(x: min(base.minX, -layoutFragmentFrame.minX), y: min(base.minY, -2), width: width + layoutFragmentFrame.minX + 4, height: max(base.height, layoutFragmentFrame.height) + 4)32 }3334 override func draw(at point: CGPoint, in context: CGContext) {35 if let info = paragraphAttributes {36 context.saveGState()37 drawDecorations(info: info, origin: point, in: context)38 context.restoreGState()39 }40 super.draw(at: point, in: context)41 }4243 private func drawDecorations(info: (style: LineStyle, ordinal: Int?, isHead: Bool, font: UIFont), origin: CGPoint, in context: CGContext) {44 let style = info.style45 let geometry = LineGeometry(style: style, theme: theme)46 let frame = layoutFragmentFrame47 // `origin` is where the fragment's frame origin lands in the context; container x = 0 is at origin.x - frame.minX.48 let containerLeft = origin.x - frame.minX49 let containerWidth = textLayoutManager?.textContainer?.size.width ?? frame.maxX50 let top = origin.y, height = frame.height5152 UIGraphicsPushContext(context)53 defer { UIGraphicsPopContext() }5455 // callout / code box56 if let boxLeft = geometry.boxLeft {57 // the fragment's height includes the spacing after the paragraph: the last paragraph of a box leaves it as a gap below the box58 let rect = CGRect(x: containerLeft + boxLeft, y: top - (joinsPrevious ? 0 : 4), width: containerWidth - boxLeft, height: height + (joinsPrevious ? 0 : 4) - (joinsNext ? 0 : 7))59 var corners: UIRectCorner = []60 if !joinsPrevious { corners.formUnion([.topLeft, .topRight]) }61 if !joinsNext { corners.formUnion([.bottomLeft, .bottomRight]) }62 Self.boxFill(style, theme: theme).setFill()63 UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: 10, height: 10)).fill()64 // 2.0: the icon of the callout (its `icon` attribute, or the kind's default), on its first line; AI blocks are marked65 if !style.isCode, !joinsPrevious, let iconLeft = geometry.calloutIconLeft, let callout = style.callout, let firstLine = textLineFragments.first {66 let midY = top + firstLine.typographicBounds.minY + firstLine.typographicBounds.height / 267 if callout.type == "aiBlock" {68 if let mark = UIImage(systemName: "sparkles", withConfiguration: UIImage.SymbolConfiguration(pointSize: info.font.pointSize * 0.82, weight: .semibold))?.withTintColor(NVUIColor.ai, renderingMode: .alwaysOriginal) {69 mark.draw(at: CGPoint(x: containerLeft + iconLeft, y: midY - mark.size.height / 2))70 }71 // the mandatory visible marker of generated content (compact form of NVAIBadge: « IA »)72 let badge = NSAttributedString(string: String(localized: "IA"), attributes: [.font: UIFont.systemFont(ofSize: 10, weight: .bold), .foregroundColor: NVUIColor.ai])73 let size = badge.size()74 let pill = CGRect(x: rect.maxX - size.width - 20, y: rect.minY + 6, width: size.width + 12, height: size.height + 4)75 NVUIColor.bgElevated.setFill(); UIBezierPath(roundedRect: pill, cornerRadius: pill.height / 2).fill()76 badge.draw(at: CGPoint(x: pill.minX + 6, y: pill.minY + 2))77 } else {78 let icon = Self.calloutIcon(callout)79 let text = NSAttributedString(string: icon, attributes: [.font: UIFont.systemFont(ofSize: info.font.pointSize * 0.95)])80 let size = text.size()81 text.draw(at: CGPoint(x: containerLeft + iconLeft, y: midY - size.height / 2))82 }83 }84 }85 // 2.0: disclosure chevron of a toggle, on its summary line86 if style.type == "detailsSummary", let left = geometry.disclosureLeft, let firstLine = textLineFragments.first {87 let open = style.details?.attrs["open"]?.boolValue == true88 let midY = top + firstLine.typographicBounds.minY + firstLine.typographicBounds.height / 289 if let chevron = UIImage(systemName: open ? "chevron.down" : "chevron.right", withConfiguration: UIImage.SymbolConfiguration(pointSize: info.font.pointSize * 0.72, weight: .bold))?.withTintColor(theme.secondary, renderingMode: .alwaysOriginal) {90 chevron.draw(at: CGPoint(x: containerLeft + left + (theme.disclosureGutter - chevron.size.width) / 2 - 2, y: midY - chevron.size.height / 2))91 }92 }93 // 2.0: label of a footnote, in its gutter94 if style.type == "footnote", let firstLine = textLineFragments.first {95 let label = NSAttributedString(string: (style.attrs["id"]?.stringValue ?? "?") + ".", attributes: [.font: UIFont.monospacedDigitSystemFont(ofSize: info.font.pointSize, weight: .medium), .foregroundColor: theme.accent])96 let size = label.size()97 let midY = top + firstLine.typographicBounds.minY + firstLine.typographicBounds.height / 298 label.draw(at: CGPoint(x: containerLeft + geometry.textIndent - 6 - size.width, y: midY - size.height / 2))99 }100 // quote bars101 for x in geometry.quoteBars {102 theme.quoteBar.setFill()103 UIBezierPath(roundedRect: CGRect(x: containerLeft + x, y: top, width: 3, height: height), cornerRadius: 1.5).fill()104 }105 // list marker on the first paragraph of an item106 guard info.isHead, let item = style.innermostItem, let firstLine = textLineFragments.first else { return }107 let lineHeight = firstLine.typographicBounds.height108 let markerRight = containerLeft + geometry.textIndent - 8109 let midY = top + firstLine.typographicBounds.minY + lineHeight / 2110 if item.type == "taskItem" {111 let side = min(22, max(16, info.font.pointSize * 1.05))112 let rect = CGRect(x: markerRight - side, y: midY - side / 2, width: side, height: side)113 let path = UIBezierPath(roundedRect: rect.insetBy(dx: 1, dy: 1), cornerRadius: side * 0.28)114 if style.isTaskChecked {115 theme.accent.setFill(); path.fill()116 let check = UIBezierPath()117 check.move(to: CGPoint(x: rect.minX + side * 0.27, y: rect.midY + side * 0.02))118 check.addLine(to: CGPoint(x: rect.minX + side * 0.44, y: rect.midY + side * 0.19))119 check.addLine(to: CGPoint(x: rect.minX + side * 0.74, y: rect.midY - side * 0.17))120 UIColor.white.setStroke(); check.lineWidth = 2; check.lineCapStyle = .round; check.lineJoinStyle = .round; check.stroke()121 } else {122 theme.muted.setStroke(); path.lineWidth = 1.6; path.stroke()123 }124 // 2.0: due date / priority badge at the right of the first line (the paragraph style reserves the room)125 if let badge = TaskBadge.attributed(for: style) {126 let size = badge.size()127 let pill = CGRect(x: containerLeft + containerWidth - size.width - 16, y: midY - (size.height + 4) / 2, width: size.width + 14, height: size.height + 4)128 NVUIColor.bgSunken.setFill()129 UIBezierPath(roundedRect: pill, cornerRadius: pill.height / 2).fill()130 badge.draw(at: CGPoint(x: pill.minX + 7, y: pill.minY + 2))131 }132 } else if let ordinal = info.ordinal {133 let text = "\(ordinal)." as NSString134 let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.monospacedDigitSystemFont(ofSize: info.font.pointSize, weight: .regular), .foregroundColor: theme.secondary]135 let size = text.size(withAttributes: attributes)136 text.draw(at: CGPoint(x: markerRight - size.width, y: midY - size.height / 2), withAttributes: attributes)137 } else {138 let depth = style.listDepth139 let radius: CGFloat = max(2.5, info.font.pointSize * 0.17)140 let center = CGPoint(x: markerRight - radius - 2, y: midY)141 let dot = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)142 theme.secondary.setFill(); theme.secondary.setStroke()143 if depth % 2 == 1 { dot.fill() } else { dot.lineWidth = 1.3; dot.stroke() }144 }145 }146147 /// Fill of the box a paragraph sits in: code, an AI block (violet), a callout tinted by its kind, a toggle.148 static func boxFill(_ style: LineStyle, theme: EditorTheme) -> UIColor {149 if style.isCode { return theme.codeBackground }150 guard let callout = style.callout else { return theme.surface }151 if callout.type == "aiBlock" { return NVUIColor.aiSoft }152 switch callout.attrs["kind"]?.stringValue {153 case "warning": return NVUIColor.warning.withAlphaComponent(0.13)154 case "danger": return NVUIColor.danger.withAlphaComponent(0.11)155 case "success": return NVUIColor.success.withAlphaComponent(0.11)156 case "decision", "question", "hypothesis": return NVUIColor.accentSoft157 default: return theme.surface158 }159 }160161 /// The icon of a callout: its `icon` attribute when it has one, else the default of its kind.162 static func calloutIcon(_ callout: Container) -> String {163 if let icon = callout.attrs["icon"]?.stringValue, !icon.isEmpty { return icon }164 return CalloutKind(rawValue: callout.attrs["kind"]?.stringValue ?? "note").defaultIcon165 }166167 /// The zone where a tap opens or closes the toggle this paragraph is the summary of (container coordinates).168 func disclosureHitRect() -> CGRect? {169 guard let info = paragraphAttributes, info.style.type == "detailsSummary" else { return nil }170 let geometry = LineGeometry(style: info.style, theme: theme)171 guard let left = geometry.disclosureLeft else { return nil }172 let frame = layoutFragmentFrame173 return CGRect(x: left - 10, y: frame.minY - 4, width: 44, height: min(frame.height, 36) + 8)174 }175176 /// The zone of the due date / priority badge of this paragraph (container coordinates), if it shows one.177 func taskBadgeHitRect() -> CGRect? {178 guard let info = paragraphAttributes, info.isHead, let reserved = TaskBadge.reservedWidth(for: info.style) else { return nil }179 let frame = layoutFragmentFrame180 let width = textLayoutManager?.textContainer?.size.width ?? frame.maxX181 return CGRect(x: width - reserved - 4, y: frame.minY - 4, width: reserved + 8, height: min(frame.height, 36) + 8)182 }183184 /// The zone where a tap toggles the checkbox of this paragraph (container coordinates), if it shows one.185 func checkboxHitRect() -> CGRect? {186 guard let info = paragraphAttributes, info.isHead, info.style.innermostItem?.type == "taskItem" else { return nil }187 let geometry = LineGeometry(style: info.style, theme: theme)188 let frame = layoutFragmentFrame189 return CGRect(x: geometry.textIndent - 40, y: frame.minY - 4, width: 44, height: min(frame.height, 36) + 8)190 }191}192193/// 2.0: the small badge at the right of a task item that has a due date and / or a priority. State is never said by colour194/// alone: the priority is written with exclamation marks, the date with its day and month.195enum TaskBadge {196 static func dueLabel(_ due: String, now: Date = Date()) -> (text: String, overdue: Bool)? {197 guard let date = TaskItemDetail.date(from: due) else { return nil }198 // a bare day is noon/midnight UTC on the server: show the UTC date part, never shifted by the device's zone199 let isDay = due.utf8.count == 10200 let zone = isDay ? TimeZone(identifier: "UTC") ?? .current : TimeZone.current201 let text = date.formatted(Date.FormatStyle(timeZone: zone).day().month(.abbreviated))202 let overdue = isDay ? due < TaskItemDetail.dayString(now) : date < now203 return (text, overdue)204 }205206 static func marks(_ priority: ItemPriority) -> String {207 switch priority { case .low: "!"; case .medium: "!!"; case .high: "!!!" }208 }209210 static func attributed(for style: LineStyle) -> NSAttributedString? {211 guard style.taskItem != nil else { return nil }212 let priority = style.taskPriority213 let due = style.taskDue.flatMap { dueLabel($0) }214 guard priority != nil || due != nil else { return nil }215 let font = UIFont.preferredFont(forTextStyle: .caption1)216 let bold = UIFontMetrics(forTextStyle: .caption1).scaledFont(for: .systemFont(ofSize: 12, weight: .heavy))217 let out = NSMutableAttributedString()218 if let priority {219 let colour: UIColor = priority == .high ? NVUIColor.dangerText : (priority == .medium ? NVUIColor.warningText : NVUIColor.fgMuted)220 out.append(NSAttributedString(string: marks(priority), attributes: [.font: bold, .foregroundColor: colour]))221 }222 if let due {223 if out.length > 0 { out.append(NSAttributedString(string: " ", attributes: [.font: font])) }224 let done = style.isTaskChecked225 out.append(NSAttributedString(string: due.text, attributes: [.font: font, .foregroundColor: due.overdue && !done ? NVUIColor.dangerText : NVUIColor.fgMuted]))226 }227 return out228 }229230 /// Width to keep free at the right of the item's text; nil when the item shows no badge.231 static func reservedWidth(for style: LineStyle) -> CGFloat? {232 guard let badge = attributed(for: style) else { return nil }233 return ceil(badge.size().width) + 24234 }235}236