aboutsummaryrefslogtreecommitdiff
path: root/plugins/all-module-page/src/main/kotlin/templates/DirectiveBasedTemplateProcessing.kt
blob: e609397bb019a69622de1b9c38c2c3409fb9a4bc (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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.allModulesPage.AllModulesPagePlugin
import org.jetbrains.dokka.base.DokkaBase
import org.jetbrains.dokka.base.resolvers.shared.ExternalDocumentation
import org.jetbrains.dokka.base.resolvers.shared.PackageList
import org.jetbrains.dokka.base.templating.*
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.plugin
import org.jetbrains.dokka.plugability.query
import org.jsoup.Jsoup
import org.jsoup.nodes.*
import org.jsoup.parser.Tag
import java.io.File
import java.net.URL
import java.nio.file.Files
import java.util.concurrent.ConcurrentHashMap

class DirectiveBasedTemplateProcessingStrategy(private val context: DokkaContext) : TemplateProcessingStrategy {
    private val navigationFragments = ConcurrentHashMap<String, Element>()

    private val substitutors = context.plugin<AllModulesPagePlugin>().query { substitutor }

    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"))
                    when (command) {
                        is ResolveLinkCommand -> resolveLink(it, command, output)
                        is AddToNavigationCommand -> navigationFragments[command.moduleName] = it
                        is SubstitutionCommand -> substitute(it, TemplatingContext(input, output, it, command))
                        else -> context.logger.warn("Unknown templating command $command")
                    }
                }
                withContext(IO) { Files.writeString(output.toPath(), document.outerHtml()) }
            }
        } else {
            launch(IO) {
                Files.copy(input.toPath(), output.toPath())
            }
        }
    }

    private fun substitute(element: Element, commandContext: TemplatingContext<SubstitutionCommand>) {
        val regex = commandContext.command.pattern.toRegex()
        element.children().forEach { it.traverseToSubstitute(regex, commandContext) }

        val childrenCopy = element.children().toList()
        val position = element.elementSiblingIndex()
        val parent = element.parent()
        element.remove()

        parent.insertChildren(position, childrenCopy)
    }

    private fun Node.traverseToSubstitute(regex: Regex, commandContext: TemplatingContext<SubstitutionCommand>) {
        when (this) {
            is TextNode -> replaceWith(TextNode(wholeText.substitute(regex, commandContext)))
            is DataNode -> replaceWith(DataNode(wholeData.substitute(regex, commandContext)))
            is Element -> {
                attributes().forEach { attr(it.key, it.value.substitute(regex, commandContext)) }
                childNodes().forEach { it.traverseToSubstitute(regex, commandContext) }
            }
        }
    }

    private fun String.substitute(regex: Regex, commandContext: TemplatingContext<SubstitutionCommand>) = buildString {
        var lastOffset = 0
        regex.findAll(this@substitute).forEach { match ->
            append(this@substitute, lastOffset, match.range.first)
            append(findSubstitution(commandContext, match))
            lastOffset = match.range.last + 1
        }
        append(this@substitute, lastOffset, this@substitute.length)
    }

    private fun findSubstitution(commandContext: TemplatingContext<SubstitutionCommand>, match: MatchResult): String =
        substitutors.asSequence().mapNotNull { it.trySubstitute(commandContext, match) }.firstOrNull() ?: match.value

    override suspend fun finish(output: File) {
        val attributes = Attributes().apply {
            put("class", "sideMenu")
        }
        val node = Element(Tag.valueOf("div"), "", attributes)
        navigationFragments.entries.sortedBy { it.key }.forEach { (moduleName, command) ->
            command.select("a").forEach { a ->
                a.attr("href")?.also { a.attr("href", "${moduleName}/${it}") }
            }
            command.childNodes().toList().forEachIndexed { index, child ->
                if (index == 0) {
                    child.attr("id", "$moduleName-nav-submenu")
                }
                node.appendChild(child)
            }
        }

        withContext(IO) {
            Files.writeString(output.resolve("navigation.html").toPath(), node.outerHtml())
        }

        node.select("a").forEach { a ->
            a.attr("href")?.also { a.attr("href", "../${it}") }
        }
        navigationFragments.keys.forEach {
            withContext(IO) {
                Files.writeString(
                    output.resolve(it).resolve("navigation.html").toPath(),
                    node.outerHtml()
                )
            }
        }
    }

    private fun resolveLink(it: Element, command: ResolveLinkCommand, fileContext: File) {
        val elpFactory = context.plugin<DokkaBase>().query { externalLocationProviderFactory }

        val packageLists =
            context.configuration.modules.map { it.sourceOutputDirectory.resolve(it.relativePathToOutputDirectory) }
                .map { module ->
                    module to PackageList.load(
                        URL("file:" + module.resolve("package-list").path),
                        8,
                        true
                    )
                }.toMap()

        val externalDocumentations =
            packageLists.map { (module, pckgList) ->
                ExternalDocumentation(
                    URL("file:/${module.name}/${module.name}"),
                    pckgList!!
                )
            }

        val elps = elpFactory
            .flatMap { externalDocumentations.map { ed -> it.getExternalLocationProvider(ed) } }
            .filterNotNull()

        val absoluteLink = elps.mapNotNull { it.resolve(command.dri) }.firstOrNull()
        if (absoluteLink == null) {
            val children = it.childNodes().toList()
            val attributes = Attributes().apply {
                put("data-unresolved-link", command.dri.toString())
            }
            val element = Element(Tag.valueOf("span"), "", attributes).apply {
                children.forEach { ch -> appendChild(ch) }
            }
            it.replaceWith(element)
            return
        }

        val modulePath = context.configuration.outputDir.absolutePath.split(File.separator)
        val contextPath = fileContext.absolutePath.split(File.separator)
        val commonPathElements = modulePath.zip(contextPath)
            .takeWhile { (a, b) -> a == b }.count()

        // -1 here to not drop the last directory
        val link =
            (List(contextPath.size - commonPathElements - 1) { ".." } + modulePath.drop(commonPathElements)).joinToString(
                "/"
            ) + absoluteLink.removePrefix("file:")

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