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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use crate::fixed_size::subtract_if_bounded;
use crate::fixed_size::{apply_fixed_min_outer, fixed_size_hint, inner_max_for_children};
use crate::grid::{resolve_tracks, resolve_tracks_with_intrinsics, sum_with_gaps};
use crate::list_item_measure::list_item_measure_spec;
use crate::resolved_style::padding_for_role_variant;
use crate::text_layout::layout_code_block;
use crate::text_layout::layout_text;
use crate::{LayoutContext, Size, SizeConstraint};
use k2f_core::{GridTrack, LayoutHint, NodeContent, Pt, SemanticNode, StackDirection};

pub fn measure_node(
    node: &SemanticNode,
    constraint: SizeConstraint,
    ctx: &LayoutContext,
) -> Result<Size, String> {
    match &node.content {
        NodeContent::Text(text) => measure_text(text, node, constraint, ctx),
        NodeContent::CodeBlock(code) => measure_code_block(code, node, constraint, ctx),
        NodeContent::Math(tex) => crate::math::measure_math(tex, node, ctx),
        NodeContent::FormField(spec) => {
            crate::form_field::measure_form_field(spec, node, constraint, ctx)
        }
        NodeContent::Image { width, height, .. } => {
            measure_image(*width, *height, node, constraint, ctx)
        }
        NodeContent::Container { children } => measure_container(node, children, constraint, ctx),
        NodeContent::Table(spec) => crate::table::measure_table(node, spec, constraint, ctx),
        NodeContent::TableReference { width, height, .. } => {
            crate::leaf::measure_table_reference(*width, *height, constraint)
        }
    }
}

fn measure_image(
    width: Pt,
    height: Pt,
    node: &SemanticNode,
    constraint: SizeConstraint,
    ctx: &LayoutContext,
) -> Result<Size, String> {
    let padding = padding_for_role_variant(&node.role, node.variant.as_deref(), ctx.theme)?;
    let inner_max = Size::new(
        subtract_if_bounded(constraint.max.width, padding.horizontal()),
        subtract_if_bounded(constraint.max.height, padding.vertical()),
    );
    let inner_constraint = SizeConstraint::new(Size::ZERO, inner_max);
    let inner = crate::leaf::measure_image(width, height, inner_constraint)?;
    Ok(constraint.constrain(Size::new(
        inner.width + padding.horizontal(),
        inner.height + padding.vertical(),
    )))
}

fn measure_code_block(
    code: &k2f_core::CodeBlockValue,
    node: &SemanticNode,
    constraint: SizeConstraint,
    ctx: &LayoutContext,
) -> Result<Size, String> {
    let padding = padding_for_role_variant(&node.role, node.variant.as_deref(), ctx.theme)?;
    let inner_max = Size::new(
        subtract_if_bounded(constraint.max.width, padding.horizontal()),
        subtract_if_bounded(constraint.max.height, padding.vertical()),
    );
    let inner_constraint = SizeConstraint::new(Size::ZERO, inner_max);

    let canonical = code.to_canonical_text();
    let layout = layout_code_block(
        canonical.as_ref(),
        &node.role,
        node.variant.as_deref(),
        &node.modifiers,
        inner_constraint,
        ctx,
    )?;

    Ok(constraint.constrain(Size::new(
        layout.width + padding.horizontal(),
        layout.height + padding.vertical(),
    )))
}

