1use std::borrow::Cow;
2
3use freya_components::{
4 get_theme_or_default,
5 scrollviews::{
6 ScrollConfig,
7 ScrollController,
8 VirtualScrollView,
9 use_scroll_controller,
10 },
11};
12use freya_core::prelude::*;
13use freya_edit::{
14 EditableConfig,
15 EditableEvent,
16};
17use torin::size::Size;
18
19use crate::{
20 editor_data::CodeEditorData,
21 editor_line::{
22 EditorGutterLineUI,
23 EditorLineUI,
24 },
25 editor_theme::{
26 EditorTheme,
27 EditorThemePartial,
28 EditorThemePreference,
29 },
30};
31
32#[derive(PartialEq, Clone)]
33pub struct CodeEditor {
34 editor: Writable<CodeEditorData>,
35 font_size: f32,
36 line_height: f32,
37 read_only: bool,
38 gutter: bool,
39 show_whitespace: bool,
40 font_family: Cow<'static, str>,
41 a11y_id: AccessibilityId,
42 a11y_auto_focus: bool,
43 cursor_mode: CursorMode,
44 scroll_controller: Option<ScrollController>,
45 pub(crate) theme: Option<EditorThemePartial>,
46 on_pre_key_down: Callback<Event<KeyboardEventData>, bool>,
47}
48
49impl CodeEditor {
50 pub fn new(editor: impl Into<Writable<CodeEditorData>>, a11y_id: AccessibilityId) -> Self {
54 Self {
55 editor: editor.into(),
56 font_size: 14.0,
57 line_height: 1.4,
58 read_only: false,
59 gutter: true,
60 show_whitespace: true,
61 font_family: Cow::Borrowed("Jetbrains Mono"),
62 a11y_id,
63 a11y_auto_focus: false,
64 cursor_mode: CursorMode::Expanded,
65 scroll_controller: None,
66 theme: None,
67 on_pre_key_down: Callback::new(|e: Event<KeyboardEventData>| {
68 e.stop_propagation();
69 if let Key::Named(NamedKey::Tab) = &e.key {
70 e.prevent_default();
71 }
72 true
73 }),
74 }
75 }
76
77 pub fn font_size(mut self, size: f32) -> Self {
78 self.font_size = size;
79 self
80 }
81
82 pub fn line_height(mut self, height: f32) -> Self {
84 self.line_height = height;
85 self
86 }
87
88 pub fn read_only(mut self, read_only: bool) -> Self {
90 self.read_only = read_only;
91 self
92 }
93
94 pub fn gutter(mut self, gutter: bool) -> Self {
96 self.gutter = gutter;
97 self
98 }
99
100 pub fn show_whitespace(mut self, show_whitespace: bool) -> Self {
102 self.show_whitespace = show_whitespace;
103 self
104 }
105
106 pub fn font_family(mut self, font_family: impl Into<Cow<'static, str>>) -> Self {
108 self.font_family = font_family.into();
109 self
110 }
111
112 pub fn cursor_mode(mut self, cursor_mode: impl Into<CursorMode>) -> Self {
114 self.cursor_mode = cursor_mode.into();
115 self
116 }
117
118 pub fn scroll_controller(
120 mut self,
121 scroll_controller: impl Into<Option<ScrollController>>,
122 ) -> Self {
123 self.scroll_controller = scroll_controller.into();
124 self
125 }
126
127 pub fn a11y_auto_focus(mut self, a11y_auto_focus: bool) -> Self {
129 self.a11y_auto_focus = a11y_auto_focus;
130 self
131 }
132
133 pub fn on_pre_key_down(
136 mut self,
137 on_pre_key_down: impl Into<Callback<Event<KeyboardEventData>, bool>>,
138 ) -> Self {
139 self.on_pre_key_down = on_pre_key_down.into();
140 self
141 }
142}
143
144impl Component for CodeEditor {
145 fn render(&self) -> impl IntoElement {
146 let CodeEditor {
147 editor,
148 font_size,
149 line_height,
150 read_only,
151 gutter,
152 show_whitespace,
153 font_family,
154 a11y_id,
155 a11y_auto_focus,
156 cursor_mode,
157 scroll_controller,
158 theme,
159 on_pre_key_down,
160 } = self.clone();
161
162 let theme = get_theme_or_default!(&theme, EditorThemePreference, "code_editor", || {
163 EditorTheme::light().into()
164 });
165
166 let focus = use_focus(a11y_id);
167 let editor_data = editor.read_unchecked();
168
169 let mut scroll_controller =
170 scroll_controller.unwrap_or_else(|| use_scroll_controller(ScrollConfig::default));
171 let line_height = (font_size * line_height).floor();
172 let lines_len = editor_data.metrics.syntax_blocks.len();
173
174 let on_key_up = {
175 let mut editor = editor.clone();
176 let font_family = font_family.clone();
177 move |e: Event<KeyboardEventData>| {
178 editor.write_if(|mut editor| {
179 editor.process(
180 font_size,
181 &font_family,
182 EditableEvent::KeyUp { key: &e.key },
183 )
184 });
185 }
186 };
187
188 let on_key_down = {
189 let editor = editor.clone();
190 let font_family = font_family.clone();
191 move |e: Event<KeyboardEventData>| {
192 const LINES_JUMP_ALT: usize = 5;
193 const LINES_JUMP_CONTROL: usize = 3;
194
195 let key = e.key.clone();
196 let modifiers = e.modifiers;
197
198 if !on_pre_key_down.call(e) {
199 return;
200 }
201
202 let mut editor = editor.clone();
203 let font_family = font_family.clone();
204 EditableEvent::KeyDown {
205 key: &key,
206 modifiers,
207 editor_line: None,
208 holder: None,
209 }
210 .resolve_and_then::<CodeEditorData>(
211 editor.clone().into(),
212 &EditableConfig::default().with_allow_changes(!read_only),
213 move |event| {
214 editor.write_if(|mut editor| {
215 let lines_jump = (line_height as f64 * LINES_JUMP_ALT as f64).ceil();
216 let content_height = lines_len as f64 * line_height as f64;
217 let viewport_height = editor.viewport.height as f64;
218 let max_scroll = (content_height - viewport_height).max(0.);
219 let (_, current_scroll) = scroll_controller.into();
220
221 let repetitions = match &event {
222 EditableEvent::KeyDown {
223 key: Key::Named(NamedKey::ArrowUp),
224 ..
225 } if modifiers.contains(Modifiers::ALT) => {
226 let jump = (current_scroll - lines_jump).clamp(0., max_scroll);
227 scroll_controller.scroll_to_y(jump);
228 LINES_JUMP_ALT
229 }
230 EditableEvent::KeyDown {
231 key: Key::Named(NamedKey::ArrowDown),
232 ..
233 } if modifiers.contains(Modifiers::ALT) => {
234 let jump = (current_scroll + lines_jump).clamp(0., max_scroll);
235 scroll_controller.scroll_to_y(jump);
236 LINES_JUMP_ALT
237 }
238 EditableEvent::KeyDown {
239 key: Key::Named(NamedKey::ArrowDown | NamedKey::ArrowUp),
240 ..
241 } if modifiers.contains(Modifiers::CONTROL) => LINES_JUMP_CONTROL,
242 _ => 1,
243 };
244
245 let mut changed = false;
246 for _ in 0..repetitions {
247 changed |= editor.process(font_size, &font_family, event.clone());
248 }
249
250 if changed {
251 editor.scroll_to_cursor(scroll_controller, line_height);
252 }
253
254 changed
255 });
256 },
257 );
258 }
259 };
260
261 let on_global_pointer_up = {
262 let mut editor = editor.clone();
263 let font_family = font_family.clone();
264 move |_: Event<PointerEventData>| {
265 editor.write_if(|mut editor| {
266 editor.process(font_size, &font_family, EditableEvent::Release)
267 });
268 }
269 };
270
271 let gutter_editor = editor.clone();
272 let gutter_theme = theme.clone();
273
274 let on_sized = {
275 let mut editor = editor.clone();
276 move |e: Event<SizedEventData>| {
277 editor.write_if(|mut editor| {
278 let changed = editor.viewport != e.area.size;
279 editor.viewport = e.area.size;
280 changed
281 });
282 }
283 };
284
285 rect()
286 .a11y_auto_focus(a11y_auto_focus)
287 .a11y_focusable(true)
288 .a11y_id(a11y_id)
289 .a11y_role(AccessibilityRole::TextInput)
290 .expanded()
291 .background(theme.background)
292 .maybe(!read_only, |el| {
293 el.on_key_down(on_key_down).on_key_up(on_key_up)
294 })
295 .on_global_pointer_up(on_global_pointer_up)
296 .child(
297 rect()
298 .horizontal()
299 .maybe_child(gutter.then(|| {
300 let gutter_width = font_size * 5.0;
301 VirtualScrollView::new(move |item, _| {
302 EditorGutterLineUI {
303 editor: gutter_editor.clone(),
304 font_size,
305 line_height,
306 line_index: item.index,
307 theme: gutter_theme.clone(),
308 }
309 .into()
310 })
311 .width(Size::px(gutter_width))
312 .show_scrollbar(false)
313 .follow_scroll_controller(scroll_controller)
314 .length(lines_len)
315 .item_size(line_height)
316 }))
317 .child(
318 VirtualScrollView::new(move |item, _| {
319 EditorLineUI {
320 editor: editor.clone(),
321 font_size,
322 line_height,
323 line_index: item.index,
324 read_only,
325 show_whitespace,
326 font_family: font_family.clone(),
327 cursor_mode,
328 theme: theme.clone(),
329 a11y_id,
330 focus,
331 scroll_controller,
332 }
333 .into()
334 })
335 .expanded()
336 .scroll_controller(scroll_controller)
337 .on_sized(on_sized)
338 .length(lines_len)
339 .item_size(line_height),
340 ),
341 )
342 }
343}