blinc_layout 0.5.0

Blinc layout engine - Flexbox layout powered by Taffy
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
//! Block-level transformations on `RichDocument`.
//!
//! These are pure functions over `&mut RichDocument` (mirroring the
//! style of `edit.rs` and `format.rs`) that change the *kind* or
//! *indent* of one or more blocks. Cursor / selection / undo are the
//! editor's job — these ops don't touch them.
//!
//! Block kind ops support a *toggle* convention: applying a kind that
//! every block in the range already has reverts those blocks to
//! plain `Paragraph`. Otherwise the kind is set on every block in
//! the range, regardless of what they were before. This matches the
//! "click bold while everything is bold → unbold" pattern from
//! inline marks.

use crate::styled_text::StyledLine;

use super::cursor::{DocPosition, Selection};
use super::document::{char_to_byte, Block, BlockKind, RichDocument};
use super::edit::split_spans;

// =============================================================================
// Public API
// =============================================================================

/// Translate a `Selection` into the inclusive `[first_block, last_block]`
/// range that block-level operations should touch.
///
/// Trims a trailing block when the selection ends *exactly* at its
/// first column (`end.line == 0 && end.col == 0`) and the start lies
/// in an earlier block — that endpoint is the cursor "sitting at the
/// start of the next block", which is the standard editor convention
/// for "the next block was not actually selected, only crossed into".
/// Without this trim, dragging slightly past the end of one paragraph
/// silently converts the next paragraph too.
fn block_range(start: DocPosition, end: DocPosition, doc_len: usize) -> Option<(usize, usize)> {
    if doc_len == 0 {
        return None;
    }
    let last = doc_len - 1;
    let first_block = start.block.min(last);
    let mut last_block = end.block.min(last);
    if last_block > first_block && end.line == 0 && end.col == 0 {
        last_block -= 1;
    }
    Some((first_block, last_block))
}

/// Set every block touched by `range` to `kind`.
///
/// `range` is a `Selection`; if collapsed, only the block containing
/// the cursor is affected. Returns `true` if any block actually
/// changed (kind differed before).
///
/// For toggle behaviour (revert to `Paragraph` when every block in
/// the range already has the requested kind), use [`toggle_block_kind`].
pub fn set_block_kind(doc: &mut RichDocument, range: Selection, kind: BlockKind) -> bool {
    let (start, end) = range.ordered();
    let Some((first, last)) = block_range(start, end, doc.blocks.len()) else {
        return false;
    };
    let mut changed = false;
    for idx in first..=last {
        let Some(block) = doc.blocks.get_mut(idx) else {
            break;
        };
        if block.kind != kind {
            block.kind = kind.clone();
            // Headings have no indent; clear it so they don't visually
            // hang from a previous list level.
            if matches!(kind, BlockKind::Heading(_)) {
                block.indent = 0;
            }
            changed = true;
        }
    }
    changed
}

/// Toggle every block touched by `range` to `kind`.
///
/// If every block in `range` already has `kind`, all of them revert
/// to `BlockKind::Paragraph`. Otherwise every block in `range` is
/// set to `kind` (whatever its previous kind was).
pub fn toggle_block_kind(doc: &mut RichDocument, range: Selection, kind: BlockKind) -> bool {
    let (start, end) = range.ordered();
    let Some((first, last)) = block_range(start, end, doc.blocks.len()) else {
        return false;
    };
    let mut all_already = true;
    let mut any = false;
    for idx in first..=last {
        if let Some(block) = doc.blocks.get(idx) {
            any = true;
            if !block_kind_eq(&block.kind, &kind) {
                all_already = false;
            }
        }
    }
    if !any {
        return false;
    }
    let target = if all_already {
        BlockKind::Paragraph
    } else {
        kind
    };
    set_block_kind(doc, range, target)
}

/// Increase the `indent` of every block touched by `range` by one.
///
/// Headings, dividers, and quotes are skipped — only paragraphs and
/// list items support indent. Indent is capped at `u8::MAX`.
pub fn indent_blocks(doc: &mut RichDocument, range: Selection) -> bool {
    let (start, end) = range.ordered();
    let Some((first, last)) = block_range(start, end, doc.blocks.len()) else {
        return false;
    };
    let mut changed = false;
    for idx in first..=last {
        let Some(block) = doc.blocks.get_mut(idx) else {
            break;
        };
        if !block_supports_indent(&block.kind) {
            continue;
        }
        let next = block.indent.saturating_add(1);
        if next != block.indent {
            block.indent = next;
            changed = true;
        }
    }
    changed
}