fn measure_text(
    text: &str,
    node: &SemanticNode,
    constraint: SizeConstraint,
    ctx: &LayoutContext,
) -> Result<Size, String> {
    if node.role == "list_item" {
        return measure_list_item_text(text, node, constraint, ctx);
    }

    let padding = padding_for_role_variant(&node.role, node.variant.as_deref(), ctx.theme)?;
    let inner_max = Size::new(
        subtract_if_bounded(constraint.max.width, padding.horizontal()),
        subtract_if_bounded(constraint.max.height, padding.vertical()),
    );
    let inner_constraint = SizeConstraint::new(Size::ZERO, inner_max);
    let layout = if node.role == "code" {
        layout_code_block(
            text,
            &node.role,
            node.variant.as_deref(),
            &node.modifiers,
            inner_constraint,
            ctx,
        )?
    } else {
        layout_text(
            text,
            &node.role,
            node.variant.as_deref(),
            &node.modifiers,
            inner_constraint,
            ctx,
        )
        .map_err(|e| crate::text_layout::tag_node(e, &node.id, &node.role))?
    };
    Ok(constraint.constrain(Size::new(
        layout.width + padding.horizontal(),
        layout.height + padding.vertical(),
    )))
}

fn measure_list_item_text(
    text: &str,
    node: &SemanticNode,
    constraint: SizeConstraint,
    ctx: &LayoutContext,
) -> Result<Size, String> {
    let padding = padding_for_role_variant(&node.role, node.variant.as_deref(), ctx.theme)?;
    let inner_max = Size::new(
        subtract_if_bounded(constraint.max.width, padding.horizontal()),
        subtract_if_bounded(constraint.max.height, padding.vertical()),
    );

    let spec = list_item_measure_spec(node, ctx)?;
    let leading = spec.leading_width();

    let wrap_w = subtract_if_bounded(inner_max.width, leading);
    let inner_constraint = SizeConstraint::new(Size::ZERO, Size::new(wrap_w, inner_max.height));

    let layout = layout_text(
        text,
        &node.role,
        node.variant.as_deref(),
        &node.modifiers,
        inner_constraint,
        ctx,
    )
    .map_err(|e| crate::text_layout::tag_node(e, &node.id, &node.role))?;

    Ok(constraint.constrain(Size::new(
        layout.width + leading + padding.horizontal(),
        layout.height + padding.vertical(),
    )))
}

