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