/// Decrease the `indent` of every block touched by `range` by one.
/// Stops at 0 (no underflow).
pub fn outdent_blocks(doc: &mut RichDocument, range: Selection) -> bool {
    let (start, end) = range.ordered();
    let Some((first, last)) = block_range(start, end, doc.blocks.len()) else {
        return false;
    };
    let mut changed = false;
    for idx in first..=last {
        let Some(block) = doc.blocks.get_mut(idx) else {
            break;
        };
        if !block_supports_indent(&block.kind) {
            continue;
        }
        if block.indent > 0 {
            block.indent -= 1;
            changed = true;
        }
    }
    changed
}

/// Apply `kind` to the text covered by `range` by splitting the
/// containing block at the selection boundaries.
///
/// This is the "make this selected text a heading" op the toolbar's
/// heading picker uses. Block-level kinds (heading, quote, list item)
/// are inherently per-block, so the only way to make *part* of a
/// paragraph a heading is to break the paragraph into pieces:
///
/// - **Prefix** (text before the selection) keeps the original kind.
/// - **Middle** (selected text) becomes a new block with `kind`.
/// - **Suffix** (text after the selection) keeps the original kind.
///
/// Empty halves are skipped, so a selection that starts at column 0
/// produces no prefix block and a selection that runs to the end of a
/// line produces no suffix block.
///
/// Returns the index of the new "middle" block on success — the caller
/// uses this to position the cursor inside the converted text. Returns
/// `None` (without mutating the document) when the operation falls
/// back to a whole-block conversion via [`set_block_kind`]:
///
/// - the selection is collapsed (no text to convert),
/// - the selection spans more than one block,
/// - the selection's anchor block has multiple soft-broken lines or
///   the selection crosses a soft break (we don't try to splice across
///   soft breaks — fall back to whole-block conversion instead),
/// - the selection covers the entire line (a split would produce one
///   block anyway, so just convert kind in place).
///
/// In all fall-back cases the document IS still updated to reflect the
/// requested kind change; only the *split* is skipped, so callers can
/// still treat a `None` return as "the requested change was applied".
pub fn convert_selection_to_block(
    doc: &mut RichDocument,
    range: Selection,
    kind: BlockKind,
) -> Option<usize> {
    let (start, end) = range.ordered();

    // Cases that fall back to whole-block conversion.
    if start == end || start.block != end.block || start.line != end.line {
        set_block_kind(doc, range, kind);
        return None;
    }

    let block_idx = start.block;
    let block = doc.blocks.get(block_idx)?.clone();

    // Don't try to splice across soft breaks — keep the implementation
    // simple and just convert the whole block.
    if block.lines.len() != 1 {
        set_block_kind(doc, range, kind);
        return None;
    }
    let line = &block.lines[0];
    let line_len = line.text.chars().count();

    // Selection covers the entire line — no split needed; just
    // convert the kind directly.
    if start.col == 0 && end.col >= line_len {
        set_block_kind(doc, range, kind);
        return None;
    }

    let start_byte = char_to_byte(&line.text, start.col);
    let end_byte = char_to_byte(&line.text, end.col);
    let prefix_text = line.text[..start_byte].to_string();
    let middle_text = line.text[start_byte..end_byte].to_string();
    let suffix_text = line.text[end_byte..].to_string();

    let (prefix_spans, rest_spans) = split_spans(&line.spans, start_byte);
    let middle_local_end = end_byte - start_byte;
    let (middle_spans, suffix_spans) = split_spans(&rest_spans, middle_local_end);

    let original_kind = block.kind.clone();
    let original_indent = block.indent;
    // Headings have no indent — they should never visually hang from
    // the parent block's list level.
    let middle_indent = if matches!(kind, BlockKind::Heading(_)) {
        0
    } else {
        original_indent
    };

    let mut replacement: Vec<Block> = Vec::with_capacity(3);
    let mut middle_offset = 0usize;
    if !prefix_text.is_empty() {
        replacement.push(Block {
            kind: original_kind.clone(),
            lines: vec![StyledLine {
                text: prefix_text,
                spans: prefix_spans,
            }],
            indent: original_indent,
        });
        middle_offset = 1;
    }
    replacement.push(Block {
        kind: kind.clone(),
        lines: vec![StyledLine {
            text: middle_text,
            spans: middle_spans,
        }],
        indent: middle_indent,
    });
    if !suffix_text.is_empty() {
        replacement.push(Block {
            kind: original_kind,
            lines: vec![StyledLine {
                text: suffix_text,
                spans: suffix_spans,
            }],
            indent: original_indent,
        });
    }

    doc.blocks.splice(block_idx..=block_idx, replacement);
    Some(block_idx + middle_offset)
}

