cotis-layout 0.1.0-alpha

Flexbox-style layout engine for Cotis
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
use crate::layout_algorithm::axis_utils::Axis;
use crate::layout_struct::layout_states::{ChildWrapping, LayoutElement, LayoutElementInfo};
use crate::layout_struct::layout_tree::{LayoutTreeCursor, LayoutTreeNodeLocalMut};
use cotis_defaults::element_configs::style::types::{
    FloatingAttachPointType, LayoutAlignmentX, LayoutAlignmentY, LayoutDirection,
};

pub(crate) fn calculate_child_positions(local: &mut LayoutTreeCursor) {
    {
        let mut local = local.get_local_mut();
        if local.self_element.config.layout.layout_direction == LayoutDirection::LeftToRight {
            layout_ltr(&mut local);
        } else {
            layout_ttb(&mut local);
        }
    }
    for child in local.get_all_child_ids() {
        calculate_child_positions(&mut local.get_child_cursor(child).unwrap());
    }
}

fn layout_ltr(local: &mut LayoutTreeNodeLocalMut<'_>) {
    if local.self_element.config.layout.wrapping == ChildWrapping::Text {
        layout_ltr_wrapped(local);
        return;
    }

    let (px, py, pw, _ph) = parent_rect(local.self_element);
    let pad = local.self_element.config.layout.padding;
    let gap = local.self_element.config.layout.child_gap as f32;
    let x_off = clip_x_off(local.self_element);
    let y_off = clip_y_off(local.self_element);
    let parent_h = local
        .self_element
        .info
        .get_final_height()
        .expect("parent must have final height");

    match local.self_element.config.layout.child_alignment.x {
        LayoutAlignmentX::Left => {
            sequence_forward(
                &mut local.children_elements,
                PhysicalAxis::X,
                px,
                py,
                pw,
                parent_h,
                px + pad.left + x_off,
                gap,
            );
        }
        LayoutAlignmentX::Right => {
            sequence_backward(
                &mut local.children_elements,
                PhysicalAxis::X,
                px,
                py,
                pw,
                parent_h,
                px + pw - pad.right + x_off,
                gap,
            );
        }
        LayoutAlignmentX::Center => {
            let lead = local.free_space_axis(Axis::Width) / 2.0;
            sequence_forward(
                &mut local.children_elements,
                PhysicalAxis::X,
                px,
                py,
                pw,
                parent_h,
                px + lead + pad.left + x_off,
                gap,
            );
        }
    }

    match local.self_element.config.layout.child_alignment.y {
        LayoutAlignmentY::Top => {
            cross_fixed_start(
                &mut local.children_elements,
                PhysicalAxis::Y,
                px,
                py,
                pw,
                parent_h,
                py + pad.top + y_off,
            );
        }
        LayoutAlignmentY::Bottom => {
            cross_align_end(
                &mut local.children_elements,
                PhysicalAxis::Y,
                px,
                py,
                pw,
                parent_h,
                py + parent_h - pad.bottom + y_off,
            );
        }
        LayoutAlignmentY::Center => {
            let inner = parent_h - local.self_element.internal_space_height();
            cross_center_each(
                &mut local.children_elements,
                PhysicalAxis::Y,
                px,
                py,
                pw,
                parent_h,
                inner,
                py,
                pad.top,
                y_off,
            );
        }
    }
}

