crepuscularity-core 0.4.7

Parser, AST, and expression evaluation for the Crepuscularity .crepus DSL (UNSTABLE; in active development).
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Indent-syntax decorators: top-of-file Google Font pragmas and trailing `.alias` class shortcuts.
//!
//! Font pragmas (only at the top of the file, before real template lines):
//! - `google-font Inter` or `google-font: Inter` — one family, unquoted (spaces allowed).
//! - `google-font "Inter"` — one family, quoted (use quotes when the name has edge cases).
//! - `google-fonts "Inter" "JetBrains Mono"` — several families in one line (each must be quoted).

use std::collections::{HashMap, HashSet};

use crate::ast::{ConditionalClass, Node, TextPart};

/// Result of stripping indent-only decorators before parse.
#[derive(Debug, Clone)]
pub struct IndentDecorators {
    /// Source with pragma lines removed (ready for `collect_lines` / `parse_template`).
    pub body: String,
    /// Google Font family names (e.g. `"Inter"`, `"JetBrains Mono"`).
    pub google_fonts: Vec<String>,
    /// Maps shortcut name (without leading dot) → expanded utility string.
    pub class_aliases: HashMap<String, String>,
    /// Raw CSS collected from trailing style blocks / CSS tails.
    pub inline_css: String,
}

/// Strip `google-font` / `google-fonts` lines from the top and `.name tokens…` alias lines from the bottom.
/// JSX mode templates are returned unchanged (no stripping).
pub fn strip_indent_decorators(raw: &str) -> IndentDecorators {
    let lines: Vec<&str> = raw.lines().collect();
    if lines.is_empty() {
        return IndentDecorators {
            body: raw.to_string(),
            google_fonts: Vec::new(),
            class_aliases: HashMap::new(),
            inline_css: String::new(),
        };
    }

    let mut google_fonts = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        let t = lines[i].trim();
        if t.is_empty() || t.starts_with('#') {
            i += 1;
            continue;
        }
        if let Some(families) = parse_google_font_pragma(t) {
            google_fonts.extend(families);
            i += 1;
            continue;
        }
        break;
    }

    let mut end = lines.len();
    let mut alias_lines: Vec<(String, String)> = Vec::new();
    while end > i {
        let t = lines[end - 1].trim();
        if t.is_empty() {
            end -= 1;
            continue;
        }
        if let Some((name, expansion)) = parse_class_alias_line(t) {
            alias_lines.push((name, expansion));
            end -= 1;
            continue;
        }
        break;
    }

    let mut class_aliases = HashMap::new();
    for (name, exp) in alias_lines.into_iter().rev() {
        class_aliases.insert(name, exp);
    }

    let (end, inline_css) = strip_trailing_inline_css(&lines, i, end);
    let body = lines[i..end].join("\n");
    IndentDecorators {
        body,
        google_fonts,
        class_aliases,
        inline_css,
    }
}

fn strip_trailing_inline_css(lines: &[&str], start: usize, mut end: usize) -> (usize, String) {
    if end <= start {
        return (end, String::new());
    }

    // Explicit trailing <style>...</style> block.
    let mut cursor = end;
    while cursor > start && lines[cursor - 1].trim().is_empty() {
        cursor -= 1;
    }
    if cursor > start && lines[cursor - 1].trim() == "</style>" {
        let mut open = cursor - 1;
        while open > start {
            open -= 1;
            if lines[open].trim() == "<style>" {
                let css = lines[(open + 1)..(cursor - 1)]
                    .join("\n")
                    .trim()
                    .to_string();
                return (open, css);
            }
        }
    }

    // Trailing raw CSS without `<style>` wrappers.
    //
    // The body and the CSS tail are not separated by a blank line in many
    // templates, so walking back through "CSS-shaped" lines alone is not
    // enough — `.crepus` element lines like `div bind:href={url}` and bare
    // expressions like `{score}` also end with `}`. We require an
    // **unambiguous CSS opener** at the top of the candidate trailing block
    // (`@`-rule, comment, or a selector line ending with `{`).
    while end > start && lines[end - 1].trim().is_empty() {
        end -= 1;
    }
    if end <= start {
        return (end, String::new());
    }
    if !lines[end - 1].trim().ends_with('}') {
        return (end, String::new());
    }

    let mut css_start = end;
    while css_start > start {
        let t = lines[css_start - 1].trim();
        if t.is_empty() || !looks_like_css_line(t) {
            break;
        }
        css_start -= 1;
    }
    if css_start >= end {
        return (end, String::new());
    }

    let opener = lines[css_start].trim();
    let opener_is_css =
        opener.starts_with('@') || opener.starts_with("/*") || opener.ends_with('{');
    if !opener_is_css {
        return (end, String::new());
    }

    let css = lines[css_start..end].join("\n").trim().to_string();
    (css_start, css)
}

