Skip to content

Commit

Permalink
V0.2.0: Implement static renderer to html
Browse files Browse the repository at this point in the history
  • Loading branch information
LimeBeck committed Jan 31, 2024
1 parent 21efe0e commit 96a2401
Show file tree
Hide file tree
Showing 6 changed files with 101 additions and 25 deletions.
7 changes: 3 additions & 4 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ yarn.ignoreScripts = false

kotlinVersion=1.9.20

revealKtVersion=0.1.4
revealKtVersion=0.2.0

kotlinCoroutinesVersion=1.7.3
ktorVersion=2.1.3
dokkaVersion=1.8.20

repo.uri=https://s01.oss.sonatype.org/service/local/staging/deploy/maven2
repo.username=limebeck
repo.password=***REMOVED***

repo.uri=https://maven.pkg.github.com/LimeBeck/reveal-kt
11 changes: 9 additions & 2 deletions reveal-kt/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,12 @@ application {
mainClass.set("dev.limebeck.application.ApplicationKt")
}

val copyJsTask = tasks.named<Copy>("jvmProcessResources") {
val jvmProcessResources = tasks.named<Copy>("jvmProcessResources")

val jsCopyTask = tasks.create<Copy>("jsCopyTask") {
val jsBrowserDistribution = tasks.named("jsBrowserDistribution")
from(jsBrowserDistribution)
into(jvmProcessResources.get().destinationDir.resolve("js"))
excludes.add("*.zip")
excludes.add("*.tar")
}
Expand All @@ -113,12 +116,16 @@ val stubJavaDocJar by tasks.registering(Jar::class) {

// tasks to create an executable jar with all components of the app
val shadow = tasks.getByName<ShadowJar>("shadowJar") {
dependsOn(copyJsTask) // make sure JS gets compiled first
dependsOn(jsCopyTask) // make sure JS gets compiled first
archiveClassifier.set("")
mergeServiceFiles()
finalizedBy(stubJavaDocJar)
}

tasks.named("jvmJar") {
dependsOn(jsCopyTask)
}

tasks.named("publish") {
dependsOn(shadow)
}
Expand Down
2 changes: 1 addition & 1 deletion reveal-kt/app/src/jvmMain/kotlin/Application.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import com.github.ajalt.clikt.completion.completionOption
import com.github.ajalt.clikt.core.subcommands

fun main(args: Array<String>) = RevealKtApplication()
.subcommands(RunServer(), InitTemplate())
.subcommands(RunServer(), InitTemplate(), RenderToFile())
.completionOption()
.main(args)
66 changes: 61 additions & 5 deletions reveal-kt/app/src/jvmMain/kotlin/Commands.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@ import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.file
import com.github.ajalt.clikt.parameters.types.int
import com.github.ajalt.clikt.parameters.types.path
import dev.limebeck.application.server.Config
import dev.limebeck.application.server.ServerConfig
import dev.limebeck.application.server.runServer
import dev.limebeck.application.server.*
import dev.limebeck.application.templates.generatePresentationTemplate
import dev.limebeck.revealkt.RevealkConfig
import dev.limebeck.revealkt.scripts.RevealKtScriptLoader
import java.io.File
import java.nio.file.Path
import kotlin.io.path.div
import kotlin.io.path.pathString
import kotlin.io.path.*

class RevealKtApplication : CliktCommand(
printHelpOnEmptyArgs = true,
Expand Down Expand Up @@ -58,6 +56,64 @@ class RunServer : CliktCommand(name = "run", help = "Serve presentation with liv
}
}

class RenderToFile : CliktCommand(name = "render", help = "Render to file") {
val outputDir: Path? by option(help = "Output dir").path(
mustBeWritable = true,
canBeDir = true,
canBeFile = false
)
val script: File by argument(help = "Script file").file(canBeDir = false, mustBeReadable = true)

init {
context {
helpFormatter = {
MordantHelpFormatter(
showDefaultValues = true,
context = it
)
}
}
}

@OptIn(ExperimentalPathApi::class)
override fun run() {
val scriptLoader = RevealKtScriptLoader()
when (val loadResult = scriptLoader.loadScript(script)) {
is RevealKtScriptLoader.LoadResult.Success -> {
val outputDir = outputDir ?: Path.of("./out")
if (outputDir.notExists()) {
outputDir.createDirectories()
}

val resources = getResourcesList("js").filter {
it.isFont() || it.name in listOf("revealkt.js", "favicon.ico")
}

resources.forEach {
it.copyTo(outputDir.resolve(it.name))
}

val assetsPath = script.parentFile.resolve("assets").toPath()
if (assetsPath.exists()) {
// println("<4a6f2742> Copy assets from $assetsPath to $outputDir")
assetsPath.copyToRecursively(outputDir.resolve("assets"), followLinks = true, overwrite = true)
}

val result = renderLoadResult(loadResult)
outputDir.resolve("index.html")
.createFile()
.writeText(result)
}

is RevealKtScriptLoader.LoadResult.Error -> {
loadResult.diagnostic.forEach {
logger.error("$it")
}
}
}
}
}

class InitTemplate : CliktCommand(name = "init", help = "Create presentation template") {
val name: String by argument(help = "Presentation name")
val basePath: Path by option(help = "Template dir")
Expand Down
18 changes: 18 additions & 0 deletions reveal-kt/app/src/jvmMain/kotlin/Utils.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package dev.limebeck.application

import java.nio.file.FileSystems
import java.nio.file.Path
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.name

fun printMessage(message: String, symbol: String = "*", minRowLength: Int = 40, borderSize: Int = 2) {
val lines = message.lines()
val rowLength = maxOf(lines.maxOf { it.length }, minRowLength)
Expand All @@ -21,3 +26,16 @@ fun printMessage(message: String, symbol: String = "*", minRowLength: Int = 40,

fun String.printToConsole(symbol: String = "*", minRowLength: Int = 40, borderSize: Int = 2) =
printMessage(this, symbol, minRowLength, borderSize)

fun getResourcesList(path: String): List<Path> {
val classLoader = {}::class.java.classLoader
val resource = classLoader.getResource(path).toURI()
FileSystems.newFileSystem(resource, mapOf("create" to "true"))
return Path.of(resource).listDirectoryEntries().map {
it
}
}

fun Path.isFont() = name.endsWith(".woff")
|| name.endsWith(".eot")
|| name.endsWith(".ttf")
22 changes: 9 additions & 13 deletions reveal-kt/app/src/jvmMain/kotlin/server/Server.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,12 @@ import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.produceIn
import kotlinx.coroutines.flow.*
import org.slf4j.LoggerFactory
import java.awt.Desktop
import java.io.File
import java.net.URI
import java.util.*
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
import kotlin.time.measureTimedValue

Expand All @@ -42,7 +38,7 @@ data class ServerConfig(

val logger = LoggerFactory.getLogger("ServerLogger")

@OptIn(ExperimentalTime::class, FlowPreview::class)
@OptIn(FlowPreview::class)
fun runServer(config: Config) {
println("Starting application...")
val startTime = TimeSource.Monotonic.markNow()
Expand Down Expand Up @@ -72,20 +68,19 @@ fun runServer(config: Config) {
}

coroutineScope.launch {
updatedFilesStateFlow.collect { sf ->
if (sf != null && (
sf.any { it.path.contains(config.script.name) }
|| sf.any { it.path.contains("assets") }
)
) {
updatedFilesStateFlow
.filterNotNull()
.filter { sf ->
sf.any { it.path.contains(config.script.name) }
|| sf.any { it.path.contains("assets") }
}.collect {
val result = measureTimedValue {
val loadResult = scriptLoader.loadScript(config.script)
renderLoadResult(loadResult)
}
logger.info("<00596867> Render time: ${result.duration}")
renderedTemplateStateFlow.emit(result.value)
}
}
}

embeddedServer(CIO, environment = applicationEngineEnvironment {
Expand Down Expand Up @@ -124,6 +119,7 @@ fun runServer(config: Config) {
) {
withContext(Dispatchers.IO) {
this::class.java.classLoader.getResourceAsStream(resourceName)?.readAllBytes()
?: this::class.java.classLoader.getResourceAsStream("js/$resourceName")?.readAllBytes()
?: throw NotFoundException()
}
}
Expand Down

0 comments on commit 96a2401

Please sign in to comment.