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#[component]
233pub fn CodeEditorWidget(
234 handle: CodeEditorHandle,
235 language: Option<Language>,
236 theme: Option<EditorTheme>,
237 show_minimap: Option<bool>,
238 show_line_numbers: Option<bool>,
239 show_fold_gutter: Option<bool>,
240 show_status_bar: Option<bool>,
241 read_only: Option<bool>,
242 font_size: Option<f32>,
243 line_height: Option<f32>,
244 viewport_height: Option<f32>,
245 on_change: Option<Rc<dyn Fn(String)>>,
246 class: Option<&'static str>,
247) -> View {
248 if let Some(lang) = language {
249 let needs_switch = handle.inner.borrow().language() != lang;
250 if needs_switch {
251 handle.inner.borrow_mut().set_language(lang);
252 }
253 }
254 if let Some(ro) = read_only {
255 handle.inner.borrow_mut().set_read_only(ro);
256 }
257
258 let options = CodeEditorOptions {
259 show_line_numbers: show_line_numbers.unwrap_or(true),
260 show_fold_gutter: show_fold_gutter.unwrap_or(true),
261 show_minimap: show_minimap.unwrap_or(true),
262 show_status_bar: show_status_bar.unwrap_or(true),
263 read_only: read_only.unwrap_or(false),
264 font_size: font_size.unwrap_or(13.0),
265 line_height: line_height.unwrap_or(22.0),
266 viewport_height: viewport_height.unwrap_or(480.0),
267 minimap: MinimapConfig::default(),
268 theme,
269 class: class.unwrap_or("").to_string(),
270 on_change,
271 };
272
273 View::new(render_interactive_editor(&handle, &options))
274}
275
276pub use CodeEditorWidget as CodeEditorView;
278
279pub fn render_interactive_editor(
282 handle: &CodeEditorHandle,
283 options: &CodeEditorOptions,
284) -> NodeBlueprint {
285 let _rev = handle.version();
287
288 {
290 let mut ed = handle.inner.borrow_mut();
291 ed.set_read_only(options.read_only);
292 ed.set_line_height(options.line_height);
293 ed.set_viewport_height(options.viewport_height);
294 ed.set_char_width((options.font_size * 0.62).max(5.5));
295 let _ = ed.ensure_folds_cached();
296 }
297
298 let ed = handle.inner.borrow();
299 let theme = options.theme.clone().unwrap_or_else(|| ed.theme().clone());
300 let effective_lh = options.line_height.max(14.0);
301 let effective_vh = options.viewport_height.max(80.0);
302 let scroll_top = ed.scroll_top();
303 let gutter_width = compute_gutter_width(options);
304
305 let visible_lines = ed.visible_logical_lines();
306 let total_visible = visible_lines.len().max(1);
307 let first_visible = (scroll_top / effective_lh).floor() as usize;
308 let visible_count = (effective_vh / effective_lh).ceil() as usize;
309 let start_idx = first_visible.saturating_sub(2).min(total_visible);
310 let end_idx = (first_visible + visible_count + 2).min(total_visible);
311
312 let top_spacer_h = start_idx as f32 * effective_lh;
313 let bottom_spacer_h = total_visible.saturating_sub(end_idx) as f32 * effective_lh;
314
315 let primary_pos = ed.cursors().primary().focus;
316 let matching_bracket = ed
317 .highlighter()
318 .find_matching_bracket(ed.buffer(), primary_pos);
319 let all_folds = ed.fold_ranges();
320 let active_search_idx = ed.search().active_match_index;
321
322 let mut row_nodes = Vec::with_capacity((end_idx - start_idx) + 2);
323
324 if top_spacer_h > 0.0 {
325 row_nodes.push(NodeBlueprint::element(
326 Tag::Div,
327 vec!["w-full pointer-events-none shrink-0".to_string()],
328 vec![Attribute::property(
329 "style",
330 format!("height: {:.1}px;", top_spacer_h),
331 )],
332 Vec::new(),
333 ));
334 }
335
336 for &logical_line in &visible_lines[start_idx..end_idx] {
337 let Some(line_str) = ed.buffer().line(logical_line) else {
338 continue;
339 };
340 let is_active_line = logical_line == primary_pos.line;
341 let line_diag_sev = ed.diagnostics().max_severity_on_line(logical_line);
342 let line_diags = ed.diagnostics().diagnostics_on_line(logical_line);
343 let is_fold_start = all_folds
344 .iter()
345 .any(|f| f.start_line == logical_line && f.end_line > f.start_line);
346 let hidden_count = ed.folded_hidden_count(logical_line);
347
348 let mut row_children = Vec::with_capacity(4);
349
350 if options.show_line_numbers || options.show_fold_gutter {
352 let mut gutter_items = Vec::with_capacity(3);
353
354 let diag_dot = if let Some(sev) = line_diag_sev {
356 let tooltip = line_diags
357 .first()
358 .map(|d| d.message.clone())
359 .unwrap_or_default();
360 NodeBlueprint::element(
361 Tag::Span,
362 vec!["inline-block w-2 h-2 rounded-full mr-1 shrink-0".to_string()],
363 vec![
364 Attribute::property("data-diag-severity", sev.label()),
365 Attribute::property("title", tooltip),
366 Attribute::property(
367 "style",
368 format!("background-color: {};", theme.diagnostic_css(sev)),
369 ),
370 ],
371 Vec::new(),
372 )
373 } else {
374 NodeBlueprint::element(
375 Tag::Span,
376 vec!["inline-block w-2 h-2 mr-1 shrink-0".to_string()],
377 Vec::new(),
378 Vec::new(),
379 )
380 };
381 gutter_items.push(diag_dot);
382
383 if options.show_line_numbers {
385 let num_color = if is_active_line {
386 &theme.gutter_active_fg
387 } else {
388 &theme.gutter_fg
389 };
390 gutter_items.push(NodeBlueprint::element(
391 Tag::Span,
392 vec!["w-9 text-right pr-1.5 select-none font-mono text-xs shrink-0".to_string()],
393 vec![Attribute::property("style", format!("color: {};", num_color))],
394 vec![NodeBlueprint::text((logical_line + 1).to_string())],
395 ));
396 }
397
398 if options.show_fold_gutter {
400 if is_fold_start {
401 let is_folded = ed.is_folded(logical_line);
402 let chevron = if is_folded { "▸" } else { "▾" };
403 let h_fold = handle.clone();
404 gutter_items.push(NodeBlueprint::element(
405 Tag::Button,
406 vec![
407 "w-4 h-4 flex items-center justify-center text-[11px] select-none cursor-pointer bg-transparent border-0 p-0 shrink-0"
408 .to_string(),
409 ],
410 vec![
411 Attribute::property("data-fold-toggle", logical_line.to_string()),
412 Attribute::property(
413 "title",
414 if is_folded { "Expand fold" } else { "Collapse fold" },
415 ),
416 Attribute::property(
417 "style",
418 format!("color: {};", theme.gutter_active_fg),
419 ),
420 Attribute::event_listener(EventType::Click, move |e: Event| {
421 e.stop_propagation();
422 h_fold.with_editor_mut(|editor| {
423 editor.toggle_fold_at(logical_line);
424 });
425 }),
426 ],
427 vec![NodeBlueprint::text(chevron)],
428 ));
429 } else {
430 gutter_items.push(NodeBlueprint::element(
431 Tag::Span,
432 vec!["w-4 shrink-0 select-none".to_string()],
433 Vec::new(),
434 Vec::new(),
435 ));
436 }
437 }
438
439 row_children.push(NodeBlueprint::element(
440 Tag::Div,
441 vec!["flex items-center px-1.5 select-none shrink-0 border-r".to_string()],
442 vec![Attribute::property(
443 "style",
444 format!(
445 "width: {:.0}px; background-color: {}; border-color: {};",
446 gutter_width, theme.gutter_bg, theme.border
447 ),
448 )],
449 gutter_items,
450 ));
451 }
452
453 let tokens = ed.highlighter().highlight_line_ast(logical_line, line_str);
455 let search_matches = ed.search().matches_on_line(logical_line);
456 let line_selections: Vec<(usize, usize)> = ed
457 .cursors()
458 .all()
459 .iter()
460 .filter_map(|sel| {
461 let (s, e) = sel.ordered_range();
462 if sel.is_collapsed() || logical_line < s.line || logical_line > e.line {
463 return None;
464 }
465 let start_c = if logical_line == s.line { s.col } else { 0 };
466 let end_c = if logical_line == e.line {
467 e.col
468 } else {
469 line_str.chars().count()
470 };
471 Some((start_c, end_c))
472 })
473 .collect();
474 let line_carets: Vec<usize> = ed
475 .cursors()
476 .all()
477 .iter()
478 .filter(|sel| sel.focus.line == logical_line)
479 .map(|sel| sel.focus.col)
480 .collect();
481
482 let mut code_spans = build_themed_line_spans(
483 line_str,
484 &tokens,
485 &theme,
486 &search_matches,
487 active_search_idx,
488 &line_selections,
489 matching_bracket.filter(|p| p.line == logical_line).map(|p| p.col),
490 &line_carets,
491 line_diag_sev,
492 );
493
494 if let Some(hidden) = hidden_count {
496 let h_unfold = handle.clone();
497 code_spans.push(NodeBlueprint::element(
498 Tag::Button,
499 vec![
500 "ml-2 px-1.5 py-0.5 rounded text-[11px] font-mono cursor-pointer border-0"
501 .to_string(),
502 ],
503 vec![
504 Attribute::property("data-fold-badge", logical_line.to_string()),
505 Attribute::property(
506 "style",
507 format!(
508 "background-color: {}; color: {};",
509 theme.fold_badge_bg, theme.fold_badge_fg
510 ),
511 ),
512 Attribute::event_listener(EventType::Click, move |e: Event| {
513 e.stop_propagation();
514 h_unfold.with_editor_mut(|editor| {
515 editor.toggle_fold_at(logical_line);
516 });
517 }),
518 ],
519 vec![NodeBlueprint::text(format!("⋯ {hidden} lines"))],
520 ));
521 }
522
523 let code_cell_style = if let Some(sev) = line_diag_sev {
524 format!(
525 "text-decoration: underline wavy {};",
526 theme.diagnostic_css(sev)
527 )
528 } else {
529 String::new()
530 };
531
532 let mut code_attrs = vec![Attribute::property("data-line-index", logical_line.to_string())];
533 if !code_cell_style.is_empty() {
534 code_attrs.push(Attribute::property("data-has-diagnostic", "true"));
535 }
536
537 row_children.push(NodeBlueprint::element(
538 Tag::Span,
539 vec!["flex-1 pl-2.5 pr-4 whitespace-pre font-mono relative".to_string()],
540 code_attrs,
541 code_spans,
542 ));
543
544 let row_bg = if is_active_line {
545 format!(
546 "height: {:.1}px; line-height: {:.1}px; background-color: {};",
547 effective_lh, effective_lh, theme.line_highlight
548 )
549 } else {
550 format!(
551 "height: {:.1}px; line-height: {:.1}px;",
552 effective_lh, effective_lh
553 )
554 };
555
556 row_nodes.push(NodeBlueprint::element(
557 Tag::Div,
558 vec!["flex items-center w-full shrink-0".to_string()],
559 vec![
560 Attribute::property("data-editor-row", logical_line.to_string()),
561 Attribute::property("style", row_bg),
562 ],
563 row_children,
564 ));
565 }
566
567 if bottom_spacer_h > 0.0 {
568 row_nodes.push(NodeBlueprint::element(
569 Tag::Div,
570 vec!["w-full pointer-events-none shrink-0".to_string()],
571 vec![Attribute::property(
572 "style",
573 format!("height: {:.1}px;", bottom_spacer_h),
574 )],
575 Vec::new(),
576 ));
577 }
578
579 let h_down = handle.clone();
581 let h_move = handle.clone();
582 let h_up = handle.clone();
583 let h_wheel = handle.clone();
584 let viewport_node = NodeBlueprint::element(
585 Tag::Div,
586 vec!["flex-1 min-w-0 h-full overflow-hidden select-none relative".to_string()],
587 vec![
588 Attribute::property("data-editor-viewport", "true"),
589 Attribute::property(
590 "style",
591 format!(
592 "height: {:.1}px; font-size: {:.1}px;",
593 effective_vh, options.font_size
594 ),
595 ),
596 Attribute::event_listener(EventType::MouseDown, move |e: Event| {
597 h_down.with_editor_mut(|editor| {
598 editor.handle_pointer_down(
599 e.offset_x as f32,
600 e.offset_y as f32,
601 e.detail,
602 e.alt_key,
603 e.shift_key,
604 gutter_width,
605 );
606 });
607 }),
608 Attribute::event_listener(EventType::MouseMove, move |e: Event| {
609 if e.buttons & 1 != 0 {
610 h_move.with_editor_mut(|editor| {
611 editor.handle_pointer_drag(
612 e.offset_x as f32,
613 e.offset_y as f32,
614 gutter_width,
615 );
616 });
617 }
618 }),
619 Attribute::event_listener(EventType::MouseUp, move |_e: Event| {
620 h_up.with_editor_mut(CodeEditor::handle_pointer_up);
621 }),
622 Attribute::event_listener(EventType::Wheel, move |e: Event| {
623 e.prevent_default();
624 h_wheel.with_editor_mut(|editor| {
625 editor.handle_wheel(e.delta_y as f32);
626 });
627 }),
628 ],
629 row_nodes,
630 );
631
632 let mut body_children = vec![viewport_node];
634 if options.show_minimap {
635 let minimap_cfg = options.minimap;
636 let commands: Arc<Vec<CanvasCommand>> = Arc::new(render_minimap_canvas_commands(
637 &ed,
638 scroll_top,
639 effective_vh,
640 effective_lh,
641 effective_vh,
642 &minimap_cfg,
643 &theme,
644 ));
645 let h_mm_down = handle.clone();
646 let h_mm_move = handle.clone();
647 let h_mm_up = handle.clone();
648 let mm_drag_down = handle.minimap_dragging.clone();
649 let mm_drag_move = handle.minimap_dragging.clone();
650 let mm_drag_up = handle.minimap_dragging.clone();
651
652 let minimap_node = NodeBlueprint::element(
653 Tag::Canvas,
654 vec!["shrink-0 border-l cursor-pointer".to_string()],
655 vec![
656 Attribute::property("data-editor-minimap", "true"),
657 Attribute::property("width", format!("{:.0}", minimap_cfg.width)),
658 Attribute::property("height", format!("{:.0}", effective_vh)),
659 Attribute::property(
660 "style",
661 format!(
662 "width: {:.0}px; height: {:.0}px; background-color: {}; border-color: {};",
663 minimap_cfg.width, effective_vh, theme.minimap_bg, theme.border
664 ),
665 ),
666 Attribute::scene_payload_arc(commands),
667 Attribute::event_listener(EventType::MouseDown, move |e: Event| {
668 e.stop_propagation();
669 mm_drag_down.set(true);
670 h_mm_down.with_editor_mut(|editor| {
671 editor.handle_minimap_pointer(
672 e.offset_y as f32,
673 effective_vh,
674 &minimap_cfg,
675 );
676 });
677 }),
678 Attribute::event_listener(EventType::MouseMove, move |e: Event| {
679 if mm_drag_move.get() && (e.buttons & 1 != 0) {
680 h_mm_move.with_editor_mut(|editor| {
681 editor.handle_minimap_pointer(
682 e.offset_y as f32,
683 effective_vh,
684 &minimap_cfg,
685 );
686 });
687 }
688 }),
689 Attribute::event_listener(EventType::MouseUp, move |_e: Event| {
690 mm_drag_up.set(false);
691 let _ = &h_mm_up;
692 }),
693 ],
694 Vec::new(),
695 );
696 body_children.push(minimap_node);
697 }
698
699 let mut root_children = Vec::with_capacity(3);
701 if ed.search().is_open {
702 root_children.push(build_find_replace_bar(
703 handle,
704 &ed,
705 &theme,
706 options.on_change.clone(),
707 ));
708 }
709
710 root_children.push(NodeBlueprint::element(
712 Tag::Div,
713 vec!["flex flex-1 min-h-0 w-full overflow-hidden".to_string()],
714 Vec::new(),
715 body_children,
716 ));
717
718 if options.show_status_bar {
720 root_children.push(build_status_bar(&ed, &theme));
721 }
722
723 let lang_name = ed.language().display_name();
725 drop(ed);
726
727 let h_key = handle.clone();
728 let on_change_key = options.on_change.clone();
729 let root_classes = if options.class.is_empty() {
730 "strata-code-editor flex flex-col font-mono rounded-lg border overflow-hidden relative outline-none"
731 .to_string()
732 } else {
733 format!(
734 "strata-code-editor flex flex-col font-mono rounded-lg border overflow-hidden relative outline-none {}",
735 options.class
736 )
737 };
738
739 NodeBlueprint::element(
740 Tag::Div,
741 vec![root_classes],
742 vec![
743 Attribute::property("role", "textbox"),
744 Attribute::property("aria-multiline", "true"),
745 Attribute::property("aria-label", format!("Code editor ({lang_name})")),
746 Attribute::property("tabindex", "0"),
747 Attribute::property("data-strata-code-editor", "true"),
748 Attribute::property("data-editor-theme", theme.name.clone()),
749 Attribute::property(
750 "style",
751 format!(
752 "background-color: {}; color: {}; border-color: {};",
753 theme.bg, theme.fg, theme.border
754 ),
755 ),
756 Attribute::event_listener(EventType::KeyDown, move |e: Event| {
757 let mut mutated_text: Option<String> = None;
758 let handled = h_key.with_editor_mut(|editor| {
759 let before_rev_len = editor.buffer().total_text_byte_len();
760 let handled = editor.handle_key_event(&e);
761 if handled
762 && on_change_key.is_some()
763 && (editor.buffer().total_text_byte_len() != before_rev_len
764 || matches!(
765 e.key.as_str(),
766 "Enter" | "Backspace" | "Delete" | "Tab" | "z" | "Z" | "y" | "Y" | "/"
767 )
768 || e.key.chars().count() == 1)
769 {
770 mutated_text = Some(editor.text());
771 }
772 handled
773 });
774 if handled {
775 e.prevent_default();
776 e.stop_propagation();
777 if let (Some(cb), Some(text)) = (&on_change_key, mutated_text) {
778 cb(text);
779 }
780 }
781 }),
782 ],
783 root_children,
784 )
785}
786
787fn compute_gutter_width(options: &CodeEditorOptions) -> f32 {
788 let mut w = 12.0; if options.show_line_numbers {
790 w += 42.0;
791 }
792 if options.show_fold_gutter {
793 w += 18.0;
794 }
795 w
796}
797
798#[allow(clippy::too_many_arguments)]
799fn build_themed_line_spans(
800 line_text: &str,
801 tokens: &[crate::syntax::SyntaxToken],
802 theme: &EditorTheme,
803 search_matches: &[(usize, &crate::search::SearchMatch)],
804 active_search_idx: usize,
805 selections: &[(usize, usize)],
806 matching_bracket_col: Option<usize>,
807 carets: &[usize],
808 line_diag_sev: Option<DiagnosticSeverity>,
809) -> Vec<NodeBlueprint> {
810 let mut nodes = Vec::new();
811 let line_chars = line_text.chars().count();
812
813 if tokens.is_empty() {
814 if !line_text.is_empty() {
815 nodes.push(NodeBlueprint::text(line_text));
816 }
817 } else {
818 let mut last_byte = 0usize;
819 for tok in tokens {
820 let start_b = tok.start_col.min(line_text.len());
821 let end_b = tok.end_col.min(line_text.len());
822 if start_b > last_byte
823 && line_text.is_char_boundary(last_byte)
824 && line_text.is_char_boundary(start_b)
825 {
826 nodes.push(NodeBlueprint::text(&line_text[last_byte..start_b]));
827 }
828
829 let tok_char_start = if line_text.is_char_boundary(start_b) {
830 line_text[..start_b].chars().count()
831 } else {
832 0
833 };
834 let tok_char_end = tok_char_start + tok.text.chars().count();
835
836 let mut style = format!("color: {};", theme.token_css(tok.token_type));
837 if matches!(
838 tok.token_type,
839 crate::syntax::TokenType::Keyword
840 | crate::syntax::TokenType::ControlFlow
841 | crate::syntax::TokenType::Heading
842 ) {
843 style.push_str(" font-weight: 600;");
844 } else if matches!(
845 tok.token_type,
846 crate::syntax::TokenType::Comment | crate::syntax::TokenType::DocComment
847 ) {
848 style.push_str(" font-style: italic;");
849 }
850
851 if selections
853 .iter()
854 .any(|&(s, e)| tok_char_start < e && tok_char_end > s)
855 {
856 style.push_str(&format!(" background-color: {};", theme.selection_bg));
857 } else if let Some((idx, _)) = search_matches
858 .iter()
859 .find(|(_, m)| tok_char_start < m.end.col && tok_char_end > m.start.col)
860 {
861 let bg = if *idx == active_search_idx {
862 &theme.find_active_bg
863 } else {
864 &theme.find_match_bg
865 };
866 style.push_str(&format!(" background-color: {}; border-radius: 2px;", bg));
867 } else if let Some(b_col) = matching_bracket_col {
868 if b_col >= tok_char_start && b_col < tok_char_end {
869 style.push_str(&format!(
870 " background-color: {}; border-radius: 2px;",
871 theme.bracket_match_bg
872 ));
873 }
874 }
875
876 if let Some(sev) = line_diag_sev {
877 style.push_str(&format!(
878 " border-bottom: 2px dotted {};",
879 theme.diagnostic_css(sev)
880 ));
881 }
882
883 nodes.push(NodeBlueprint::element(
884 Tag::Span,
885 Vec::<String>::new(),
886 vec![Attribute::property("style", style)],
887 vec![NodeBlueprint::text(tok.text.clone())],
888 ));
889 last_byte = end_b.max(last_byte);
890 }
891 if last_byte < line_text.len() && line_text.is_char_boundary(last_byte) {
892 nodes.push(NodeBlueprint::text(&line_text[last_byte..]));
893 }
894 }
895
896 for &caret_col in carets {
898 let clamped_col = caret_col.min(line_chars);
899 nodes.push(NodeBlueprint::element(
900 Tag::Span,
901 vec!["inline-block w-[2px] h-[16px] align-middle pointer-events-none".to_string()],
902 vec![
903 Attribute::property("data-editor-caret-col", clamped_col.to_string()),
904 Attribute::property(
905 "style",
906 format!("background-color: {};", theme.caret),
907 ),
908 ],
909 Vec::new(),
910 ));
911 }
912
913 nodes
914}
915
916fn build_find_replace_bar(
917 handle: &CodeEditorHandle,
918 ed: &CodeEditor,
919 theme: &EditorTheme,
920 on_change: Option<Rc<dyn Fn(String)>>,
921) -> NodeBlueprint {
922 let search = ed.search();
923 let status = search.status_label();
924
925 let h_query = handle.clone();
926 let h_case = handle.clone();
927 let h_word = handle.clone();
928 let h_regex = handle.clone();
929 let h_prev = handle.clone();
930 let h_next = handle.clone();
931 let h_close = handle.clone();
932
933 let toggle_btn = |label: &str, active: bool, attr: &str, on_click: Box<dyn Fn(Event)>| {
934 let style = if active {
935 format!(
936 "background-color: {}; color: {}; border-color: {};",
937 theme.selection_bg, theme.fg, theme.caret
938 )
939 } else {
940 format!(
941 "background-color: transparent; color: {}; border-color: {};",
942 theme.gutter_fg, theme.panel_border
943 )
944 };
945 NodeBlueprint::element(
946 Tag::Button,
947 vec!["px-1.5 py-0.5 text-xs font-mono rounded border cursor-pointer".to_string()],
948 vec![
949 Attribute::property("data-find-action", attr),
950 Attribute::property("style", style),
951 Attribute::event_listener(EventType::Click, move |e: Event| {
952 e.stop_propagation();
953 on_click(e);
954 }),
955 ],
956 vec![NodeBlueprint::text(label)],
957 )
958 };
959
960 let find_row = NodeBlueprint::element(
961 Tag::Div,
962 vec!["flex items-center gap-1.5".to_string()],
963 Vec::new(),
964 vec![
965 NodeBlueprint::element(
966 Tag::Input,
967 vec!["flex-1 min-w-[140px] px-2 py-0.5 text-xs font-mono rounded border".to_string()],
968 vec![
969 Attribute::property("type", "text"),
970 Attribute::property("placeholder", "Find..."),
971 Attribute::property("value", search.query.clone()),
972 Attribute::property("data-find-input", "query"),
973 Attribute::property(
974 "style",
975 format!(
976 "background-color: {}; color: {}; border-color: {};",
977 theme.bg, theme.fg, theme.panel_border
978 ),
979 ),
980 Attribute::value_listener(EventType::Input, move |val: String| {
981 h_query.with_editor_mut(|editor| editor.set_find_query(val));
982 }),
983 ],
984 Vec::new(),
985 ),
986 toggle_btn(
987 "Aa",
988 search.case_sensitive,
989 "case",
990 Box::new(move |_| {
991 h_case.with_editor_mut(|editor| {
992 let mut s = std::mem::take(editor.search_mut());
993 s.toggle_case_sensitive(editor.buffer());
994 *editor.search_mut() = s;
995 });
996 }),
997 ),
998 toggle_btn(
999 "Ab",
1000 search.whole_word,
1001 "whole-word",
1002 Box::new(move |_| {
1003 h_word.with_editor_mut(|editor| {
1004 let mut s = std::mem::take(editor.search_mut());
1005 s.toggle_whole_word(editor.buffer());
1006 *editor.search_mut() = s;
1007 });
1008 }),
1009 ),
1010 toggle_btn(
1011 ".*",
1012 search.use_regex,
1013 "regex",
1014 Box::new(move |_| {
1015 h_regex.with_editor_mut(|editor| {
1016 let mut s = std::mem::take(editor.search_mut());
1017 s.toggle_regex(editor.buffer());
1018 *editor.search_mut() = s;
1019 });
1020 }),
1021 ),
1022 NodeBlueprint::element(
1023 Tag::Span,
1024 vec!["text-xs font-mono px-1 min-w-[64px] text-center select-none".to_string()],
1025 vec![
1026 Attribute::property("data-find-status", "true"),
1027 Attribute::property("style", format!("color: {};", theme.gutter_active_fg)),
1028 ],
1029 vec![NodeBlueprint::text(status)],
1030 ),
1031 toggle_btn(
1032 "↑",
1033 false,
1034 "prev",
1035 Box::new(move |_| {
1036 h_prev.with_editor_mut(|editor| {
1037 let _ = editor.find_prev();
1038 });
1039 }),
1040 ),
1041 toggle_btn(
1042 "↓",
1043 false,
1044 "next",
1045 Box::new(move |_| {
1046 h_next.with_editor_mut(|editor| {
1047 let _ = editor.find_next();
1048 });
1049 }),
1050 ),
1051 toggle_btn(
1052 "×",
1053 false,
1054 "close",
1055 Box::new(move |_| {
1056 h_close.with_editor_mut(CodeEditor::close_find);
1057 }),
1058 ),
1059 ],
1060 );
1061
1062 let mut rows = vec![find_row];
1063
1064 if search.show_replace {
1065 let h_repl_in = handle.clone();
1066 let h_repl_one = handle.clone();
1067 let h_repl_all = handle.clone();
1068 let cb_one = on_change.clone();
1069 let cb_all = on_change;
1070
1071 rows.push(NodeBlueprint::element(
1072 Tag::Div,
1073 vec!["flex items-center gap-1.5 mt-1".to_string()],
1074 Vec::new(),
1075 vec![
1076 NodeBlueprint::element(
1077 Tag::Input,
1078 vec!["flex-1 min-w-[140px] px-2 py-0.5 text-xs font-mono rounded border".to_string()],
1079 vec![
1080 Attribute::property("type", "text"),
1081 Attribute::property("placeholder", "Replace..."),
1082 Attribute::property("value", search.replacement.clone()),
1083 Attribute::property("data-find-input", "replace"),
1084 Attribute::property(
1085 "style",
1086 format!(
1087 "background-color: {}; color: {}; border-color: {};",
1088 theme.bg, theme.fg, theme.panel_border
1089 ),
1090 ),
1091 Attribute::value_listener(EventType::Input, move |val: String| {
1092 h_repl_in.with_editor_mut(|editor| editor.set_replace_text(val));
1093 }),
1094 ],
1095 Vec::new(),
1096 ),
1097 toggle_btn(
1098 "Replace",
1099 false,
1100 "replace",
1101 Box::new(move |_| {
1102 let updated = h_repl_one.with_editor_mut(|editor| {
1103 if editor.replace_current() {
1104 Some(editor.text())
1105 } else {
1106 None
1107 }
1108 });
1109 if let (Some(cb), Some(text)) = (&cb_one, updated) {
1110 cb(text);
1111 }
1112 }),
1113 ),
1114 toggle_btn(
1115 "All",
1116 false,
1117 "replace-all",
1118 Box::new(move |_| {
1119 let updated = h_repl_all.with_editor_mut(|editor| {
1120 if editor.replace_all() > 0 {
1121 Some(editor.text())
1122 } else {
1123 None
1124 }
1125 });
1126 if let (Some(cb), Some(text)) = (&cb_all, updated) {
1127 cb(text);
1128 }
1129 }),
1130 ),
1131 ],
1132 ));
1133 }
1134
1135 NodeBlueprint::element(
1136 Tag::Div,
1137 vec!["px-2.5 py-1.5 border-b flex flex-col shrink-0".to_string()],
1138 vec![
1139 Attribute::property("data-find-replace-bar", "true"),
1140 Attribute::property(
1141 "style",
1142 format!(
1143 "background-color: {}; border-color: {};",
1144 theme.panel_bg, theme.panel_border
1145 ),
1146 ),
1147 ],
1148 rows,
1149 )
1150}
1151
1152fn build_status_bar(ed: &CodeEditor, theme: &EditorTheme) -> NodeBlueprint {
1153 let primary = ed.cursors().primary().focus;
1154 let counts = ed.diagnostic_counts();
1155 let cursor_badge = if ed.cursors().count() > 1 {
1156 format!(
1157 "Ln {}, Col {} ({} cursors)",
1158 primary.line + 1,
1159 primary.col + 1,
1160 ed.cursors().count()
1161 )
1162 } else {
1163 format!("Ln {}, Col {}", primary.line + 1, primary.col + 1)
1164 };
1165
1166 NodeBlueprint::element(
1167 Tag::Div,
1168 vec![
1169 "flex items-center justify-between px-3 py-1 text-[11px] font-mono border-t select-none shrink-0"
1170 .to_string(),
1171 ],
1172 vec![
1173 Attribute::property("data-editor-statusbar", "true"),
1174 Attribute::property(
1175 "style",
1176 format!(
1177 "background-color: {}; color: {}; border-color: {};",
1178 theme.gutter_bg, theme.gutter_fg, theme.border
1179 ),
1180 ),
1181 ],
1182 vec![
1183 NodeBlueprint::element(
1184 Tag::Div,
1185 vec!["flex items-center gap-3".to_string()],
1186 Vec::new(),
1187 vec![
1188 NodeBlueprint::element(
1189 Tag::Span,
1190 Vec::<String>::new(),
1191 vec![Attribute::property(
1192 "style",
1193 format!("color: {};", theme.diag_error),
1194 )],
1195 vec![NodeBlueprint::text(format!("✕ {}", counts.errors))],
1196 ),
1197 NodeBlueprint::element(
1198 Tag::Span,
1199 Vec::<String>::new(),
1200 vec![Attribute::property(
1201 "style",
1202 format!("color: {};", theme.diag_warning),
1203 )],
1204 vec![NodeBlueprint::text(format!("▲ {}", counts.warnings))],
1205 ),
1206 NodeBlueprint::text(cursor_badge),
1207 ],
1208 ),
1209 NodeBlueprint::element(
1210 Tag::Div,
1211 vec!["flex items-center gap-3".to_string()],
1212 Vec::new(),
1213 vec![
1214 NodeBlueprint::text(format!("Spaces: {}", ed.tab_size())),
1215 NodeBlueprint::text("UTF-8"),
1216 NodeBlueprint::element(
1217 Tag::Span,
1218 vec!["font-semibold".to_string()],
1219 vec![Attribute::property(
1220 "style",
1221 format!("color: {};", theme.gutter_active_fg),
1222 )],
1223 vec![NodeBlueprint::text(ed.language().display_name())],
1224 ),
1225 ],
1226 ),
1227 ],
1228 )
1229}