strata-style 0.1.0

Pure Rust CSS engine, cascade solver, and Tailwind CSS JIT compiler
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! CSS Media Queries Level 4 Parser and Evaluator.
//!
//! Supports:
//! - Media types: `screen`, `all`, `print`, `speech`
//! - Media features: `min-width`, `max-width`, `min-height`, `max-height`, `prefers-color-scheme`, `orientation`
//! - Complex queries: `and`, `not`, comma-separated OR lists

/// Color scheme preference (dark vs light).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorScheme {
    Light,
    Dark,
}

/// Device posture state for CSS `@media (device-posture: ...)` queries (W3C Device Posture API).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DevicePostureQuery {
    Continuous,
    Folded,
}

/// Device or viewport orientation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
    Portrait,
    Landscape,
}

/// Primary CSS media type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MediaType {
    All,
    Screen,
    Print,
    Speech,
}

/// Individual media feature condition within a media query.
#[derive(Debug, Clone, PartialEq)]
pub enum MediaFeature {
    MinWidth(f32),
    MaxWidth(f32),
    MinHeight(f32),
    MaxHeight(f32),
    WidthRange {
        min: Option<f32>,
        min_inclusive: bool,
        max: Option<f32>,
        max_inclusive: bool,
    },
    HeightRange {
        min: Option<f32>,
        min_inclusive: bool,
        max: Option<f32>,
        max_inclusive: bool,
    },
    PrefersColorScheme(ColorScheme),
    Orientation(Orientation),
    HorizontalViewportSegments(u32),
    MinHorizontalViewportSegments(u32),
    MaxHorizontalViewportSegments(u32),
    VerticalViewportSegments(u32),
    MinVerticalViewportSegments(u32),
    MaxVerticalViewportSegments(u32),
    DevicePosture(DevicePostureQuery),
}

impl MediaFeature {
    /// Evaluates this media feature against the active device context.
    pub fn matches(&self, ctx: &MediaContext) -> bool {
        match self {
            MediaFeature::MinWidth(min_w) => ctx.viewport_width >= *min_w,
            MediaFeature::MaxWidth(max_w) => ctx.viewport_width <= *max_w,
            MediaFeature::MinHeight(min_h) => ctx.viewport_height >= *min_h,
            MediaFeature::MaxHeight(max_h) => ctx.viewport_height <= *max_h,
            MediaFeature::WidthRange {
                min,
                min_inclusive,
                max,
                max_inclusive,
            } => {
                let w = ctx.viewport_width;
                let min_ok = match min {
                    Some(m) if *min_inclusive => w >= *m,
                    Some(m) => w > *m,
                    None => true,
                };
                let max_ok = match max {
                    Some(m) if *max_inclusive => w <= *m,
                    Some(m) => w < *m,
                    None => true,
                };
                min_ok && max_ok
            }
            MediaFeature::HeightRange {
                min,
                min_inclusive,
                max,
                max_inclusive,
            } => {
                let h = ctx.viewport_height;
                let min_ok = match min {
                    Some(m) if *min_inclusive => h >= *m,
                    Some(m) => h > *m,
                    None => true,
                };
                let max_ok = match max {
                    Some(m) if *max_inclusive => h <= *m,
                    Some(m) => h < *m,
                    None => true,
                };
                min_ok && max_ok
            }
            MediaFeature::PrefersColorScheme(scheme) => match scheme {
                ColorScheme::Dark => ctx.is_dark,
                ColorScheme::Light => !ctx.is_dark,
            },
            MediaFeature::Orientation(orient) => match orient {
                Orientation::Portrait => ctx.viewport_height >= ctx.viewport_width,
                Orientation::Landscape => ctx.viewport_width > ctx.viewport_height,
            },
            MediaFeature::HorizontalViewportSegments(n) => ctx.horizontal_viewport_segments == *n,
            MediaFeature::MinHorizontalViewportSegments(n) => {
                ctx.horizontal_viewport_segments >= *n
            }
            MediaFeature::MaxHorizontalViewportSegments(n) => {
                ctx.horizontal_viewport_segments <= *n
            }
            MediaFeature::VerticalViewportSegments(n) => ctx.vertical_viewport_segments == *n,
            MediaFeature::MinVerticalViewportSegments(n) => ctx.vertical_viewport_segments >= *n,
            MediaFeature::MaxVerticalViewportSegments(n) => ctx.vertical_viewport_segments <= *n,
            MediaFeature::DevicePosture(posture) => ctx.device_posture == *posture,
        }
    }
}

/// Single CSS media query clause (e.g. `screen and (min-width: 768px)` or `not print`).
#[derive(Debug, Clone, PartialEq)]
pub struct MediaQuery {
    pub negated: bool,
    pub media_type: MediaType,
    pub features: Vec<MediaFeature>,
}

