Skip to content

Commit c588c94

Browse files
committed
Add WebJar class for accessing WebJar files
1 parent 2cfc699 commit c588c94

File tree

1 file changed

+36
-12
lines changed

1 file changed

+36
-12
lines changed

build.scala

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -405,13 +405,9 @@ object LaikaCustomizations {
405405
}
406406

407407
val Icons = {
408-
def loadFaIcon(prefix: String, name: String) = {
409-
val resourcePath =
410-
"/META-INF/resources/webjars/fortawesome__fontawesome-free/7.2.0"
411-
val inputStream =
412-
getClass.getResourceAsStream(s"$resourcePath/svgs/$prefix/$name.svg")
413-
String(inputStream.readAllBytes())
414-
}
408+
val fa = WebJar("fortawesome__fontawesome-free")
409+
def loadFaIcon(prefix: String, name: String) =
410+
fa.load(s"svgs/$prefix/$name.svg")
415411

416412
Map(
417413
// brands
@@ -439,11 +435,9 @@ object KaTeX {
439435
import org.graalvm.polyglot.*
440436
import scala.jdk.CollectionConverters.*
441437

442-
private def loadKaTeX(): String = {
443-
val resourcePath = "/META-INF/resources/webjars/katex/0.16.44/dist/katex.js"
444-
val inputStream = getClass.getResourceAsStream(resourcePath)
445-
String(inputStream.readAllBytes())
446-
}
438+
private val katexJar = WebJar("katex")
439+
440+
private def loadKaTeX(): String = katexJar.load("dist/katex.js")
447441

448442
private lazy val katex = {
449443
val ctx = Context
@@ -476,6 +470,36 @@ object KaTeX {
476470

477471
}
478472

473+
// Provides access to resources of a bundled WebJar.
474+
class WebJar(artifactId: String) {
475+
private val version: String =
476+
val propsPath = s"META-INF/maven/org.webjars.npm/$artifactId/pom.properties"
477+
val stream = Thread
478+
.currentThread()
479+
.getContextClassLoader
480+
.getResourceAsStream(propsPath)
481+
if stream == null then
482+
throw IllegalStateException(
483+
s"Could not find pom.properties for webjar '$artifactId' on the classpath."
484+
)
485+
val props = java.util.Properties()
486+
props.load(stream)
487+
props.getProperty("version")
488+
489+
// Load a resource from this WebJar as a String, uses relative paths.
490+
def load(path: String): String =
491+
val resourcePath = s"META-INF/resources/webjars/$artifactId/$version/$path"
492+
val stream = Thread
493+
.currentThread()
494+
.getContextClassLoader
495+
.getResourceAsStream(resourcePath)
496+
if stream == null then
497+
throw IllegalStateException(
498+
s"Could not find resource '$path' in webjar '$artifactId' ($version)."
499+
)
500+
String(stream.readAllBytes())
501+
}
502+
479503
object Redirects {
480504
import laika.io.model.InputTree
481505
import laika.ast.Path.Root

0 commit comments

Comments
 (0)