summaryrefslogtreecommitdiff
path: root/crates/typst-html/src/css.rs
blob: 2b659188a2b56b8e86fd197747076bb445bef5c0 (plain) (blame)
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
//! Conversion from Typst data types into CSS data types.

use std::fmt::{self, Display};

use typst_library::layout::Length;
use typst_library::visualize::{Color, Hsl, LinearRgb, Oklab, Oklch, Rgb};
use typst_utils::Numeric;

pub fn length(length: Length) -> impl Display {
    typst_utils::display(move |f| match (length.abs.is_zero(), length.em.is_zero()) {
        (false, false) => {
            write!(f, "calc({}pt + {}em)", length.abs.to_pt(), length.em.get())
        }
        (true, false) => write!(f, "{}em", length.em.get()),
        (_, true) => write!(f, "{}pt", length.abs.to_pt()),
    })
}

pub fn color(color: Color) -> impl Display {
    typst_utils::display(move |f| match color {
        Color::Rgb(_) | Color::Cmyk(_) | Color::Luma(_) => rgb(f, color.to_rgb()),
        Color::Oklab(v) => oklab(f, v),
        Color::Oklch(v) => oklch(f, v),
        Color::LinearRgb(v) => linear_rgb(f, v),
        Color::Hsl(_) | Color::Hsv(_) => hsl(f, color.to_hsl()),
    })
}

fn oklab(f: &mut fmt::Formatter<'_>, v: Oklab) -> fmt::Result {
    write!(f, "oklab({} {} {}{})", percent(v.l), number(v.a), number(v.b), alpha(v.alpha))
}

fn oklch(f: &mut fmt::Formatter<'_>, v: Oklch) -> fmt::Result {
    write!(
        f,
        "oklch({} {} {}deg{})",
        percent(v.l),
        number(v.chroma),
        number(v.hue.into_degrees()),
        alpha(v.alpha)
    )
}

fn rgb(f: &mut fmt::Formatter<'_>, v: Rgb) -> fmt::Result {
    if let Some(v) = rgb_to_8_bit_lossless(v) {
        let (r, g, b, a) = v.into_components();
        write!(f, "#{r:02x}{g:02x}{b:02x}")?;
        if a != u8::MAX {
            write!(f, "{a:02x}")?;
        }
        Ok(())
    } else {
        write!(
            f,
            "rgb({} {} {}{})",
            percent(v.red),
            percent(v.green),
            percent(v.blue),
            alpha(v.alpha)
        )
    }
}

/// Converts an f32 RGBA color to its 8-bit representation if the result is
/// [very close](is_very_close) to the original.
fn rgb_to_8_bit_lossless(
    v: Rgb,
) -> Option<palette::rgb::Rgba<palette::encoding::Srgb, u8>> {
    let l = v.into_format::<u8, u8>();
    let h = l.into_format::<f32, f32>();
    (is_very_close(v.red, h.red)
        && is_very_close(v.blue, h.blue)
        && is_very_close(v.green, h.green)
        && is_very_close(v.alpha, h.alpha))
    .then_some(l)
}

fn linear_rgb(f: &mut fmt::Formatter<'_>, v: LinearRgb) -> fmt::Result {
    write!(
        f,
        "color(srgb-linear {} {} {}{})",
        percent(v.red),
        percent(v.green),
        percent(v.blue),
        alpha(v.alpha),
    )
}

fn hsl(f: &mut fmt::Formatter<'_>, v: Hsl) -> fmt::Result {
    write!(
        f,
        "hsl({}deg {} {}{})",
        number(v.hue.into_degrees()),
        percent(v.saturation),
        percent(v.lightness),
        alpha(v.alpha),
    )
}

/// Displays an alpha component if it not 1.
fn alpha(value: f32) -> impl Display {
    typst_utils::display(move |f| {
        if !is_very_close(value, 1.0) {
            write!(f, " / {}", percent(value))?;
        }
        Ok(())
    })
}

/// Displays a rounded percentage.
///
/// For a percentage, two significant digits after the comma gives us a
/// precision of 1/10_000, which is more than 12 bits (see `is_very_close`).
fn percent(ratio: f32) -> impl Display {
    typst_utils::display(move |f| {
        write!(f, "{}%", typst_utils::round_with_precision(ratio as f64 * 100.0, 2))
    })
}

/// Rounds a number for display.
///
/// For a number between 0 and 1, four significant digits give us a
/// precision of 1/10_000, which is more than 12 bits (see `is_very_close`).
fn number(value: f32) -> impl Display {
    typst_utils::round_with_precision(value as f64, 4)
}

/// Whether two component values are close enough that there is no
/// difference when encoding them with 12-bit. 12 bit is the highest
/// reasonable color bit depth found in the industry.
fn is_very_close(a: f32, b: f32) -> bool {
    const MAX_BIT_DEPTH: u32 = 12;
    const EPS: f32 = 0.5 / 2_i32.pow(MAX_BIT_DEPTH) as f32;
    (a - b).abs() < EPS
}