use std::{cell::RefCell, ops::Range, rc::Rc};
use gpui::{Action, App, Context, SharedString, Window, actions};
use serde::Deserialize;
use super::{InputBaseState, kind::InputModeKind};
pub trait SpellChecker {
fn misspelled_words(&self, text: &str, cx: &App) -> Vec<Range<usize>>;
fn guesses(&self, word: &str, cx: &App) -> Vec<SharedString>;
fn learn(&self, word: &str, cx: &mut App);
}
#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
#[action(namespace = input, no_json)]
pub struct CorrectSpelling {
pub replacement: SharedString,
}
actions!(
input,
[
LearnSpelling
]
);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Misspelling {
pub range: Range<usize>,
pub word: SharedString,
pub guesses: Vec<SharedString>,
}
pub(crate) struct Spelling {
checker: Rc<dyn SpellChecker>,
found: RefCell<Option<(u64, Rc<[Range<usize>]>)>>,
}
impl Spelling {
fn new(checker: Rc<dyn SpellChecker>) -> Self {
Self {
checker,
found: RefCell::new(None),
}
}
}
impl<M: InputModeKind> InputBaseState<M> {
pub fn spell_checker(mut self, checker: impl SpellChecker + 'static) -> Self {
self.spelling = Some(Spelling::new(Rc::new(checker)));
self
}
pub fn set_spell_checker(
&mut self,
checker: Option<Rc<dyn SpellChecker>>,
cx: &mut Context<Self>,
) {
self.spelling = checker.map(Spelling::new);
cx.notify();
}
pub(crate) fn misspelled_words(&self, cx: &App) -> Rc<[Range<usize>]> {
let Some(spelling) = self.spelling.as_ref().filter(|_| !self.masked) else {
return Rc::new([]);
};
let mut found = spelling.found.borrow_mut();
if let Some((revision, ranges)) = found.as_ref()
&& *revision == self.document_revision
{
return ranges.clone();
}
let ranges: Rc<[Range<usize>]> = spelling
.checker
.misspelled_words(&self.text.to_string(), cx)
.into();
*found = Some((self.document_revision, ranges.clone()));
ranges
}
pub(crate) fn misspellings_shown(&self, cx: &App) -> Vec<Range<usize>> {
let cursor = self.cursor();
let typing = self.active_selection().is_empty();
self.misspelled_words(cx)
.iter()
.filter(|range| !(typing && range.end == cursor))
.cloned()
.collect()
}
pub(crate) fn misspelling_at(&self, offset: usize, cx: &App) -> Option<Misspelling> {
let spelling = self.spelling.as_ref()?;
let range = self
.misspelled_words(cx)
.iter()
.find(|range| range.start <= offset && offset <= range.end)?
.clone();
let word: SharedString = self.text.slice(range.clone()).to_string().into();
let guesses = spelling.checker.guesses(&word, cx);
Some(Misspelling {
range,
word,
guesses,
})
}
pub fn context_menu_misspelling(&self, cx: &App) -> Option<Misspelling> {
self.misspelling_at(self.context_menu_offset()?, cx)
}
fn misspelling_acted_on(&self, cx: &App) -> Option<Misspelling> {
self.misspelling_at(self.context_menu_offset().unwrap_or(self.cursor()), cx)
}
pub(super) fn correct_spelling(
&mut self,
action: &CorrectSpelling,
window: &mut Window,
cx: &mut Context<Self>,
) {
if !self.is_editable() {
return;
}
let Some(misspelling) = self.misspelling_acted_on(cx) else {
return;
};
self.set_selection(misspelling.range.start, misspelling.range.end);
self.replace(action.replacement.clone(), window, cx);
}
pub(super) fn learn_spelling(
&mut self,
_: &LearnSpelling,
_: &mut Window,
cx: &mut Context<Self>,
) {
let Some(misspelling) = self.misspelling_acted_on(cx) else {
return;
};
let Some(spelling) = self.spelling.as_ref() else {
return;
};
let checker = spelling.checker.clone();
spelling.found.borrow_mut().take();
checker.learn(&misspelling.word, cx);
cx.notify();
}
}
#[cfg(test)]
mod tests {
use std::{cell::RefCell, ops::Range, rc::Rc};
use gpui::{App, SharedString};
use super::{CorrectSpelling, LearnSpelling, SpellChecker};
use crate::input::TextareaState;
struct Words(Rc<RefCell<Vec<String>>>);
impl SpellChecker for Words {
fn misspelled_words(&self, text: &str, _: &App) -> Vec<Range<usize>> {
let known = self.0.borrow();
let mut found = Vec::new();
let mut start = 0;
for word in text.split(' ') {
if !word.is_empty() && !known.iter().any(|k| k == word) {
found.push(start..start + word.len());
}
start += word.len() + 1;
}
found
}
fn guesses(&self, _: &str, _: &App) -> Vec<SharedString> {
vec!["world".into()]
}
fn learn(&self, word: &str, _: &mut App) {
self.0.borrow_mut().push(word.to_owned());
}
}
#[gpui::test]
fn misspelled_words_are_found_corrected_and_learned(cx: &mut gpui::TestAppContext) {
cx.update(crate::init);
let known = Rc::new(RefCell::new(vec!["hello".to_owned(), "world".to_owned()]));
let checker = Words(known.clone());
let (state, cx) = cx.add_window_view(|window, cx| {
TextareaState::new(window, cx)
.spell_checker(checker)
.default_value("hello wurld zorp")
});
let misspelled = |cx: &mut gpui::VisualTestContext| {
state.read_with(cx, |state, cx| state.misspelled_words(cx).to_vec())
};
assert_eq!(misspelled(cx), vec![6..11, 12..16]);
cx.update(|_, cx| state.update(cx, |state, cx| state.set_selected_range(16..16, cx)));
let shown = state.read_with(cx, |state, cx| state.misspellings_shown(cx));
assert_eq!(shown, vec![6..11]);
let found = state.read_with(cx, |state, cx| state.misspelling_at(8, cx));
assert_eq!(
found.map(|m| (m.word, m.guesses)),
Some(("wurld".into(), vec!["world".into()]))
);
cx.update(|window, cx| {
state.update(cx, |state, cx| {
state.set_selected_range(8..8, cx);
let world = CorrectSpelling {
replacement: "world".into(),
};
state.correct_spelling(&world, window, cx);
})
});
assert_eq!(
state.read_with(cx, |state, _| state.value()),
"hello world zorp"
);
assert_eq!(misspelled(cx), vec![12..16]);
cx.update(|window, cx| {
state.update(cx, |state, cx| {
state.set_selected_range(13..13, cx);
state.learn_spelling(&LearnSpelling, window, cx);
})
});
assert!(known.borrow().iter().any(|k| k == "zorp"));
assert!(misspelled(cx).is_empty());
}
}