k2f_layout 0.3.3

K2F deterministic layout 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
use crate::list_style::ListStyle;
use crate::style::{apply_patch, resolve_base_style, Style};
use crate::theme::{Theme, ThemeDecoration};
use crate::visual_primitives::EdgeInsetsPt;
use k2f_core::{Align, NodeContent, Pt, SemanticNode};

/// Insets in fixed-point pt units (1/1000 pt).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EdgeInsets {
    pub top: Pt,
    pub right: Pt,
    pub bottom: Pt,
    pub left: Pt,
}

impl EdgeInsets {
    pub const ZERO: EdgeInsets = EdgeInsets {
        top: Pt::ZERO,
        right: Pt::ZERO,
        bottom: Pt::ZERO,
        left: Pt::ZERO,
    };

    pub fn horizontal(self) -> Pt {
        self.left + self.right
    }

    pub fn vertical(self) -> Pt {
        self.top + self.bottom
    }
}

/// Resolve the base text style for a role, then apply any role-variant text overrides.
///
/// Modifiers are applied later by the text run splitting logic.
pub fn resolve_text_style(role: &str, variant: Option<&str>, theme: &Theme) -> Style {
    let mut style = resolve_base_style(role, theme);

    let Some(variant_name) = variant else {
        return style;
    };

    let Some(role_style) = theme.roles.get(role).or_else(|| theme.roles.get("default")) else {
        return style;
    };

    let Some(variant_def) = role_style.variants.get(variant_name) else {
        return style;
    };

    if let Some(patch) = &variant_def.text_overrides {
        style = apply_patch(style, patch);
    }

    style
}

/// Resolve the self-alignment override for a role/variant.
///
/// Returns Some(Align) if the theme explicitly sets it, otherwise None.
pub fn resolve_self_align(role: &str, variant: Option<&str>, theme: &Theme) -> Option<Align> {
    let role_style = theme
        .roles
        .get(role)
        .or_else(|| theme.roles.get("default"))?;

    if let Some(variant_name) = variant {
        if let Some(variant_def) = role_style.variants.get(variant_name) {
            if let Some(sa) = variant_def.self_align {
                return Some(sa);
            }
        }
    }

    role_style.self_align
}

/// Parent align, then role `self_align`. Form fields never stretch: the reserved box is locked.
pub(crate) fn align_for_child(node: &SemanticNode, parent_align: Align, theme: &Theme) -> Align {
    let resolved =
        resolve_self_align(&node.role, node.variant.as_deref(), theme).unwrap_or(parent_align);
    if matches!(node.content, NodeContent::FormField(_)) && resolved == Align::Stretch {
        Align::Start
    } else {
        resolved
    }
}

/// Resolve the box decoration for a role, then apply any role-variant overrides.
///
/// The output is representation-level (it preserves primitive references). Consumers decide
/// when/where to resolve named primitives into concrete paint operations.
pub fn resolve_box_decoration(
    role: &str,
    variant: Option<&str>,
    theme: &Theme,
) -> Option<ThemeDecoration> {
    let role_style = theme
        .roles
        .get(role)
        .or_else(|| theme.roles.get("default"))?;

    let mut decoration = role_style.box_decoration.clone();

    let Some(variant_name) = variant else {
        return decoration;
    };
    let Some(variant_def) = role_style.variants.get(variant_name) else {
        return decoration;
    };
    let Some(variant_decoration) = &variant_def.box_decoration else {
        return decoration;
    };

    match decoration.as_mut() {
        Some(base) => base.merge_from(variant_decoration),
        None => decoration = Some(variant_decoration.clone()),
    }

    decoration
}

/// How an image role maps its bitmap into the laid-out box. Omit = contain.
pub fn resolve_image_fit(role: &str, variant: Option<&str>, theme: &Theme) -> k2f_core::ImageFit {
    use k2f_core::ImageFit;
    let Some(role_style) = theme.roles.get(role).or_else(|| theme.roles.get("default")) else {
        return ImageFit::Contain;
    };
    if let Some(variant_name) = variant {
        if let Some(variant_def) = role_style.variants.get(variant_name) {
            if let Some(fit) = variant_def.image_fit {
                return fit;
            }
        }
    }
    role_style.image_fit.unwrap_or(ImageFit::Contain)
}

