39 lines
1.2 KiB
Swift
39 lines
1.2 KiB
Swift
import Ink
|
|
|
|
struct MarkdownHeadlineProcessor: MarkdownProcessor {
|
|
|
|
static let modifier: Modifier.Target = .headings
|
|
|
|
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
|
|
}
|
|
|
|
/**
|
|
Modify headlines by extracting an id from the headline and adding it into the html element
|
|
|
|
The id is created by lowercasing the string, removing all special characters, and replacing spaces with scores
|
|
*/
|
|
func process(html: String, markdown: Substring) -> String {
|
|
let parts2 = markdown.components(separatedBy: "#")
|
|
// Determine the type of heading, e.g. 2 for <h2>
|
|
let headlineParts = parts2.drop { $0.isEmpty }
|
|
let headlineType = parts2.count - headlineParts.count
|
|
|
|
guard headlineType > 1 && headlineType < 4 else {
|
|
return html
|
|
}
|
|
|
|
let title = headlineParts.joined(separator: "#")
|
|
let headline = HeadlineLink(level: headlineType, title: title)
|
|
return headline.content
|
|
}
|
|
}
|