Full page content, fixes, cleaner settings

This commit is contained in:
Christoph Hagen
2024-12-13 11:26:34 +01:00
parent efc9234917
commit b3b8c9a610
50 changed files with 1351 additions and 607 deletions

View File

@ -4,20 +4,16 @@ final class LocalizedWebsiteGenerator {
let language: ContentLanguage
let localizedSettings: LocalizedSettings
private let localizedPostSettings: LocalizedPostSettings
private var outputDirectory: URL {
URL(filePath: content.settings.outputDirectoryPath)
content.settings.outputDirectory
}
private var postsPerPage: Int {
content.settings.posts.postsPerPage
}
private var navigationIconPath: String {
content.settings.navigationBar.iconPath
}
private var mainContentMaximumWidth: CGFloat {
CGFloat(content.settings.posts.contentWidth)
}
@ -26,19 +22,20 @@ final class LocalizedWebsiteGenerator {
private let imageGenerator: ImageGenerator
private var navigationBarData: NavigationBarData {
createNavigationBarData(
settings: content.settings.navigationBar,
iconDescription: localizedSettings.navigationBarIconDescription)
private var navigationBarLinks: [NavigationBar.Link] {
content.settings.navigationTags.map {
let localized = $0.localized(in: language)
return .init(text: localized.name, url: content.absoluteUrlToTag($0, language: language))
}
}
init(content: Content, language: ContentLanguage) {
self.language = language
self.content = content
self.localizedSettings = content.settings.localized(in: language)
self.localizedPostSettings = content.settings.localized(in: language)
self.imageGenerator = ImageGenerator(
storage: content.storage,
relativeImageOutputPath: "images") // TODO: Get from settings
relativeImageOutputPath: content.settings.paths.imagesOutputFolderPath)
}
func generateWebsite(callback: (String) -> Void) -> Bool {
@ -63,11 +60,11 @@ final class LocalizedWebsiteGenerator {
language: language,
content: content,
imageGenerator: imageGenerator,
navigationBarData: navigationBarData,
navigationBarLinks: navigationBarLinks,
showTitle: false,
pageTitle: localizedSettings.posts.title,
pageDescription: localizedSettings.posts.description,
pageUrlPrefix: localizedSettings.posts.feedUrlPrefix)
pageTitle: localizedPostSettings.title,
pageDescription: localizedPostSettings.description,
pageUrlPrefix: localizedPostSettings.feedUrlPrefix)
return generator.createPages(for: content.posts)
}
@ -78,16 +75,17 @@ final class LocalizedWebsiteGenerator {
let localized = tag.localized(in: language)
#warning("Get tag url prefix from settings")
let urlPrefix = content.absoluteUrlPrefixForTag(tag, language: language)
let generator = PostListPageGenerator(
language: language,
content: content,
imageGenerator: imageGenerator,
navigationBarData: navigationBarData,
navigationBarLinks: navigationBarLinks,
showTitle: true,
pageTitle: localized.name,
pageDescription: localized.description ?? "",
pageUrlPrefix: "tags/\(localized.urlComponent)")
pageUrlPrefix: urlPrefix)
guard generator.createPages(for: posts) else {
return false
}
@ -95,17 +93,6 @@ final class LocalizedWebsiteGenerator {
return true
}
private func createNavigationBarData(settings: NavigationBarSettings, iconDescription: String) -> NavigationBarData {
let navigationItems: [NavigationBarLink] = settings.tags.map {
let localized = $0.localized(in: language)
return .init(text: localized.name, url: localized.urlComponent)
}
return NavigationBarData(
navigationIconPath: navigationIconPath,
iconDescription: iconDescription,
navigationItems: navigationItems)
}
private func generatePagesFolderIfNeeded() -> Bool {
let relativePath = content.settings.pages.pageUrlPrefix
@ -125,7 +112,10 @@ final class LocalizedWebsiteGenerator {
print("Failed to generate output folder")
return false
}
let pageGenerator = PageGenerator(content: content, imageGenerator: imageGenerator, navigationBarData: navigationBarData)
let pageGenerator = PageGenerator(
content: content,
imageGenerator: imageGenerator,
navigationBarLinks: navigationBarLinks)
let content: String
let results: PageGenerationResults
@ -140,7 +130,7 @@ final class LocalizedWebsiteGenerator {
return true
}
let path = self.content.pageLink(page, language: language) + ".html"
let path = self.content.absoluteUrlToPage(page, language: language) + ".html"
guard save(content, to: path) else {
print("Failed to save page")
return false
@ -161,15 +151,7 @@ final class LocalizedWebsiteGenerator {
continue
}
let outputPath: String
switch file.type {
case .video:
outputPath = content.pathToVideo(file)
case .image:
outputPath = content.pathToImage(file)
default:
outputPath = content.pathToFile(file)
}
let outputPath = content.absoluteUrlToFile(file)
do {
try content.storage.copy(file: file.id, to: outputPath)
} catch {

View File

@ -0,0 +1,31 @@
import Ink
final class PageCommandExtractor {
private var occurences: [(full: String, command: String, arguments: [String])] = []
func findOccurences(of command: ShorthandMarkdownKey, in content: String) -> [(full: String, arguments: [String])] {
findOccurences(of: command.rawValue, in: content)
}
func findOccurences(of command: String, in content: String) -> [(full: String, arguments: [String])] {
let parser = MarkdownParser(modifiers: [
Modifier(target: .images, closure: processMarkdownImage),
])
_ = parser.html(from: content)
return occurences
.filter { $0.command == command }
.map { ($0.full, $0.arguments) }
}
private func processMarkdownImage(html: String, markdown: Substring) -> String {
let argumentList = markdown.between(first: "](", andLast: ")").removingPercentEncoding ?? markdown.between(first: "](", andLast: ")")
let arguments = argumentList.components(separatedBy: ";")
let command = markdown.between("![", and: "]").trimmed
occurences.append((full: String(markdown), command: command, arguments: arguments))
return ""
}
}

View File

@ -0,0 +1,67 @@
enum PageContentAnomaly {
case failedToLoadContent(Error)
case missingFile(String)
case missingPage(String)
case missingTag(String)
case unknownCommand(String)
case invalidCommandArguments(command: ShorthandMarkdownKey, arguments: [String])
}
extension PageContentAnomaly: Identifiable {
var id: String {
switch self {
case .failedToLoadContent:
return "load-failed"
case .missingFile(let string):
return "missing-file-\(string)"
case .missingPage(let string):
return "missing-page-\(string)"
case .missingTag(let string):
return "missing-tag-\(string)"
case .unknownCommand(let string):
return "unknown-command-\(string)"
case .invalidCommandArguments(let command, let arguments):
return "invalid-arguments-\(command)-\(arguments.joined(separator: "-"))"
}
}
}
extension PageContentAnomaly {
enum Severity: String, CaseIterable {
case warning
case error
}
var severity: Severity {
switch self {
case .failedToLoadContent:
return .error
case .missingFile, .missingPage, .missingTag, .unknownCommand, .invalidCommandArguments:
return .warning
}
}
}
extension PageContentAnomaly: CustomStringConvertible {
var description: String {
switch self {
case .failedToLoadContent(let error):
return "Failed to load content: \(error)"
case .missingFile(let string):
return "Missing file \(string)"
case .missingPage(let string):
return "Missing page \(string)"
case .missingTag(let string):
return "Missing tag \(string)"
case .unknownCommand(let string):
return "Unknown command \(string)"
case .invalidCommandArguments(let command, let arguments):
return "Invalid command arguments for \(command): \(arguments)"
}
}
}

View File

@ -8,15 +8,17 @@ final class PageContentParser {
private let pageLinkMarker = "page:"
private let tagLinkMarker = "tag:"
private static let codeHighlightFooter = "<script>hljs.highlightAll();</script>"
private let swift = SyntaxHighlighter(format: HTMLOutputFormat())
let results = PageGenerationResults()
private let content: Content
private let language: ContentLanguage
private var largeImageCount: Int = 0
let language: ContentLanguage
var largeImageWidth: Int {
content.settings.pages.largeImageWidth
@ -32,26 +34,16 @@ final class PageContentParser {
}
func requestImages(_ generator: ImageGenerator) {
let thumbnailWidth = CGFloat(thumbnailWidth)
let largeImageWidth = CGFloat(largeImageWidth)
for image in results.files {
guard case .image = image.type else {
continue
}
for request in results.imagesToGenerate {
generator.generateImageSet(
for: image.id,
maxWidth: thumbnailWidth, maxHeight: thumbnailWidth)
generator.generateImageSet(
for: image.id,
maxWidth: largeImageWidth, maxHeight: largeImageWidth)
for: request.image.id,
maxWidth: CGFloat(request.size),
maxHeight: CGFloat(request.size))
}
}
func reset() {
results.reset()
largeImageCount = 0
}
func generatePage(from content: String) -> String {
@ -68,6 +60,8 @@ final class PageContentParser {
private func handleCode(html: String, markdown: Substring) -> String {
guard markdown.starts(with: "```swift") else {
results.requiredHeaders.insert(.codeHightlighting)
results.requiredFooters.insert(PageContentParser.codeHighlightFooter)
return html // Just use normal code highlighting
}
// Highlight swift code using Splash
@ -78,35 +72,46 @@ final class PageContentParser {
private func handleLink(html: String, markdown: Substring) -> String {
let file = markdown.between("(", and: ")")
if file.hasPrefix(pageLinkMarker) {
// Retain links pointing to elements within a page
let textToChange = file.dropAfterFirst("#")
let pageId = textToChange.replacingOccurrences(of: pageLinkMarker, with: "")
guard let page = content.page(pageId) else {
results.missingPages.insert(pageId)
// Remove link since the page can't be found
return markdown.between("[", and: "]")
}
results.linkedPages.insert(page)
let pagePath = content.pageLink(page, language: language)
return html.replacingOccurrences(of: textToChange, with: pagePath)
return handlePageLink(file: file, html: html, markdown: markdown)
}
// TODO: Check that linked file exists
// if let filePath = page.nonAbsolutePathRelativeToRootForContainedInputFile(file) {
// // The target of the page link must be present after generation is complete
// results.expect(file: filePath, source: page.path)
// }
if file.hasPrefix(tagLinkMarker) {
return handleTagLink(file: file, html: html, markdown: markdown)
}
#warning("Check existence of linked file")
return html
}
private func handlePageLink(file: String, html: String, markdown: Substring) -> String {
// Retain links pointing to elements within a page
let textToChange = file.dropAfterFirst("#")
let pageId = textToChange.replacingOccurrences(of: pageLinkMarker, with: "")
guard let page = content.page(pageId) else {
results.missingPages.insert(pageId)
// Remove link since the page can't be found
return markdown.between("[", and: "]")
}
results.linkedPages.insert(page)
let pagePath = content.absoluteUrlToPage(page, language: language)
return html.replacingOccurrences(of: textToChange, with: pagePath)
}
private func handleTagLink(file: String, html: String, markdown: Substring) -> String {
// Retain links pointing to elements within a page
let textToChange = file.dropAfterFirst("#")
let tagId = textToChange.replacingOccurrences(of: tagLinkMarker, with: "")
guard let tag = content.tag(tagId) else {
results.missingTags.insert(tagId)
// Remove link since the tag can't be found
return markdown.between("[", and: "]")
}
results.linkedTags.insert(tag)
let tagPath = content.absoluteUrlToTag(tag, language: language)
return html.replacingOccurrences(of: textToChange, with: tagPath)
}
private func handleHTML(html: String, markdown: Substring) -> String {
// TODO: Check HTML code in markdown for required resources
//print("[HTML] Found in page \(page.path):")
//print(markdown)
// Things to check:
// <img src=
// <a href=
//
#warning("Check HTML code in markdown for required resources")
// Things to check: <img src= <a href= <source>
return html
}
@ -130,35 +135,28 @@ final class PageContentParser {
return parts[0] + " id=\"\(id)\">" + parts.dropFirst().joined(separator: ">")
}
private func processMarkdownImage(html: String, markdown: Substring) -> String {
// First, check the content type, then parse the remaining arguments
// Notation:
// <abc?> -> Optional argument
// <abc...> -> Repeated argument (0 or more)
// ![url](<url>;<text>)
// ![image](<imageId>;<caption?>]
// ![video](<fileId>;<option1...>]
// ![svg](<fileId>;<<x>;<y>;<width>;<height>?>)
// ![download](<<fileId>,<text>,<download-filename?>;...)
// ![box](<title>;<body>)
// ![model](<file>;<description>)
// ![page](<pageId>)
// ![external](<<url>;<text>...>
// ![html](<fileId>)
private func percentDecoded(_ string: String) -> String {
guard let decoded = string.removingPercentEncoding else {
print("Invalid string: \(string)")
return string
}
return decoded
}
let argumentList = markdown.between(first: "](", andLast: ")").removingPercentEncoding ?? markdown.between(first: "](", andLast: ")")
private func processMarkdownImage(html: String, markdown: Substring) -> String {
//
let argumentList = percentDecoded(markdown.between(first: "](", andLast: ")"))
let arguments = argumentList.components(separatedBy: ";")
let rawCommand = markdown.between("![", and: "]").trimmed
let rawCommand = percentDecoded(markdown.between("![", and: "]").trimmed)
guard rawCommand != "" else {
return handleImage(arguments)
}
guard let convertedCommand = rawCommand.removingPercentEncoding,
let command = ShorthandMarkdownKey(rawValue: convertedCommand) else {
guard let command = ShorthandMarkdownKey(rawValue: rawCommand) else {
// Treat unknown commands as normal links
results.warnings.append("Unknown markdown command '\(rawCommand)'")
results.unknownCommands.append(rawCommand)
return html
}
@ -173,25 +171,28 @@ final class PageContentParser {
return handleVideo(arguments)
case .externalLink:
return handleExternalButtons(arguments)
/*
case .includedHtml:
return handleExternalHTML(file: content)
case .box:
return handleSimpleBox(content: content)
case .gitLink:
return handleGitButtons(arguments)
case .pageLink:
return handlePageLink(pageId: content)
return handlePageLink(arguments)
case .includedHtml:
return handleExternalHtml(arguments)
case .box:
return handleSimpleBox(arguments)
case .model:
return handle3dModel(content: content)
*/
return handleModel(arguments)
case .svg:
return handleSvg(arguments)
default:
results.warnings.append("Unhandled command '\(command.rawValue)'")
results.unknownCommands.append(command.rawValue)
return ""
}
}
/**
Format: `[image](<imageId>;<caption?>]`
*/
private func handleImage(_ arguments: [String]) -> String {
// [image](<imageId>;<caption?>]
guard (1...2).contains(arguments.count) else {
results.invalidCommandArguments.append((.image , arguments))
return ""
@ -207,19 +208,25 @@ final class PageContentParser {
let caption = arguments.count == 2 ? arguments[1] : nil
let altText = image.getDescription(for: language)
let path = content.pathToImage(image)
let path = content.absoluteUrlToFile(image)
guard !image.type.isSvg else {
return SvgImage(imagePath: path, altText: altText).content
}
let thumbnail = FeedEntryData.Image(
rawImagePath: path,
width: thumbnailWidth,
height: thumbnailWidth,
altText: altText)
results.imagesToGenerate.insert(.init(size: thumbnailWidth, image: image))
let largeImage = FeedEntryData.Image(
rawImagePath: path,
width: largeImageWidth,
height: largeImageWidth,
altText: altText)
results.imagesToGenerate.insert(.init(size: largeImageWidth, image: image))
return PageImage(
imageId: imageId.replacingOccurrences(of: ".", with: "-"),
@ -228,7 +235,11 @@ final class PageContentParser {
caption: caption).content
}
/**
Format: `![hiking-stats](<time>;<elevation-up>;<elevation-down>;<distance>;<calories>)`
*/
private func handleHikingStatistics(_ arguments: [String]) -> String {
#warning("Make statistics more generic using key-value pairs")
guard (1...5).contains(arguments.count) else {
results.invalidCommandArguments.append((.hikingStatistics, arguments))
return ""
@ -249,30 +260,37 @@ final class PageContentParser {
.content
}
/**
Format: `![download](<<fileId>,<text>,<download-filename?>;...)`
*/
private func handleDownloadButtons(_ arguments: [String]) -> String {
// ![download](<<fileId>,<text>,<download-filename?>;...)
let buttons: [ContentButtons.Item] = arguments.compactMap { button in
let parts = button.components(separatedBy: ",")
guard (2...3).contains(parts.count) else {
results.invalidCommandArguments.append((.downloadButtons, parts))
return nil
}
let file = parts[0].trimmed
let title = parts[1].trimmed
let downloadName = parts.count > 2 ? parts[2].trimmed : nil
// Ensure that file is available
guard let filePath = content.pathToFile(file) else {
results.missingFiles.insert(file)
return nil
}
return ContentButtons.Item(icon: .download, filePath: filePath, text: title, downloadFileName: downloadName)
}
let buttons = arguments.compactMap(convertButton)
return ContentButtons(items: buttons).content
}
private func convertButton(definition button: String) -> ContentButtons.Item? {
let parts = button.components(separatedBy: ",")
guard (2...3).contains(parts.count) else {
results.invalidCommandArguments.append((.downloadButtons, parts))
return nil
}
let fileId = parts[0].trimmed
let title = parts[1].trimmed
let downloadName = parts.count > 2 ? parts[2].trimmed : nil
guard let file = content.file(id: fileId) else {
results.missingFiles.insert(fileId)
return nil
}
results.files.insert(file)
let filePath = content.absoluteUrlToFile(file)
return ContentButtons.Item(icon: .download, filePath: filePath, text: title, downloadFileName: downloadName)
}
/**
Format: `![video](<fileId>;<option1...>]`
*/
private func handleVideo(_ arguments: [String]) -> String {
// ![video](<fileId>;<option1...>]
guard arguments.count >= 1 else {
results.invalidCommandArguments.append((.video, arguments))
return ""
@ -288,11 +306,11 @@ final class PageContentParser {
results.files.insert(file)
guard let videoType = file.type.videoType?.htmlType else {
results.warnings.append("Unknown video file type for \(fileId)")
results.invalidCommandArguments.append((.video, arguments))
return ""
}
let filePath = content.pathToFile(file)
let filePath = content.absoluteUrlToFile(file)
return ContentPageVideo(
filePath: filePath,
videoType: videoType,
@ -311,7 +329,7 @@ final class PageContentParser {
if case let .poster(imageId) = option {
if let image = content.image(imageId) {
results.files.insert(image)
let link = content.pathToImage(image)
let link = content.absoluteUrlToFile(image)
let width = 2*thumbnailWidth
let fullLink = WebsiteImage.imagePath(source: link, width: width, height: width)
return .poster(image: fullLink)
@ -323,7 +341,7 @@ final class PageContentParser {
if case let .src(videoId) = option {
if let video = content.video(videoId) {
results.files.insert(video)
let link = content.pathToVideo(video)
let link = content.absoluteUrlToFile(video)
// TODO: Set correct video path?
return .src(link)
} else {
@ -334,64 +352,17 @@ final class PageContentParser {
return option
}
/*
private func handleGif(file: String, altText: String) -> String {
let imagePath = page.pathRelativeToRootForContainedInputFile(file)
results.require(file: imagePath, source: page.path)
guard let size = results.getImageSize(atPath: imagePath, source: page.path) else {
return ""
}
let width = Int(size.width)
let height = Int(size.height)
return factory.html.image(file: file, width: width, height: height, altText: altText)
}
private func handleSvg(file: String, area: String?) -> String {
let imagePath = page.pathRelativeToRootForContainedInputFile(file)
results.require(file: imagePath, source: page.path)
guard let size = results.getImageSize(atPath: imagePath, source: page.path) else {
return "" // Missing image warning already produced
}
let width = Int(size.width)
let height = Int(size.height)
var altText = "image " + file.lastComponentAfter("/")
guard let area = area else {
return factory.html.image(file: file, width: width, height: height, altText: altText)
}
let parts = area.components(separatedBy: ",").map { $0.trimmed }
switch parts.count {
case 1:
return factory.html.image(file: file, width: width, height: height, altText: parts[0])
case 4:
break
case 5:
altText = parts[4]
default:
results.warning("Invalid area string for svg image", source: page.path)
return factory.html.image(file: file, width: width, height: height, altText: altText)
}
guard let x = Int(parts[0]),
let y = Int(parts[1]),
let partWidth = Int(parts[2]),
let partHeight = Int(parts[3]) else {
results.warning("Invalid area string for svg image", source: page.path)
return factory.html.image(file: file, width: width, height: height, altText: altText)
}
let part = SVGSelection(x, y, partWidth, partHeight)
return factory.html.svgImage(file: file, part: part, altText: altText)
}
private func handleFile(file: String, fileExtension: String) -> String {
results.warning("Unhandled file \(file) with extension \(fileExtension)", source: page.path)
return ""
}
*/
private func handleExternalButtons(_ arguments: [String]) -> String {
// ![external](<<url>;<text>...>
handleButtons(icon: .externalLink, arguments: arguments)
}
private func handleGitButtons(_ arguments: [String]) -> String {
// ![git](<<url>;<text>...>
handleButtons(icon: .gitLink, arguments: arguments)
}
private func handleButtons(icon: PageIcon, arguments: [String]) -> String {
guard arguments.count >= 1 else {
results.invalidCommandArguments.append((.externalLink, arguments))
return ""
@ -410,98 +381,161 @@ final class PageContentParser {
let title = parts[1].trimmed
return .init(
icon: .externalLink,
icon: icon,
filePath: url,
text: title)
}
return ContentButtons(items: buttons).content
}
/*
private func handleExternalHTML(file: String) -> String {
let path = page.pathRelativeToRootForContainedInputFile(file)
return results.getContentOfRequiredFile(at: path, source: page.path) ?? ""
}
private func handleSimpleBox(content: String) -> String {
let parts = content.components(separatedBy: ";")
guard parts.count > 1 else {
results.warning("Invalid box specification", page: page)
/**
Format: `![html](<fileId>)`
*/
private func handleExternalHtml(_ arguments: [String]) -> String {
guard arguments.count == 1 else {
results.invalidCommandArguments.append((.includedHtml, arguments))
return ""
}
let title = parts[0]
let text = parts.dropFirst().joined(separator: ";")
return factory.makePlaceholder(title: title, text: text)
}
private func handlePageLink(pageId: String) -> String {
guard let linkedPage = siteRoot.find(pageId) else {
// Checking the page path will add it to the missing pages
_ = results.getPagePath(for: pageId, source: page.path, language: language)
// Remove link since the page can't be found
let fileId = arguments[0]
guard let file = content.file(id: fileId) else {
results.missingFiles.insert(fileId)
return ""
}
guard linkedPage.state == .standard else {
return file.textContent()
}
/**
Format: `![box](<title>;<body>)`
*/
private func handleSimpleBox(_ arguments: [String]) -> String {
guard arguments.count > 1 else {
results.invalidCommandArguments.append((.box, arguments))
return ""
}
let title = arguments[0]
let text = arguments.dropFirst().joined(separator: ";")
return ContentBox(title: title, text: text).content
}
/**
Format: `![page](<pageId>)`
*/
private func handlePageLink(_ arguments: [String]) -> String {
guard arguments.count == 1 else {
results.invalidCommandArguments.append((.pageLink, arguments))
return ""
}
let pageId = arguments[0]
guard let page = content.page(pageId) else {
results.missingPages.insert(pageId)
return ""
}
guard !page.isDraft else {
// Prevent linking to unpublished content
return ""
}
var content = [PageLinkTemplate.Key: String]()
content[.title] = linkedPage.title(for: language)
content[.altText] = ""
let localized = page.localized(in: language)
let url = content.absoluteUrlToPage(page, language: language)
let title = localized.linkPreviewTitle ?? localized.title
let description = localized.linkPreviewDescription ?? ""
let fullThumbnailPath = linkedPage.thumbnailFilePath(for: language).destination
// Note: Here we assume that the thumbnail was already used elsewhere, so already generated
let relativeImageUrl = page.relativePathToOtherSiteElement(file: fullThumbnailPath)
let metadata = linkedPage.localized(for: language)
let image = localized.linkPreviewImage.map { image in
let size = content.settings.pages.pageLinkImageSize
results.files.insert(image)
results.imagesToGenerate.insert(.init(size: size, image: image))
if linkedPage.state.hasThumbnailLink {
let fullPageUrl = linkedPage.fullPageUrl(for: language)
let relativePageUrl = page.relativePathToOtherSiteElement(file: fullPageUrl)
content[.url] = "href=\"\(relativePageUrl)\""
return RelatedPageLink.Image(
url: content.absoluteUrlToFile(image),
description: image.getDescription(for: language),
size: size)
}
content[.image] = relativeImageUrl.dropAfterLast(".")
if let suffix = metadata.thumbnailSuffix {
content[.title] = factory.html.make(title: metadata.title, suffix: suffix)
} else {
content[.title] = metadata.title
}
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)
return RelatedPageLink(
title: title,
description: description,
url: url,
image: image)
.content
}
private func handle3dModel(content: String) -> String {
let parts = content.components(separatedBy: ";")
guard parts.count > 1 else {
results.warning("Invalid 3d model specification", page: page)
/**
Format: `![model](<file>)`
*/
private func handleModel(_ arguments: [String]) -> String {
guard arguments.count == 1 else {
results.invalidCommandArguments.append((.model, arguments))
return ""
}
let file = parts[0]
guard file.hasSuffix(".glb") else {
results.warning("Invalid 3d model file \(file) (must be .glb)", page: page)
let fileId = arguments[0]
guard fileId.hasSuffix(".glb") else {
results.invalidCommandArguments.append((.model, ["\(fileId) is not a .glb file"]))
return ""
}
// Ensure that file is available
let filePath = page.pathRelativeToRootForContainedInputFile(file)
results.require(file: filePath, source: page.path)
guard let file = content.file(id: fileId) else {
results.missingFiles.insert(fileId)
return ""
}
results.files.insert(file)
results.requiredHeaders.insert(.modelViewer)
// Add required file to head
headers.insert(.modelViewer)
let description = parts.dropFirst().joined(separator: ";")
return """
<model-viewer alt="\(description)" src="\(file)" ar shadow-intensity="1" camera-controls touch-action="pan-y"></model-viewer>
"""
let path = content.absoluteUrlToFile(file)
let description = file.getDescription(for: language)
return ModelViewer(file: path, description: description).content
}
*/
private func handleSvg(_ arguments: [String]) -> String {
guard arguments.count == 5 else {
results.invalidCommandArguments.append((.svg, arguments))
return ""
}
guard let x = Int(arguments[1]),
let y = Int(arguments[2]),
let partWidth = Int(arguments[3]),
let partHeight = Int(arguments[4]) else {
results.invalidCommandArguments.append((.svg, arguments))
return ""
}
let imageId = arguments[0]
guard let image = content.image(imageId) else {
results.missingFiles.insert(imageId)
return ""
}
guard case .image(let imageType) = image.type,
imageType == .svg else {
results.invalidCommandArguments.append((.svg, arguments))
return ""
}
let path = content.absoluteUrlToFile(image)
return PartialSvgImage(
imagePath: path,
altText: image.getDescription(for: language),
x: x,
y: y,
width: partWidth,
height: partHeight)
.content
}
}
/*
private func handleGif(file: String, altText: String) -> String {
let imagePath = page.pathRelativeToRootForContainedInputFile(file)
results.require(file: imagePath, source: page.path)
guard let size = results.getImageSize(atPath: imagePath, source: page.path) else {
return ""
}
let width = Int(size.width)
let height = Int(size.height)
return factory.html.image(file: file, width: width, height: height, altText: altText)
}
*/

View File

@ -1,32 +1,75 @@
import Foundation
struct ImageToGenerate {
let size: Int
let image: FileResource
}
extension ImageToGenerate: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(size)
hasher.combine(image.id)
}
}
final class PageGenerationResults: ObservableObject {
@Published
var linkedPages: Set<Page> = []
@Published
var linkedTags: Set<Tag> = []
@Published
var files: Set<FileResource> = []
@Published
var imagesToGenerate: Set<ImageToGenerate> = []
@Published
var missingPages: Set<String> = []
@Published
var missingFiles: Set<String> = []
@Published
var missingTags: Set<String> = []
@Published
var unknownCommands: [String] = []
@Published
var invalidCommandArguments: [(command: ShorthandMarkdownKey, arguments: [String])] = []
@Published
var warnings: [String] = []
var requiredHeaders: RequiredHeaders = []
@Published
var requiredFooters: Set<String> = []
func reset() {
linkedPages = []
linkedTags = []
files = []
imagesToGenerate = []
missingPages = []
missingFiles = []
missingTags = []
unknownCommands = []
invalidCommandArguments = []
warnings = []
requiredHeaders = []
requiredFooters = []
}
var convertedWarnings: [PageContentAnomaly] {
var result = [PageContentAnomaly]()
result += missingPages.map { .missingPage($0) }
result += missingFiles.map { .missingFile($0) }
result += unknownCommands.map { .unknownCommand($0) }
result += invalidCommandArguments.map { .invalidCommandArguments(command: $0.command, arguments: $0.arguments) }
return result
}
}

View File

@ -4,12 +4,12 @@ final class PageGenerator {
private let imageGenerator: ImageGenerator
private let navigationBarData: NavigationBarData
private let navigationBarLinks: [NavigationBar.Link]
init(content: Content, imageGenerator: ImageGenerator, navigationBarData: NavigationBarData) {
init(content: Content, imageGenerator: ImageGenerator, navigationBarLinks: [NavigationBar.Link]) {
self.content = content
self.imageGenerator = imageGenerator
self.navigationBarData = navigationBarData
self.navigationBarLinks = navigationBarLinks
}
func generate(page: Page, language: ContentLanguage) throws -> (page: String, results: PageGenerationResults) {
@ -27,9 +27,12 @@ final class PageGenerator {
let tags: [FeedEntryData.Tag] = page.tags.map { tag in
.init(name: tag.localized(in: language).name,
url: content.tagLink(tag, language: language))
url: content.absoluteUrlToTag(tag, language: language))
}
let headers = AdditionalPageHeaders(
headers: contentGenerator.results.requiredHeaders,
assetPath: content.settings.pages.javascriptFilesPath)
let fullPage = ContentPage(
language: language,
dateString: page.dateText(in: language),
@ -37,8 +40,10 @@ final class PageGenerator {
tags: tags,
linkTitle: localized.linkPreviewTitle ?? localized.title,
description: localized.linkPreviewDescription ?? "",
navigationBarData: navigationBarData,
pageContent: pageContent)
navigationBarLinks: navigationBarLinks,
pageContent: pageContent,
headers: headers.content,
footers: contentGenerator.results.requiredFooters.sorted())
.content
return (fullPage, contentGenerator.results)

View File

@ -8,7 +8,7 @@ final class PostListPageGenerator {
private let imageGenerator: ImageGenerator
private let navigationBarData: NavigationBarData
private let navigationBarLinks: [NavigationBar.Link]
private let showTitle: Bool
@ -19,11 +19,11 @@ final class PostListPageGenerator {
/// The url of the page, excluding the extension
private let pageUrlPrefix: String
init(language: ContentLanguage, content: Content, imageGenerator: ImageGenerator, navigationBarData: NavigationBarData, showTitle: Bool, pageTitle: String, pageDescription: String, pageUrlPrefix: String) {
init(language: ContentLanguage, content: Content, imageGenerator: ImageGenerator, navigationBarLinks: [NavigationBar.Link], showTitle: Bool, pageTitle: String, pageDescription: String, pageUrlPrefix: String) {
self.language = language
self.content = content
self.imageGenerator = imageGenerator
self.navigationBarData = navigationBarData
self.navigationBarLinks = navigationBarLinks
self.showTitle = showTitle
self.pageTitle = pageTitle
self.pageDescription = pageDescription
@ -49,30 +49,30 @@ final class PostListPageGenerator {
let startIndex = (pageIndex - 1) * postsPerPage
let endIndex = min(pageIndex * postsPerPage, totalCount)
let postsOnPage = posts[startIndex..<endIndex]
guard createPostFeedPage(pageIndex, pageCount: numberOfPages, posts: postsOnPage, bar: navigationBarData) else {
guard createPostFeedPage(pageIndex, pageCount: numberOfPages, posts: postsOnPage, bar: navigationBarLinks) else {
return false
}
}
return true
}
private func createPostFeedPage(_ pageIndex: Int, pageCount: Int, posts: ArraySlice<Post>, bar: NavigationBarData) -> Bool {
private func createPostFeedPage(_ pageIndex: Int, pageCount: Int, posts: ArraySlice<Post>, bar: [NavigationBar.Link]) -> Bool {
let posts: [FeedEntryData] = posts.map { post in
let localized: LocalizedPost = post.localized(in: language)
let linkUrl = post.linkedPage.map {
FeedEntryData.Link(
url: content.pageLink($0, language: language),
url: content.absoluteUrlToPage($0, language: language),
text: language == .english ? "View" : "Anzeigen") // TODO: Add to settings
}
let tags: [FeedEntryData.Tag] = post.tags.filter { $0.isVisible }.map { tag in
.init(name: tag.localized(in: language).name,
url: content.tagLink(tag, language: language))
url: content.absoluteUrlToTag(tag, language: language))
}
return FeedEntryData(
entryId: "\(post.id)",
entryId: post.id,
title: localized.title,
textAboveTitle: post.dateText(in: language),
link: linkUrl,
@ -86,7 +86,7 @@ final class PostListPageGenerator {
title: pageTitle,
showTitle: showTitle,
description: pageDescription,
navigationBarData: bar,
navigationBarLinks: bar,
pageNumber: pageIndex,
totalPages: pageCount,
posts: posts)
@ -104,7 +104,7 @@ final class PostListPageGenerator {
maxWidth: mainContentMaximumWidth,
maxHeight: mainContentMaximumWidth)
return .init(
rawImagePath: content.pathToImage(image),
rawImagePath: content.absoluteUrlToFile(image),
width: Int(mainContentMaximumWidth),
height: Int(mainContentMaximumWidth),
altText: image.getDescription(for: language))

View File

@ -0,0 +1,16 @@
enum HeaderFile: String {
case codeHightlighting = "highlight.min.js"
case modelViewer = "model-viewer.min.js"
var asModule: Bool {
switch self {
case .codeHightlighting: return false
case .modelViewer: return true
}
}
}
typealias RequiredHeaders = Set<HeaderFile>

View File

@ -44,8 +44,16 @@ enum ShorthandMarkdownKey: String {
/// Format: `![external](<<url>;<text>...>`
case externalLink = "external"
/// A large button to a git/github page
/// Format: `![git](<<url>;<text>...>`
case gitLink = "git"
/// Additional HTML code include verbatim into the page.
/// Format: `![html](<fileId>)`
case includedHtml = "html"
/// SVG Image showing only a part of the image
/// Format `![svg](<fileId>;`
case svg
}