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