impl MediaQuery {
    /// Evaluates whether this single media query condition is satisfied.
    pub fn matches(&self, ctx: &MediaContext) -> bool {
        let type_matched = match self.media_type {
            MediaType::All | MediaType::Screen => true,
            MediaType::Print | MediaType::Speech => false,
        };

        let features_matched = self.features.iter().all(|f| f.matches(ctx));
        let outcome = type_matched && features_matched;

        if self.negated {
            !outcome
        } else {
            outcome
        }
    }

    /// Parses a single media query clause.
    pub fn parse(input: &str) -> Result<Self, String> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Ok(Self {
                negated: false,
                media_type: MediaType::All,
                features: Vec::new(),
            });
        }

        let mut negated = false;
        let mut rest = trimmed;

        if let Some(after_not) = rest
            .strip_prefix("not")
            .or_else(|| rest.strip_prefix("NOT"))
        {
            if after_not.starts_with(char::is_whitespace) {
                negated = true;
                rest = after_not.trim();
            }
        }

        // Optional `only` prefix per CSS syntax
        if let Some(after_only) = rest
            .strip_prefix("only")
            .or_else(|| rest.strip_prefix("ONLY"))
        {
            if after_only.starts_with(char::is_whitespace) {
                rest = after_only.trim();
            }
        }

        let mut media_type = MediaType::All;
        let mut features = Vec::new();

        // Split by 'and' or 'AND'
        let parts: Vec<&str> = rest
            .split(" and ")
            .flat_map(|p| p.split(" AND "))
            .map(|s| s.trim())
            .collect();

        for (idx, part) in parts.iter().enumerate() {
            if part.starts_with('(') && part.ends_with(')') {
                let inner = &part[1..part.len() - 1].trim();
                let feat = parse_feature(inner)?;
                features.push(feat);
            } else if idx == 0 {
                media_type = match part.to_ascii_lowercase().as_str() {
                    "all" => MediaType::All,
                    "screen" => MediaType::Screen,
                    "print" => MediaType::Print,
                    "speech" => MediaType::Speech,
                    _ => return Err(format!("Unrecognized media type '{}'", part)),
                };
            } else {
                return Err(format!("Unexpected media query token '{}'", part));
            }
        }

        Ok(Self {
            negated,
            media_type,
            features,
        })
    }
}

/// Comma-separated list of media queries, matching if any condition holds (CSS OR logic).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct MediaQueryList {
    pub queries: Vec<MediaQuery>,
}

impl MediaQueryList {
    /// Evaluates whether any media query in this list matches the active context.
    pub fn matches(&self, ctx: &MediaContext) -> bool {
        if self.queries.is_empty() {
            return true;
        }
        self.queries.iter().any(|q| q.matches(ctx))
    }

    /// Parses a comma-separated list of media queries (e.g. `screen and (max-width: 600px), print`).
    pub fn parse(input: &str) -> Result<Self, String> {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Ok(Self {
                queries: Vec::new(),
            });
        }

        let mut queries = Vec::new();
        for item in trimmed.split(',') {
            let item_trimmed = item.trim();
            if !item_trimmed.is_empty() {
                queries.push(MediaQuery::parse(item_trimmed)?);
            }
        }

        Ok(Self { queries })
    }
}

/// Device context used to evaluate media and container query conditions.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MediaContext {
    pub viewport_width: f32,
    pub viewport_height: f32,
    pub is_dark: bool,
    pub container_width: Option<f32>,
    pub container_height: Option<f32>,
    pub horizontal_viewport_segments: u32,
    pub vertical_viewport_segments: u32,
    pub device_posture: DevicePostureQuery,
}

impl Default for MediaContext {
    fn default() -> Self {
        Self {
            viewport_width: 1280.0,
            viewport_height: 800.0,
            is_dark: true,
            container_width: None,
            container_height: None,
            horizontal_viewport_segments: 1,
            vertical_viewport_segments: 1,
            device_posture: DevicePostureQuery::Continuous,
        }
    }
}

impl MediaContext {
    /// Constructs a MediaContext with viewport dimensions and color scheme.
    pub const fn new(viewport_width: f32, viewport_height: f32, is_dark: bool) -> Self {
        Self {
            viewport_width,
            viewport_height,
            is_dark,
            container_width: None,
            container_height: None,
            horizontal_viewport_segments: 1,
            vertical_viewport_segments: 1,
            device_posture: DevicePostureQuery::Continuous,
        }
    }

    /// Sets container size for evaluating @container queries.
    pub fn with_container_size(mut self, width: f32, height: f32) -> Self {
        self.container_width = Some(width);
        self.container_height = Some(height);
        self
    }

