Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerText/MarkdownPresentation.swift
T
schihei a3e544fbe4 feat(panel): close with Esc without a click and render Markdown
Esc: make the panel key when shown (closeWithEscape, default on) without activating the app; the source app stays frontmost and Replace still targets it. Handle Esc with SwiftUI's exit command, which also works from the popover and after clicking controls. Add TranslationPanel.canBecomeKey and amend ADR-009.\n\nMarkdown: add MarkdownPresentation in SprachmittlerText (Foundation inline parser plus a conservative block parser for headings, lists, quotes, fenced code and rules), a SwiftUI MarkdownTranslationView, and a renderMarkdown setting (default on). JSON, HTML and code sources are never rendered; only http/https links open; images become alt text; Copy and Replace keep the raw Markdown (ADR-021).\n\nVerified: make verify green; synthetic Esc closes the panel and closes an open language popover first; a live Markdown translation rendered heading, bold/italic, inline code, list, quote, code block and link; Copy returned the raw Markdown; Replace still changed the TextEdit selection with the panel key.
2026-11-26 15:26:30 +01:00

270 lines
10 KiB
Swift

import Foundation
/// A block-level element produced by the conservative Markdown presentation parser.
///
/// The cases carry raw inline Markdown; the app parses that with
/// ``MarkdownPresentation/inline(_:)``. The parser is presentation-only: it never changes the
/// translation that is validated, copied or inserted.
public enum MarkdownBlock: Equatable, Sendable {
/// A paragraph, with soft line breaks preserved.
case paragraph(String)
/// An ATX heading (`#`…`######`).
case heading(level: Int, text: String)
/// One list item. `indent` is a display indentation in steps, `number` is the ordinal for ordered lists.
case listItem(ordered: Bool, number: Int, indent: Int, text: String)
/// A block quote, with one level of `>` removed.
case quote(String)
/// A fenced code block.
case codeBlock(language: String?, text: String)
/// A thematic break (`---`, `***`, `___`).
case rule
}
/// Presentation-only Markdown parsing for the translation panel.
///
/// Inline formatting comes from Foundation's Markdown parser. Block structure is parsed here with a
/// deliberately small set of rules: anything that is not recognised stays visible as plain text
/// rather than being silently dropped.
public enum MarkdownPresentation {
private static let classifier = ContentClassifier()
private static let inlineDetectionPatterns = [
#"\*\*[^*\n]+\*\*"#,
#"(?<![\w*])\*[^*\s][^*\n]*\*(?![\w*])"#,
#"(?<![\w_])__[^_\n]+__(?![\w_])"#,
#"~~[^~\n]+~~"#,
#"`[^`\n]+`"#,
#"\[[^\]\n]+\]\([^)\s]+\)"#,
]
/// Whether the panel should render this source/translation pair as Markdown.
///
/// JSON, HTML and code are never rendered as Markdown, so their text is not mangled. Plain or
/// delimiter-heavy text is rendered only when it contains Markdown inline markers.
public static func shouldRender(source: String, translation: String) -> Bool {
let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return false }
switch classifier.classify(trimmed) {
case .json, .html, .code:
return false
case .markdown:
return true
case .plain, .delimited:
break
}
return hasInlineMarkdown(trimmed) || hasInlineMarkdown(translation)
}
/// Splits `markdown` into display blocks. Unknown constructs stay in a paragraph.
public static func blocks(in markdown: String) -> [MarkdownBlock] {
let normalized = markdown
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
let lines = normalized.components(separatedBy: "\n")
var blocks: [MarkdownBlock] = []
var paragraph: [String] = []
var index = 0
func flushParagraph() {
guard !paragraph.isEmpty else { return }
let text = paragraph.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
if !text.isEmpty {
blocks.append(.paragraph(text))
}
paragraph.removeAll()
}
while index < lines.count {
let raw = lines[index]
let line = raw.trimmingCharacters(in: .whitespaces)
if line.isEmpty {
flushParagraph()
index += 1
} else if let fence = fenceMarker(line) {
flushParagraph()
blocks.append(fencedBlock(lines, index: &index, opening: line, fence: fence))
} else if let heading = heading(in: raw) {
flushParagraph()
blocks.append(heading)
index += 1
} else if isRule(line) {
flushParagraph()
blocks.append(.rule)
index += 1
} else if line.hasPrefix(">") {
flushParagraph()
blocks.append(quoteBlock(lines, index: &index))
} else if let item = listItem(in: raw) {
flushParagraph()
blocks.append(item)
index += 1
} else {
paragraph.append(line)
index += 1
}
}
flushParagraph()
return blocks
}
private static func fencedBlock(
_ lines: [String],
index: inout Int,
opening: String,
fence: (marker: Character, count: Int)
) -> MarkdownBlock {
var code: [String] = []
var closed = false
index += 1
while index < lines.count, !isClosingFence(lines[index], marker: fence.marker) {
code.append(lines[index])
index += 1
}
if index < lines.count {
index += 1
closed = true
}
let info = opening.dropFirst(fence.count).trimmingCharacters(in: .whitespaces)
let language = info.split(separator: " ").first.map(String.init)
var text = code.joined(separator: "\n")
if !closed {
text = text.trimmingCharacters(in: .newlines)
}
return .codeBlock(language: language, text: text)
}
private static func quoteBlock(_ lines: [String], index: inout Int) -> MarkdownBlock {
var quote: [String] = []
while index < lines.count {
let line = lines[index].trimmingCharacters(in: .whitespaces)
guard line.hasPrefix(">") else { break }
var content = String(line.dropFirst())
if content.hasPrefix(" ") {
content.removeFirst()
}
quote.append(content)
index += 1
}
return .quote(quote.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines))
}
/// Parses one inline Markdown fragment. Images are reduced to their alt text so no attachment
/// or remote resource can be requested; malformed input falls back to plain text.
public static func inline(_ text: String) -> AttributedString {
let cleaned = strippingImages(text)
let options = AttributedString.MarkdownParsingOptions(
interpretedSyntax: .inlineOnlyPreservingWhitespace,
failurePolicy: .returnPartiallyParsedIfPossible
)
if let attributed = try? AttributedString(markdown: cleaned, options: options) {
return attributed
}
return AttributedString(cleaned)
}
/// Only explicit web links may be opened. `file:`, `javascript:`, `data:` and app schemes stay inert.
public static func isAllowedLink(_ url: URL) -> Bool {
guard let scheme = url.scheme?.lowercased(), let host = url.host, !host.isEmpty else {
return false
}
return scheme == "http" || scheme == "https"
}
private static func hasInlineMarkdown(_ text: String) -> Bool {
inlineDetectionPatterns.contains { pattern in
text.range(of: pattern, options: .regularExpression) != nil
}
}
private static func strippingImages(_ text: String) -> String {
var result = text.replacingOccurrences(
of: #"!\[([^\]]*)\]\([^)]*\)"#,
with: "$1",
options: .regularExpression
)
result = result.replacingOccurrences(
of: #"<img\b[^>]*>"#,
with: "",
options: [.regularExpression, .caseInsensitive]
)
return result
}
private static func fenceMarker(_ line: String) -> (marker: Character, count: Int)? {
let stripped = line.drop(while: { $0 == " " })
guard let first = stripped.first, first == "`" || first == "~" else { return nil }
let count = stripped.prefix(while: { $0 == first }).count
guard count >= 3 else { return nil }
return (first, count)
}
private static func isClosingFence(_ line: String, marker: Character) -> Bool {
let stripped = line.trimmingCharacters(in: .whitespaces)
guard stripped.count >= 3 else { return false }
return stripped.allSatisfy { $0 == marker }
}
private static func heading(in raw: String) -> MarkdownBlock? {
let leading = raw.prefix(while: { $0 == " " }).count
guard leading <= 3 else { return nil }
let trimmed = raw.dropFirst(leading)
let hashes = trimmed.prefix(while: { $0 == "#" }).count
guard (1 ... 6).contains(hashes) else { return nil }
let rest = trimmed.dropFirst(hashes)
guard rest.isEmpty || rest.first == " " || rest.first == "\t" else { return nil }
var text = rest.trimmingCharacters(in: .whitespaces)
if text.hasSuffix("#") {
text = String(text.reversed().drop(while: { $0 == "#" }).reversed())
.trimmingCharacters(in: .whitespaces)
}
return .heading(level: hashes, text: text)
}
private static func isRule(_ line: String) -> Bool {
let compact = line.replacingOccurrences(of: " ", with: "")
guard compact.count >= 3, let first = compact.first, "-*_".contains(first) else {
return false
}
return compact.allSatisfy { $0 == first }
}
private static func listItem(in raw: String) -> MarkdownBlock? {
var columns = 0
for character in raw {
if character == " " {
columns += 1
} else if character == "\t" {
columns += 4
} else {
break
}
}
let indent = min(columns / 2, 8)
let trimmed = raw.trimmingCharacters(in: .whitespaces)
if let first = trimmed.first, "-*+".contains(first) {
let rest = trimmed.dropFirst()
guard rest.first == " " || rest.first == "\t" else { return nil }
let text = rest.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil }
return .listItem(ordered: false, number: 0, indent: indent, text: text)
}
let digits = trimmed.prefix(while: { $0.isNumber })
guard !digits.isEmpty, digits.count <= 9 else { return nil }
let afterDigits = trimmed.dropFirst(digits.count)
guard let delimiter = afterDigits.first, delimiter == "." || delimiter == ")" else {
return nil
}
let rest = afterDigits.dropFirst()
guard rest.first == " " || rest.first == "\t", let number = Int(digits) else { return nil }
let text = rest.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil }
return .listItem(ordered: true, number: number, indent: indent, text: text)
}
}