1use crate::{Error, RichDocument, RichSelection};
3use std::rc::Rc;
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum RichCommand {
6 Undo,
7 Redo,
8 Bold,
9 Italic,
10 Code,
11 ContinueLine,
12 Indent,
13 Outdent,
14}
15impl RichCommand {
16 pub fn input_key(input: crate::KeyboardInput<'_>) -> Option<Self> {
19 if input.composing || input.repeat || input.alt {
20 return None;
21 }
22 let chord = input.control || input.meta;
23 if chord {
24 return match input.key.to_ascii_lowercase().as_str() {
25 "z" if input.shift => Some(Self::Redo),
26 "z" => Some(Self::Undo),
27 "y" => Some(Self::Redo),
28 "b" if !input.shift => Some(Self::Bold),
29 "i" if !input.shift => Some(Self::Italic),
30 "`" if !input.shift => Some(Self::Code),
31 "]" if !input.shift => Some(Self::Indent),
32 "[" if !input.shift => Some(Self::Outdent),
33 _ => None,
34 };
35 }
36 match input.key {
37 "Enter" if !input.shift => Some(Self::ContinueLine),
38 _ => None,
39 }
40 }
41 pub fn source_only(self) -> bool {
42 matches!(self, Self::ContinueLine | Self::Indent | Self::Outdent)
43 }
44}
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct RichEditorProps {
47 pub document: Rc<RichDocument>,
48 pub enabled: bool,
49 pub revision: u64,
50}
51impl Default for RichEditorProps {
52 fn default() -> Self {
53 Self {
54 document: Rc::new(RichDocument::default()),
55 enabled: true,
56 revision: 0,
57 }
58 }
59}
60impl RichEditorProps {
61 pub fn validate(&self) -> Result<(), Error> {
62 self.document.validate()
63 }
64 pub(crate) fn validate_update(&self, previous: &Self) -> Result<(), Error> {
65 self.validate()?;
66 if self.revision < previous.revision
67 || self.revision == previous.revision && self.document != previous.document
68 {
69 return Err(Error::InputRevision {
70 current: previous.revision,
71 incoming: self.revision,
72 });
73 }
74 Ok(())
75 }
76}
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub struct RichSnapshot {
79 pub document: Rc<RichDocument>,
80 pub selection: RichSelection,
81 pub revision: u64,
82 pub composing: bool,
83}
84impl RichSnapshot {
85 pub fn validate(&self) -> Result<(), Error> {
86 self.document.validate()?;
87 self.document.validate_selection(self.selection)
88 }
89 pub(crate) fn validate_input(&self, props: &RichEditorProps) -> Result<(), Error> {
90 self.validate()?;
91 if self.revision > props.revision {
92 return Err(Error::InputRevision {
93 current: props.revision,
94 incoming: self.revision,
95 });
96 }
97 Ok(())
98 }
99}