1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use crate::prelude::*;

use crate::jsx::lists::child_list::{FormatChildrenResult, FormatJsxChildList, JsxChildListLayout};
use crate::utils::jsx::{is_jsx_suppressed, is_meaningful_jsx_text};
use biome_formatter::{format_args, write, CstFormatContext, FormatResult, FormatRuleWithOptions};
use biome_js_syntax::{
    AnyJsExpression, AnyJsxChild, JsxChildList, JsxElement, JsxExpressionChild, JsxFragment,
};
use biome_rowan::{declare_node_union, SyntaxResult};

#[derive(Debug, Clone, Default)]
pub struct FormatJsxElement;

impl FormatNodeRule<JsxElement> for FormatJsxElement {
    fn fmt_fields(&self, node: &JsxElement, f: &mut JsFormatter) -> FormatResult<()> {
        AnyJsxTagWithChildren::from(node.clone()).fmt(f)
    }

    fn is_suppressed(&self, node: &JsxElement, f: &JsFormatter) -> bool {
        is_jsx_suppressed(&node.clone().into(), f.comments())
    }

    fn fmt_leading_comments(&self, node: &JsxElement, f: &mut JsFormatter) -> FormatResult<()> {
        debug_assert!(
            !f.comments().has_leading_comments(node.syntax()),
            "JsxElement can not have comments."
        );
        Ok(())
    }

    fn fmt_dangling_comments(&self, node: &JsxElement, f: &mut JsFormatter) -> FormatResult<()> {
        debug_assert!(
            !f.comments().has_dangling_comments(node.syntax()),
            "JsxElement can not have comments."
        );
        Ok(())
    }

    fn fmt_trailing_comments(&self, node: &JsxElement, f: &mut JsFormatter) -> FormatResult<()> {
        debug_assert!(
            !f.comments().has_trailing_comments(node.syntax()),
            "JsxElement can not have comments."
        );
        Ok(())
    }
}

declare_node_union! {
    pub(super) AnyJsxTagWithChildren = JsxElement | JsxFragment
}

impl Format<JsFormatContext> for AnyJsxTagWithChildren {
    fn fmt(&self, f: &mut Formatter<JsFormatContext>) -> FormatResult<()> {
        let format_opening = format_with(|f| self.fmt_opening(f));
        let format_closing = format_with(|f| self.fmt_closing(f));

        let layout = self.layout(f)?;

        match layout {
            ElementLayout::NoChildren => {
                write!(f, [format_opening, format_closing])
            }

            ElementLayout::Template(expression) => {
                write!(f, [format_opening, expression.format(), format_closing])
            }

            ElementLayout::Default => {
                let mut format_opening = format_opening.memoized();
                let opening_breaks = format_opening.inspect(f)?.will_break();

                let multiple_attributes = match self {
                    AnyJsxTagWithChildren::JsxElement(element) => {
                        element.opening_element()?.attributes().len() > 1
                    }
                    AnyJsxTagWithChildren::JsxFragment(_) => false,
                };

                let list_layout = if multiple_attributes || opening_breaks {
                    JsxChildListLayout::Multiline
                } else {
                    JsxChildListLayout::BestFitting
                };

                let children = self.children();
                let format_children = FormatJsxChildList::default()
                    .with_options(list_layout)
                    .fmt_children(&children, f)?;

                match format_children {
                    FormatChildrenResult::ForceMultiline(multiline) => {
                        write!(f, [format_opening, multiline, format_closing])
                    }
                    FormatChildrenResult::BestFitting {
                        flat_children,
                        expanded_children,
                    } => {
                        let format_closing = format_closing.memoized();
                        write!(
                            f,
                            [best_fitting![
                                format_args![format_opening, flat_children, format_closing],
                                format_args![format_opening, expanded_children, format_closing]
                            ]]
                        )
                    }
                }
            }
        }
    }
}

impl AnyJsxTagWithChildren {
    fn fmt_opening(&self, f: &mut JsFormatter) -> FormatResult<()> {
        match self {
            AnyJsxTagWithChildren::JsxElement(element) => {
                write!(f, [element.opening_element().format()])
            }
            AnyJsxTagWithChildren::JsxFragment(fragment) => {
                write!(f, [fragment.opening_fragment().format()])
            }
        }
    }

    fn fmt_closing(&self, f: &mut JsFormatter) -> FormatResult<()> {
        match self {
            AnyJsxTagWithChildren::JsxElement(element) => {
                write!(f, [element.closing_element().format()])
            }
            AnyJsxTagWithChildren::JsxFragment(fragment) => {
                write!(f, [fragment.closing_fragment().format()])
            }
        }
    }

    fn children(&self) -> JsxChildList {
        match self {
            AnyJsxTagWithChildren::JsxElement(element) => element.children(),
            AnyJsxTagWithChildren::JsxFragment(fragment) => fragment.children(),
        }
    }

    fn layout(&self, f: &mut JsFormatter) -> SyntaxResult<ElementLayout> {
        use AnyJsExpression::*;
        use AnyJsxChild::*;

        let children = self.children();

        let layout = match children.len() {
            0 => ElementLayout::NoChildren,
            1 => {
                // SAFETY: Safe because of length check above
                let child = children.first().unwrap();

                match child {
                    JsxText(text) => {
                        let value_token = text.value_token()?;
                        if !is_meaningful_jsx_text(value_token.text()) {
                            // Text nodes can't have suppressions
                            f.context_mut()
                                .comments()
                                .mark_suppression_checked(text.syntax());
                            // It's safe to ignore the tokens here because JSX text tokens can't have comments (nor whitespace) attached.
                            f.state_mut().track_token(&value_token);

                            ElementLayout::NoChildren
                        } else {
                            ElementLayout::Default
                        }
                    }
                    JsxExpressionChild(expression) => match expression.expression() {
                        Some(JsTemplateExpression(_)) => ElementLayout::Template(expression),
                        _ => ElementLayout::Default,
                    },
                    _ => ElementLayout::Default,
                }
            }
            _ => ElementLayout::Default,
        };

        Ok(layout)
    }
}

#[derive(Debug, Clone)]
enum ElementLayout {
    /// Empty Tag with no children or contains no meaningful text.
    NoChildren,

    /// Prefer breaking the template if it is the only child of the element
    /// ```javascript
    /// <div>{`A Long Tempalte String That uses ${
    ///   5 + 4
    /// } that will eventually break across multiple lines ${(40 / 3) * 45}`}</div>;
    /// ```
    ///
    /// instead of
    ///
    /// ```javascript
    /// <div>
    ///   {`A Long Template String That uses ${
    ///     5 + 4
    ///   } that will eventually break across multiple lines ${(40 / 3) * 45}`}
    /// </div>;
    /// ```
    Template(JsxExpressionChild),

    /// Default layout used for all elements that have children and [ElementLayout::Template] does not apply.
    ///
    /// ```javascript
    ///<Element2>
    ///   Some more content
    ///   <Sub />
    ///   <Sub />
    ///   <Sub />
    /// </Element2>;
    /// ```
    Default,
}