Skip to main content

webui_parser/plugin/
fast.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT license.
3
4//! FAST parser plugin for the WebUI parser.
5//!
6//! Tracks component definitions during HTML parsing and returns `<f-template>`
7//! artifacts after parsing. Converts WebUI Framework template syntax (`<if>`, `<for>`, `{{}}`)
8//! into FAST-compatible syntax (`<f-when>`, `<f-repeat>`, `{}`).
9
10use super::{AttributeAction, ParserPlugin, ParserPluginArtifacts};
11use crate::component_registry::Component;
12use crate::{CssStrategy, Result};
13use webui_protocol::FastElementData;
14
15/// Information about a tracked component for `<f-template>` generation.
16struct TrackedComponent {
17    tag_name: String,
18    html_content: String,
19    css_content: Option<String>,
20}
21
22/// FAST parser plugin.
23///
24/// Implements the `ParserPlugin` trait for the FAST framework:
25/// - Filters FAST-specific runtime binding attributes (`@click`, `f-ref`, etc.)
26/// - Tracks components encountered during parsing
27/// - Returns `<f-template>` artifacts with converted FAST syntax after parsing
28/// - Emits binding attribute counts as `Plugin` protocol fragment data
29pub struct FastParserPlugin {
30    /// Components tracked during parsing, in discovery order.
31    components: Vec<TrackedComponent>,
32    /// CSS delivery strategy for f-templates.
33    css_strategy: CssStrategy,
34}
35
36impl FastParserPlugin {
37    /// Create a new FAST parser plugin.
38    #[must_use]
39    pub fn new() -> Self {
40        Self {
41            components: Vec::new(),
42            css_strategy: CssStrategy::Link,
43        }
44    }
45
46    /// Set the CSS delivery strategy for generated f-templates.
47    pub fn set_css_strategy(&mut self, strategy: CssStrategy) {
48        self.css_strategy = strategy;
49    }
50
51    /// Take the individual component f-template strings, keyed by tag name.
52    ///
53    /// Each value is a complete `<f-template name="tag-name">...</f-template>` string
54    /// ready to be appended to a document. This is used by the JSON partial render
55    /// endpoint to send only the templates the client needs.
56    #[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        // Only track each component once (avoids duplicate <f-template> blocks
87        // when a component is used in multiple parent templates)
88        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
130/// Generate a single f-template HTML string from component data.
131///
132/// Used by the server to generate templates on demand for route components
133/// that weren't encountered during initial parsing.
134pub 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    // Build the CSS injection string based on the configured strategy
149    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
202/// Convert WebUI Framework template syntax to FAST syntax in HTML content.
203///
204/// Performs the following transformations without regex:
205/// - `<if condition="EXPR">` → `<f-when value="{{EXPR}}">`
206/// - `</if>` → `</f-when>`
207/// - `<for each="EXPR">` → `<f-repeat value="{{EXPR}}">`
208/// - `</for>` → `</f-repeat>`
209/// - `{{expr}}` inside `:attr` complex attribute values → `{expr}`
210/// - Strips `shadowrootmode` attributes from `<template>` tags
211///   (in f-template context, shadowrootmode must be removed to prevent
212///   the browser from auto-activating it as a declarative shadow root)
213fn 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        // Check for {{expr}} inside :attr values — handled at attribute level
228        // in try_convert_tag. Outside of tags, double-braces are left as-is
229        // (they're text content interpolation for FAST, kept unchanged).
230        result.push(bytes[i] as char);
231        i += 1;
232    }
233
234    result
235}
236
237/// Try to convert a tag starting at position `pos`. Returns `Some(bytes_consumed)`
238/// if a conversion was performed, or `None` if this is not a convertible tag.
239fn try_convert_tag(input: &str, pos: usize, result: &mut String) -> Option<usize> {
240    let remaining = &input[pos..];
241
242    // Check for closing tags first (shorter patterns)
243    if remaining.starts_with("</if>") {
244        result.push_str("</f-when>");
245        return Some(5);
246    }
247    if remaining.starts_with("</for>") {
248        result.push_str("</f-repeat>");
249        return Some(6);
250    }
251    // <route> in f-templates becomes empty <webui-route> (client router mounts components)
252    if remaining.starts_with("</route>") {
253        result.push_str("</webui-route>");
254        return Some(8);
255    }
256
257    // <outlet /> is kept as a marker element in f-templates.
258    // The client router finds it and replaces it with <webui-route> stubs.
259    if starts_with_tag_name(remaining, "outlet") {
260        if let Some(close) = remaining.find('>') {
261            result.push_str("<outlet></outlet>");
262            return Some(close + 1);
263        }
264    }
265
266    // Check for <if condition="...">
267    if starts_with_tag_name(remaining, "if") {
268        if let Some(consumed) = convert_if_tag(remaining, result) {
269            return Some(consumed);
270        }
271    }
272
273    // Check for <for each="...">
274    if starts_with_tag_name(remaining, "for") {
275        if let Some(consumed) = convert_for_tag(remaining, result) {
276            return Some(consumed);
277        }
278    }
279
280    // Check for <route ...> → <webui-route ...> in f-templates
281    if starts_with_tag_name(remaining, "route") {
282        if let Some(consumed) = convert_route_tag(remaining, result) {
283            return Some(consumed);
284        }
285    }
286
287    // Check for tags with :attr="{{expr}}" complex attribute values
288    if remaining.starts_with("<") {
289        // Strip shadowrootmode from <template> tags
290        if starts_with_tag_name(remaining, "template") {
291            if let Some(consumed) = strip_shadowrootmode(remaining, result) {
292                return Some(consumed);
293            }
294        }
295        if let Some(consumed) = convert_complex_attrs(remaining, result) {
296            return Some(consumed);
297        }
298    }
299
300    None
301}
302
303/// Check if `s` starts with `<name` followed by whitespace or `>`.
304fn starts_with_tag_name(s: &str, name: &str) -> bool {
305    if !s.starts_with('<') {
306        return false;
307    }
308    let after_bracket = &s[1..];
309    if !after_bracket.starts_with(name) {
310        return false;
311    }
312    let after_name = &after_bracket[name.len()..];
313    if after_name.is_empty() {
314        return false;
315    }
316    let next = after_name.as_bytes()[0];
317    next == b' ' || next == b'\t' || next == b'\n' || next == b'\r' || next == b'>'
318}
319
320/// Convert `<if condition="EXPR">` to `<f-when value="{{EXPR}}">`.
321/// Returns bytes consumed on success.
322fn convert_if_tag(tag_str: &str, result: &mut String) -> Option<usize> {
323    // Find the closing '>'
324    let close = tag_str.find('>')?;
325    let tag_content = &tag_str[..=close];
326
327    // Find condition="..." attribute
328    let attr_value = extract_attribute_value(tag_content, "condition")?;
329
330    result.push_str("<f-when value=\"{{");
331    result.push_str(attr_value);
332    result.push_str("}}\">");
333
334    Some(close + 1)
335}
336
337/// Convert `<for each="EXPR">` to `<f-repeat value="{{EXPR}}">`.
338/// Returns bytes consumed on success.
339fn convert_for_tag(tag_str: &str, result: &mut String) -> Option<usize> {
340    // Find the closing '>'
341    let close = tag_str.find('>')?;
342    let tag_content = &tag_str[..=close];
343
344    // Find each="..." attribute
345    let attr_value = extract_attribute_value(tag_content, "each")?;
346
347    result.push_str("<f-repeat value=\"{{");
348    result.push_str(attr_value);
349    result.push_str("}}\">");
350
351    Some(close + 1)
352}
353
354/// Convert `<route ...>` to `<webui-route ...>` in f-templates.
355/// Self-closing routes become `<webui-route ...></webui-route>` (empty).
356/// The component attribute is preserved for the client router.
357fn convert_route_tag(tag_str: &str, result: &mut String) -> Option<usize> {
358    let close = tag_str.find('>')?;
359    let is_self_closing = tag_str[..=close].ends_with("/>");
360    let tag = &tag_str[..=close];
361
362    result.push_str("<webui-route");
363
364    if let Some(v) = extract_attribute_value(tag, "path") {
365        result.push_str(" path=\"");
366        result.push_str(v);
367        result.push('"');
368    }
369    if let Some(v) = extract_attribute_value(tag, "name") {
370        result.push_str(" name=\"");
371        result.push_str(v);
372        result.push('"');
373    }
374    if let Some(v) = extract_attribute_value(tag, "component") {
375        result.push_str(" component=\"");
376        result.push_str(v);
377        result.push('"');
378    }
379    if let Some(v) = extract_attribute_value(tag, "redirectTo") {
380        result.push_str(" redirectto=\"");
381        result.push_str(v);
382        result.push('"');
383    }
384    if tag.contains(" exact") {
385        result.push_str(" exact");
386    }
387    if tag.contains(" layout") {
388        result.push_str(" layout");
389    }
390    result.push_str(" style=\"display:none\"");
391
392    if is_self_closing {
393        result.push_str("></webui-route>");
394    } else {
395        result.push('>');
396    }
397
398    Some(close + 1)
399}
400
401/// Extract the value of a named attribute from a tag string.
402/// Looks for `name="value"` and returns `value`.
403fn extract_attribute_value<'a>(tag: &'a str, attr_name: &str) -> Option<&'a str> {
404    // Search for the attribute name followed by '='
405    let mut search_from = 0;
406    loop {
407        let attr_pos = tag[search_from..].find(attr_name)?;
408        let abs_pos = search_from + attr_pos;
409
410        // Verify it's preceded by whitespace (not part of another attribute name)
411        if abs_pos > 0 {
412            let prev = tag.as_bytes()[abs_pos - 1];
413            if prev != b' ' && prev != b'\t' && prev != b'\n' && prev != b'\r' {
414                search_from = abs_pos + attr_name.len();
415                continue;
416            }
417        }
418
419        let after_name = &tag[abs_pos + attr_name.len()..];
420        if !after_name.starts_with('=') {
421            search_from = abs_pos + attr_name.len();
422            continue;
423        }
424
425        let after_eq = &after_name[1..];
426        if after_eq.starts_with('"') {
427            let value_start = abs_pos + attr_name.len() + 2; // skip `="`
428            let end_quote = tag[value_start..].find('"')?;
429            return Some(&tag[value_start..value_start + end_quote]);
430        }
431
432        return None;
433    }
434}
435
436/// Convert tags that contain `:attr="{{expr}}"` complex attribute bindings.
437/// Replaces `{{expr}}` with `{expr}` in attribute values on `:` prefixed attributes.
438/// Returns bytes consumed on success, or `None` if no conversion needed.
439fn convert_complex_attrs(tag_str: &str, result: &mut String) -> Option<usize> {
440    // Find the closing '>'
441    let close = tag_str.find('>')?;
442    let tag_content = &tag_str[..=close];
443
444    // Quick check: does this tag have both a colon-prefixed attribute and `{{`?
445    if !tag_content.contains(":") || !tag_content.contains("{{") {
446        return None;
447    }
448
449    // Process the tag character by character, converting {{}} to {} in :attr values
450    let mut converted = String::with_capacity(tag_content.len());
451    let tag_bytes = tag_content.as_bytes();
452    let tag_len = tag_bytes.len();
453    let mut j = 0;
454    let mut in_colon_attr_value = false;
455
456    while j < tag_len {
457        if !in_colon_attr_value {
458            // Look for :attrname="
459            if tag_bytes[j] == b':' && j > 0 && is_whitespace(tag_bytes[j - 1]) {
460                // Found a colon-prefixed attribute, scan to the ="
461                let attr_start = j;
462                j += 1;
463                // Skip attribute name
464                while j < tag_len && tag_bytes[j] != b'=' && !is_whitespace(tag_bytes[j]) {
465                    j += 1;
466                }
467                if j < tag_len && tag_bytes[j] == b'=' {
468                    j += 1;
469                    if j < tag_len && tag_bytes[j] == b'"' {
470                        // Push everything up to and including the opening quote
471                        converted.push_str(&tag_content[attr_start..=j]);
472                        j += 1;
473                        in_colon_attr_value = true;
474                        continue;
475                    }
476                }
477                // Not a valid :attr="..." pattern, output as-is
478                converted.push_str(&tag_content[attr_start..j]);
479                continue;
480            }
481            converted.push(tag_bytes[j] as char);
482            j += 1;
483        } else {
484            // Inside a :attr value — convert {{expr}} to {expr}
485            if tag_bytes[j] == b'"' {
486                // End of attribute value
487                converted.push('"');
488                j += 1;
489                in_colon_attr_value = false;
490            } else if j + 1 < tag_len && tag_bytes[j] == b'{' && tag_bytes[j + 1] == b'{' {
491                // Found {{ — find matching }}
492                let expr_start = j + 2;
493                if let Some(end_offset) = tag_content[expr_start..].find("}}") {
494                    let expr = &tag_content[expr_start..expr_start + end_offset];
495                    converted.push('{');
496                    converted.push_str(expr);
497                    converted.push('}');
498                    j = expr_start + end_offset + 2;
499                } else {
500                    // No matching }}, output as-is
501                    converted.push('{');
502                    converted.push('{');
503                    j += 2;
504                }
505            } else {
506                converted.push(tag_bytes[j] as char);
507                j += 1;
508            }
509        }
510    }
511
512    result.push_str(&converted);
513    Some(close + 1)
514}
515
516/// Check if a byte is ASCII whitespace.
517fn is_whitespace(b: u8) -> bool {
518    b == b' ' || b == b'\t' || b == b'\n' || b == b'\r'
519}
520
521/// Collapse whitespace-only text between `>` and `<` to eliminate extra DOM
522/// text nodes that would shift element indices during hydration.
523/// This ensures the f-template DOM structure matches the minified DSD output.
524fn minify_inter_tag_whitespace(input: &str) -> String {
525    let mut result = String::with_capacity(input.len());
526    let bytes = input.as_bytes();
527    let len = bytes.len();
528    let mut i = 0;
529
530    while i < len {
531        if bytes[i] == b'>' && i + 1 < len {
532            result.push('>');
533            i += 1;
534            // Skip whitespace-only content between > and <
535            let ws_start = i;
536            while i < len && is_whitespace(bytes[i]) {
537                i += 1;
538            }
539            // If we hit '<', the whitespace was inter-tag — drop it
540            // If we hit non-'<', it's meaningful text — keep it
541            if i >= len || bytes[i] != b'<' {
542                // Keep the whitespace (it's before text content)
543                result.push_str(&input[ws_start..i]);
544            }
545        } else {
546            result.push(bytes[i] as char);
547            i += 1;
548        }
549    }
550
551    result
552}
553
554/// Strip `shadowrootmode` attribute from a `<template ...>` opening tag.
555/// Returns `Some(bytes_consumed)` if a `<template` tag was found and processed.
556fn strip_shadowrootmode(tag_str: &str, result: &mut String) -> Option<usize> {
557    // Find the closing '>'
558    let close = tag_str.find('>')?;
559    let tag_content = &tag_str[..=close];
560
561    // Only process if this tag contains shadowrootmode
562    if !tag_content.contains("shadowrootmode") {
563        return None;
564    }
565
566    // Rebuild the tag without the shadowrootmode attribute
567    result.push_str("<template");
568    let attr_start = "<template".len();
569    let inner = &tag_content[attr_start..close];
570
571    // Scan through the attributes, skipping shadowrootmode
572    let inner_bytes = inner.as_bytes();
573    let inner_len = inner_bytes.len();
574    let mut j = 0;
575    while j < inner_len {
576        // Skip whitespace
577        if is_whitespace(inner_bytes[j]) {
578            j += 1;
579            continue;
580        }
581
582        // Find the end of this attribute (name="value" or just name)
583        let attr_begin = j;
584        // Find '=' or whitespace or end
585        while j < inner_len && inner_bytes[j] != b'=' && !is_whitespace(inner_bytes[j]) {
586            j += 1;
587        }
588        let attr_name = &inner[attr_begin..j];
589
590        // If there's a '=', consume the value
591        let mut attr_end = j;
592        if j < inner_len && inner_bytes[j] == b'=' {
593            j += 1; // skip '='
594            if j < inner_len && inner_bytes[j] == b'"' {
595                j += 1; // skip opening quote
596                while j < inner_len && inner_bytes[j] != b'"' {
597                    j += 1;
598                }
599                if j < inner_len {
600                    j += 1; // skip closing quote
601                }
602            } else {
603                // Unquoted value
604                while j < inner_len && !is_whitespace(inner_bytes[j]) {
605                    j += 1;
606                }
607            }
608            attr_end = j;
609        }
610
611        // Skip the shadowrootmode attribute entirely
612        if attr_name == "shadowrootmode" {
613            continue;
614        }
615
616        // Keep this attribute
617        result.push(' ');
618        result.push_str(&inner[attr_begin..attr_end]);
619    }
620
621    if tag_content.ends_with("/>") {
622        result.push_str("/>");
623    } else {
624        result.push('>');
625    }
626
627    Some(close + 1)
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633    use std::path::PathBuf;
634
635    fn make_component(tag: &str, html: &str, css: Option<&str>) -> Component {
636        Component {
637            tag_name: tag.to_string(),
638            html_content: html.to_string(),
639            css_content: css.map(ToString::to_string),
640            css_tokens: Vec::new(),
641            source_path: PathBuf::from("/test"),
642            class_name: None,
643        }
644    }
645
646    // --- classify_attribute ---
647
648    #[test]
649    fn skip_event_binding() {
650        let mut plugin = FastParserPlugin::new();
651        assert_eq!(
652            plugin.classify_attribute("@click"),
653            AttributeAction::SkipAndCountBinding
654        );
655        assert_eq!(
656            plugin.classify_attribute("@input"),
657            AttributeAction::SkipAndCountBinding
658        );
659        assert_eq!(
660            plugin.classify_attribute("@custom-event"),
661            AttributeAction::SkipAndCountBinding
662        );
663    }
664
665    #[test]
666    fn skip_f_ref() {
667        let mut plugin = FastParserPlugin::new();
668        assert_eq!(
669            plugin.classify_attribute("f-ref"),
670            AttributeAction::SkipAndCountBinding
671        );
672    }
673
674    #[test]
675    fn skip_f_slotted() {
676        let mut plugin = FastParserPlugin::new();
677        assert_eq!(
678            plugin.classify_attribute("f-slotted"),
679            AttributeAction::SkipAndCountBinding
680        );
681    }
682
683    #[test]
684    fn skip_f_children() {
685        let mut plugin = FastParserPlugin::new();
686        assert_eq!(
687            plugin.classify_attribute("f-children"),
688            AttributeAction::SkipAndCountBinding
689        );
690    }
691
692    #[test]
693    fn do_not_skip_normal_attributes() {
694        let mut plugin = FastParserPlugin::new();
695        assert_eq!(plugin.classify_attribute("class"), AttributeAction::Keep);
696        assert_eq!(plugin.classify_attribute("id"), AttributeAction::Keep);
697        assert_eq!(
698            plugin.classify_attribute("data-value"),
699            AttributeAction::Keep
700        );
701        assert_eq!(plugin.classify_attribute(":title"), AttributeAction::Keep);
702        assert_eq!(plugin.classify_attribute("f-other"), AttributeAction::Keep);
703    }
704
705    // --- finish_element ---
706
707    #[test]
708    fn element_parsed_zero_count_returns_none() {
709        let mut plugin = FastParserPlugin::new();
710        assert!(plugin.finish_element(0).is_none());
711    }
712
713    #[test]
714    fn element_parsed_nonzero_count_returns_le_bytes() {
715        let mut plugin = FastParserPlugin::new();
716        let data = plugin.finish_element(3);
717        assert!(data.is_some());
718        let bytes = data.as_deref().unwrap_or_default();
719        assert_eq!(bytes, &3u32.to_le_bytes());
720    }
721
722    #[test]
723    fn element_parsed_large_count() {
724        let mut plugin = FastParserPlugin::new();
725        let data = plugin.finish_element(256);
726        assert!(data.is_some());
727        let bytes = data.as_deref().unwrap_or_default();
728        assert_eq!(bytes, &256u32.to_le_bytes());
729    }
730
731    #[test]
732    fn component_template_simple_component() {
733        let mut plugin = FastParserPlugin::new();
734        let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
735        plugin
736            .register_component_template("my-comp", &comp, &comp.html_content)
737            .unwrap();
738
739        let templates = plugin.take_component_templates();
740        assert_eq!(templates.len(), 1);
741        let (name, html) = &templates[0];
742        assert_eq!(name, "my-comp");
743        assert!(html.contains("<f-template name=\"my-comp\">"));
744        assert!(html.contains("</f-template>"));
745        assert!(html.contains("<template>"));
746        assert!(html.contains("</template>"));
747        assert!(html.contains("<link rel=\"stylesheet\" href=\"/my-comp.css\">"));
748        assert!(html.contains("<div>hello</div>"));
749    }
750
751    #[test]
752    fn component_template_without_css() {
753        let mut plugin = FastParserPlugin::new();
754        let comp = make_component("no-css", "<span>text</span>", None);
755        plugin
756            .register_component_template("no-css", &comp, &comp.html_content)
757            .unwrap();
758
759        let templates = plugin.take_component_templates();
760        assert_eq!(templates.len(), 1);
761        let (name, html) = &templates[0];
762        assert_eq!(name, "no-css");
763        assert!(html.contains("<f-template name=\"no-css\">"));
764        assert!(!html.contains("<link rel=\"stylesheet\""));
765        assert!(html.contains("<span>text</span>"));
766    }
767
768    #[test]
769    fn component_template_css_strategy_style() {
770        let mut plugin = FastParserPlugin::new();
771        plugin.set_css_strategy(crate::CssStrategy::Style);
772        let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
773        plugin
774            .register_component_template("my-comp", &comp, &comp.html_content)
775            .unwrap();
776
777        let templates = plugin.take_component_templates();
778        assert_eq!(templates.len(), 1);
779        let (_, html) = &templates[0];
780        assert!(
781            html.contains("<style>div { color: red; }</style>"),
782            "Style strategy should inline CSS, got: {html}"
783        );
784        assert!(
785            !html.contains("<link"),
786            "Style strategy should not emit <link> tags"
787        );
788    }
789
790    #[test]
791    fn component_template_css_strategy_module() {
792        let mut plugin = FastParserPlugin::new();
793        plugin.set_css_strategy(crate::CssStrategy::Module);
794        let comp = make_component("my-comp", "<div>hello</div>", Some("div { color: red; }"));
795        plugin
796            .register_component_template("my-comp", &comp, &comp.html_content)
797            .unwrap();
798
799        let templates = plugin.take_component_templates();
800        assert_eq!(templates.len(), 1);
801        let (_, html) = &templates[0];
802
803        // f-template should NOT contain the CSS module — that is added
804        // by the handler (SSR) or prepend_css_module (partials).
805        assert!(
806            !html.contains(r#"<style type="module""#),
807            "CSS module should not be baked into f-template: {html}"
808        );
809        // shadowrootadoptedstylesheets on the inner template
810        assert!(
811            html.contains(r#"shadowrootadoptedstylesheets="my-comp""#),
812            "Module strategy should add shadowrootadoptedstylesheets, got: {html}"
813        );
814        // No inline <style> or <link> inside the template
815        assert!(
816            !html.contains("<style>div"),
817            "Module strategy should not have inline <style> inside template"
818        );
819        assert!(
820            !html.contains("<link"),
821            "Module strategy should not emit <link> tags"
822        );
823    }
824
825    #[test]
826    fn component_template_css_strategy_module_no_css() {
827        let mut plugin = FastParserPlugin::new();
828        plugin.set_css_strategy(crate::CssStrategy::Module);
829        let comp = make_component("my-comp", "<div>hello</div>", None);
830        plugin
831            .register_component_template("my-comp", &comp, &comp.html_content)
832            .unwrap();
833
834        let templates = plugin.take_component_templates();
835        assert_eq!(templates.len(), 1);
836        let (_, html) = &templates[0];
837        assert!(
838            !html.contains("shadowrootadoptedstylesheets"),
839            "No CSS = no shadowrootadoptedstylesheets, got: {html}"
840        );
841        assert!(
842            !html.contains("<style"),
843            "No CSS = no style tag, got: {html}"
844        );
845    }
846
847    #[test]
848    fn component_template_multiple_components() {
849        let mut plugin = FastParserPlugin::new();
850        let comp1 = make_component("comp-a", "<div>A</div>", None);
851        let comp2 = make_component("comp-b", "<div>B</div>", Some("b { }"));
852        plugin
853            .register_component_template("comp-a", &comp1, &comp1.html_content)
854            .unwrap();
855        plugin
856            .register_component_template("comp-b", &comp2, &comp2.html_content)
857            .unwrap();
858
859        let templates = plugin.take_component_templates();
860        assert_eq!(templates.len(), 2);
861
862        let names: Vec<&str> = templates.iter().map(|(n, _)| n.as_str()).collect();
863        assert!(names.contains(&"comp-a"));
864        assert!(names.contains(&"comp-b"));
865
866        for (_, html) in &templates {
867            assert!(html.contains("<f-template name="));
868        }
869    }
870
871    #[test]
872    fn component_template_deduplicates_same_component() {
873        let mut plugin = FastParserPlugin::new();
874        let comp = make_component(
875            "my-button",
876            "<button><slot></slot></button>",
877            Some(".btn{}"),
878        );
879
880        // Simulate the same component encountered multiple times
881        // (e.g., <my-button> used in todo-app, todo-item, etc.)
882        plugin
883            .register_component_template("my-button", &comp, &comp.html_content)
884            .unwrap();
885        plugin
886            .register_component_template("my-button", &comp, &comp.html_content)
887            .unwrap();
888        plugin
889            .register_component_template("my-button", &comp, &comp.html_content)
890            .unwrap();
891
892        let templates = plugin.take_component_templates();
893        assert_eq!(
894            templates.len(),
895            1,
896            "Expected exactly 1 template for my-button, got {}",
897            templates.len()
898        );
899        assert_eq!(templates[0].0, "my-button");
900    }
901
902    #[test]
903    fn component_template_deduplicates_mixed_components() {
904        let mut plugin = FastParserPlugin::new();
905        let btn = make_component("my-button", "<button><slot></slot></button>", None);
906        let card = make_component("my-card", "<div><slot></slot></div>", Some(".card{}"));
907
908        // my-button used in two different parent templates, my-card used once
909        plugin
910            .register_component_template("my-button", &btn, &btn.html_content)
911            .unwrap();
912        plugin
913            .register_component_template("my-card", &card, &card.html_content)
914            .unwrap();
915        plugin
916            .register_component_template("my-button", &btn, &btn.html_content)
917            .unwrap();
918
919        let templates = plugin.take_component_templates();
920        assert_eq!(templates.len(), 2);
921
922        let button_count = templates.iter().filter(|(n, _)| n == "my-button").count();
923        let card_count = templates.iter().filter(|(n, _)| n == "my-card").count();
924        assert_eq!(button_count, 1);
925        assert_eq!(card_count, 1);
926    }
927
928    // --- FAST syntax conversion ---
929
930    #[test]
931    fn convert_if_to_f_when() {
932        let input = r#"<if condition="isComplete"><span>Done</span></if>"#;
933        let output = convert_btr_to_fast(input);
934        assert_eq!(
935            output,
936            r#"<f-when value="{{isComplete}}"><span>Done</span></f-when>"#
937        );
938    }
939
940    #[test]
941    fn convert_for_to_f_repeat() {
942        let input = r#"<for each="tag in tags"><span>{{tag}}</span></for>"#;
943        let output = convert_btr_to_fast(input);
944        assert_eq!(
945            output,
946            r#"<f-repeat value="{{tag in tags}}"><span>{{tag}}</span></f-repeat>"#
947        );
948    }
949
950    #[test]
951    fn convert_nested_if_and_for() {
952        let input = r#"<if condition="show"><for each="x in items"><p>{{x}}</p></for></if>"#;
953        let output = convert_btr_to_fast(input);
954        assert_eq!(
955            output,
956            r#"<f-when value="{{show}}"><f-repeat value="{{x in items}}"><p>{{x}}</p></f-repeat></f-when>"#
957        );
958    }
959
960    #[test]
961    fn convert_complex_attr_double_braces() {
962        let input = r#"<div :data="{{config}}"></div>"#;
963        let output = convert_btr_to_fast(input);
964        assert_eq!(output, r#"<div :data="{config}"></div>"#);
965    }
966
967    #[test]
968    fn convert_multiple_complex_attrs() {
969        let input = r#"<div :title="{{name}}" :data-id="{{id}}"></div>"#;
970        let output = convert_btr_to_fast(input);
971        assert_eq!(output, r#"<div :title="{name}" :data-id="{id}"></div>"#);
972    }
973
974    #[test]
975    fn no_conversion_for_text_double_braces() {
976        // Double braces in text content (not in :attr) should stay as-is
977        let input = "<span>{{greeting}}</span>";
978        let output = convert_btr_to_fast(input);
979        assert_eq!(output, "<span>{{greeting}}</span>");
980    }
981
982    #[test]
983    fn no_conversion_for_regular_attr() {
984        // Double braces in non-colon attributes should stay as-is
985        let input = r#"<div title="{{name}}"></div>"#;
986        let output = convert_btr_to_fast(input);
987        assert_eq!(output, r#"<div title="{{name}}"></div>"#);
988    }
989
990    #[test]
991    fn component_template_with_btr_conversion() {
992        let mut plugin = FastParserPlugin::new();
993        let html = r#"<div><if condition="visible"><span>hi</span></if></div>"#;
994        let comp = make_component("my-widget", html, None);
995        plugin
996            .register_component_template("my-widget", &comp, &comp.html_content)
997            .unwrap();
998
999        let templates = plugin.take_component_templates();
1000        assert_eq!(templates.len(), 1);
1001        let (name, result) = &templates[0];
1002        assert_eq!(name, "my-widget");
1003
1004        assert!(result.contains("<f-when value=\"{{visible}}\">"));
1005        assert!(result.contains("</f-when>"));
1006        assert!(!result.contains("<if condition="));
1007        assert!(!result.contains("</if>"));
1008    }
1009
1010    #[test]
1011    fn passthrough_normal_html() {
1012        let input = r#"<div class="container"><p>Hello</p></div>"#;
1013        let output = convert_btr_to_fast(input);
1014        assert_eq!(output, input);
1015    }
1016
1017    #[test]
1018    fn outlet_kept_as_marker_in_f_template() {
1019        let input = r#"<div><outlet /></div>"#;
1020        let output = convert_btr_to_fast(input);
1021        assert_eq!(output, r#"<div><outlet></outlet></div>"#);
1022    }
1023
1024    #[test]
1025    fn outlet_marker_in_component_template() {
1026        let mut plugin = FastParserPlugin::new();
1027        let html =
1028            r#"<template shadowrootmode="open"><h1>Title</h1><main><outlet /></main></template>"#;
1029        let comp = make_component("my-shell", html, None);
1030        plugin
1031            .register_component_template("my-shell", &comp, &comp.html_content)
1032            .unwrap();
1033
1034        let templates = plugin.take_component_templates();
1035        let (_, result) = &templates[0];
1036        assert!(
1037            result.contains("<outlet></outlet>"),
1038            "outlet should be kept as marker in f-template: {result}"
1039        );
1040    }
1041
1042    #[test]
1043    fn strip_shadowrootmode_from_template() {
1044        let input = r#"<template shadowrootmode="open"><div>Hello</div></template>"#;
1045        let output = convert_btr_to_fast(input);
1046        assert_eq!(output, "<template><div>Hello</div></template>");
1047    }
1048
1049    #[test]
1050    fn strip_shadowrootmode_preserves_other_attrs() {
1051        let input =
1052            r#"<template shadowrootmode="open" @click="{onClick(e)}"><div>Hi</div></template>"#;
1053        let output = convert_btr_to_fast(input);
1054        assert!(output.contains(r#"@click="{onClick(e)}""#));
1055        assert!(!output.contains("shadowrootmode"));
1056        assert!(output.starts_with("<template "));
1057    }
1058
1059    #[test]
1060    fn no_strip_when_no_shadowrootmode() {
1061        let input = r#"<template foo="bar"><div>Hi</div></template>"#;
1062        let output = convert_btr_to_fast(input);
1063        assert_eq!(output, input);
1064    }
1065
1066    #[test]
1067    fn component_template_strips_shadowrootmode_from_f_template() {
1068        let mut plugin = FastParserPlugin::new();
1069        let comp = make_component(
1070            "my-comp",
1071            r#"<template shadowrootmode="open" @click="{onClick(e)}"><div>{{title}}</div></template>"#,
1072            Some("div { color: red; }"),
1073        );
1074        plugin
1075            .register_component_template("my-comp", &comp, &comp.html_content)
1076            .unwrap();
1077        let templates = plugin.take_component_templates();
1078        assert_eq!(templates.len(), 1);
1079        let (name, html) = &templates[0];
1080        assert_eq!(name, "my-comp");
1081        // f-template content should NOT have shadowrootmode
1082        assert!(!html.contains("shadowrootmode"));
1083        // But should keep @click (framework attr kept in f-template mode)
1084        assert!(html.contains("@click"));
1085        // Should have the converted content
1086        assert!(html.contains("{{title}}"));
1087    }
1088
1089    #[test]
1090    fn test_complex_attribute_normalization() {
1091        // All spacing variants should convert {{}} to {} in :attr values,
1092        // preserving any whitespace within the expression.
1093        let cases = [
1094            (
1095                r#"<div :foo="{{value}}"></div>"#,
1096                r#"<div :foo="{value}"></div>"#,
1097            ),
1098            (
1099                r#"<div :foo="{{ value}}"></div>"#,
1100                r#"<div :foo="{ value}"></div>"#,
1101            ),
1102            (
1103                r#"<div :foo="{{value }}"></div>"#,
1104                r#"<div :foo="{value }"></div>"#,
1105            ),
1106            (
1107                r#"<div :foo="{{ value }}"></div>"#,
1108                r#"<div :foo="{ value }"></div>"#,
1109            ),
1110        ];
1111        for (input, expected) in &cases {
1112            let output = convert_btr_to_fast(input);
1113            assert_eq!(&output, expected, "normalization failed for input: {input}");
1114        }
1115    }
1116
1117    #[test]
1118    fn test_non_js_component_inner_template() {
1119        let mut plugin = FastParserPlugin::new();
1120        // A JS component whose HTML contains a non-JS component using
1121        // declarative shadow DOM (template with shadowrootmode).
1122        let html = r#"<div><child-comp><template shadowrootmode="open"><p>inner</p></template></child-comp></div>"#;
1123        let comp = make_component("parent-comp", html, None);
1124        plugin
1125            .register_component_template("parent-comp", &comp, &comp.html_content)
1126            .unwrap();
1127
1128        let templates = plugin.take_component_templates();
1129        assert_eq!(templates.len(), 1);
1130        let (name, output) = &templates[0];
1131        assert_eq!(name, "parent-comp");
1132
1133        assert!(output.contains("<f-template name=\"parent-comp\">"));
1134        // shadowrootmode must be stripped from the inner non-JS component's template
1135        assert!(!output.contains("shadowrootmode"));
1136        // The inner template structure should be preserved (without shadowrootmode)
1137        assert!(output.contains("<child-comp><template><p>inner</p></template></child-comp>"));
1138    }
1139
1140    #[test]
1141    fn route_tags_converted_to_f_route() {
1142        let input = r#"<route path="/home" name="home" exact><span>Home</span></route>"#;
1143        let output = convert_btr_to_fast(input);
1144        assert!(output.starts_with("<webui-route"));
1145        assert!(output.contains(r#"path="/home""#));
1146        assert!(output.contains(r#"name="home""#));
1147        assert!(output.contains(" exact"));
1148        assert!(output.contains("style=\"display:none\""));
1149        assert!(output.contains("<span>Home</span>"));
1150        assert!(output.ends_with("</webui-route>"));
1151    }
1152
1153    #[test]
1154    fn f_route_tags_pass_through() {
1155        // <webui-route> tags emitted by the parser should pass through unchanged
1156        let input = r#"<webui-route path="/" name="dashboard" component="cb-page-dashboard" exact style="display:none"></webui-route>"#;
1157        let output = convert_btr_to_fast(input);
1158        assert_eq!(output, input);
1159    }
1160
1161    // --- End-to-end f-template regression tests ---
1162    // Verify that generated f-template blocks always use FAST syntax
1163    // (<f-when>/<f-repeat>) instead of webui syntax (<if>/<for>).
1164
1165    #[test]
1166    fn ftemplate_for_loop_converted_to_f_repeat() {
1167        let mut plugin = FastParserPlugin::new();
1168        let html = r#"<ul><for each="item in items"><li>{{item.name}}</li></for></ul>"#;
1169        let comp = make_component("my-list", html, None);
1170        plugin
1171            .register_component_template("my-list", &comp, &comp.html_content)
1172            .unwrap();
1173
1174        let templates = plugin.take_component_templates();
1175        let (_, result) = &templates[0];
1176
1177        assert!(
1178            result.contains("<f-repeat value=\"{{item in items}}\">"),
1179            "f-template should use <f-repeat>, got: {result}"
1180        );
1181        assert!(
1182            result.contains("</f-repeat>"),
1183            "f-template should close with </f-repeat>, got: {result}"
1184        );
1185        assert!(
1186            !result.contains("<for "),
1187            "f-template should NOT contain <for>, got: {result}"
1188        );
1189    }
1190
1191    #[test]
1192    fn ftemplate_shadow_dom_strips_shadowroot_and_converts_directives() {
1193        let mut plugin = FastParserPlugin::new();
1194        let html = r#"<template shadowrootmode="open"><div><if condition="visible">Shown</if><for each="x in list"><span>{{x}}</span></for></div></template>"#;
1195        let comp = make_component("my-shadow", html, None);
1196        plugin
1197            .register_component_template("my-shadow", &comp, &comp.html_content)
1198            .unwrap();
1199
1200        let templates = plugin.take_component_templates();
1201        let (_, result) = &templates[0];
1202
1203        assert!(
1204            result.contains("<f-when value=\"{{visible}}\">"),
1205            "Shadow f-template should contain <f-when>, got: {result}"
1206        );
1207        assert!(
1208            result.contains("<f-repeat value=\"{{x in list}}\">"),
1209            "Shadow f-template should contain <f-repeat>, got: {result}"
1210        );
1211        assert!(
1212            !result.contains("shadowrootmode"),
1213            "Shadow f-template should strip shadowrootmode, got: {result}"
1214        );
1215        assert!(
1216            !result.contains("<if "),
1217            "Shadow f-template should NOT contain <if>, got: {result}"
1218        );
1219        assert!(
1220            !result.contains("<for "),
1221            "Shadow f-template should NOT contain <for>, got: {result}"
1222        );
1223    }
1224
1225    #[test]
1226    fn ftemplate_nested_if_and_for_both_converted() {
1227        let mut plugin = FastParserPlugin::new();
1228        let html =
1229            r#"<div><if condition="show"><for each="x in items"><p>{{x}}</p></for></if></div>"#;
1230        let comp = make_component("my-nested", html, None);
1231        plugin
1232            .register_component_template("my-nested", &comp, &comp.html_content)
1233            .unwrap();
1234
1235        let templates = plugin.take_component_templates();
1236        let (_, result) = &templates[0];
1237
1238        assert!(
1239            result.contains("<f-when value=\"{{show}}\">"),
1240            "Nested f-template should contain <f-when>, got: {result}"
1241        );
1242        assert!(
1243            result.contains("<f-repeat value=\"{{x in items}}\">"),
1244            "Nested f-template should contain <f-repeat>, got: {result}"
1245        );
1246        assert!(
1247            !result.contains("<if "),
1248            "Nested f-template should NOT contain <if>, got: {result}"
1249        );
1250        assert!(
1251            !result.contains("<for "),
1252            "Nested f-template should NOT contain <for>, got: {result}"
1253        );
1254    }
1255}