compmd 0.11.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In 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
//! Params evaluated (spec §9.2, §9.3, §12.3): each value read by its kind and declared type, a bound input's value
//! with its name, an expression evaluated at each breakpoint where the body's params have breakpoint values, a
//! definition fence's params under the caller's, and all classes in one `class`.

use super::Expander;
use super::env::Env;
use super::fonts::FONT_FAMILY;
use crate::breakpoint::{BREAKPOINTS, rank};
use crate::cel::{Error, Value};
use crate::diagnostic::{Code, Location};
use crate::expanded;
use crate::tree::{DeclaredType, Param, ParamValue, Point, Signature, StringPart};
use crate::validate::params::value_at;

/// An evaluated param.
#[derive(Clone, Debug)]
pub(super) struct Out {
    pub(super) key: String,
    pub(super) breakpoint: Option<String>,
    pub(super) value: Value,
    /// The input it is bound to.
    pub(super) input: Option<String>,
}

impl Out {
    fn into_param(self) -> expanded::Param {
        expanded::Param {
            key: self.key,
            breakpoint: self.breakpoint,
            value: self.value.to_json(),
            input: self.input,
        }
    }
}

/// A param's key: `class` for `.name`, `id` for `#name`.
pub(super) fn key_of(param: &Param) -> &str {
    match param.value {
        ParamValue::Class(_) => "class",
        ParamValue::Id(_) => "id",
        _ => param.key.as_deref().unwrap_or(""),
    }
}

impl<'r> Expander<'r> {
    /// The value of `param`, written in `env`, read as `declared`, a `font-family`'s naming its font as the tree does;
    /// `None` when its expression fails (F024), or it names no font (F009), so that it is treated as absent.
    pub(super) fn param_value(
        &mut self,
        param: &Param,
        declared: Option<&DeclaredType>,
        env: &Env<'r>,
    ) -> Option<Value> {
        let value = self.written_value(param, declared, env)?;
        if key_of(param) == FONT_FAMILY {
            return self.font_family(value, param, env);
        }
        Some(value)
    }

    /// The value of `param` as written: its text, or its expression's value.
    fn written_value(
        &mut self,
        param: &Param,
        declared: Option<&DeclaredType>,
        env: &Env<'r>,
    ) -> Option<Value> {
        Some(match &param.value {
            ParamValue::Bare(text) => Value::bare(text, declared),
            ParamValue::String(parts) => Value::string(&self.quoted(parts, param, env)),
            ParamValue::Json(text) => Value::from_json(&serde_json::from_str(text).ok()?),
            ParamValue::Expr(source) => match self.evaluate(source, env) {
                Ok(value) => value,
                Err(error) => {
                    self.failed(&error, source, param, env);
                    return None;
                }
            },
            ParamValue::Flag => Value::Bool(true),
            ParamValue::Class(text) | ParamValue::Id(text) => Value::string(text),
        })
    }

    /// F024 at the column inside the expression.
    fn failed(&mut self, error: &Error, source: &str, param: &Param, env: &Env) {
        let at = value_at(param);
        let at = Location::new(at.line, at.column + 1 + error.at());
        self.report(
            Code::F024,
            env,
            at,
            format!("`{source}`: {}", error.message()),
        );
    }

    /// A quoted value's text, its interpolations filled in.
    fn quoted(&mut self, parts: &[StringPart], param: &Param, env: &Env<'r>) -> String {
        let at = value_at(param);
        let start = Point {
            line: at.line,
            column: at.column,
            offset: 0,
        };
        let mut places = self.lines[&env.document].paths_from(start).into_iter();
        let mut text = String::new();
        for part in parts {
            match part {
                StringPart::Text(literal) => text.push_str(&literal.value),
                StringPart::Interpolation(interpolation) => {
                    let at = places.next().unwrap_or(at);
                    text.push_str(
                        &self
                            .path_text(&interpolation.path, at, env)
                            .unwrap_or_default(),
                    );
                }
            }
        }
        text
    }

