replaceCssVarFunctions function
Replace var(...) function calls in a CSS value string using a lightweight
scanner that supports nested parentheses and quoted substrings.
Implementation
String replaceCssVarFunctions(String input, String Function(String varFunctionText) replacer) {
if (!input.contains('var(')) return input;
final int len = input.length;
final StringBuffer out = StringBuffer();
int i = 0;
while (i < len) {
final int idx = input.indexOf('var(', i);
if (idx == -1) {
out.write(input.substring(i));
break;
}
out.write(input.substring(i, idx));
final int open = idx + 3;
if (open >= len || input.codeUnitAt(open) != 0x28 /* ( */) {
// Should not happen, but fall back to literal copy.
out.write('var');
i = open;
continue;
}
int depth = 0;
String? quote;
bool escape = false;
int j = open;
for (; j < len; j++) {
final String ch = input[j];
final int cu = input.codeUnitAt(j);
if (quote != null) {
if (escape) {
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
quote = null;
}
continue;
}
if (ch == '"' || ch == '\'') {
quote = ch;
continue;
}
if (cu == 0x28 /* ( */) {
depth++;
} else if (cu == 0x29 /* ) */) {
depth--;
if (depth == 0) {
final String varText = input.substring(idx, j + 1);
out.write(replacer(varText));
i = j + 1;
break;
}
}
}
if (j >= len) {
// Unbalanced; append remainder as-is.
out.write(input.substring(idx));
break;
}
}
return out.toString();
}