strata-editor 0.1.2

Monaco-class interactive code editor and rich-text document engine for Strata UI
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
//! Drop-in interactive Monaco-class `<CodeEditorWidget>` component, reactive `CodeEditorHandle`,
//! and `use_code_editor` hook.
//!
//! Renders a virtualized, fold-aware viewport with line numbers, clickable fold chevrons,
//! diagnostic gutter indicators & inline squiggles, Find & Replace overlay bar, matching
//! bracket highlights, multi-cursor carets & selections, Canvas2D minimap with scrub-to-scroll,
//! Monaco status bar, and full `--strata-editor-*` CSS-variable theming.

#![allow(non_snake_case)]

use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use strata_dom::{
    use_ref, use_signal, Attribute, Event, EventType, NodeBlueprint, Signal, Tag, View,
};
use strata_macro::component;
use strata_render::canvas2d::CanvasCommand;

use crate::code_editor::CodeEditor;
use crate::diagnostics::{DiagnosticCounts, DiagnosticSeverity, EditorDiagnostic};
use crate::minimap::{render_minimap_canvas_commands, MinimapConfig};
use crate::syntax::Language;
use crate::theme::EditorTheme;

/// Visual and behavioral configuration for interactive `<CodeEditorWidget>` rendering.
#[derive(Clone)]
pub struct CodeEditorOptions {
    pub show_line_numbers: bool,
    pub show_fold_gutter: bool,
    pub show_minimap: bool,
    pub show_status_bar: bool,
    pub read_only: bool,
    pub font_size: f32,
    pub line_height: f32,
    pub viewport_height: f32,
    pub minimap: MinimapConfig,
    pub theme: Option<EditorTheme>,
    pub class: String,
    pub on_change: Option<Rc<dyn Fn(String)>>,
}

impl std::fmt::Debug for CodeEditorOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CodeEditorOptions")
            .field("show_line_numbers", &self.show_line_numbers)
            .field("show_fold_gutter", &self.show_fold_gutter)
            .field("show_minimap", &self.show_minimap)
            .field("show_status_bar", &self.show_status_bar)
            .field("read_only", &self.read_only)
            .field("font_size", &self.font_size)
            .field("line_height", &self.line_height)
            .field("viewport_height", &self.viewport_height)
            .field("minimap", &self.minimap)
            .field("theme", &self.theme)
            .field("class", &self.class)
            .field("on_change", &self.on_change.as_ref().map(|_| "<callback>"))
            .finish()
    }
}

impl Default for CodeEditorOptions {
    fn default() -> Self {
        Self {
            show_line_numbers: true,
            show_fold_gutter: true,
            show_minimap: true,
            show_status_bar: true,
            read_only: false,
            font_size: 13.0,
            line_height: 22.0,
            viewport_height: 480.0,
            minimap: MinimapConfig::default(),
            theme: None,
            class: String::new(),
            on_change: None,
        }
    }
}

/// Reactive shared handle to a [`CodeEditor`] instance.
///
/// Wraps `Rc<RefCell<CodeEditor>>` alongside a reactive `Signal<u64>` revision counter so
/// editing, scrolling, folding, and Find & Replace trigger immediate fine-grained UI updates
/// without cloning the underlying B-Tree text rope.
#[derive(Clone)]
pub struct CodeEditorHandle {
    inner: Rc<RefCell<CodeEditor>>,
    revision: Signal<u64>,
    minimap_dragging: Rc<std::cell::Cell<bool>>,
}

impl std::fmt::Debug for CodeEditorHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ed = self.inner.borrow();
        f.debug_struct("CodeEditorHandle")
            .field("language", &ed.language())
            .field("lines", &ed.line_count())
            .field("revision", &self.revision.get())
            .finish()
    }
}

impl CodeEditorHandle {
    /// Creates a new standalone handle initialized with `initial_text` and `language`.
    pub fn new(initial_text: &str, language: Language) -> Self {
        Self {
            inner: Rc::new(RefCell::new(CodeEditor::new(initial_text, language))),
            revision: Signal::new(0),
            minimap_dragging: Rc::new(std::cell::Cell::new(false)),
        }
    }

    fn from_parts(inner: Rc<RefCell<CodeEditor>>, revision: Signal<u64>) -> Self {
        Self {
            inner,
            revision,
            minimap_dragging: Rc::new(std::cell::Cell::new(false)),
        }
    }

    /// Reads the reactive revision signal (subscribes callers to editor updates).
    pub fn version(&self) -> u64 {
        self.revision.get()
    }

    /// Bumps the reactive revision counter to schedule a repaint.
    pub fn notify(&self) {
        let next = self.revision.get().wrapping_add(1);
        self.revision.set(next);
    }

    /// Executes a read-only closure against the inner [`CodeEditor`].
    pub fn with_editor<R>(&self, f: impl FnOnce(&CodeEditor) -> R) -> R {
        let _ = self.revision.get();
        let guard = self.inner.borrow();
        f(&guard)
    }

    /// Executes a mutating closure against the inner [`CodeEditor`] and notifies subscribers.
    pub fn with_editor_mut<R>(&self, f: impl FnOnce(&mut CodeEditor) -> R) -> R {
        let result = {
            let mut guard = self.inner.borrow_mut();
            f(&mut guard)
        };
        self.notify();
        result
    }

    /// Returns the full document text.
    pub fn text(&self) -> String {
        self.with_editor(CodeEditor::text)
    }

    /// Replaces document contents and resets history.
    pub fn set_text(&self, text: &str) {
        self.with_editor_mut(|ed| ed.set_text(text));
    }

    /// Returns the active language.
    pub fn language(&self) -> Language {
        self.with_editor(CodeEditor::language)
    }

    /// Changes syntax language and re-parses the buffer.
    pub fn set_language(&self, language: Language) {
        self.with_editor_mut(|ed| ed.set_language(language));
    }

