Files
image/image/svg/paint.sakura
T
2026-10-28 08:29:27 -05:00

73 lines
2.2 KiB
Plaintext

#! Contains paints, as a fill or stroke gives one: none, the element's own
#! color, a color, or a gradient by its ID, with what paints where it can't be
#! found.
module image::svg;
# What paints a fill or stroke.
enum paint_kind: u8 {
none,
color,
current, #! The element's `color`.
url, #! A gradient, by its ID, or the fallback after it.
}
struct paint {
var kind: paint_kind;
var color: color;
var url: strview;
var fallback: paint_kind = paint_kind::none; #! What paints where the gradient can't: none, a color, or `currentColor`.
}
# Reads a paint: `none`, `currentColor`, a color, or `url(#id)` and what paints
# where it can't.
def parse_paint(text: strview): maybe<paint> {
val trimmed := text.trim();
if trimmed == "none" {
return paint { kind = paint_kind::none };
}
if same_letters(trimmed, "currentColor") {
return paint { kind = paint_kind::current };
}
if trimmed.starts_with("url(") {
val close := trimmed.find(")") else { return nothing {}; };
var target := trimmed.substr(4, close - 4).trim();
if target.length >= 2 && (target[0] == '"' || target[0] == '\'') {
target = target.substr(1, target.length - 2);
}
if !target.starts_with("#") {
return nothing {};
}
var made := paint { kind = paint_kind::url, url = target.substr(1, target.length - 1) };
val rest := trimmed.substr(close + 1, trimmed.length - close - 1).trim();
if rest.length != 0 {
val fallback := parse_paint(rest) else { return nothing {}; };
made.fallback = fallback.kind;
made.color = fallback.color;
}
return made;
}
val found := parse_color(trimmed) else { return nothing {}; };
return paint { kind = paint_kind::color, color = found };
}
# The ID `url(#id)` names, or empty for `none` or what isn't one.
def url_of(text: strview): strview {
val read := parse_paint(text) else { return ""; };
return read.kind == paint_kind::url ? read.url : "";
}
# Whether two words are the same but for the case of their letters.
def same_letters(a: strview, b: strview): bool {
if a.length != b.length {
return false;
}
for index in 0..a.length {
if a[index].to_lower != b[index].to_lower {
return false;
}
}
return true;
}