splitTopLevelSpaces function
Splits input on runs of top-level whitespace.
Whitespace inside brackets or quotes does not split, so
inset 0px 0px 0px 2px light-dark(rgba(5, 54, 89, 0.15), #FFF) yields six
parts, the last being the whole light-dark(...) expression.
Implementation
List<String> splitTopLevelSpaces(String input) {
final parts = <String>[];
final buffer = StringBuffer();
var depth = 0;
String? quote;
var isEscaped = false;
void flush() {
if (buffer.isNotEmpty) {
parts.add(buffer.toString());
buffer.clear();
}
}
for (var i = 0; i < input.length; i++) {
final char = input[i];
if (quote != null) {
buffer.write(char);
if (isEscaped) {
isEscaped = false;
} else if (char == r'\') {
isEscaped = true;
} else if (char == quote) {
quote = null;
}
continue;
}
if (char == '"' || char == "'") {
quote = char;
buffer.write(char);
continue;
}
if (char == '(') {
depth++;
} else if (char == ')') {
depth = math.max(0, depth - 1);
} else if (depth == 0 && char.trim().isEmpty) {
flush();
continue;
}
buffer.write(char);
}
flush();
return parts;
}