    /// Updates the active CSS-variable [`EditorTheme`].
    pub fn set_theme(&self, theme: EditorTheme) {
        self.with_editor_mut(|ed| ed.set_theme(theme));
    }

    /// Updates external/LSP diagnostics without clobbering live syntax diagnostics.
    pub fn set_diagnostics(&self, diagnostics: Vec<EditorDiagnostic>) {
        self.with_editor_mut(|ed| ed.set_external_diagnostics(diagnostics));
    }

    /// Returns diagnostic severity counts.
    pub fn diagnostic_counts(&self) -> DiagnosticCounts {
        self.with_editor(CodeEditor::diagnostic_counts)
    }

    /// Opens the Find bar.
    pub fn open_find(&self) {
        self.with_editor_mut(CodeEditor::open_find);
    }

    /// Opens the Find & Replace bar.
    pub fn open_replace(&self) {
        self.with_editor_mut(CodeEditor::open_replace);
    }

    /// Collapses all foldable blocks.
    pub fn fold_all(&self) {
        self.with_editor_mut(CodeEditor::fold_all);
    }

    /// Expands all folded blocks.
    pub fn unfold_all(&self) {
        self.with_editor_mut(CodeEditor::unfold_all);
    }

    /// Renders the complete interactive Monaco-class [`NodeBlueprint`] using `options`.
    pub fn render_interactive(&self, options: &CodeEditorOptions) -> NodeBlueprint {
        render_interactive_editor(self, options)
    }

    /// Renders the interactive editor wrapped in a Strata [`View`].
    pub fn render_view(&self, options: &CodeEditorOptions) -> View {
        View::new(self.render_interactive(options))
    }
}

/// Reactive Strata hook returning a persistent [`CodeEditorHandle`] across component re-renders.
pub fn use_code_editor(initial_text: &str, language: Language) -> CodeEditorHandle {
    let shared_ref = use_ref::<Option<Rc<RefCell<CodeEditor>>>>(None);
    let revision = use_signal(0u64);
    let shared = shared_ref.with_mut(|slot| {
        Rc::clone(slot.get_or_insert_with(|| Rc::new(RefCell::new(CodeEditor::new(initial_text, language)))))
    });
    CodeEditorHandle::from_parts(shared, revision)
}

/// Drop-in Monaco-class interactive `<CodeEditorWidget>` Strata component.
///
/// Supports virtualized rendering, incremental Tree-Sitter & 10-language syntax highlighting,
/// gutter folding, Find & Replace (`Ctrl+F` / `Ctrl+H`), Canvas2D minimap, LSP/syntax
/// diagnostics, multi-cursor keyboard/mouse editing, and `--strata-editor-*` CSS-variable theming.
#[allow(clippy::too_many_arguments)]
#[component]
pub fn CodeEditorWidget(
    handle: CodeEditorHandle,
    language: Option<Language>,
    theme: Option<EditorTheme>,
    show_minimap: Option<bool>,
    show_line_numbers: Option<bool>,
    show_fold_gutter: Option<bool>,
    show_status_bar: Option<bool>,
    read_only: Option<bool>,
    font_size: Option<f32>,
    line_height: Option<f32>,
    viewport_height: Option<f32>,
    on_change: Option<Rc<dyn Fn(String)>>,
    class: Option<&'static str>,
) -> View {
    if let Some(lang) = language {
        let needs_switch = handle.inner.borrow().language() != lang;
        if needs_switch {
            handle.inner.borrow_mut().set_language(lang);
        }
    }
    if let Some(ro) = read_only {
        handle.inner.borrow_mut().set_read_only(ro);
    }

    let options = CodeEditorOptions {
        show_line_numbers: show_line_numbers.unwrap_or(true),
        show_fold_gutter: show_fold_gutter.unwrap_or(true),
        show_minimap: show_minimap.unwrap_or(true),
        show_status_bar: show_status_bar.unwrap_or(true),
        read_only: read_only.unwrap_or(false),
        font_size: font_size.unwrap_or(13.0),
        line_height: line_height.unwrap_or(22.0),
        viewport_height: viewport_height.unwrap_or(480.0),
        minimap: MinimapConfig::default(),
        theme,
        class: class.unwrap_or("").to_string(),
        on_change,
    };

    View::new(render_interactive_editor(&handle, &options))
}

/// Alias matching `<CodeEditorView ... />` naming convention.
pub use CodeEditorWidget as CodeEditorView;