/// Heuristic: does this trimmed line look like a real CSS line (selector, rule
/// boundary, declaration, at-rule, or comment) rather than a `.crepus` template
/// line?
///
/// `.crepus` lines such as text nodes (`"Hello {name}"`), bare expressions
/// (`{score}`), `$:` declarations (`$: let x = {expr}`), bound elements
/// (`div bind:href={url}`), and control headers (`for x in {items}`,
/// `match {status}`) all contain braces but must be kept in the body — so we
/// only treat a line as CSS when it has an *unambiguous* CSS shape:
///
/// - starts with `@` (at-rule) or `/*` (comment) or `}` (block close)
/// - ends with `{` (selector opener — never appears in indent-mode `.crepus`)
/// - is a CSS declaration `prop: value;`
/// - is a complete inline CSS rule `selector { prop: value; }`
fn looks_like_css_line(line: &str) -> bool {
    if line.starts_with('@') || line.starts_with("/*") || line.starts_with('}') {
        return true;
    }
    if line.ends_with('{') {
        return true;
    }
    if line.ends_with(';') && line.contains(':') {
        return true;
    }
    if line.ends_with('}') && line.contains('{') && line.contains(':') && line.contains(';') {
        return true;
    }
    false
}

/// Returns font families declared on this line, or `None` if the line is not a font pragma.
fn parse_google_font_pragma(line: &str) -> Option<Vec<String>> {
    let t = line.trim();
    // `google-font` is a prefix of `google-fonts` — match plural first.
    let (plural, after_kw) = if let Some(r) = t.strip_prefix("google-fonts") {
        (true, r.trim_start())
    } else if let Some(r) = t.strip_prefix("google-font") {
        (false, r.trim_start())
    } else {
        return None;
    };

    let rest = after_kw
        .strip_prefix(':')
        .map(str::trim)
        .unwrap_or(after_kw)
        .trim();
    if rest.is_empty() {
        return None;
    }

    let quoted = parse_quoted_font_names(rest);
    if !quoted.is_empty() {
        if plural {
            return Some(quoted);
        }
        return Some(vec![quoted[0].clone()]);
    }

    if plural {
        // `google-fonts` requires quoted family names so multi-word names are unambiguous.
        return None;
    }

    Some(vec![rest.to_string()])
}

/// Parses consecutive `"..."` tokens (supports `\"` and `\\` inside quotes).
fn parse_quoted_font_names(s: &str) -> Vec<String> {
    let mut out = Vec::new();
    let b = s.as_bytes();
    let mut i = 0usize;
    while i < b.len() {
        while i < b.len() && b[i].is_ascii_whitespace() {
            i += 1;
        }
        if i >= b.len() {
            break;
        }
        if b[i] != b'"' {
            return out;
        }
        i += 1;
        let start = i;
        while i < b.len() {
            match b[i] {
                b'\\' if i + 1 < b.len() => i += 2,
                b'"' => break,
                _ => i += 1,
            }
        }
        if i >= b.len() {
            break;
        }
        let inner = &s[start..i];
        let decoded = inner.replace("\\\\", "\\").replace("\\\"", "\"");
        out.push(decoded);
        i += 1;
    }
    out
}

