blinc_layout 0.5.1

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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
//! `rich_text_editor(state, theme, content_width)` — interactive editor.
//!
//! Phases 3 + 3.5 + 4 in this file:
//!
//! - Click to place cursor, drag to select, arrow / Home / End nav.
//! - Canvas-based blinking visual cursor (no rebuilds for the blink).
//! - Typing inserts characters at the cursor with the current
//!   `ActiveFormat`; Backspace / Delete / Enter / Shift+Enter all work
//!   as expected. Undo / redo are wired to Cmd-Z / Cmd-Shift-Z and use
//!   a snapshot stack capped at 200 entries.
//!
//! The factory wraps the renderer in a `Stateful` whose rebuild is
//! triggered by a private `version: State<u32>` signal that the click
//! and key handlers bump after every mutation. The Stateful's `on_state`
//! callback re-walks the line geometry index against the current
//! document and emits the cursor / selection overlay.

use std::sync::Arc;

use blinc_core::context_state::BlincContextState;
use blinc_core::{Brush, Color, CornerRadius, DrawContext, Rect, State};

use crate::canvas::{canvas, Canvas, CanvasBounds};
use crate::div::{div, Div, ElementBuilder};
use crate::stateful::{stateful_with_key, NoState};
use crate::widgets::cursor::SharedCursorState;

use super::block_ops::{indent_blocks, outdent_blocks, toggle_block_kind};
use super::cursor::{step_backward, step_forward, DocPosition};
use super::document::BlockKind;
use super::edit::{
    delete_backward, delete_forward, delete_selection, insert_char, insert_text, soft_break,
    split_block,
};
use super::format::{apply_mark_to_selection, Mark};
use super::render::{compute_line_geometry, render_document, RichTextTheme};
use super::state::RichTextState;

