Skip to content

Commit

Permalink
Improve CssBuilder syntactic sugar with DSL
Browse files Browse the repository at this point in the history
  • Loading branch information
iamgio committed Jun 23, 2024
1 parent 0e85d48 commit 90aca9e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class CssBuilder {
* @param value CSS entry value
* @return this for concatenation
*/
fun entry(
private fun entry(
key: String,
value: String?,
) = apply {
Expand All @@ -30,13 +30,31 @@ class CssBuilder {
* @param value CSS entry value
* @return this for concatenation
*/
fun entry(
private fun entry(
key: String,
value: RenderRepresentable?,
) = entry(key, value?.asCSS)

/**
* Shorthand syntactic sugar for [entry].
* @see entry
*/
infix fun String.value(value: RenderRepresentable?) = entry(this, value)

/**
* @return a string representation of the CSS entries contained within this builder
*/
fun build() = entries.entries.joinToString(separator = " ") { "${it.key}: ${it.value};" }
}

/**
* Example usage:
* ```
* val css = css {
* "color" value Color(255, 0, 0)
* "font-size" value Size(16, SizeUnit.PX)
* }
* ```
* @return a string representation of CSS entries contained within the builder.
*/
fun css(init: CssBuilder.() -> Unit): String = CssBuilder().apply(init).build()
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@ class QuarkdownHtmlNodeRenderer(context: Context) : BaseHtmlNodeRenderer(context
.attribute("class", "stack stack-" + node.orientation.asCSS)
.attribute(
"style",
CssBuilder()
.entry("justify-content", node.mainAxisAlignment.asCSS)
.entry("align-items", node.crossAxisAlignment.asCSS)
.entry("gap", node.gap)
.build(),
css {
"justify-content" value node.mainAxisAlignment
"align-items" value node.crossAxisAlignment
"gap" value node.gap
},
)
.build()
}
Expand All @@ -87,12 +87,11 @@ class QuarkdownHtmlNodeRenderer(context: Context) : BaseHtmlNodeRenderer(context
// Box style.
optionalAttribute(
"style",
CssBuilder()
.entry("padding", node.padding)
.entry("background-color", node.backgroundColor)
.entry("color", node.foregroundColor)
.build()
.takeUnless { it.isEmpty() },
css {
"padding" value node.padding
"background-color" value node.backgroundColor
"color" value node.foregroundColor
}.takeUnless { it.isEmpty() },
)
}

Expand Down

0 comments on commit 90aca9e

Please sign in to comment.