1use super::{AttributeAction, ComponentTemplateArtifact, ParserPlugin, ParserPluginArtifacts};
11use crate::component_registry::Component;
12use crate::html_parser::{find_tag_close, opening_tag_name};
13use crate::{CssLinkOptions, CssStrategy, Result};
14use webui_protocol::FastElementData;
15
16struct TrackedComponent {
18 tag_name: String,
19 template_html: String,
20}
21
22pub struct FastV2ParserPlugin {
30 components: Vec<TrackedComponent>,
32}
33
34impl FastV2ParserPlugin {
35 #[must_use]
37 pub fn new() -> Self {
38 Self {
39 components: Vec::new(),
40 }
41 }
42
43 #[must_use]
49 pub fn take_component_templates(&self) -> Vec<ComponentTemplateArtifact> {
50 self.components
51 .iter()
52 .map(|comp| {
53 let tmpl = generate_f_template_from_processed(&comp.tag_name, &comp.template_html);
54 ComponentTemplateArtifact::template(comp.tag_name.clone(), tmpl)
55 })
56 .collect()
57 }
58}
59
60impl Default for FastV2ParserPlugin {
61 fn default() -> Self {
62 Self::new()
63 }
64}
65
66impl ParserPlugin for FastV2ParserPlugin {
67 fn register_component_template(
68 &mut self,
69 tag_name: &str,
70 component: &Component,
71 processed_template: &str,
72 ) -> Result<()> {
73 if self.components.iter().any(|c| c.tag_name == tag_name) {
76 return Ok(());
77 }
78 self.components.push(TrackedComponent {
79 tag_name: tag_name.to_string(),
80 template_html: processed_template.to_string(),
81 });
82 let _ = component;
83 Ok(())
84 }
85
86 fn classify_attribute(&mut self, attr_name: &str) -> AttributeAction {
87 if attr_name.starts_with('@')
88 || attr_name == "f-ref"
89 || attr_name == "f-slotted"
90 || attr_name == "f-children"
91 {
92 AttributeAction::SkipAndCountBinding
93 } else {
94 AttributeAction::Keep
95 }
96 }
97
98 fn finish_element(&mut self, binding_attribute_count: u32) -> Option<Vec<u8>> {
99 if binding_attribute_count > 0 {
100 Some(
101 FastElementData {
102 binding_count: binding_attribute_count,
103 }
104 .encode()
105 .to_vec(),
106 )
107 } else {
108 None
109 }
110 }
111
112 fn into_artifacts(self: Box<Self>) -> Result<ParserPluginArtifacts> {
113 Ok(ParserPluginArtifacts::ComponentTemplates(
114 self.take_component_templates(),
115 ))
116 }
117}
118
119pub fn generate_f_template(
128 tag_name: &str,
129 html_content: &str,
130 css_content: Option<&str>,
131 css_strategy: CssStrategy,
132) -> String {
133 generate_f_template_with_css_options(
134 tag_name,
135 html_content,
136 css_content,
137 css_strategy,
138 &CssLinkOptions::default(),
139 )
140}
141
142fn generate_f_template_from_processed(tag_name: &str, processed_template: &str) -> String {
143 let mut output = String::with_capacity(256);
144 output.push_str("<f-template name=\"");
145 output.push_str(tag_name);
146 output.push_str("\">\n");
147
148 let converted = convert_btr_to_fast(processed_template);
149 let trimmed = minify_inter_tag_whitespace(converted.trim());
150
151 if trimmed.starts_with("<template") {
152 output.push_str(&trimmed);
153 } else {
154 output.push_str("<template>");
155 output.push_str(&trimmed);
156 output.push_str("</template>");
157 }
158
159 output.push_str("\n</f-template>\n");
160 output
161}
162
163pub fn generate_f_template_with_css_options(
165 tag_name: &str,
166 html_content: &str,
167 css_content: Option<&str>,
168 css_strategy: CssStrategy,
169 css_link_options: &CssLinkOptions,
170) -> String {
171 let mut output = String::with_capacity(256);
172 output.push_str("<f-template name=\"");
173 output.push_str(tag_name);
174 output.push_str("\">\n");
175
176 let converted = convert_btr_to_fast(html_content);
177 let trimmed = minify_inter_tag_whitespace(converted.trim());
178
179 let css_injection = match css_strategy {
181 CssStrategy::Link => css_content.map(|css| {
182 let href = css_link_options.resolve(tag_name, css);
183 let mut s = String::with_capacity(40 + href.href.len());
184 s.push_str("<link rel=\"stylesheet\" href=\"");
185 s.push_str(&href.href);
186 s.push_str("\">");
187 s
188 }),
189 CssStrategy::Style => css_content.map(|css| {
190 let mut s = String::with_capacity(15 + css.len());
191 s.push_str("<style>");
192 s.push_str(css.trim());
193 s.push_str("</style>");
194 s
195 }),
196 CssStrategy::Module => None,
197 };
198
199 if trimmed.starts_with("<template") {
200 if let Some(close_pos) = find_tag_close(&trimmed) {
201 output.push_str(&trimmed[..close_pos]);
206 output.push('>');
207 if let Some(ref injection) = css_injection {
208 output.push_str(injection);
209 }
210 output.push_str(&trimmed[close_pos + 1..]);
211 } else {
212 output.push_str(&trimmed);
213 }
214 } else {
215 output.push_str("<template");
216 if css_strategy == CssStrategy::Module && css_content.is_some() {
217 output.push_str(" shadowrootadoptedstylesheets=\"");
218 output.push_str(tag_name);
219 output.push('"');
220 }
221 output.push('>');
222 if let Some(ref injection) = css_injection {
223 output.push_str(injection);
224 }
225 output.push_str(&trimmed);
226 output.push_str("</template>");
227 }
228
229 output.push_str("\n</f-template>\n");
230 output
231}
232
233fn convert_btr_to_fast(input: &str) -> String {
245 let mut result = String::with_capacity(input.len());
246 let bytes = input.as_bytes();
247 let len = bytes.len();
248 let mut i = 0;
249
250 while i < len {
251 if bytes[i] == b'<' {
252 if let Some(consumed) = try_convert_tag(input, i, &mut result) {
253 i += consumed;
254 continue;
255 }
256 }
257
258 i = push_char_at(input, i, &mut result);
262 }
263
264 result
265}
266
267fn try_convert_tag(input: &str, pos: usize, result: &mut String) -> Option<usize> {
270 let remaining = &input[pos..];
271
272 if remaining.starts_with("</if>") {
274 result.push_str("</f-when>");
275 return Some(5);
276 }
277 if remaining.starts_with("</for>") {
278 result.push_str("</f-repeat>");
279 return Some(6);
280 }
281 if remaining.starts_with("</route>") {
283 result.push_str("</webui-route>");
284 return Some(8);
285 }
286
287 if starts_with_tag_name(remaining, "outlet") {
290 if let Some(close) = find_tag_close(remaining) {
291 result.push_str("<outlet></outlet>");
292 return Some(close + 1);
293 }
294 }
295
296 if starts_with_tag_name(remaining, "if") {
298 if let Some(consumed) = convert_if_tag(remaining, result) {
299 return Some(consumed);
300 }
301 }
302
303 if starts_with_tag_name(remaining, "for") {
305 if let Some(consumed) = convert_for_tag(remaining, result) {
306 return Some(consumed);
307 }
308 }
309
310 if starts_with_tag_name(remaining, "route") {
312 if let Some(consumed) = convert_route_tag(remaining, result) {
313 return Some(consumed);
314 }
315 }
316
317 if remaining.starts_with("<") {
319 if starts_with_tag_name(remaining, "template") {
321 if let Some(consumed) = strip_shadowrootmode(remaining, result) {
322 return Some(consumed);
323 }
324 }
325 if let Some(consumed) = convert_complex_attrs(remaining, result) {
326 return Some(consumed);
327 }
328 }
329
330 None
331}
332
333fn starts_with_tag_name(s: &str, name: &str) -> bool {
335 opening_tag_name(s).is_some_and(|tag_name| tag_name == name)
336}
337
338fn convert_if_tag(tag_str: &str, result: &mut String) -> Option<usize> {
341 let close = find_tag_close(tag_str)?;
343 let tag_content = &tag_str[..=close];
344
345 let attr_value = extract_attribute_value(tag_content, "condition")?;
347
348 result.push_str("<f-when value=\"{{");
349 result.push_str(attr_value);
350 result.push_str("}}\">");
351
352 Some(close + 1)
353}
354
355fn convert_for_tag(tag_str: &str, result: &mut String) -> Option<usize> {
358 let close = find_tag_close(tag_str)?;
360 let tag_content = &tag_str[..=close];
361
362 let attr_value = extract_attribute_value(tag_content, "each")?;
364
365 result.push_str("<f-repeat value=\"{{");
366 result.push_str(attr_value);
367 result.push_str("}}\">");
368
369 Some(close + 1)
370}
371
372fn convert_route_tag(tag_str: &str, result: &mut String) -> Option<usize> {
376 let close = find_tag_close(tag_str)?;
377 let is_self_closing = tag_str[..=close].ends_with("/>");
378 let tag = &tag_str[..=close];
379
380 result.push_str("<webui-route");
381
382 if let Some(v) = extract_attribute_value(tag, "path") {
383 result.push_str(" path=\"");
384 result.push_str(v);
385 result.push('"');
386 }
387 if let Some(v) = extract_attribute_value(tag, "name") {
388 result.push_str(" name=\"");
389 result.push_str(v);
390 result.push('"');
391 }
392 if let Some(v) = extract_attribute_value(tag, "component") {
393 result.push_str(" component=\"");
394 result.push_str(v);
395 result.push('"');
396 }
397 if let Some(v) = extract_attribute_value(tag, "redirectTo") {
398 result.push_str(" redirectto=\"");
399 result.push_str(v);
400 result.push('"');
401 }
402 if tag.contains(" exact") {
403 result.push_str(" exact");
404 }
405 if tag.contains(" layout") {
406 result.push_str(" layout");
407 }
408 if let Some(v) = extract_attribute_value(tag, "query") {
409 result.push_str(" query=\"");
410 result.push_str(v);
411 result.push('"');
412 }
413 result.push_str(" style=\"display:none\"");
414
415 if is_self_closing {
416 result.push_str("></webui-route>");
417 } else {
418 result.push('>');
419 }
420
421 Some(close + 1)
422}
423
424fn extract_attribute_value<'a>(tag: &'a str, attr_name: &str) -> Option<&'a str> {
427 let mut search_from = 0;
429 loop {
430 let attr_pos = tag[search_from..].find(attr_name)?;
431 let abs_pos = search_from + attr_pos;
432
433 if abs_pos > 0 {
435 let prev = tag.as_bytes()[abs_pos - 1];
436 if prev != b' ' && prev != b'\t' && prev != b'\n' && prev != b'\r' {
437 search_from = abs_pos + attr_name.len();
438 continue;
439 }
440 }
441
442 let after_name = &tag[abs_pos + attr_name.len()..];
443 if !after_name.starts_with('=') {
444 search_from = abs_pos + attr_name.len();
445 continue;
446 }
447
448 let after_eq = &after_name[1..];
449 if after_eq.starts_with('"') {
450 let value_start = abs_pos + attr_name.len() + 2; let end_quote = tag[value_start..].find('"')?;
452 return Some(&tag[value_start..value_start + end_quote]);
453 }
454
455 return None;
456 }
457}
458
459fn convert_complex_attrs(tag_str: &str, result: &mut String) -> Option<usize> {
463 let close = find_tag_close(tag_str)?;
465 let tag_content = &tag_str[..=close];
466
467 if !tag_content.contains(":") || !tag_content.contains("{{") {
469 return None;
470 }
471
472 let mut converted = String::with_capacity(tag_content.len());
474 let tag_bytes = tag_content.as_bytes();
475 let tag_len = tag_bytes.len();
476 let mut j = 0;
477 let mut in_colon_attr_value = false;
478
479 while j < tag_len {
480 if !in_colon_attr_value {
481 if tag_bytes[j] == b':' && j > 0 && is_whitespace(tag_bytes[j - 1]) {
483 let attr_start = j;
485 j += 1;
486 while j < tag_len && tag_bytes[j] != b'=' && !is_whitespace(tag_bytes[j]) {
488 j += 1;
489 }
490 if j < tag_len && tag_bytes[j] == b'=' {
491 j += 1;
492 if j < tag_len && tag_bytes[j] == b'"' {
493 converted.push_str(&tag_content[attr_start..=j]);
495 j += 1;
496 in_colon_attr_value = true;
497 continue;
498 }
499 }
500 converted.push_str(&tag_content[attr_start..j]);
502 continue;
503 }
504 j = push_char_at(tag_content, j, &mut converted);
505 } else {
506 if tag_bytes[j] == b'"' {
508 converted.push('"');
510 j += 1;
511 in_colon_attr_value = false;
512 } else if j + 1 < tag_len && tag_bytes[j] == b'{' && tag_bytes[j + 1] == b'{' {
513 let expr_start = j + 2;
515 if let Some(end_offset) = tag_content[expr_start..].find("}}") {
516 let expr = &tag_content[expr_start..expr_start + end_offset];
517 converted.push('{');
518 converted.push_str(expr);
519 converted.push('}');
520 j = expr_start + end_offset + 2;
521 } else {
522 converted.push('{');
524 converted.push('{');
525 j += 2;
526 }
527 } else {
528 j = push_char_at(tag_content, j, &mut converted);
529 }
530 }
531 }
532
533 result.push_str(&converted);
534 Some(close + 1)
535}
536
537fn push_char_at(input: &str, pos: usize, out: &mut String) -> usize {
540 let bytes = input.as_bytes();
541 if bytes[pos].is_ascii() {
542 out.push(bytes[pos] as char);
543 pos + 1
544 } else {
545 let mut end = pos + 1;
546 while end < bytes.len() && !input.is_char_boundary(end) {
547 end += 1;
548 }
549 out.push_str(&input[pos..end]);
550 end
551 }
552}
553
554fn is_whitespace(b: u8) -> bool {
556 b == b' ' || b == b'\t' || b == b'\n' || b == b'\r'
557}
558
559fn minify_inter_tag_whitespace(input: &str) -> String {
563 let mut result = String::with_capacity(input.len());
564 let bytes = input.as_bytes();
565 let len = bytes.len();
566 let mut i = 0;
567
568 while i < len {
569 if bytes[i] == b'>' && i + 1 < len {
570 result.push('>');
571 i += 1;
572 let ws_start = i;
574 while i < len && is_whitespace(bytes[i]) {
575 i += 1;
576 }
577 if i >= len || bytes[i] != b'<' {
580 result.push_str(&input[ws_start..i]);
582 }
583 } else {
584 i = push_char_at(input, i, &mut result);
585 }
586 }
587
588 result
589}
590
591fn strip_shadowrootmode(tag_str: &str, result: &mut String) -> Option<usize> {
594 let close = find_tag_close(tag_str)?;
596 let tag_content = &tag_str[..=close];
597
598 if !tag_content.contains("shadowrootmode") {
600 return None;
601 }
602
603 result.push_str("<template");
605 let attr_start = "<template".len();
606 let inner = &tag_content[attr_start..close];
607
608 let inner_bytes = inner.as_bytes();
610 let inner_len = inner_bytes.len();
611 let mut j = 0;
612 while j < inner_len {
613 if is_whitespace(inner_bytes[j]) {
615 j += 1;
616 continue;
617 }
618
619 let attr_begin = j;
621 while j < inner_len && inner_bytes[j] != b'=' && !is_whitespace(inner_bytes[j]) {
623 j += 1;
624 }
625 let attr_name = &inner[attr_begin..j];
626
627 let mut attr_end = j;
629 if j < inner_len && inner_bytes[j] == b'=' {
630 j += 1; if j < inner_len && inner_bytes[j] == b'"' {
632 j += 1; while j < inner_len && inner_bytes[j] != b'"' {
634 j += 1;
635 }
636 if j < inner_len {
637 j += 1; }
639 } else {
640 while j < inner_len && !is_whitespace(inner_bytes[j]) {
642 j += 1;
643 }
644 }
645 attr_end = j;
646 }
647
648 if attr_name == "shadowrootmode" {
650 continue;
651 }
652
653 result.push(' ');
655 result.push_str(&inner[attr_begin..attr_end]);
656 }
657
658 if tag_content.ends_with("/>") {
659 result.push_str("/>");
660 } else {
661 result.push('>');
662 }
663
664 Some(close + 1)
665}
666
667#[cfg(test)]
668mod tests {
669 #![allow(clippy::disallowed_methods)]
670
671 use super::*;
672 use std::path::PathBuf;
673
674 fn make_component(tag: &str, html: &str, css: Option<&str>) -> Component {
675 Component {
676 tag_name: tag.to_string(),
677 html_content: html.to_string(),
678 css_content: css.map(ToString::to_string),
679 css_tokens: Vec::new(),
680 source_path: PathBuf::from("/test"),
681 class_name: None,
682 }
683 }
684
685 #[test]
688 fn skip_event_binding() {
689 let mut plugin = FastV2ParserPlugin::new();
690 assert_eq!(
691 plugin.classify_attribute("@click"),
692 AttributeAction::SkipAndCountBinding
693 );
694 assert_eq!(
695 plugin.classify_attribute("@input"),
696 AttributeAction::SkipAndCountBinding
697 );
698 assert_eq!(
699 plugin.classify_attribute("@custom-event"),
700 AttributeAction::SkipAndCountBinding
701 );
702 }
703
704 #[test]
705 fn skip_f_ref() {
706 let mut plugin = FastV2ParserPlugin::new();
707 assert_eq!(
708 plugin.classify_attribute("f-ref"),
709 AttributeAction::SkipAndCountBinding
710 );
711 }
712
713 #[test]
714 fn skip_f_slotted() {
715 let mut plugin = FastV2ParserPlugin::new();
716 assert_eq!(
717 plugin.classify_attribute("f-slotted"),
718 AttributeAction::SkipAndCountBinding
719 );
720 }
721
722 #[test]
723 fn skip_f_children() {
724 let mut plugin = FastV2ParserPlugin::new();
725 assert_eq!(
726 plugin.classify_attribute("f-children"),
727 AttributeAction::SkipAndCountBinding
728 );
729 }
730
731 #[test]
732 fn do_not_skip_normal_attributes() {
733 let mut plugin = FastV2ParserPlugin::new();
734 assert_eq!(plugin.classify_attribute("class"), AttributeAction::Keep);
735 assert_eq!(plugin.classify_attribute("id"), AttributeAction::Keep);
736 assert_eq!(
737 plugin.classify_attribute("data-value"),
738 AttributeAction::Keep
739 );
740 assert_eq!(plugin.classify_attribute(":title"), AttributeAction::Keep);
741 assert_eq!(plugin.classify_attribute("f-other"), AttributeAction::Keep);
742 }
743
744 #[test]
747 fn element_parsed_zero_count_returns_none() {
748 let mut plugin = FastV2ParserPlugin::new();
749 assert!(plugin.finish_element(0).is_none());
750 }
751
752 #[test]
753 fn element_parsed_nonzero_count_returns_le_bytes() {
754 let mut plugin = FastV2ParserPlugin::new();
755 let data = plugin.finish_element(3);
756 assert!(data.is_some());
757 let bytes = data.as_deref().unwrap_or_default();
758 assert_eq!(bytes, &3u32.to_le_bytes());
759 }
760
761 #[test]
762 fn element_parsed_large_count() {
763 let mut plugin = FastV2ParserPlugin::new();
764 let data = plugin.finish_element(256);
765 assert!(data.is_some());
766 let bytes = data.as_deref().unwrap_or_default();
767 assert_eq!(bytes, &256u32.to_le_bytes());
768 }
769
770 #[test]
771 fn component_template_simple_component() {
772 let mut plugin = FastV2ParserPlugin::new();
773 let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
774 plugin
775 .register_component_template(
776 "my-comp",
777 &comp,
778 r#"<template><link rel="stylesheet" href="my-comp.css"><div>hello</div></template>"#,
779 )
780 .unwrap();
781
782 let templates = plugin.take_component_templates();
783 assert_eq!(templates.len(), 1);
784 let name = &templates[0].tag_name;
785 let html = &templates[0].template;
786 assert_eq!(name, "my-comp");
787 assert!(html.contains("<f-template name=\"my-comp\">"));
788 assert!(html.contains("</f-template>"));
789 assert!(html.contains("<template>"));
790 assert!(html.contains("</template>"));
791 assert!(html.contains("<link rel=\"stylesheet\" href=\"my-comp.css\">"));
792 assert!(html.contains("<div>hello</div>"));
793 }
794
795 #[test]
796 fn component_template_without_css() {
797 let mut plugin = FastV2ParserPlugin::new();
798 let comp = make_component("no-css", "<span>text</span>", None);
799 plugin
800 .register_component_template("no-css", &comp, &comp.html_content)
801 .unwrap();
802
803 let templates = plugin.take_component_templates();
804 assert_eq!(templates.len(), 1);
805 let name = &templates[0].tag_name;
806 let html = &templates[0].template;
807 assert_eq!(name, "no-css");
808 assert!(html.contains("<f-template name=\"no-css\">"));
809 assert!(!html.contains("<link rel=\"stylesheet\""));
810 assert!(html.contains("<span>text</span>"));
811 }
812
813 #[test]
814 fn component_template_css_strategy_style() {
815 let mut plugin = FastV2ParserPlugin::new();
816 let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
817 plugin
818 .register_component_template(
819 "my-comp",
820 &comp,
821 r#"<template><style>div { color: red; }</style><div>hello</div></template>"#,
822 )
823 .unwrap();
824
825 let templates = plugin.take_component_templates();
826 assert_eq!(templates.len(), 1);
827 let html = &templates[0].template;
828 assert!(
829 html.contains("<style>div { color: red; }</style>"),
830 "Style strategy should inline CSS, got: {html}"
831 );
832 assert!(
833 !html.contains("<link"),
834 "Style strategy should not emit <link> tags"
835 );
836 }
837
838 #[test]
839 fn component_template_css_strategy_module() {
840 let mut plugin = FastV2ParserPlugin::new();
841 let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
842 plugin
843 .register_component_template(
844 "my-comp",
845 &comp,
846 r#"<template shadowrootadoptedstylesheets="my-comp"><div>hello</div></template>"#,
847 )
848 .unwrap();
849
850 let templates = plugin.take_component_templates();
851 assert_eq!(templates.len(), 1);
852 let html = &templates[0].template;
853
854 assert!(
857 !html.contains(r#"<style type="module""#),
858 "Legacy CSS module shape should not be baked into f-template: {html}"
859 );
860 assert!(
861 !html.contains(r#"<script type="importmap""#),
862 "CSS module importmap should not be baked into f-template: {html}"
863 );
864 assert!(
866 html.contains(r#"shadowrootadoptedstylesheets="my-comp""#),
867 "Module strategy should add shadowrootadoptedstylesheets, got: {html}"
868 );
869 assert!(
871 !html.contains("<style>div"),
872 "Module strategy should not have inline <style> inside template"
873 );
874 assert!(
875 !html.contains("<link"),
876 "Module strategy should not emit <link> tags"
877 );
878 }
879
880 #[test]
881 fn component_template_css_strategy_module_no_css() {
882 let mut plugin = FastV2ParserPlugin::new();
883 let comp = make_component("my-comp", "<div>hello</div>", None);
884 plugin
885 .register_component_template(
886 "my-comp",
887 &comp,
888 r#"<template><div>hello</div></template>"#,
889 )
890 .unwrap();
891
892 let templates = plugin.take_component_templates();
893 assert_eq!(templates.len(), 1);
894 let html = &templates[0].template;
895 assert!(
896 !html.contains("shadowrootadoptedstylesheets"),
897 "No CSS = no shadowrootadoptedstylesheets, got: {html}"
898 );
899 assert!(
900 !html.contains("<style"),
901 "No CSS = no style tag, got: {html}"
902 );
903 }
904
905 #[test]
906 fn component_template_multiple_components() {
907 let mut plugin = FastV2ParserPlugin::new();
908 let comp1 = make_component("comp-a", "<div>A</div>", None);
909 let comp2 = make_component("comp-b", "<div>B</div>", Some("b { }"));
910 plugin
911 .register_component_template("comp-a", &comp1, &comp1.html_content)
912 .unwrap();
913 plugin
914 .register_component_template("comp-b", &comp2, &comp2.html_content)
915 .unwrap();
916
917 let templates = plugin.take_component_templates();
918 assert_eq!(templates.len(), 2);
919
920 let names: Vec<&str> = templates
921 .iter()
922 .map(|artifact| artifact.tag_name.as_str())
923 .collect();
924 assert!(names.contains(&"comp-a"));
925 assert!(names.contains(&"comp-b"));
926
927 for artifact in &templates {
928 assert!(artifact.template.contains("<f-template name="));
929 }
930 }
931
932 #[test]
933 fn component_template_deduplicates_same_component() {
934 let mut plugin = FastV2ParserPlugin::new();
935 let comp = make_component(
936 "my-button",
937 "<button><slot></slot></button>",
938 Some(".btn{}"),
939 );
940
941 plugin
944 .register_component_template("my-button", &comp, &comp.html_content)
945 .unwrap();
946 plugin
947 .register_component_template("my-button", &comp, &comp.html_content)
948 .unwrap();
949 plugin
950 .register_component_template("my-button", &comp, &comp.html_content)
951 .unwrap();
952
953 let templates = plugin.take_component_templates();
954 assert_eq!(
955 templates.len(),
956 1,
957 "Expected exactly 1 template for my-button, got {}",
958 templates.len()
959 );
960 assert_eq!(templates[0].tag_name, "my-button");
961 }
962
963 #[test]
964 fn component_template_deduplicates_mixed_components() {
965 let mut plugin = FastV2ParserPlugin::new();
966 let btn = make_component("my-button", "<button><slot></slot></button>", None);
967 let card = make_component("my-card", "<div><slot></slot></div>", Some(".card{}"));
968
969 plugin
971 .register_component_template("my-button", &btn, &btn.html_content)
972 .unwrap();
973 plugin
974 .register_component_template("my-card", &card, &card.html_content)
975 .unwrap();
976 plugin
977 .register_component_template("my-button", &btn, &btn.html_content)
978 .unwrap();
979
980 let templates = plugin.take_component_templates();
981 assert_eq!(templates.len(), 2);
982
983 let button_count = templates
984 .iter()
985 .filter(|artifact| artifact.tag_name == "my-button")
986 .count();
987 let card_count = templates
988 .iter()
989 .filter(|artifact| artifact.tag_name == "my-card")
990 .count();
991 assert_eq!(button_count, 1);
992 assert_eq!(card_count, 1);
993 }
994
995 #[test]
998 fn convert_if_to_f_when() {
999 let input = r#"<if condition="isComplete"><span>Done</span></if>"#;
1000 let output = convert_btr_to_fast(input);
1001 assert_eq!(
1002 output,
1003 r#"<f-when value="{{isComplete}}"><span>Done</span></f-when>"#
1004 );
1005 }
1006
1007 #[test]
1008 fn convert_if_with_greater_than() {
1009 let input = r#"<if condition="vara > 2">Over two</if>"#;
1010 let output = convert_btr_to_fast(input);
1011 assert_eq!(output, r#"<f-when value="{{vara > 2}}">Over two</f-when>"#);
1012 }
1013
1014 #[test]
1015 fn convert_if_with_greater_than_or_equal() {
1016 let input = r#"<if condition="vara >= 2">Two and over</if>"#;
1017 let output = convert_btr_to_fast(input);
1018 assert_eq!(
1019 output,
1020 r#"<f-when value="{{vara >= 2}}">Two and over</f-when>"#
1021 );
1022 }
1023
1024 #[test]
1025 fn convert_if_with_less_than() {
1026 let input = r#"<if condition="x < 10">small</if>"#;
1027 let output = convert_btr_to_fast(input);
1028 assert_eq!(output, r#"<f-when value="{{x < 10}}">small</f-when>"#);
1029 }
1030
1031 #[test]
1032 fn convert_for_to_f_repeat() {
1033 let input = r#"<for each="tag in tags"><span>{{tag}}</span></for>"#;
1034 let output = convert_btr_to_fast(input);
1035 assert_eq!(
1036 output,
1037 r#"<f-repeat value="{{tag in tags}}"><span>{{tag}}</span></f-repeat>"#
1038 );
1039 }
1040
1041 #[test]
1042 fn convert_nested_if_and_for() {
1043 let input = r#"<if condition="show"><for each="x in items"><p>{{x}}</p></for></if>"#;
1044 let output = convert_btr_to_fast(input);
1045 assert_eq!(
1046 output,
1047 r#"<f-when value="{{show}}"><f-repeat value="{{x in items}}"><p>{{x}}</p></f-repeat></f-when>"#
1048 );
1049 }
1050
1051 #[test]
1052 fn convert_complex_attr_double_braces() {
1053 let input = r#"<div :data="{{config}}"></div>"#;
1054 let output = convert_btr_to_fast(input);
1055 assert_eq!(output, r#"<div :data="{config}"></div>"#);
1056 }
1057
1058 #[test]
1059 fn convert_multiple_complex_attrs() {
1060 let input = r#"<div :title="{{name}}" :data-id="{{id}}"></div>"#;
1061 let output = convert_btr_to_fast(input);
1062 assert_eq!(output, r#"<div :title="{name}" :data-id="{id}"></div>"#);
1063 }
1064
1065 #[test]
1066 fn no_conversion_for_text_double_braces() {
1067 let input = "<span>{{greeting}}</span>";
1069 let output = convert_btr_to_fast(input);
1070 assert_eq!(output, "<span>{{greeting}}</span>");
1071 }
1072
1073 #[test]
1074 fn no_conversion_for_regular_attr() {
1075 let input = r#"<div title="{{name}}"></div>"#;
1077 let output = convert_btr_to_fast(input);
1078 assert_eq!(output, r#"<div title="{{name}}"></div>"#);
1079 }
1080
1081 #[test]
1082 fn component_template_with_btr_conversion() {
1083 let mut plugin = FastV2ParserPlugin::new();
1084 let html = r#"<div><if condition="visible"><span>hi</span></if></div>"#;
1085 let comp = make_component("my-widget", html, None);
1086 plugin
1087 .register_component_template("my-widget", &comp, &comp.html_content)
1088 .unwrap();
1089
1090 let templates = plugin.take_component_templates();
1091 assert_eq!(templates.len(), 1);
1092 let name = &templates[0].tag_name;
1093 let result = &templates[0].template;
1094 assert_eq!(name, "my-widget");
1095
1096 assert!(result.contains("<f-when value=\"{{visible}}\">"));
1097 assert!(result.contains("</f-when>"));
1098 assert!(!result.contains("<if condition="));
1099 assert!(!result.contains("</if>"));
1100 }
1101
1102 #[test]
1103 fn passthrough_normal_html() {
1104 let input = r#"<div class="container"><p>Hello</p></div>"#;
1105 let output = convert_btr_to_fast(input);
1106 assert_eq!(output, input);
1107 }
1108
1109 #[test]
1110 fn outlet_kept_as_marker_in_f_template() {
1111 let input = r#"<div><outlet /></div>"#;
1112 let output = convert_btr_to_fast(input);
1113 assert_eq!(output, r#"<div><outlet></outlet></div>"#);
1114 }
1115
1116 #[test]
1117 fn outlet_marker_in_component_template() {
1118 let mut plugin = FastV2ParserPlugin::new();
1119 let html =
1120 r#"<template shadowrootmode="open"><h1>Title</h1><main><outlet /></main></template>"#;
1121 let comp = make_component("my-shell", html, None);
1122 plugin
1123 .register_component_template("my-shell", &comp, &comp.html_content)
1124 .unwrap();
1125
1126 let templates = plugin.take_component_templates();
1127 let result = &templates[0].template;
1128 assert!(
1129 result.contains("<outlet></outlet>"),
1130 "outlet should be kept as marker in f-template: {result}"
1131 );
1132 }
1133
1134 #[test]
1135 fn strip_shadowrootmode_from_template() {
1136 let input = r#"<template shadowrootmode="open"><div>Hello</div></template>"#;
1137 let output = convert_btr_to_fast(input);
1138 assert_eq!(output, "<template><div>Hello</div></template>");
1139 }
1140
1141 #[test]
1142 fn strip_shadowrootmode_preserves_other_attrs() {
1143 let input =
1144 r#"<template shadowrootmode="open" @click="{onClick(e)}"><div>Hi</div></template>"#;
1145 let output = convert_btr_to_fast(input);
1146 assert!(output.contains(r#"@click="{onClick(e)}""#));
1147 assert!(!output.contains("shadowrootmode"));
1148 assert!(output.starts_with("<template "));
1149 }
1150
1151 #[test]
1152 fn no_strip_when_no_shadowrootmode() {
1153 let input = r#"<template foo="bar"><div>Hi</div></template>"#;
1154 let output = convert_btr_to_fast(input);
1155 assert_eq!(output, input);
1156 }
1157
1158 #[test]
1159 fn component_template_strips_shadowrootmode_from_f_template() {
1160 let mut plugin = FastV2ParserPlugin::new();
1161 let comp = make_component(
1162 "my-comp",
1163 r#"<template shadowrootmode="open" @click="{onClick(e)}"><div>{{title}}</div></template>"#,
1164 Some("div { color: red; }"),
1165 );
1166 plugin
1167 .register_component_template("my-comp", &comp, &comp.html_content)
1168 .unwrap();
1169 let templates = plugin.take_component_templates();
1170 assert_eq!(templates.len(), 1);
1171 let name = &templates[0].tag_name;
1172 let html = &templates[0].template;
1173 assert_eq!(name, "my-comp");
1174 assert!(!html.contains("shadowrootmode"));
1176 assert!(html.contains("@click"));
1178 assert!(html.contains("{{title}}"));
1180 }
1181
1182 #[test]
1183 fn test_complex_attribute_normalization() {
1184 let cases = [
1187 (
1188 r#"<div :foo="{{value}}"></div>"#,
1189 r#"<div :foo="{value}"></div>"#,
1190 ),
1191 (
1192 r#"<div :foo="{{ value}}"></div>"#,
1193 r#"<div :foo="{ value}"></div>"#,
1194 ),
1195 (
1196 r#"<div :foo="{{value }}"></div>"#,
1197 r#"<div :foo="{value }"></div>"#,
1198 ),
1199 (
1200 r#"<div :foo="{{ value }}"></div>"#,
1201 r#"<div :foo="{ value }"></div>"#,
1202 ),
1203 ];
1204 for (input, expected) in &cases {
1205 let output = convert_btr_to_fast(input);
1206 assert_eq!(&output, expected, "normalization failed for input: {input}");
1207 }
1208 }
1209
1210 #[test]
1211 fn test_non_js_component_inner_template() {
1212 let mut plugin = FastV2ParserPlugin::new();
1213 let html = r#"<div><child-comp><template shadowrootmode="open"><p>inner</p></template></child-comp></div>"#;
1216 let comp = make_component("parent-comp", html, None);
1217 plugin
1218 .register_component_template("parent-comp", &comp, &comp.html_content)
1219 .unwrap();
1220
1221 let templates = plugin.take_component_templates();
1222 assert_eq!(templates.len(), 1);
1223 let name = &templates[0].tag_name;
1224 let output = &templates[0].template;
1225 assert_eq!(name, "parent-comp");
1226
1227 assert!(output.contains("<f-template name=\"parent-comp\">"));
1228 assert!(!output.contains("shadowrootmode"));
1230 assert!(output.contains("<child-comp><template><p>inner</p></template></child-comp>"));
1232 }
1233
1234 #[test]
1235 fn route_tags_converted_to_f_route() {
1236 let input = r#"<route path="/home" name="home" exact><span>Home</span></route>"#;
1237 let output = convert_btr_to_fast(input);
1238 assert!(output.starts_with("<webui-route"));
1239 assert!(output.contains(r#"path="/home""#));
1240 assert!(output.contains(r#"name="home""#));
1241 assert!(output.contains(" exact"));
1242 assert!(output.contains("style=\"display:none\""));
1243 assert!(output.contains("<span>Home</span>"));
1244 assert!(output.ends_with("</webui-route>"));
1245 }
1246
1247 #[test]
1248 fn f_route_tags_pass_through() {
1249 let input = r#"<webui-route path="/" name="dashboard" component="cb-page-dashboard" exact style="display:none"></webui-route>"#;
1251 let output = convert_btr_to_fast(input);
1252 assert_eq!(output, input);
1253 }
1254
1255 #[test]
1260 fn ftemplate_for_loop_converted_to_f_repeat() {
1261 let mut plugin = FastV2ParserPlugin::new();
1262 let html = r#"<ul><for each="item in items"><li>{{item.name}}</li></for></ul>"#;
1263 let comp = make_component("my-list", html, None);
1264 plugin
1265 .register_component_template("my-list", &comp, &comp.html_content)
1266 .unwrap();
1267
1268 let templates = plugin.take_component_templates();
1269 let result = &templates[0].template;
1270
1271 assert!(
1272 result.contains("<f-repeat value=\"{{item in items}}\">"),
1273 "f-template should use <f-repeat>, got: {result}"
1274 );
1275 assert!(
1276 result.contains("</f-repeat>"),
1277 "f-template should close with </f-repeat>, got: {result}"
1278 );
1279 assert!(
1280 !result.contains("<for "),
1281 "f-template should NOT contain <for>, got: {result}"
1282 );
1283 }
1284
1285 #[test]
1286 fn ftemplate_shadow_dom_strips_shadowroot_and_converts_directives() {
1287 let mut plugin = FastV2ParserPlugin::new();
1288 let html = r#"<template shadowrootmode="open"><div><if condition="visible">Shown</if><for each="x in list"><span>{{x}}</span></for></div></template>"#;
1289 let comp = make_component("my-shadow", html, None);
1290 plugin
1291 .register_component_template("my-shadow", &comp, &comp.html_content)
1292 .unwrap();
1293
1294 let templates = plugin.take_component_templates();
1295 let result = &templates[0].template;
1296
1297 assert!(
1298 result.contains("<f-when value=\"{{visible}}\">"),
1299 "Shadow f-template should contain <f-when>, got: {result}"
1300 );
1301 assert!(
1302 result.contains("<f-repeat value=\"{{x in list}}\">"),
1303 "Shadow f-template should contain <f-repeat>, got: {result}"
1304 );
1305 assert!(
1306 !result.contains("shadowrootmode"),
1307 "Shadow f-template should strip shadowrootmode, got: {result}"
1308 );
1309 assert!(
1310 !result.contains("<if "),
1311 "Shadow f-template should NOT contain <if>, got: {result}"
1312 );
1313 assert!(
1314 !result.contains("<for "),
1315 "Shadow f-template should NOT contain <for>, got: {result}"
1316 );
1317 }
1318
1319 #[test]
1320 fn ftemplate_nested_if_and_for_both_converted() {
1321 let mut plugin = FastV2ParserPlugin::new();
1322 let html =
1323 r#"<div><if condition="show"><for each="x in items"><p>{{x}}</p></for></if></div>"#;
1324 let comp = make_component("my-nested", html, None);
1325 plugin
1326 .register_component_template("my-nested", &comp, &comp.html_content)
1327 .unwrap();
1328
1329 let templates = plugin.take_component_templates();
1330 let result = &templates[0].template;
1331
1332 assert!(
1333 result.contains("<f-when value=\"{{show}}\">"),
1334 "Nested f-template should contain <f-when>, got: {result}"
1335 );
1336 assert!(
1337 result.contains("<f-repeat value=\"{{x in items}}\">"),
1338 "Nested f-template should contain <f-repeat>, got: {result}"
1339 );
1340 assert!(
1341 !result.contains("<if "),
1342 "Nested f-template should NOT contain <if>, got: {result}"
1343 );
1344 assert!(
1345 !result.contains("<for "),
1346 "Nested f-template should NOT contain <for>, got: {result}"
1347 );
1348 }
1349
1350 #[test]
1351 fn convert_btr_preserves_utf8_text_content() {
1352 let input = "<span>✓ passed</span>";
1353 let output = convert_btr_to_fast(input);
1354 assert_eq!(output, "<span>✓ passed</span>");
1355 }
1356
1357 #[test]
1358 fn convert_btr_preserves_utf8_multibyte_chars() {
1359 let input = "<span>✓ yes ✗ no ⭐ star</span>";
1360 let output = convert_btr_to_fast(input);
1361 assert_eq!(output, "<span>✓ yes ✗ no ⭐ star</span>");
1362 }
1363
1364 #[test]
1365 fn convert_btr_preserves_utf8_with_directives() {
1366 let input = r#"<if condition="x"><span>✓</span></if>"#;
1367 let output = convert_btr_to_fast(input);
1368 assert_eq!(output, r#"<f-when value="{{x}}"><span>✓</span></f-when>"#);
1369 }
1370
1371 #[test]
1372 fn minify_preserves_utf8_text_content() {
1373 let input = "<span>✓</span><span>✗</span>";
1374 let output = minify_inter_tag_whitespace(input);
1375 assert_eq!(output, "<span>✓</span><span>✗</span>");
1376 }
1377
1378 #[test]
1379 fn minify_preserves_utf8_between_elements() {
1380 let input = "<div> ✓ </div>";
1381 let output = minify_inter_tag_whitespace(input);
1382 assert_eq!(output, "<div> ✓ </div>");
1383 }
1384
1385 #[test]
1386 fn convert_complex_attrs_preserves_utf8() {
1387 let input = r#"<span :title="{{label}}" data-icon="⭐">text</span>"#;
1388 let output = convert_btr_to_fast(input);
1389 assert!(
1390 output.contains("⭐"),
1391 "UTF-8 star should be preserved: {output}"
1392 );
1393 }
1394}