CHGenerator/WebsiteGenerator/Generators/PageHeadGenerator.swift
2022-09-04 17:47:35 +02:00

48 lines
1.9 KiB
Swift

import Foundation
struct PageHeadGenerator {
static let linkPreviewDesiredImageWidth = 1600
let factory: TemplateFactory
init(factory: TemplateFactory) {
self.factory = factory
}
func generate(page: Element, language: String, includesCode: Bool = false) -> String {
let metadata = page.localized(for: language)
var content = [PageHeadTemplate.Key : String]()
content[.author] = page.author
content[.title] = metadata.linkPreviewTitle
content[.description] = metadata.linkPreviewDescription
if let image = page.linkPreviewImage(for: language) {
// 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)
content[.image] = factory.html.linkPreviewImage(file: linkPreviewImageName)
}
content[.customPageContent] = page.customHeadContent()
if includesCode {
let scriptPath = "assets/js/highlight.js"
let relative = page.relativePathToOtherSiteElement(file: scriptPath)
let includeText = factory.html.scriptInclude(path: relative)
if let head = content[.customPageContent] {
content[.customPageContent] = head + "\n" + includeText
} else {
content[.customPageContent] = includeText
}
}
return factory.pageHead.generate(content)
}
}