use std::collections::BTreeMap;
use std::path::PathBuf;
use super::imports::leading_tag;
use super::own_stem;
use super::text::{closing_angle, closing_paren};
pub(super) fn reactive_closures(body: &str, reactive: &BTreeMap<String, Vec<String>>) -> String {
let mut out = String::with_capacity(body.len());
for line in body.split_inclusive('\n') {
let Some(props) = leading_tag(line).and_then(|tag| reactive.get(tag)) else {
out.push_str(line);
continue;
};
let mut rewritten = line.to_string();
for prop in props {
let needle = format!("{prop}:(");
let Some(at) = rewritten.find(&needle) else {
continue;
};
let open = at + needle.len() - 1;
let Some(close) = closing_paren(rewritten.as_bytes(), open) else {
continue;
};
let inner = &rewritten[open + 1..close];
if !inner.trim_start().starts_with('|') && !inner.trim_start().starts_with("move |") {
continue;
}
rewritten = format!(
"{}{prop}:(Reactive::of({inner})){}",
&rewritten[..at],
&rewritten[close + 1..]
);
}
out.push_str(&rewritten);
}
out
}
pub(super) fn reactive_props(sources: &[PathBuf]) -> BTreeMap<String, Vec<String>> {
let mut out = BTreeMap::new();
for path in sources {
let Ok(source) = std::fs::read_to_string(path) else {
continue;
};
let Some(at) = source.find("pub struct Props {") else {
continue;
};
let Some(end) = source[at..].find("\n}").map(|i| at + i) else {
continue;
};
let (_, names) = rewrite_boxed_props(&source[at..end]);
if !names.is_empty() {
out.insert(own_stem(path).to_string(), names);
}
}
out
}
pub(super) fn shared_handlers(body: &str) -> String {
let Some(at) = body.find("pub struct Props {") else {
return body.to_string();
};
let Some(end) = body[at..].find("\n}").map(|i| at + i) else {
return body.to_string();
};
let (declaration, reactive) = rewrite_boxed_props(&body[at..end]);
if declaration == body[at..end] {
return body.to_string();
}
let mut rest = format!("{}{}", &declaration, &body[end..]);
for name in &reactive {
rest = rest.replace(&format!("(props.{name})()"), &format!("props.{name}.get()"));
}
let out = format!("{}{rest}", &body[..at]);
match !out.contains("Rc<dyn Fn") || out.contains("use std::rc::Rc;") || out.contains("::rc::{")
{
true => out,
false => format!("use std::rc::Rc;\n\n{out}"),
}
}
pub(super) fn rewrite_boxed_props(declaration: &str) -> (String, Vec<String>) {
let declaration =
&declaration.replace("#[props(default = Box::new(", "#[props(default = Rc::new(");
let mut out = String::with_capacity(declaration.len());
let mut reactive = Vec::new();
let mut rest = declaration.as_str();
while let Some((at, owner)) = ["Box<dyn Fn", "Rc<dyn Fn"]
.iter()
.filter_map(|owner| rest.find(owner).map(|at| (at, *owner)))
.min()
{
let head = owner.len() - "<dyn Fn".len();
let Some(close) = closing_angle(rest, at + head) else {
out.push_str(&rest[..at + head]);
rest = &rest[at + head..];
continue;
};
out.push_str(&rest[..at]);
let inner = &rest[at + head + 1..close];
let reads = inner
.split_once("->")
.filter(|(args, _)| args.trim().ends_with("()"));
match reads {
Some((_, yields)) => {
if let Some(name) = field_name(&out) {
reactive.push(name);
}
out.push_str(&format!("Reactive<{}>", yields.trim()));
if rest[close + 1..].starts_with(" = Box::new(") {
out.push_str(" = Reactive::of(");
rest = &rest[close + 1 + " = Box::new(".len()..];
continue;
}
}
None => out.push_str(&format!("Rc<{inner}>")),
}
rest = &rest[close + 1..];
}
out.push_str(rest);
(permissive(&out, &reactive), reactive)
}
pub(super) fn field_name(so_far: &str) -> Option<String> {
let line = so_far.rsplit('\n').next()?;
let (name, _) = line.rsplit_once(':')?;
Some(name.trim().trim_start_matches("pub ").to_string())
}
pub(super) fn permissive(declaration: &str, reactive: &[String]) -> String {
let mut out = String::with_capacity(declaration.len());
for line in declaration.split_inclusive('\n') {
let names = line
.split_once(':')
.map(|(name, _)| name.trim().trim_start_matches("pub ").to_string());
let wants = names.is_some_and(|name| reactive.contains(&name));
if wants && !out.trim_end().ends_with(']') {
let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
out.push_str(&format!("{indent}#[props(into)]\n"));
}
out.push_str(line);
}
out
}