/// Resolve list layout tokens for a role, then deterministically apply any role-variant overrides.
pub fn resolve_list_style(role: &str, variant: Option<&str>, theme: &Theme) -> Option<ListStyle> {
    let role_style = theme
        .roles
        .get(role)
        .or_else(|| theme.roles.get("default"))?;

    let base = role_style.list_style.as_ref();
    let variant_overlay = variant.and_then(|name| {
        role_style
            .variants
            .get(name)
            .and_then(|v| v.list_style.as_ref())
    });
    let merged = ListStyle::merged(base, variant_overlay);

    if role == "list_item" {
        ListStyle::merged(Some(&ListStyle::list_item_defaults()), merged.as_ref())
    } else {
        merged
    }
}

/// Extract padding insets for a node-like (role, variant) pair.
pub fn padding_for_role_variant(
    role: &str,
    variant: Option<&str>,
    theme: &Theme,
) -> Result<EdgeInsets, String> {
    let decoration = resolve_box_decoration(role, variant, theme);
    let Some(decoration) = decoration else {
        return Ok(EdgeInsets::ZERO);
    };
    padding_from_decoration(&decoration)
}

pub fn padding_from_decoration(decoration: &ThemeDecoration) -> Result<EdgeInsets, String> {
    let Some(padding) = &decoration.padding_pt else {
        return Ok(EdgeInsets::ZERO);
    };
    edge_insets_from_pt(padding)
}

