Skip to content

Commit

Permalink
feat(svg): introduce style tags parsing
Browse files Browse the repository at this point in the history
This commit introduces the ability to parse CSS code within `<style>` tags in SVG files.

It adds a new `SvgStyleNode` class to represent `<style>` elements and stores the parsed CSS as an Abstract Syntax Tree (AST) for later use.
  • Loading branch information
rafaeltonholo committed Dec 11, 2024
1 parent 37969e3 commit 9b88ed2
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ class SvgRootNode(
*/
val gradients: HashMap<String, SvgGradient<*>> = hashMapOf()

val styles: MutableList<SvgStyleNode> = mutableListOf()

/**
* The transform applied to the entire SVG.
* If the SVG has a viewBox with an offset (x or y not 0), a translation
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package dev.tonholo.s2c.domain.svg

import dev.tonholo.s2c.domain.xml.XmlNode
import dev.tonholo.s2c.domain.xml.XmlParentNode
import dev.tonholo.s2c.domain.xml.XmlTextNode
import dev.tonholo.s2c.extensions.firstInstanceOf
import dev.tonholo.s2c.lexer.css.CssTokenizer
import dev.tonholo.s2c.lexer.css.CssTokenKind
import dev.tonholo.s2c.parser.ast.AstParser
import dev.tonholo.s2c.parser.ast.css.syntax.node.StyleSheet

class SvgStyleNode(
parent: XmlParentNode,
override val children: MutableSet<XmlNode>,
override val attributes: MutableMap<String, String>,
) : SvgElementNode<SvgStyleNode>(parent, children, attributes, tagName = TAG_NAME), SvgNode {
override val constructor = ::SvgStyleNode
override val tagName: String = TAG_NAME
val content: String by lazy {
children
.firstInstanceOf<XmlTextNode>()
.content
}
private var _tree: StyleSheet? = null
val tree: StyleSheet
get() = checkNotNull(_tree) {
"Css tree is not resolved. Did you forget to call `resolveTree()`?"
}

override fun toString(): String = toJsString {
}

internal fun resolveTree(parser: AstParser<CssTokenKind, StyleSheet>) {
val tokens = CssTokenizer().tokenize(content).toList()
_tree = parser.parse(tokens)
}

companion object {
const val TAG_NAME = "style"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,17 @@ abstract class XmlChildNode(
}
}

class XmlTextNode(
parent: XmlParentNode,
val content: String,
) : XmlChildNode(parent) {
override val tagName: String = parent.tagName
override val attributes: MutableMap<String, String> = parent.attributes
override fun toString(): String = toJsString {
append("\"content\": $content")
}
}

data class XmlRootNode(
override val tagName: String = "#root",
override val children: MutableSet<XmlNode>,
Expand Down

0 comments on commit 9b88ed2

Please sign in to comment.