SPB Git

Repository Public

BlockLayoutFragment.swift 13.3 KB 179 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/BlockLayoutFragment.swift3// Description: TextKit 2 layout fragment that draws what surrounds a paragraph: list markers, check boxes, quote bars, code / callout / AI panels, the due and priority chips of a task item, the « Généré par IA » marker and the source chips of an AI block.4import AppKit5import SPNotesDesign67/// Small rounded labels drawn by the editor itself (task chips, AI sources).8enum ChipDrawing {9    static var font: NSFont { EditorTheme.uiFont(EditorMetrics.microFontSize, weight: .medium) }10    static func size(of chip: ParaDecoration.Chip) -> CGSize {11        let text = (chip.text as NSString).size(withAttributes: [.font: font]).width12        let icon: CGFloat = chip.symbol == nil ? 0 : EditorMetrics.microFontSize + NVSpace.xxs13        return CGSize(width: ceil(min(text, 220) + icon + EditorMetrics.chipPadding * 2), height: EditorMetrics.chipHeight)14    }15    static func width(of chips: [ParaDecoration.Chip]) -> CGFloat { chips.reduce(0) { $0 + size(of: $1).width } + CGFloat(max(0, chips.count - 1)) * EditorMetrics.chipGap }16    /// Rectangles of the chips laid out from `origin` to the right (or right-aligned to `trailing`).17    static func rects(_ chips: [ParaDecoration.Chip], origin: CGPoint? = nil, trailing: CGPoint? = nil, maxX: CGFloat = .greatestFiniteMagnitude) -> [CGRect] {18        var x = origin?.x ?? ((trailing?.x ?? 0) - width(of: chips)); let y = origin?.y ?? trailing?.y ?? 019        var out: [CGRect] = []20        for c in chips { let s = size(of: c); if x + s.width > maxX { break }; out.append(CGRect(x: x, y: y, width: s.width, height: s.height)); x += s.width + EditorMetrics.chipGap }21        return out22    }23    static func draw(_ chip: ParaDecoration.Chip, in rect: CGRect, fill: NSColor? = nil) {24        (fill ?? chip.tone.fill).setFill(); NSBezierPath(roundedRect: rect, xRadius: EditorMetrics.chipRadius, yRadius: EditorMetrics.chipRadius).fill()25        var x = rect.minX + EditorMetrics.chipPadding26        if let symbol = chip.symbol, let icon = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)?.withSymbolConfiguration(.init(pointSize: EditorMetrics.microFontSize - 2, weight: .semibold)) {27            AtomRenderer.drawTemplate(icon, in: CGRect(x: x, y: rect.midY - icon.size.height / 2, width: icon.size.width, height: icon.size.height), color: chip.tone.foreground)28            x += EditorMetrics.microFontSize + NVSpace.xxs29        }30        let para = NSMutableParagraphStyle(); para.lineBreakMode = .byTruncatingTail31        let s = NSAttributedString(string: chip.text, attributes: [.font: font, .foregroundColor: chip.tone.foreground, .paragraphStyle: para])32        let h = s.size().height33        s.draw(with: CGRect(x: x, y: rect.midY - h / 2, width: rect.maxX - EditorMetrics.chipPadding - x, height: h), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])34    }35}3637final class BlockLayoutFragment: NSTextLayoutFragment {38    var decoration: ParaDecoration?39    var containerWidth: CGFloat = 60040    var fontSize: CGFloat = 164142    /// Drawing happens left of and around the text: the surface covers the full width of the container.43    override var renderingSurfaceBounds: CGRect {44        let base = super.renderingSurfaceBounds45        guard decoration != nil else { return base }46        let full = CGRect(x: -layoutFragmentFrame.minX, y: 0, width: containerWidth, height: layoutFragmentFrame.height)47        return base.union(full)48    }4950    private var paragraphStyle: NSParagraphStyle? {51        let para = (textElement as? NSTextParagraph)?.attributedString52        return para.flatMap { $0.length > 0 ? $0.attribute(.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle : nil }53    }54    private var firstLine: CGRect { textLineFragments.first?.typographicBounds ?? CGRect(x: 0, y: 0, width: 0, height: fontSize * 1.3) }5556    /// Check box rectangle in the fragment's own coordinates (nil when the paragraph has none).57    var checkboxRect: CGRect? {58        guard let d = decoration, case .checkbox = d.marker else { return nil }59        let side = (fontSize * 0.95).rounded()60        return CGRect(x: d.markerX + 3 - layoutFragmentFrame.minX, y: firstLine.midY - side / 2, width: side, height: side)61    }62    /// Due / priority chips of a task item, right-aligned on its first line (fragment coordinates).63    var taskChipRects: [CGRect] {64        guard let d = decoration, !d.taskChips.isEmpty else { return [] }65        let right = containerWidth - layoutFragmentFrame.minX - NVSpace.xs - (d.panel != nil ? EditorMetrics.panelInset : 0)66        return ChipDrawing.rects(d.taskChips, trailing: CGPoint(x: right, y: firstLine.midY - EditorMetrics.chipHeight / 2))67    }68    /// Source chips of an AI block, under its last paragraph (fragment coordinates).69    var aiSourceRects: [CGRect] {70        guard let d = decoration, !d.aiSources.isEmpty else { return [] }71        let x = d.panelX + EditorMetrics.panelInset - layoutFragmentFrame.minX72        let y = layoutFragmentFrame.height - EditorMetrics.panelGap - EditorMetrics.aiFooterHeight + (EditorMetrics.aiFooterHeight - EditorMetrics.chipHeight) / 2 - NVSpace.xxs73        return ChipDrawing.rects(d.aiSources, origin: CGPoint(x: x, y: y), maxX: containerWidth - layoutFragmentFrame.minX - EditorMetrics.panelInset)74    }7576    override func draw(at point: CGPoint, in context: CGContext) {77        if let d = decoration {78            context.saveGState()79            let gc = NSGraphicsContext(cgContext: context, flipped: true)80            NSGraphicsContext.saveGraphicsState(); NSGraphicsContext.current = gc81            let left = point.x - layoutFragmentFrame.minX   // x of the container's left edge82            let height = layoutFragmentFrame.height83            if let panel = d.panel {84                // paragraph spacing lives inside the fragment: the panel leaves the outer gap out at both ends85                let ps = paragraphStyle86                let gap = EditorMetrics.panelGap / 287                let top = d.panelFirst ? max(0, min(ps?.paragraphSpacingBefore ?? 0, EditorMetrics.panelGap) - gap) : 088                let bottom = d.panelLast ? max(0, min(ps?.paragraphSpacing ?? 0, EditorMetrics.panelGap) - gap) : 089                let rect = CGRect(x: left + d.panelX, y: point.y + top, width: containerWidth - d.panelX - NVSpace.xxs, height: height - top - bottom)90                let color: NSColor; var bar: NSColor?91                switch panel {92                case .code: color = EditorTheme.codeBackground93                case .callout(let kind, _): color = EditorTheme.calloutBackground(kind); bar = EditorTheme.calloutTone(kind).hue94                case .ai: color = EditorTheme.aiBackground; bar = EditorTheme.ai95                case .unknown: color = EditorTheme.codeBackground; bar = EditorTheme.strongLine96                }97                var isAI = false; if case .ai = panel { isAI = true }98                let labelColor = isAI ? EditorTheme.ai : EditorTheme.mutedText99                let path = Self.panelPath(rect, top: d.panelFirst, bottom: d.panelLast)100                color.setFill(); path.fill()101                if let bar {102                    // a coloured edge says what kind of block this is without relying on the tint alone103                    NSGraphicsContext.saveGraphicsState(); path.addClip()104                    bar.setFill(); CGRect(x: rect.minX, y: rect.minY, width: EditorMetrics.quoteBarWidth, height: rect.height).fill()105                    NSGraphicsContext.restoreGraphicsState()106                }107                if case .callout(_, let icon) = panel, d.panelFirst, let ix = d.calloutIconX {108                    let s = NSAttributedString(string: icon, attributes: [.font: NSFont.systemFont(ofSize: fontSize)])109                    s.draw(at: CGPoint(x: left + ix, y: point.y + firstLine.midY - s.size().height / 2))110                }111                do {112                    if let header = d.panelHeader {113                        let attrs: [NSAttributedString.Key: Any] = [.font: EditorTheme.uiFont(EditorMetrics.microFontSize, weight: .semibold), .foregroundColor: labelColor, .kern: 0.2]114                        let x = rect.minX + EditorMetrics.panelInset, y = rect.minY + NVSpace.sm115                        if let icon = NSImage(systemSymbolName: isAI ? "sparkles" : "square.dashed", accessibilityDescription: nil)?.withSymbolConfiguration(.init(pointSize: EditorMetrics.microFontSize - 1, weight: .semibold)) {116                            AtomRenderer.drawTemplate(icon, in: CGRect(x: x, y: y + 1, width: icon.size.width, height: icon.size.height), color: labelColor)117                        }118                        (header as NSString).draw(at: CGPoint(x: x + EditorMetrics.microFontSize + NVSpace.xs, y: y), withAttributes: attrs)119                    }120                    for (chip, r) in zip(d.aiSources, aiSourceRects) { ChipDrawing.draw(chip, in: r.offsetBy(dx: point.x, dy: point.y), fill: EditorTheme.surface) }121                }122            }123            for x in d.quoteBars {124                EditorTheme.quoteBar.setFill()125                NSBezierPath(roundedRect: CGRect(x: left + x, y: point.y, width: EditorMetrics.quoteBarWidth, height: height), xRadius: EditorMetrics.quoteBarWidth / 2, yRadius: EditorMetrics.quoteBarWidth / 2).fill()126            }127            if let marker = d.marker {128                let midY = point.y + firstLine.midY129                switch marker {130                case .bullet(let level):131                    let side = max(4.5, fontSize * 0.34); let rect = CGRect(x: left + d.markerX + NVSpace.sm, y: midY - side / 2, width: side, height: side)132                    EditorTheme.mutedText.setFill(); EditorTheme.mutedText.setStroke()133                    switch level % 3 { case 0: NSBezierPath(ovalIn: rect).fill(); case 1: let p = NSBezierPath(ovalIn: rect.insetBy(dx: 0.5, dy: 0.5)); p.lineWidth = 1; p.stroke(); default: NSBezierPath(rect: rect.insetBy(dx: 0.5, dy: 0.5)).fill() }134                case .number(let text):135                    let s = NSAttributedString(string: text, attributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: fontSize * 0.95, weight: .regular), .foregroundColor: EditorTheme.mutedText])136                    let size = s.size()137                    s.draw(at: CGPoint(x: left + d.markerX + EditorMetrics.listIndent - NVSpace.xs - size.width, y: midY - size.height / 2))138                case .checkbox(let on):139                    guard let local = checkboxRect else { break }140                    let rect = local.offsetBy(dx: point.x, dy: point.y)141                    let box = NSBezierPath(roundedRect: rect.insetBy(dx: 0.75, dy: 0.75), xRadius: EditorMetrics.checkboxRadius, yRadius: EditorMetrics.checkboxRadius)142                    if on {143                        EditorTheme.accent.setFill(); box.fill()144                        let tick = NSBezierPath(); tick.lineWidth = 1.7; tick.lineCapStyle = .round; tick.lineJoinStyle = .round145                        tick.move(to: CGPoint(x: rect.minX + rect.width * 0.26, y: rect.midY + rect.height * 0.02))146                        tick.line(to: CGPoint(x: rect.minX + rect.width * 0.44, y: rect.maxY - rect.height * 0.28))147                        tick.line(to: CGPoint(x: rect.maxX - rect.width * 0.24, y: rect.minY + rect.height * 0.3))148                        NSColor.nv(.accentFg).setStroke(); tick.stroke()149                    } else { EditorTheme.strongLine.setStroke(); box.lineWidth = 1.5; box.stroke() }150                case .disclosure:151                    let s = NSAttributedString(string: "▸", attributes: [.font: NSFont.systemFont(ofSize: fontSize * 0.9), .foregroundColor: EditorTheme.mutedText])152                    s.draw(at: CGPoint(x: left + d.markerX + NVSpace.xxs, y: midY - s.size().height / 2))153                }154            }155            for (chip, r) in zip(d.taskChips, taskChipRects) { ChipDrawing.draw(chip, in: r.offsetBy(dx: point.x, dy: point.y)) }156            NSGraphicsContext.restoreGraphicsState()157            context.restoreGState()158        }159        super.draw(at: point, in: context)160    }161162    /// A panel whose corners are rounded only where the block starts and ends (its paragraphs join into one shape).163    private static func panelPath(_ rect: CGRect, top: Bool, bottom: Bool) -> NSBezierPath {164        let r = EditorMetrics.panelRadius165        let tl = top ? r : 0, bl = bottom ? r : 0166        let path = NSBezierPath()167        path.move(to: CGPoint(x: rect.minX + tl, y: rect.minY)); path.line(to: CGPoint(x: rect.maxX - tl, y: rect.minY))168        if tl > 0 { path.curve(to: CGPoint(x: rect.maxX, y: rect.minY + tl), controlPoint1: CGPoint(x: rect.maxX, y: rect.minY), controlPoint2: CGPoint(x: rect.maxX, y: rect.minY)) }169        path.line(to: CGPoint(x: rect.maxX, y: rect.maxY - bl))170        if bl > 0 { path.curve(to: CGPoint(x: rect.maxX - bl, y: rect.maxY), controlPoint1: CGPoint(x: rect.maxX, y: rect.maxY), controlPoint2: CGPoint(x: rect.maxX, y: rect.maxY)) }171        path.line(to: CGPoint(x: rect.minX + bl, y: rect.maxY))172        if bl > 0 { path.curve(to: CGPoint(x: rect.minX, y: rect.maxY - bl), controlPoint1: CGPoint(x: rect.minX, y: rect.maxY), controlPoint2: CGPoint(x: rect.minX, y: rect.maxY)) }173        path.line(to: CGPoint(x: rect.minX, y: rect.minY + tl))174        if tl > 0 { path.curve(to: CGPoint(x: rect.minX + tl, y: rect.minY), controlPoint1: CGPoint(x: rect.minX, y: rect.minY), controlPoint2: CGPoint(x: rect.minX, y: rect.minY)) }175        path.close()176        return path177    }178}179
Files main
Menu

Theme