    /// The params `params` give a node, evaluated in `env` and read by `signature`, in written order. A bound input
    /// gives its value and name. An expression without a breakpoint, in a body whose params have breakpoint values,
    /// is evaluated at each breakpoint, and each value that differs from the one before becomes a param of that
    /// breakpoint (spec §9.3). A param whose expression fails, or whose value is `null`, is left out.
    pub(super) fn evaluated(
        &mut self,
        params: &[&'r Param],
        signature: Option<&Signature>,
        env: &Env<'r>,
    ) -> Vec<Out> {
        let mut out = Vec::new();
        for param in params {
            let key = key_of(param).to_string();
            let declared = signature
                .and_then(|signature| signature.params.iter().find(|d| d.name == key))
                .map(|declaration| &declaration.declared);
            if let (Some(DeclaredType::Input { .. }), ParamValue::Bare(input)) =
                (declared, &param.value)
            {
                out.push(Out {
                    value: env.input(input),
                    key,
                    breakpoint: param.breakpoint.clone(),
                    input: Some(input.clone()),
                });
                continue;
            }
            let Some(value) = self.param_value(param, declared, env) else {
                continue;
            };
            let mut previous = value.to_json();
            out.push(Out {
                key: key.clone(),
                breakpoint: param.breakpoint.clone(),
                value,
                input: None,
            });
            let responsive =
                matches!(param.value, ParamValue::Expr(_)) && param.breakpoint.is_none();
            let Some(values) = env.breakpoints.clone().filter(|_| responsive) else {
                continue;
            };
            for (values, breakpoint) in values.iter().zip(BREAKPOINTS) {
                let at = Env {
                    values: values.clone(),
                    ..env.clone()
                };
                let Some(value) = self.param_value(param, declared, &at) else {
                    continue;
                };
                let written = value.to_json();
                if written != previous {
                    previous = written;
                    out.push(Out {
                        key: key.clone(),
                        breakpoint: Some(breakpoint.to_string()),
                        value,
                        input: None,
                    });
                }
            }
        }
        out.retain(|out| !matches!(out.value, Value::Null));
        out
    }
}

/// The params of a component's box: the fence's, less what the caller's cover (spec §9.2), then the caller's, with
/// all classes in one `class`, last.
pub(super) fn boxed(fence: Vec<Out>, caller: Vec<Out>) -> Vec<expanded::Param> {
    let mut params = Vec::new();
    for out in fence {
        under(out, &caller, &mut params);
    }
    params.extend(caller);
    let mut classes: Vec<String> = Vec::new();
    for out in params.iter().filter(|out| out.key == "class") {
        let names = out.value.written().ok().flatten().unwrap_or_default();
        for name in names.split_whitespace() {
            if !classes.iter().any(|known| known == name) {
                classes.push(name.to_string());
            }
        }
    }
    params.retain(|out| out.key != "class");
    if !classes.is_empty() {
        params.push(Out {
            key: "class".into(),
            breakpoint: None,
            value: Value::string(&classes.join(" ")),
            input: None,
        });
    }
    params.into_iter().map(Out::into_param).collect()
}

/// A fence param kept unless a caller's param covers it from its breakpoint or a wider one; a shorthand the caller
/// covers in part is written as its longhands first.
fn under(fence: Out, caller: &[Out], kept: &mut Vec<Out>) {
    if fence.key == "class" {
        kept.push(fence);
        return;
    }
    let from_here =
        |out: &&Out| rank(out.breakpoint.as_deref()) <= rank(fence.breakpoint.as_deref());
    if caller
        .iter()
        .filter(from_here)
        .any(|out| covers(&out.key, &fence.key))
    {
        return;
    }
    let in_part = caller
        .iter()
        .filter(from_here)
        .any(|out| out.key != fence.key && covers(&fence.key, &out.key));
    match longhands(&fence).filter(|_| in_part) {
        Some(parts) => {
            for part in parts {
                under(part, caller, kept);
            }
        }
        None => kept.push(fence),
    }
}

/// The parts a shorthand sets: `padding` its block and inline padding, those their two sides; `border` its four
/// sides.
fn parts(key: &str) -> &'static [&'static str] {
    match key {
        "padding" => &["padding-block", "padding-inline"],
        "padding-block" => &["padding-block-start", "padding-block-end"],
        "padding-inline" => &["padding-inline-start", "padding-inline-end"],
        "border" => &BORDER_SIDES,
        _ => &[],
    }
}

/// `border`'s sides, each of which takes `border`'s whole value.
const BORDER_SIDES: [&str; 4] = [
    "border-block-start",
    "border-block-end",
    "border-inline-start",
    "border-inline-end",
];

/// Whether a param of `key` sets the property `other`: it is the same, or one of its parts.
fn covers(key: &str, other: &str) -> bool {
    key == other || parts(key).iter().any(|part| covers(part, other))
}