/// `ChildWrapping::Text` on an LTR row: break lines like [`crate::layout_algorithm::wrapping::wrap_elements_left_to_right`], then set child x/y.
fn layout_ltr_wrapped(local: &mut LayoutTreeNodeLocalMut<'_>) {
    let (px, py, pw, _) = parent_rect(local.self_element);
    let pad = local.self_element.config.layout.padding;
    let gap = local.self_element.config.layout.child_gap as f32;
    let x_off = clip_x_off(local.self_element);
    let y_off = clip_y_off(local.self_element);
    let parent_h = local
        .self_element
        .info
        .get_final_height()
        .expect("parent must have final height");

    let content_left = px + pad.left + x_off;
    let content_right = px + pw - pad.right + x_off;
    let content_width = (content_right - content_left).max(0.0);

    let children = &mut local.children_elements;

    for child in children.iter_mut() {
        if child.config.floating.config.is_some() {
            try_float_x(child, px, pw);
            try_float_y(child, py, parent_h);
        }
    }

    let in_flow: Vec<usize> = children
        .iter()
        .enumerate()
        .filter(|(_, c)| c.config.floating.config.is_none())
        .map(|(i, _)| i)
        .collect();

    let mut lines: Vec<Vec<usize>> = Vec::new();
    let mut current_line: Vec<usize> = Vec::new();
    let mut row_width = 0.0f32;

    for &i in &in_flow {
        let w = children[i].info.get_final_width().expect("child width");
        if current_line.is_empty() {
            current_line.push(i);
            row_width = w;
        } else if row_width + gap + w > content_width {
            lines.push(std::mem::take(&mut current_line));
            current_line.push(i);
            row_width = w;
        } else {
            current_line.push(i);
            row_width += gap + w;
        }
    }
    if !current_line.is_empty() {
        lines.push(current_line);
    }

    if lines.is_empty() {
        return;
    }

    let line_heights: Vec<f32> = lines
        .iter()
        .map(|line| wrapped_line_max_height(children.as_mut_slice(), line))
        .collect();

    let lines_inner_height: f32 =
        line_heights.iter().sum::<f32>() + gap * line_heights.len().saturating_sub(1) as f32;

    let inner_h = parent_h - pad.top - pad.bottom;
    let block_start_y = match local.self_element.config.layout.child_alignment.y {
        LayoutAlignmentY::Top => py + pad.top + y_off,
        LayoutAlignmentY::Bottom => py + parent_h - pad.bottom + y_off - lines_inner_height,
        LayoutAlignmentY::Center => py + pad.top + y_off + (inner_h - lines_inner_height) / 2.0,
    };

    let mut line_y = block_start_y;
    for (line_idx, line) in lines.iter().enumerate() {
        let row_h = line_heights[line_idx];
        let used_w = wrapped_line_used_width(children.as_mut_slice(), line, gap);

        let line_start_x = match local.self_element.config.layout.child_alignment.x {
            LayoutAlignmentX::Left => content_left,
            LayoutAlignmentX::Right => content_right - used_w,
            LayoutAlignmentX::Center => content_left + (content_width - used_w) / 2.0,
        };

        let mut cursor_x = line_start_x;
        for &i in line {
            let child = &mut children[i];
            let child_w = child.info.get_final_width().expect("child width");
            let child_h = child.info.get_final_height().expect("child height");
            let y = match local.self_element.config.layout.child_alignment.y {
                LayoutAlignmentY::Top => line_y,
                LayoutAlignmentY::Bottom => line_y + row_h - child_h,
                LayoutAlignmentY::Center => line_y + (row_h - child_h) / 2.0,
            };
            child.info.set_x(cursor_x);
            child.info.set_y(y);
            cursor_x += child_w + gap;
        }

        line_y += row_h + gap;
    }
}

fn wrapped_line_used_width(children: &mut [&mut LayoutElement], line: &[usize], gap: f32) -> f32 {
    if line.is_empty() {
        return 0.0;
    }
    let sum_w: f32 = line
        .iter()
        .map(|&i| children[i].info.get_final_width().expect("child width"))
        .sum();
    sum_w + gap * (line.len().saturating_sub(1) as f32)
}

fn wrapped_line_max_height(children: &mut [&mut LayoutElement], line: &[usize]) -> f32 {
    line.iter()
        .map(|&i| {
            children[i]
                .info
                .get_final_axis(Axis::Height)
                .expect("child min height for wrapped layout")
        })
        .fold(0.0f32, f32::max)
}

fn layout_ttb(local: &mut LayoutTreeNodeLocalMut<'_>) {
    let (px, py, pw, _ph) = parent_rect(local.self_element);
    let pad = local.self_element.config.layout.padding;
    let gap = local.self_element.config.layout.child_gap as f32;
    let x_off = clip_x_off(local.self_element);
    let y_off = clip_y_off(local.self_element);
    let parent_h = local
        .self_element
        .info
        .get_final_height()
        .expect("parent must have final height");

    match local.self_element.config.layout.child_alignment.y {
        LayoutAlignmentY::Top => {
            sequence_forward(
                &mut local.children_elements,
                PhysicalAxis::Y,
                px,
                py,
                pw,
                parent_h,
                py + pad.top + y_off,
                gap,
            );
        }
        LayoutAlignmentY::Bottom => {
            sequence_backward(
                &mut local.children_elements,
                PhysicalAxis::Y,
                px,
                py,
                pw,
                parent_h,
                py + parent_h - pad.bottom + y_off,
                gap,
            );
        }
        LayoutAlignmentY::Center => {
            let lead = local.free_space_axis(Axis::Height) / 2.0;
            sequence_forward(
                &mut local.children_elements,
                PhysicalAxis::Y,
                px,
                py,
                pw,
                parent_h,
                py + lead + pad.top + y_off,
                gap,
            );
        }
    }

    match local.self_element.config.layout.child_alignment.x {
        LayoutAlignmentX::Left => {
            cross_fixed_start(
                &mut local.children_elements,
                PhysicalAxis::X,
                px,
                py,
                pw,
                parent_h,
                px + pad.left + x_off,
            );
        }
        LayoutAlignmentX::Right => {
            cross_align_end(
                &mut local.children_elements,
                PhysicalAxis::X,
                px,
                py,
                pw,
                parent_h,
                px + pw - pad.right + x_off,
            );
        }
        LayoutAlignmentX::Center => {
            let inner = pw - local.self_element.internal_space_width();
            cross_center_each(
                &mut local.children_elements,
                PhysicalAxis::X,
                px,
                py,
                pw,
                parent_h,
                inner,
                px,
                pad.left,
                x_off,
            );
        }
    }
}

