1#![allow(non_snake_case)]
10
11use std::cell::RefCell;
12use std::rc::Rc;
13use std::sync::Arc;
14
15use strata_dom::{
16 use_ref, use_signal, Attribute, Event, EventType, NodeBlueprint, Signal, Tag, View,
17};
18use strata_macro::component;
19use strata_render::canvas2d::CanvasCommand;
20
21use crate::code_editor::CodeEditor;
22use crate::diagnostics::{DiagnosticCounts, DiagnosticSeverity, EditorDiagnostic};
23use crate::minimap::{render_minimap_canvas_commands, MinimapConfig};
24use crate::syntax::Language;
25use crate::theme::EditorTheme;
26
27#[derive(Clone)]
29pub struct CodeEditorOptions {
30 pub show_line_numbers: bool,
31 pub show_fold_gutter: bool,
32 pub show_minimap: bool,
33 pub show_status_bar: bool,
34 pub read_only: bool,
35 pub font_size: f32,
36 pub line_height: f32,
37 pub viewport_height: f32,
38 pub minimap: MinimapConfig,
39 pub theme: Option<EditorTheme>,
40 pub class: String,
41 pub on_change: Option<Rc<dyn Fn(String)>>,
42}
43
44impl std::fmt::Debug for CodeEditorOptions {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 f.debug_struct("CodeEditorOptions")
47 .field("show_line_numbers", &self.show_line_numbers)
48 .field("show_fold_gutter", &self.show_fold_gutter)
49 .field("show_minimap", &self.show_minimap)
50 .field("show_status_bar", &self.show_status_bar)
51 .field("read_only", &self.read_only)
52 .field("font_size", &self.font_size)
53 .field("line_height", &self.line_height)
54 .field("viewport_height", &self.viewport_height)
55 .field("minimap", &self.minimap)
56 .field("theme", &self.theme)
57 .field("class", &self.class)
58 .field("on_change", &self.on_change.as_ref().map(|_| "<callback>"))
59 .finish()
60 }
61}
62
63impl Default for CodeEditorOptions {
64 fn default() -> Self {
65 Self {
66 show_line_numbers: true,
67 show_fold_gutter: true,
68 show_minimap: true,
69 show_status_bar: true,
70 read_only: false,
71 font_size: 13.0,
72 line_height: 22.0,
73 viewport_height: 480.0,
74 minimap: MinimapConfig::default(),
75 theme: None,
76 class: String::new(),
77 on_change: None,
78 }
79 }
80}
81
82#[derive(Clone)]
88pub struct CodeEditorHandle {
89 inner: Rc<RefCell<CodeEditor>>,
90 revision: Signal<u64>,
91 minimap_dragging: Rc<std::cell::Cell<bool>>,
92}
93
94impl std::fmt::Debug for CodeEditorHandle {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 let ed = self.inner.borrow();
97 f.debug_struct("CodeEditorHandle")
98 .field("language", &ed.language())
99 .field("lines", &ed.line_count())
100 .field("revision", &self.revision.get())
101 .finish()
102 }
103}
104
105impl CodeEditorHandle {
106 pub fn new(initial_text: &str, language: Language) -> Self {
108 Self {
109 inner: Rc::new(RefCell::new(CodeEditor::new(initial_text, language))),
110 revision: Signal::new(0),
111 minimap_dragging: Rc::new(std::cell::Cell::new(false)),
112 }
113 }
114
115 fn from_parts(inner: Rc<RefCell<CodeEditor>>, revision: Signal<u64>) -> Self {
116 Self {
117 inner,
118 revision,
119 minimap_dragging: Rc::new(std::cell::Cell::new(false)),
120 }
121 }
122
123 pub fn version(&self) -> u64 {
125 self.revision.get()
126 }
127
128 pub fn notify(&self) {
130 let next = self.revision.get().wrapping_add(1);
131 self.revision.set(next);
132 }
133
134 pub fn with_editor<R>(&self, f: impl FnOnce(&CodeEditor) -> R) -> R {
136 let _ = self.revision.get();
137 let guard = self.inner.borrow();
138 f(&guard)
139 }
140
141 pub fn with_editor_mut<R>(&self, f: impl FnOnce(&mut CodeEditor) -> R) -> R {
143 let result = {
144 let mut guard = self.inner.borrow_mut();
145 f(&mut guard)
146 };
147 self.notify();
148 result
149 }
150
151 pub fn text(&self) -> String {
153 self.with_editor(CodeEditor::text)
154 }
155
156 pub fn set_text(&self, text: &str) {
158 self.with_editor_mut(|ed| ed.set_text(text));
159 }
160
161 pub fn language(&self) -> Language {
163 self.with_editor(CodeEditor::language)
164 }
165
166 pub fn set_language(&self, language: Language) {
168 self.with_editor_mut(|ed| ed.set_language(language));
169 }
170
171 pub fn set_theme(&self, theme: EditorTheme) {
173 self.with_editor_mut(|ed| ed.set_theme(theme));
174 }
175
176 pub fn set_diagnostics(&self, diagnostics: Vec<EditorDiagnostic>) {
178 self.with_editor_mut(|ed| ed.set_external_diagnostics(diagnostics));
179 }
180
181 pub fn diagnostic_counts(&self) -> DiagnosticCounts {
183 self.with_editor(CodeEditor::diagnostic_counts)
184 }
185
186 pub fn open_find(&self) {
188 self.with_editor_mut(CodeEditor::open_find);
189 }
190
191 pub fn open_replace(&self) {
193 self.with_editor_mut(CodeEditor::open_replace);
194 }
195
196 pub fn fold_all(&self) {
198 self.with_editor_mut(CodeEditor::fold_all);
199 }
200
201 pub fn unfold_all(&self) {
203 self.with_editor_mut(CodeEditor::unfold_all);
204 }
205
206 pub fn render_interactive(&self, options: &CodeEditorOptions) -> NodeBlueprint {
208 render_interactive_editor(self, options)
209 }
210
211 pub fn render_view(&self, options: &CodeEditorOptions) -> View {
213 View::new(self.render_interactive(options))
214 }
215}
216
217pub fn use_code_editor(initial_text: &str, language: Language) -> CodeEditorHandle {
219 let shared_ref = use_ref::<Option<Rc<RefCell<CodeEditor>>>>(None);
220 let revision = use_signal(0u64);
221 let shared = shared_ref.with_mut(|slot| {
222 Rc::clone(slot.get_or_insert_with(|| Rc::new(RefCell::new(CodeEditor::new(initial_text, language)))))
223 });
224 CodeEditorHandle::from_parts(shared, revision)
225}
226
227#[allow(clippy::too_many_arguments)]
233#[component]
234pub fn CodeEditorWidget(
235 handle: CodeEditorHandle,
236 language: Option<Language>,
237 theme: Option<EditorTheme>,
238 show_minimap: Option<bool>,
239 show_line_numbers: Option<bool>,
240 show_fold_gutter: Option<bool>,
241 show_status_bar: Option<bool>,
242 read_only: Option<bool>,
243 font_size: Option<f32>,
244 line_height: Option<f32>,
245 viewport_height: Option<f32>,
246 on_change: Option<Rc<dyn Fn(String)>>,
247 class: Option<&'static str>,
248) -> View {
249 if let Some(lang) = language {
250 let needs_switch = handle.inner.borrow().language() != lang;
251 if needs_switch {
252 handle.inner.borrow_mut().set_language(lang);
253 }
254 }
255 if let Some(ro) = read_only {
256 handle.inner.borrow_mut().set_read_only(ro);
257 }
258
259 let options = CodeEditorOptions {
260 show_line_numbers: show_line_numbers.unwrap_or(true),
261 show_fold_gutter: show_fold_gutter.unwrap_or(true),
262 show_minimap: show_minimap.unwrap_or(true),
263 show_status_bar: show_status_bar.unwrap_or(true),
264 read_only: read_only.unwrap_or(false),
265 font_size: font_size.unwrap_or(13.0),
266 line_height: line_height.unwrap_or(22.0),
267 viewport_height: viewport_height.unwrap_or(480.0),
268 minimap: MinimapConfig::default(),
269 theme,
270 class: class.unwrap_or("").to_string(),
271 on_change,
272 };
273
274 View::new(render_interactive_editor(&handle, &options))
275}
276
277pub use CodeEditorWidget as CodeEditorView;
279
280pub fn render_interactive_editor(
283 handle: &CodeEditorHandle,
284 options: &CodeEditorOptions,
285) -> NodeBlueprint {
286 let _rev = handle.version();
288
289 {
291 let mut ed = handle.inner.borrow_mut();
292 ed.set_read_only(options.read_only);
293 ed.set_line_height(options.line_height);
294 ed.set_viewport_height(options.viewport_height);
295 ed.set_char_width((options.font_size * 0.62).max(5.5));
296 let _ = ed.ensure_folds_cached();
297 }
298
299 let ed = handle.inner.borrow();
300 let theme = options.theme.clone().unwrap_or_else(|| ed.theme().clone());
301 let effective_lh = options.line_height.max(14.0);
302 let effective_vh = options.viewport_height.max(80.0);
303 let scroll_top = ed.scroll_top();
304 let gutter_width = compute_gutter_width(options);
305
306 let visible_lines = ed.visible_logical_lines();
307 let total_visible = visible_lines.len().max(1);
308 let first_visible = (scroll_top / effective_lh).floor() as usize;
309 let visible_count = (effective_vh / effective_lh).ceil() as usize;
310 let start_idx = first_visible.saturating_sub(2).min(total_visible);
311 let end_idx = (first_visible + visible_count + 2).min(total_visible);
312 let slice_offset_y = -(scroll_top - (start_idx as f32 * effective_lh));
313
314 let primary_pos = ed.cursors().primary().focus;
315 let matching_bracket = ed
316 .highlighter()
317 .find_matching_bracket(ed.buffer(), primary_pos);
318 let all_folds = ed.fold_ranges();
319 let active_search_idx = ed.search().active_match_index;
320
321 let mut row_nodes = Vec::with_capacity(end_idx.saturating_sub(start_idx));
322
323 for &logical_line in &visible_lines[start_idx..end_idx] {
324 let Some(line_str) = ed.buffer().line(logical_line) else {
325 continue;
326 };
327 let is_active_line = logical_line == primary_pos.line;
328 let line_diag_sev = ed.diagnostics().max_severity_on_line(logical_line);
329 let line_diags = ed.diagnostics().diagnostics_on_line(logical_line);
330 let is_fold_start = all_folds
331 .iter()
332 .any(|f| f.start_line == logical_line && f.end_line > f.start_line);
333 let hidden_count = ed.folded_hidden_count(logical_line);
334
335 let mut row_children = Vec::with_capacity(4);
336
337 if options.show_line_numbers || options.show_fold_gutter {
339 let mut gutter_items = Vec::with_capacity(3);
340
341 let diag_dot = if let Some(sev) = line_diag_sev {
343 let tooltip = line_diags
344 .first()
345 .map(|d| d.message.clone())
346 .unwrap_or_default();
347 NodeBlueprint::element(
348 Tag::Span,
349 vec!["inline-block w-2 h-2 rounded-full mr-1 shrink-0".to_string()],
350 vec![
351 Attribute::property("data-diag-severity", sev.label()),
352 Attribute::property("title", tooltip),
353 Attribute::property(
354 "style",
355 format!("background-color: {};", theme.diagnostic_css(sev)),
356 ),
357 ],
358 Vec::new(),
359 )
360 } else {
361 NodeBlueprint::element(
362 Tag::Span,
363 vec!["inline-block w-2 h-2 mr-1 shrink-0".to_string()],
364 Vec::new(),
365 Vec::new(),
366 )
367 };
368 gutter_items.push(diag_dot);
369
370 if options.show_line_numbers {
372 let num_color = if is_active_line {
373 &theme.gutter_active_fg
374 } else {
375 &theme.gutter_fg
376 };
377 gutter_items.push(NodeBlueprint::element(
378 Tag::Span,
379 vec!["w-9 text-right pr-1.5 select-none font-mono text-xs shrink-0 whitespace-nowrap".to_string()],
380 vec![Attribute::property("style", format!("color: {};", num_color))],
381 vec![NodeBlueprint::text((logical_line + 1).to_string())],
382 ));
383 }
384
385 if options.show_fold_gutter {
387 if is_fold_start {
388 let is_folded = ed.is_folded(logical_line);
389 let chevron = if is_folded { "▸" } else { "▾" };
390 let h_fold = handle.clone();
391 gutter_items.push(NodeBlueprint::element(
392 Tag::Button,
393 vec![
394 "w-4 h-4 flex items-center justify-center text-[11px] select-none cursor-pointer bg-transparent border-0 p-0 shrink-0"
395 .to_string(),
396 ],
397 vec![
398 Attribute::property("data-fold-toggle", logical_line.to_string()),
399 Attribute::property(
400 "title",
401 if is_folded { "Expand fold" } else { "Collapse fold" },
402 ),
403 Attribute::property(
404 "style",
405 format!("color: {};", theme.gutter_active_fg),
406 ),
407 Attribute::event_listener(EventType::Click, move |e: Event| {
408 e.stop_propagation();
409 h_fold.with_editor_mut(|editor| {
410 editor.toggle_fold_at(logical_line);
411 });
412 }),
413 ],
414 vec![NodeBlueprint::text(chevron)],
415 ));
416 } else {
417 gutter_items.push(NodeBlueprint::element(
418 Tag::Span,
419 vec!["w-4 shrink-0 select-none".to_string()],
420 Vec::new(),
421 Vec::new(),
422 ));
423 }
424 }
425
426 row_children.push(NodeBlueprint::element(
427 Tag::Div,
428 vec!["flex items-center h-full px-1.5 select-none shrink-0 border-r".to_string()],
429 vec![Attribute::property(
430 "style",
431 format!(
432 "width: {:.0}px; background-color: {}; border-color: {};",
433 gutter_width, theme.gutter_bg, theme.border
434 ),
435 )],
436 gutter_items,
437 ));
438 }
439
440 let tokens = ed.highlighter().highlight_line_ast(logical_line, line_str);
442 let search_matches = if ed.search().is_open {
443 ed.search().matches_on_line(logical_line)
444 } else {
445 Vec::new()
446 };
447 let line_selections: Vec<(usize, usize)> = ed
448 .cursors()
449 .all()
450 .iter()
451 .filter_map(|sel| {
452 let (s, e) = sel.ordered_range();
453 if sel.is_collapsed() || logical_line < s.line || logical_line > e.line {
454 return None;
455 }
456 let start_c = if logical_line == s.line { s.col } else { 0 };
457 let end_c = if logical_line == e.line {
458 e.col
459 } else {
460 line_str.chars().count()
461 };
462 Some((start_c, end_c))
463 })
464 .collect();
465 let line_carets: Vec<usize> = ed
466 .cursors()
467 .all()
468 .iter()
469 .filter(|sel| sel.focus.line == logical_line)
470 .map(|sel| sel.focus.col)
471 .collect();
472
473 let mut code_spans = build_themed_line_spans(
474 line_str,
475 &tokens,
476 &theme,
477 &search_matches,
478 active_search_idx,
479 &line_selections,
480 matching_bracket.filter(|p| p.line == logical_line).map(|p| p.col),
481 &line_carets,
482 line_diag_sev,
483 );
484
485 if let Some(hidden) = hidden_count {
487 let h_unfold = handle.clone();
488 code_spans.push(NodeBlueprint::element(
489 Tag::Button,
490 vec![
491 "ml-2 px-1.5 py-0.5 rounded text-[11px] font-mono leading-none whitespace-nowrap shrink-0 cursor-pointer border-0"
492 .to_string(),
493 ],
494 vec![
495 Attribute::property("data-fold-badge", logical_line.to_string()),
496 Attribute::property(
497 "style",
498 format!(
499 "background-color: {}; color: {};",
500 theme.fold_badge_bg, theme.fold_badge_fg
501 ),
502 ),
503 Attribute::event_listener(EventType::Click, move |e: Event| {
504 e.stop_propagation();
505 h_unfold.with_editor_mut(|editor| {
506 editor.toggle_fold_at(logical_line);
507 });
508 }),
509 ],
510 vec![NodeBlueprint::text(format!("⋯ {hidden} lines"))],
511 ));
512 }
513
514 let mut code_attrs = vec![Attribute::property("data-line-index", logical_line.to_string())];
515 if line_diag_sev.is_some() {
516 code_attrs.push(Attribute::property("data-has-diagnostic", "true"));
517 }
518
519 row_children.push(NodeBlueprint::element(
520 Tag::Div,
521 vec![
522 "flex-1 min-w-0 h-full flex items-center pl-2.5 pr-4 whitespace-pre font-mono relative overflow-hidden"
523 .to_string(),
524 ],
525 code_attrs,
526 code_spans,
527 ));
528
529 let row_bg = if is_active_line {
530 format!(
531 "height: {:.1}px; line-height: {:.1}px; background-color: {};",
532 effective_lh, effective_lh, theme.line_highlight
533 )
534 } else {
535 format!(
536 "height: {:.1}px; line-height: {:.1}px;",
537 effective_lh, effective_lh
538 )
539 };
540
541 row_nodes.push(NodeBlueprint::element(
542 Tag::Div,
543 vec!["flex items-center w-full shrink-0 overflow-hidden".to_string()],
544 vec![
545 Attribute::property("data-editor-row", logical_line.to_string()),
546 Attribute::property("style", row_bg),
547 ],
548 row_children,
549 ));
550 }
551
552 let slice_container = NodeBlueprint::element(
553 Tag::Div,
554 vec!["flex flex-col w-full relative".to_string()],
555 vec![
556 Attribute::property("data-editor-slice", "true"),
557 Attribute::property("style", format!("top: {:.2}px;", slice_offset_y)),
558 ],
559 row_nodes,
560 );
561
562 let h_down = handle.clone();
564 let h_move = handle.clone();
565 let h_up = handle.clone();
566 let h_wheel = handle.clone();
567 let viewport_node = NodeBlueprint::element(
568 Tag::Div,
569 vec!["flex-1 min-w-0 h-full overflow-hidden select-none relative".to_string()],
570 vec![
571 Attribute::property("data-editor-viewport", "true"),
572 Attribute::property(
573 "style",
574 format!(
575 "height: {:.1}px; font-size: {:.1}px;",
576 effective_vh, options.font_size
577 ),
578 ),
579 Attribute::event_listener(EventType::MouseDown, move |e: Event| {
580 h_down.with_editor_mut(|editor| {
581 editor.handle_pointer_down(
582 e.offset_x as f32,
583 e.offset_y as f32,
584 e.detail,
585 e.alt_key,
586 e.shift_key,
587 gutter_width,
588 );
589 });
590 }),
591 Attribute::event_listener(EventType::MouseMove, move |e: Event| {
592 if e.buttons & 1 != 0 {
593 h_move.with_editor_mut(|editor| {
594 editor.handle_pointer_drag(
595 e.offset_x as f32,
596 e.offset_y as f32,
597 gutter_width,
598 );
599 });
600 }
601 }),
602 Attribute::event_listener(EventType::MouseUp, move |_e: Event| {
603 h_up.with_editor_mut(CodeEditor::handle_pointer_up);
604 }),
605 Attribute::event_listener(EventType::Wheel, move |e: Event| {
606 e.prevent_default();
607 h_wheel.with_editor_mut(|editor| {
608 editor.handle_wheel(e.delta_y as f32);
609 });
610 }),
611 ],
612 vec![slice_container],
613 );
614
615 let mut body_children = vec![viewport_node];
617 if options.show_minimap {
618 let minimap_cfg = options.minimap;
619 let commands: Arc<Vec<CanvasCommand>> = Arc::new(render_minimap_canvas_commands(
620 &ed,
621 scroll_top,
622 effective_vh,
623 effective_lh,
624 effective_vh,
625 &minimap_cfg,
626 &theme,
627 ));
628 let h_mm_down = handle.clone();
629 let h_mm_move = handle.clone();
630 let h_mm_up = handle.clone();
631 let mm_drag_down = handle.minimap_dragging.clone();
632 let mm_drag_move = handle.minimap_dragging.clone();
633 let mm_drag_up = handle.minimap_dragging.clone();
634
635 let minimap_node = NodeBlueprint::element(
636 Tag::Canvas,
637 vec!["shrink-0 border-l cursor-pointer".to_string()],
638 vec![
639 Attribute::property("data-editor-minimap", "true"),
640 Attribute::property("width", format!("{:.0}", minimap_cfg.width)),
641 Attribute::property("height", format!("{:.0}", effective_vh)),
642 Attribute::property(
643 "style",
644 format!(
645 "width: {:.0}px; height: {:.0}px; background-color: {}; border-color: {};",
646 minimap_cfg.width, effective_vh, theme.minimap_bg, theme.border
647 ),
648 ),
649 Attribute::scene_payload_arc(commands),
650 Attribute::event_listener(EventType::MouseDown, move |e: Event| {
651 e.stop_propagation();
652 mm_drag_down.set(true);
653 h_mm_down.with_editor_mut(|editor| {
654 editor.handle_minimap_pointer(
655 e.offset_y as f32,
656 effective_vh,
657 &minimap_cfg,
658 );
659 });
660 }),
661 Attribute::event_listener(EventType::MouseMove, move |e: Event| {
662 if mm_drag_move.get() && (e.buttons & 1 != 0) {
663 h_mm_move.with_editor_mut(|editor| {
664 editor.handle_minimap_pointer(
665 e.offset_y as f32,
666 effective_vh,
667 &minimap_cfg,
668 );
669 });
670 }
671 }),
672 Attribute::event_listener(EventType::MouseUp, move |_e: Event| {
673 mm_drag_up.set(false);
674 let _ = &h_mm_up;
675 }),
676 ],
677 Vec::new(),
678 );
679 body_children.push(minimap_node);
680 }
681
682 let mut root_children = Vec::with_capacity(3);
684 if ed.search().is_open {
685 root_children.push(build_find_replace_bar(
686 handle,
687 &ed,
688 &theme,
689 options.on_change.clone(),
690 ));
691 }
692
693 root_children.push(NodeBlueprint::element(
695 Tag::Div,
696 vec!["flex flex-1 min-h-0 w-full overflow-hidden".to_string()],
697 Vec::new(),
698 body_children,
699 ));
700
701 if options.show_status_bar {
703 root_children.push(build_status_bar(&ed, &theme));
704 }
705
706 let lang_name = ed.language().display_name();
708 drop(ed);
709
710 let h_key = handle.clone();
711 let on_change_key = options.on_change.clone();
712 let h_input = handle.clone();
713 let on_change_input = options.on_change.clone();
714 let root_classes = if options.class.is_empty() {
715 "strata-code-editor flex flex-col font-mono rounded-lg border overflow-hidden relative outline-none"
716 .to_string()
717 } else {
718 format!(
719 "strata-code-editor flex flex-col font-mono rounded-lg border overflow-hidden relative outline-none {}",
720 options.class
721 )
722 };
723
724 NodeBlueprint::element(
725 Tag::Div,
726 vec![root_classes],
727 vec![
728 Attribute::property("role", "textbox"),
729 Attribute::property("aria-multiline", "true"),
730 Attribute::property("aria-label", format!("Code editor ({lang_name})")),
731 Attribute::property("tabindex", "0"),
732 Attribute::property("data-strata-code-editor", "true"),
733 Attribute::property("data-editor-theme", theme.name.clone()),
734 Attribute::property(
735 "style",
736 format!(
737 "background-color: {}; color: {}; border-color: {};",
738 theme.bg, theme.fg, theme.border
739 ),
740 ),
741 Attribute::event_listener(EventType::KeyDown, move |e: Event| {
742 let mut mutated_text: Option<String> = None;
743 let handled = h_key.with_editor_mut(|editor| {
744 let before_edit_rev = editor.edit_revision();
745 let handled = editor.handle_key_event(&e);
746 if handled
747 && on_change_key.is_some()
748 && editor.edit_revision() != before_edit_rev
749 {
750 mutated_text = Some(editor.text());
751 }
752 handled
753 });
754 if handled {
755 e.prevent_default();
756 e.stop_propagation();
757 if let (Some(cb), Some(text)) = (&on_change_key, mutated_text) {
758 cb(text);
759 }
760 }
761 }),
762 Attribute::event_listener(EventType::Input, move |e: Event| {
763 let mut mutated_text: Option<String> = None;
764 let handled = h_input.with_editor_mut(|editor| {
765 let before_edit_rev = editor.edit_revision();
766 let handled = editor.handle_input_event(&e);
767 if handled
768 && on_change_input.is_some()
769 && editor.edit_revision() != before_edit_rev
770 {
771 mutated_text = Some(editor.text());
772 }
773 handled
774 });
775 if handled {
776 e.prevent_default();
777 e.stop_propagation();
778 if let (Some(cb), Some(text)) = (&on_change_input, mutated_text) {
779 cb(text);
780 }
781 }
782 }),
783 ],
784 root_children,
785 )
786}
787
788fn compute_gutter_width(options: &CodeEditorOptions) -> f32 {
789 let mut w = 12.0; if options.show_line_numbers {
791 w += 42.0;
792 }
793 if options.show_fold_gutter {
794 w += 18.0;
795 }
796 w
797}
798
799#[inline]
800fn char_slice_to_str(s: &str, start_char: usize, end_char: usize) -> &str {
801 if start_char >= end_char {
802 return "";
803 }
804 let start_byte = s
805 .char_indices()
806 .nth(start_char)
807 .map(|(b, _)| b)
808 .unwrap_or(s.len());
809 let end_byte = s
810 .char_indices()
811 .nth(end_char)
812 .map(|(b, _)| b)
813 .unwrap_or(s.len());
814 if start_byte <= end_byte {
815 &s[start_byte..end_byte]
816 } else {
817 ""
818 }
819}
820
821fn make_code_span(text: String, style: Option<&str>) -> NodeBlueprint {
822 let attrs = match style {
823 Some(st) if !st.is_empty() => vec![Attribute::property("style", st.to_string())],
824 _ => Vec::new(),
825 };
826 NodeBlueprint::element(
827 Tag::Span,
828 vec!["whitespace-pre shrink-0".to_string()],
829 attrs,
830 vec![NodeBlueprint::text(text)],
831 )
832}
833
834fn make_caret_anchor(col: usize, caret_color: &str) -> NodeBlueprint {
835 NodeBlueprint::element(
836 Tag::Span,
837 vec!["relative inline-block w-0 h-full shrink-0 pointer-events-none".to_string()],
838 vec![Attribute::property("data-editor-caret-anchor", col.to_string())],
839 vec![NodeBlueprint::element(
840 Tag::Span,
841 vec!["absolute left-0 top-[2px] w-[2px] h-[16px] pointer-events-none".to_string()],
842 vec![
843 Attribute::property("data-editor-caret-col", col.to_string()),
844 Attribute::property("style", format!("background-color: {};", caret_color)),
845 ],
846 Vec::new(),
847 )],
848 )
849}
850
851#[allow(clippy::too_many_arguments)]
852fn build_themed_line_spans(
853 line_text: &str,
854 tokens: &[crate::syntax::SyntaxToken],
855 theme: &EditorTheme,
856 search_matches: &[(usize, &crate::search::SearchMatch)],
857 active_search_idx: usize,
858 selections: &[(usize, usize)],
859 matching_bracket_col: Option<usize>,
860 carets: &[usize],
861 line_diag_sev: Option<DiagnosticSeverity>,
862) -> Vec<NodeBlueprint> {
863 let line_chars = line_text.chars().count();
864
865 let decorate_style = |base: String, char_start: usize, char_end: usize| -> String {
866 let mut style = base;
867 if let Some((idx, _)) = search_matches
868 .iter()
869 .find(|(_, m)| char_start < m.end.col && char_end > m.start.col)
870 {
871 let bg = if *idx == active_search_idx {
872 &theme.find_active_bg
873 } else {
874 &theme.find_match_bg
875 };
876 style.push_str(&format!(" background-color: {}; border-radius: 2px;", bg));
877 } else if selections
878 .iter()
879 .any(|&(s, e)| char_start < e && char_end > s)
880 {
881 style.push_str(&format!(" background-color: {};", theme.selection_bg));
882 } else if let Some(b_col) = matching_bracket_col {
883 if b_col >= char_start && b_col < char_end {
884 style.push_str(&format!(
885 " background-color: {}; border-radius: 2px;",
886 theme.bracket_match_bg
887 ));
888 }
889 }
890 if let Some(sev) = line_diag_sev {
891 style.push_str(&format!(
892 " border-bottom: 2px dotted {};",
893 theme.diagnostic_css(sev)
894 ));
895 }
896 style
897 };
898
899 let mut runs: Vec<(usize, usize, String, String)> = Vec::new();
901 if tokens.is_empty() {
902 if !line_text.is_empty() {
903 let st = decorate_style(String::new(), 0, line_chars);
904 runs.push((0, line_chars, line_text.to_string(), st));
905 }
906 } else {
907 let mut last_byte = 0usize;
908 let mut cur_char = 0usize;
909 for tok in tokens {
910 let start_b = tok.start_col.min(line_text.len());
911 let end_b = tok.end_col.min(line_text.len());
912 if start_b > last_byte
913 && line_text.is_char_boundary(last_byte)
914 && line_text.is_char_boundary(start_b)
915 {
916 let gap = &line_text[last_byte..start_b];
917 let gap_len = gap.chars().count();
918 let st = decorate_style(String::new(), cur_char, cur_char + gap_len);
919 runs.push((cur_char, cur_char + gap_len, gap.to_string(), st));
920 cur_char += gap_len;
921 }
922
923 let tok_char_start = if line_text.is_char_boundary(start_b) {
924 line_text[..start_b].chars().count()
925 } else {
926 cur_char
927 };
928 let tok_char_len = tok.text.chars().count();
929 let tok_char_end = tok_char_start + tok_char_len;
930
931 let mut base_style = format!("color: {};", theme.token_css(tok.token_type));
932 if matches!(
933 tok.token_type,
934 crate::syntax::TokenType::Keyword
935 | crate::syntax::TokenType::ControlFlow
936 | crate::syntax::TokenType::Heading
937 ) {
938 base_style.push_str(" font-weight: 600;");
939 } else if matches!(
940 tok.token_type,
941 crate::syntax::TokenType::Comment | crate::syntax::TokenType::DocComment
942 ) {
943 base_style.push_str(" font-style: italic;");
944 }
945 let st = decorate_style(base_style, tok_char_start, tok_char_end);
946 runs.push((tok_char_start, tok_char_end, tok.text.clone(), st));
947 last_byte = end_b.max(last_byte);
948 cur_char = tok_char_end;
949 }
950 if last_byte < line_text.len() && line_text.is_char_boundary(last_byte) {
951 let tail = &line_text[last_byte..];
952 let tail_len = tail.chars().count();
953 let st = decorate_style(String::new(), cur_char, cur_char + tail_len);
954 runs.push((cur_char, cur_char + tail_len, tail.to_string(), st));
955 }
956 }
957
958 let mut clamped_carets: Vec<usize> = carets.iter().map(|&c| c.min(line_chars)).collect();
961 clamped_carets.sort_unstable();
962 clamped_carets.dedup();
963
964 let mut nodes = Vec::with_capacity(runs.len() + clamped_carets.len() * 2);
965 let mut caret_idx = 0usize;
966
967 for (r_start, r_end, text, style) in runs {
968 while caret_idx < clamped_carets.len() && clamped_carets[caret_idx] <= r_start {
969 nodes.push(make_caret_anchor(clamped_carets[caret_idx], &theme.caret));
970 caret_idx += 1;
971 }
972
973 let mut local_start = 0usize;
974 let run_len = r_end.saturating_sub(r_start);
975 while caret_idx < clamped_carets.len() && clamped_carets[caret_idx] < r_end {
976 let col = clamped_carets[caret_idx];
977 let split_at = col.saturating_sub(r_start).min(run_len);
978 if split_at > local_start {
979 let piece = char_slice_to_str(&text, local_start, split_at);
980 if !piece.is_empty() {
981 nodes.push(make_code_span(piece.to_string(), Some(style.as_str())));
982 }
983 }
984 nodes.push(make_caret_anchor(col, &theme.caret));
985 local_start = split_at;
986 caret_idx += 1;
987 }
988
989 if local_start == 0 {
990 if !text.is_empty() {
991 nodes.push(make_code_span(text, Some(style.as_str())));
992 }
993 } else if local_start < run_len {
994 let tail = char_slice_to_str(&text, local_start, run_len);
995 if !tail.is_empty() {
996 nodes.push(make_code_span(tail.to_string(), Some(style.as_str())));
997 }
998 }
999 }
1000
1001 while caret_idx < clamped_carets.len() {
1003 nodes.push(make_caret_anchor(clamped_carets[caret_idx], &theme.caret));
1004 caret_idx += 1;
1005 }
1006
1007 nodes
1008}
1009
1010fn build_find_replace_bar(
1011 handle: &CodeEditorHandle,
1012 ed: &CodeEditor,
1013 theme: &EditorTheme,
1014 on_change: Option<Rc<dyn Fn(String)>>,
1015) -> NodeBlueprint {
1016 let search = ed.search();
1017 let status = search.status_label();
1018
1019 let h_query = handle.clone();
1020 let h_case = handle.clone();
1021 let h_word = handle.clone();
1022 let h_regex = handle.clone();
1023 let h_prev = handle.clone();
1024 let h_next = handle.clone();
1025 let h_close = handle.clone();
1026 let h_find_key = handle.clone();
1027
1028 let toggle_btn = |label: &str, active: bool, attr: &str, on_click: Box<dyn Fn(Event)>| {
1029 let style = if active {
1030 format!(
1031 "background-color: {}; color: {}; border-color: {};",
1032 theme.selection_bg, theme.fg, theme.caret
1033 )
1034 } else {
1035 format!(
1036 "background-color: transparent; color: {}; border-color: {};",
1037 theme.gutter_fg, theme.panel_border
1038 )
1039 };
1040 NodeBlueprint::element(
1041 Tag::Button,
1042 vec!["px-1.5 py-0.5 text-xs font-mono rounded border cursor-pointer whitespace-nowrap shrink-0".to_string()],
1043 vec![
1044 Attribute::property("data-find-action", attr),
1045 Attribute::property("style", style),
1046 Attribute::event_listener(EventType::Click, move |e: Event| {
1047 e.stop_propagation();
1048 on_click(e);
1049 }),
1050 ],
1051 vec![NodeBlueprint::text(label)],
1052 )
1053 };
1054
1055 let find_row = NodeBlueprint::element(
1056 Tag::Div,
1057 vec!["flex items-center gap-1.5".to_string()],
1058 Vec::new(),
1059 vec![
1060 NodeBlueprint::element(
1061 Tag::Input,
1062 vec!["flex-1 min-w-[140px] px-2 py-0.5 text-xs font-mono rounded border".to_string()],
1063 vec![
1064 Attribute::property("type", "text"),
1065 Attribute::property("placeholder", "Find..."),
1066 Attribute::property("value", search.query.clone()),
1067 Attribute::property("data-find-input", "query"),
1068 Attribute::property(
1069 "style",
1070 format!(
1071 "background-color: {}; color: {}; border-color: {};",
1072 theme.bg, theme.fg, theme.panel_border
1073 ),
1074 ),
1075 Attribute::value_listener(EventType::Input, move |val: String| {
1076 h_query.with_editor_mut(|editor| editor.set_find_query(val));
1077 }),
1078 Attribute::event_listener(EventType::KeyDown, move |e: Event| {
1079 match e.key.as_str() {
1080 "Escape" => {
1081 e.prevent_default();
1082 e.stop_propagation();
1083 h_find_key.with_editor_mut(CodeEditor::close_find);
1084 }
1085 "Enter" => {
1086 e.prevent_default();
1087 e.stop_propagation();
1088 let shift = e.shift_key;
1089 h_find_key.with_editor_mut(|editor| {
1090 if shift {
1091 let _ = editor.find_prev();
1092 } else {
1093 let _ = editor.find_next();
1094 }
1095 });
1096 }
1097 _ => {
1098 e.stop_propagation();
1099 }
1100 }
1101 }),
1102 ],
1103 Vec::new(),
1104 ),
1105 toggle_btn(
1106 "Aa",
1107 search.case_sensitive,
1108 "case",
1109 Box::new(move |_| {
1110 h_case.with_editor_mut(|editor| {
1111 let mut s = std::mem::take(editor.search_mut());
1112 s.toggle_case_sensitive(editor.buffer());
1113 *editor.search_mut() = s;
1114 });
1115 }),
1116 ),
1117 toggle_btn(
1118 "Ab",
1119 search.whole_word,
1120 "whole-word",
1121 Box::new(move |_| {
1122 h_word.with_editor_mut(|editor| {
1123 let mut s = std::mem::take(editor.search_mut());
1124 s.toggle_whole_word(editor.buffer());
1125 *editor.search_mut() = s;
1126 });
1127 }),
1128 ),
1129 toggle_btn(
1130 ".*",
1131 search.use_regex,
1132 "regex",
1133 Box::new(move |_| {
1134 h_regex.with_editor_mut(|editor| {
1135 let mut s = std::mem::take(editor.search_mut());
1136 s.toggle_regex(editor.buffer());
1137 *editor.search_mut() = s;
1138 });
1139 }),
1140 ),
1141 NodeBlueprint::element(
1142 Tag::Span,
1143 vec!["text-xs font-mono px-1 min-w-[64px] text-center select-none whitespace-nowrap shrink-0".to_string()],
1144 vec![
1145 Attribute::property("data-find-status", "true"),
1146 Attribute::property("style", format!("color: {};", theme.gutter_active_fg)),
1147 ],
1148 vec![NodeBlueprint::text(status)],
1149 ),
1150 toggle_btn(
1151 "↑",
1152 false,
1153 "prev",
1154 Box::new(move |_| {
1155 h_prev.with_editor_mut(|editor| {
1156 let _ = editor.find_prev();
1157 });
1158 }),
1159 ),
1160 toggle_btn(
1161 "↓",
1162 false,
1163 "next",
1164 Box::new(move |_| {
1165 h_next.with_editor_mut(|editor| {
1166 let _ = editor.find_next();
1167 });
1168 }),
1169 ),
1170 toggle_btn(
1171 "×",
1172 false,
1173 "close",
1174 Box::new(move |_| {
1175 h_close.with_editor_mut(CodeEditor::close_find);
1176 }),
1177 ),
1178 ],
1179 );
1180
1181 let mut rows = vec![find_row];
1182
1183 if search.show_replace {
1184 let h_repl_in = handle.clone();
1185 let h_repl_key = handle.clone();
1186 let h_repl_one = handle.clone();
1187 let h_repl_all = handle.clone();
1188 let cb_repl_enter = on_change.clone();
1189 let cb_one = on_change.clone();
1190 let cb_all = on_change;
1191
1192 rows.push(NodeBlueprint::element(
1193 Tag::Div,
1194 vec!["flex items-center gap-1.5 mt-1".to_string()],
1195 Vec::new(),
1196 vec![
1197 NodeBlueprint::element(
1198 Tag::Input,
1199 vec!["flex-1 min-w-[140px] px-2 py-0.5 text-xs font-mono rounded border".to_string()],
1200 vec![
1201 Attribute::property("type", "text"),
1202 Attribute::property("placeholder", "Replace..."),
1203 Attribute::property("value", search.replacement.clone()),
1204 Attribute::property("data-find-input", "replace"),
1205 Attribute::property(
1206 "style",
1207 format!(
1208 "background-color: {}; color: {}; border-color: {};",
1209 theme.bg, theme.fg, theme.panel_border
1210 ),
1211 ),
1212 Attribute::value_listener(EventType::Input, move |val: String| {
1213 h_repl_in.with_editor_mut(|editor| editor.set_replace_text(val));
1214 }),
1215 Attribute::event_listener(EventType::KeyDown, move |e: Event| {
1216 match e.key.as_str() {
1217 "Escape" => {
1218 e.prevent_default();
1219 e.stop_propagation();
1220 h_repl_key.with_editor_mut(CodeEditor::close_find);
1221 }
1222 "Enter" => {
1223 e.prevent_default();
1224 e.stop_propagation();
1225 let updated = h_repl_key.with_editor_mut(|editor| {
1226 if editor.replace_current() {
1227 Some(editor.text())
1228 } else {
1229 None
1230 }
1231 });
1232 if let (Some(cb), Some(text)) = (&cb_repl_enter, updated) {
1233 cb(text);
1234 }
1235 }
1236 _ => {
1237 e.stop_propagation();
1238 }
1239 }
1240 }),
1241 ],
1242 Vec::new(),
1243 ),
1244 toggle_btn(
1245 "Replace",
1246 false,
1247 "replace",
1248 Box::new(move |_| {
1249 let updated = h_repl_one.with_editor_mut(|editor| {
1250 if editor.replace_current() {
1251 Some(editor.text())
1252 } else {
1253 None
1254 }
1255 });
1256 if let (Some(cb), Some(text)) = (&cb_one, updated) {
1257 cb(text);
1258 }
1259 }),
1260 ),
1261 toggle_btn(
1262 "All",
1263 false,
1264 "replace-all",
1265 Box::new(move |_| {
1266 let updated = h_repl_all.with_editor_mut(|editor| {
1267 if editor.replace_all() > 0 {
1268 Some(editor.text())
1269 } else {
1270 None
1271 }
1272 });
1273 if let (Some(cb), Some(text)) = (&cb_all, updated) {
1274 cb(text);
1275 }
1276 }),
1277 ),
1278 ],
1279 ));
1280 }
1281
1282 NodeBlueprint::element(
1283 Tag::Div,
1284 vec!["px-2.5 py-1.5 border-b flex flex-col shrink-0".to_string()],
1285 vec![
1286 Attribute::property("data-find-replace-bar", "true"),
1287 Attribute::property(
1288 "style",
1289 format!(
1290 "background-color: {}; border-color: {};",
1291 theme.panel_bg, theme.panel_border
1292 ),
1293 ),
1294 ],
1295 rows,
1296 )
1297}
1298
1299fn build_status_bar(ed: &CodeEditor, theme: &EditorTheme) -> NodeBlueprint {
1300 let primary = ed.cursors().primary().focus;
1301 let counts = ed.diagnostic_counts();
1302 let cursor_badge = if ed.cursors().count() > 1 {
1303 format!(
1304 "Ln {}, Col {} ({} cursors)",
1305 primary.line + 1,
1306 primary.col + 1,
1307 ed.cursors().count()
1308 )
1309 } else {
1310 format!("Ln {}, Col {}", primary.line + 1, primary.col + 1)
1311 };
1312
1313 NodeBlueprint::element(
1314 Tag::Div,
1315 vec![
1316 "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"
1317 .to_string(),
1318 ],
1319 vec![
1320 Attribute::property("data-editor-statusbar", "true"),
1321 Attribute::property(
1322 "style",
1323 format!(
1324 "background-color: {}; color: {}; border-color: {};",
1325 theme.gutter_bg, theme.gutter_fg, theme.border
1326 ),
1327 ),
1328 ],
1329 vec![
1330 NodeBlueprint::element(
1331 Tag::Div,
1332 vec!["flex items-center gap-3 whitespace-nowrap overflow-hidden shrink-0".to_string()],
1333 Vec::new(),
1334 vec![
1335 NodeBlueprint::element(
1336 Tag::Span,
1337 vec!["whitespace-nowrap shrink-0".to_string()],
1338 vec![Attribute::property(
1339 "style",
1340 format!("color: {};", theme.diag_error),
1341 )],
1342 vec![NodeBlueprint::text(format!("✕ {}", counts.errors))],
1343 ),
1344 NodeBlueprint::element(
1345 Tag::Span,
1346 vec!["whitespace-nowrap shrink-0".to_string()],
1347 vec![Attribute::property(
1348 "style",
1349 format!("color: {};", theme.diag_warning),
1350 )],
1351 vec![NodeBlueprint::text(format!("▲ {}", counts.warnings))],
1352 ),
1353 NodeBlueprint::element(
1354 Tag::Span,
1355 vec!["whitespace-nowrap shrink-0".to_string()],
1356 vec![Attribute::property("data-status-cursor", "true")],
1357 vec![NodeBlueprint::text(cursor_badge)],
1358 ),
1359 ],
1360 ),
1361 NodeBlueprint::element(
1362 Tag::Div,
1363 vec!["flex items-center gap-3 whitespace-nowrap overflow-hidden shrink-0".to_string()],
1364 Vec::new(),
1365 vec![
1366 NodeBlueprint::element(
1367 Tag::Span,
1368 vec!["whitespace-nowrap shrink-0".to_string()],
1369 vec![Attribute::property("data-status-spaces", "true")],
1370 vec![NodeBlueprint::text(format!("Spaces: {}", ed.tab_size()))],
1371 ),
1372 NodeBlueprint::element(
1373 Tag::Span,
1374 vec!["whitespace-nowrap shrink-0".to_string()],
1375 Vec::new(),
1376 vec![NodeBlueprint::text("UTF-8")],
1377 ),
1378 NodeBlueprint::element(
1379 Tag::Span,
1380 vec!["font-semibold whitespace-nowrap shrink-0".to_string()],
1381 vec![Attribute::property(
1382 "style",
1383 format!("color: {};", theme.gutter_active_fg),
1384 )],
1385 vec![NodeBlueprint::text(ed.language().display_name())],
1386 ),
1387 ],
1388 ),
1389 ],
1390 )
1391}