/// Builds the full interactive Monaco-class DOM blueprint (with live event listeners,
/// virtualized fold-aware rows, Find & Replace overlay, Canvas2D minimap, and status bar).
pub fn render_interactive_editor(
    handle: &CodeEditorHandle,
    options: &CodeEditorOptions,
) -> NodeBlueprint {
    // Subscribe to reactive revision changes.
    let _rev = handle.version();

    // Synchronize layout metrics & fold cache once per render pass.
    {
        let mut ed = handle.inner.borrow_mut();
        ed.set_read_only(options.read_only);
        ed.set_line_height(options.line_height);
        ed.set_viewport_height(options.viewport_height);
        ed.set_char_width((options.font_size * 0.62).max(5.5));
        let _ = ed.ensure_folds_cached();
    }

    let ed = handle.inner.borrow();
    let theme = options.theme.clone().unwrap_or_else(|| ed.theme().clone());
    let effective_lh = options.line_height.max(14.0);
    let effective_vh = options.viewport_height.max(80.0);
    let scroll_top = ed.scroll_top();
    let gutter_width = compute_gutter_width(options);

    let visible_lines = ed.visible_logical_lines();
    let total_visible = visible_lines.len().max(1);
    let first_visible = (scroll_top / effective_lh).floor() as usize;
    let visible_count = (effective_vh / effective_lh).ceil() as usize;
    let start_idx = first_visible.saturating_sub(2).min(total_visible);
    let end_idx = (first_visible + visible_count + 2).min(total_visible);
    let slice_offset_y = -(scroll_top - (start_idx as f32 * effective_lh));

    let primary_pos = ed.cursors().primary().focus;
    let matching_bracket = ed
        .highlighter()
        .find_matching_bracket(ed.buffer(), primary_pos);
    let all_folds = ed.fold_ranges();
    let active_search_idx = ed.search().active_match_index;

    let mut row_nodes = Vec::with_capacity(end_idx.saturating_sub(start_idx));

    for &logical_line in &visible_lines[start_idx..end_idx] {
        let Some(line_str) = ed.buffer().line(logical_line) else {
            continue;
        };
        let is_active_line = logical_line == primary_pos.line;
        let line_diag_sev = ed.diagnostics().max_severity_on_line(logical_line);
        let line_diags = ed.diagnostics().diagnostics_on_line(logical_line);
        let is_fold_start = all_folds
            .iter()
            .any(|f| f.start_line == logical_line && f.end_line > f.start_line);
        let hidden_count = ed.folded_hidden_count(logical_line);

        let mut row_children = Vec::with_capacity(4);

        // 1. Diagnostic severity gutter dot + Fold chevron + Line number gutter
        if options.show_line_numbers || options.show_fold_gutter {
            let mut gutter_items = Vec::with_capacity(3);

            // Diagnostic dot
            let diag_dot = if let Some(sev) = line_diag_sev {
                let tooltip = line_diags
                    .first()
                    .map(|d| d.message.clone())
                    .unwrap_or_default();
                NodeBlueprint::element(
                    Tag::Span,
                    vec!["inline-block w-2 h-2 rounded-full mr-1 shrink-0".to_string()],
                    vec![
                        Attribute::property("data-diag-severity", sev.label()),
                        Attribute::property("title", tooltip),
                        Attribute::property(
                            "style",
                            format!("background-color: {};", theme.diagnostic_css(sev)),
                        ),
                    ],
                    Vec::new(),
                )
            } else {
                NodeBlueprint::element(
                    Tag::Span,
                    vec!["inline-block w-2 h-2 mr-1 shrink-0".to_string()],
                    Vec::new(),
                    Vec::new(),
                )
            };
            gutter_items.push(diag_dot);

            // Line number
            if options.show_line_numbers {
                let num_color = if is_active_line {
                    &theme.gutter_active_fg
                } else {
                    &theme.gutter_fg
                };
                gutter_items.push(NodeBlueprint::element(
                    Tag::Span,
                    vec!["w-9 text-right pr-1.5 select-none font-mono text-xs shrink-0 whitespace-nowrap".to_string()],
                    vec![Attribute::property("style", format!("color: {};", num_color))],
                    vec![NodeBlueprint::text((logical_line + 1).to_string())],
                ));
            }

            // Clickable fold chevron
            if options.show_fold_gutter {
                if is_fold_start {
                    let is_folded = ed.is_folded(logical_line);
                    let chevron = if is_folded { "▸" } else { "▾" };
                    let h_fold = handle.clone();
                    gutter_items.push(NodeBlueprint::element(
                        Tag::Button,
                        vec![
                            "w-4 h-4 flex items-center justify-center text-[11px] select-none cursor-pointer bg-transparent border-0 p-0 shrink-0"
                                .to_string(),
                        ],
                        vec![
                            Attribute::property("data-fold-toggle", logical_line.to_string()),
                            Attribute::property(
                                "title",
                                if is_folded { "Expand fold" } else { "Collapse fold" },
                            ),
                            Attribute::property(
                                "style",
                                format!("color: {};", theme.gutter_active_fg),
                            ),
                            Attribute::event_listener(EventType::Click, move |e: Event| {
                                e.stop_propagation();
                                h_fold.with_editor_mut(|editor| {
                                    editor.toggle_fold_at(logical_line);
                                });
                            }),
                        ],
                        vec![NodeBlueprint::text(chevron)],
                    ));
                } else {
                    gutter_items.push(NodeBlueprint::element(
                        Tag::Span,
                        vec!["w-4 shrink-0 select-none".to_string()],
                        Vec::new(),
                        Vec::new(),
                    ));
                }
            }

            row_children.push(NodeBlueprint::element(
                Tag::Div,
                vec!["flex items-center h-full px-1.5 select-none shrink-0 border-r".to_string()],
                vec![Attribute::property(
                    "style",
                    format!(
                        "width: {:.0}px; background-color: {}; border-color: {};",
                        gutter_width, theme.gutter_bg, theme.border
                    ),
                )],
                gutter_items,
            ));
        }

        // 2. Syntax-colored code content with search matches, bracket match, carets, diagnostics, and fold badge
        let tokens = ed.highlighter().highlight_line_ast(logical_line, line_str);
        let search_matches = if ed.search().is_open {
            ed.search().matches_on_line(logical_line)
        } else {
            Vec::new()
        };
        let line_selections: Vec<(usize, usize)> = ed
            .cursors()
            .all()
            .iter()
            .filter_map(|sel| {
                let (s, e) = sel.ordered_range();
                if sel.is_collapsed() || logical_line < s.line || logical_line > e.line {
                    return None;
                }
                let start_c = if logical_line == s.line { s.col } else { 0 };
                let end_c = if logical_line == e.line {
                    e.col
                } else {
                    line_str.chars().count()
                };
                Some((start_c, end_c))
            })
            .collect();
        let line_carets: Vec<usize> = ed
            .cursors()
            .all()
            .iter()
            .filter(|sel| sel.focus.line == logical_line)
            .map(|sel| sel.focus.col)
            .collect();

        let mut code_spans = build_themed_line_spans(
            line_str,
            &tokens,
            &theme,
            &search_matches,
            active_search_idx,
            &line_selections,
            matching_bracket.filter(|p| p.line == logical_line).map(|p| p.col),
            &line_carets,
            line_diag_sev,
        );

        // Collapsed fold pill `⋯ N lines`
        if let Some(hidden) = hidden_count {
            let h_unfold = handle.clone();
            code_spans.push(NodeBlueprint::element(
                Tag::Button,
                vec![
                    "ml-2 px-1.5 py-0.5 rounded text-[11px] font-mono leading-none whitespace-nowrap shrink-0 cursor-pointer border-0"
                        .to_string(),
                ],
                vec![
                    Attribute::property("data-fold-badge", logical_line.to_string()),
                    Attribute::property(
                        "style",
                        format!(
                            "background-color: {}; color: {};",
                            theme.fold_badge_bg, theme.fold_badge_fg
                        ),
                    ),
                    Attribute::event_listener(EventType::Click, move |e: Event| {
                        e.stop_propagation();
                        h_unfold.with_editor_mut(|editor| {
                            editor.toggle_fold_at(logical_line);
                        });
                    }),
                ],
                vec![NodeBlueprint::text(format!("⋯ {hidden} lines"))],
            ));
        }

        let mut code_attrs = vec![Attribute::property("data-line-index", logical_line.to_string())];
        if line_diag_sev.is_some() {
            code_attrs.push(Attribute::property("data-has-diagnostic", "true"));
        }

        row_children.push(NodeBlueprint::element(
            Tag::Div,
            vec![
                "flex-1 min-w-0 h-full flex items-center pl-2.5 pr-4 whitespace-pre font-mono relative overflow-hidden"
                    .to_string(),
            ],
            code_attrs,
            code_spans,
        ));

        let row_bg = if is_active_line {
            format!(
                "height: {:.1}px; line-height: {:.1}px; background-color: {};",
                effective_lh, effective_lh, theme.line_highlight
            )
        } else {
            format!(
                "height: {:.1}px; line-height: {:.1}px;",
                effective_lh, effective_lh
            )
        };

        row_nodes.push(NodeBlueprint::element(
            Tag::Div,
            vec!["flex items-center w-full shrink-0 overflow-hidden".to_string()],
            vec![
                Attribute::property("data-editor-row", logical_line.to_string()),
                Attribute::property("style", row_bg),
            ],
            row_children,
        ));
    }

    let slice_container = NodeBlueprint::element(
        Tag::Div,
        vec!["flex flex-col w-full relative".to_string()],
        vec![
            Attribute::property("data-editor-slice", "true"),
            Attribute::property("style", format!("top: {:.2}px;", slice_offset_y)),
        ],
        row_nodes,
    );

    // Main virtualized viewport pane with pointer + wheel events
    let h_down = handle.clone();
    let h_move = handle.clone();
    let h_up = handle.clone();
    let h_wheel = handle.clone();
    let viewport_node = NodeBlueprint::element(
        Tag::Div,
        vec!["flex-1 min-w-0 h-full overflow-hidden select-none relative".to_string()],
        vec![
            Attribute::property("data-editor-viewport", "true"),
            Attribute::property(
                "style",
                format!(
                    "height: {:.1}px; font-size: {:.1}px;",
                    effective_vh, options.font_size
                ),
            ),
            Attribute::event_listener(EventType::MouseDown, move |e: Event| {
                h_down.with_editor_mut(|editor| {
                    editor.handle_pointer_down(
                        e.offset_x as f32,
                        e.offset_y as f32,
                        e.detail,
                        e.alt_key,
                        e.shift_key,
                        gutter_width,
                    );
                });
            }),
            Attribute::event_listener(EventType::MouseMove, move |e: Event| {
                if e.buttons & 1 != 0 {
                    h_move.with_editor_mut(|editor| {
                        editor.handle_pointer_drag(
                            e.offset_x as f32,
                            e.offset_y as f32,
                            gutter_width,
                        );
                    });
                }
            }),
            Attribute::event_listener(EventType::MouseUp, move |_e: Event| {
                h_up.with_editor_mut(CodeEditor::handle_pointer_up);
            }),
            Attribute::event_listener(EventType::Wheel, move |e: Event| {
                e.prevent_default();
                h_wheel.with_editor_mut(|editor| {
                    editor.handle_wheel(e.delta_y as f32);
                });
            }),
        ],
        vec![slice_container],
    );

    // Optional Canvas2D minimap
    let mut body_children = vec![viewport_node];
    if options.show_minimap {
        let minimap_cfg = options.minimap;
        let commands: Arc<Vec<CanvasCommand>> = Arc::new(render_minimap_canvas_commands(
            &ed,
            scroll_top,
            effective_vh,
            effective_lh,
            effective_vh,
            &minimap_cfg,
            &theme,
        ));
        let h_mm_down = handle.clone();
        let h_mm_move = handle.clone();
        let h_mm_up = handle.clone();
        let mm_drag_down = handle.minimap_dragging.clone();
        let mm_drag_move = handle.minimap_dragging.clone();
        let mm_drag_up = handle.minimap_dragging.clone();

        let minimap_node = NodeBlueprint::element(
            Tag::Canvas,
            vec!["shrink-0 border-l cursor-pointer".to_string()],
            vec![
                Attribute::property("data-editor-minimap", "true"),
                Attribute::property("width", format!("{:.0}", minimap_cfg.width)),
                Attribute::property("height", format!("{:.0}", effective_vh)),
                Attribute::property(
                    "style",
                    format!(
                        "width: {:.0}px; height: {:.0}px; background-color: {}; border-color: {};",
                        minimap_cfg.width, effective_vh, theme.minimap_bg, theme.border
                    ),
                ),
                Attribute::scene_payload_arc(commands),
                Attribute::event_listener(EventType::MouseDown, move |e: Event| {
                    e.stop_propagation();
                    mm_drag_down.set(true);
                    h_mm_down.with_editor_mut(|editor| {
                        editor.handle_minimap_pointer(
                            e.offset_y as f32,
                            effective_vh,
                            &minimap_cfg,
                        );
                    });
                }),
                Attribute::event_listener(EventType::MouseMove, move |e: Event| {
                    if mm_drag_move.get() && (e.buttons & 1 != 0) {
                        h_mm_move.with_editor_mut(|editor| {
                            editor.handle_minimap_pointer(
                                e.offset_y as f32,
                                effective_vh,
                                &minimap_cfg,
                            );
                        });
                    }
                }),
                Attribute::event_listener(EventType::MouseUp, move |_e: Event| {
                    mm_drag_up.set(false);
                    let _ = &h_mm_up;
                }),
            ],
            Vec::new(),
        );
        body_children.push(minimap_node);
    }

    // Optional Find & Replace bar overlay
    let mut root_children = Vec::with_capacity(3);
    if ed.search().is_open {
        root_children.push(build_find_replace_bar(
            handle,
            &ed,
            &theme,
            options.on_change.clone(),
        ));
    }

    // Split body (viewport + minimap)
    root_children.push(NodeBlueprint::element(
        Tag::Div,
        vec!["flex flex-1 min-h-0 w-full overflow-hidden".to_string()],
        Vec::new(),
        body_children,
    ));

    // Optional Monaco-style status bar
    if options.show_status_bar {
        root_children.push(build_status_bar(&ed, &theme));
    }

    // Drop read borrow before wiring root keyboard listener
    let lang_name = ed.language().display_name();
    drop(ed);

    let h_key = handle.clone();
    let on_change_key = options.on_change.clone();
    let h_input = handle.clone();
    let on_change_input = options.on_change.clone();
    let root_classes = if options.class.is_empty() {
        "strata-code-editor flex flex-col font-mono rounded-lg border overflow-hidden relative outline-none"
            .to_string()
    } else {
        format!(
            "strata-code-editor flex flex-col font-mono rounded-lg border overflow-hidden relative outline-none {}",
            options.class
        )
    };

    NodeBlueprint::element(
        Tag::Div,
        vec![root_classes],
        vec![
            Attribute::property("role", "textbox"),
            Attribute::property("aria-multiline", "true"),
            Attribute::property("aria-label", format!("Code editor ({lang_name})")),
            Attribute::property("tabindex", "0"),
            Attribute::property("data-strata-code-editor", "true"),
            Attribute::property("data-editor-theme", theme.name.clone()),
            Attribute::property(
                "style",
                format!(
                    "background-color: {}; color: {}; border-color: {};",
                    theme.bg, theme.fg, theme.border
                ),
            ),
            Attribute::event_listener(EventType::KeyDown, move |e: Event| {
                let mut mutated_text: Option<String> = None;
                let handled = h_key.with_editor_mut(|editor| {
                    let before_edit_rev = editor.edit_revision();
                    let handled = editor.handle_key_event(&e);
                    if handled
                        && on_change_key.is_some()
                        && editor.edit_revision() != before_edit_rev
                    {
                        mutated_text = Some(editor.text());
                    }
                    handled
                });
                if handled {
                    e.prevent_default();
                    e.stop_propagation();
                    if let (Some(cb), Some(text)) = (&on_change_key, mutated_text) {
                        cb(text);
                    }
                }
            }),
            Attribute::event_listener(EventType::Input, move |e: Event| {
                let mut mutated_text: Option<String> = None;
                let handled = h_input.with_editor_mut(|editor| {
                    let before_edit_rev = editor.edit_revision();
                    let handled = editor.handle_input_event(&e);
                    if handled
                        && on_change_input.is_some()
                        && editor.edit_revision() != before_edit_rev
                    {
                        mutated_text = Some(editor.text());
                    }
                    handled
                });
                if handled {
                    e.prevent_default();
                    e.stop_propagation();
                    if let (Some(cb), Some(text)) = (&on_change_input, mutated_text) {
                        cb(text);
                    }
                }
            }),
        ],
        root_children,
    )
}

