CHGenerator/Sources/Generator/Generators/MarkdownProcessor.swift

298 lines
13 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 {
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
2022-09-25 17:19:07 +02:00
processMarkdownImage(markdown: markdown, html: html, page: page, language: language)
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-31 00:02:42 +02:00
handleLink(page: page, language: language, html: html, markdown: markdown)
}
2022-08-29 13:35:25 +02:00
let htmlModifier = Modifier(target: .html) { html, markdown in
2022-08-31 00:02:42 +02:00
handleHTML(page: page, language: language, html: html, markdown: markdown)
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
}
2022-08-31 00:02:42 +02:00
private func handleLink(page: Element, language: String, html: String, markdown: Substring) -> String {
let file = markdown.between("(", and: ")")
if file.hasPrefix("page:") {
let pageId = file.replacingOccurrences(of: "page:", with: "")
guard let pagePath = files.getPage(for: pageId) else {
log.add(warning: "Page id '\(pageId)' not found", source: page.path)
// Remove link since the page can't be found
return markdown.between("[", and: "]")
}
let fullPath = pagePath + Element.htmlPagePathAddition(for: language)
// Adjust file path to get the page url
2022-09-04 17:47:35 +02:00
let url = page.relativePathToOtherSiteElement(file: fullPath)
2022-08-31 00:02:42 +02:00
return html.replacingOccurrences(of: file, with: url)
}
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
}
private func handleHTML(page: Element, language: String, html: String, markdown: Substring) -> String {
#warning("Check HTML code in markdown for required resources")
//print("[HTML] Found in page \(page.path):")
//print(markdown)
// Things to check:
// <img src=
// <a href=
//
return html
}
2022-09-25 17:19:07 +02:00
private func processMarkdownImage(markdown: Substring, html: String, page: Element, language: String) -> String {
2022-08-29 13:35:25 +02:00
// Split the markdown ![alt](file title)
2022-09-18 17:49:50 +02:00
// There are several known shorthand commands
2022-08-29 13:35:25 +02:00
// For images: ![left_title](file right_title)
// For videos: ![option1,option2,...](file)
// For svg with custom area: ![x,y,width,height](file.svg)
2022-09-04 17:48:13 +02:00
// For downloads: ![download](file1, text1; file2, text2, ...)
2022-09-18 17:21:57 +02:00
// For a simple boxes: ![box](title;body)
2022-09-25 17:19:07 +02:00
// A fancy page link: ![page](page_id)
2022-09-04 17:48:13 +02:00
// External pages: ![external](url1, text1; url2, text2, ...)
let fileAndTitle = markdown.between("(", and: ")")
let alt = markdown.between("[", and: "]").nonEmpty
2022-09-18 17:49:50 +02:00
if let alt = alt, let command = ShorthandMarkdownKey(rawValue: alt) {
2022-09-25 17:19:07 +02:00
return handleShortHandCommand(command, page: page, language: language, content: fileAndTitle)
2022-08-30 11:29:53 +02:00
}
2022-08-29 13:35:25 +02:00
let file = fileAndTitle.dropAfterFirst(" ")
let title = fileAndTitle.contains(" ") ? fileAndTitle.dropBeforeFirst(" ").nonEmpty : nil
let fileExtension = file.lastComponentAfter(".").lowercased()
2022-08-29 18:57:37 +02:00
if let _ = ImageType(fileExtension: fileExtension) {
return handleImage(page: page, file: file, rightTitle: title, leftTitle: alt)
2022-08-29 18:57:37 +02:00
}
if let _ = VideoType(rawValue: fileExtension) {
return handleVideo(page: page, file: file, optionString: alt)
2022-08-29 18:57:37 +02:00
}
if fileExtension == "svg" {
2022-08-29 13:35:25 +02:00
return handleSvg(page: page, file: file, area: alt)
2022-08-16 10:39:05 +02:00
}
2022-08-29 18:57:37 +02:00
return handleFile(page: page, file: file, fileExtension: fileExtension)
}
2022-08-16 10:39:05 +02:00
2022-09-25 17:19:07 +02:00
private func handleShortHandCommand(_ command: ShorthandMarkdownKey, page: Element, language: String, content: String) -> String {
2022-09-18 17:49:50 +02:00
switch command {
case .downloadButtons:
return handleDownloadButtons(page: page, content: content)
case .externalLink:
return handleExternalButtons(page: page, content: content)
case .includedHtml:
return handleExternalHTML(page: page, file: content)
case .box:
return handleSimpleBox(page: page, content: content)
2022-09-25 17:19:07 +02:00
case .pageLink:
return handlePageLink(page: page, language: language, pageId: content)
2022-09-18 17:49:50 +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)
2022-09-18 16:47:13 +02:00
let size = files.requireImage(
source: imagePath,
destination: imagePath,
requiredBy: page.path,
width: configuration.pageImageWidth)
2022-08-16 10:39:05 +02:00
let imagePath2x = imagePath.insert("@2x", beforeLast: ".")
let file2x = file.insert("@2x", beforeLast: ".")
2022-09-18 16:47:13 +02:00
files.requireImage(
source: imagePath,
destination: imagePath2x,
requiredBy: page.path,
width: 2 * configuration.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)
}
2022-08-31 00:02:42 +02:00
let parts = area.components(separatedBy: ",").map { $0.trimmed }
2022-08-29 13:35:25 +02:00
guard parts.count == 4,
2022-09-04 17:48:13 +02:00
let x = Int(parts[0].trimmed),
let y = Int(parts[1].trimmed),
let width = Int(parts[2].trimmed),
let height = Int(parts[3].trimmed) else {
2022-08-29 13:35:25 +02:00
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-30 11:29:53 +02:00
private func handleExternalButtons(page: Element, content: String) -> String {
let buttons = content
.components(separatedBy: ";")
.compactMap { button -> (url: String, text: String)? in
let parts = button.components(separatedBy: ",")
guard parts.count == 2 else {
log.add(warning: "Invalid external link definition", source: page.path)
return nil
}
let url = parts[0].trimmed
let title = parts[1].trimmed
return (url, title)
}
return factory.html.externalButtons(buttons)
}
2022-09-08 13:12:55 +02:00
private func handleExternalHTML(page: Element, file: String) -> String {
let url = page.inputFolder.appendingPathComponent(file)
guard url.exists else {
log.add(error: "File \(file) not found", source: page.path)
return ""
}
do {
return try String(contentsOf: url)
} catch {
log.add(error: "File \(file) could not be read", source: page.path, error: error)
return ""
}
}
2022-09-18 17:21:57 +02:00
private func handleSimpleBox(page: Element, content: String) -> String {
let parts = content.components(separatedBy: ";")
guard parts.count > 1 else {
log.add(error: "Invalid box specification", source: page.path)
return ""
}
let title = parts[0]
let text = parts.dropFirst().joined(separator: ";")
return factory.makePlaceholder(title: title, text: text)
}
2022-09-25 17:19:07 +02:00
private func handlePageLink(page: Element, language: String, pageId: String) -> String {
guard let linkedPage = siteRoot.find(pageId) else {
log.add(warning: "Page id '\(pageId)' not found", source: page.path)
// Remove link since the page can't be found
return ""
}
var content = [PageLinkTemplate.Key: String]()
content[.url] = page.relativePathToOtherSiteElement(file: linkedPage.fullPageUrl(for: language))
content[.title] = linkedPage.title(for: language)
let fullThumbnailPath = linkedPage.thumbnailFilePath(for: language)
let relativeImageUrl = page.relativePathToOtherSiteElement(file: fullThumbnailPath)
let metadata = linkedPage.localized(for: language)
if linkedPage.state.hasThumbnailLink {
let fullPageUrl = linkedPage.fullPageUrl(for: language)
let relativePageUrl = page.relativePathToOtherSiteElement(file: fullPageUrl)
content[.url] = "href=\"\(relativePageUrl)\""
}
content[.image] = relativeImageUrl
if let suffix = metadata.thumbnailSuffix {
content[.title] = factory.html.make(title: metadata.title, suffix: suffix)
} else {
content[.title] = metadata.title
}
content[.image2x] = relativeImageUrl.insert("@2x", beforeLast: ".")
let path = linkedPage.makePath(language: language, from: siteRoot)
content[.path] = factory.pageLink.makePath(components: path)
content[.description] = metadata.relatedContentText
if let parent = linkedPage.findParent(from: siteRoot), parent.thumbnailStyle == .large {
content[.className] = " related-page-link-large"
}
// We assume that the thumbnail images are already required by overview pages.
return factory.pageLink.generate(content)
}
2022-08-16 10:39:05 +02:00
}