/// A shorthand's longhands, its one or two values split between them (`border`'s value whole on each side); `None`
/// for a param that isn't one.
fn longhands(out: &Out) -> Option<Vec<Out>> {
    let names = parts(&out.key);
    let text = out.value.written().ok().flatten()?;
    let side = |name: &&str| Out {
        key: (*name).to_string(),
        breakpoint: out.breakpoint.clone(),
        value: Value::string(text.trim()),
        input: None,
    };
    if out.key == "border" {
        return Some(names.iter().map(side).collect());
    }
    let values: Vec<&str> = text.split_whitespace().collect();
    let (first, second) = match values.as_slice() {
        [one] => (*one, *one),
        [first, second] => (*first, *second),
        _ => return None,
    };
    let [one, two] = names else {
        return None;
    };
    Some(
        [(one, first), (two, second)]
            .into_iter()
            .map(|(name, value)| Out {
                key: (*name).to_string(),
                breakpoint: out.breakpoint.clone(),
                value: Value::string(value),
                input: None,
            })
            .collect(),
    )
}

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

    fn out(key: &str, breakpoint: Option<&str>, value: &str) -> Out {
        Out {
            key: key.into(),
            breakpoint: breakpoint.map(Into::into),
            value: Value::string(value),
            input: None,
        }
    }

    fn written(params: &[expanded::Param]) -> Vec<String> {
        params
            .iter()
            .map(|param| match &param.breakpoint {
                Some(breakpoint) => format!("{breakpoint}:{}={}", param.key, param.value),
                None => format!("{}={}", param.key, param.value),
            })
            .collect()
    }

    #[test]
    fn the_callers_params_cover_the_fences_from_their_breakpoint_up() {
        let fence = || {
            vec![
                out("class", None, "card"),
                out("padding", None, "s"),
                out("border", None, "subtle"),
                out("padding", Some("md"), "m"),
            ]
        };
        let wide = boxed(
            fence(),
            vec![out("padding", None, "l"), out("class", None, "wide card")],
        );
        assert_eq!(
            written(&wide),
            ["border=\"subtle\"", "padding=\"l\"", "class=\"card wide\""]
        );
        let from_md = boxed(fence(), vec![out("padding", Some("md"), "l")]);
        assert_eq!(
            written(&from_md),
            [
                "padding=\"s\"",
                "border=\"subtle\"",
                "md:padding=\"l\"",
                "class=\"card\""
            ]
        );
    }

    #[test]
    fn a_shorthand_covered_in_part_is_split() {
        let split = boxed(
            vec![out("padding", None, "s l")],
            vec![out("padding-inline-start", None, "m")],
        );
        assert_eq!(
            written(&split),
            [
                "padding-block=\"s\"",
                "padding-inline-end=\"l\"",
                "padding-inline-start=\"m\""
            ]
        );
        let covered = boxed(
            vec![out("padding-inline", None, "l")],
            vec![out("padding", None, "s")],
        );
        assert_eq!(written(&covered), ["padding=\"s\""]);
        let odd = boxed(
            vec![out("padding", None, "s m l")],
            vec![out("padding-block", None, "m")],
        );
        assert_eq!(written(&odd), ["padding=\"s m l\"", "padding-block=\"m\""]);
        assert!(longhands(&out("border-radius", None, "s")).is_none());
    }

    #[test]
    fn a_callers_border_side_splits_the_fences_border_into_its_sides_each_whole() {
        let sides = boxed(
            vec![out("border", None, "1px solid teal")],
            vec![out("border-inline-start", None, "strong")],
        );
        assert_eq!(
            written(&sides),
            [
                "border-block-start=\"1px solid teal\"",
                "border-block-end=\"1px solid teal\"",
                "border-inline-end=\"1px solid teal\"",
                "border-inline-start=\"strong\""
            ]
        );
        let covered = boxed(
            vec![out("border-inline-start", None, "strong")],
            vec![out("border", None, "none")],
        );
        assert_eq!(written(&covered), ["border=\"none\""]);
    }

    #[test]
    fn whole_numbers_are_written_without_a_fraction() {
        let number = Out {
            key: "n".into(),
            breakpoint: None,
            value: Value::Double(5.0),
            input: Some("limit".into()),
        };
        let param = number.into_param();
        assert_eq!(serde_json::to_value(&param).unwrap()["value"], json!(5));
    }
}