CHGenerator/WebsiteGenerator/Generators/MarkdownProcessor.swift

170 lines
7.0 KiB
Swift
Raw Normal View History

2022-08-16 10:39:05 +02:00
import Foundation
import Ink
2022-08-18 08:49:01 +02:00
import Splash
2022-08-16 10:39:05 +02:00
struct PageContentGenerator {
2022-08-18 08:49:36 +02:00
#warning("Specify page image width in configuration")
let pageImageWidth = 748
private let factory: TemplateFactory
2022-08-18 08:49:01 +02:00
private let swift = SyntaxHighlighter(format: HTMLOutputFormat())
init(factory: TemplateFactory) {
self.factory = factory
2022-08-16 10:39:05 +02:00
}
2022-08-29 13:35:25 +02:00
func generate(page: Element, language: String, content: String) -> (content: String, includesCode: Bool) {
2022-08-16 10:39:05 +02:00
var hasCodeContent = false
let imageModifier = Modifier(target: .images) { html, markdown in
processMarkdownImage(markdown: markdown, html: html, page: page)
2022-08-16 10:39:05 +02:00
}
let codeModifier = Modifier(target: .codeBlocks) { html, markdown in
if markdown.starts(with: "```swift") {
2022-08-18 08:49:01 +02:00
let code = markdown.between("```swift", and: "```").trimmed
return "<pre><code>" + swift.highlight(code) + "</pre></code>"
2022-08-16 10:39:05 +02:00
}
hasCodeContent = true
return html
}
let linkModifier = Modifier(target: .links) { html, markdown in
2022-08-29 13:35:25 +02:00
let file = markdown.between("(", and: ")")
if let filePath = page.nonAbsolutePathRelativeToRootForContainedInputFile(file) {
// The target of the page link must be present after generation is complete
files.expect(file: filePath, source: page.path)
}
return html
}
2022-08-29 13:35:25 +02:00
let htmlModifier = Modifier(target: .html) { html, markdown in
//print("[HTML] Found in page \(page.path):")
//print(markdown)
// Thinks to check
// <img src=
// <a href=
//
return html
2022-08-16 10:39:05 +02:00
}
2022-08-29 13:35:25 +02:00
let parser = MarkdownParser(modifiers: [imageModifier, codeModifier, linkModifier, htmlModifier])
return (parser.html(from: content), hasCodeContent)
2022-08-16 10:39:05 +02:00
}
private func processMarkdownImage(markdown: Substring, html: String, page: Element) -> String {
2022-08-29 13:35:25 +02:00
// Split the markdown ![alt](file title)
// For images: ![left_title](file right_title)
// For videos: ![option1,option2,...](file)
// For svg with custom area: ![x,y,width,height](file.svg)
// For downloads: ![download](file1,text1;file2,text2, ...)
// For files: ?
let fileAndTitle = markdown.between("(", and: ")")
let alt = markdown.between("[", and: "]").nonEmpty
2022-08-29 13:35:25 +02:00
if alt == "download" {
return handleDownloadButtons(page: page, content: fileAndTitle)
}
let file = fileAndTitle.dropAfterFirst(" ")
let title = fileAndTitle.contains(" ") ? fileAndTitle.dropBeforeFirst(" ").nonEmpty : nil
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)
2022-08-29 13:35:25 +02:00
case .svg:
return handleSvg(page: page, file: file, area: alt)
case .file:
return handleFile(page: page, file: file, fileExtension: fileExtension)
2022-08-16 10:39:05 +02:00
}
}
2022-08-16 10:39:05 +02:00
private func handleImage(page: Element, file: String, rightTitle: String?, leftTitle: String?) -> String {
2022-08-16 10:39:05 +02:00
let imagePath = page.pathRelativeToRootForContainedInputFile(file)
let size = files.requireImage(source: imagePath, destination: imagePath, width: pageImageWidth)
2022-08-16 10:39:05 +02:00
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)
2022-08-16 10:39:05 +02:00
}
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 {
2022-08-29 13:35:25 +02:00
log.add(warning: "Unknown video option \(optionText)", source: page.path)
return nil
}
return option
}
} ?? []
#warning("Check page folder for alternative video versions")
let sources: [PageVideoTemplate.VideoSource] = [(url: file, type: .mp4)]
2022-08-16 10:39:05 +02:00
let filePath = page.pathRelativeToRootForContainedInputFile(file)
files.require(file: filePath)
return factory.video.generate(sources: sources, options: options)
2022-08-16 10:39:05 +02:00
}
2022-08-18 08:49:36 +02:00
2022-08-29 13:35:25 +02:00
private func handleSvg(page: Element, file: String, area: String?) -> String {
2022-08-18 08:49:36 +02:00
let imagePath = page.pathRelativeToRootForContainedInputFile(file)
files.require(file: imagePath)
2022-08-29 13:35:25 +02:00
guard let area = area else {
return factory.html.svgImage(file: file)
}
let parts = area.components(separatedBy: ",")
guard parts.count == 4,
let x = Int(parts[0]),
let y = Int(parts[1]),
let width = Int(parts[2]),
let height = Int(parts[3]) else {
log.add(warning: "Invalid area string for svg image", source: page.path)
return factory.html.svgImage(file: file)
}
return factory.html.svgImage(file: file, x: x, y: y, width: width, height: height)
2022-08-18 08:49:36 +02:00
}
private func handleFile(page: Element, file: String, fileExtension: String) -> String {
2022-08-29 13:35:25 +02:00
log.add(warning: "Unhandled file \(file) with extension \(fileExtension)", source: page.path)
2022-08-18 08:49:36 +02:00
return ""
}
2022-08-29 13:35:25 +02:00
private func handleDownloadButtons(page: Element, content: String) -> String {
let buttons = content
.components(separatedBy: ";")
.compactMap { button -> (file: String, text: String, downloadName: String?)? in
let parts = button.components(separatedBy: ",")
guard parts.count == 2 || parts.count == 3 else {
log.add(warning: "Invalid button definition", source: page.path)
return nil
}
let file = parts[0].trimmed
let title = parts[1].trimmed
let downloadName = parts.count == 3 ? parts[2].trimmed : nil
// Ensure that file is available
let filePath = page.pathRelativeToRootForContainedInputFile(file)
files.require(file: filePath)
return (file, title, downloadName)
}
return factory.html.downloadButtons(buttons)
}
2022-08-16 10:39:05 +02:00
}