Skip to main content

glory_html/
styles.rs

1use glory_style::*;
2use std::fmt::Write;
3
4fn length(value: Length) -> String {
5    match value {
6        Length::Auto => "auto".into(),
7        Length::Px(value) => format!("{value}px"),
8        Length::Percent(value) => format!("{value}%"),
9        Length::Ch(value) => format!("{value}ch"),
10    }
11}
12fn limit(value: Limit) -> String {
13    match value {
14        Limit::None => "none".into(),
15        Limit::Px(value) => format!("{value}px"),
16        Limit::Percent(value) => format!("{value}%"),
17    }
18}
19fn color(value: Color) -> String {
20    format!(
21        "#{:02x}{:02x}{:02x}{:02x}",
22        value.0, value.1, value.2, value.3
23    )
24}
25// CSS strings also occur inside a <style> raw-text body. Hex-escape '<'
26// regardless of quoting, so a face name cannot terminate that HTML element.
27fn family(value: &Family) -> String {
28    let Family::Named(name) = value else {
29        return match value {
30            Family::Serif => "serif",
31            Family::Sans => "sans-serif",
32            Family::Mono => "monospace",
33            Family::System => "system-ui",
34            Family::Cursive => "cursive",
35            Family::Fantasy => "fantasy",
36            Family::Named(_) => unreachable!(),
37        }
38        .into();
39    };
40    let mut out = String::from("\"");
41    for c in name.chars() {
42        match c {
43            '\0' => out.push('\u{fffd}'),
44            '"' | '\\' => {
45                out.push('\\');
46                out.push(c);
47            }
48            c if c == '<' || c.is_control() => {
49                write!(out, "\\{:x} ", c as u32).expect("string write");
50            }
51            c => out.push(c),
52        }
53    }
54    out.push('"');
55    out
56}
57pub fn style(style: &Style) -> String {
58    let mut out = String::new();
59    let mut declaration = |name: &str, value: String| {
60        write!(out, "{name}:{value};").expect("string write");
61    };
62    if let Some(value) = style.pointer_events {
63        declaration(
64            "pointer-events",
65            match value {
66                PointerEvents::Auto => "auto",
67                PointerEvents::None => "none",
68            }
69            .into(),
70        );
71    }
72    for (name, value) in [
73        ("grid-template-columns", style.grid_columns.as_ref()),
74        ("grid-template-rows", style.grid_rows.as_ref()),
75    ] {
76        if let Some(value) = value {
77            declaration(
78                name,
79                match value {
80                    GridTracks::None => "none".into(),
81                    GridTracks::Tracks(tracks) => tracks
82                        .iter()
83                        .map(|track| match track {
84                            GridTrack::Auto => "auto".into(),
85                            GridTrack::Px(value) => format!("{value}px"),
86                            GridTrack::Percent(value) => format!("{value}%"),
87                            GridTrack::Fr(value) => format!("{value}fr"),
88                        })
89                        .collect::<Vec<_>>()
90                        .join(" "),
91                },
92            );
93        }
94    }
95    for (name, value) in [
96        ("grid-column", style.grid_column),
97        ("grid-row", style.grid_row),
98    ] {
99        if let Some(value) = value {
100            declaration(
101                name,
102                match value {
103                    GridPlacement::Auto => "auto".into(),
104                    GridPlacement::Span(span) => format!("span {span}"),
105                    GridPlacement::At { start, span } => format!("{start} / span {span}"),
106                },
107            );
108        }
109    }
110    if let Some(value) = style.object_fit {
111        declaration(
112            "object-fit",
113            match value {
114                ObjectFit::Fill => "fill",
115                ObjectFit::Contain => "contain",
116                ObjectFit::Cover => "cover",
117                ObjectFit::None => "none",
118                ObjectFit::ScaleDown => "scale-down",
119            }
120            .into(),
121        );
122    }
123    if let Some(value) = style.aspect_ratio {
124        declaration(
125            "aspect-ratio",
126            match value {
127                AspectRatio::Auto => "auto".into(),
128                AspectRatio::Ratio(value) => format!("{value}"),
129            },
130        );
131    }
132    if let Some(value) = style.flex_wrap {
133        declaration(
134            "flex-wrap",
135            match value {
136                FlexWrap::NoWrap => "nowrap",
137                FlexWrap::Wrap => "wrap",
138            }
139            .into(),
140        );
141    }
142    for (name, value) in [
143        ("width", style.width),
144        ("height", style.height),
145        ("min-width", style.min_width),
146        ("min-height", style.min_height),
147    ] {
148        if let Some(value) = value {
149            declaration(name, length(value));
150        }
151    }
152    for (name, value) in [
153        ("max-width", style.max_width),
154        ("max-height", style.max_height),
155    ] {
156        if let Some(value) = value {
157            declaration(name, limit(value));
158        }
159    }
160    for (name, value) in [
161        ("top", style.top),
162        ("left", style.left),
163        ("right", style.right),
164        ("bottom", style.bottom),
165    ] {
166        if let Some(value) = value {
167            declaration(name, length(value));
168        }
169    }
170    if let Some(value) = style.position {
171        declaration(
172            "position",
173            match value {
174                Position::Static => "static",
175                Position::Relative => "relative",
176                Position::Absolute => "absolute",
177                Position::Sticky => "sticky",
178                Position::Fixed => "fixed",
179            }
180            .into(),
181        );
182    }
183    if let Some(value) = style.display {
184        declaration(
185            "display",
186            match value {
187                Display::Block => "block",
188                Display::Flex => "flex",
189                Display::InlineFlex => "inline-flex",
190                Display::Grid => "grid",
191                Display::None => "none",
192            }
193            .into(),
194        );
195    }
196    if let Some(value) = style.flex_direction {
197        declaration(
198            "flex-direction",
199            match value {
200                FlexDirection::Row => "row",
201                FlexDirection::Column => "column",
202            }
203            .into(),
204        );
205    }
206    for (name, value) in [
207        ("gap", style.gap),
208        ("font-size", style.font_size),
209        ("line-height", style.line_height),
210        ("border-radius", style.radius),
211    ] {
212        if let Some(value) = value {
213            declaration(name, format!("{value}px"));
214        }
215    }
216    for (name, value) in [
217        ("padding", style.padding),
218        ("margin", style.margin),
219        ("border-width", style.border_width),
220    ] {
221        if let Some(value) = value {
222            declaration(
223                name,
224                format!(
225                    "{}px {}px {}px {}px",
226                    value.top, value.right, value.bottom, value.left
227                ),
228            );
229        }
230    }
231    for (name, value) in [
232        ("flex-grow", style.grow),
233        ("flex-shrink", style.shrink),
234        ("font-weight", style.font_weight),
235        ("opacity", style.opacity),
236    ] {
237        if let Some(value) = value {
238            declaration(name, value.to_string());
239        }
240    }
241    for (name, value) in [
242        ("color", style.color),
243        ("background-color", style.background),
244        ("border-color", style.border_color),
245    ] {
246        if let Some(value) = value {
247            declaration(name, color(value));
248        }
249    }
250    if let Some(value) = &style.font_family {
251        declaration(
252            "font-family",
253            value.iter().map(family).collect::<Vec<_>>().join(","),
254        );
255    }
256    if let Some(value) = style.field_sizing {
257        declaration(
258            "field-sizing",
259            match value {
260                FieldSizing::Fixed => "fixed",
261                FieldSizing::Content => "content",
262            }
263            .into(),
264        );
265    }
266    if let Some(value) = style.text_overflow {
267        declaration(
268            "text-overflow",
269            match value {
270                TextOverflow::Clip => "clip",
271                TextOverflow::Ellipsis => "ellipsis",
272            }
273            .into(),
274        );
275    }
276    if let Some(value) = style.white_space {
277        declaration(
278            "white-space",
279            match value {
280                WhiteSpace::Normal => "normal",
281                WhiteSpace::NoWrap => "nowrap",
282                WhiteSpace::Pre => "pre",
283                WhiteSpace::PreWrap => "pre-wrap",
284            }
285            .into(),
286        );
287    }
288    if let Some(value) = style.border_style {
289        declaration(
290            "border-style",
291            match value {
292                BorderStyle::None => "none",
293                BorderStyle::Solid => "solid",
294            }
295            .into(),
296        );
297    }
298    for (name, value) in [
299        ("overflow-x", style.overflow_x),
300        ("overflow-y", style.overflow_y),
301    ] {
302        if let Some(value) = value {
303            declaration(
304                name,
305                match value {
306                    Overflow::Visible => "visible",
307                    Overflow::Hidden => "hidden",
308                    Overflow::Clip => "clip",
309                    Overflow::Auto => "auto",
310                    Overflow::Scroll => "scroll",
311                }
312                .into(),
313            );
314        }
315    }
316    if let Some(value) = style.align {
317        declaration(
318            "align-items",
319            match value {
320                Align::Start => "flex-start",
321                Align::End => "flex-end",
322                Align::Center => "center",
323                Align::Stretch => "stretch",
324            }
325            .into(),
326        );
327    }
328    if let Some(value) = style.scroll_anchor {
329        declaration(
330            "overflow-anchor",
331            if value { "auto" } else { "none" }.into(),
332        );
333    }
334    if let Some(value) = style.justify {
335        declaration(
336            "justify-content",
337            match value {
338                Justify::Start => "flex-start",
339                Justify::End => "flex-end",
340                Justify::Center => "center",
341                Justify::Between => "space-between",
342                Justify::Around => "space-around",
343                Justify::Evenly => "space-evenly",
344            }
345            .into(),
346        );
347    }
348    if let Some(shadow) = style.box_shadow {
349        declaration(
350            "box-shadow",
351            match shadow {
352                BoxShadow::None => "none".into(),
353                BoxShadow::Outset(shadow) => format!(
354                    "{}px {}px {}px {}px {}",
355                    shadow.x,
356                    shadow.y,
357                    shadow.blur,
358                    shadow.spread,
359                    color(shadow.color)
360                ),
361            },
362        );
363    }
364    out
365}