package expo.modules.image.svg
/**
* Substitutes CSS custom properties — `var(--name)` and `var(--name, fallback)` — in an SVG
* document with caller-provided values, before the document is handed to a parser.
*
* Rewriting the source text, rather than asking the renderer to resolve the variables, keeps this
* independent of what the renderer supports. AndroidSVG has a CSS selector engine but no support
* for custom properties, and Apple's CoreSVG has neither, so neither platform could resolve
* `var()` on its own.
*
* Substitution happens only inside quoted attribute values and `` that closes the tag starting at [start]. */
private fun endOfTag(chars: CharArray, start: Int): Int {
var index = start + 1
var quote: Char? = null
while (index < chars.size) {
val char = chars[index]
when {
quote != null -> if (char == quote) {
quote = null
}
char == '"' || char == '\'' -> quote = char
char == '>' -> return index + 1
}
index += 1
}
return chars.size
}
private fun isSelfClosing(chars: CharArray, tagEnd: Int): Boolean {
var index = tagEnd - 2
while (index >= 0 && chars[index].isWhitespace()) {
index -= 1
}
return index >= 0 && chars[index] == '/'
}
// MARK: - Tag rewriting
/** Whitespace before the name through the closing quote — the span to keep or drop wholesale. */
private class Attribute(val name: String, val start: Int, val end: Int, val valueStart: Int, val valueEnd: Int)
/**
* Rewrites one element tag, substituting variables inside attribute values.
*
* An attribute whose entire value is a single unresolved variable with no fallback is dropped, so
* the renderer applies its own default for that property rather than seeing a value it cannot
* parse. Any tag this cannot confidently parse is copied through verbatim.
*/
private fun substituteTag(
chars: CharArray,
start: Int,
end: Int,
variables: Map
): String {
var index = start + 1
// The element name.
while (index < end && !chars[index].isWhitespace() && chars[index] != '>' && chars[index] != '/') {
index += 1
}
val prefixEnd = index
val attributes = mutableListOf()
while (index < end) {
val whitespaceStart = index
while (index < end && chars[index].isWhitespace()) {
index += 1
}
// The tag's own closing characters — no attributes left.
if (index >= end || chars[index] == '>' || chars[index] == '/') {
index = whitespaceStart
break
}
val attribute = readAttribute(chars, whitespaceStart, end)
// Something we don't understand — don't risk mangling it.
?: return String(chars, start, end - start)
attributes.add(attribute)
index = attribute.end
}
val out = StringBuilder()
out.append(chars, start, prefixEnd - start)
for (attribute in attributes) {
// A `style` attribute is a CSS declaration list, with the same escaping needs as a `