fn parse_class_alias_line(line: &str) -> Option<(String, String)> {
    let t = line.trim();
    let rest = t.strip_prefix('.')?;
    let mut parts = rest.splitn(2, char::is_whitespace);
    let name = parts.next()?.trim();
    if name.is_empty() {
        return None;
    }
    let expansion = parts.next()?.trim();
    if expansion.is_empty() {
        return None;
    }
    Some((name.to_string(), expansion.to_string()))
}

/// Expand `.shortcut` tokens in `classes` using `aliases` (one level).
pub fn expand_class_token(token: &str, aliases: &HashMap<String, String>) -> Vec<String> {
    if let Some(exp) = aliases.get(token) {
        return exp.split_whitespace().map(|s| s.to_string()).collect();
    }
    vec![token.to_string()]
}

/// Recursively expand class shortcuts on every element.
pub fn expand_class_aliases_in_nodes(nodes: &mut [Node], aliases: &HashMap<String, String>) {
    if aliases.is_empty() {
        return;
    }
    for node in nodes.iter_mut() {
        match node {
            Node::Element(el) => {
                let mut out = Vec::new();
                for c in std::mem::take(&mut el.classes) {
                    out.extend(expand_class_token(&c, aliases));
                }
                el.classes = out;
                let mut out_cc: Vec<ConditionalClass> = Vec::new();
                for cc in std::mem::take(&mut el.conditional_classes) {
                    for c in expand_class_token(&cc.class, aliases) {
                        out_cc.push(ConditionalClass {
                            class: c,
                            condition: cc.condition.clone(),
                        });
                    }
                }
                el.conditional_classes = out_cc;
                expand_class_aliases_in_nodes(&mut el.children, aliases);
            }
            Node::If(b) => {
                expand_class_aliases_in_nodes(&mut b.then_children, aliases);
                if let Some(else_c) = &mut b.else_children {
                    expand_class_aliases_in_nodes(else_c, aliases);
                }
            }
            Node::For(b) => {
                expand_class_aliases_in_nodes(&mut b.body, aliases);
            }
            Node::Match(b) => {
                for arm in &mut b.arms {
                    expand_class_aliases_in_nodes(&mut arm.body, aliases);
                }
            }
            Node::Include(inc) => {
                expand_class_aliases_in_nodes(&mut inc.slot, aliases);
            }
            Node::LetDecl(_) | Node::Text(_) | Node::RawText(_) | Node::Embed(_) => {}
        }
    }
}

/// Deduplicate font family names (case-insensitive), preserving first-seen order.
pub fn merge_unique_font_families<I: IntoIterator<Item = String>>(iter: I) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    for f in iter {
        let t = f.trim().to_string();
        if t.is_empty() {
            continue;
        }
        let k = t.to_lowercase();
        if seen.insert(k) {
            out.push(t);
        }
    }
    out
}

/// `<link rel="preconnect">` and one Google Fonts `css2` stylesheet for the given families.
pub fn google_fonts_head_markup(families: &[String]) -> String {
    if families.is_empty() {
        return String::new();
    }
    let mut q = String::new();
    for (i, f) in families.iter().enumerate() {
        if i > 0 {
            q.push('&');
        }
        let slug = f.split_whitespace().collect::<Vec<_>>().join("+");
        q.push_str("family=");
        q.push_str(&slug);
        q.push_str(":wght@400;500;600;700");
    }
    q.push_str("&display=swap");
    format!(
        r#"  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?{q}" rel="stylesheet">"#
    )
}