/// Horizontal vs vertical coordinate for child placement (distinct from flex [`Axis`]).
#[derive(Clone, Copy)]
enum PhysicalAxis {
    X,
    Y,
}

impl PhysicalAxis {
    fn try_float(
        self,
        child: &mut LayoutElement,
        px: f32,
        py: f32,
        parent_w: f32,
        parent_h: f32,
    ) -> bool {
        match self {
            PhysicalAxis::X => try_float_x(child, px, parent_w),
            PhysicalAxis::Y => try_float_y(child, py, parent_h),
        }
    }

    fn size(self, child: &LayoutElement) -> f32 {
        match self {
            PhysicalAxis::X => child.info.get_final_width().expect("child width"),
            PhysicalAxis::Y => child.info.get_final_height().expect("child height"),
        }
    }

    fn set(self, child: &mut LayoutElement, v: f32) {
        match self {
            PhysicalAxis::X => child.info.set_x(v),
            PhysicalAxis::Y => child.info.set_y(v),
        }
    }
}

fn with_children_order(
    children: &mut Vec<&mut LayoutElement>,
    reverse: bool,
    mut f: impl FnMut(&mut LayoutElement),
) {
    if reverse {
        for c in children.iter_mut().rev() {
            f(*c);
        }
    } else {
        for c in children.iter_mut() {
            f(*c);
        }
    }
}

/// In-flow children placed along the axis from `cursor`, advancing by size + gap (left/top main).
fn sequence_forward(
    children: &mut Vec<&mut LayoutElement>,
    axis: PhysicalAxis,
    px: f32,
    py: f32,
    parent_w: f32,
    parent_h: f32,
    mut cursor: f32,
    gap: f32,
) {
    with_children_order(children, false, |child| {
        if axis.try_float(child, px, py, parent_w, parent_h) {
            return;
        }
        let s = axis.size(child);
        axis.set(child, cursor);
        cursor += s + gap;
    });
}

/// In-flow children packed toward the end edge (right/bottom main), iterating children in reverse order.
fn sequence_backward(
    children: &mut Vec<&mut LayoutElement>,
    axis: PhysicalAxis,
    px: f32,
    py: f32,
    parent_w: f32,
    parent_h: f32,
    mut cursor: f32,
    gap: f32,
) {
    with_children_order(children, true, |child| {
        if axis.try_float(child, px, py, parent_w, parent_h) {
            return;
        }
        let s = axis.size(child);
        axis.set(child, cursor - s);
        cursor -= s + gap;
    });
}

/// Same coordinate for every in-flow child (e.g. top-aligned or left-aligned cross axis).
fn cross_fixed_start(
    children: &mut Vec<&mut LayoutElement>,
    axis: PhysicalAxis,
    px: f32,
    py: f32,
    parent_w: f32,
    parent_h: f32,
    coord: f32,
) {
    with_children_order(children, false, |child| {
        if axis.try_float(child, px, py, parent_w, parent_h) {
            return;
        }
        axis.set(child, coord);
    });
}

/// Align outer edge to `end` (bottom or right inner edge).
fn cross_align_end(
    children: &mut Vec<&mut LayoutElement>,
    axis: PhysicalAxis,
    px: f32,
    py: f32,
    parent_w: f32,
    parent_h: f32,
    end: f32,
) {
    with_children_order(children, true, |child| {
        if axis.try_float(child, px, py, parent_w, parent_h) {
            return;
        }
        let s = axis.size(child);
        axis.set(child, end - s);
    });
}

