use crate::{Error, RichDocument, RichSelection};
use std::rc::Rc;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RichCommand {
Undo,
Redo,
Bold,
Italic,
Code,
ContinueLine,
Indent,
Outdent,
}
impl RichCommand {
pub fn input_key(input: crate::KeyboardInput<'_>) -> Option<Self> {
if input.composing || input.repeat || input.alt {
return None;
}
let chord = input.control || input.meta;
if chord {
return match input.key.to_ascii_lowercase().as_str() {
"z" if input.shift => Some(Self::Redo),
"z" => Some(Self::Undo),
"y" => Some(Self::Redo),
"b" if !input.shift => Some(Self::Bold),
"i" if !input.shift => Some(Self::Italic),
"`" if !input.shift => Some(Self::Code),
"]" if !input.shift => Some(Self::Indent),
"[" if !input.shift => Some(Self::Outdent),
_ => None,
};
}
match input.key {
"Enter" if !input.shift => Some(Self::ContinueLine),
_ => None,
}
}
pub fn source_only(self) -> bool {
matches!(self, Self::ContinueLine | Self::Indent | Self::Outdent)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RichEditorProps {
pub document: Rc<RichDocument>,
pub enabled: bool,
pub revision: u64,
}
impl Default for RichEditorProps {
fn default() -> Self {
Self {
document: Rc::new(RichDocument::default()),
enabled: true,
revision: 0,
}
}
}
impl RichEditorProps {
pub fn validate(&self) -> Result<(), Error> {
self.document.validate()
}
pub(crate) fn validate_update(&self, previous: &Self) -> Result<(), Error> {
self.validate()?;
if self.revision < previous.revision
|| self.revision == previous.revision && self.document != previous.document
{
return Err(Error::InputRevision {
current: previous.revision,
incoming: self.revision,
});
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RichSnapshot {
pub document: Rc<RichDocument>,
pub selection: RichSelection,
pub revision: u64,
pub composing: bool,
}
impl RichSnapshot {
pub fn validate(&self) -> Result<(), Error> {
self.document.validate()?;
self.document.validate_selection(self.selection)
}
pub(crate) fn validate_input(&self, props: &RichEditorProps) -> Result<(), Error> {
self.validate()?;
if self.revision > props.revision {
return Err(Error::InputRevision {
current: props.revision,
incoming: self.revision,
});
}
Ok(())
}
}