fn measure_container(
    node: &SemanticNode,
    children: &[SemanticNode],
    constraint: SizeConstraint,
    ctx: &LayoutContext,
) -> Result<Size, String> {
    let padding = padding_for_role_variant(&node.role, node.variant.as_deref(), ctx.theme)?;
    let fixed = fixed_size_hint(&node.layout);
    let inner_max = inner_max_for_children(constraint, padding, fixed);
    let inner_max_w = inner_max.width;
    let inner_max_h = inner_max.height;

    // Default strategy: Vertical Stack
    // Width = Max Child Width
    // Height = Sum Child Heights

    // Overlay container: children are measured independently and placed at the same origin.
    // Container size is the max child width/height (plus padding).
    if matches!(node.layout, Some(LayoutHint::Overlay { .. })) {
        let mut width = Pt::ZERO;
        let mut height = Pt::ZERO;

        let child_constraint = SizeConstraint::new(Size::ZERO, Size::new(inner_max_w, inner_max_h));

        for child in children {
            let child_size = measure_in(child, child_constraint, ctx, node, padding.horizontal())?;
            if child_size.width > width {
                width = child_size.width;
            }
            if child_size.height > height {
                height = child_size.height;
            }
        }

        let measured = Size::new(width + padding.horizontal(), height + padding.vertical());
        return Ok(apply_fixed_min_outer(measured, fixed, constraint));
    }

    // Grid container (pt / fr / auto tracks)
    if let Some(LayoutHint::Grid {
        columns,
        rows,
        gap,
        row_gap,
        column_gap,
        ..
    }) = &node.layout
    {
        let available_w = inner_max_w;
        let available_h = inner_max_h;
        let (row_gap_pt, col_gap_pt) = crate::grid::grid_axis_gaps(*gap, *row_gap, *column_gap);
        let (col_sizes, row_sizes) = grid_track_sizes(
            columns,
            rows,
            col_gap_pt,
            row_gap_pt,
            available_w,
            available_h,
            children,
            ctx,
        )
        .map_err(|e| note_inside(e, node, padding.horizontal()))?;

        let total_w = sum_with_gaps(&col_sizes, col_gap_pt);
        let total_h = sum_with_gaps(&row_sizes, row_gap_pt);

        // Measure children inside their cells. Vertical overflow is a
        // CONTENT_OVERFLOW warning after arrange (slack.rs), not a hard error.
        for (idx, child) in children.iter().enumerate() {
            let c = idx % col_sizes.len();
            let r = idx / col_sizes.len();
            if r >= row_sizes.len() {
                break;
            }
            let cell = Size::new(col_sizes[c], row_sizes[r]);
            let child_constraint = SizeConstraint::new(Size::ZERO, cell);
            let _ = measure_in(child, child_constraint, ctx, node, padding.horizontal())
                .map_err(|e| note_column(e, c, col_sizes[c]))?;
        }

        let measured = Size::new(total_w + padding.horizontal(), total_h + padding.vertical());
        return Ok(apply_fixed_min_outer(measured, fixed, constraint));
    }

    // Continuous multi-column flow: full width, height ≈ ceil(content_h / N).
    if let Some(LayoutHint::Columns { count, gap }) = &node.layout {
        let n = (*count).max(1) as i128;
        let gap_pt = Pt(*gap as i128);
        let tracks: Vec<k2f_core::GridTrack> = (0..*count as usize)
            .map(|_| k2f_core::GridTrack::Fr { fr: 1 })
            .collect();
        let widths = resolve_tracks(&tracks, gap_pt, inner_max_w)?;
        let measure_w = widths.iter().copied().min().unwrap_or(inner_max_w);
        let child_constraint = SizeConstraint::new(Size::ZERO, Size::new(measure_w, Pt(i128::MAX)));
        let mut content_h = Pt::ZERO;
        for child in children {
            content_h +=
                measure_in(child, child_constraint, ctx, node, padding.horizontal())?.height;
        }
        let packed_h = if content_h.0 <= 0 {
            Pt::ZERO
        } else {
            Pt((content_h.0 + n - 1) / n)
        };
        let measured = Size::new(
            inner_max_w + padding.horizontal(),
            packed_h + padding.vertical(),
        );
        return Ok(apply_fixed_min_outer(measured, fixed, constraint));
    }

    // Stack container (vertical or horizontal)
    let (direction, gap) = match &node.layout {
        Some(LayoutHint::Stack { direction, gap, .. }) => (*direction, Pt(*gap as i128)),
        _ => (StackDirection::Vertical, Pt::ZERO),
    };

    match direction {
        StackDirection::Vertical => {
            let mut width = Pt::ZERO;
            let mut height = Pt::ZERO;

            // For vertical stacks: constrain width, leave height unconstrained per child.
            // If a fixed outer height is present, we still use it to bound children deterministically.
            let child_max_h = if fixed.height.is_some() {
                inner_max_h
            } else {
                Pt(i128::MAX)
            };
            let child_constraint =
                SizeConstraint::new(Size::ZERO, Size::new(inner_max_w, child_max_h));

            for (i, child) in children.iter().enumerate() {
                let child_size =
                    measure_in(child, child_constraint, ctx, node, padding.horizontal())?;
                if child_size.width > width {
                    width = child_size.width;
                }
                height += child_size.height;
                if gap != Pt::ZERO && i + 1 < children.len() {
                    height += gap;
                }
            }

            let measured = Size::new(width + padding.horizontal(), height + padding.vertical());
            Ok(apply_fixed_min_outer(measured, fixed, constraint))
        }
        StackDirection::Horizontal => {
            let mut width = Pt::ZERO;
            let mut height = Pt::ZERO;

            // For horizontal stacks: constrain height, leave width unconstrained per child.
            // If a fixed outer width is present, we still use it to bound children deterministically.
            let child_max_w = if fixed.width.is_some() {
                inner_max_w
            } else {
                Pt(i128::MAX)
            };
            let child_constraint =
                SizeConstraint::new(Size::ZERO, Size::new(child_max_w, inner_max_h));

            for (i, child) in children.iter().enumerate() {
                let child_size =
                    measure_in(child, child_constraint, ctx, node, padding.horizontal())?;
                width += child_size.width;
                if child_size.height > height {
                    height = child_size.height;
                }
                if gap != Pt::ZERO && i + 1 < children.len() {
                    width += gap;
                }
            }

            let measured = Size::new(width + padding.horizontal(), height + padding.vertical());
            Ok(apply_fixed_min_outer(measured, fixed, constraint))
        }
    }
}

