ori-core 0.1.0-alpha.1

Core library for Ori, a declarative UI framework for Rust.
Documentation
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::{
    cmp::Ordering,
    fmt::Display,
    ops::{Add, AddAssign},
};

use smallvec::SmallVec;
use smol_str::SmolStr;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StyleSpecificity {
    pub class: u16,
    pub tag: u16,
}

impl StyleSpecificity {
    pub const MAX: Self = Self::new(u16::MAX, u16::MAX);
    pub const INLINE: Self = Self::MAX;

    pub const fn new(class: u16, tag: u16) -> Self {
        Self { class, tag }
    }
}

impl PartialOrd for StyleSpecificity {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match self.class.partial_cmp(&other.class) {
            Some(Ordering::Equal) => {}
            ord => return ord,
        }
        self.tag.partial_cmp(&other.tag)
    }
}

impl Ord for StyleSpecificity {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.class.cmp(&other.class) {
            Ordering::Equal => {}
            ord => return ord,
        }
        self.tag.cmp(&other.tag)
    }
}

impl Add for StyleSpecificity {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            class: self.class + other.class,
            tag: self.tag + other.tag,
        }
    }
}

impl AddAssign for StyleSpecificity {
    fn add_assign(&mut self, other: Self) {
        self.class += other.class;
        self.tag += other.tag;
    }
}

/// A [`Style`](super::Style) selector.
///
/// A selector is a list of classes and an optional element.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct StyleSelectors {
    /// The element name.
    pub selectors: SmallVec<[StyleSelector; 1]>,
}

impl StyleSelectors {
    pub const fn new() -> Self {
        Self {
            selectors: SmallVec::new_const(),
        }
    }

    pub fn len(&self) -> usize {
        self.selectors.len()
    }

    pub fn is_empty(&self) -> bool {
        self.selectors.is_empty()
    }

    pub fn push(&mut self, selector: StyleSelector) {
        self.selectors.push(selector);
    }

    pub fn with(mut self, selector: StyleSelector) -> Self {
        self.push(selector);
        self
    }

    pub fn specificity(&self) -> StyleSpecificity {
        let mut specificity = StyleSpecificity::default();

        for selector in self.selectors.iter() {
            specificity += selector.specificity();
        }

        specificity
    }

    /// Returns true if `other` is a subset of `self`.
    pub fn select(&self, other: &Self) -> bool {
        if other.len() > self.len() {
            return false;
        }

        for (a, b) in self.iter().rev().zip(other.iter().rev()) {
            if !a.select(b) {
                return false;
            }
        }

        true
    }

    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &StyleSelector> {
        self.selectors.iter()
    }
}

impl IntoIterator for StyleSelectors {
    type Item = StyleSelector;
    type IntoIter = smallvec::IntoIter<[Self::Item; 1]>;

    fn into_iter(self) -> Self::IntoIter {
        self.selectors.into_iter()
    }
}

impl<'a> IntoIterator for &'a StyleSelectors {
    type Item = &'a StyleSelector;
    type IntoIter = std::slice::Iter<'a, StyleSelector>;

    fn into_iter(self) -> Self::IntoIter {
        self.selectors.iter()
    }
}

impl FromIterator<StyleSelector> for StyleSelectors {
    fn from_iter<T: IntoIterator<Item = StyleSelector>>(iter: T) -> Self {
        Self {
            selectors: iter.into_iter().collect(),
        }
    }
}

impl Display for StyleSelectors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, selector) in self.selectors.iter().enumerate() {
            if i > 0 {
                write!(f, " ")?;
            }
            write!(f, "{}", selector)?;
        }

        Ok(())
    }
}

pub type StyleElement = SmolStr;
pub type StyleClass = SmolStr;

#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct StyleSelector {
    pub element: Option<StyleElement>,
    pub classes: StyleClasses,
    pub states: StyleStates,
}

impl StyleSelector {
    pub fn new(element: Option<StyleElement>, classes: StyleClasses, states: StyleStates) -> Self {
        Self {
            element,
            classes,
            states,
        }
    }

    pub fn specificity(&self) -> StyleSpecificity {
        StyleSpecificity {
            class: self.classes.len() as u16 + self.states.len() as u16,
            tag: self.element.is_some() as u16,
        }
    }

    pub fn select(&self, other: &Self) -> bool {
        if other.element.is_some() && self.element != other.element {
            return false;
        }

        self.classes.select(&other.classes) && self.states.select(&other.states)
    }
}

