Skip to content

Commit

Permalink
Add importCss helper for importing 3rd party styles into layers
Browse files Browse the repository at this point in the history
  • Loading branch information
DennisTsar committed Dec 17, 2024
1 parent 314d410 commit eb34fab
Showing 1 changed file with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.varabyte.kobweb.gradle.core.util

import kotlinx.html.HEAD
import kotlinx.html.STYLE
import kotlinx.html.TagConsumer
import kotlinx.html.stream.createHTML
import kotlinx.html.unsafe

object HtmlUtil {
// Workaround for generating child nodes without the containing <head> tag
Expand All @@ -23,3 +25,41 @@ object HtmlUtil {
fun serializeHeadContents(block: HEAD.() -> Unit): String =
createHTML(prettyPrint = false, xhtmlCompatible = true).headFragment(block)
}

/**
* Adds an [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) rule to import a CSS stylesheet,
* optionally loading it into a specific [CSS Cascade layer](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers).
*
* This can be useful when using a third party CSS library whose styles are a bit too aggressive and are interfering
* with your own styles.
*
* For example, replace a `<link>` tag with an `@import` rule:
*
* ```
* kobweb.app.index.head.add {
* // Before
* link(href = "/highlight.js/styles/dracula.css", rel = "stylesheet")
* // After
* style {
* importCss("/highlight.js/styles/dracula.css", layerName = "highlightjs")
* }
* }
* ```
*
* Then, register your new layer in an `@InitSilk` block:
*
* ```
* @InitSilk
* fun initSilk(ctx: InitSilkContext) {
* // Layer(s) referenced in build.gradle.kts
* ctx.stylesheet.cssLayers.add("highlightjs", after = SilkLayer.BASE)
* }
* ```
*
* @param url The URL of the CSS file to import. This can be an external URL or a path to a local `public` resource.
* @param layerName The cascade layer in which to load the stylesheet. **For this to have any effect, the layer
* MUST be registered in an `@InitSilk` block.**
*/
fun STYLE.importCss(url: String, layerName: String? = null) {
unsafe { raw("@import url(\"$url\")${if (layerName != null) " layer($layerName)" else ""};\n") }
}

0 comments on commit eb34fab

Please sign in to comment.