CHGenerator/Sources/Generator/Generators/PageHeadGenerator.swift

48 lines
1.9 KiB
Swift
Raw Normal View History

2022-08-16 10:39:05 +02:00
import Foundation
struct PageHeadGenerator {
static let linkPreviewDesiredImageWidth = 1600
2022-08-16 10:39:05 +02:00
2022-08-28 14:01:53 +02:00
let factory: TemplateFactory
2022-08-16 10:39:05 +02:00
init(factory: TemplateFactory) {
2022-08-28 14:01:53 +02:00
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, includesCode: Bool = false) -> String {
let metadata = page.localized(for: language)
2022-08-16 10:39:05 +02:00
var content = [PageHeadTemplate.Key : String]()
content[.author] = page.author
content[.title] = metadata.linkPreviewTitle
content[.description] = metadata.linkPreviewDescription
if let image = page.linkPreviewImage(for: language) {
2022-08-16 10:39:05 +02:00
// Note: Generate separate destination link for the image,
// since we don't want a single large image for thumbnails.
// Warning: Link preview source path must be relative to root
let linkPreviewImageName = image.insert("-link", beforeLast: ".")
let sourceImagePath = page.pathRelativeToRootForContainedInputFile(image)
let destinationImagePath = page.pathRelativeToRootForContainedInputFile(linkPreviewImageName)
files.requireImage(
source: sourceImagePath,
destination: destinationImagePath,
width: PageHeadGenerator.linkPreviewDesiredImageWidth)
2022-08-28 14:01:53 +02:00
content[.image] = factory.html.linkPreviewImage(file: linkPreviewImageName)
2022-08-16 10:39:05 +02:00
}
content[.customPageContent] = page.customHeadContent()
2022-08-29 13:35:25 +02:00
if includesCode {
2022-09-04 17:47:35 +02:00
let scriptPath = "assets/js/highlight.js"
let relative = page.relativePathToOtherSiteElement(file: scriptPath)
let includeText = factory.html.scriptInclude(path: relative)
2022-08-29 13:35:25 +02:00
if let head = content[.customPageContent] {
content[.customPageContent] = head + "\n" + includeText
} else {
content[.customPageContent] = includeText
}
}
2022-08-16 10:39:05 +02:00
2022-08-28 14:01:53 +02:00
return factory.pageHead.generate(content)
2022-08-16 10:39:05 +02:00
}
}