fn edge_insets_from_pt(insets: &EdgeInsetsPt) -> Result<EdgeInsets, String> {
    let (top, right, bottom, left) = match insets {
        EdgeInsetsPt::Uniform(v) => (*v, *v, *v, *v),
        EdgeInsetsPt::PerEdge {
            top,
            right,
            bottom,
            left,
        } => (*top, *right, *bottom, *left),
    };

    if top < 0 || right < 0 || bottom < 0 || left < 0 {
        return Err("Padding insets must be non-negative".to_string());
    }

    Ok(EdgeInsets {
        top: Pt(top as i128),
        right: Pt(right as i128),
        bottom: Pt(bottom as i128),
        left: Pt(left as i128),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::{RoleStyle, RoleVariant};
    use crate::visual_primitives::EdgeInsetsPt;
    use std::collections::HashMap;

    #[test]
    fn resolves_and_merges_box_decoration_from_role_and_variant() {
        let mut roles = HashMap::new();
        roles.insert(
            "card".to_string(),
            RoleStyle {
                font_family: "default".to_string(),
                font_size: Pt(12_000),
                line_height_mult: 1_200,
                color: "black".to_string(),
                text_align: crate::style::TextAlign::Start,
                self_align: None,
                box_decoration: Some(ThemeDecoration {
                    padding_pt: Some(EdgeInsetsPt::Uniform(4_000)),
                    ..ThemeDecoration::default()
                }),
                list_style: None,
                image_fit: None,
                bold: false,
                italic: false,
                letter_spacing_pt: Pt::ZERO,
                first_line_indent_pt: Pt::ZERO,
                variants: HashMap::from([(
                    "spacious".to_string(),
                    RoleVariant {
                        box_decoration: Some(ThemeDecoration {
                            padding_pt: Some(EdgeInsetsPt::Uniform(10_000)),
                            ..ThemeDecoration::default()
                        }),
                        self_align: None,
                        text_overrides: None,
                        list_style: None,
                        image_fit: None,
                    },
                )]),
            },
        );

        let theme = Theme {
            palette: HashMap::new(),
            primitives: Default::default(),
            roles,
            modifiers: Default::default(),
            font_aliases: HashMap::new(),
            font_faces: HashMap::new(),
        };

        let decoration = resolve_box_decoration("card", Some("spacious"), &theme).unwrap();
        assert_eq!(
            padding_from_decoration(&decoration).unwrap(),
            EdgeInsets {
                top: Pt(10_000),
                right: Pt(10_000),
                bottom: Pt(10_000),
                left: Pt(10_000),
            }
        );
    }

    #[test]
    fn resolves_and_merges_list_style_from_role_and_variant() {
        use crate::list_style::ListStyle;

        let mut roles = HashMap::new();
        roles.insert(
            "list_item".to_string(),
            RoleStyle {
                font_family: "default".to_string(),
                font_size: Pt(12_000),
                line_height_mult: 1_200,
                color: "black".to_string(),
                text_align: crate::style::TextAlign::Start,
                self_align: None,
                box_decoration: None,
                list_style: Some(ListStyle {
                    marker_box_width_pt: Some(Pt(18_000)),
                    marker_gap_pt: Some(Pt(4_000)),
                    ..ListStyle::default()
                }),
                image_fit: None,
                bold: false,
                italic: false,
                letter_spacing_pt: Pt::ZERO,
                first_line_indent_pt: Pt::ZERO,
                variants: HashMap::from([(
                    "compact".to_string(),
                    RoleVariant {
                        box_decoration: None,
                        self_align: None,
                        text_overrides: None,
                        list_style: Some(ListStyle {
                            marker_gap_pt: Some(Pt(2_000)),
                            bullet_glyph: Some("*".to_string()),
                            ..ListStyle::default()
                        }),
                        image_fit: None,
                    },
                )]),
            },
        );

        let theme = Theme {
            palette: HashMap::new(),
            primitives: Default::default(),
            roles,
            modifiers: Default::default(),
            font_aliases: HashMap::new(),
            font_faces: HashMap::new(),
        };

        let resolved = resolve_list_style("list_item", Some("compact"), &theme).unwrap();
        assert_eq!(resolved.marker_box_width_pt, Some(Pt(18_000)));
        assert_eq!(resolved.marker_gap_pt, Some(Pt(2_000)));
        assert_eq!(resolved.bullet_glyph.as_deref(), Some("*"));
        assert_eq!(
            resolved.depth_indent_pt,
            ListStyle::list_item_defaults().depth_indent_pt
        );
    }

    #[test]
    fn list_item_partial_list_style_merges_defaults() {
        use crate::list_style::ListStyle;

        let mut roles = HashMap::new();
        roles.insert(
            "list_item".to_string(),
            RoleStyle {
                font_family: "default".to_string(),
                font_size: Pt(12_000),
                line_height_mult: 1_200,
                color: "black".to_string(),
                text_align: crate::style::TextAlign::Start,
                self_align: None,
                box_decoration: None,
                list_style: Some(ListStyle {
                    bullet_glyph: Some("•".to_string()),
                    ..ListStyle::default()
                }),
                image_fit: None,
                bold: false,
                italic: false,
                letter_spacing_pt: Pt::ZERO,
                first_line_indent_pt: Pt::ZERO,
                variants: HashMap::new(),
            },
        );
        let theme = Theme {
            palette: HashMap::new(),
            primitives: Default::default(),
            roles,
            modifiers: Default::default(),
            font_aliases: HashMap::new(),
            font_faces: HashMap::new(),
        };
        let resolved = resolve_list_style("list_item", None, &theme).unwrap();
        let defaults = ListStyle::list_item_defaults();
        assert_eq!(resolved.bullet_glyph.as_deref(), Some("•"));
        assert_eq!(resolved.marker_box_width_pt, defaults.marker_box_width_pt);
        assert_eq!(resolved.marker_gap_pt, defaults.marker_gap_pt);
        assert_eq!(resolved.depth_indent_pt, defaults.depth_indent_pt);
    }

    #[test]
    fn image_fit_variant_cover_overrides_role() {
        use k2f_core::ImageFit;

        let mut roles = HashMap::new();
        roles.insert(
            "image".to_string(),
            RoleStyle {
                font_family: "default".to_string(),
                font_size: Pt(12_000),
                line_height_mult: 1_200,
                color: "black".to_string(),
                image_fit: Some(ImageFit::Contain),
                variants: HashMap::from([(
                    "cover".to_string(),
                    RoleVariant {
                        image_fit: Some(ImageFit::Cover),
                        ..Default::default()
                    },
                )]),
                ..Default::default()
            },
        );
        let theme = Theme {
            roles,
            ..Default::default()
        };
        assert_eq!(resolve_image_fit("image", None, &theme), ImageFit::Contain);
        assert_eq!(
            resolve_image_fit("image", Some("cover"), &theme),
            ImageFit::Cover
        );
        assert_eq!(
            resolve_image_fit("image", Some("missing"), &theme),
            ImageFit::Contain
        );
    }
}