layoutcss_parser/
media_query.rs

1use std::cmp::Ordering;
2
3#[derive(Debug, Hash, PartialEq, Eq, Clone)]
4pub enum MediaQuery {
5    SuperiorTo(usize, String),
6    InferiorOrEqualTo(usize),
7}
8
9impl MediaQuery {
10    pub fn get_breakpoint(&self) -> &usize {
11        match self {
12            Self::SuperiorTo(breakpoint, _) => breakpoint,
13            Self::InferiorOrEqualTo(breakpoint) => breakpoint,
14        }
15    }
16}
17
18impl PartialOrd for MediaQuery {
19    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
20        Some(self.cmp(other)) // Use the `Ord` comparison logic for `PartialOrd`
21    }
22}
23
24impl Ord for MediaQuery {
25    fn cmp(&self, other: &Self) -> Ordering {
26        match (self, other) {
27            // `SuperiorTo` is greater than `InferiorOrEqualTo`
28            (MediaQuery::SuperiorTo(_, _), MediaQuery::InferiorOrEqualTo(_)) => Ordering::Greater,
29            (MediaQuery::InferiorOrEqualTo(_), MediaQuery::SuperiorTo(_, _)) => Ordering::Less,
30
31            //I think in the next two cases it's the same thinkg so we can say in every other case,
32            //compare
33
34            // If both are `SuperiorTo`, compare by usize, so if the same return Equals
35            (MediaQuery::SuperiorTo(a, _), MediaQuery::SuperiorTo(b, _)) => b.cmp(a),
36
37            // If both are `InferiorOrEqualTo`, compare by usize, so if the same return Equals
38            (MediaQuery::InferiorOrEqualTo(a), MediaQuery::InferiorOrEqualTo(b)) => b.cmp(a),
39        }
40    }
41}
42
43pub fn extract_breakpoint(input: &str) -> Option<usize> {
44    // Wrong pattern, nothing to extract
45    if input.len() <= "layoutpx".len() {
46        return None;
47    }
48    let number_part = &input[6..input.len() - 2]; // Slice out the number part
49    return number_part.parse::<usize>().ok();
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn extract_breakpoint_with_nothing_after_at() {
58        let bp = extract_breakpoint("layout@");
59        assert_eq!(bp, None)
60    }
61
62    #[test]
63    fn extract_breakpoint_without_at_cool() {
64        let bp = extract_breakpoint("layout600px");
65        assert_eq!(bp, Some(600))
66    }
67
68    #[test]
69    fn extract_breakpoint_from_correct_mq() {
70        let bp = extract_breakpoint("layout@600px");
71        assert_eq!(bp, None)
72    }
73}