    /// Sets horizontal and vertical viewport segments (W3C Viewport Segments Level 1).
    pub fn with_viewport_segments(mut self, horizontal: u32, vertical: u32) -> Self {
        self.horizontal_viewport_segments = horizontal.max(1);
        self.vertical_viewport_segments = vertical.max(1);
        self
    }

    /// Sets the device posture (W3C Device Posture API).
    pub fn with_device_posture(mut self, posture: DevicePostureQuery) -> Self {
        self.device_posture = posture;
        self
    }
}

fn parse_range_feature(input: &str) -> Result<MediaFeature, String> {
    let lower = input.to_ascii_lowercase();
    let is_width = lower.contains("width");
    let is_height = lower.contains("height");
    if !is_width && !is_height {
        return Err(format!(
            "Range query only supported for width and height: '{}'",
            input
        ));
    }

    // Tokenize into operands and operators
    let mut tokens: Vec<String> = Vec::new();
    let mut cur = String::new();
    let chars: Vec<char> = input.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c.is_whitespace() {
            if !cur.is_empty() {
                tokens.push(cur.clone());
                cur.clear();
            }
            i += 1;
            continue;
        }
        if c == '<' || c == '>' || c == '=' {
            if !cur.is_empty() {
                tokens.push(cur.clone());
                cur.clear();
            }
            let mut op = String::new();
            op.push(c);
            if i + 1 < chars.len() && chars[i + 1] == '=' {
                op.push('=');
                i += 1;
            }
            tokens.push(op);
            i += 1;
            continue;
        }
        cur.push(c);
        i += 1;
    }
    if !cur.is_empty() {
        tokens.push(cur);
    }

    // Expected patterns:
    // 1. [val, op1, prop, op2, val2] (e.g. 768px <= width <= 1200px)
    // 2. [prop, op, val] (e.g. width >= 768px)
    // 3. [val, op, prop] (e.g. 768px <= width)
    if tokens.len() == 5 {
        let val1 = parse_px_dimension(&tokens[0])?;
        let op1 = &tokens[1];
        let prop = tokens[2].to_ascii_lowercase();
        let op2 = &tokens[3];
        let val2 = parse_px_dimension(&tokens[4])?;

        if prop != "width" && prop != "height" {
            return Err(format!(
                "Expected width or height in range query, got '{}'",
                prop
            ));
        }

        let (min, min_inclusive) = match op1.as_str() {
            "<=" => (Some(val1), true),
            "<" => (Some(val1), false),
            ">=" => (Some(val2), true),
            ">" => (Some(val2), false),
            _ => return Err(format!("Unsupported operator '{}' in range query", op1)),
        };

        let (max, max_inclusive) = match op2.as_str() {
            "<=" => (Some(val2), true),
            "<" => (Some(val2), false),
            ">=" => (Some(val1), true),
            ">" => (Some(val1), false),
            _ => return Err(format!("Unsupported operator '{}' in range query", op2)),
        };

        if prop == "width" {
            Ok(MediaFeature::WidthRange {
                min,
                min_inclusive,
                max,
                max_inclusive,
            })
        } else {
            Ok(MediaFeature::HeightRange {
                min,
                min_inclusive,
                max,
                max_inclusive,
            })
        }
    } else if tokens.len() == 3 {
        let t0_lower = tokens[0].to_ascii_lowercase();
        let t2_lower = tokens[2].to_ascii_lowercase();

        if t0_lower == "width" || t0_lower == "height" {
            let prop = t0_lower;
            let op = &tokens[1];
            let val = parse_px_dimension(&tokens[2])?;

            let (min, min_inclusive, max, max_inclusive) = match op.as_str() {
                ">=" => (Some(val), true, None, false),
                ">" => (Some(val), false, None, false),
                "<=" => (None, false, Some(val), true),
                "<" => (None, false, Some(val), false),
                "=" => (Some(val), true, Some(val), true),
                _ => return Err(format!("Unsupported operator '{}' in range query", op)),
            };

            if prop == "width" {
                Ok(MediaFeature::WidthRange {
                    min,
                    min_inclusive,
                    max,
                    max_inclusive,
                })
            } else {
                Ok(MediaFeature::HeightRange {
                    min,
                    min_inclusive,
                    max,
                    max_inclusive,
                })
            }
        } else if t2_lower == "width" || t2_lower == "height" {
            let val = parse_px_dimension(&tokens[0])?;
            let op = &tokens[1];
            let prop = t2_lower;

            let (min, min_inclusive, max, max_inclusive) = match op.as_str() {
                "<=" => (Some(val), true, None, false),
                "<" => (Some(val), false, None, false),
                ">=" => (None, false, Some(val), true),
                ">" => (None, false, Some(val), false),
                "=" => (Some(val), true, Some(val), true),
                _ => return Err(format!("Unsupported operator '{}' in range query", op)),
            };

            if prop == "width" {
                Ok(MediaFeature::WidthRange {
                    min,
                    min_inclusive,
                    max,
                    max_inclusive,
                })
            } else {
                Ok(MediaFeature::HeightRange {
                    min,
                    min_inclusive,
                    max,
                    max_inclusive,
                })
            }
        } else {
            Err(format!(
                "Neither side of comparison is width/height in '{}'",
                input
            ))
        }
    } else {
        Err(format!("Invalid range media query syntax: '{}'", input))
    }
}