/// Insert a new horizontal divider block immediately after `block_idx`,
/// followed by a fresh empty paragraph (so the user has a place for
/// the cursor to land after the divider).
///
/// Returns the index of the new paragraph block.
pub fn insert_divider_after(doc: &mut RichDocument, block_idx: usize) -> usize {
    let insert_at = (block_idx + 1).min(doc.blocks.len());
    doc.blocks.insert(insert_at, Block::divider());
    let paragraph_at = insert_at + 1;
    doc.blocks.insert(paragraph_at, Block::paragraph_empty());
    paragraph_at
}

// =============================================================================
// Internals
// =============================================================================

fn block_supports_indent(kind: &BlockKind) -> bool {
    matches!(
        kind,
        BlockKind::Paragraph | BlockKind::BulletItem | BlockKind::NumberedItem
    )
}

fn block_kind_eq(a: &BlockKind, b: &BlockKind) -> bool {
    match (a, b) {
        (BlockKind::Paragraph, BlockKind::Paragraph) => true,
        (BlockKind::Heading(x), BlockKind::Heading(y)) => x == y,
        (BlockKind::BulletItem, BlockKind::BulletItem) => true,
        (BlockKind::NumberedItem, BlockKind::NumberedItem) => true,
        (BlockKind::Quote, BlockKind::Quote) => true,
        (BlockKind::Divider, BlockKind::Divider) => true,
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::super::cursor::DocPosition;
    use super::*;
    use blinc_core::Color;

    fn doc(blocks: Vec<Block>) -> RichDocument {
        RichDocument::from_blocks(blocks)
    }

    /// Build a selection from the start of `b1` to a non-zero column
    /// inside `b2`, so the trim convention (which excludes a trailing
    /// block whose endpoint is exactly its first column) does not kick
    /// in. Most tests want both blocks to be in the operation range.
    fn sel(b1: usize, b2: usize) -> Selection {
        Selection {
            anchor: DocPosition::new(b1, 0, 0),
            // col=1 is enough to mean "really inside b2", even when b1==b2.
            head: DocPosition::new(b2, 0, 1),
        }
    }

    #[test]
    fn set_kind_changes_one_block() {
        let mut d = doc(vec![Block::paragraph("hi", Color::WHITE)]);
        assert!(set_block_kind(&mut d, sel(0, 0), BlockKind::Heading(2)));
        assert_eq!(d.blocks[0].kind, BlockKind::Heading(2));
    }

    #[test]
    fn set_kind_no_op_when_already_matches() {
        let mut d = doc(vec![Block::heading(1, "hi", Color::WHITE)]);
        assert!(!set_block_kind(&mut d, sel(0, 0), BlockKind::Heading(1)));
    }

    #[test]
    fn set_kind_clears_indent_for_heading() {
        let mut blocks = vec![Block::bullet("hi", Color::WHITE)];
        blocks[0].indent = 3;
        let mut d = doc(blocks);
        set_block_kind(&mut d, sel(0, 0), BlockKind::Heading(1));
        assert_eq!(d.blocks[0].indent, 0);
    }

    #[test]
    fn toggle_kind_reverts_to_paragraph_when_all_match() {
        let mut d = doc(vec![
            Block::bullet("a", Color::WHITE),
            Block::bullet("b", Color::WHITE),
        ]);
        toggle_block_kind(&mut d, sel(0, 1), BlockKind::BulletItem);
        assert_eq!(d.blocks[0].kind, BlockKind::Paragraph);
        assert_eq!(d.blocks[1].kind, BlockKind::Paragraph);
    }

    #[test]
    fn toggle_kind_sets_when_some_dont_match() {
        let mut d = doc(vec![
            Block::bullet("a", Color::WHITE),
            Block::paragraph("b", Color::WHITE),
        ]);
        toggle_block_kind(&mut d, sel(0, 1), BlockKind::BulletItem);
        assert_eq!(d.blocks[0].kind, BlockKind::BulletItem);
        assert_eq!(d.blocks[1].kind, BlockKind::BulletItem);
    }

    #[test]
    fn indent_increments_paragraph_and_bullets() {
        let mut d = doc(vec![
            Block::paragraph("a", Color::WHITE),
            Block::bullet("b", Color::WHITE),
            Block::heading(1, "c", Color::WHITE),
        ]);
        indent_blocks(&mut d, sel(0, 2));
        assert_eq!(d.blocks[0].indent, 1);
        assert_eq!(d.blocks[1].indent, 1);
        // Heading is skipped
        assert_eq!(d.blocks[2].indent, 0);
    }

    #[test]
    fn outdent_floors_at_zero() {
        let mut d = doc(vec![Block::paragraph("a", Color::WHITE)]);
        let changed = outdent_blocks(&mut d, sel(0, 0));
        assert!(!changed);
        assert_eq!(d.blocks[0].indent, 0);
    }

    #[test]
    fn outdent_walks_back_one_level() {
        let mut blocks = vec![Block::bullet("a", Color::WHITE)];
        blocks[0].indent = 2;
        let mut d = doc(blocks);
        outdent_blocks(&mut d, sel(0, 0));
        assert_eq!(d.blocks[0].indent, 1);
    }

    #[test]
    fn insert_divider_after_inserts_two_blocks() {
        let mut d = doc(vec![
            Block::paragraph("a", Color::WHITE),
            Block::paragraph("b", Color::WHITE),
        ]);
        let landing = insert_divider_after(&mut d, 0);
        assert_eq!(d.blocks.len(), 4);
        assert_eq!(d.blocks[1].kind, BlockKind::Divider);
        assert_eq!(d.blocks[2].kind, BlockKind::Paragraph);
        assert!(d.blocks[2].is_empty());
        assert_eq!(landing, 2);
        // Original blocks shift / preserve as expected
        assert_eq!(d.blocks[0].lines[0].text, "a");
        assert_eq!(d.blocks[3].lines[0].text, "b");
    }

    #[test]
    fn set_kind_trims_trailing_col_zero_endpoint() {
        // Selection ends at the very start of block 1 — that endpoint
        // is the cursor "sitting at the start of the next paragraph"
        // and should not drag block 1 into the operation. Only block
        // 0 should become a heading.
        let mut d = doc(vec![
            Block::paragraph("first", Color::WHITE),
            Block::paragraph("second", Color::WHITE),
        ]);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 0),
            head: DocPosition::new(1, 0, 0),
        };
        set_block_kind(&mut d, range, BlockKind::Heading(1));
        assert_eq!(d.blocks[0].kind, BlockKind::Heading(1));
        assert_eq!(d.blocks[1].kind, BlockKind::Paragraph);
    }

    #[test]
    fn set_kind_includes_trailing_block_when_endpoint_is_inside_it() {
        // Endpoint at col 1 of block 1 — the user actually entered
        // block 1, so it should be included.
        let mut d = doc(vec![
            Block::paragraph("first", Color::WHITE),
            Block::paragraph("second", Color::WHITE),
        ]);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 0),
            head: DocPosition::new(1, 0, 1),
        };
        set_block_kind(&mut d, range, BlockKind::Heading(1));
        assert_eq!(d.blocks[0].kind, BlockKind::Heading(1));
        assert_eq!(d.blocks[1].kind, BlockKind::Heading(1));
    }

    #[test]
    fn collapsed_selection_at_block_zero_still_affects_block_zero() {
        // Sanity: a collapsed cursor at (0, 0, 0) is NOT a "trailing
        // boundary" — block 0 must still be included.
        let mut d = doc(vec![Block::paragraph("hi", Color::WHITE)]);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 0),
            head: DocPosition::new(0, 0, 0),
        };
        set_block_kind(&mut d, range, BlockKind::Heading(1));
        assert_eq!(d.blocks[0].kind, BlockKind::Heading(1));
    }

    #[test]
    fn convert_selection_splits_into_three_blocks() {
        // "Hello world" with "lo wor" selected (chars 3..9) →
        // ["Hel", "lo wor", "ld"] with the middle as a heading.
        let mut d = doc(vec![Block::paragraph("Hello world", Color::WHITE)]);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 3),
            head: DocPosition::new(0, 0, 9),
        };
        let middle = convert_selection_to_block(&mut d, range, BlockKind::Heading(2));
        assert_eq!(middle, Some(1));
        assert_eq!(d.blocks.len(), 3);
        assert_eq!(d.blocks[0].kind, BlockKind::Paragraph);
        assert_eq!(d.blocks[0].lines[0].text, "Hel");
        assert_eq!(d.blocks[1].kind, BlockKind::Heading(2));
        assert_eq!(d.blocks[1].lines[0].text, "lo wor");
        assert_eq!(d.blocks[2].kind, BlockKind::Paragraph);
        assert_eq!(d.blocks[2].lines[0].text, "ld");
    }

    #[test]
    fn convert_selection_at_block_start_skips_prefix() {
        let mut d = doc(vec![Block::paragraph("Hello world", Color::WHITE)]);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 0),
            head: DocPosition::new(0, 0, 5),
        };
        let middle = convert_selection_to_block(&mut d, range, BlockKind::Heading(1));
        assert_eq!(middle, Some(0));
        assert_eq!(d.blocks.len(), 2);
        assert_eq!(d.blocks[0].kind, BlockKind::Heading(1));
        assert_eq!(d.blocks[0].lines[0].text, "Hello");
        assert_eq!(d.blocks[1].kind, BlockKind::Paragraph);
        assert_eq!(d.blocks[1].lines[0].text, " world");
    }

    #[test]
    fn convert_selection_at_block_end_skips_suffix() {
        let mut d = doc(vec![Block::paragraph("Hello world", Color::WHITE)]);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 6),
            head: DocPosition::new(0, 0, 11),
        };
        let middle = convert_selection_to_block(&mut d, range, BlockKind::Heading(3));
        assert_eq!(middle, Some(1));
        assert_eq!(d.blocks.len(), 2);
        assert_eq!(d.blocks[0].kind, BlockKind::Paragraph);
        assert_eq!(d.blocks[0].lines[0].text, "Hello ");
        assert_eq!(d.blocks[1].kind, BlockKind::Heading(3));
        assert_eq!(d.blocks[1].lines[0].text, "world");
    }

    #[test]
    fn convert_selection_full_line_returns_none_and_converts_in_place() {
        // Selection covers the entire line → no split, just kind change.
        let mut d = doc(vec![Block::paragraph("Hello", Color::WHITE)]);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 0),
            head: DocPosition::new(0, 0, 5),
        };
        let middle = convert_selection_to_block(&mut d, range, BlockKind::Heading(1));
        assert_eq!(middle, None);
        assert_eq!(d.blocks.len(), 1);
        assert_eq!(d.blocks[0].kind, BlockKind::Heading(1));
    }

    #[test]
    fn convert_selection_collapsed_falls_back_to_set_kind() {
        let mut d = doc(vec![Block::paragraph("Hello", Color::WHITE)]);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 2),
            head: DocPosition::new(0, 0, 2),
        };
        let middle = convert_selection_to_block(&mut d, range, BlockKind::Heading(1));
        assert_eq!(middle, None);
        assert_eq!(d.blocks.len(), 1);
        assert_eq!(d.blocks[0].kind, BlockKind::Heading(1));
    }

    #[test]
    fn convert_selection_clears_indent_for_heading_only() {
        // Original block has indent=2; the middle heading should drop
        // to indent=0, but the prefix/suffix paragraphs should keep
        // the original indent.
        let mut blocks = vec![Block::paragraph("Hello world", Color::WHITE)];
        blocks[0].indent = 2;
        let mut d = doc(blocks);
        let range = Selection {
            anchor: DocPosition::new(0, 0, 3),
            head: DocPosition::new(0, 0, 8),
        };
        convert_selection_to_block(&mut d, range, BlockKind::Heading(2));
        assert_eq!(d.blocks[0].indent, 2); // prefix
        assert_eq!(d.blocks[1].indent, 0); // heading
        assert_eq!(d.blocks[2].indent, 2); // suffix
    }

    #[test]
    fn toggle_quote_sets_then_clears() {
        let mut d = doc(vec![Block::paragraph("hi", Color::WHITE)]);
        toggle_block_kind(&mut d, sel(0, 0), BlockKind::Quote);
        assert_eq!(d.blocks[0].kind, BlockKind::Quote);
        toggle_block_kind(&mut d, sel(0, 0), BlockKind::Quote);
        assert_eq!(d.blocks[0].kind, BlockKind::Paragraph);
    }
}