use super::imports::leading_token;
use super::text::{closing_paren, replace_outside_strings, string_end, top_level_space};
pub(super) const DIRECTIVES: &[&str] = &[
"transition",
"hover_style",
"active_style",
"disabled_style",
"focus_style",
"cols",
"stroke_width",
"drag_button",
];
pub(super) fn colonise(body: &str) -> String {
let mut out = String::with_capacity(body.len());
for line in body.split_inclusive('\n') {
out.push_str(&colonise_line(line));
}
out
}
pub(super) fn colonise_line(line: &str) -> String {
if leading_token(line).is_some_and(is_control_flow) {
return line.to_string();
}
let bytes = line.as_bytes();
let mut out = String::with_capacity(line.len());
let mut i = 0;
while i < line.len() {
if let Some(end) = string_end(bytes, i) {
out.push_str(&line[i..end]);
i = end;
continue;
}
if bytes[i] == b'(' && i > 0 && bytes[i - 1] == b':' {
let end = closing_paren(bytes, i).map(|c| c + 1).unwrap_or(line.len());
out.push_str(&line[i..end]);
i = end;
continue;
}
let step = line[i..].chars().next().unwrap().len_utf8();
let Some((key, open)) = key_before_paren(line, i) else {
out.push_str(&line[i..i + step]);
i += step;
continue;
};
let Some(close) = closing_paren(bytes, open) else {
out.push_str(&line[i..i + step]);
i += step;
continue;
};
if DIRECTIVES.contains(&key) {
out.push_str(&line[i..=close]);
i = close + 1;
continue;
}
let inner = &line[open + 1..close];
out.truncate(out.len() - key.len());
out.push_str(key);
out.push(':');
match top_level_space(inner) || inner.trim_start().starts_with("::") {
true => out.push_str(&format!("({inner})")),
false => out.push_str(inner),
}
i = close + 1;
}
out
}
pub(super) fn is_control_flow(word: &str) -> bool {
matches!(word, "if" | "else" | "for" | "let" | "match" | "while")
}
pub(super) fn key_before_paren(line: &str, i: usize) -> Option<(&str, usize)> {
let bytes = line.as_bytes();
if bytes[i] != b'(' {
return None;
}
let start = line[..i]
.rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.map(|at| at + 1)
.unwrap_or(0);
let key = &line[start..i];
let leads_ok = key
.chars()
.next()
.is_some_and(|c| c.is_ascii_lowercase() || c == '_');
let preceded_by_space = start == 0 || bytes[start - 1].is_ascii_whitespace();
(!key.is_empty() && leads_ok && preceded_by_space).then_some((key, i))
}
pub(super) fn i18n_macro(body: &str) -> String {
let mut out = String::with_capacity(body.len());
let mut rest = body;
while let Some(at) = rest.find(":t\"") {
let Some(end) = string_end(rest.as_bytes(), at + 2) else {
break;
};
out.push_str(&rest[..at + 1]);
out.push_str("t!(");
out.push_str(&rest[at + 2..end]);
out.push(')');
rest = &rest[end..];
}
out.push_str(rest);
out
}
pub(super) fn clip_shapes(body: &str) -> String {
replace_outside_strings(body, |chunk| {
chunk
.replace("clip:x", "clip:Clip::x()")
.replace("clip:y", "clip:Clip::y()")
.replace("clip:both", "clip")
})
}