use super::{AttributeAction, ParserPlugin, ParserPluginArtifacts};
use crate::component_registry::Component;
use crate::tag_scan::find_tag_close;
use crate::{CssStrategy, Result};
use webui_protocol::FastElementData;
struct TrackedComponent {
tag_name: String,
html_content: String,
css_content: Option<String>,
}
pub struct FastV2ParserPlugin {
components: Vec<TrackedComponent>,
css_strategy: CssStrategy,
}
impl FastV2ParserPlugin {
#[must_use]
pub fn new() -> Self {
Self {
components: Vec::new(),
css_strategy: CssStrategy::Link,
}
}
pub fn set_css_strategy(&mut self, strategy: CssStrategy) {
self.css_strategy = strategy;
}
#[must_use]
pub fn take_component_templates(&self) -> Vec<(String, String)> {
self.components
.iter()
.map(|comp| {
let tmpl = generate_f_template(
&comp.tag_name,
&comp.html_content,
comp.css_content.as_deref(),
self.css_strategy,
);
(comp.tag_name.clone(), tmpl)
})
.collect()
}
}
impl Default for FastV2ParserPlugin {
fn default() -> Self {
Self::new()
}
}
impl ParserPlugin for FastV2ParserPlugin {
fn register_component_template(
&mut self,
tag_name: &str,
component: &Component,
_processed_template: &str,
) -> Result<()> {
if self.components.iter().any(|c| c.tag_name == tag_name) {
return Ok(());
}
self.components.push(TrackedComponent {
tag_name: tag_name.to_string(),
html_content: component.html_content.clone(),
css_content: component.css_content.clone(),
});
Ok(())
}
fn classify_attribute(&mut self, attr_name: &str) -> AttributeAction {
if attr_name.starts_with('@')
|| attr_name == "f-ref"
|| attr_name == "f-slotted"
|| attr_name == "f-children"
{
AttributeAction::SkipAndCountBinding
} else {
AttributeAction::Keep
}
}
fn finish_element(&mut self, binding_attribute_count: u32) -> Option<Vec<u8>> {
if binding_attribute_count > 0 {
Some(
FastElementData {
binding_count: binding_attribute_count,
}
.encode()
.to_vec(),
)
} else {
None
}
}
fn into_artifacts(self: Box<Self>) -> ParserPluginArtifacts {
ParserPluginArtifacts::ComponentTemplates(self.take_component_templates())
}
}
pub fn generate_f_template(
tag_name: &str,
html_content: &str,
css_content: Option<&str>,
css_strategy: CssStrategy,
) -> String {
let mut output = String::with_capacity(256);
output.push_str("<f-template name=\"");
output.push_str(tag_name);
output.push_str("\">\n");
let converted = convert_btr_to_fast(html_content);
let trimmed = minify_inter_tag_whitespace(converted.trim());
let css_injection = match css_strategy {
CssStrategy::Link => css_content.map(|_| {
let mut s = String::with_capacity(40 + tag_name.len());
s.push_str("<link rel=\"stylesheet\" href=\"");
s.push_str(tag_name);
s.push_str(".css\">");
s
}),
CssStrategy::Style => css_content.map(|css| {
let mut s = String::with_capacity(15 + css.len());
s.push_str("<style>");
s.push_str(css.trim());
s.push_str("</style>");
s
}),
CssStrategy::Module => None,
};
if trimmed.starts_with("<template") {
if let Some(close_pos) = trimmed.find('>') {
output.push_str(&trimmed[..close_pos]);
if css_strategy == CssStrategy::Module && css_content.is_some() {
output.push_str(" shadowrootadoptedstylesheets=\"");
output.push_str(tag_name);
output.push('"');
}
output.push('>');
if let Some(ref injection) = css_injection {
output.push_str(injection);
}
output.push_str(&trimmed[close_pos + 1..]);
} else {
output.push_str(&trimmed);
}
} else {
output.push_str("<template");
if css_strategy == CssStrategy::Module && css_content.is_some() {
output.push_str(" shadowrootadoptedstylesheets=\"");
output.push_str(tag_name);
output.push('"');
}
output.push('>');
if let Some(ref injection) = css_injection {
output.push_str(injection);
}
output.push_str(&trimmed);
output.push_str("</template>");
}
output.push_str("\n</f-template>\n");
output
}
fn convert_btr_to_fast(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let bytes = input.as_bytes();
let len = bytes.len();
let mut i = 0;
while i < len {
if bytes[i] == b'<' {
if let Some(consumed) = try_convert_tag(input, i, &mut result) {
i += consumed;
continue;
}
}
i = push_char_at(input, i, &mut result);
}
result
}
fn try_convert_tag(input: &str, pos: usize, result: &mut String) -> Option<usize> {
let remaining = &input[pos..];
if remaining.starts_with("</if>") {
result.push_str("</f-when>");
return Some(5);
}
if remaining.starts_with("</for>") {
result.push_str("</f-repeat>");
return Some(6);
}
if remaining.starts_with("</route>") {
result.push_str("</webui-route>");
return Some(8);
}
if starts_with_tag_name(remaining, "outlet") {
if let Some(close) = remaining.find('>') {
result.push_str("<outlet></outlet>");
return Some(close + 1);
}
}
if starts_with_tag_name(remaining, "if") {
if let Some(consumed) = convert_if_tag(remaining, result) {
return Some(consumed);
}
}
if starts_with_tag_name(remaining, "for") {
if let Some(consumed) = convert_for_tag(remaining, result) {
return Some(consumed);
}
}
if starts_with_tag_name(remaining, "route") {
if let Some(consumed) = convert_route_tag(remaining, result) {
return Some(consumed);
}
}
if remaining.starts_with("<") {
if starts_with_tag_name(remaining, "template") {
if let Some(consumed) = strip_shadowrootmode(remaining, result) {
return Some(consumed);
}
}
if let Some(consumed) = convert_complex_attrs(remaining, result) {
return Some(consumed);
}
}
None
}
fn starts_with_tag_name(s: &str, name: &str) -> bool {
if !s.starts_with('<') {
return false;
}
let after_bracket = &s[1..];
if !after_bracket.starts_with(name) {
return false;
}
let after_name = &after_bracket[name.len()..];
if after_name.is_empty() {
return false;
}
let next = after_name.as_bytes()[0];
next == b' ' || next == b'\t' || next == b'\n' || next == b'\r' || next == b'>'
}
fn convert_if_tag(tag_str: &str, result: &mut String) -> Option<usize> {
let close = find_tag_close(tag_str)?;
let tag_content = &tag_str[..=close];
let attr_value = extract_attribute_value(tag_content, "condition")?;
result.push_str("<f-when value=\"{{");
result.push_str(attr_value);
result.push_str("}}\">");
Some(close + 1)
}
fn convert_for_tag(tag_str: &str, result: &mut String) -> Option<usize> {
let close = find_tag_close(tag_str)?;
let tag_content = &tag_str[..=close];
let attr_value = extract_attribute_value(tag_content, "each")?;
result.push_str("<f-repeat value=\"{{");
result.push_str(attr_value);
result.push_str("}}\">");
Some(close + 1)
}
fn convert_route_tag(tag_str: &str, result: &mut String) -> Option<usize> {
let close = find_tag_close(tag_str)?;
let is_self_closing = tag_str[..=close].ends_with("/>");
let tag = &tag_str[..=close];
result.push_str("<webui-route");
if let Some(v) = extract_attribute_value(tag, "path") {
result.push_str(" path=\"");
result.push_str(v);
result.push('"');
}
if let Some(v) = extract_attribute_value(tag, "name") {
result.push_str(" name=\"");
result.push_str(v);
result.push('"');
}
if let Some(v) = extract_attribute_value(tag, "component") {
result.push_str(" component=\"");
result.push_str(v);
result.push('"');
}
if let Some(v) = extract_attribute_value(tag, "redirectTo") {
result.push_str(" redirectto=\"");
result.push_str(v);
result.push('"');
}
if tag.contains(" exact") {
result.push_str(" exact");
}
if tag.contains(" layout") {
result.push_str(" layout");
}
if let Some(v) = extract_attribute_value(tag, "query") {
result.push_str(" query=\"");
result.push_str(v);
result.push('"');
}
result.push_str(" style=\"display:none\"");
if is_self_closing {
result.push_str("></webui-route>");
} else {
result.push('>');
}
Some(close + 1)
}
fn extract_attribute_value<'a>(tag: &'a str, attr_name: &str) -> Option<&'a str> {
let mut search_from = 0;
loop {
let attr_pos = tag[search_from..].find(attr_name)?;
let abs_pos = search_from + attr_pos;
if abs_pos > 0 {
let prev = tag.as_bytes()[abs_pos - 1];
if prev != b' ' && prev != b'\t' && prev != b'\n' && prev != b'\r' {
search_from = abs_pos + attr_name.len();
continue;
}
}
let after_name = &tag[abs_pos + attr_name.len()..];
if !after_name.starts_with('=') {
search_from = abs_pos + attr_name.len();
continue;
}
let after_eq = &after_name[1..];
if after_eq.starts_with('"') {
let value_start = abs_pos + attr_name.len() + 2; let end_quote = tag[value_start..].find('"')?;
return Some(&tag[value_start..value_start + end_quote]);
}
return None;
}
}
fn convert_complex_attrs(tag_str: &str, result: &mut String) -> Option<usize> {
let close = find_tag_close(tag_str)?;
let tag_content = &tag_str[..=close];
if !tag_content.contains(":") || !tag_content.contains("{{") {
return None;
}
let mut converted = String::with_capacity(tag_content.len());
let tag_bytes = tag_content.as_bytes();
let tag_len = tag_bytes.len();
let mut j = 0;
let mut in_colon_attr_value = false;
while j < tag_len {
if !in_colon_attr_value {
if tag_bytes[j] == b':' && j > 0 && is_whitespace(tag_bytes[j - 1]) {
let attr_start = j;
j += 1;
while j < tag_len && tag_bytes[j] != b'=' && !is_whitespace(tag_bytes[j]) {
j += 1;
}
if j < tag_len && tag_bytes[j] == b'=' {
j += 1;
if j < tag_len && tag_bytes[j] == b'"' {
converted.push_str(&tag_content[attr_start..=j]);
j += 1;
in_colon_attr_value = true;
continue;
}
}
converted.push_str(&tag_content[attr_start..j]);
continue;
}
j = push_char_at(tag_content, j, &mut converted);
} else {
if tag_bytes[j] == b'"' {
converted.push('"');
j += 1;
in_colon_attr_value = false;
} else if j + 1 < tag_len && tag_bytes[j] == b'{' && tag_bytes[j + 1] == b'{' {
let expr_start = j + 2;
if let Some(end_offset) = tag_content[expr_start..].find("}}") {
let expr = &tag_content[expr_start..expr_start + end_offset];
converted.push('{');
converted.push_str(expr);
converted.push('}');
j = expr_start + end_offset + 2;
} else {
converted.push('{');
converted.push('{');
j += 2;
}
} else {
j = push_char_at(tag_content, j, &mut converted);
}
}
}
result.push_str(&converted);
Some(close + 1)
}
fn push_char_at(input: &str, pos: usize, out: &mut String) -> usize {
let bytes = input.as_bytes();
if bytes[pos].is_ascii() {
out.push(bytes[pos] as char);
pos + 1
} else {
let mut end = pos + 1;
while end < bytes.len() && !input.is_char_boundary(end) {
end += 1;
}
out.push_str(&input[pos..end]);
end
}
}
fn is_whitespace(b: u8) -> bool {
b == b' ' || b == b'\t' || b == b'\n' || b == b'\r'
}
fn minify_inter_tag_whitespace(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let bytes = input.as_bytes();
let len = bytes.len();
let mut i = 0;
while i < len {
if bytes[i] == b'>' && i + 1 < len {
result.push('>');
i += 1;
let ws_start = i;
while i < len && is_whitespace(bytes[i]) {
i += 1;
}
if i >= len || bytes[i] != b'<' {
result.push_str(&input[ws_start..i]);
}
} else {
i = push_char_at(input, i, &mut result);
}
}
result
}
fn strip_shadowrootmode(tag_str: &str, result: &mut String) -> Option<usize> {
let close = find_tag_close(tag_str)?;
let tag_content = &tag_str[..=close];
if !tag_content.contains("shadowrootmode") {
return None;
}
result.push_str("<template");
let attr_start = "<template".len();
let inner = &tag_content[attr_start..close];
let inner_bytes = inner.as_bytes();
let inner_len = inner_bytes.len();
let mut j = 0;
while j < inner_len {
if is_whitespace(inner_bytes[j]) {
j += 1;
continue;
}
let attr_begin = j;
while j < inner_len && inner_bytes[j] != b'=' && !is_whitespace(inner_bytes[j]) {
j += 1;
}
let attr_name = &inner[attr_begin..j];
let mut attr_end = j;
if j < inner_len && inner_bytes[j] == b'=' {
j += 1; if j < inner_len && inner_bytes[j] == b'"' {
j += 1; while j < inner_len && inner_bytes[j] != b'"' {
j += 1;
}
if j < inner_len {
j += 1; }
} else {
while j < inner_len && !is_whitespace(inner_bytes[j]) {
j += 1;
}
}
attr_end = j;
}
if attr_name == "shadowrootmode" {
continue;
}
result.push(' ');
result.push_str(&inner[attr_begin..attr_end]);
}
if tag_content.ends_with("/>") {
result.push_str("/>");
} else {
result.push('>');
}
Some(close + 1)
}
#[cfg(test)]
mod tests {
#![allow(clippy::disallowed_methods)]
use super::*;
use std::path::PathBuf;
fn make_component(tag: &str, html: &str, css: Option<&str>) -> Component {
Component {
tag_name: tag.to_string(),
html_content: html.to_string(),
css_content: css.map(ToString::to_string),
css_tokens: Vec::new(),
source_path: PathBuf::from("/test"),
class_name: None,
}
}
#[test]
fn skip_event_binding() {
let mut plugin = FastV2ParserPlugin::new();
assert_eq!(
plugin.classify_attribute("@click"),
AttributeAction::SkipAndCountBinding
);
assert_eq!(
plugin.classify_attribute("@input"),
AttributeAction::SkipAndCountBinding
);
assert_eq!(
plugin.classify_attribute("@custom-event"),
AttributeAction::SkipAndCountBinding
);
}
#[test]
fn skip_f_ref() {
let mut plugin = FastV2ParserPlugin::new();
assert_eq!(
plugin.classify_attribute("f-ref"),
AttributeAction::SkipAndCountBinding
);
}
#[test]
fn skip_f_slotted() {
let mut plugin = FastV2ParserPlugin::new();
assert_eq!(
plugin.classify_attribute("f-slotted"),
AttributeAction::SkipAndCountBinding
);
}
#[test]
fn skip_f_children() {
let mut plugin = FastV2ParserPlugin::new();
assert_eq!(
plugin.classify_attribute("f-children"),
AttributeAction::SkipAndCountBinding
);
}
#[test]
fn do_not_skip_normal_attributes() {
let mut plugin = FastV2ParserPlugin::new();
assert_eq!(plugin.classify_attribute("class"), AttributeAction::Keep);
assert_eq!(plugin.classify_attribute("id"), AttributeAction::Keep);
assert_eq!(
plugin.classify_attribute("data-value"),
AttributeAction::Keep
);
assert_eq!(plugin.classify_attribute(":title"), AttributeAction::Keep);
assert_eq!(plugin.classify_attribute("f-other"), AttributeAction::Keep);
}
#[test]
fn element_parsed_zero_count_returns_none() {
let mut plugin = FastV2ParserPlugin::new();
assert!(plugin.finish_element(0).is_none());
}
#[test]
fn element_parsed_nonzero_count_returns_le_bytes() {
let mut plugin = FastV2ParserPlugin::new();
let data = plugin.finish_element(3);
assert!(data.is_some());
let bytes = data.as_deref().unwrap_or_default();
assert_eq!(bytes, &3u32.to_le_bytes());
}
#[test]
fn element_parsed_large_count() {
let mut plugin = FastV2ParserPlugin::new();
let data = plugin.finish_element(256);
assert!(data.is_some());
let bytes = data.as_deref().unwrap_or_default();
assert_eq!(bytes, &256u32.to_le_bytes());
}
#[test]
fn component_template_simple_component() {
let mut plugin = FastV2ParserPlugin::new();
let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
plugin
.register_component_template("my-comp", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 1);
let (name, html) = &templates[0];
assert_eq!(name, "my-comp");
assert!(html.contains("<f-template name=\"my-comp\">"));
assert!(html.contains("</f-template>"));
assert!(html.contains("<template>"));
assert!(html.contains("</template>"));
assert!(html.contains("<link rel=\"stylesheet\" href=\"my-comp.css\">"));
assert!(html.contains("<div>hello</div>"));
}
#[test]
fn component_template_without_css() {
let mut plugin = FastV2ParserPlugin::new();
let comp = make_component("no-css", "<span>text</span>", None);
plugin
.register_component_template("no-css", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 1);
let (name, html) = &templates[0];
assert_eq!(name, "no-css");
assert!(html.contains("<f-template name=\"no-css\">"));
assert!(!html.contains("<link rel=\"stylesheet\""));
assert!(html.contains("<span>text</span>"));
}
#[test]
fn component_template_css_strategy_style() {
let mut plugin = FastV2ParserPlugin::new();
plugin.set_css_strategy(crate::CssStrategy::Style);
let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
plugin
.register_component_template("my-comp", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 1);
let (_, html) = &templates[0];
assert!(
html.contains("<style>div { color: red; }</style>"),
"Style strategy should inline CSS, got: {html}"
);
assert!(
!html.contains("<link"),
"Style strategy should not emit <link> tags"
);
}
#[test]
fn component_template_css_strategy_module() {
let mut plugin = FastV2ParserPlugin::new();
plugin.set_css_strategy(crate::CssStrategy::Module);
let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
plugin
.register_component_template("my-comp", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 1);
let (_, html) = &templates[0];
assert!(
!html.contains(r#"<style type="module""#),
"CSS module should not be baked into f-template: {html}"
);
assert!(
html.contains(r#"shadowrootadoptedstylesheets="my-comp""#),
"Module strategy should add shadowrootadoptedstylesheets, got: {html}"
);
assert!(
!html.contains("<style>div"),
"Module strategy should not have inline <style> inside template"
);
assert!(
!html.contains("<link"),
"Module strategy should not emit <link> tags"
);
}
#[test]
fn component_template_css_strategy_module_no_css() {
let mut plugin = FastV2ParserPlugin::new();
plugin.set_css_strategy(crate::CssStrategy::Module);
let comp = make_component("my-comp", "<div>hello</div>", None);
plugin
.register_component_template("my-comp", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 1);
let (_, html) = &templates[0];
assert!(
!html.contains("shadowrootadoptedstylesheets"),
"No CSS = no shadowrootadoptedstylesheets, got: {html}"
);
assert!(
!html.contains("<style"),
"No CSS = no style tag, got: {html}"
);
}
#[test]
fn component_template_multiple_components() {
let mut plugin = FastV2ParserPlugin::new();
let comp1 = make_component("comp-a", "<div>A</div>", None);
let comp2 = make_component("comp-b", "<div>B</div>", Some("b { }"));
plugin
.register_component_template("comp-a", &comp1, &comp1.html_content)
.unwrap();
plugin
.register_component_template("comp-b", &comp2, &comp2.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 2);
let names: Vec<&str> = templates.iter().map(|(n, _)| n.as_str()).collect();
assert!(names.contains(&"comp-a"));
assert!(names.contains(&"comp-b"));
for (_, html) in &templates {
assert!(html.contains("<f-template name="));
}
}
#[test]
fn component_template_deduplicates_same_component() {
let mut plugin = FastV2ParserPlugin::new();
let comp = make_component(
"my-button",
"<button><slot></slot></button>",
Some(".btn{}"),
);
plugin
.register_component_template("my-button", &comp, &comp.html_content)
.unwrap();
plugin
.register_component_template("my-button", &comp, &comp.html_content)
.unwrap();
plugin
.register_component_template("my-button", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(
templates.len(),
1,
"Expected exactly 1 template for my-button, got {}",
templates.len()
);
assert_eq!(templates[0].0, "my-button");
}
#[test]
fn component_template_deduplicates_mixed_components() {
let mut plugin = FastV2ParserPlugin::new();
let btn = make_component("my-button", "<button><slot></slot></button>", None);
let card = make_component("my-card", "<div><slot></slot></div>", Some(".card{}"));
plugin
.register_component_template("my-button", &btn, &btn.html_content)
.unwrap();
plugin
.register_component_template("my-card", &card, &card.html_content)
.unwrap();
plugin
.register_component_template("my-button", &btn, &btn.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 2);
let button_count = templates.iter().filter(|(n, _)| n == "my-button").count();
let card_count = templates.iter().filter(|(n, _)| n == "my-card").count();
assert_eq!(button_count, 1);
assert_eq!(card_count, 1);
}
#[test]
fn convert_if_to_f_when() {
let input = r#"<if condition="isComplete"><span>Done</span></if>"#;
let output = convert_btr_to_fast(input);
assert_eq!(
output,
r#"<f-when value="{{isComplete}}"><span>Done</span></f-when>"#
);
}
#[test]
fn convert_if_with_greater_than() {
let input = r#"<if condition="vara > 2">Over two</if>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, r#"<f-when value="{{vara > 2}}">Over two</f-when>"#);
}
#[test]
fn convert_if_with_greater_than_or_equal() {
let input = r#"<if condition="vara >= 2">Two and over</if>"#;
let output = convert_btr_to_fast(input);
assert_eq!(
output,
r#"<f-when value="{{vara >= 2}}">Two and over</f-when>"#
);
}
#[test]
fn convert_if_with_less_than() {
let input = r#"<if condition="x < 10">small</if>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, r#"<f-when value="{{x < 10}}">small</f-when>"#);
}
#[test]
fn convert_for_to_f_repeat() {
let input = r#"<for each="tag in tags"><span>{{tag}}</span></for>"#;
let output = convert_btr_to_fast(input);
assert_eq!(
output,
r#"<f-repeat value="{{tag in tags}}"><span>{{tag}}</span></f-repeat>"#
);
}
#[test]
fn convert_nested_if_and_for() {
let input = r#"<if condition="show"><for each="x in items"><p>{{x}}</p></for></if>"#;
let output = convert_btr_to_fast(input);
assert_eq!(
output,
r#"<f-when value="{{show}}"><f-repeat value="{{x in items}}"><p>{{x}}</p></f-repeat></f-when>"#
);
}
#[test]
fn convert_complex_attr_double_braces() {
let input = r#"<div :data="{{config}}"></div>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, r#"<div :data="{config}"></div>"#);
}
#[test]
fn convert_multiple_complex_attrs() {
let input = r#"<div :title="{{name}}" :data-id="{{id}}"></div>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, r#"<div :title="{name}" :data-id="{id}"></div>"#);
}
#[test]
fn no_conversion_for_text_double_braces() {
let input = "<span>{{greeting}}</span>";
let output = convert_btr_to_fast(input);
assert_eq!(output, "<span>{{greeting}}</span>");
}
#[test]
fn no_conversion_for_regular_attr() {
let input = r#"<div title="{{name}}"></div>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, r#"<div title="{{name}}"></div>"#);
}
#[test]
fn component_template_with_btr_conversion() {
let mut plugin = FastV2ParserPlugin::new();
let html = r#"<div><if condition="visible"><span>hi</span></if></div>"#;
let comp = make_component("my-widget", html, None);
plugin
.register_component_template("my-widget", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 1);
let (name, result) = &templates[0];
assert_eq!(name, "my-widget");
assert!(result.contains("<f-when value=\"{{visible}}\">"));
assert!(result.contains("</f-when>"));
assert!(!result.contains("<if condition="));
assert!(!result.contains("</if>"));
}
#[test]
fn passthrough_normal_html() {
let input = r#"<div class="container"><p>Hello</p></div>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, input);
}
#[test]
fn outlet_kept_as_marker_in_f_template() {
let input = r#"<div><outlet /></div>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, r#"<div><outlet></outlet></div>"#);
}
#[test]
fn outlet_marker_in_component_template() {
let mut plugin = FastV2ParserPlugin::new();
let html =
r#"<template shadowrootmode="open"><h1>Title</h1><main><outlet /></main></template>"#;
let comp = make_component("my-shell", html, None);
plugin
.register_component_template("my-shell", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
let (_, result) = &templates[0];
assert!(
result.contains("<outlet></outlet>"),
"outlet should be kept as marker in f-template: {result}"
);
}
#[test]
fn strip_shadowrootmode_from_template() {
let input = r#"<template shadowrootmode="open"><div>Hello</div></template>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, "<template><div>Hello</div></template>");
}
#[test]
fn strip_shadowrootmode_preserves_other_attrs() {
let input =
r#"<template shadowrootmode="open" @click="{onClick(e)}"><div>Hi</div></template>"#;
let output = convert_btr_to_fast(input);
assert!(output.contains(r#"@click="{onClick(e)}""#));
assert!(!output.contains("shadowrootmode"));
assert!(output.starts_with("<template "));
}
#[test]
fn no_strip_when_no_shadowrootmode() {
let input = r#"<template foo="bar"><div>Hi</div></template>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, input);
}
#[test]
fn component_template_strips_shadowrootmode_from_f_template() {
let mut plugin = FastV2ParserPlugin::new();
let comp = make_component(
"my-comp",
r#"<template shadowrootmode="open" @click="{onClick(e)}"><div>{{title}}</div></template>"#,
Some("div { color: red; }"),
);
plugin
.register_component_template("my-comp", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 1);
let (name, html) = &templates[0];
assert_eq!(name, "my-comp");
assert!(!html.contains("shadowrootmode"));
assert!(html.contains("@click"));
assert!(html.contains("{{title}}"));
}
#[test]
fn test_complex_attribute_normalization() {
let cases = [
(
r#"<div :foo="{{value}}"></div>"#,
r#"<div :foo="{value}"></div>"#,
),
(
r#"<div :foo="{{ value}}"></div>"#,
r#"<div :foo="{ value}"></div>"#,
),
(
r#"<div :foo="{{value }}"></div>"#,
r#"<div :foo="{value }"></div>"#,
),
(
r#"<div :foo="{{ value }}"></div>"#,
r#"<div :foo="{ value }"></div>"#,
),
];
for (input, expected) in &cases {
let output = convert_btr_to_fast(input);
assert_eq!(&output, expected, "normalization failed for input: {input}");
}
}
#[test]
fn test_non_js_component_inner_template() {
let mut plugin = FastV2ParserPlugin::new();
let html = r#"<div><child-comp><template shadowrootmode="open"><p>inner</p></template></child-comp></div>"#;
let comp = make_component("parent-comp", html, None);
plugin
.register_component_template("parent-comp", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
assert_eq!(templates.len(), 1);
let (name, output) = &templates[0];
assert_eq!(name, "parent-comp");
assert!(output.contains("<f-template name=\"parent-comp\">"));
assert!(!output.contains("shadowrootmode"));
assert!(output.contains("<child-comp><template><p>inner</p></template></child-comp>"));
}
#[test]
fn route_tags_converted_to_f_route() {
let input = r#"<route path="/home" name="home" exact><span>Home</span></route>"#;
let output = convert_btr_to_fast(input);
assert!(output.starts_with("<webui-route"));
assert!(output.contains(r#"path="/home""#));
assert!(output.contains(r#"name="home""#));
assert!(output.contains(" exact"));
assert!(output.contains("style=\"display:none\""));
assert!(output.contains("<span>Home</span>"));
assert!(output.ends_with("</webui-route>"));
}
#[test]
fn f_route_tags_pass_through() {
let input = r#"<webui-route path="/" name="dashboard" component="cb-page-dashboard" exact style="display:none"></webui-route>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, input);
}
#[test]
fn ftemplate_for_loop_converted_to_f_repeat() {
let mut plugin = FastV2ParserPlugin::new();
let html = r#"<ul><for each="item in items"><li>{{item.name}}</li></for></ul>"#;
let comp = make_component("my-list", html, None);
plugin
.register_component_template("my-list", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
let (_, result) = &templates[0];
assert!(
result.contains("<f-repeat value=\"{{item in items}}\">"),
"f-template should use <f-repeat>, got: {result}"
);
assert!(
result.contains("</f-repeat>"),
"f-template should close with </f-repeat>, got: {result}"
);
assert!(
!result.contains("<for "),
"f-template should NOT contain <for>, got: {result}"
);
}
#[test]
fn ftemplate_shadow_dom_strips_shadowroot_and_converts_directives() {
let mut plugin = FastV2ParserPlugin::new();
let html = r#"<template shadowrootmode="open"><div><if condition="visible">Shown</if><for each="x in list"><span>{{x}}</span></for></div></template>"#;
let comp = make_component("my-shadow", html, None);
plugin
.register_component_template("my-shadow", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
let (_, result) = &templates[0];
assert!(
result.contains("<f-when value=\"{{visible}}\">"),
"Shadow f-template should contain <f-when>, got: {result}"
);
assert!(
result.contains("<f-repeat value=\"{{x in list}}\">"),
"Shadow f-template should contain <f-repeat>, got: {result}"
);
assert!(
!result.contains("shadowrootmode"),
"Shadow f-template should strip shadowrootmode, got: {result}"
);
assert!(
!result.contains("<if "),
"Shadow f-template should NOT contain <if>, got: {result}"
);
assert!(
!result.contains("<for "),
"Shadow f-template should NOT contain <for>, got: {result}"
);
}
#[test]
fn ftemplate_nested_if_and_for_both_converted() {
let mut plugin = FastV2ParserPlugin::new();
let html =
r#"<div><if condition="show"><for each="x in items"><p>{{x}}</p></for></if></div>"#;
let comp = make_component("my-nested", html, None);
plugin
.register_component_template("my-nested", &comp, &comp.html_content)
.unwrap();
let templates = plugin.take_component_templates();
let (_, result) = &templates[0];
assert!(
result.contains("<f-when value=\"{{show}}\">"),
"Nested f-template should contain <f-when>, got: {result}"
);
assert!(
result.contains("<f-repeat value=\"{{x in items}}\">"),
"Nested f-template should contain <f-repeat>, got: {result}"
);
assert!(
!result.contains("<if "),
"Nested f-template should NOT contain <if>, got: {result}"
);
assert!(
!result.contains("<for "),
"Nested f-template should NOT contain <for>, got: {result}"
);
}
#[test]
fn convert_btr_preserves_utf8_text_content() {
let input = "<span>✓ passed</span>";
let output = convert_btr_to_fast(input);
assert_eq!(output, "<span>✓ passed</span>");
}
#[test]
fn convert_btr_preserves_utf8_multibyte_chars() {
let input = "<span>✓ yes ✗ no ⭐ star</span>";
let output = convert_btr_to_fast(input);
assert_eq!(output, "<span>✓ yes ✗ no ⭐ star</span>");
}
#[test]
fn convert_btr_preserves_utf8_with_directives() {
let input = r#"<if condition="x"><span>✓</span></if>"#;
let output = convert_btr_to_fast(input);
assert_eq!(output, r#"<f-when value="{{x}}"><span>✓</span></f-when>"#);
}
#[test]
fn minify_preserves_utf8_text_content() {
let input = "<span>✓</span><span>✗</span>";
let output = minify_inter_tag_whitespace(input);
assert_eq!(output, "<span>✓</span><span>✗</span>");
}
#[test]
fn minify_preserves_utf8_between_elements() {
let input = "<div> ✓ </div>";
let output = minify_inter_tag_whitespace(input);
assert_eq!(output, "<div> ✓ </div>");
}
#[test]
fn convert_complex_attrs_preserves_utf8() {
let input = r#"<span :title="{{label}}" data-icon="⭐">text</span>"#;
let output = convert_btr_to_fast(input);
assert!(
output.contains("⭐"),
"UTF-8 star should be preserved: {output}"
);
}
}