CHGenerator/WebsiteGenerator/Generators/OverviewSectionGenerator.swift

70 lines
2.9 KiB
Swift
Raw Normal View History

2022-08-16 10:39:05 +02:00
import Foundation
struct OverviewSectionGenerator {
private let multipleSectionsTemplate: OverviewSectionTemplate
private let singleSectionsTemplate: OverviewSectionCleanTemplate
2022-08-16 12:26:45 +02:00
let files: FileProcessor
2022-08-16 10:39:05 +02:00
private let generator: ThumbnailListGenerator
2022-08-16 12:26:45 +02:00
init(factory: TemplateFactory, files: FileProcessor) {
2022-08-16 10:39:05 +02:00
self.multipleSectionsTemplate = factory.overviewSection
self.singleSectionsTemplate = factory.overviewSectionClean
2022-08-16 12:26:45 +02:00
self.files = files
self.generator = ThumbnailListGenerator(factory: factory, files: files)
2022-08-16 10:39:05 +02:00
}
func generate(sections: [Section], in parent: SiteElement, language: String, sectionItemCount: Int) throws -> String {
try sections.map { section in
let metadata = section.localized(for: language)
let fullUrl = section.fullPageUrl(for: language)
let relativeUrl = parent.relativePathToFileWithPath(fullUrl)
var content = [OverviewSectionTemplate.Key : String]()
content[.url] = relativeUrl
content[.title] = metadata.title
content[.items] = try sectionContent(section: section, in: parent, language: language, shownItemCount: sectionItemCount)
content[.more] = metadata.moreLinkTitle
return multipleSectionsTemplate.generate(content)
}
.joined(separator: "\n")
}
func generate(section: Section, language: String) throws -> String {
var content = [OverviewSectionCleanTemplate.Key : String]()
content[.items] = try sectionContent(section: section, in: section, language: language, shownItemCount: nil)
return singleSectionsTemplate.generate(content)
}
private func sectionContent(section: Section, in parent: SiteElement, language: String, shownItemCount: Int?) throws -> String {
let sectionItems: [SiteElement]
if let shownItemCount = shownItemCount {
sectionItems = Array(section.sortedItems.prefix(shownItemCount))
} else {
sectionItems = section.sortedItems
}
let items: [ThumbnailInfo] = sectionItems.map { item in
#warning("Check if page exists for the language")
let fullPageUrl = item.fullPageUrl(for: language)
let relativePageUrl = parent.relativePathToFileWithPath(fullPageUrl)
let fullThumbnailPath = item.thumbnailFilePath(for: language)
let relativeImageUrl = parent.relativePathToFileWithPath(fullThumbnailPath)
return ThumbnailInfo(
url: relativePageUrl,
imageFilePath: fullThumbnailPath,
imageHtmlUrl: relativeImageUrl,
title: item.title(for: language),
cornerText: item.cornerText(for: language))
}
return try generator.generateContent(
items: items,
style: section.metadata.thumbnailStyle)
}
}