fn compute_gutter_width(options: &CodeEditorOptions) -> f32 {
    let mut w = 12.0; // padding + diagnostic dot
    if options.show_line_numbers {
        w += 42.0;
    }
    if options.show_fold_gutter {
        w += 18.0;
    }
    w
}

#[inline]
fn char_slice_to_str(s: &str, start_char: usize, end_char: usize) -> &str {
    if start_char >= end_char {
        return "";
    }
    let start_byte = s
        .char_indices()
        .nth(start_char)
        .map(|(b, _)| b)
        .unwrap_or(s.len());
    let end_byte = s
        .char_indices()
        .nth(end_char)
        .map(|(b, _)| b)
        .unwrap_or(s.len());
    if start_byte <= end_byte {
        &s[start_byte..end_byte]
    } else {
        ""
    }
}

fn make_code_span(text: String, style: Option<&str>) -> NodeBlueprint {
    let attrs = match style {
        Some(st) if !st.is_empty() => vec![Attribute::property("style", st.to_string())],
        _ => Vec::new(),
    };
    NodeBlueprint::element(
        Tag::Span,
        vec!["whitespace-pre shrink-0".to_string()],
        attrs,
        vec![NodeBlueprint::text(text)],
    )
}

fn make_caret_anchor(col: usize, caret_color: &str) -> NodeBlueprint {
    NodeBlueprint::element(
        Tag::Span,
        vec!["relative inline-block w-0 h-full shrink-0 pointer-events-none".to_string()],
        vec![Attribute::property("data-editor-caret-anchor", col.to_string())],
        vec![NodeBlueprint::element(
            Tag::Span,
            vec!["absolute left-0 top-[2px] w-[2px] h-[16px] pointer-events-none".to_string()],
            vec![
                Attribute::property("data-editor-caret-col", col.to_string()),
                Attribute::property("style", format!("background-color: {};", caret_color)),
            ],
            Vec::new(),
        )],
    )
}

