Skip to main content

sk_css/
corner_shape.rs

1//! `corner-shape` and its longhands and side shorthands (css-borders-4 §3.7–3.8). The flow-relative
2//! names map as horizontal-tb, left-to-right.
3
4use gpui::CornerShape;
5use lightningcss::traits::Parse;
6
7/// Corner indices in `corner-shape` value order, matching the `RadiusInherit` bit order.
8const TL: usize = 0;
9const TR: usize = 1;
10const BR: usize = 2;
11const BL: usize = 3;
12
13/// For each number of values a property takes, the corners each value sets.
14type Layout = &'static [&'static [&'static [usize]]];
15
16fn layout(name: &str) -> Option<Layout> {
17    const ALL: Layout = &[
18        &[&[TL, TR, BR, BL]],
19        &[&[TL, BR], &[TR, BL]],
20        &[&[TL], &[TR, BL], &[BR]],
21        &[&[TL], &[TR], &[BR], &[BL]],
22    ];
23    Some(match name.to_ascii_lowercase().as_str() {
24        "corner-shape" => ALL,
25        "corner-top-left-shape" | "corner-start-start-shape" => &[&[&[TL]]],
26        "corner-top-right-shape" | "corner-start-end-shape" => &[&[&[TR]]],
27        "corner-bottom-right-shape" | "corner-end-end-shape" => &[&[&[BR]]],
28        "corner-bottom-left-shape" | "corner-end-start-shape" => &[&[&[BL]]],
29        "corner-top-shape" | "corner-block-start-shape" => &[&[&[TL, TR]], &[&[TL], &[TR]]],
30        "corner-bottom-shape" | "corner-block-end-shape" => &[&[&[BL, BR]], &[&[BL], &[BR]]],
31        "corner-left-shape" | "corner-inline-start-shape" => &[&[&[TL, BL]], &[&[TL], &[BL]]],
32        "corner-right-shape" | "corner-inline-end-shape" => &[&[&[TR, BR]], &[&[TR], &[BR]]],
33        _ => return None,
34    })
35}
36
37pub(crate) fn is_property(name: &str) -> bool {
38    layout(name).is_some()
39}
40
41/// The RadiusInherit bit of a corner's shape, above the four radius bits.
42pub(crate) fn inherit_bit(corner: usize) -> u8 {
43    1 << (4 + corner)
44}
45
46#[derive(Debug, PartialEq)]
47pub(crate) enum Declared {
48    Shapes([Option<CornerShape>; 4]),
49    /// The `RadiusInherit` bits of the corners that take the parent's shape.
50    Inherit(u8),
51}
52
53pub(crate) fn parse(name: &str, value: &str) -> Result<Declared, String> {
54    let layout = layout(name).ok_or_else(|| format!("`{name}` is not a corner shape property"))?;
55    let corners = || layout[0].iter().flat_map(|c| c.iter().copied());
56    let value = value.trim();
57    match value.to_ascii_lowercase().as_str() {
58        "inherit" => return Ok(Declared::Inherit(corners().map(inherit_bit).sum())),
59        "initial" | "unset" | "revert" | "revert-layer" => {
60            let mut shapes = [None; 4];
61            corners().for_each(|c| shapes[c] = Some(CornerShape::ROUND));
62            return Ok(Declared::Shapes(shapes));
63        }
64        _ => {}
65    }
66    let values = split(value)
67        .into_iter()
68        .map(shape)
69        .collect::<Result<Vec<_>, _>>()?;
70    let targets = values
71        .len()
72        .checked_sub(1)
73        .and_then(|i| layout.get(i))
74        .ok_or_else(|| {
75            format!(
76                "`{name}` takes 1 to {} values, got {}",
77                layout.len(),
78                values.len()
79            )
80        })?;
81    let mut shapes = [None; 4];
82    for (value, corners) in values.into_iter().zip(targets.iter()) {
83        corners.iter().for_each(|&c| shapes[c] = Some(value));
84    }
85    Ok(Declared::Shapes(shapes))
86}
87
88/// The top-level space-separated parts, keeping each function call whole.
89fn split(value: &str) -> Vec<&str> {
90    let (mut parts, mut depth, mut start) = (Vec::new(), 0usize, None);
91    for (i, ch) in value.char_indices() {
92        match ch {
93            '(' => depth += 1,
94            ')' => depth = depth.saturating_sub(1),
95            c if c.is_whitespace() && depth == 0 => {
96                if let Some(s) = start.take() {
97                    parts.push(&value[s..i]);
98                }
99                continue;
100            }
101            _ => {}
102        }
103        start.get_or_insert(i);
104    }
105    if let Some(s) = start {
106        parts.push(&value[s..]);
107    }
108    parts
109}
110
111fn shape(part: &str) -> Result<CornerShape, String> {
112    let lower = part.to_ascii_lowercase();
113    Ok(match lower.as_str() {
114        "round" => CornerShape::ROUND,
115        "scoop" => CornerShape::SCOOP,
116        "bevel" => CornerShape::BEVEL,
117        "notch" => CornerShape::NOTCH,
118        "square" => CornerShape::SQUARE,
119        "squircle" => CornerShape::SQUIRCLE,
120        _ => {
121            let argument = lower
122                .strip_prefix("superellipse(")
123                .and_then(|rest| rest.strip_suffix(')'))
124                .map(str::trim)
125                .ok_or_else(|| {
126                    format!(
127                        "`{part}` is not a corner shape: use `round`, `scoop`, `bevel`, `notch`, \
128                         `square`, `squircle` or `superellipse(<number>)`"
129                    )
130                })?;
131            match argument {
132                "infinity" => CornerShape::SQUARE,
133                "-infinity" => CornerShape::NOTCH,
134                text => match f32::parse_string(text) {
135                    Ok(k) if !k.is_nan() => CornerShape(k),
136                    _ => {
137                        return Err(format!(
138                            "`{part}` needs a number, `infinity` or `-infinity` inside \
139                             `superellipse()`"
140                        ))
141                    }
142                },
143            }
144        }
145    })
146}
147
148/// A shape as CSS: its keyword when it has one.
149pub fn to_css(shape: CornerShape) -> String {
150    let k = shape.0;
151    match k {
152        _ if k == 1. => "round".into(),
153        _ if k == -1. => "scoop".into(),
154        _ if k == 0. => "bevel".into(),
155        _ if k == 2. => "squircle".into(),
156        f32::INFINITY => "square".into(),
157        f32::NEG_INFINITY => "notch".into(),
158        _ => format!("superellipse({k})"),
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    fn shapes(name: &str, value: &str) -> [Option<f32>; 4] {
167        match parse(name, value) {
168            Ok(Declared::Shapes(s)) => s.map(|s| s.map(|s| s.0)),
169            other => panic!("{name}: {value} gave {other:?}"),
170        }
171    }
172
173    const INF: f32 = f32::INFINITY;
174
175    #[test]
176    fn keywords_and_superellipse_parse() {
177        let one = |v: &str| shapes("corner-top-left-shape", v)[0].unwrap();
178        assert_eq!(one("round"), 1.);
179        assert_eq!(one("SCOOP"), -1.);
180        assert_eq!(one("bevel"), 0.);
181        assert_eq!(one("notch"), -INF);
182        assert_eq!(one("square"), INF);
183        assert_eq!(one("squircle"), 2.);
184        assert_eq!(one("superellipse(0.5)"), 0.5);
185        assert_eq!(one("superellipse(-3)"), -3.);
186        assert_eq!(one("Superellipse( infinity )"), INF);
187        assert_eq!(one("superellipse(-infinity)"), -INF);
188        assert_eq!(one("superellipse(calc(1 + 2))"), 3.);
189    }
190
191    #[test]
192    fn values_expand_like_border_radius() {
193        let (r, s, b) = (Some(1.), Some(INF), Some(0.));
194        assert_eq!(shapes("corner-shape", "round"), [r; 4]);
195        assert_eq!(shapes("corner-shape", "round square"), [r, s, r, s]);
196        assert_eq!(shapes("corner-shape", "round square bevel"), [r, s, b, s]);
197        assert_eq!(
198            shapes("corner-shape", "round square bevel notch"),
199            [r, s, b, Some(-INF)]
200        );
201    }
202
203    #[test]
204    fn side_and_logical_names_set_their_corners() {
205        let (r, s) = (Some(1.), Some(INF));
206        assert_eq!(
207            shapes("corner-top-shape", "round square"),
208            [r, s, None, None]
209        );
210        assert_eq!(
211            shapes("corner-bottom-shape", "round square"),
212            [None, None, s, r]
213        );
214        assert_eq!(
215            shapes("corner-left-shape", "round square"),
216            [r, None, None, s]
217        );
218        assert_eq!(shapes("corner-right-shape", "square"), [None, s, s, None]);
219        assert_eq!(
220            shapes("corner-block-start-shape", "round square"),
221            [r, s, None, None]
222        );
223        assert_eq!(
224            shapes("corner-inline-end-shape", "round square"),
225            [None, r, s, None]
226        );
227        assert_eq!(
228            shapes("corner-start-end-shape", "square"),
229            [None, s, None, None]
230        );
231        assert_eq!(
232            shapes("corner-end-start-shape", "square"),
233            [None, None, None, s]
234        );
235        assert_eq!(
236            shapes("corner-end-end-shape", "square"),
237            [None, None, s, None]
238        );
239    }
240
241    #[test]
242    fn css_wide_keywords() {
243        assert_eq!(
244            shapes("corner-top-shape", "initial"),
245            [Some(1.), Some(1.), None, None]
246        );
247        assert_eq!(shapes("corner-shape", "unset"), [Some(1.); 4]);
248        assert_eq!(
249            parse("corner-right-shape", "inherit"),
250            Ok(Declared::Inherit(inherit_bit(TR) | inherit_bit(BR)))
251        );
252    }
253
254    #[test]
255    fn invalid_values_are_errors() {
256        for (name, value) in [
257            ("corner-shape", "round round round round round"),
258            ("corner-top-shape", "round square bevel"),
259            ("corner-top-left-shape", "round square"),
260            ("corner-shape", "rounded"),
261            ("corner-shape", "superellipse()"),
262            ("corner-shape", "superellipse(1px)"),
263            ("corner-shape", "superellipse(1, 2)"),
264            ("corner-shape", "8px"),
265            ("corner-shape", ""),
266        ] {
267            assert!(parse(name, value).is_err(), "{name}: {value}");
268        }
269    }
270
271    fn mapped(body: &str) -> (gpui::StyleRefinement, crate::Extras, Vec<String>) {
272        let mut d = Vec::new();
273        let (r, _, x) = crate::mapper::parse_inline_full(body, &mut d);
274        (r, x, d)
275    }
276
277    #[test]
278    fn the_mapper_sets_the_shapes_and_drops_an_invalid_value() {
279        let (r, _, d) = mapped("corner-shape: bevel; corner-bottom-right-shape: superellipse(3)");
280        assert!(d.is_empty(), "{d:?}");
281        let s = r.vn_corner_shapes;
282        assert_eq!(s.top_left, Some(CornerShape::BEVEL));
283        assert_eq!(s.bottom_right, Some(CornerShape(3.)));
284
285        let (r, _, d) = mapped("corner-shape: bevel; corner-shape: wobbly");
286        assert_eq!(r.vn_corner_shapes.top_left, Some(CornerShape::BEVEL));
287        assert_eq!(d.len(), 1);
288    }
289
290    #[test]
291    fn var_is_substituted() {
292        let mut d = Vec::new();
293        let vars = crate::vars::resolve(
294            &std::rc::Rc::new(crate::Vars::default()),
295            &[&(
296                "--s".to_string(),
297                "scoop superellipse(-infinity)".to_string(),
298            )],
299            &crate::Env::default(),
300            &mut d,
301        );
302        let (mut r, mut x) = (gpui::StyleRefinement::default(), crate::Extras::default());
303        crate::mapper::apply_dynamic(
304            "corner-top-shape",
305            "var(--s)",
306            &vars,
307            &crate::Env::default(),
308            &mut r,
309            &mut x,
310            &mut d,
311        );
312        assert!(d.is_empty(), "{d:?}");
313        assert_eq!(r.vn_corner_shapes.top_left, Some(CornerShape::SCOOP));
314        assert_eq!(r.vn_corner_shapes.top_right, Some(CornerShape::NOTCH));
315    }
316
317    #[test]
318    fn inherit_takes_the_parents_shape_and_a_later_value_cancels_it() {
319        let (r, _, _) = mapped("corner-shape: squircle bevel");
320        let parent = crate::InheritedRadii::of(&r);
321        let child = |body: &str| {
322            let (r, extras, d) = mapped(body);
323            assert!(d.is_empty(), "{d:?}");
324            let mut states = crate::ComputedStates {
325                base: std::rc::Rc::new(r),
326                extras,
327                ..Default::default()
328            };
329            crate::resolve_inherited_radii(&mut states, parent);
330            states.base.vn_corner_shapes.clone()
331        };
332        let s = child("corner-right-shape: inherit");
333        assert_eq!(s.top_right, Some(CornerShape::BEVEL));
334        assert_eq!(s.bottom_right, Some(CornerShape::SQUIRCLE));
335        assert_eq!(s.top_left, None);
336        let s = child("corner-shape: inherit; corner-top-left-shape: notch");
337        assert_eq!(s.top_left, Some(CornerShape::NOTCH));
338        assert_eq!(s.bottom_left, Some(CornerShape::BEVEL));
339    }
340
341    fn transitioned(from: &str, to: &str, at_ms: u64) -> gpui::CornersRefinement<CornerShape> {
342        use std::time::{Duration, Instant};
343        let states = |shape: &str| {
344            let mut d = Vec::new();
345            let (r, t) = crate::parse_inline_with_transitions(
346                &format!("corner-shape: {shape}; transition: corner-shape 1s linear"),
347                &mut d,
348            );
349            assert!(d.is_empty(), "{d:?}");
350            crate::ComputedStates {
351                base: std::rc::Rc::new(r),
352                transitions: std::rc::Rc::new(t),
353                ..Default::default()
354            }
355        };
356        let mut a = crate::Animator::new();
357        let now = Instant::now();
358        a.on_computed(1, Some(&states(from)), &states(to), now);
359        a.overlay(
360            1,
361            &gpui::StyleRefinement::default(),
362            now + Duration::from_millis(at_ms),
363        )
364        .expect("a running transition")
365        .vn_corner_shapes
366    }
367
368    #[test]
369    fn transitions_move_the_half_corner() {
370        let s = transitioned("bevel", "square", 500);
371        let mid = CornerShape::BEVEL.interpolate(CornerShape::SQUARE, 0.5);
372        assert!((mid.half_corner() - 0.75).abs() < 1e-4);
373        assert_eq!([s.top_left, s.bottom_left], [Some(mid); 2]);
374        let s = transitioned("round", "scoop", 500);
375        assert!(s.top_right.is_some_and(|k| k.0.abs() < 1e-3), "{s:?}");
376        let s = transitioned("superellipse(infinity)", "round", 250);
377        assert!(
378            s.top_left.is_some_and(|k| k.0.is_finite() && k.0 > 1.),
379            "{s:?}"
380        );
381    }
382
383    #[test]
384    fn serialization_round_trips() {
385        for v in [
386            "round",
387            "notch",
388            "square",
389            "superellipse(0.5)",
390            "superellipse(-4)",
391        ] {
392            let parsed = shapes("corner-top-left-shape", v)[0].unwrap();
393            assert_eq!(to_css(CornerShape(parsed)), v);
394        }
395    }
396}