/// Build an interactive rich text editor element.
///
/// `state` is an externally-owned `RichTextState` that survives across
/// rebuilds. `theme` controls visual style. `content_width` is the
/// pixel width of the column the document will be rendered into — same
/// caveat as [`render_document`].
///
/// The returned element is a `Stateful` so it can be embedded anywhere
/// a normal element fits. Use a parent with explicit width (e.g. inside
/// a centered column) to control the editor's footprint.
pub fn rich_text_editor(
    state: &RichTextState,
    theme: RichTextTheme,
    content_width: f32,
) -> impl ElementBuilder {
    // Per-editor signal that bumps on every state mutation. The Stateful
    // rebuilds whenever this signal changes, which triggers a fresh
    // line-index computation and a new cursor overlay.
    let blinc = BlincContextState::get();
    let version_key = format!("rich_text_editor:{:p}", Arc::as_ptr(state));
    let version: State<u32> = blinc.use_state_keyed(&version_key, || 0);
    let stateful_key = format!("rich_text_editor_root:{:p}", Arc::as_ptr(state));

    // Pre-populate the line index so the very first frame can already
    // hit-test clicks before any state mutation has happened.
    {
        if let Ok(mut data) = state.lock() {
            let geometry = compute_line_geometry(&data.document, &theme, content_width);
            data.set_line_index(geometry);
        }
    }

    // Clones for the various closures
    let state_for_render = Arc::clone(state);
    let state_for_click = Arc::clone(state);
    let state_for_drag = Arc::clone(state);
    let state_for_key = Arc::clone(state);
    let state_for_text = Arc::clone(state);
    let theme_for_render = theme.clone();
    let version_for_render = version.clone();
    let version_for_click = version.clone();
    let version_for_drag = version.clone();
    let version_for_key = version.clone();
    let version_for_text = version.clone();

    stateful_with_key::<NoState>(&stateful_key)
        .deps([version.signal_id()])
        .on_state(move |_ctx| {
            // Re-walk geometry against the (possibly mutated) document.
            let mut data = state_for_render.lock().unwrap();
            let geometry = compute_line_geometry(&data.document, &theme_for_render, content_width);
            data.set_line_index(geometry);

            // Sync cursor blink state's visibility with focus.
            data.set_cursor_visible(data.focused);

            // Compute the editor's content height from the line index so
            // the cursor canvas can be sized to span every visual line.
            // Without this the canvas defaults to its `h(1.0)` and the
            // cursor bar gets vertically clipped to a 1px dot. We add
            // a small bottom slack so the cursor is visible at the very
            // last line.
            let content_height = data
                .line_index
                .iter()
                .map(|g| g.y + g.height)
                .fold(0.0_f32, f32::max)
                .max(theme_for_render.font_size * theme_for_render.line_height);

            let doc_tree = render_document(&data.document, &theme_for_render, content_width);

            // Selection rectangles (one per visual line). The cursor
            // canvas overlays the entire content rect and is responsible
            // for its own blink animation.
            let mut overlay_children: Vec<Div> = Vec::new();
            if data.focused {
                if let Some(sel) = data.selection {
                    if !sel.is_empty() {
                        overlay_children.extend(selection_rects(&data, sel, &theme_for_render));
                    }
                }
            }

            // Wrap the document in a relative-positioned container so
            // absolute children (cursor / selection) are positioned
            // against the editor's content rect, not the window.
            //
            // The text cursor (`cursor_text`) is set on this inner Div
            // — not on the outer Stateful — because every rebuild
            // replaces the inner Div's RenderProps. Setting it on the
            // outer Stateful would only stick until the first state
            // mutation, after which the rebuilt inner div reverts to
            // the default arrow.
            //
            // The `blinc-rich-text-editor` class is the canonical CSS
            // hook for stylesheet overrides — users can target it via
            // `.blinc-rich-text-editor { … }` in `ctx.add_css(…)` for
            // background, padding, font, etc.
            let mut root = div()
                .w_full()
                .relative()
                .cursor_text()
                .class("blinc-rich-text-editor")
                .child(doc_tree);
            for child in overlay_children {
                root = root.child(child);
            }
            // Cursor canvas spans the entire content rect and reads its
            // (x, y) position from the state on each redraw.
            root = root.child(cursor_overlay_canvas(
                Arc::clone(&state_for_render),
                data.cursor_state.clone(),
                theme_for_render.text,
                content_width,
                content_height,
            ));

            // Floating context toolbar — only shows when the editor is
            // focused and has a non-empty selection. Clear any stale
            // toolbar_rect first so a previous frame's rect doesn't
            // keep blocking clicks after the selection is collapsed.
            data.toolbar_rect = None;
            drop(data);
            if let Some(toolbar) = super::toolbar::selection_toolbar(
                &state_for_render,
                &version_for_render,
                &theme_for_render,
            ) {
                root = root.child(toolbar);
            }
            root
        })
        .w_full()
        .on_mouse_down(move |ctx| {
            let mut data = state_for_click.lock().unwrap();
            data.set_focus(true);
            data.editor_bounds = (
                ctx.bounds_x,
                ctx.bounds_y,
                ctx.bounds_width,
                ctx.bounds_height,
            );

            // Tell the mobile platform runner that the user just tapped
            // the rich-text editor. The tap-generation counter
            // (`focus_tap_generation`) drives scroll-into-view on
            // re-taps and cross-input focus swaps; the
            // generic-editable-node atomic
            // (`set_focused_editable_node`) is what the
            // `RenderTree::scroll_focused_text_input_above_keyboard`
            // helper looks up to find the editor's bounds. Both are
            // populated unconditionally — even when the click ends up
            // being suppressed below for a toolbar button — so the
            // user always sees the keyboard re-engage with the editor.
            //
            // The blur callback captures the editor state so when the
            // user taps outside, `blur_all_text_inputs` can call
            // `set_focus(false)`, which both clears the local
            // `focused` flag AND decrements the global focus count
            // (the global hook lives inside `RichTextEditorState::set_focus`).
            crate::widgets::text_input::bump_focus_tap_generation();
            let blur_state = Arc::clone(&state_for_click);
            crate::widgets::text_input::set_focused_editable_node(
                ctx.node_id,
                Some(Box::new(move || {
                    if let Ok(mut data) = blur_state.lock() {
                        data.set_focus(false);
                    }
                })),
            );

            // A toolbar button just consumed the click — skip cursor
            // placement so we don't collapse the selection underneath.
            // Events dispatch deepest-first, so the button's handler
            // already ran and set this flag before we got here.
            //
            // We can't use a coordinate-based hit test here because
            // bubbling events carry the *button's* local coordinates,
            // not the editor's (Blinc's event router caches
            // `last_hit_local_*` once and forwards them up the chain).
            if data.suppress_next_outer_click {
                data.suppress_next_outer_click = false;
                return;
            }

            // Detect double-click within the standard 400ms window.
            let now = web_time::Instant::now();
            let is_double = data
                .last_click_time
                .map(|t| now.duration_since(t).as_millis() < 400)
                .unwrap_or(false);
            data.last_click_time = Some(now);

            let touch = crate::widgets::text_input::is_touch_input();

            if let Some(pos) = data.position_from_click(ctx.local_x, ctx.local_y) {
                if is_double {
                    // Double-click — select the word under the cursor.
                    if let Some(line) = data
                        .document
                        .blocks
                        .get(pos.block)
                        .and_then(|b| b.lines.get(pos.line))
                    {
                        let (start_col, end_col) =
                            crate::widgets::text_edit::word_at_position(&line.text, pos.col);
                        data.cursor = super::cursor::DocPosition::new(pos.block, pos.line, end_col);
                        data.selection = Some(super::cursor::Selection {
                            anchor: super::cursor::DocPosition::new(pos.block, pos.line, start_col),
                            head: super::cursor::DocPosition::new(pos.block, pos.line, end_col),
                        });
                        data.reset_cursor_blink();
                        if touch {
                            crate::widgets::text_edit::haptic_impact_light();
                            use crate::widgets::text_edit::edit_menu_actions;
                            crate::widgets::text_edit::show_edit_menu(
                                ctx.bounds_x + ctx.local_x,
                                ctx.bounds_y + ctx.local_y,
                                ctx.bounds_x + ctx.local_x,
                                ctx.bounds_y + ctx.local_y,
                                0.0,
                                24.0,
                                edit_menu_actions::CUT
                                    | edit_menu_actions::COPY
                                    | edit_menu_actions::PASTE
                                    | edit_menu_actions::SELECT_ALL,
                            );
                        }
                    }
                } else if touch {
                    // Touch single-tap: position the caret without
                    // starting a selection (touch drag will move it).
                    // Light haptic to mirror UITextField focus feedback.
                    // Also arm the long-press timer for the
                    // press-and-hold edit menu, with a callback that
                    // selects the word under the press position so
                    // long-press matches the double-tap UX above.
                    data.move_cursor(pos, false);
                    crate::widgets::text_edit::haptic_selection();
                    crate::widgets::text_edit::hide_edit_menu();
                    let captured_pos = pos;
                    let state_for_long_press = Arc::clone(&state_for_click);
                    let version_for_long_press = version_for_click.clone();
                    crate::widgets::text_input::arm_long_press_timer(
                        ctx.bounds_x + ctx.local_x,
                        ctx.bounds_y + ctx.local_y,
                        24.0,
                        Some(Box::new(move || {
                            let did_update = {
                                let mut data = match state_for_long_press.lock() {
                                    Ok(d) => d,
                                    Err(_) => return,
                                };
                                if !data.focused {
                                    return;
                                }
                                let line_text = data
                                    .document
                                    .blocks
                                    .get(captured_pos.block)
                                    .and_then(|b| b.lines.get(captured_pos.line))
                                    .map(|l| l.text.clone());
                                let Some(line_text) = line_text else {
                                    return;
                                };
                                let (start_col, end_col) =
                                    crate::widgets::text_edit::word_at_position(
                                        &line_text,
                                        captured_pos.col,
                                    );
                                if start_col == end_col {
                                    return;
                                }
                                data.cursor = super::cursor::DocPosition::new(
                                    captured_pos.block,
                                    captured_pos.line,
                                    end_col,
                                );
                                data.selection = Some(super::cursor::Selection {
                                    anchor: super::cursor::DocPosition::new(
                                        captured_pos.block,
                                        captured_pos.line,
                                        start_col,
                                    ),
                                    head: super::cursor::DocPosition::new(
                                        captured_pos.block,
                                        captured_pos.line,
                                        end_col,
                                    ),
                                });
                                data.reset_cursor_blink();
                                true
                            };
                            if did_update {
                                version_for_long_press
                                    .set(version_for_long_press.get().wrapping_add(1));
                            }
                        })),
                    );
                } else {
                    let extend = ctx.shift;
                    data.move_cursor(pos, extend);
                }
            }
            drop(data);
            version_for_click.set(version_for_click.get().wrapping_add(1));
        })
        .on_drag(move |ctx| {
            let mut data = state_for_drag.lock().unwrap();
            if !data.focused {
                return;
            }
            // Touch drag = move cursor (no selection extension), with
            // a subtle haptic per character boundary.
            // Mouse drag = extend selection from anchor to pointer.
            let touch = crate::widgets::text_input::is_touch_input();
            if let Some(pos) = data.position_from_click(ctx.local_x, ctx.local_y) {
                if touch {
                    // Drift-cancel any armed long-press so a real
                    // cursor drag doesn't also fire the paste menu.
                    crate::widgets::text_input::check_long_press_drift(ctx.mouse_x, ctx.mouse_y);
                    if data.cursor != pos {
                        data.move_cursor(pos, false);
                        crate::widgets::text_edit::haptic_selection();
                    }
                } else {
                    data.move_cursor(pos, true);
                }
            }
            drop(data);
            version_for_drag.set(version_for_drag.get().wrapping_add(1));
        })
        .on_text_input(move |ctx| {
            // Printable characters arrive here (post-IME). The
            // on_key_down handler intentionally doesn't insert anything
            // for typed characters; it only handles editing keys and
            // Cmd-shortcuts.
            let ch: char = match ctx.key_char {
                Some(c) => c,
                None => return,
            };
            // Skip control chars — those come via on_key_down.
            if ch.is_control() {
                return;
            }
            let mut data = state_for_text.lock().unwrap();
            if !data.focused {
                return;
            }
            // If the link prompt is open, route the keystroke into the
            // URL draft instead of inserting into the document.
            if let super::state::PickerState::Link { ref mut draft } = data.picker {
                draft.push(ch);
                drop(data);
                version_for_text.set(version_for_text.get().wrapping_add(1));
                return;
            }
            // If there's a selection, replace it first.
            let mut pos = data.cursor;
            if let Some(sel) = data.selection.take() {
                pos = delete_selection(&mut data.document, sel);
            }
            data.push_undo();
            let fmt = data.active_format.clone();
            let new_pos = insert_char(&mut data.document, pos, ch, &fmt);
            data.set_cursor(new_pos);
            drop(data);
            version_for_text.set(version_for_text.get().wrapping_add(1));
        })
        .on_key_down(move |ctx| {
            let mut data = state_for_key.lock().unwrap();
            if !data.focused {
                return;
            }

            // Link-prompt key handling — Backspace edits the draft,
            // Enter commits, Esc cancels. Other keys fall through so
            // arrow keys still navigate the document underneath.
            if matches!(data.picker, super::state::PickerState::Link { .. }) {
                match ctx.key_code {
                    8 => {
                        // Backspace — pop the last character from the draft
                        if let super::state::PickerState::Link { ref mut draft } = data.picker {
                            draft.pop();
                            drop(data);
                            version_for_key.set(version_for_key.get().wrapping_add(1));
                            return;
                        }
                    }
                    13 => {
                        // Enter — commit the link
                        if let super::state::PickerState::Link { draft } = data.picker.clone() {
                            if !draft.is_empty() {
                                if let Some(sel) = data.selection {
                                    if !sel.is_empty() {
                                        data.push_undo();
                                        super::format::apply_mark_to_selection(
                                            &mut data.document,
                                            sel,
                                            super::format::Mark::Link(Some(draft)),
                                        );
                                    }
                                }
                            }
                            data.picker = super::state::PickerState::None;
                            drop(data);
                            version_for_key.set(version_for_key.get().wrapping_add(1));
                            return;
                        }
                    }
                    27 => {
                        // Esc — cancel the prompt
                        data.picker = super::state::PickerState::None;
                        drop(data);
                        version_for_key.set(version_for_key.get().wrapping_add(1));
                        return;
                    }
                    _ => {}
                }
            }

            let mod_key = ctx.meta || ctx.ctrl;
            let extend = ctx.shift;
            let mut changed = false;

            // Modifier shortcuts first
            if mod_key {
                match ctx.key_code {
                    // Cmd+Z — undo
                    90 if !ctx.shift => {
                        changed |= data.undo();
                    }
                    // Cmd+Shift+Z — redo
                    90 if ctx.shift => {
                        changed |= data.redo();
                    }
                    // Cmd+A — select all
                    65 => {
                        let last_block = data.document.blocks.len().saturating_sub(1);
                        let last_line = data.document.blocks[last_block]
                            .lines
                            .len()
                            .saturating_sub(1);
                        let last_col = data.document.blocks[last_block].lines[last_line]
                            .text
                            .chars()
                            .count();
                        data.selection = Some(super::cursor::Selection {
                            anchor: DocPosition::ZERO,
                            head: DocPosition::new(last_block, last_line, last_col),
                        });
                        data.cursor = DocPosition::new(last_block, last_line, last_col);
                        data.reset_cursor_blink();
                        changed = true;
                    }
                    // Cmd+B — bold
                    66 => {
                        changed |= toggle_mark(&mut data, Mark::Bold);
                    }
                    // Cmd+I — italic
                    73 => {
                        changed |= toggle_mark(&mut data, Mark::Italic);
                    }
                    // Cmd+U — underline
                    85 => {
                        changed |= toggle_mark(&mut data, Mark::Underline);
                    }
                    // Cmd+Shift+X — strikethrough
                    88 if ctx.shift => {
                        changed |= toggle_mark(&mut data, Mark::Strikethrough);
                    }
                    // Cmd+E — inline code
                    69 => {
                        changed |= toggle_mark(&mut data, Mark::Code);
                    }
                    // Cmd+C — copy selected text to system clipboard
                    67 => {
                        if let Some(sel) = data.selection {
                            if !sel.is_empty() {
                                let (s, e) = sel.ordered();
                                let plain = data.document.plain_text_range(s, e);
                                if !plain.is_empty() {
                                    crate::widgets::text_edit::clipboard_write(&plain);
                                }
                            }
                        }
                        // Copy never mutates the document, so we don't
                        // bump the rebuild signal.
                    }
                    // Cmd+X — cut: copy then delete
                    88 if !ctx.shift => {
                        if let Some(sel) = data.selection {
                            if !sel.is_empty() {
                                let (s, e) = sel.ordered();
                                let plain = data.document.plain_text_range(s, e);
                                if !plain.is_empty() {
                                    crate::widgets::text_edit::clipboard_write(&plain);
                                }
                                data.push_undo();
                                data.selection = None;
                                let new_pos = delete_selection(&mut data.document, sel);
                                data.set_cursor(new_pos);
                                changed = true;
                            }
                        }
                    }
                    // Cmd+V — paste: replace selection (if any) with
                    // clipboard text. Newlines in the clipboard become
                    // soft breaks via `insert_text`.
                    86 => {
                        if let Some(text) = crate::widgets::text_edit::clipboard_read() {
                            if !text.is_empty() {
                                data.push_undo();
                                let mut pos = data.cursor;
                                if let Some(sel) = data.selection.take() {
                                    pos = delete_selection(&mut data.document, sel);
                                }
                                let fmt = data.active_format.clone();
                                let new_pos = insert_text(&mut data.document, pos, &text, &fmt);
                                data.set_cursor(new_pos);
                                changed = true;
                            }
                        }
                    }
                    // Cmd+Alt+0 — paragraph
                    48 if ctx.alt => {
                        changed |= apply_block_kind(&mut data, BlockKind::Paragraph);
                    }
                    // Cmd+Alt+1..6 — headings
                    49 if ctx.alt => {
                        changed |= apply_block_kind(&mut data, BlockKind::Heading(1));
                    }
                    50 if ctx.alt => {
                        changed |= apply_block_kind(&mut data, BlockKind::Heading(2));
                    }
                    51 if ctx.alt => {
                        changed |= apply_block_kind(&mut data, BlockKind::Heading(3));
                    }
                    52 if ctx.alt => {
                        changed |= apply_block_kind(&mut data, BlockKind::Heading(4));
                    }
                    53 if ctx.alt => {
                        changed |= apply_block_kind(&mut data, BlockKind::Heading(5));
                    }
                    54 if ctx.alt => {
                        changed |= apply_block_kind(&mut data, BlockKind::Heading(6));
                    }
                    // Cmd+Shift+7 — toggle numbered list
                    55 if ctx.shift => {
                        changed |= apply_block_kind(&mut data, BlockKind::NumberedItem);
                    }
                    // Cmd+Shift+8 — toggle bullet list
                    56 if ctx.shift => {
                        changed |= apply_block_kind(&mut data, BlockKind::BulletItem);
                    }
                    // Cmd+Shift+9 — toggle quote
                    57 if ctx.shift => {
                        changed |= apply_block_kind(&mut data, BlockKind::Quote);
                    }
                    _ => {}
                }
                if changed {
                    drop(data);
                    version_for_key.set(version_for_key.get().wrapping_add(1));
                    return;
                }
            }

            match ctx.key_code {
                // Left
                37 => {
                    if mod_key {
                        // Cmd+Left jumps to start of line
                        let pos = home_of(&data);
                        data.move_cursor(pos, extend);
                        changed = true;
                    } else if let Some(pos) = step_backward(&data.document, data.cursor) {
                        data.move_cursor(pos, extend);
                        changed = true;
                    }
                }
                // Right
                39 => {
                    if mod_key {
                        let pos = end_of(&data);
                        data.move_cursor(pos, extend);
                        changed = true;
                    } else if let Some(pos) = step_forward(&data.document, data.cursor) {
                        data.move_cursor(pos, extend);
                        changed = true;
                    }
                }
                // Up
                38 => {
                    if let Some(pos) = move_vertical(&data, -1) {
                        data.move_cursor(pos, extend);
                        changed = true;
                    }
                }
                // Down
                40 => {
                    if let Some(pos) = move_vertical(&data, 1) {
                        data.move_cursor(pos, extend);
                        changed = true;
                    }
                }
                // Home
                36 => {
                    let pos = home_of(&data);
                    data.move_cursor(pos, extend);
                    changed = true;
                }
                // End
                35 => {
                    let pos = end_of(&data);
                    data.move_cursor(pos, extend);
                    changed = true;
                }
                // Backspace
                8 => {
                    let pos = data.cursor;
                    let sel = data.selection.take();
                    data.push_undo();
                    let new_pos = if let Some(s) = sel {
                        delete_selection(&mut data.document, s)
                    } else {
                        delete_backward(&mut data.document, pos)
                    };
                    data.set_cursor(new_pos);
                    changed = true;
                }
                // Delete (forward)
                127 => {
                    let pos = data.cursor;
                    let sel = data.selection.take();
                    data.push_undo();
                    let new_pos = if let Some(s) = sel {
                        delete_selection(&mut data.document, s)
                    } else {
                        delete_forward(&mut data.document, pos)
                    };
                    data.set_cursor(new_pos);
                    changed = true;
                }
                // Enter — Shift+Enter is a soft break, plain Enter splits the block
                13 => {
                    // Replace selection first
                    let mut pos = data.cursor;
                    if let Some(s) = data.selection.take() {
                        pos = delete_selection(&mut data.document, s);
                    }
                    data.push_undo();
                    let new_pos = if ctx.shift {
                        soft_break(&mut data.document, pos)
                    } else {
                        split_block(&mut data.document, pos)
                    };
                    data.set_cursor(new_pos);
                    changed = true;
                }
                // Escape — blur
                27 => {
                    data.set_focus(false);
                    changed = true;
                }
                // Tab — indent the current block (or selected blocks).
                // Shift+Tab outdents. Only paragraphs and list items
                // are affected; headings, dividers, and quotes are
                // skipped by `indent_blocks` / `outdent_blocks`.
                9 => {
                    let range = block_selection(&data);
                    let did_change = if ctx.shift {
                        data.push_undo();
                        let r = outdent_blocks(&mut data.document, range);
                        if !r {
                            data.undo_stack.pop();
                        }
                        r
                    } else {
                        data.push_undo();
                        let r = indent_blocks(&mut data.document, range);
                        if !r {
                            data.undo_stack.pop();
                        }
                        r
                    };
                    if did_change {
                        let cursor = data.cursor;
                        data.set_cursor(cursor);
                        changed = true;
                    }
                }
                _ => {}
            }

            drop(data);
            if changed {
                version_for_key.set(version_for_key.get().wrapping_add(1));
            }
        })
}