#[allow(clippy::too_many_arguments)]
fn build_themed_line_spans(
    line_text: &str,
    tokens: &[crate::syntax::SyntaxToken],
    theme: &EditorTheme,
    search_matches: &[(usize, &crate::search::SearchMatch)],
    active_search_idx: usize,
    selections: &[(usize, usize)],
    matching_bracket_col: Option<usize>,
    carets: &[usize],
    line_diag_sev: Option<DiagnosticSeverity>,
) -> Vec<NodeBlueprint> {
    let line_chars = line_text.chars().count();

    let decorate_style = |base: String, char_start: usize, char_end: usize| -> String {
        let mut style = base;
        if let Some((idx, _)) = search_matches
            .iter()
            .find(|(_, m)| char_start < m.end.col && char_end > m.start.col)
        {
            let bg = if *idx == active_search_idx {
                &theme.find_active_bg
            } else {
                &theme.find_match_bg
            };
            style.push_str(&format!(" background-color: {}; border-radius: 2px;", bg));
        } else if selections
            .iter()
            .any(|&(s, e)| char_start < e && char_end > s)
        {
            style.push_str(&format!(" background-color: {};", theme.selection_bg));
        } else if let Some(b_col) = matching_bracket_col {
            if b_col >= char_start && b_col < char_end {
                style.push_str(&format!(
                    " background-color: {}; border-radius: 2px;",
                    theme.bracket_match_bg
                ));
            }
        }
        if let Some(sev) = line_diag_sev {
            style.push_str(&format!(
                " border-bottom: 2px dotted {};",
                theme.diagnostic_css(sev)
            ));
        }
        style
    };

    // 1. Build contiguous char-column styled runs covering `line_text`.
    let mut runs: Vec<(usize, usize, String, String)> = Vec::new();
    if tokens.is_empty() {
        if !line_text.is_empty() {
            let st = decorate_style(String::new(), 0, line_chars);
            runs.push((0, line_chars, line_text.to_string(), st));
        }
    } else {
        let mut last_byte = 0usize;
        let mut cur_char = 0usize;
        for tok in tokens {
            let start_b = tok.start_col.min(line_text.len());
            let end_b = tok.end_col.min(line_text.len());
            if start_b > last_byte
                && line_text.is_char_boundary(last_byte)
                && line_text.is_char_boundary(start_b)
            {
                let gap = &line_text[last_byte..start_b];
                let gap_len = gap.chars().count();
                let st = decorate_style(String::new(), cur_char, cur_char + gap_len);
                runs.push((cur_char, cur_char + gap_len, gap.to_string(), st));
                cur_char += gap_len;
            }

            let tok_char_start = if line_text.is_char_boundary(start_b) {
                line_text[..start_b].chars().count()
            } else {
                cur_char
            };
            let tok_char_len = tok.text.chars().count();
            let tok_char_end = tok_char_start + tok_char_len;

            let mut base_style = format!("color: {};", theme.token_css(tok.token_type));
            if matches!(
                tok.token_type,
                crate::syntax::TokenType::Keyword
                    | crate::syntax::TokenType::ControlFlow
                    | crate::syntax::TokenType::Heading
            ) {
                base_style.push_str(" font-weight: 600;");
            } else if matches!(
                tok.token_type,
                crate::syntax::TokenType::Comment | crate::syntax::TokenType::DocComment
            ) {
                base_style.push_str(" font-style: italic;");
            }
            let st = decorate_style(base_style, tok_char_start, tok_char_end);
            runs.push((tok_char_start, tok_char_end, tok.text.clone(), st));
            last_byte = end_b.max(last_byte);
            cur_char = tok_char_end;
        }
        if last_byte < line_text.len() && line_text.is_char_boundary(last_byte) {
            let tail = &line_text[last_byte..];
            let tail_len = tail.chars().count();
            let st = decorate_style(String::new(), cur_char, cur_char + tail_len);
            runs.push((cur_char, cur_char + tail_len, tail.to_string(), st));
        }
    }

    // 2. Sort and deduplicate clamped caret columns on this line, then split runs inline
    //    at every caret column so carets render at their exact column without shifting text.
    let mut clamped_carets: Vec<usize> = carets.iter().map(|&c| c.min(line_chars)).collect();
    clamped_carets.sort_unstable();
    clamped_carets.dedup();

    let mut nodes = Vec::with_capacity(runs.len() + clamped_carets.len() * 2);
    let mut caret_idx = 0usize;

    for (r_start, r_end, text, style) in runs {
        while caret_idx < clamped_carets.len() && clamped_carets[caret_idx] <= r_start {
            nodes.push(make_caret_anchor(clamped_carets[caret_idx], &theme.caret));
            caret_idx += 1;
        }

        let mut local_start = 0usize;
        let run_len = r_end.saturating_sub(r_start);
        while caret_idx < clamped_carets.len() && clamped_carets[caret_idx] < r_end {
            let col = clamped_carets[caret_idx];
            let split_at = col.saturating_sub(r_start).min(run_len);
            if split_at > local_start {
                let piece = char_slice_to_str(&text, local_start, split_at);
                if !piece.is_empty() {
                    nodes.push(make_code_span(piece.to_string(), Some(style.as_str())));
                }
            }
            nodes.push(make_caret_anchor(col, &theme.caret));
            local_start = split_at;
            caret_idx += 1;
        }

        if local_start == 0 {
            if !text.is_empty() {
                nodes.push(make_code_span(text, Some(style.as_str())));
            }
        } else if local_start < run_len {
            let tail = char_slice_to_str(&text, local_start, run_len);
            if !tail.is_empty() {
                nodes.push(make_code_span(tail.to_string(), Some(style.as_str())));
            }
        }
    }

    // Emit any remaining carets (e.g. at end-of-line or on empty lines).
    while caret_idx < clamped_carets.len() {
        nodes.push(make_caret_anchor(clamped_carets[caret_idx], &theme.caret));
        caret_idx += 1;
    }

    nodes
}

