Add single file audio player, introduce blocks

This commit is contained in:
Christoph Hagen
2025-01-06 01:17:06 +01:00
parent c78c359819
commit 245534e989
27 changed files with 521 additions and 88 deletions

View File

@ -0,0 +1,62 @@
struct AudioBlockProcessor: KeyedBlockProcessor {
enum Key: String {
case name
case artist
case album
case file
case cover
}
static let blockId: ContentBlock = .audio
let content: Content
let results: PageGenerationResults
let language: ContentLanguage
init(content: Content, results: PageGenerationResults, language: ContentLanguage) {
self.content = content
self.results = results
self.language = language
}
func process(_ arguments: [Key : String], markdown: Substring) -> String {
guard let name = arguments[.name],
let artist = arguments[.artist],
let album = arguments[.album],
let fileId = arguments[.file],
let cover = arguments[.cover] else {
invalid(markdown)
return ""
}
guard let image = content.image(cover) else {
results.missing(file: cover, source: "Audio Block")
return ""
}
guard let file = content.file(fileId) else {
results.missing(file: fileId, source: "Audio Block")
return ""
}
let coverSize = 2 * content.settings.audioPlayer.smallCoverImageSize
let coverImage = image.imageVersion(width: coverSize, height: coverSize, type: image.type)
let footer = SingleFilePlayer.footer(
name: name,
artist: artist,
album: album,
url: file.absoluteUrl,
cover: coverImage.outputPath)
results.require(image: coverImage)
results.require(footer: footer)
results.require(headers: .audioPlayerJs, .audioPlayerCss)
results.require(icons: .audioPlayerPlay, .audioPlayerPause)
return SingleFilePlayer().content
}
}

View File

@ -0,0 +1,86 @@
enum ContentBlock: String, CaseIterable {
case audio
case swift
var processor: BlockProcessor.Type {
switch self {
case .audio: return AudioBlockProcessor.self
case .swift: return SwiftBlockProcessor.self
}
}
}
protocol BlockProcessor {
static var blockId: ContentBlock { get }
var results: PageGenerationResults { get }
init(content: Content, results: PageGenerationResults, language: ContentLanguage)
func process(_ markdown: Substring) -> String
}
extension BlockProcessor {
func invalid(_ markdown: Substring) {
results.invalid(block: Self.blockId, markdown)
}
}
protocol BlockLineProcessor: BlockProcessor {
func process(_ lines: [String], markdown: Substring) -> String
}
extension BlockLineProcessor {
func process(_ markdown: Substring) -> String {
let lines = markdown
.between("```\(Self.blockId.self)", and: "```")
.components(separatedBy: "\n")
return process(lines, markdown: markdown)
}
}
protocol OrderedKeyBlockProcessor: BlockLineProcessor {
associatedtype Key: Hashable, RawRepresentable where Key.RawValue == String
func process(_ arguments: [(key: Key, value: String)], markdown: Substring) -> String
}
extension OrderedKeyBlockProcessor {
func process(_ lines: [String], markdown: Substring) -> String {
let result: [(key: Key, value: String)] = lines.compactMap { line in
guard line.trimmed != "" else {
return nil
}
let (rawKey, rawValue) = line.splitAtFirst(":")
guard let key = Key(rawValue: rawKey.trimmed) else {
print("Invalid key \(rawKey)")
invalid(markdown)
return nil
}
return (key, rawValue.trimmed)
}
return process(result, markdown: markdown)
}
}
protocol KeyedBlockProcessor: OrderedKeyBlockProcessor {
func process(_ arguments: [Key : String], markdown: Substring) -> String
}
extension KeyedBlockProcessor {
func process(_ arguments: [(key: Key, value: String)], markdown: Substring) -> String {
let result = arguments.reduce(into: [:]) { $0[$1.key] = $1.value }
return process(result, markdown: markdown)
}
}

View File

@ -0,0 +1,33 @@
struct CodeBlockProcessor {
private let codeHighlightFooter = "<script>hljs.highlightAll();</script>"
let results: PageGenerationResults
private let blocks: [ContentBlock : BlockProcessor]
private let other: OtherCodeProcessor
init(content: Content, results: PageGenerationResults, language: ContentLanguage) {
self.results = results
self.other = .init(results: results)
self.blocks = ContentBlock.allCases.reduce(into: [:]) { blocks, block in
blocks[block] = block.processor.init(content: content, results: results, language: language)
}
}
func process(_ html: String, markdown: Substring) -> String {
let input = String(markdown)
let rawBlockId = input.dropAfterFirst("\n").dropBeforeFirst("```").trimmed
guard let blockId = ContentBlock(rawValue: rawBlockId) else {
return other.process(html: html)
}
guard let processor = self.blocks[blockId] else {
results.invalid(block: blockId, markdown)
return ""
}
return processor.process(markdown)
}
}