/// Build a `Selection` covering whatever block range the editor's
/// current cursor / selection covers — used by block-level ops that
/// need a range even when the user has no explicit selection.
fn block_selection(data: &super::state::RichTextData) -> super::cursor::Selection {
    if let Some(sel) = data.selection {
        if !sel.is_empty() {
            return sel;
        }
    }
    super::cursor::Selection {
        anchor: data.cursor,
        head: data.cursor,
    }
}

/// Toggle every block in the editor's current cursor range to `kind`.
/// If every block in the range already has `kind`, they all revert
/// to `BlockKind::Paragraph`. Pushes undo before mutating; pops the
/// undo entry if nothing actually changed.
fn apply_block_kind(data: &mut super::state::RichTextData, kind: BlockKind) -> bool {
    let range = block_selection(data);
    data.push_undo();
    let changed = toggle_block_kind(&mut data.document, range, kind);
    if !changed {
        data.undo_stack.pop();
        return false;
    }
    let cursor = data.cursor;
    data.set_cursor(cursor);
    true
}

/// Canvas overlay that draws a blinking cursor at the current document
/// position. The closure reads the cursor geometry from `state` on each
/// frame, so when the editor's content rect is animating (or the cursor
/// blink advances) we don't need a tree rebuild — the canvas redraws
/// itself in place.
fn cursor_overlay_canvas(
    state: RichTextState,
    cursor_state: SharedCursorState,
    color: Color,
    width: f32,
    height: f32,
) -> Canvas {
    canvas(move |ctx: &mut dyn DrawContext, _bounds: CanvasBounds| {
        // Compute opacity from blink state.
        let (opacity, visible) = match cursor_state.lock() {
            Ok(s) => (s.current_opacity(), s.visible),
            Err(_) => (1.0, false),
        };
        if !visible || opacity < 0.01 {
            return;
        }

        let Ok(data) = state.lock() else {
            return;
        };
        if !data.focused {
            return;
        }
        let Some((x, y, h)) = data.cursor_geometry() else {
            return;
        };

        let c = Color::rgba(color.r, color.g, color.b, color.a * opacity);
        ctx.fill_rect(
            Rect::new(x, y, 2.0, h),
            CornerRadius::default(),
            Brush::Solid(c),
        );
    })
    .absolute()
    .left(0.0)
    .top(0.0)
    .w(width)
    .h(height.max(1.0))
}

