From 8338bc4f33743b6274dc273bef354382f839f072 Mon Sep 17 00:00:00 2001 From: Lanius Trolling Date: Sat, 6 Apr 2024 12:35:50 -0400 Subject: [PATCH] Reduce recursion, remove redundancy, and extract expression --- .../kotlin/info/mechyrdia/lore/parser_html.kt | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/jvmMain/kotlin/info/mechyrdia/lore/parser_html.kt b/src/jvmMain/kotlin/info/mechyrdia/lore/parser_html.kt index 06a91bf..862a56c 100644 --- a/src/jvmMain/kotlin/info/mechyrdia/lore/parser_html.kt +++ b/src/jvmMain/kotlin/info/mechyrdia/lore/parser_html.kt @@ -22,7 +22,7 @@ fun (TagConsumer<*>.() -> Any?).toFragment() = buildString { builder.finalize() } -class HtmlLexerTagConsumer(private val downstream: TagConsumer<*>) : TagConsumer { +class HtmlLexerTagConsumer private constructor(private val downstream: TagConsumer<*>) : TagConsumer { override fun onTagStart(tag: Tag) { downstream.onTagStart(tag) } @@ -58,6 +58,14 @@ class HtmlLexerTagConsumer(private val downstream: TagConsumer<*>) : TagConsumer override fun finalize() { // no-op } + + companion object { + operator fun invoke(downstream: TagConsumer<*>) = + if (downstream is HtmlLexerTagConsumer) + downstream + else + HtmlLexerTagConsumer(downstream) + } } context(C) @@ -66,7 +74,6 @@ operator fun > String.unaryPlus() = onTagContent(this) context(C) operator fun > Entities.unaryPlus() = onTagContentEntity(this) -context(C) fun > C.unsafe(block: Unsafe.() -> Unit) = onTagContentUnsafe(block) fun ParserTree.shouldSplitSections(): Boolean = firstOrNull()?.let { @@ -77,6 +84,12 @@ fun ParserTree.splitSections(): List = splitBefore { it is ParserTreeNode.Tag && it.tag.lowercase() == "h2" } +fun ParserTreeNode.isWhitespace() = when (this) { + is ParserTreeNode.Text -> text.isBlank() + ParserTreeNode.LineBreak -> true + is ParserTreeNode.Tag -> false +} + fun ParserTreeNode.isParagraph(inlineTags: Set): Boolean = when (this) { is ParserTreeNode.Text -> true ParserTreeNode.LineBreak -> false @@ -180,7 +193,7 @@ object HtmlLexerProcessor : LexerTagFallback, nodes: ParserTree): HtmlBuilderSubject { - return combine(env, nodes.filter { it !is ParserTreeNode.Text || it.text.isNotBlank() }.map(env::processNode)) + return combine(env, nodes.filterNot(ParserTreeNode::isWhitespace).map(env::processNode)) } override fun combine(env: LexerTagEnvironment, subjects: List): HtmlBuilderSubject { -- 2.25.1