View File

@ -0,0 +1,17 @@
struct OtherCodeProcessor {
private let codeHighlightFooter = "<script>hljs.highlightAll();</script>"
let results: PageGenerationResults
init(results: PageGenerationResults) {
self.results = results
}
func process(html: String) -> String {
results.require(header: .codeHightlighting)
results.require(footer: codeHighlightFooter)
return html // Just use normal code highlighting
}
}

View File

@ -0,0 +1,26 @@
import Splash
struct SwiftBlockProcessor: BlockProcessor {
static let blockId: ContentBlock = .swift
let content: Content
let results: PageGenerationResults
let language: ContentLanguage
private let swift = SyntaxHighlighter(format: HTMLOutputFormat())
init(content: Content, results: PageGenerationResults, language: ContentLanguage) {
self.content = content
self.results = results
self.language = language
}
func process(_ markdown: Substring) -> String {
// Highlight swift code using Splash
let code = markdown.between("```swift", and: "```").trimmed
return "<pre><code>" + swift.highlight(code) + "</pre></code>"
}
}

View File

@ -31,6 +31,9 @@ final class GenerationResults: ObservableObject {
@Published
var invalidCommands: Set<String> = []
@Published
var invalidBlocks: Set<String> = []
@Published
var warnings: Set<String> = []
@ -105,6 +108,8 @@ final class GenerationResults: ObservableObject {
update { self.imagesToGenerate = imagesToGenerate }
let invalidCommands = cache.values.map { $0.invalidCommands.map { $0.markdown }}.union()
update { self.invalidCommands = invalidCommands }
let invalidBlocks = cache.values.map { $0.invalidBlocks.map { $0.markdown }}.union()
update { self.invalidBlocks = invalidBlocks }
let warnings = cache.values.map { $0.warnings }.union()
update { self.warnings = warnings }
let unsavedOutputFiles = cache.values.map { $0.unsavedOutputFiles.keys }.union()
@ -163,6 +168,10 @@ final class GenerationResults: ObservableObject {
update { self.invalidCommands.insert(markdown) }
}
func invalidBlock(_ markdown: String) {
update { self.invalidBlocks.insert(markdown) }
}
func warning(_ warning: String) {
update { self.warnings.insert(warning) }
}

View File

@ -26,11 +26,11 @@ enum KnownHeaderElement: Int {
return HeaderElement.jsModule(file)
}
case .audioPlayerCss:
if let file = content.settings.pages.audioPlayerCssFile {
if let file = content.settings.audioPlayer.audioPlayerCssFile {
return .css(file: file, order: HeaderElement.audioPlayerCssOrder)
}
case .audioPlayerJs:
if let file = content.settings.pages.audioPlayerJsFile {
if let file = content.settings.audioPlayer.audioPlayerJsFile {
return .js(file: file, defer: true)
}
case .imageCompareJs:

View File

@ -46,7 +46,7 @@ struct AudioPlayerCommandProcessor: CommandProcessor {
var amplitude: [AmplitudeSong] = []
for song in songs {
guard let image = content.image(song.cover) else {
guard let image = content.file(song.cover) else {
results.missing(file: song.cover, containedIn: file)
continue
}
@ -63,7 +63,11 @@ struct AudioPlayerCommandProcessor: CommandProcessor {
results.warning("Song '\(song.file)' in file \(fileId) is not an audio file")
continue
}
let coverUrl = image.absoluteUrl
let coverSize = 2 * content.settings.audioPlayer.playlistCoverImageSize
let coverImage = image.imageVersion(width: coverSize, height: coverSize, type: image.type)
let coverUrl = coverImage.outputPath
results.require(image: coverImage)
let playlistItem = AudioPlayer.PlaylistItem(
index: playlist.count,

View File

@ -13,7 +13,6 @@ struct ButtonCommandProcessor: CommandProcessor {
}
/**
Format: `![buttons](<<fileId>,<text>,<download-filename?>;...)`
Format: `![buttons](type=<specification>;...)`
Types:
- Download: `download=<fileId>,<text>,<download-filename?>`

View File

@ -1,25 +0,0 @@
import Splash
struct PageCodeProcessor {
private let codeHighlightFooter = "<script>hljs.highlightAll();</script>"
private let swift = SyntaxHighlighter(format: HTMLOutputFormat())
let results: PageGenerationResults
init(results: PageGenerationResults) {
self.results = results
}
func process(_ html: String, markdown: Substring) -> String {
guard markdown.starts(with: "```swift") else {
results.require(header: .codeHightlighting)
results.require(footer: codeHighlightFooter)
return html // Just use normal code highlighting
}
// Highlight swift code using Splash
let code = markdown.between("```swift", and: "```").trimmed
return "<pre><code>" + swift.highlight(code) + "</pre></code>"
}
}

View File

@ -33,7 +33,7 @@ final class PageContentParser {
private let inlineLink: InlineLinkProcessor
private let code: PageCodeProcessor
private let code: CodeBlockProcessor
init(content: Content, language: ContentLanguage, results: PageGenerationResults) {
self.content = content
@ -50,7 +50,7 @@ final class PageContentParser {
self.images = .init(content: content, results: results, language: language)
self.inlineLink = .init(content: content, results: results, language: language)
self.code = .init(results: results)
self.code = .init(content: content, results: results, language: language)
}
func generatePage(from content: String) -> String {
@ -84,21 +84,12 @@ final class PageContentParser {
return parts[0] + " id=\"\(id)\">" + parts.dropFirst().joined(separator: ">")
}
private func percentDecoded(_ string: String) -> String {
guard let decoded = string.removingPercentEncoding else {
print("Invalid string: \(string)")
return string
}
return decoded
}
private func processMarkdownImage(html: String, markdown: Substring) -> String {
//
let argumentList = percentDecoded(markdown.between(first: "](", andLast: ")"))
let argumentList = markdown.between(first: "](", andLast: ")").percentDecoded()
let arguments = argumentList.components(separatedBy: ";")
let rawCommand = percentDecoded(markdown.between("![", and: "]").trimmed)
let rawCommand = markdown.between("![", and: "]").trimmed.percentDecoded()
guard rawCommand != "" else {
return images.process(arguments, markdown: markdown)
}

View File

@ -66,7 +66,9 @@ final class PageGenerationResults: ObservableObject {
/// The image versions required for this page
private(set) var imagesToGenerate: Set<ImageVersion>
private(set) var invalidCommands: [(command: ShorthandMarkdownKey?, markdown: String)] = []
private(set) var invalidCommands: [(command: ShorthandMarkdownKey?, markdown: String)]
private(set) var invalidBlocks: [(block: ContentBlock?, markdown: String)]
private(set) var warnings: Set<String>
@ -94,6 +96,7 @@ final class PageGenerationResults: ObservableObject {
requiredFiles = []
imagesToGenerate = []
invalidCommands = []
invalidBlocks = []
warnings = []
unsavedOutputFiles = [:]
pageIsEmpty = false
@ -116,6 +119,7 @@ final class PageGenerationResults: ObservableObject {
requiredFiles = []
imagesToGenerate = []
invalidCommands = []
invalidBlocks = []
warnings = []
unsavedOutputFiles = [:]
pageIsEmpty = false
@ -134,6 +138,12 @@ final class PageGenerationResults: ObservableObject {
delegate.invalidCommand(markdown)
}
func invalid(block: ContentBlock?, _ markdown: Substring) {
let markdown = String(markdown)
invalidBlocks.append((block, markdown))
delegate.invalidBlock(markdown)
}
func missing(page: String, source: String) {
missingLinkedPages[page, default: []].insert(source)
delegate.missing(page: page)

View File

@ -17,8 +17,16 @@ enum ShorthandMarkdownKey: String {
/// Format: `![video](<fileId>;<option1...>]`
case video
/// A variable number of download buttons for file downloads
/// Format: `[buttons](type=<<fileId>,<text>,<download-filename?>;...)`
/**
A variable number of buttons for file downloads, external links or other uses
Format: `![buttons](type=<specification>;...)`
Types:
- Download: `download=<fileId>,<text>,<download-filename?>`
- External link: `external=<url>,<text>`
- Git: `git=<url>,<text>`
- Play: `play-circle=<text>,<click-action>`
*/
case buttons
/// A box with a title and content