CHGenerator/WebsiteGenerator/Generators/MarkdownProcessor.swift
2022-08-18 08:49:01 +02:00

126 lines
4.8 KiB
Swift

import Foundation
import Ink
import Splash
struct PageContentGenerator {
private let factory: TemplateFactory
private let files: FileProcessor
private let swift = SyntaxHighlighter(format: HTMLOutputFormat())
init(factory: TemplateFactory, files: FileProcessor) {
self.factory = factory
self.files = files
}
func generate(page: Page, language: String, at url: URL) throws -> String {
var errorToThrow: Error? = nil
let content = try wrap(.missingPage(page: url.path, language: language)) {
try String(contentsOf: url)
}
var hasCodeContent = false
let imageModifier = Modifier(target: .images) { html, markdown in
do {
return try processMarkdownImage(markdown: markdown, html: html, page: page)
} catch {
errorToThrow = error
return ""
}
}
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 hightlighting if code samples are found")
}
let result = parser.html(from: content)
if let error = errorToThrow {
throw error
}
return result
}
private func processMarkdownImage(markdown: Substring, html: String, page: Page) throws -> 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 files.mediaType(forExtension: fileExtension) {
case .image:
return try handleImage(page: page, file: file, rightTitle: title, leftTitle: alt)
case .video:
return try handleVideo(page: page, file: file, optionString: alt)
case .file:
#warning("Handle other files in markdown")
print("[WARN] Unhandled file \(file) with extension \(fileExtension)")
return ""
}
}
private func handleImage(page: Page, file: String, rightTitle: String?, leftTitle: String?) throws -> String {
let imagePath = page.pathRelativeToRootForContainedInputFile(file)
#warning("Specify page image width in configuration")
let pageImageWidth = 748
let size = try files.requireImage(source: imagePath, destination: imagePath, width: pageImageWidth)
let imagePath2x = imagePath.insert("@2x", beforeLast: ".")
let file2x = file.insert("@2x", beforeLast: ".")
try 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: Page, file: String, optionString: String?) throws -> 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)
}
}