freya_edit/
use_editable.rs

1use std::time::Duration;
2
3use freya_core::prelude::*;
4
5use crate::{
6    EditableConfig,
7    EditableEvent,
8    TextDragging,
9    editor_history::EditorHistory,
10    rope_editor::RopeEditor,
11    text_editor::TextSelection,
12};
13
14/// Manage an editable text.
15#[derive(Clone, Copy, PartialEq)]
16pub struct UseEditable {
17    pub(crate) editor: State<RopeEditor>,
18    pub(crate) dragging: State<TextDragging>,
19    pub(crate) config: EditableConfig,
20}
21
22impl UseEditable {
23    /// Manually create an editable content instead of using [use_editable].
24    pub fn create(content: String, config: EditableConfig) -> Self {
25        let editor = State::create(RopeEditor::new(
26            content,
27            TextSelection::new_cursor(0),
28            config.identation,
29            EditorHistory::new(Duration::from_millis(10)),
30        ));
31        let dragging = State::create(TextDragging::default());
32
33        UseEditable {
34            editor,
35            dragging,
36            config,
37        }
38    }
39
40    /// Reference to the editor.
41    pub fn editor(&self) -> &State<RopeEditor> {
42        &self.editor
43    }
44
45    /// Mutable reference to the editor.
46    pub fn editor_mut(&mut self) -> &mut State<RopeEditor> {
47        &mut self.editor
48    }
49
50    /// Process a [`EditableEvent`] event.
51    pub fn process_event(&mut self, edit_event: EditableEvent) {
52        edit_event.process(self.editor, self.dragging, &self.config);
53    }
54}
55
56/// Hook to create an editable text.
57///
58/// For manual creation use [UseEditable::create].
59///
60/// **This is a low level hook and is not expected to be used by the common user, in fact,
61/// you might be looking for something like the `Input` component instead.**
62pub fn use_editable(
63    content: impl FnOnce() -> String,
64    config: impl FnOnce() -> EditableConfig,
65) -> UseEditable {
66    use_hook(|| UseEditable::create(content(), config()))
67}