From 8cd483351c1975e8692ffdf46d270a4edc0a2bfe Mon Sep 17 00:00:00 2001 From: Lanius Trolling Date: Sun, 14 Apr 2024 06:40:32 -0400 Subject: [PATCH] Optimize and refactor code --- src/jvmMain/kotlin/info/mechyrdia/data/DataFiles.kt | 10 ++++++---- src/jvmMain/kotlin/info/mechyrdia/lore/ParserHtml.kt | 12 ++++-------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/jvmMain/kotlin/info/mechyrdia/data/DataFiles.kt b/src/jvmMain/kotlin/info/mechyrdia/data/DataFiles.kt index b1127d9..d5b5a02 100644 --- a/src/jvmMain/kotlin/info/mechyrdia/data/DataFiles.kt +++ b/src/jvmMain/kotlin/info/mechyrdia/data/DataFiles.kt @@ -24,17 +24,19 @@ import java.io.File import java.nio.ByteBuffer import java.nio.file.FileAlreadyExistsException import java.nio.file.Files -import java.nio.file.LinkOption -import java.nio.file.attribute.BasicFileAttributeView import java.nio.file.attribute.BasicFileAttributes import java.time.Instant import kotlin.String import kotlin.time.Duration.Companion.hours +fun StoragePath.getContentType(): ContentType { + val extension = elements.last().substringAfter('.', "") + return if (extension.isEmpty()) ContentType.Text.Plain else ContentType.defaultForFileExtension(extension) +} + suspend fun ApplicationCall.respondStoredFile(path: StoragePath) { val content = FileStorage.instance.readFile(path) ?: return respond(HttpStatusCode.NotFound) - val extension = path.elements.last().substringAfter('.', "") - val type = if (extension.isEmpty()) ContentType.Text.Plain else ContentType.defaultForFileExtension(extension) + val type = path.getContentType() attributes.put(StoragePathAttributeKey, path) respondBytes(content, type) diff --git a/src/jvmMain/kotlin/info/mechyrdia/lore/ParserHtml.kt b/src/jvmMain/kotlin/info/mechyrdia/lore/ParserHtml.kt index 614a0ee..c6fbe09 100644 --- a/src/jvmMain/kotlin/info/mechyrdia/lore/ParserHtml.kt +++ b/src/jvmMain/kotlin/info/mechyrdia/lore/ParserHtml.kt @@ -4,7 +4,7 @@ import info.mechyrdia.JsonStorageCodec import io.ktor.util.* import kotlinx.html.* import kotlinx.html.org.w3c.dom.events.Event -import kotlinx.html.stream.appendHTML +import kotlinx.html.stream.createHTML import kotlinx.serialization.json.JsonPrimitive import kotlin.text.toCharArray @@ -14,13 +14,9 @@ typealias HtmlBuilderSubject = TagConsumer<*>.() -> Any? context(T) operator fun (TagConsumer<*>.() -> Any?).unaryPlus() = with(HtmlLexerTagConsumer(consumer)) { this@unaryPlus() } -fun (TagConsumer<*>.() -> Any?).toFragment() = StringBuilder() - .appendHTML() - .also { builder -> - with(HtmlLexerTagConsumer(builder)) { this@toFragment() } - } - .finalize() - .toString() +fun (TagConsumer<*>.() -> Any?).toFragment() = createHTML().also { builder -> + with(HtmlLexerTagConsumer(builder)) { this@toFragment() } +}.finalize() class HtmlLexerTagConsumer private constructor(private val downstream: TagConsumer<*>) : TagConsumer { override fun onTagStart(tag: Tag) { -- 2.25.1