bern-ir 0.1.3

Versioned, platform-independent intermediate representation of Bern applications
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
//! Style overrides and motion tokens declared with `style!`.
//!
//! Standard controls keep their platform look unless the application
//! declares otherwise. A rule overrides one kind of control, or one named
//! variant of it, on every platform or on the platforms it names. Colors
//! are semantic roles or explicit pairs for light and dark; motion refers
//! to spring tokens by name.

use crate::{SourceLocation, Srgb};
use serde::{Deserialize, Serialize};

/// Spring tokens every application has: name, period in seconds and
/// damping ratio. An application may change their values.
pub const BUILT_IN_MOTION: [(&str, f64, f64); 6] = [
    ("press", 0.12, 1.0),
    ("snappy", 0.22, 0.85),
    ("smooth", 0.45, 1.0),
    ("bouncy", 0.50, 0.62),
    ("jelly", 0.42, 0.42),
    ("hero", 0.48, 0.86),
];

/// Semantic color roles a style may name. Native targets map them to their
/// system colors; Bern-drawn targets take them from the theme kernel.
pub const COLOR_ROLES: &[&str] = &[
    "surface.canvas",
    "surface.panel",
    "surface.raised",
    "text.primary",
    "text.secondary",
    "text.placeholder",
    "icon.primary",
    "icon.secondary",
    "accent",
    "on_accent",
    "status.success",
    "status.warning",
    "status.error",
    "control.border",
    "control.track",
    "control.thumb",
    "focus.indicator",
    "selection.background",
    "selection.foreground",
    "disabled.foreground",
    "disabled.surface",
    "fill.subtle",
    "fill.strong",
];

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct StyleSheet {
    /// Every motion token: the built-in ones, then the application's own.
    pub motion: Vec<MotionToken>,
    pub rules: Vec<StyleRule>,
    /// Every transition: the built-in ones, then the application's own.
    #[serde(default)]
    pub transitions: Vec<TransitionDef>,
    /// Patterns `Pattern(name:)` tiles over a canvas.
    #[serde(default)]
    pub patterns: Vec<PatternDef>,
    /// Accent colors the application chooses among at run time with
    /// `WindowSet(accent:)`.
    #[serde(default)]
    pub accents: Vec<AccentDef>,
    /// The weights the application gives text styles, such as a heavy
    /// `large_title`; the sizes stay the platform's.
    #[serde(default)]
    pub text_weights: Vec<TextWeight>,
    /// Named corner radii (`corner { card: 22 }`) in declaration order:
    /// the values for every platform, then those of `#[target(…)]` blocks.
    #[serde(default)]
    pub corners: Vec<CornerDef>,
}

/// A named corner radius, for every platform when `targets` is empty and
/// for the platforms it names otherwise.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CornerDef {
    pub name: String,
    pub radius: f64,
    #[serde(default)]
    pub targets: Vec<String>,
}

/// The weight, and the size when the application's design gives one, of
/// one text style.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TextWeight {
    /// A text style, such as `large_title`.
    pub style: String,
    /// One of [`TEXT_WEIGHTS`].
    pub weight: String,
    /// The size in points on desktops; the platform's size of the style
    /// when absent.
    #[serde(default)]
    pub size: Option<f64>,
    /// The size in points on a television, read from across a room, where
    /// the design gives one; `size` there otherwise.
    #[serde(default)]
    pub tv_size: Option<f64>,
}

/// The weights a text style can take.
pub const TEXT_WEIGHTS: &[&str] = &[
    "ultralight",
    "thin",
    "light",
    "regular",
    "medium",
    "semibold",
    "bold",
    "heavy",
    "black",
];

/// A named accent color.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccentDef {
    pub name: String,
    pub color: ColorRef,
}

/// A woven check: the bands, repeated across and down, colored where they
/// cross; with `twill`, fine diagonal lines over it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PatternDef {
    pub name: String,
    pub bands: Vec<Band>,
    pub twill: bool,
}