/// Plain-text lines from a `slot-rotate` element's children (web + native renderers).
pub fn slot_rotate_child_phrases(children: &[Node]) -> Result<Vec<String>, String> {
    let mut out = Vec::new();
    for c in children {
        match c {
            Node::Text(parts) => {
                let mut s = String::new();
                for p in parts {
                    match p {
                        TextPart::Literal(l) => s.push_str(l),
                        TextPart::Expr(_) => {
                            return Err(
                                "slot-rotate children must be plain text (no `{…}` expressions)"
                                    .into(),
                            );
                        }
                    }
                }
                let t = s.trim();
                if !t.is_empty() {
                    out.push(t.to_string());
                }
            }
            _ => return Err("slot-rotate only allows quoted text lines as children".into()),
        }
    }
    Ok(out)
}

/// JSON array for `data-slot-words` (avoids `|` collisions in phrases).
pub fn slot_rotate_words_json_attr(phrases: &[String]) -> String {
    let mut s = String::from('[');
    for (i, p) in phrases.iter().enumerate() {
        if i > 0 {
            s.push(',');
        }
        s.push('"');
        for ch in p.chars() {
            match ch {
                '\\' => s.push_str(r"\\"),
                '"' => s.push_str("\\\""),
                c if c.is_control() => {
                    s.push_str(&format!("\\u{:04x}", ch as u32));
                }
                c => s.push(c),
            }
        }
        s.push('"');
    }
    s.push(']');
    s
}

