CHGenerator/WebsiteGenerator/Generators/MarkdownProcessor.swift
Christoph Hagen 80d3c08a93 Update generation
- Move to global objects for files and validation
- Only write changed files
- Check images for changes before scaling
- Simplify code
2022-08-26 17:40:51 +02:00

128 lines
4.9 KiB
Swift

import Foundation
import Ink
import Splash
struct PageContentGenerator {
#warning("Specify page image width in configuration")
let pageImageWidth = 748
private let factory: TemplateFactory
private let swift = SyntaxHighlighter(format: HTMLOutputFormat())
init(factory: TemplateFactory) {
self.factory = factory
}
func generate(page: Element, language: String, content: String) -> String {
var hasCodeContent = false
let imageModifier = Modifier(target: .images) { html, markdown in
processMarkdownImage(markdown: markdown, html: html, page: page)
}
let codeModifier = Modifier(target: .codeBlocks) { html, markdown in
if markdown.starts(with: "```swift") {
let code = markdown.between("```swift", and: "```").trimmed
return "<pre><code>" + swift.highlight(code) + "</pre></code>"
}
hasCodeContent = true
return html
}
let linkModifier = Modifier(target: .links) { html, markdown in
#warning("Check links in markdown for (missing) files to copy")
return html
}
let parser = MarkdownParser(modifiers: [imageModifier, codeModifier, linkModifier])
if hasCodeContent {
#warning("Automatically add hljs highlighting if code samples are found")
}
return parser.html(from: content)
}
private func processMarkdownImage(markdown: Substring, html: String, page: Element) -> String {
// Split the markdown ![alt](file "title")
// For images: ![left_title](file "right_title")
// For videos: ![option...](file)
// For files: ?
let fileAndTitle = markdown.between("(", and: ")")
let file = fileAndTitle.dropAfterFirst(" \"")
let title = fileAndTitle.contains(" \"") ? fileAndTitle.between("\"", and: "\"").nonEmpty : nil
let alt = markdown.between("[", and: "]").nonEmpty
let fileExtension = file.lastComponentAfter(".").lowercased()
switch MediaType(fileExtension: fileExtension) {
case .image:
return handleImage(page: page, file: file, rightTitle: title, leftTitle: alt)
case .video:
return handleVideo(page: page, file: file, optionString: alt)
case .file:
if fileExtension == "svg" {
return handleSvg(page: page, file: file)
}
return handleFile(page: page, file: file, fileExtension: fileExtension)
}
}
private func handleImage(page: Element, file: String, rightTitle: String?, leftTitle: String?) -> String {
let imagePath = page.pathRelativeToRootForContainedInputFile(file)
let size = files.requireImage(source: imagePath, destination: imagePath, width: pageImageWidth)
let imagePath2x = imagePath.insert("@2x", beforeLast: ".")
let file2x = file.insert("@2x", beforeLast: ".")
files.requireImage(source: imagePath, destination: imagePath2x, width: 2 * pageImageWidth)
let content: [PageImageTemplate.Key : String] = [
.image: file,
.image2x: file2x,
.width: "\(Int(size.width))",
.height: "\(Int(size.height))",
.leftText: leftTitle ?? "",
.rightText: rightTitle ?? ""]
return factory.image.generate(content)
}
private func handleVideo(page: Element, file: String, optionString: String?) -> String {
let options: [PageVideoTemplate.VideoOption] = optionString.unwrapped { string in
string.components(separatedBy: " ").compactMap { optionText in
guard let optionText = optionText.trimmed.nonEmpty else {
return nil
}
guard let option = PageVideoTemplate.VideoOption(rawValue: optionText) else {
print("[WARN] Unknown video option \(optionText) in page \(page.path)")
return nil
}
return option
}
} ?? []
#warning("Check page folder for alternative video versions")
let sources: [PageVideoTemplate.VideoSource] = [(url: file, type: .mp4)]
let filePath = page.pathRelativeToRootForContainedInputFile(file)
files.require(file: filePath)
return factory.video.generate(sources: sources, options: options)
}
private func handleSvg(page: Element, file: String) -> String {
let imagePath = page.pathRelativeToRootForContainedInputFile(file)
files.require(file: imagePath)
return """
<span class="image">
<img src="\(file)"/>
</span>
"""
}
private func handleFile(page: Element, file: String, fileExtension: String) -> String {
#warning("Handle other files in markdown")
print("[WARN] Unhandled file \(file) with extension \(fileExtension)")
return ""
}
}