aboutsummaryrefslogtreecommitdiff
path: root/plugins/all-modules-page/src/main/kotlin/ResolveLinkCommandHandler.kt
blob: 7976ba5a0c29d507c137552e806c0beb9c2a8351 (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
package org.jetbrains.dokka.allModulesPage

import org.jetbrains.dokka.base.templating.Command
import org.jetbrains.dokka.base.templating.ResolveLinkCommand
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.plugin
import org.jetbrains.dokka.plugability.querySingle
import org.jetbrains.dokka.templates.CommandHandler
import org.jsoup.nodes.Attributes
import org.jsoup.nodes.Element
import org.jsoup.parser.Tag
import java.io.File

class ResolveLinkCommandHandler(context: DokkaContext) : CommandHandler {

    private val externalModuleLinkResolver =
        context.plugin<AllModulesPagePlugin>().querySingle { externalModuleLinkResolver }

    override fun handleCommandAsTag(command: Command, body: Element, input: File, output: File) {
        command as ResolveLinkCommand
        val link = externalModuleLinkResolver.resolve(command.dri, output)
        if (link == null) {
            val children = body.childNodes().toList()
            val attributes = Attributes().apply {
                put("data-unresolved-link", command.dri.toString())
            }
            val el = Element(Tag.valueOf("span"), "", attributes).apply {
                children.forEach { ch -> appendChild(ch) }
            }
            body.replaceWith(el)
            return
        }

        val attributes = Attributes().apply {
            put("href", link)
        }
        val children = body.childNodes().toList()
        val el = Element(Tag.valueOf("a"), "", attributes).apply {
            children.forEach { ch -> appendChild(ch) }
        }
        body.replaceWith(el)
    }

    override fun canHandle(command: Command): Boolean = command is ResolveLinkCommand
}