/// Build absolute-positioned selection rectangles for the given selection.
/// One rect per visual line that the selection covers, sized to the
/// width of the selected text on that line.
fn selection_rects(
    data: &super::state::RichTextData,
    sel: super::cursor::Selection,
    theme: &RichTextTheme,
) -> Vec<Div> {
    let (start, end) = sel.ordered();
    let mut rects = Vec::new();
    let highlight = Color::rgba(theme.text.r, theme.text.g, theme.text.b, 0.18);
    for g in &data.line_index {
        // Determine the [start_col_in_line .. end_col_in_line) range for
        // this visual line in the selection.
        let line_chars = g.total_chars();
        let line_end_col = g.start.col + line_chars;
        let on_block = g.start.block;
        let on_line = g.start.line;

        // Skip lines fully outside the selection.
        let after_start = (on_block, on_line, line_end_col) >= (start.block, start.line, start.col);
        let before_end = (on_block, on_line, g.start.col) <= (end.block, end.line, end.col);
        if !(after_start && before_end) {
            continue;
        }

        // Compute clamped local columns within this visual line.
        let line_start_pos = (on_block, on_line, g.start.col);
        let line_end_pos = (on_block, on_line, line_end_col);
        let sel_start_pos = (start.block, start.line, start.col);
        let sel_end_pos = (end.block, end.line, end.col);

        let sx_global = sel_start_pos.max(line_start_pos);
        let ex_global = sel_end_pos.min(line_end_pos);
        if sx_global >= ex_global {
            continue;
        }
        let local_start = sx_global.2 - g.start.col;
        let local_end = ex_global.2 - g.start.col;

        // Walk runs to find the pixel x for each end of the selection
        // range, measuring each prefix with its run's actual font.
        let start_px = super::state::pixel_x_for_local_col(g, local_start);
        let end_px = super::state::pixel_x_for_local_col(g, local_end);
        let mid_w = end_px - start_px;
        if mid_w <= 0.0 {
            continue;
        }
        rects.push(
            div()
                .absolute()
                .left(g.x + start_px)
                .top(g.y)
                .w(mid_w)
                .h(g.height)
                .bg(highlight),
        );
    }
    rects
}

