Files
helder/Sources/HelderUI/Editor/MarkdownPreviewView.swift
2026-10-05 10:32:09 +02:00

356 lines
15 KiB
Swift

import AppKit
import HelderCore
import SwiftUI
/// The rendered Markdown document: read-only, derived from the live buffer.
struct MarkdownPreviewView: View {
let editor: EditorStore
let path: String
let text: String
var body: some View {
let blocks = MarkdownParser.parse(text, baseDir: PathUtils.dirname(path))
ScrollView {
MarkdownBlocks(blocks: blocks, editor: editor)
.frame(maxWidth: MarkdownStyle.measure, alignment: .leading)
.padding(EdgeInsets(top: 18, leading: 20, bottom: 48, trailing: 20))
.frame(maxWidth: .infinity, alignment: .leading)
.textSelection(.enabled)
.background(PointerTextRegion())
}
.background(Palette.editor)
.environment(\.openURL, OpenURLAction { url in open(url) })
}
/// Web links go to the browser; a link to a file in the project opens it in the editor.
private func open(_ url: URL) -> OpenURLAction.Result {
if url.scheme == MarkdownStyle.fileScheme {
let path = String(url.absoluteString.dropFirst(MarkdownStyle.fileScheme.count + 1)).removingPercentEncoding ?? ""
if !path.isEmpty { editor.open(path) }
return .handled
}
guard let scheme = url.scheme?.lowercased(), ["http", "https", "mailto"].contains(scheme) else { return .discarded }
NSWorkspace.shared.open(url)
return .handled
}
}
enum MarkdownStyle {
/// About 68 characters of 14pt Plex Sans.
static let measure: CGFloat = 580
static let fileScheme = "helder-file"
static let body = Typography.body
static let bodyLineSpacing: CGFloat = 14 * 1.7 - 18
static func heading(_ level: Int) -> TypeRole {
switch level {
case 1, 2: Typography.markdownH2
case 3: Typography.markdownH3
case 4: TypeRole(.monoBold, 15, lineHeight: 18)
default: TypeRole(.monoBold, 13, lineHeight: 16)
}
}
/// Block margins; neighbours collapse to the larger one.
static func margins(_ block: MarkdownBlock) -> (top: CGFloat, bottom: CGFloat) {
switch block {
case let .heading(level, _):
let size = heading(level).size
return (1.6 * size, 0.6 * size)
case .paragraph, .list, .table: return (14, 14)
case .quote, .code: return (16.8, 16.8)
case .rule: return (22.4, 22.4)
}
}
}
/// A run of blocks with collapsed margins between them.
struct MarkdownBlocks: View {
let blocks: [MarkdownBlock]
let editor: EditorStore
var quoted = false
var body: some View {
VStack(alignment: .leading, spacing: 0) {
ForEach(Array(blocks.enumerated()), id: \.offset) { index, block in
MarkdownBlockView(block: block, editor: editor, quoted: quoted)
.padding(.top, index == 0 ? firstTop(block) : max(MarkdownStyle.margins(blocks[index - 1]).bottom, MarkdownStyle.margins(block).top))
}
}
}
private func firstTop(_ block: MarkdownBlock) -> CGFloat {
if case let .heading(level, _) = block { return 0.2 * MarkdownStyle.heading(level).size }
return 0
}
}
private struct MarkdownBlockView: View {
let block: MarkdownBlock
let editor: EditorStore
let quoted: Bool
var body: some View {
switch block {
case let .heading(level, content):
let role = MarkdownStyle.heading(level)
VStack(alignment: .leading, spacing: 8) {
Text(MarkdownInlines.attributed(content, style: .heading(role)))
.typeRole(role)
.foregroundStyle(Palette.text1)
.fixedSize(horizontal: false, vertical: true)
if level == 3 { Rectangle().fill(Palette.raised).frame(height: Metrics.hairline) }
}
case let .paragraph(content):
if case let .image(alt, source, _)? = content.first, content.count == 1 {
MarkdownImage(alt: alt, source: source, editor: editor)
} else {
paragraph(content)
}
case let .code(language, text):
ScrollView(.horizontal, showsIndicators: false) {
Text(MarkdownInlines.highlighted(text, language: language))
.font(Typography.code.font)
.lineSpacing(20 - 17)
.fixedSize()
.padding(EdgeInsets(top: 14, leading: 16, bottom: 14, trailing: 16))
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(Palette.panel, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
case let .quote(blocks):
HStack(alignment: .top, spacing: 16) {
Rectangle().fill(Palette.amber).frame(width: Metrics.accentRule)
MarkdownBlocks(blocks: blocks, editor: editor, quoted: true)
}
.fixedSize(horizontal: false, vertical: true)
case let .list(ordered, items):
VStack(alignment: .leading, spacing: 7) {
ForEach(Array(items.enumerated()), id: \.offset) { index, item in
HStack(alignment: .firstTextBaseline, spacing: 10) {
Text(ordered ? "\(index + 1)." : "—")
.typeRole(MarkdownStyle.body)
.foregroundStyle(Palette.amber)
.frame(minWidth: 12, alignment: .leading)
paragraph(item)
}
}
}
case let .table(header, alignments, rows):
MarkdownTable(header: header, alignments: alignments, rows: rows)
case .rule:
Rectangle().fill(Palette.raised).frame(height: Metrics.hairline)
}
}
private func paragraph(_ content: [MarkdownInline]) -> some View {
Text(MarkdownInlines.attributed(content, style: quoted ? .quote : .body))
.typeRole(quoted ? Typography.markdownQuote : MarkdownStyle.body)
.lineSpacing(MarkdownStyle.bodyLineSpacing)
.foregroundStyle(quoted ? Palette.amberSoft : Palette.text2)
.fixedSize(horizontal: false, vertical: true)
}
}
private struct MarkdownTable: View {
let header: [[MarkdownInline]]
let alignments: [TableAlignment?]
let rows: [[[MarkdownInline]]]
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {
GridRow {
ForEach(Array(header.enumerated()), id: \.offset) { column, cell in
Text(MarkdownInlines.attributed(cell, style: .tableHeader))
.typeRole(Typography.panelLabel)
.foregroundStyle(Palette.text4)
.padding(EdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 14))
.frame(maxWidth: .infinity, alignment: alignment(column))
.background(Palette.panel)
.gridColumnAlignment(horizontal(column))
}
}
ForEach(Array(rows.enumerated()), id: \.offset) { _, row in
Rectangle().fill(Palette.raised).frame(height: Metrics.hairline).gridCellUnsizedAxes(.horizontal)
GridRow {
ForEach(Array(row.enumerated()), id: \.offset) { column, cell in
Text(MarkdownInlines.attributed(cell, style: .body))
.typeRole(Typography.row)
.foregroundStyle(Palette.text3)
.padding(EdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 14))
.frame(maxWidth: .infinity, alignment: alignment(column))
}
}
}
}
.fixedSize()
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).stroke(Palette.raised, lineWidth: Metrics.hairline))
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
}
}
private func alignment(_ column: Int) -> Alignment {
switch column < alignments.count ? alignments[column] : nil {
case .center: .center
case .right: .trailing
default: .leading
}
}
private func horizontal(_ column: Int) -> HorizontalAlignment {
switch column < alignments.count ? alignments[column] : nil {
case .center: .center
case .right: .trailing
default: .leading
}
}
}
/// A block image: a project file read through the file service, or a remote URL.
private struct MarkdownImage: View {
let alt: String
let source: ImageSource
let editor: EditorStore
@State private var data: Data?
@State private var failed = false
var body: some View {
Group {
switch source {
case let .remote(url):
AsyncImage(url: url) { phase in
if let image = phase.image {
image.resizable().aspectRatio(contentMode: .fit)
} else {
altText
}
}
case let .local(path):
if let data, let image = NSImage(data: data) {
Image(nsImage: image).resizable().aspectRatio(contentMode: .fit)
.frame(maxWidth: image.size.width)
} else {
altText.task(id: path) {
data = await editor.readImage(path)
failed = data == nil
}
}
}
}
.clipShape(RoundedRectangle(cornerRadius: Metrics.radiusSmall))
.accessibilityLabel(alt)
}
private var altText: some View {
Text(alt.isEmpty ? "—" : alt).typeRole(Typography.path).foregroundStyle(Palette.text3)
}
}
/// Inline runs as one AttributedString, so a paragraph wraps and selects as a single text.
enum MarkdownInlines {
enum Style {
case body
case quote
case heading(TypeRole)
case tableHeader
var role: TypeRole {
switch self {
case .body: MarkdownStyle.body
case .quote: Typography.markdownQuote
case let .heading(role): role
case .tableHeader: Typography.panelLabel
}
}
}
static func attributed(_ inlines: [MarkdownInline], style: Style) -> AttributedString {
var out = AttributedString()
append(inlines, to: &out, style: style, strong: false, emphasis: false)
return out
}
private static func append(_ inlines: [MarkdownInline], to out: inout AttributedString, style: Style,
strong: Bool, emphasis: Bool, link: URL? = nil, strike: Bool = false) {
for inline in inlines {
switch inline {
case let .text(text):
var run = AttributedString(text)
run.font = font(style: style, strong: strong, emphasis: emphasis)
if strong { run.foregroundColor = Palette.text1 }
if let link {
run.link = link
run.foregroundColor = Palette.amber
}
if strike { run.strikethroughStyle = .single }
out += run
case let .code(code):
var run = AttributedString("\u{2009}" + code + "\u{2009}")
run.font = Typography.code.font
run.foregroundColor = Palette.amberSoft
run.backgroundColor = Palette.panel
if let link { run.link = link }
out += run
case let .strong(children):
append(children, to: &out, style: style, strong: true, emphasis: emphasis, link: link, strike: strike)
case let .emphasis(children):
append(children, to: &out, style: style, strong: strong, emphasis: true, link: link, strike: strike)
case let .strikethrough(children):
append(children, to: &out, style: style, strong: strong, emphasis: emphasis, link: link, strike: true)
case let .link(children, url, _):
append(children, to: &out, style: style, strong: strong, emphasis: emphasis, link: linkURL(url), strike: strike)
case let .image(alt, _, _):
var run = AttributedString(alt)
run.font = Typography.path.font
run.foregroundColor = Palette.text4
out += run
}
}
}
/// Relative links point into the project; they get a private scheme the preview opens in the editor.
static func linkURL(_ raw: String) -> URL? {
guard let safe = MarkdownParser.safeURL(raw), !safe.hasPrefix("#") else { return nil }
if MarkdownParser.isLocalURL(safe) {
let encoded = safe.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? safe
return URL(string: MarkdownStyle.fileScheme + ":" + encoded)
}
return URL(string: safe)
}
private static func font(style: Style, strong: Bool, emphasis: Bool) -> Font {
switch style {
case .heading, .tableHeader:
return style.role.font
case .quote:
return Typography.markdownQuote.font
case .body:
if emphasis { return Typography.markdownQuote.nsFont.withSize(14).swiftUIFont }
return (strong ? Typography.rowSelected.nsFont : MarkdownStyle.body.nsFont).withSize(14).swiftUIFont
}
}
/// Fenced code with the six syntax colours, flat weight.
static func highlighted(_ text: String, language: Language?) -> AttributedString {
let ns = text as NSString
let colored = NSMutableAttributedString(string: text, attributes: [.foregroundColor: EditorColors.syntax(.plain)])
if let language {
for token in SyntaxHighlighter.tokens(for: text, language: language) where token.role != .plain {
let range = NSIntersectionRange(NSRange(location: token.location, length: token.length), NSRange(location: 0, length: ns.length))
colored.addAttribute(.foregroundColor, value: EditorColors.syntax(token.role), range: range)
}
}
var out = AttributedString(text)
colored.enumerateAttribute(.foregroundColor, in: NSRange(location: 0, length: ns.length)) { value, range, _ in
guard let color = value as? NSColor, let bounds = Range(range, in: out) else { return }
out[bounds].foregroundColor = Color(nsColor: color)
}
return out
}
}
private extension NSFont {
var swiftUIFont: Font { Font(self) }
}