fn build_find_replace_bar(
    handle: &CodeEditorHandle,
    ed: &CodeEditor,
    theme: &EditorTheme,
    on_change: Option<Rc<dyn Fn(String)>>,
) -> NodeBlueprint {
    let search = ed.search();
    let status = search.status_label();

    let h_query = handle.clone();
    let h_case = handle.clone();
    let h_word = handle.clone();
    let h_regex = handle.clone();
    let h_prev = handle.clone();
    let h_next = handle.clone();
    let h_close = handle.clone();
    let h_find_key = handle.clone();

    let toggle_btn = |label: &str, active: bool, attr: &str, on_click: Box<dyn Fn(Event)>| {
        let style = if active {
            format!(
                "background-color: {}; color: {}; border-color: {};",
                theme.selection_bg, theme.fg, theme.caret
            )
        } else {
            format!(
                "background-color: transparent; color: {}; border-color: {};",
                theme.gutter_fg, theme.panel_border
            )
        };
        NodeBlueprint::element(
            Tag::Button,
            vec!["px-1.5 py-0.5 text-xs font-mono rounded border cursor-pointer whitespace-nowrap shrink-0".to_string()],
            vec![
                Attribute::property("data-find-action", attr),
                Attribute::property("style", style),
                Attribute::event_listener(EventType::Click, move |e: Event| {
                    e.stop_propagation();
                    on_click(e);
                }),
            ],
            vec![NodeBlueprint::text(label)],
        )
    };

    let find_row = NodeBlueprint::element(
        Tag::Div,
        vec!["flex items-center gap-1.5".to_string()],
        Vec::new(),
        vec![
            NodeBlueprint::element(
                Tag::Input,
                vec!["flex-1 min-w-[140px] px-2 py-0.5 text-xs font-mono rounded border".to_string()],
                vec![
                    Attribute::property("type", "text"),
                    Attribute::property("placeholder", "Find..."),
                    Attribute::property("value", search.query.clone()),
                    Attribute::property("data-find-input", "query"),
                    Attribute::property(
                        "style",
                        format!(
                            "background-color: {}; color: {}; border-color: {};",
                            theme.bg, theme.fg, theme.panel_border
                        ),
                    ),
                    Attribute::value_listener(EventType::Input, move |val: String| {
                        h_query.with_editor_mut(|editor| editor.set_find_query(val));
                    }),
                    Attribute::event_listener(EventType::KeyDown, move |e: Event| {
                        match e.key.as_str() {
                            "Escape" => {
                                e.prevent_default();
                                e.stop_propagation();
                                h_find_key.with_editor_mut(CodeEditor::close_find);
                            }
                            "Enter" => {
                                e.prevent_default();
                                e.stop_propagation();
                                let shift = e.shift_key;
                                h_find_key.with_editor_mut(|editor| {
                                    if shift {
                                        let _ = editor.find_prev();
                                    } else {
                                        let _ = editor.find_next();
                                    }
                                });
                            }
                            _ => {
                                e.stop_propagation();
                            }
                        }
                    }),
                ],
                Vec::new(),
            ),
            toggle_btn(
                "Aa",
                search.case_sensitive,
                "case",
                Box::new(move |_| {
                    h_case.with_editor_mut(|editor| {
                        let mut s = std::mem::take(editor.search_mut());
                        s.toggle_case_sensitive(editor.buffer());
                        *editor.search_mut() = s;
                    });
                }),
            ),
            toggle_btn(
                "Ab",
                search.whole_word,
                "whole-word",
                Box::new(move |_| {
                    h_word.with_editor_mut(|editor| {
                        let mut s = std::mem::take(editor.search_mut());
                        s.toggle_whole_word(editor.buffer());
                        *editor.search_mut() = s;
                    });
                }),
            ),
            toggle_btn(
                ".*",
                search.use_regex,
                "regex",
                Box::new(move |_| {
                    h_regex.with_editor_mut(|editor| {
                        let mut s = std::mem::take(editor.search_mut());
                        s.toggle_regex(editor.buffer());
                        *editor.search_mut() = s;
                    });
                }),
            ),
            NodeBlueprint::element(
                Tag::Span,
                vec!["text-xs font-mono px-1 min-w-[64px] text-center select-none whitespace-nowrap shrink-0".to_string()],
                vec![
                    Attribute::property("data-find-status", "true"),
                    Attribute::property("style", format!("color: {};", theme.gutter_active_fg)),
                ],
                vec![NodeBlueprint::text(status)],
            ),
            toggle_btn(
                "↑",
                false,
                "prev",
                Box::new(move |_| {
                    h_prev.with_editor_mut(|editor| {
                        let _ = editor.find_prev();
                    });
                }),
            ),
            toggle_btn(
                "↓",
                false,
                "next",
                Box::new(move |_| {
                    h_next.with_editor_mut(|editor| {
                        let _ = editor.find_next();
                    });
                }),
            ),
            toggle_btn(
                "×",
                false,
                "close",
                Box::new(move |_| {
                    h_close.with_editor_mut(CodeEditor::close_find);
                }),
            ),
        ],
    );

    let mut rows = vec![find_row];

    if search.show_replace {
        let h_repl_in = handle.clone();
        let h_repl_key = handle.clone();
        let h_repl_one = handle.clone();
        let h_repl_all = handle.clone();
        let cb_repl_enter = on_change.clone();
        let cb_one = on_change.clone();
        let cb_all = on_change;

        rows.push(NodeBlueprint::element(
            Tag::Div,
            vec!["flex items-center gap-1.5 mt-1".to_string()],
            Vec::new(),
            vec![
                NodeBlueprint::element(
                    Tag::Input,
                    vec!["flex-1 min-w-[140px] px-2 py-0.5 text-xs font-mono rounded border".to_string()],
                    vec![
                        Attribute::property("type", "text"),
                        Attribute::property("placeholder", "Replace..."),
                        Attribute::property("value", search.replacement.clone()),
                        Attribute::property("data-find-input", "replace"),
                        Attribute::property(
                            "style",
                            format!(
                                "background-color: {}; color: {}; border-color: {};",
                                theme.bg, theme.fg, theme.panel_border
                            ),
                        ),
                        Attribute::value_listener(EventType::Input, move |val: String| {
                            h_repl_in.with_editor_mut(|editor| editor.set_replace_text(val));
                        }),
                        Attribute::event_listener(EventType::KeyDown, move |e: Event| {
                            match e.key.as_str() {
                                "Escape" => {
                                    e.prevent_default();
                                    e.stop_propagation();
                                    h_repl_key.with_editor_mut(CodeEditor::close_find);
                                }
                                "Enter" => {
                                    e.prevent_default();
                                    e.stop_propagation();
                                    let updated = h_repl_key.with_editor_mut(|editor| {
                                        if editor.replace_current() {
                                            Some(editor.text())
                                        } else {
                                            None
                                        }
                                    });
                                    if let (Some(cb), Some(text)) = (&cb_repl_enter, updated) {
                                        cb(text);
                                    }
                                }
                                _ => {
                                    e.stop_propagation();
                                }
                            }
                        }),
                    ],
                    Vec::new(),
                ),
                toggle_btn(
                    "Replace",
                    false,
                    "replace",
                    Box::new(move |_| {
                        let updated = h_repl_one.with_editor_mut(|editor| {
                            if editor.replace_current() {
                                Some(editor.text())
                            } else {
                                None
                            }
                        });
                        if let (Some(cb), Some(text)) = (&cb_one, updated) {
                            cb(text);
                        }
                    }),
                ),
                toggle_btn(
                    "All",
                    false,
                    "replace-all",
                    Box::new(move |_| {
                        let updated = h_repl_all.with_editor_mut(|editor| {
                            if editor.replace_all() > 0 {
                                Some(editor.text())
                            } else {
                                None
                            }
                        });
                        if let (Some(cb), Some(text)) = (&cb_all, updated) {
                            cb(text);
                        }
                    }),
                ),
            ],
        ));
    }

    NodeBlueprint::element(
        Tag::Div,
        vec!["px-2.5 py-1.5 border-b flex flex-col shrink-0".to_string()],
        vec![
            Attribute::property("data-find-replace-bar", "true"),
            Attribute::property(
                "style",
                format!(
                    "background-color: {}; border-color: {};",
                    theme.panel_bg, theme.panel_border
                ),
            ),
        ],
        rows,
    )
}