/// Toggle an inline `mark`.
///
/// - With a non-empty selection, applies the toggle to the selected
///   range via [`apply_mark_to_selection`] and pushes an undo entry.
/// - With no selection, flips the corresponding flag on the cursor's
///   `ActiveFormat` so the next typed character carries the mark.
///   This matches every other rich editor's "click bold then start
///   typing" behaviour.
///
/// Returns `true` if anything changed (selection mark applied OR
/// active-format flag flipped), so the caller knows whether to bump
/// the rebuild signal.
fn toggle_mark(data: &mut super::state::RichTextData, mark: Mark) -> bool {
    if let Some(sel) = data.selection {
        if !sel.is_empty() {
            data.push_undo();
            let changed = apply_mark_to_selection(&mut data.document, sel, mark.clone());
            // Refresh the active format from the cursor location so the
            // toolbar (Phase 7) sees the new state.
            data.active_format =
                super::cursor::ActiveFormat::from_position(&data.document, data.cursor);
            data.reset_cursor_blink();
            return changed;
        }
    }

    // No selection — flip the active format flag in place.
    let fmt = &mut data.active_format;
    match mark {
        Mark::Bold => fmt.bold = !fmt.bold,
        Mark::Italic => fmt.italic = !fmt.italic,
        Mark::Underline => fmt.underline = !fmt.underline,
        Mark::Strikethrough => fmt.strikethrough = !fmt.strikethrough,
        Mark::Code => fmt.code = !fmt.code,
        Mark::Color(c) => fmt.color = Some(c),
        Mark::Link(url) => fmt.link = url,
    }
    data.reset_cursor_blink();
    true
}

