Skip to main content

sk_css/
snap.rs

1//! CSS Scroll Snap: `scroll-snap-type`, `scroll-snap-align`, `scroll-snap-stop`, `scroll-padding`
2//! and `scroll-margin`, carried to the renderer (`sk_tree::snap`) that applies them. Writing mode is
3//! always horizontal-tb, left to right: block is y, inline is x.
4
5use std::rc::Rc;
6
7use lightningcss::properties::custom::{Token, TokenList, TokenOrValue};
8use lightningcss::properties::Property;
9use lightningcss::values::length::LengthPercentageOrAuto;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct SnapType {
13    pub x: bool,
14    pub y: bool,
15    pub mandatory: bool,
16}
17
18impl SnapType {
19    pub const NONE: Self = Self {
20        x: false,
21        y: false,
22        mandatory: false,
23    };
24
25    pub fn snaps(self) -> bool {
26        self.x || self.y
27    }
28}
29
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum SnapAlign {
32    #[default]
33    None,
34    Start,
35    End,
36    Center,
37}
38
39/// A `scroll-padding` edge; a percentage is of the scrollport's size on that axis.
40#[derive(Clone, Copy, Debug, PartialEq)]
41pub enum ScrollInset {
42    Auto,
43    Length { px: f32, fraction: f32 },
44}
45
46impl ScrollInset {
47    pub fn resolve(self, basis: f32) -> f32 {
48        match self {
49            ScrollInset::Auto => 0.0,
50            ScrollInset::Length { px, fraction } => px + fraction * basis,
51        }
52    }
53}
54
55/// Top, right, bottom, left; `None` is an edge no declaration set.
56pub type Edges<T> = [Option<T>; 4];
57
58#[derive(Clone, Debug, Default, PartialEq)]
59pub struct SnapPatch {
60    pub snap_type: Option<SnapType>,
61    /// (x, y).
62    pub align: Option<(SnapAlign, SnapAlign)>,
63    pub stop_always: Option<bool>,
64    pub padding: Option<Rc<Edges<ScrollInset>>>,
65    pub margin: Option<Rc<Edges<f32>>>,
66}
67
68impl SnapPatch {
69    pub(crate) fn refine(&mut self, other: &Self) {
70        if other.snap_type.is_some() {
71            self.snap_type = other.snap_type;
72        }
73        if other.align.is_some() {
74            self.align = other.align;
75        }
76        if other.stop_always.is_some() {
77            self.stop_always = other.stop_always;
78        }
79        merge(&mut self.padding, &other.padding);
80        merge(&mut self.margin, &other.margin);
81    }
82
83    /// `scroll-padding` resolved against a scrollport of `width` × `height`: top, right, bottom, left.
84    pub fn padding_px(&self, width: f32, height: f32) -> [f32; 4] {
85        let edges = self.padding.as_deref().copied().unwrap_or_default();
86        let basis = [height, width, height, width];
87        std::array::from_fn(|i| edges[i].map_or(0.0, |e| e.resolve(basis[i]).max(0.0)))
88    }
89
90    pub fn margin_px(&self) -> [f32; 4] {
91        let edges = self.margin.as_deref().copied().unwrap_or_default();
92        edges.map(|e| e.unwrap_or(0.0))
93    }
94}
95
96fn merge<T: Copy>(mine: &mut Option<Rc<Edges<T>>>, theirs: &Option<Rc<Edges<T>>>) {
97    let Some(theirs) = theirs else { return };
98    let next = match mine.as_deref() {
99        None => **theirs,
100        Some(edges) => {
101            let mut edges = *edges;
102            for (e, t) in edges.iter_mut().zip(theirs.iter()) {
103                if t.is_some() {
104                    *e = *t;
105                }
106            }
107            edges
108        }
109    };
110    *mine = Some(Rc::new(next));
111}
112
113fn set_edges<T: Copy>(slot: &mut Option<Rc<Edges<T>>>, which: [bool; 4], value: T) {
114    let mut edges: Edges<T> = [None; 4];
115    for (e, on) in edges.iter_mut().zip(which) {
116        if on {
117            *e = Some(value);
118        }
119    }
120    merge(slot, &Some(Rc::new(edges)));
121}
122
123const TOP: [bool; 4] = [true, false, false, false];
124const RIGHT: [bool; 4] = [false, true, false, false];
125const BOTTOM: [bool; 4] = [false, false, true, false];
126const LEFT: [bool; 4] = [false, false, false, true];
127
128/// The keywords of a token list, or `None` when anything else is in it.
129fn keywords(value: &TokenList<'_>) -> Option<Vec<String>> {
130    let mut out = Vec::new();
131    for t in value.0.iter() {
132        match t {
133            TokenOrValue::Token(Token::WhiteSpace(_)) => {}
134            TokenOrValue::Token(Token::Ident(id)) => out.push(id.as_ref().to_ascii_lowercase()),
135            _ => return None,
136        }
137    }
138    Some(out)
139}
140
141/// `scroll-snap-type`, `scroll-snap-align` or `scroll-snap-stop`, which lightningcss leaves as tokens.
142pub(crate) fn apply_keywords(
143    name: &str,
144    value: &TokenList<'_>,
145    snap: &mut SnapPatch,
146    diagnostics: &mut Vec<String>,
147) {
148    let words = keywords(value).unwrap_or_default();
149    let words: Vec<&str> = words.iter().map(String::as_str).collect();
150    if let [w] = words.as_slice() {
151        match *w {
152            "inherit" => return,
153            "initial" | "unset" | "revert" | "revert-layer" => {
154                match name {
155                    "scroll-snap-type" => snap.snap_type = Some(SnapType::NONE),
156                    "scroll-snap-align" => snap.align = Some((SnapAlign::None, SnapAlign::None)),
157                    _ => snap.stop_always = Some(false),
158                }
159                return;
160            }
161            _ => {}
162        }
163    }
164    let ok = match name {
165        "scroll-snap-type" => snap_type(&words).map(|t| snap.snap_type = Some(t)),
166        "scroll-snap-align" => snap_align(&words).map(|a| snap.align = Some(a)),
167        _ => match words.as_slice() {
168            ["normal"] => Some(snap.stop_always = Some(false)),
169            ["always"] => Some(snap.stop_always = Some(true)),
170            _ => None,
171        },
172    };
173    if ok.is_none() {
174        let expected = match name {
175            "scroll-snap-type" => {
176                "`none`, or `x` | `y` | `block` | `inline` | `both` then optionally `mandatory` | `proximity`"
177            }
178            "scroll-snap-align" => "one or two of `none` | `start` | `end` | `center`",
179            _ => "`normal` | `always`",
180        };
181        crate::mapper::once(
182            diagnostics,
183            format!("`{name}` takes {expected} — the declaration was dropped"),
184        );
185    }
186}
187
188fn snap_type(words: &[&str]) -> Option<SnapType> {
189    let (axis, strictness) = match words {
190        ["none"] => return Some(SnapType::NONE),
191        [axis] => (*axis, "proximity"),
192        [axis, strictness] => (*axis, *strictness),
193        _ => return None,
194    };
195    let (x, y) = match axis {
196        "x" | "inline" => (true, false),
197        "y" | "block" => (false, true),
198        "both" => (true, true),
199        _ => return None,
200    };
201    let mandatory = match strictness {
202        "mandatory" => true,
203        "proximity" => false,
204        _ => return None,
205    };
206    Some(SnapType { x, y, mandatory })
207}
208
209fn snap_align(words: &[&str]) -> Option<(SnapAlign, SnapAlign)> {
210    let one = |w: &str| match w {
211        "none" => Some(SnapAlign::None),
212        "start" => Some(SnapAlign::Start),
213        "end" => Some(SnapAlign::End),
214        "center" => Some(SnapAlign::Center),
215        _ => None,
216    };
217    match words {
218        [both] => one(both).map(|a| (a, a)),
219        [block, inline] => Some((one(inline)?, one(block)?)),
220        _ => None,
221    }
222}
223
224fn inset(v: &LengthPercentageOrAuto) -> Option<ScrollInset> {
225    use gpui::{AbsoluteLength, DefiniteLength};
226    let LengthPercentageOrAuto::LengthPercentage(lp) = v else {
227        return Some(ScrollInset::Auto);
228    };
229    Some(match crate::mapper::lp_definite(lp)? {
230        DefiniteLength::Absolute(AbsoluteLength::Pixels(p)) => ScrollInset::Length {
231            px: f32::from(p),
232            fraction: 0.0,
233        },
234        DefiniteLength::Absolute(AbsoluteLength::Rems(r)) => ScrollInset::Length {
235            px: r.0 * crate::mapper::rem_basis(),
236            fraction: 0.0,
237        },
238        DefiniteLength::Fraction(f) => ScrollInset::Length {
239            px: 0.0,
240            fraction: f,
241        },
242        DefiniteLength::Calc { fraction, pixels } => ScrollInset::Length {
243            px: f32::from(pixels),
244            fraction,
245        },
246    })
247}
248
249fn margin(v: &LengthPercentageOrAuto, diagnostics: &mut Vec<String>) -> Option<f32> {
250    match inset(v) {
251        Some(ScrollInset::Length { px, fraction }) if fraction == 0.0 => Some(px),
252        _ => {
253            crate::mapper::once(
254                diagnostics,
255                "`scroll-margin` takes a length — `auto` and percentages are invalid, and the \
256                 declaration was dropped"
257                    .into(),
258            );
259            None
260        }
261    }
262}
263
264/// `scroll-padding*` and `scroll-margin*`, physical and logical.
265pub(crate) fn apply_box(p: &Property, snap: &mut SnapPatch, diagnostics: &mut Vec<String>) {
266    use Property::*;
267    let mut pad: Vec<([bool; 4], &LengthPercentageOrAuto)> = Vec::new();
268    let mut mar: Vec<([bool; 4], &LengthPercentageOrAuto)> = Vec::new();
269    match p {
270        ScrollPaddingTop(v) | ScrollPaddingBlockStart(v) => pad.push((TOP, v)),
271        ScrollPaddingBottom(v) | ScrollPaddingBlockEnd(v) => pad.push((BOTTOM, v)),
272        ScrollPaddingLeft(v) | ScrollPaddingInlineStart(v) => pad.push((LEFT, v)),
273        ScrollPaddingRight(v) | ScrollPaddingInlineEnd(v) => pad.push((RIGHT, v)),
274        ScrollPaddingBlock(v) => pad.extend([(TOP, &v.block_start), (BOTTOM, &v.block_end)]),
275        ScrollPaddingInline(v) => pad.extend([(LEFT, &v.inline_start), (RIGHT, &v.inline_end)]),
276        ScrollPadding(v) => pad.extend([
277            (TOP, &v.top),
278            (RIGHT, &v.right),
279            (BOTTOM, &v.bottom),
280            (LEFT, &v.left),
281        ]),
282        ScrollMarginTop(v) | ScrollMarginBlockStart(v) => mar.push((TOP, v)),
283        ScrollMarginBottom(v) | ScrollMarginBlockEnd(v) => mar.push((BOTTOM, v)),
284        ScrollMarginLeft(v) | ScrollMarginInlineStart(v) => mar.push((LEFT, v)),
285        ScrollMarginRight(v) | ScrollMarginInlineEnd(v) => mar.push((RIGHT, v)),
286        ScrollMarginBlock(v) => mar.extend([(TOP, &v.block_start), (BOTTOM, &v.block_end)]),
287        ScrollMarginInline(v) => mar.extend([(LEFT, &v.inline_start), (RIGHT, &v.inline_end)]),
288        ScrollMargin(v) => mar.extend([
289            (TOP, &v.top),
290            (RIGHT, &v.right),
291            (BOTTOM, &v.bottom),
292            (LEFT, &v.left),
293        ]),
294        _ => {}
295    }
296    for (which, v) in pad {
297        if let Some(i) = inset(v) {
298            set_edges(&mut snap.padding, which, i);
299        }
300    }
301    for (which, v) in mar {
302        if let Some(m) = margin(v, diagnostics) {
303            set_edges(&mut snap.margin, which, m);
304        }
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::parse_inline_style;
312
313    fn snap(body: &str) -> (SnapPatch, Vec<String>) {
314        let mut d = Vec::new();
315        let s = parse_inline_style(body, &mut d);
316        (s.extras.snap, d)
317    }
318
319    #[test]
320    fn snap_type_reads_axis_and_strictness() {
321        let t = |body: &str| snap(body).0.snap_type;
322        let mk = |x, y, mandatory| Some(SnapType { x, y, mandatory });
323        assert_eq!(t("scroll-snap-type: x mandatory"), mk(true, false, true));
324        assert_eq!(t("scroll-snap-type: block"), mk(false, true, false));
325        assert_eq!(t("scroll-snap-type: both proximity"), mk(true, true, false));
326        assert_eq!(
327            t("scroll-snap-type: inline mandatory"),
328            mk(true, false, true)
329        );
330        assert_eq!(t("scroll-snap-type: none"), Some(SnapType::NONE));
331        let (s, d) = snap("scroll-snap-type: x sideways");
332        assert_eq!((s.snap_type, d.len()), (None, 1));
333    }
334
335    #[test]
336    fn the_two_value_align_is_block_then_inline() {
337        let a = |body: &str| snap(body).0.align;
338        assert_eq!(
339            a("scroll-snap-align: center"),
340            Some((SnapAlign::Center, SnapAlign::Center))
341        );
342        assert_eq!(
343            a("scroll-snap-align: start end"),
344            Some((SnapAlign::End, SnapAlign::Start))
345        );
346        assert_eq!(snap("scroll-snap-align: start end center").1.len(), 1);
347        assert_eq!(snap("scroll-snap-stop: always").0.stop_always, Some(true));
348    }
349
350    #[test]
351    fn padding_and_margin_merge_per_edge_and_logical_maps_to_physical() {
352        let (s, d) = snap(
353            "scroll-padding: 10px; scroll-padding-inline: 5%; scroll-padding-block-end: auto; \
354             scroll-margin: 4px; scroll-margin-block-start: 1rem",
355        );
356        assert!(d.is_empty(), "{d:?}");
357        assert_eq!(s.padding_px(400.0, 100.0), [10.0, 20.0, 0.0, 20.0]);
358        assert_eq!(s.margin_px(), [16.0, 4.0, 4.0, 4.0]);
359        let (s, d) = snap("scroll-margin: 10%");
360        assert_eq!((s.margin, d.len()), (None, 1));
361    }
362
363    #[test]
364    fn a_later_rule_overrides_one_edge_and_keeps_the_rest() {
365        let mut base = snap("scroll-padding: 8px").0;
366        base.refine(&snap("scroll-padding-top: 20px").0);
367        assert_eq!(base.padding_px(100.0, 100.0), [20.0, 8.0, 8.0, 8.0]);
368    }
369}