aboutsummaryrefslogtreecommitdiff
path: root/plugins/all-module-page/src/main/kotlin/templates/DirectiveBasedTemplateProcessing.kt
blob: 7786ca180bb3d78d1721de9b0452052663ded0fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package org.jetbrains.dokka.allModulesPage.templates

import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.dokka.base.templating.Command
import org.jetbrains.dokka.base.templating.ResolveLinkCommand
import org.jetbrains.dokka.base.templating.parseJson
import org.jetbrains.dokka.plugability.DokkaContext
import org.jsoup.Jsoup
import org.jsoup.nodes.Attributes
import org.jsoup.nodes.Element
import org.jsoup.parser.Tag
import java.io.File
import java.nio.file.Files

class DirectiveBasedTemplateProcessingStrategy(context: DokkaContext) : TemplateProcessingStrategy {
    override suspend fun process(input: File, output: File): Unit = coroutineScope {
        if (input.extension == "html") {
            launch {
                val document = withContext(IO) { Jsoup.parse(input, "UTF-8") }
                document.outputSettings().indentAmount(0).prettyPrint(false)
                document.select("dokka-template-command").forEach {
                    val command = parseJson<Command>(it.attr("data"))
                    if (command is ResolveLinkCommand) {
                        resolveLink(it, command)
                    }
                }
                withContext(IO) { Files.writeString(output.toPath(), document.outerHtml()) }
            }
        } else {
            launch(IO) {
                Files.copy(input.toPath(), output.toPath())
            }
        }
    }

    private fun resolveLink(it: Element, command: ResolveLinkCommand) {
        val attributes = Attributes().apply {
            put("href", "") // TODO: resolve
        }
        val children = it.childNodes().toList()
        val element = Element(Tag.valueOf("a"), "", attributes).apply {
            children.forEach { ch -> appendChild(ch) }
        }
        it.replaceWith(element)
    }
}