ChWebsiteApp/CHDataManagement/Generator/Markdown/MarkdownImageProcessor.swift
2025-01-06 10:00:51 +01:00

46 lines
1.5 KiB
Swift

import Ink
struct MarkdownImageProcessor: MarkdownProcessor {
static var modifier: Modifier.Target = .images
private let content: Content
private let results: PageGenerationResults
private let language: ContentLanguage
private let commands: [CommandType : CommandProcessor]
init(content: Content, results: PageGenerationResults, language: ContentLanguage) {
self.content = content
self.results = results
self.language = language
self.commands = CommandType.allCases.reduce(into: [:]) { commands, command in
commands[command] = command.processor.init(content: content, results: results, language: language)
}
}
var html: HtmlCommand {
commands[.includedHtml] as! HtmlCommand
}
func process(html: String, markdown: Substring) -> String {
let argumentList = markdown.between(first: "](", andLast: ")").percentDecoded()
let arguments = argumentList.components(separatedBy: ";")
let rawCommand = markdown.between("![", and: "]").trimmed.percentDecoded()
guard rawCommand != "" else {
return commands[.image]!.process(arguments, markdown: markdown)
}
guard let command = CommandType(rawValue: rawCommand) else {
// Treat unknown commands as normal links
results.invalid(command: nil, markdown)
return html
}
return commands[command]!.process(arguments, markdown: markdown)
}
}