/// A band of a pattern: `width` logical units of `color` at `opacity`, or
/// a gap of the canvas's own color when `color` is `None`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Band {
    pub color: Option<ColorRef>,
    pub width: f64,
    pub opacity: f64,
}

/// How an element appears or disappears, moved by a motion token.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TransitionDef {
    pub name: String,
    pub kind: TransitionKind,
    pub motion: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TransitionKind {
    /// Fades in or out.
    Fade,
    /// Grows from (or shrinks to) `from` of its size while fading.
    Pop { from: f64 },
    /// Extends from zero along one axis, keeping `edge` fixed, without fading.
    Grow { edge: Edge },
    /// Slides from (or to) `distance` beyond `edge` while fading.
    Slide { edge: Edge, distance: f64 },
    /// Moves in from (or out to) beyond `edge`, its whole size away, without
    /// fading, as a sheet comes up from the bottom of the screen.
    Move { edge: Edge },
}

/// Transitions every application has.
pub fn built_in_transitions() -> Vec<TransitionDef> {
    vec![
        TransitionDef {
            name: "fade".into(),
            kind: TransitionKind::Fade,
            motion: "smooth".into(),
        },
        TransitionDef {
            name: "pop".into(),
            kind: TransitionKind::Pop { from: 0.8 },
            motion: "bouncy".into(),
        },
        TransitionDef {
            name: "slide".into(),
            kind: TransitionKind::Slide {
                edge: Edge::Bottom,
                distance: 16.0,
            },
            motion: "smooth".into(),
        },
    ]
}

impl StyleSheet {
    pub fn token(&self, name: &str) -> Option<&MotionToken> {
        self.motion.iter().find(|token| token.name == name)
    }

    /// The accent named like an enum variant: `Crimson` and `crimson`
    /// name the same accent.
    pub fn accent(&self, name: &str) -> Option<&AccentDef> {
        let wanted = name.replace('_', "").to_lowercase();
        self.accents
            .iter()
            .find(|accent| accent.name.replace('_', "").to_lowercase() == wanted)
    }

    pub fn pattern(&self, name: &str) -> Option<&PatternDef> {
        self.patterns.iter().find(|pattern| pattern.name == name)
    }

    pub fn transition(&self, name: &str) -> Option<&TransitionDef> {
        self.transitions
            .iter()
            .find(|transition| transition.name == name)
    }

    /// The radius the corner `name` has on `platform`: the last
    /// declaration that applies there.
    pub fn corner(&self, name: &str, platform: &str) -> Option<f64> {
        self.corners
            .iter()
            .rev()
            .find(|corner| {
                corner.name == name
                    && (corner.targets.is_empty() || corner.targets.iter().any(|t| t == platform))
            })
            .map(|corner| corner.radius)
    }

    /// The rules for `platform`, in declaration order: later rules override
    /// earlier ones property by property.
    pub fn rules_for<'a>(&'a self, platform: &'a str) -> impl Iterator<Item = &'a StyleRule> {
        self.rules.iter().filter(move |rule| {
            rule.targets.is_empty() || rule.targets.iter().any(|t| t == platform)
        })
    }
}