pub(crate) fn grid_track_sizes(
    columns: &[GridTrack],
    rows: &[GridTrack],
    col_gap: Pt,
    row_gap: Pt,
    available_w: Pt,
    available_h: Pt,
    children: &[SemanticNode],
    ctx: &LayoutContext,
) -> Result<(Vec<Pt>, Vec<Pt>), String> {
    let resolved_rows = k2f_core::grid_rows_for_children(columns, rows, children.len());
    let rows = resolved_rows.as_slice();
    let n_cols = columns.len();
    let n_rows = rows.len();
    if n_cols == 0 || n_rows == 0 {
        return Err("grid requires at least one column and one row".to_string());
    }

    let mut col_auto = vec![Pt::ZERO; n_cols];
    if columns.iter().any(GridTrack::is_auto) {
        for (idx, child) in children.iter().enumerate() {
            let c = idx % n_cols;
            let r = idx / n_cols;
            if r >= n_rows {
                break;
            }
            if !columns[c].is_auto() {
                continue;
            }
            let measured = measure_node(
                child,
                SizeConstraint::new(Size::ZERO, Size::new(available_w, Pt(i128::MAX))),
                ctx,
            )?;
            if measured.width > col_auto[c] {
                col_auto[c] = measured.width;
            }
        }
    }
    let col_sizes = resolve_tracks_with_intrinsics(columns, col_gap, available_w, &col_auto)?;

    let mut row_auto = vec![Pt::ZERO; n_rows];
    if rows.iter().any(GridTrack::is_auto) {
        for (idx, child) in children.iter().enumerate() {
            let c = idx % n_cols;
            let r = idx / n_cols;
            if r >= n_rows {
                break;
            }
            if !rows[r].is_auto() {
                continue;
            }
            let measured = measure_node(
                child,
                SizeConstraint::new(Size::ZERO, Size::new(col_sizes[c], Pt(i128::MAX))),
                ctx,
            )
            .map_err(|e| note_column(e, c, col_sizes[c]))?;
            if measured.height > row_auto[r] {
                row_auto[r] = measured.height;
            }
        }
    }
    let row_sizes = resolve_tracks_with_intrinsics(rows, row_gap, available_h, &row_auto)?;
    Ok((col_sizes, row_sizes))
}

fn measure_in(
    child: &SemanticNode,
    constraint: SizeConstraint,
    ctx: &LayoutContext,
    parent: &SemanticNode,
    pad_h: Pt,
) -> Result<Size, String> {
    measure_node(child, constraint, ctx).map_err(|e| note_inside(e, parent, pad_h))
}

fn note_inside(err: String, node: &SemanticNode, pad_h: Pt) -> String {
    if !err.contains("does not fit") {
        return err;
    }
    let marker = format!("inside '{}'", node.id);
    if err.contains(&marker) {
        return err;
    }
    format!(
        "{err}; inside '{}' (role '{}', horizontal padding {} millipt)",
        node.id, node.role, pad_h.0
    )
}

fn note_column(err: String, column: usize, width: Pt) -> String {
    if !err.contains("does not fit") {
        return err;
    }
    format!("{err}; grid column {column} is {} millipt wide", width.0)
}