Skip to main content

waft_widgets/widgets/
spell_check.rs

1//! Flutter counterpart: `widgets/spell_check.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use waft_embedder::{Color, TargetPlatform, TextDecoration, TextRange};
7use waft_foundation::App;
8use waft_painting::{InlineSpanRef, TextSpan, TextStyle};
9use waft_services::{SpellCheckResults, SpellCheckService, SuggestionSpan, TextEditingValue};
10
11use crate::widgets::editable_text::EditableTextContextMenuBuilder;
12
13/// Controls how spell check is performed for text input.
14///
15/// This configuration determines the [`SpellCheckService`] used to fetch the
16/// [`SuggestionSpan`] spell check results and the [`TextStyle`] used to
17/// mark misspelled words within text input.
18#[derive(Clone)]
19pub struct SpellCheckConfiguration {
20    /// The service used to fetch spell check results for text input.
21    pub spell_check_service: Option<Rc<dyn SpellCheckService>>,
22    /// The color the paint the selection highlight when spell check is showing
23    /// suggestions for a misspelled word.
24    ///
25    /// For example, on iOS, the selection appears red while the spell check menu
26    /// is showing.
27    pub misspelled_selection_color: Option<Color>,
28    /// Style used to indicate misspelled words.
29    ///
30    /// This is nullable to allow style-specific wrappers of `EditableText`
31    /// to infer this, but this must be specified if this configuration is
32    /// provided directly to `EditableText` or its construction will fail with an
33    /// assertion error.
34    pub misspelled_text_style: Option<TextStyle>,
35    /// Builds the toolbar used to display spell check suggestions for misspelled
36    /// words.
37    pub spell_check_suggestions_toolbar_builder: Option<EditableTextContextMenuBuilder>,
38    spell_check_enabled: bool,
39}
40
41impl SpellCheckConfiguration {
42    /// Creates a configuration that specifies the service and suggestions handler
43    /// for spell check.
44    pub const fn new() -> SpellCheckConfiguration {
45        SpellCheckConfiguration {
46            spell_check_service: None,
47            misspelled_selection_color: None,
48            misspelled_text_style: None,
49            spell_check_suggestions_toolbar_builder: None,
50            spell_check_enabled: true,
51        }
52    }
53
54    /// Creates a configuration that disables spell check.
55    pub const fn disabled() -> SpellCheckConfiguration {
56        SpellCheckConfiguration {
57            spell_check_enabled: false,
58            spell_check_service: None,
59            spell_check_suggestions_toolbar_builder: None,
60            misspelled_text_style: None,
61            misspelled_selection_color: None,
62        }
63    }
64
65    /// Dart `SpellCheckConfiguration(spellCheckService:)`.
66    pub fn spell_check_service(
67        mut self,
68        spell_check_service: Rc<dyn SpellCheckService>,
69    ) -> SpellCheckConfiguration {
70        self.spell_check_service = Some(spell_check_service);
71        self
72    }
73
74    /// Dart `SpellCheckConfiguration(misspelledSelectionColor:)`.
75    pub fn misspelled_selection_color(
76        mut self,
77        misspelled_selection_color: Color,
78    ) -> SpellCheckConfiguration {
79        self.misspelled_selection_color = Some(misspelled_selection_color);
80        self
81    }
82
83    /// Dart `SpellCheckConfiguration(misspelledTextStyle:)`.
84    pub fn misspelled_text_style(
85        mut self,
86        misspelled_text_style: TextStyle,
87    ) -> SpellCheckConfiguration {
88        self.misspelled_text_style = Some(misspelled_text_style);
89        self
90    }
91
92    /// Dart `SpellCheckConfiguration(spellCheckSuggestionsToolbarBuilder:)`.
93    pub fn spell_check_suggestions_toolbar_builder(
94        mut self,
95        spell_check_suggestions_toolbar_builder: EditableTextContextMenuBuilder,
96    ) -> SpellCheckConfiguration {
97        self.spell_check_suggestions_toolbar_builder =
98            Some(spell_check_suggestions_toolbar_builder);
99        self
100    }
101
102    /// Whether or not the configuration should enable or disable spell check.
103    pub fn spell_check_enabled(&self) -> bool {
104        self.spell_check_enabled
105    }
106
107    /// Returns a copy of the current [`SpellCheckConfiguration`] instance with
108    /// specified overrides.
109    ///
110    /// If this configuration is disabled, returns [`SpellCheckConfiguration::disabled`].
111    /// Chain setters: `config.copy_with().misspelled_text_style(style)`.
112    pub fn copy_with(&self) -> SpellCheckConfiguration {
113        if !self.spell_check_enabled {
114            return SpellCheckConfiguration::disabled();
115        }
116        self.clone()
117    }
118}
119
120impl Default for SpellCheckConfiguration {
121    fn default() -> SpellCheckConfiguration {
122        SpellCheckConfiguration::new()
123    }
124}
125
126impl Debug for SpellCheckConfiguration {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        write!(
129            f,
130            "SpellCheckConfiguration({}, service: {}, text style: {:?}, toolbar builder: {})",
131            if self.spell_check_enabled {
132                "enabled"
133            } else {
134                "disabled"
135            },
136            if self.spell_check_service.is_some() {
137                "Some"
138            } else {
139                "None"
140            },
141            self.misspelled_text_style,
142            if self.spell_check_suggestions_toolbar_builder.is_some() {
143                "Some"
144            } else {
145                "None"
146            },
147        )
148    }
149}
150
151impl PartialEq for SpellCheckConfiguration {
152    fn eq(&self, other: &SpellCheckConfiguration) -> bool {
153        option_rc_ptr_eq(&self.spell_check_service, &other.spell_check_service)
154            && self.misspelled_text_style == other.misspelled_text_style
155            && option_rc_ptr_eq(
156                &self.spell_check_suggestions_toolbar_builder,
157                &other.spell_check_suggestions_toolbar_builder,
158            )
159            && self.spell_check_enabled == other.spell_check_enabled
160    }
161}
162
163fn option_rc_ptr_eq<T: ?Sized>(left: &Option<Rc<T>>, right: &Option<Rc<T>>) -> bool {
164    match (left, right) {
165        (None, None) => true,
166        (Some(left), Some(right)) => Rc::ptr_eq(left, right),
167        _ => false,
168    }
169}
170
171// Methods for displaying spell check results:
172
173/// Adjusts spell check results to correspond to [`new_text`] if the only results
174/// that the handler has access to are the [`results`] corresponding to
175/// [`results_text`].
176///
177/// Used in the case where the request for the spell check results of the
178/// [`new_text`] is lagging in order to avoid display of incorrect results.
179fn correct_spell_check_results(
180    new_text: &str,
181    results_text: &str,
182    results: &[SuggestionSpan],
183) -> Vec<SuggestionSpan> {
184    let mut corrected_spell_check_results = Vec::new();
185    let mut span_pointer = 0;
186    let mut offset = 0;
187
188    // Assumes that the order of spans has not been jumbled for optimization
189    // purposes, and will only search since the previously found span.
190    let mut search_start = 0;
191
192    while span_pointer < results.len() {
193        let current_span = &results[span_pointer];
194        let current_span_text = utf16_substring(
195            results_text,
196            current_span.range.start,
197            current_span.range.end,
198        );
199        let span_length = current_span.range.end - current_span.range.start;
200
201        // Try finding SuggestionSpan from resultsText in new text.
202        let found_index =
203            index_of_word_bounded(utf16_suffix(new_text, search_start), current_span_text);
204
205        // Check whether word was found exactly where expected or elsewhere in the newText.
206        let current_span_found_exactly = current_span.range.start == found_index + search_start;
207        let current_span_found_exactly_with_offset =
208            current_span.range.start + offset == found_index + search_start;
209        let current_span_found_elsewhere = found_index >= 0;
210
211        if current_span_found_exactly || current_span_found_exactly_with_offset {
212            // currentSpan was found at the same index in newText and resultsText
213            // or at the same index with the previously calculated adjustment by
214            // the offset value, so apply it to new text by adding it to the list of
215            // corrected results.
216            let adjusted_span = SuggestionSpan::new(
217                TextRange::new(
218                    current_span.range.start + offset,
219                    current_span.range.end + offset,
220                ),
221                current_span.suggestions.clone(),
222            );
223
224            // Start search for the next misspelled word at the end of currentSpan.
225            search_start = (current_span.range.end + 1 + offset).min(utf16_len(new_text));
226            corrected_spell_check_results.push(adjusted_span);
227        } else if current_span_found_elsewhere {
228            // Word was pushed forward but not modified.
229            let adjusted_span_start = search_start + found_index;
230            let adjusted_span_end = adjusted_span_start + span_length;
231            let adjusted_span = SuggestionSpan::new(
232                TextRange::new(adjusted_span_start, adjusted_span_end),
233                current_span.suggestions.clone(),
234            );
235
236            // Start search for the next misspelled word at the end of the
237            // adjusted currentSpan.
238            search_start = (adjusted_span_end + 1).min(utf16_len(new_text));
239            // Adjust offset to reflect the difference between where currentSpan
240            // was positioned in resultsText versus in newText.
241            offset = adjusted_span_start - current_span.range.start;
242            corrected_spell_check_results.push(adjusted_span);
243        }
244        span_pointer += 1;
245    }
246    corrected_spell_check_results
247}
248
249/// Builds the [`TextSpan`] tree given the current state of the text input and
250/// spell check results.
251///
252/// The [`value`] is the current [`TextEditingValue`] requested to be rendered
253/// by a text input widget. The [`composing_within_current_text_range`] value
254/// represents whether or not there is a valid composing region in the
255/// [`value`]. The [`style`] is the [`TextStyle`] to render the [`value`]'s text with,
256/// and the [`misspelled_text_style`] is the [`TextStyle`] to render misspelled
257/// words within the [`value`]'s text with. The [`spell_check_results`] are the
258/// results of spell checking the [`value`]'s text.
259pub fn build_text_span_with_spell_check_suggestions(
260    app: &App,
261    value: &TextEditingValue,
262    composing_within_current_text_range: bool,
263    style: Option<&TextStyle>,
264    misspelled_text_style: &TextStyle,
265    spell_check_results: &SpellCheckResults,
266) -> TextSpan {
267    let mut spell_check_results_spans = spell_check_results.suggestion_spans.clone();
268    let spell_check_results_text = &spell_check_results.spell_checked_text;
269
270    if spell_check_results_text != &value.text {
271        spell_check_results_spans = correct_spell_check_results(
272            &value.text,
273            spell_check_results_text,
274            &spell_check_results_spans,
275        );
276    }
277
278    // We will draw the TextSpan tree based on the composing region, if it is
279    // available.
280    // TODO(camsim99): The two separate strategies for building TextSpan trees
281    // based on the availability of a composing region should be merged:
282    // https://github.com/flutter/flutter/issues/124142.
283    let should_consider_composing_region =
284        app.platform().target_platform() == TargetPlatform::Android;
285    if should_consider_composing_region {
286        return text_span_children(
287            style,
288            build_subtrees_with_composing_region(
289                &spell_check_results_spans,
290                value,
291                style,
292                misspelled_text_style,
293                composing_within_current_text_range,
294            ),
295        );
296    }
297
298    text_span_children(
299        style,
300        build_subtrees_without_composing_region(
301            &spell_check_results_spans,
302            value,
303            style,
304            misspelled_text_style,
305            value.selection.base_offset,
306        ),
307    )
308}
309
310/// Builds the [`TextSpan`] tree for spell check without considering the composing
311/// region. Instead, uses the cursor to identify the word that's actively being
312/// edited and shouldn't be spell checked. This is useful for platforms and IMEs
313/// that don't use the composing region for the active word.
314fn build_subtrees_without_composing_region(
315    spell_check_suggestions: &[SuggestionSpan],
316    value: &TextEditingValue,
317    style: Option<&TextStyle>,
318    misspelled_style: &TextStyle,
319    cursor_index: i32,
320) -> Vec<TextSpan> {
321    let mut text_span_tree_children = Vec::new();
322
323    let mut text_pointer = 0;
324    let mut current_span_pointer = 0;
325    let text = &value.text;
326    let text_len = utf16_len(text);
327    let misspelled_joint_style = style
328        .map(|style| style.merge(Some(misspelled_style)))
329        .unwrap_or_else(|| misspelled_style.clone());
330
331    // Add text interwoven with any misspelled words to the tree.
332    while text_pointer < text_len && current_span_pointer < spell_check_suggestions.len() {
333        let current_span = &spell_check_suggestions[current_span_pointer];
334
335        if current_span.range.start > text_pointer {
336            let end_index = if current_span.range.start < text_len {
337                current_span.range.start
338            } else {
339                text_len
340            };
341            text_span_tree_children.push(span_text(
342                style,
343                utf16_substring(text, text_pointer, end_index),
344            ));
345            text_pointer = end_index;
346        } else {
347            let end_index = if current_span.range.end < text_len {
348                current_span.range.end
349            } else {
350                text_len
351            };
352            let cursor_in_current_span =
353                current_span.range.start <= cursor_index && current_span.range.end >= cursor_index;
354            text_span_tree_children.push(span_text(
355                if cursor_in_current_span {
356                    style
357                } else {
358                    Some(&misspelled_joint_style)
359                },
360                utf16_substring(text, current_span.range.start, end_index),
361            ));
362
363            text_pointer = end_index;
364            current_span_pointer += 1;
365        }
366    }
367
368    // Add any remaining text to the tree if applicable.
369    if text_pointer < text_len {
370        text_span_tree_children.push(span_text(
371            style,
372            utf16_substring(text, text_pointer, text_len),
373        ));
374    }
375
376    text_span_tree_children
377}
378
379/// Builds [`TextSpan`] subtree for text with misspelled words with logic based on
380/// a valid composing region.
381fn build_subtrees_with_composing_region(
382    spell_check_suggestions: &[SuggestionSpan],
383    value: &TextEditingValue,
384    style: Option<&TextStyle>,
385    misspelled_style: &TextStyle,
386    composing_within_current_text_range: bool,
387) -> Vec<TextSpan> {
388    let mut text_span_tree_children = Vec::new();
389
390    let mut text_pointer = 0;
391    let mut current_span_pointer = 0;
392    let text = &value.text;
393    let text_len = utf16_len(text);
394    let composing_region = value.composing;
395    let underline = TextStyle::new().decoration(TextDecoration::UNDERLINE);
396    let composing_text_style = style
397        .map(|style| style.merge(Some(&underline)))
398        .unwrap_or(underline);
399    let misspelled_joint_style = style
400        .map(|style| style.merge(Some(misspelled_style)))
401        .unwrap_or_else(|| misspelled_style.clone());
402
403    // Add text interwoven with any misspelled words to the tree.
404    while text_pointer < text_len && current_span_pointer < spell_check_suggestions.len() {
405        let current_span = &spell_check_suggestions[current_span_pointer];
406
407        if current_span.range.start > text_pointer {
408            let end_index = if current_span.range.start < text_len {
409                current_span.range.start
410            } else {
411                text_len
412            };
413            let text_pointer_within_composing_region = composing_region.start >= text_pointer
414                && composing_region.end <= end_index
415                && !composing_within_current_text_range;
416
417            if text_pointer_within_composing_region {
418                add_composing_region_text_spans(
419                    &mut text_span_tree_children,
420                    text,
421                    text_pointer,
422                    composing_region,
423                    style,
424                    &composing_text_style,
425                );
426                text_span_tree_children.push(span_text(
427                    style,
428                    utf16_substring(text, composing_region.end, end_index),
429                ));
430            } else {
431                text_span_tree_children.push(span_text(
432                    style,
433                    utf16_substring(text, text_pointer, end_index),
434                ));
435            }
436
437            text_pointer = end_index;
438        } else {
439            let end_index = if current_span.range.end < text_len {
440                current_span.range.end
441            } else {
442                text_len
443            };
444            let current_span_is_composing_region = text_pointer >= composing_region.start
445                && end_index <= composing_region.end
446                && !composing_within_current_text_range;
447            text_span_tree_children.push(span_text(
448                if current_span_is_composing_region {
449                    Some(&composing_text_style)
450                } else {
451                    Some(&misspelled_joint_style)
452                },
453                utf16_substring(text, current_span.range.start, end_index),
454            ));
455
456            text_pointer = end_index;
457            current_span_pointer += 1;
458        }
459    }
460
461    // Add any remaining text to the tree if applicable.
462    if text_pointer < text_len {
463        if text_pointer < composing_region.start && !composing_within_current_text_range {
464            add_composing_region_text_spans(
465                &mut text_span_tree_children,
466                text,
467                text_pointer,
468                composing_region,
469                style,
470                &composing_text_style,
471            );
472
473            if composing_region.end != text_len {
474                text_span_tree_children.push(span_text(
475                    style,
476                    utf16_substring(text, composing_region.end, text_len),
477                ));
478            }
479        } else {
480            text_span_tree_children.push(span_text(
481                style,
482                utf16_substring(text, text_pointer, text_len),
483            ));
484        }
485    }
486
487    text_span_tree_children
488}
489
490/// Helper method to create [`TextSpan`] tree children for specified range of
491/// text up to and including the composing region.
492fn add_composing_region_text_spans(
493    tree_children: &mut Vec<TextSpan>,
494    text: &str,
495    start: i32,
496    composing_region: TextRange,
497    style: Option<&TextStyle>,
498    composing_text_style: &TextStyle,
499) {
500    tree_children.push(span_text(
501        style,
502        utf16_substring(text, start, composing_region.start),
503    ));
504    tree_children.push(span_text(
505        Some(composing_text_style),
506        utf16_substring(text, composing_region.start, composing_region.end),
507    ));
508}
509
510fn span_text(style: Option<&TextStyle>, text: impl Into<String>) -> TextSpan {
511    let span = TextSpan::new().text(text);
512    match style {
513        Some(style) => span.style(style.clone()),
514        None => span,
515    }
516}
517
518fn text_span_children(style: Option<&TextStyle>, children: Vec<TextSpan>) -> TextSpan {
519    let children: Vec<InlineSpanRef> = children.into_iter().map(TextSpan::into_span).collect();
520    let span = TextSpan::new().children(children);
521    match style {
522        Some(style) => span.style(style.clone()),
523        None => span,
524    }
525}
526
527fn utf16_len(text: &str) -> i32 {
528    text.encode_utf16().count() as i32
529}
530
531fn utf16_substring(text: &str, start: i32, end: i32) -> &str {
532    TextRange::new(start, end).text_inside(text)
533}
534
535fn utf16_suffix(text: &str, start: i32) -> &str {
536    TextRange::collapsed(start).text_after(text)
537}
538
539/// First UTF-16 index of `needle` in `haystack` with ASCII word boundaries on
540/// both sides. Dart: `haystack.indexOf(RegExp('\\b${RegExp.escape(needle)}\\b'))`.
541///
542/// `\b` is a transition between `[A-Za-z0-9_]` and a non-word char or a string
543/// edge, matching Dart's default (non-`unicode`) JS-style `\b`.
544fn index_of_word_bounded(haystack: &str, needle: &str) -> i32 {
545    let mut utf16 = 0i32;
546    let mut byte = 0usize;
547    loop {
548        let end_byte = byte + needle.len();
549        let ends_on_boundary = needle.is_empty()
550            || (end_byte <= haystack.len() && haystack.is_char_boundary(end_byte));
551        if haystack.is_char_boundary(byte)
552            && ends_on_boundary
553            && haystack[byte..].starts_with(needle)
554            && is_word_boundary(haystack, byte)
555            && is_word_boundary(haystack, end_byte)
556        {
557            return utf16;
558        }
559        if byte >= haystack.len() {
560            return -1;
561        }
562        let Some(ch) = haystack[byte..].chars().next() else {
563            return -1;
564        };
565        byte += ch.len_utf8();
566        utf16 += ch.len_utf16() as i32;
567    }
568}
569
570fn is_word_boundary(text: &str, byte_pos: usize) -> bool {
571    let left_word = byte_pos > 0
572        && text[..byte_pos]
573            .chars()
574            .next_back()
575            .is_some_and(is_ascii_word_char);
576    let right_word = byte_pos < text.len()
577        && text[byte_pos..]
578            .chars()
579            .next()
580            .is_some_and(is_ascii_word_char);
581    left_word != right_word
582}
583
584fn is_ascii_word_char(c: char) -> bool {
585    matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | '_')
586}
587
588#[cfg(test)]
589mod tests {
590    use waft_foundation::AppCell;
591    use waft_painting::InlineSpan;
592
593    use super::*;
594
595    fn misspelled_style() -> TextStyle {
596        TextStyle::new().decoration(TextDecoration::UNDERLINE)
597    }
598
599    #[test]
600    fn empty_spans_yield_a_single_child_with_the_value_text() {
601        let cell = AppCell::new();
602        let app = cell.borrow_mut();
603        let text = "Hello, wrold! Hey";
604        let value = TextEditingValue::new().text(text);
605        let spell_check_results = SpellCheckResults::new(text, Vec::new());
606        let misspelled = misspelled_style();
607
608        let actual = build_text_span_with_spell_check_suggestions(
609            &app,
610            &value,
611            true,
612            None,
613            &misspelled,
614            &spell_check_results,
615        );
616        let expected = TextSpan::new().children(vec![TextSpan::new().text(text).into_span()]);
617        assert!(actual.eq_span(&expected));
618    }
619
620    #[test]
621    fn a_span_in_the_middle_gets_the_misspelled_style() {
622        let cell = AppCell::new();
623        let app = cell.borrow_mut();
624        let text = "Hello, wrold! Hey";
625        let value = TextEditingValue::new().text(text);
626        let misspelled = misspelled_style();
627        let spell_check_results = SpellCheckResults::new(
628            text,
629            vec![SuggestionSpan::new(
630                TextRange::new(7, 12),
631                vec!["world".into(), "word".into(), "old".into()],
632            )],
633        );
634
635        let actual = build_text_span_with_spell_check_suggestions(
636            &app,
637            &value,
638            true,
639            None,
640            &misspelled,
641            &spell_check_results,
642        );
643        let expected = TextSpan::new().children(vec![
644            TextSpan::new().text("Hello, ").into_span(),
645            TextSpan::new()
646                .style(misspelled.clone())
647                .text("wrold")
648                .into_span(),
649            TextSpan::new().text("! Hey").into_span(),
650        ]);
651        assert!(actual.eq_span(&expected));
652    }
653}