CHGenerator/Sources/Generator/Generators/PageHeadGenerator.swift
2023-12-16 22:10:27 +01:00

53 lines
2.2 KiB
Swift

import Foundation
struct PageHeadGenerator {
// TODO: Add to configuration
static let linkPreviewDesiredImageWidth = 1600
let factory: TemplateFactory
private let results: GenerationResultsHandler
init(factory: TemplateFactory, results: GenerationResultsHandler) {
self.factory = factory
self.results = results
}
func generate(page: Element, language: String, headers: RequiredHeaders = .init()) -> 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 = "thumbnail-link.\(image.lastComponentAfter("."))"
let sourceImagePath = page.pathRelativeToRootForContainedInputFile(image)
let destinationImagePath = page.pathRelativeToRootForContainedInputFile(linkPreviewImageName)
results.requireSingleImage(
source: sourceImagePath,
destination: destinationImagePath,
requiredBy: page.path,
width: PageHeadGenerator.linkPreviewDesiredImageWidth)
content[.image] = factory.html.linkPreviewImage(file: linkPreviewImageName)
}
content[.customPageContent] = results.getContentOfOptionalFile(at: page.additionalHeadContentPath, source: page.path)
let head = (content[.customPageContent].unwrapped { [$0] } ?? []) + headers
.map { $0.rawValue }
.sorted()
.map { option in
let scriptPath = "assets/js/\(option)"
let relative = page.relativePathToOtherSiteElement(file: scriptPath)
return factory.html.scriptInclude(path: relative)
}
content[.customPageContent] = head.joined(separator: "\n")
return factory.pageHead.generate(content)
}
}