/// A spring: undamped period `period` in seconds and damping ratio
/// `damping`. Stiffness is (2π / period)² and damping 4π·damping / period,
/// for a mass of 1.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MotionToken {
    pub name: String,
    pub period: f64,
    pub damping: f64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StyleRule {
    /// The control kind, such as `SidebarItem`.
    pub component: String,
    /// A named variant that instances select with `variant:`.
    pub variant: Option<String>,
    /// Platforms the rule applies to (`macos`, `ios`, `windows`, `linux`,
    /// `browser`); empty for all.
    pub targets: Vec<String>,
    /// Platforms that keep their default look for effects they cannot show.
    pub exempt: Vec<String>,
    /// Effects in every state.
    pub base: Vec<StyleEffect>,
    pub states: Vec<StateStyle>,
    /// Motion back to the resting state.
    pub settle: Option<String>,
    pub source: SourceLocation,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StateStyle {
    pub state: StyleState,
    pub effects: Vec<StyleEffect>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StyleState {
    Hover,
    Pressed,
    Selected,
    Focus,
    Disabled,
}

impl StyleState {
    pub const ALL: [StyleState; 5] = [
        StyleState::Hover,
        StyleState::Pressed,
        StyleState::Selected,
        StyleState::Focus,
        StyleState::Disabled,
    ];

    pub fn name(self) -> &'static str {
        match self {
            StyleState::Hover => "hover",
            StyleState::Pressed => "pressed",
            StyleState::Selected => "selected",
            StyleState::Focus => "focus",
            StyleState::Disabled => "disabled",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StyleEffect {
    Background {
        color: ColorRef,
    },
    Foreground {
        color: ColorRef,
    },
    Border {
        color: ColorRef,
        width: f64,
    },
    Corner {
        radius: f64,
    },
    Padding {
        length: f64,
    },
    Size {
        size: ControlSize,
    },
    /// A selected item filled with `color`; its text and icons use the
    /// color's foreground pair.
    Fill {
        color: ColorRef,
    },
    /// A selected item marked by a bar on one edge.
    Indicator {
        color: ColorRef,
        edge: Edge,
        width: f64,
    },
    Scale {
        x: f64,
        y: f64,
        motion: String,
    },
    Offset {
        x: f64,
        y: f64,
        motion: String,
    },
    Opacity {
        value: f64,
        motion: String,
    },
    /// A shadow below the control, as if lifted off the page: `radius` of
    /// blur, `y` down, black at `opacity`.
    Shadow {
        radius: f64,
        y: f64,
        opacity: f64,
    },
    /// The platform's own look for this state.
    System,
    /// No feedback in this state.
    Nothing,
    /// A length the element writes, replaced for the platforms the rule
    /// applies to; `None` drops a written width or height, so the element
    /// takes its content's.
    Metric {
        metric: Metric,
        value: Option<f64>,
    },
}

/// The lengths a style may set in place of those an element writes: a
/// row's or column's spacing, a container's padding and size, a control's
/// text or symbol size.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Metric {
    Gap,
    PaddingX,
    PaddingY,
    Width,
    Height,
    FontSize,
    RowHeight,
}

impl Metric {
    pub const ALL: [Metric; 7] = [
        Metric::Gap,
        Metric::PaddingX,
        Metric::PaddingY,
        Metric::Width,
        Metric::Height,
        Metric::FontSize,
        Metric::RowHeight,
    ];

    /// The property's name, in `style!` and on the element.
    pub fn name(self) -> &'static str {
        match self {
            Metric::Gap => "gap",
            Metric::PaddingX => "padding_x",
            Metric::PaddingY => "padding_y",
            Metric::Width => "width",
            Metric::Height => "height",
            Metric::FontSize => "font_size",
            Metric::RowHeight => "row_height",
        }
    }
}

impl StyleEffect {
    /// The effect's name in `style!` and in target capabilities.
    pub fn name(&self) -> &'static str {
        match self {
            StyleEffect::Background { .. } => "background",
            StyleEffect::Foreground { .. } => "foreground",
            StyleEffect::Border { .. } => "border",
            StyleEffect::Corner { .. } => "corner",
            StyleEffect::Padding { .. } => "padding",
            StyleEffect::Size { .. } => "size",
            StyleEffect::Fill { .. } => "fill",
            StyleEffect::Indicator { .. } => "indicator",
            StyleEffect::Scale { .. } => "scale",
            StyleEffect::Offset { .. } => "offset",
            StyleEffect::Opacity { .. } => "opacity",
            StyleEffect::Shadow { .. } => "shadow",
            StyleEffect::System => "system",
            StyleEffect::Nothing => "none",
            StyleEffect::Metric { metric, .. } => metric.name(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ColorRef {
    Role { role: String },
    Fixed { light: Srgb, dark: Srgb },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ControlSize {
    Small,
    Regular,
    Large,
    ExtraLarge,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Edge {
    Leading,
    Trailing,
    Top,
    Bottom,
}