/// Center each child in the content box: `origin + (inner - size) / 2 + pad_start + clip_off`.
fn cross_center_each(
    children: &mut Vec<&mut LayoutElement>,
    axis: PhysicalAxis,
    px: f32,
    py: f32,
    parent_w: f32,
    parent_h: f32,
    inner: f32,
    origin: f32,
    pad_start: f32,
    clip_off: f32,
) {
    with_children_order(children, false, |child| {
        if axis.try_float(child, px, py, parent_w, parent_h) {
            return;
        }
        let s = axis.size(child);
        let half = (inner - s) / 2.0;
        axis.set(child, origin + half + pad_start + clip_off);
    });
}

fn parent_rect(parent: &LayoutElement) -> (f32, f32, f32, f32) {
    match &parent.info {
        LayoutElementInfo::TotalSizedAndPosition(p) => (p.x, p.y, p.width, p.height),
        _ => panic!("tried using parent without position"),
    }
}

fn clip_x_off(parent: &LayoutElement) -> f32 {
    if parent.config.clip.horizontal {
        parent.config.clip.offset.x
    } else {
        0.0
    }
}

fn clip_y_off(parent: &LayoutElement) -> f32 {
    if parent.config.clip.vertical {
        parent.config.clip.offset.y
    } else {
        0.0
    }
}

fn try_float_x(child: &mut LayoutElement, parent_x: f32, parent_w: f32) -> bool {
    if let Some(cfg) = &child.config.floating.config {
        let child_w = child.info.get_final_width().expect("child width");
        let anchor_x = floating_anchor_x(parent_x, parent_w, cfg.attach_point);
        let child_anchor_x = floating_child_anchor_x(child_w, cfg.attach_point);
        child.info.set_x(anchor_x - child_anchor_x + cfg.offset.x);
        true
    } else {
        false
    }
}

fn try_float_y(child: &mut LayoutElement, parent_y: f32, parent_h: f32) -> bool {
    if let Some(cfg) = &child.config.floating.config {
        let child_h = child.info.get_final_height().expect("child height");
        let anchor_y = floating_anchor_y(parent_y, parent_h, cfg.attach_point);
        let child_anchor_y = floating_child_anchor_y(child_h, cfg.attach_point);
        child.info.set_y(anchor_y - child_anchor_y + cfg.offset.y);
        true
    } else {
        false
    }
}

fn floating_anchor_x(parent_x: f32, parent_w: f32, attach: FloatingAttachPointType) -> f32 {
    match attach {
        FloatingAttachPointType::LeftTop
        | FloatingAttachPointType::LeftCenter
        | FloatingAttachPointType::LeftBottom => parent_x,
        FloatingAttachPointType::CenterTop
        | FloatingAttachPointType::CenterCenter
        | FloatingAttachPointType::CenterBottom => parent_x + parent_w / 2.0,
        FloatingAttachPointType::RightTop
        | FloatingAttachPointType::RightCenter
        | FloatingAttachPointType::RightBottom => parent_x + parent_w,
    }
}

fn floating_anchor_y(parent_y: f32, parent_h: f32, attach: FloatingAttachPointType) -> f32 {
    match attach {
        FloatingAttachPointType::LeftTop
        | FloatingAttachPointType::CenterTop
        | FloatingAttachPointType::RightTop => parent_y,
        FloatingAttachPointType::LeftCenter
        | FloatingAttachPointType::CenterCenter
        | FloatingAttachPointType::RightCenter => parent_y + parent_h / 2.0,
        FloatingAttachPointType::LeftBottom
        | FloatingAttachPointType::CenterBottom
        | FloatingAttachPointType::RightBottom => parent_y + parent_h,
    }
}

fn floating_child_anchor_x(child_w: f32, attach: FloatingAttachPointType) -> f32 {
    match attach {
        FloatingAttachPointType::LeftTop
        | FloatingAttachPointType::LeftCenter
        | FloatingAttachPointType::LeftBottom => 0.0,
        FloatingAttachPointType::CenterTop
        | FloatingAttachPointType::CenterCenter
        | FloatingAttachPointType::CenterBottom => child_w / 2.0,
        FloatingAttachPointType::RightTop
        | FloatingAttachPointType::RightCenter
        | FloatingAttachPointType::RightBottom => child_w,
    }
}

fn floating_child_anchor_y(child_h: f32, attach: FloatingAttachPointType) -> f32 {
    match attach {
        FloatingAttachPointType::LeftTop
        | FloatingAttachPointType::CenterTop
        | FloatingAttachPointType::RightTop => 0.0,
        FloatingAttachPointType::LeftCenter
        | FloatingAttachPointType::CenterCenter
        | FloatingAttachPointType::RightCenter => child_h / 2.0,
        FloatingAttachPointType::LeftBottom
        | FloatingAttachPointType::CenterBottom
        | FloatingAttachPointType::RightBottom => child_h,
    }
}