impl Display for StyleSelector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(element) = &self.element {
            write!(f, "{}", element)?;
        } else {
            write!(f, "*")?;
        }

        write!(f, "{}", self.classes)?;
        write!(f, "{}", self.states)?;

        Ok(())
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct StyleClasses {
    classes: SmallVec<[StyleClass; 4]>,
}

impl StyleClasses {
    pub const fn new() -> Self {
        Self {
            classes: SmallVec::new_const(),
        }
    }

    pub fn len(&self) -> usize {
        self.classes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.classes.is_empty()
    }

    pub fn push(&mut self, class: impl Into<SmolStr>) {
        self.classes.push(class.into());
    }

    pub fn extend(&mut self, classes: impl IntoIterator<Item = impl Into<StyleClass>>) {
        self.classes.extend(classes.into_iter().map(Into::into));
    }

    pub fn iter(&self) -> impl Iterator<Item = &SmolStr> {
        self.classes.iter()
    }

    /// Returns true if `other` is a subset of `self`.
    pub fn select(&self, other: &Self) -> bool {
        for class in other.classes.iter() {
            if !self.classes.contains(class) {
                return false;
            }
        }

        true
    }
}

impl IntoIterator for StyleClasses {
    type Item = SmolStr;
    type IntoIter = smallvec::IntoIter<[SmolStr; 4]>;

    fn into_iter(self) -> Self::IntoIter {
        self.classes.into_iter()
    }
}

impl<T: Into<SmolStr>> FromIterator<T> for StyleClasses {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self {
            classes: iter.into_iter().map(Into::into).collect(),
        }
    }
}

impl Display for StyleClasses {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for class in self.classes.iter() {
            write!(f, ".{}", class)?;
        }

        Ok(())
    }
}

/// A list of style states.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct StyleStates {
    elements: SmallVec<[SmolStr; 4]>,
}

impl StyleStates {
    /// Creates a new empty list.
    pub const fn new() -> Self {
        Self {
            elements: SmallVec::new_const(),
        }
    }

    /// Returns the number of states in the list.
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    /// Returns true if the list is empSharedty.
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    /// Adds a state to the list.
    pub fn push(&mut self, element: impl Into<SmolStr>) {
        self.elements.push(element.into());
    }

    /// Extends the list with the given states.
    pub fn extend(&mut self, elements: impl IntoIterator<Item = impl Into<SmolStr>>) {
        let iter = elements.into_iter().map(|element| element.into());
        self.elements.extend(iter);
    }

    /// Returns an iterator over the states.
    pub fn iter(&self) -> impl Iterator<Item = &str> {
        self.elements.iter().map(|element| element.as_str())
    }

    /// Returns true if `element` is in the list.
    pub fn contains(&self, element: impl AsRef<str>) -> bool {
        self.elements.iter().any(|e| e == element.as_ref())
    }

    /// Returns true if `other` is a subset of `self`.
    pub fn select(&self, other: &Self) -> bool {
        for element in other.elements.iter() {
            if !self.contains(element) {
                return false;
            }
        }

        true
    }
}

impl IntoIterator for StyleStates {
    type Item = SmolStr;
    type IntoIter = smallvec::IntoIter<[Self::Item; 4]>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.into_iter()
    }
}

impl<T: Into<SmolStr>> FromIterator<T> for StyleStates {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self {
            elements: iter.into_iter().map(|e| e.into()).collect(),
        }
    }
}

impl Display for StyleStates {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for element in self.elements.iter() {
            write!(f, ":{}", element)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn selector_select() {
        let selector = StyleSelectors::from_str("a .b .c").unwrap();
        let other = StyleSelectors::from_str(".b .c").unwrap();

        assert!(selector.select(&other));
    }

    #[test]
    fn selector_select_not() {
        let selector = StyleSelectors::from_str("a .b .c").unwrap();
        let other = StyleSelectors::from_str(".b .c .d").unwrap();

        assert!(!selector.select(&other));
    }

    #[test]
    fn classes_select() {
        let classes =
            StyleClasses::from_iter(vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
        let other = StyleClasses::from_iter(vec!["b", "d", "f", "h", "j"]);

        assert!(classes.select(&other));
    }

    #[test]
    fn classes_select_not() {
        let classes =
            StyleClasses::from_iter(vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
        let other = StyleClasses::from_iter(vec!["b", "d", "f", "h", "j", "k"]);

        assert!(!classes.select(&other));
    }
}