fn parse_feature(input: &str) -> Result<MediaFeature, String> {
    if input.contains('<') || input.contains('>') {
        return parse_range_feature(input);
    }

    let (prop, val) = match input.split_once(':') {
        Some((p, v)) => (p.trim().to_ascii_lowercase(), v.trim()),
        None => return Err(format!("Invalid media feature without colon: '{}'", input)),
    };

    match prop.as_str() {
        "min-width" => {
            let px = parse_px_dimension(val)?;
            Ok(MediaFeature::MinWidth(px))
        }
        "max-width" => {
            let px = parse_px_dimension(val)?;
            Ok(MediaFeature::MaxWidth(px))
        }
        "min-height" => {
            let px = parse_px_dimension(val)?;
            Ok(MediaFeature::MinHeight(px))
        }
        "max-height" => {
            let px = parse_px_dimension(val)?;
            Ok(MediaFeature::MaxHeight(px))
        }
        "prefers-color-scheme" => match val.to_ascii_lowercase().as_str() {
            "dark" => Ok(MediaFeature::PrefersColorScheme(ColorScheme::Dark)),
            "light" => Ok(MediaFeature::PrefersColorScheme(ColorScheme::Light)),
            _ => Err(format!("Unknown prefers-color-scheme value '{}'", val)),
        },
        "orientation" => match val.to_ascii_lowercase().as_str() {
            "portrait" => Ok(MediaFeature::Orientation(Orientation::Portrait)),
            "landscape" => Ok(MediaFeature::Orientation(Orientation::Landscape)),
            _ => Err(format!("Unknown orientation value '{}'", val)),
        },
        "horizontal-viewport-segments" => {
            let count = val.trim().parse::<u32>().map_err(|e| e.to_string())?;
            Ok(MediaFeature::HorizontalViewportSegments(count))
        }
        "min-horizontal-viewport-segments" => {
            let count = val.trim().parse::<u32>().map_err(|e| e.to_string())?;
            Ok(MediaFeature::MinHorizontalViewportSegments(count))
        }
        "max-horizontal-viewport-segments" => {
            let count = val.trim().parse::<u32>().map_err(|e| e.to_string())?;
            Ok(MediaFeature::MaxHorizontalViewportSegments(count))
        }
        "vertical-viewport-segments" => {
            let count = val.trim().parse::<u32>().map_err(|e| e.to_string())?;
            Ok(MediaFeature::VerticalViewportSegments(count))
        }
        "min-vertical-viewport-segments" => {
            let count = val.trim().parse::<u32>().map_err(|e| e.to_string())?;
            Ok(MediaFeature::MinVerticalViewportSegments(count))
        }
        "max-vertical-viewport-segments" => {
            let count = val.trim().parse::<u32>().map_err(|e| e.to_string())?;
            Ok(MediaFeature::MaxVerticalViewportSegments(count))
        }
        "device-posture" => match val.to_ascii_lowercase().as_str() {
            "continuous" => Ok(MediaFeature::DevicePosture(DevicePostureQuery::Continuous)),
            "folded" => Ok(MediaFeature::DevicePosture(DevicePostureQuery::Folded)),
            _ => Err(format!("Unknown device-posture value '{}'", val)),
        },
        _ => Err(format!("Unsupported media feature property '{}'", prop)),
    }
}

fn parse_px_dimension(val: &str) -> Result<f32, String> {
    let cleaned = val.trim().to_ascii_lowercase();
    if let Some(px_str) = cleaned.strip_suffix("px") {
        px_str.trim().parse::<f32>().map_err(|e| e.to_string())
    } else if let Some(em_str) = cleaned.strip_suffix("em") {
        let em = em_str.trim().parse::<f32>().map_err(|e| e.to_string())?;
        Ok(em * 16.0)
    } else if let Some(rem_str) = cleaned.strip_suffix("rem") {
        let rem = rem_str.trim().parse::<f32>().map_err(|e| e.to_string())?;
        Ok(rem * 16.0)
    } else {
        cleaned.parse::<f32>().map_err(|e| e.to_string())
    }
}