freya_edit/
use_editable.rs

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