How do you embed runnable sample code in Dokka generated documentation

418 views Asked by At

I'm trying to add sample code to my API Reference.

I followed the pattern highlighted here https://androidessence.com/contributing-to-kotlin Was able to create my sample project and all the code runs, duplicating the _sampleUtils that the the kotlin stdlib source uses.

I configured my module to include the sample in the dokka configuration.

tasks.dokkaHtml {
    dokkaSourceSets.configureEach {
        samples.from("$projectDir/../module-samples/test/samples/SampleFile.kt")
    }
}

The sample correctly loads into and is displayed in the documentation for the function with a run button.

When I hit run though, it just comes back with Unresolved reference for all the symbols in my library. It also could not find assertPrint method from the _samplesUtils.kt file.

I don't see any other settings in the Dokka configuration for samples to make it include jar files for the library being documented.

1

There are 1 answers

0
Michael Krussel On

After researching I found out that the samples are using Kotlin playground. To add extra dependencies you need to create your own compiler server. https://github.com/AlexanderPrendota/kotlin-compiler-server.

You then modify the build.gradle.kts file with your extra dependencies.

The next part is updating the html generated by Dokka to point to your new server. I couldn't find a built in way to do that, so I implemented this.

dokkaHtml {
    doLast {
        def docTree = fileTree(
                dir: "${dokkaHtml.outputDirectory.get()}",
                includes: ["**/*.html"])
        docTree.each { file ->
            def text = file.text
            file.write(text.replace(
                    '<script src="https://unpkg.com/kotlin-playground@1" data-selector="code.runnablesample"></script>',
                    '<script src="https://unpkg.com/kotlin-playground@1" data-selector="code.runnablesample" data-server="http://localhost:8080"></script>'
            ))
        }
    }
}

You also have to create a custom little jar to replace test code types and functions with ones that work better for samples.