/// Expand alias tokens in one element's class list (for the `view!` proc-macro AST).
pub fn expand_class_list_in_place(classes: &mut Vec<String>, aliases: &HashMap<String, String>) {
    if aliases.is_empty() {
        return;
    }
    let mut out = Vec::new();
    for c in std::mem::take(classes) {
        out.extend(expand_class_token(&c, aliases));
    }
    *classes = out;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn strips_fonts_and_aliases() {
        let s = r#"google-font Inter
google-font JetBrains Mono

div center
  "hi"
.center items-center justify-center flex
.body-text text-sm text-black
"#;
        let d = strip_indent_decorators(s);
        assert_eq!(d.google_fonts, vec!["Inter", "JetBrains Mono"]);
        assert_eq!(
            d.class_aliases.get("center").map(String::as_str),
            Some("items-center justify-center flex")
        );
        assert!(d.body.contains("div center"));
        assert!(!d.body.contains("google-font"));
        assert!(!d.body.contains(".center"));
        assert!(d.inline_css.is_empty());
    }

    #[test]
    fn google_fonts_one_line_quoted() {
        let s = r#"google-fonts "Inter" "JetBrains Mono"

div
  "x"
"#;
        let d = strip_indent_decorators(s);
        assert_eq!(d.google_fonts, vec!["Inter", "JetBrains Mono"]);
    }

    #[test]
    fn google_font_quoted_single() {
        let s = "google-font \"IBM Plex Sans\"\ndiv\n";
        let d = strip_indent_decorators(s);
        assert_eq!(d.google_fonts, vec!["IBM Plex Sans"]);
    }

    #[test]
    fn strips_trailing_style_block_into_inline_css() {
        let s = r#"div p-4
  "hello"
<style>
  @keyframes sunset {
    0% { opacity: .6; }
    100% { opacity: 1; }
  }
</style>
"#;
        let d = strip_indent_decorators(s);
        assert!(d.body.contains("div p-4"));
        assert!(!d.body.contains("<style>"));
        assert!(d.inline_css.contains("@keyframes sunset"));
    }

    #[test]
    fn strips_trailing_raw_css_tail() {
        let s = r#"div
  "x"
@keyframes fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}
.animate-fade-in {
  animation: fade-in 1s ease-in-out;
}
"#;
        let d = strip_indent_decorators(s);
        assert_eq!(d.body.trim(), "div\n  \"x\"");
        assert!(d.inline_css.contains(".animate-fade-in"));
    }

    #[test]
    fn google_fonts_head_markup_smoke() {
        let s = google_fonts_head_markup(&["JetBrains Mono".into(), "Inter".into()]);
        assert!(s.contains("fonts.googleapis.com"));
        assert!(s.contains("JetBrains+Mono"));
        assert!(s.contains("family=Inter"));
    }

    #[test]
    fn does_not_strip_trailing_text_with_interpolation() {
        let s = "div w-full h-full flex-col\n  div\n    \"Hello {name}\"\n";
        let d = strip_indent_decorators(s);
        assert!(
            d.body.contains("Hello {name}"),
            "trailing text node was stripped: body={:?} css={:?}",
            d.body,
            d.inline_css
        );
        assert!(d.inline_css.is_empty(), "css={:?}", d.inline_css);
    }

    #[test]
    fn does_not_strip_trailing_bare_expression() {
        let s = "div\n  {score}\n";
        let d = strip_indent_decorators(s);
        assert!(
            d.body.contains("{score}"),
            "bare expression was stripped: body={:?} css={:?}",
            d.body,
            d.inline_css
        );
        assert!(d.inline_css.is_empty());
    }

    #[test]
    fn does_not_strip_trailing_let_decl() {
        let s = "div\n  $: let total = {price * qty}\n";
        let d = strip_indent_decorators(s);
        assert!(
            d.body.contains("$: let total"),
            "$: let was stripped: body={:?} css={:?}",
            d.body,
            d.inline_css
        );
        assert!(d.inline_css.is_empty());
    }

    #[test]
    fn still_strips_at_rule_tail_with_interpolation_above() {
        let s = "div\n  \"score: {score}\"\n@keyframes pulse {\n  0% { opacity: .5; }\n  100% { opacity: 1; }\n}\n";
        let d = strip_indent_decorators(s);
        assert!(d.body.contains("score: {score}"), "body={:?}", d.body);
        assert!(d.inline_css.contains("@keyframes pulse"));
    }

    #[test]
    fn does_not_strip_trailing_element_with_binding() {
        let s = "div bind:href={url}\n";
        let d = strip_indent_decorators(s);
        assert!(d.body.contains("bind:href={url}"), "body={:?}", d.body);
        assert!(d.inline_css.is_empty());
    }

    #[test]
    fn does_not_strip_trailing_class_binding() {
        let s = "div\n  span class:active={selected}\n";
        let d = strip_indent_decorators(s);
        assert!(
            d.body.contains("class:active={selected}"),
            "body={:?}",
            d.body
        );
        assert!(d.inline_css.is_empty());
    }

    #[test]
    fn strips_css_after_trailing_binding_line_without_blank_separator() {
        // Regression: a bound element on the last template line directly
        // followed by a CSS `@keyframes` block (no blank line in between)
        // must keep the binding in the body and strip only the CSS.
        let s = "div bind:href={url}\n@keyframes pulse {\n  0% { opacity: .5; }\n  100% { opacity: 1; }\n}\n";
        let d = strip_indent_decorators(s);
        assert!(d.body.contains("bind:href={url}"), "body={:?}", d.body);
        assert!(
            d.inline_css.contains("@keyframes pulse"),
            "css={:?}",
            d.inline_css
        );
        assert!(
            !d.body.contains("@keyframes"),
            "css leaked into body: body={:?}",
            d.body
        );
    }

    #[test]
    fn does_not_strip_trailing_match_header() {
        let s = "div\n  match {status}\n    \"a\" =>\n      div\n        \"A\"\n";
        let d = strip_indent_decorators(s);
        assert!(d.body.contains("match {status}"), "body={:?}", d.body);
        assert!(d.inline_css.is_empty());
    }

    #[test]
    fn does_not_strip_trailing_for_header() {
        let s = "div\n  for item in {items}\n    div\n      {item}\n";
        let d = strip_indent_decorators(s);
        assert!(d.body.contains("for item in {items}"), "body={:?}", d.body);
        assert!(d.inline_css.is_empty());
    }
}