fn build_status_bar(ed: &CodeEditor, theme: &EditorTheme) -> NodeBlueprint {
    let primary = ed.cursors().primary().focus;
    let counts = ed.diagnostic_counts();
    let cursor_badge = if ed.cursors().count() > 1 {
        format!(
            "Ln {}, Col {} ({} cursors)",
            primary.line + 1,
            primary.col + 1,
            ed.cursors().count()
        )
    } else {
        format!("Ln {}, Col {}", primary.line + 1, primary.col + 1)
    };

    NodeBlueprint::element(
        Tag::Div,
        vec![
            "flex items-center justify-between gap-3 px-3 py-1 text-[11px] font-mono border-t select-none shrink-0 whitespace-nowrap overflow-hidden"
                .to_string(),
        ],
        vec![
            Attribute::property("data-editor-statusbar", "true"),
            Attribute::property(
                "style",
                format!(
                    "background-color: {}; color: {}; border-color: {};",
                    theme.gutter_bg, theme.gutter_fg, theme.border
                ),
            ),
        ],
        vec![
            NodeBlueprint::element(
                Tag::Div,
                vec!["flex items-center gap-3 whitespace-nowrap overflow-hidden shrink-0".to_string()],
                Vec::new(),
                vec![
                    NodeBlueprint::element(
                        Tag::Span,
                        vec!["whitespace-nowrap shrink-0".to_string()],
                        vec![Attribute::property(
                            "style",
                            format!("color: {};", theme.diag_error),
                        )],
                        vec![NodeBlueprint::text(format!("✕ {}", counts.errors))],
                    ),
                    NodeBlueprint::element(
                        Tag::Span,
                        vec!["whitespace-nowrap shrink-0".to_string()],
                        vec![Attribute::property(
                            "style",
                            format!("color: {};", theme.diag_warning),
                        )],
                        vec![NodeBlueprint::text(format!("▲ {}", counts.warnings))],
                    ),
                    NodeBlueprint::element(
                        Tag::Span,
                        vec!["whitespace-nowrap shrink-0".to_string()],
                        vec![Attribute::property("data-status-cursor", "true")],
                        vec![NodeBlueprint::text(cursor_badge)],
                    ),
                ],
            ),
            NodeBlueprint::element(
                Tag::Div,
                vec!["flex items-center gap-3 whitespace-nowrap overflow-hidden shrink-0".to_string()],
                Vec::new(),
                vec![
                    NodeBlueprint::element(
                        Tag::Span,
                        vec!["whitespace-nowrap shrink-0".to_string()],
                        vec![Attribute::property("data-status-spaces", "true")],
                        vec![NodeBlueprint::text(format!("Spaces: {}", ed.tab_size()))],
                    ),
                    NodeBlueprint::element(
                        Tag::Span,
                        vec!["whitespace-nowrap shrink-0".to_string()],
                        Vec::new(),
                        vec![NodeBlueprint::text("UTF-8")],
                    ),
                    NodeBlueprint::element(
                        Tag::Span,
                        vec!["font-semibold whitespace-nowrap shrink-0".to_string()],
                        vec![Attribute::property(
                            "style",
                            format!("color: {};", theme.gutter_active_fg),
                        )],
                        vec![NodeBlueprint::text(ed.language().display_name())],
                    ),
                ],
            ),
        ],
    )
}