/// Move the cursor up (-1) or down (+1) one visual line by stepping in
/// the line-geometry index. Preserves the cursor's column where possible.
fn move_vertical(data: &super::state::RichTextData, dir: i32) -> Option<DocPosition> {
    let cursor = data.cursor;
    // Find the cursor's current visual line in the index.
    let current_idx = data.line_index.iter().position(|g| {
        if g.start.block != cursor.block || g.start.line != cursor.line {
            return false;
        }
        let end_col = g.start.col + g.total_chars();
        cursor.col >= g.start.col && cursor.col <= end_col
    })?;
    let target_idx = if dir < 0 {
        current_idx.checked_sub(1)?
    } else {
        let n = current_idx + 1;
        if n >= data.line_index.len() {
            return None;
        }
        n
    };
    let g = &data.line_index[target_idx];
    let local_col = cursor
        .col
        .saturating_sub(data.line_index[current_idx].start.col);
    let new_col = g.start.col + local_col.min(g.total_chars());
    Some(DocPosition::new(g.start.block, g.start.line, new_col))
}

/// Position at the start of the cursor's current visual line.
fn home_of(data: &super::state::RichTextData) -> DocPosition {
    let cursor = data.cursor;
    for g in &data.line_index {
        if g.start.block == cursor.block && g.start.line == cursor.line {
            let end_col = g.start.col + g.total_chars();
            if cursor.col >= g.start.col && cursor.col <= end_col {
                return DocPosition::new(g.start.block, g.start.line, g.start.col);
            }
        }
    }
    cursor
}

/// Position at the end of the cursor's current visual line.
fn end_of(data: &super::state::RichTextData) -> DocPosition {
    let cursor = data.cursor;
    for g in &data.line_index {
        if g.start.block == cursor.block && g.start.line == cursor.line {
            let end_col = g.start.col + g.total_chars();
            if cursor.col >= g.start.col && cursor.col <= end_col {
                return DocPosition::new(g.start.block, g.start.line, end_col);
            }
        }
    }
    cursor
}