Skip to main content

iced_cube/forms/rich_text_editor/
mod.rs

1//! A rich text editor: bold, italic, underline, strikethrough, links,
2//! text sizes, bulleted and numbered lists, drawn as they will look.
3//!
4//! The app owns a [`Content`] and applies every [`Action`] the editor sends
5//! in `update`, as with iced's own text editor. The content keeps the
6//! [`Document`], the selection and the undo history, so formatting from a
7//! toolbar, a shortcut or the app is undone like typing. Read it back as
8//! HTML with [`Content::html`] and as the plain-text alternative with
9//! [`Content::plain_text`], and load a draft with [`Content::with_html`].
10//!
11//! The editor handles the usual keys: arrows, Home, End, Page Up and Page
12//! Down (with Shift to select and Ctrl, or Alt on macOS, to move by word),
13//! select all, copy, cut and paste. Undo, redo, word deletion, Escape and
14//! the formatting chords are [`Shortcut`]s from the same set inputs and
15//! textareas take, bound by [`default_keymap`]; pass a [`Shortcuts`] set to
16//! [`RichTextEditor::shortcuts`] to switch some or all of them off, and
17//! their keys reach the app instead.
18//!
19//! Copying puts plain text on the clipboard. Pasting that same text back
20//! into the editor keeps its formatting.
21//!
22//! Bold uses [`theme::semibold`](crate::theme::semibold) and italic the
23//! italic face of [`theme::font`](crate::theme::font), so the app must
24//! load an italic face of its font for italic text to slant.
25//!
26//! ```no_run
27//! use iced::Element;
28//! use iced_cube::forms::rich_text_editor::{self, Action, Content, rich_text_editor};
29//!
30//! #[derive(Debug, Clone)]
31//! enum Message {
32//!     Edit(Action),
33//! }
34//!
35//! struct Compose {
36//!     body: Content,
37//! }
38//!
39//! impl Compose {
40//!     fn update(&mut self, message: Message) {
41//!         let Message::Edit(action) = message;
42//!         self.body.perform(action);
43//!     }
44//!
45//!     fn view(&self) -> Element<'_, Message> {
46//!         rich_text_editor(&self.body)
47//!             .placeholder("Write your message")
48//!             .on_action(Message::Edit)
49//!             .into()
50//!     }
51//!
52//!     fn send(&self) -> (String, String) {
53//!         (self.body.html(), self.body.plain_text())
54//!     }
55//! }
56//! ```
57
58mod content;
59pub mod document;
60pub mod html;
61mod layout;
62pub mod plain;
63mod snapshot;
64mod widget;
65
66use std::fmt;
67
68use iced::widget::Id;
69use iced::widget::text_input;
70use iced::{Element, Length, Padding};
71
72pub use crate::editing::{Shortcut, Shortcuts};
73pub use content::{Action, Content, Edit, Format, Formatting, Motion};
74pub use document::{
75    Block, BlockKind, Document, Mark, Position, Run, Selection, Size, Style, normalise_link,
76};
77
78use crate::keys::Keymap;
79use crate::primitives::input;
80use crate::theme::{Tokens, space, text_size};
81
82/// Minimum height while the height is [`Length::Shrink`], roughly four lines.
83pub const MIN_HEIGHT: f32 = 96.0;
84
85/// The default shortcuts: undo, redo, word deletion and Escape as in
86/// [`input::default_keymap`], plus the formatting chords. Mod is Cmd on
87/// macOS and Ctrl elsewhere.
88///
89/// | Keys | Shortcut |
90/// | --- | --- |
91/// | `Mod+Z` | [`Shortcut::Undo`] |
92/// | `Mod+Shift+Z`, `Mod+Y` | [`Shortcut::Redo`] |
93/// | `Ctrl+Backspace` | [`Shortcut::DeleteWordBackward`] |
94/// | `Ctrl+Delete` | [`Shortcut::DeleteWordForward`] |
95/// | `Escape` | [`Shortcut::EscapeUnfocus`] |
96/// | `Mod+B` | [`Shortcut::Bold`] |
97/// | `Mod+I` | [`Shortcut::Italic`] |
98/// | `Mod+U` | [`Shortcut::Underline`] |
99/// | `Mod+Shift+X` | [`Shortcut::Strikethrough`] |
100/// | `Mod+Shift+8` | [`Shortcut::BulletedList`] |
101/// | `Mod+Shift+7` | [`Shortcut::NumberedList`] |
102/// | `Mod+K` | [`Shortcut::Link`] |
103/// | `Mod+\` | [`Shortcut::ClearFormatting`] |
104pub fn default_keymap() -> Keymap<Shortcut> {
105    crate::editing::formatting_keymap()
106}
107
108/// The [`Action`] a shortcut sends, or `None` for Escape, which the editor
109/// handles itself.
110pub fn shortcut_action(shortcut: Shortcut) -> Option<Action> {
111    Some(match shortcut {
112        Shortcut::Undo => Action::Undo,
113        Shortcut::Redo => Action::Redo,
114        Shortcut::DeleteWordBackward => Action::Edit(Edit::DeleteWordBackward),
115        Shortcut::DeleteWordForward => Action::Edit(Edit::DeleteWordForward),
116        Shortcut::EscapeUnfocus => return None,
117        Shortcut::Bold => Action::Format(Format::Toggle(Mark::Bold)),
118        Shortcut::Italic => Action::Format(Format::Toggle(Mark::Italic)),
119        Shortcut::Underline => Action::Format(Format::Toggle(Mark::Underline)),
120        Shortcut::Strikethrough => Action::Format(Format::Toggle(Mark::Strikethrough)),
121        Shortcut::BulletedList => Action::Format(Format::Block(BlockKind::Bullet)),
122        Shortcut::NumberedList => Action::Format(Format::Block(BlockKind::Numbered)),
123        Shortcut::Link => Action::RequestLink,
124        Shortcut::ClearFormatting => Action::Format(Format::Clear),
125    })
126}
127
128/// A rich text editor builder. Convert it into an [`Element`] to render.
129///
130/// An editor without an `on_action` message is rendered disabled.
131pub struct RichTextEditor<'a, Message> {
132    content: &'a Content,
133    placeholder: Option<String>,
134    id: Option<Id>,
135    on_action: Option<Box<dyn Fn(Action) -> Message + 'a>>,
136    on_link: Option<Box<dyn Fn(String) -> Message + 'a>>,
137    invalid: bool,
138    width: Length,
139    height: Length,
140    min_height: f32,
141    max_height: f32,
142    text_size: f32,
143    padding: Padding,
144    shortcuts: Shortcuts,
145    keymap: Keymap<Shortcut>,
146}
147
148/// Creates a rich text editor for `content`.
149pub fn rich_text_editor<'a, Message>(content: &'a Content) -> RichTextEditor<'a, Message> {
150    RichTextEditor {
151        content,
152        placeholder: None,
153        id: None,
154        on_action: None,
155        on_link: None,
156        invalid: false,
157        width: Length::Fill,
158        height: Length::Shrink,
159        min_height: MIN_HEIGHT,
160        max_height: f32::INFINITY,
161        text_size: text_size::SM,
162        padding: Padding::from([space::SM, space::MD]),
163        shortcuts: Shortcuts::all(),
164        keymap: default_keymap(),
165    }
166}
167
168impl<'a, Message> RichTextEditor<'a, Message> {
169    /// Text shown while the document is empty.
170    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
171        self.placeholder = Some(placeholder.into());
172        self
173    }
174
175    /// Sets the widget id, used to focus the editor or find it in tests.
176    pub fn id(mut self, id: impl Into<Id>) -> Self {
177        self.id = Some(id.into());
178        self
179    }
180
181    /// Sets the message for every action. Without it the editor is disabled.
182    pub fn on_action(mut self, on_action: impl Fn(Action) -> Message + 'a) -> Self {
183        self.on_action = Some(Box::new(on_action));
184        self
185    }
186
187    pub fn on_action_maybe(mut self, on_action: Option<impl Fn(Action) -> Message + 'a>) -> Self {
188        self.on_action = on_action.map(|f| Box::new(f) as Box<dyn Fn(Action) -> Message + 'a>);
189        self
190    }
191
192    /// Sets the message for a link clicked with Ctrl, or Cmd on macOS, held.
193    /// It carries the address; opening it is up to the app.
194    pub fn on_link(mut self, on_link: impl Fn(String) -> Message + 'a) -> Self {
195        self.on_link = Some(Box::new(on_link));
196        self
197    }
198
199    /// Marks the value as invalid, drawing a destructive border.
200    pub fn invalid(mut self, invalid: bool) -> Self {
201        self.invalid = invalid;
202        self
203    }
204
205    /// Overrides the width. Editors fill the available width by default.
206    pub fn width(mut self, width: impl Into<Length>) -> Self {
207        self.width = width.into();
208        self
209    }
210
211    /// Sets the height. The default shrinks to the content and grows as
212    /// lines are added, from [`MIN_HEIGHT`] up to the maximum height. A
213    /// fixed or filling height scrolls once the text overflows.
214    pub fn height(mut self, height: impl Into<Length>) -> Self {
215        self.height = height.into();
216        self
217    }
218
219    /// Sets the starting height used while the height is [`Length::Shrink`].
220    pub fn min_height(mut self, min_height: f32) -> Self {
221        self.min_height = min_height.max(0.0);
222        self
223    }
224
225    /// Caps the height while it is [`Length::Shrink`]; longer text scrolls.
226    pub fn max_height(mut self, max_height: f32) -> Self {
227        self.max_height = max_height.max(0.0);
228        self
229    }
230
231    /// The size of normal text. Small, large and huge text scale from it.
232    pub fn text_size(mut self, size: f32) -> Self {
233        self.text_size = size.max(1.0);
234        self
235    }
236
237    pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
238        self.padding = padding.into();
239        self
240    }
241
242    /// Sets which [`Shortcut`]s the editor handles. All of them by
243    /// default; pass [`Shortcuts::none`] to turn them all off. The keys of
244    /// a shortcut that is off reach the app, and the editor's own keys,
245    /// such as arrows and copy, always work.
246    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
247        self.shortcuts = shortcuts;
248        self
249    }
250
251    /// Replaces the [`default_keymap`], to bind the shortcuts to other keys.
252    pub fn keymap(mut self, keymap: Keymap<Shortcut>) -> Self {
253        self.keymap = keymap;
254        self
255    }
256
257    pub fn is_enabled(&self) -> bool {
258        self.on_action.is_some()
259    }
260}
261
262impl<Message> fmt::Debug for RichTextEditor<'_, Message> {
263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264        f.debug_struct("RichTextEditor")
265            .field("placeholder", &self.placeholder)
266            .field("id", &self.id)
267            .field("enabled", &self.is_enabled())
268            .field("invalid", &self.invalid)
269            .field("width", &self.width)
270            .field("height", &self.height)
271            .field("min_height", &self.min_height)
272            .field("max_height", &self.max_height)
273            .field("text_size", &self.text_size)
274            .field("shortcuts", &self.shortcuts)
275            .finish_non_exhaustive()
276    }
277}
278
279impl<'a, Message: Clone + 'a> From<RichTextEditor<'a, Message>> for Element<'a, Message> {
280    fn from(editor: RichTextEditor<'a, Message>) -> Self {
281        Element::new(widget::Editor::new(editor))
282    }
283}
284
285/// How the editor looks in a status.
286#[derive(Debug, Clone, Copy, PartialEq)]
287pub struct Appearance {
288    pub field: text_input::Style,
289    /// Underlines under links.
290    pub link: iced::Color,
291    /// Quote bars and the text of quoted lines.
292    pub quote: iced::Color,
293    pub quote_text: iced::Color,
294    pub caret: iced::Color,
295    pub scrollbar: iced::Color,
296}
297
298/// The editor's look, matching the input's for the field itself.
299pub fn style(tokens: &Tokens, status: text_input::Status, invalid: bool) -> Appearance {
300    let field = input::style(tokens, status, invalid);
301    let disabled = status == text_input::Status::Disabled;
302    let fade = |colour| {
303        if disabled {
304            crate::theme::fade(colour, 0.5)
305        } else {
306            colour
307        }
308    };
309    Appearance {
310        field,
311        link: fade(tokens.primary),
312        quote: tokens.border,
313        quote_text: fade(tokens.muted_foreground),
314        caret: tokens.foreground,
315        scrollbar: crate::theme::fade(tokens.foreground, 0.25),
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use crate::keys;
323    use crate::theme::{dark, light};
324
325    const STATES: [text_input::Status; 4] = [
326        text_input::Status::Active,
327        text_input::Status::Hovered,
328        text_input::Status::Focused { is_hovered: false },
329        text_input::Status::Disabled,
330    ];
331
332    #[test]
333    fn default_builder_fills_shrinks_and_is_disabled() {
334        let content = Content::new();
335        let editor: RichTextEditor<'_, ()> = rich_text_editor(&content);
336        assert_eq!(editor.width, Length::Fill);
337        assert_eq!(editor.height, Length::Shrink);
338        assert_eq!(editor.min_height, MIN_HEIGHT);
339        assert_eq!(editor.text_size, text_size::SM);
340        assert_eq!(editor.shortcuts, Shortcuts::all());
341        assert_eq!(editor.keymap, default_keymap());
342        assert!(!editor.is_enabled());
343        let enabled = rich_text_editor::<Action>(&content).on_action(|action| action);
344        assert!(enabled.is_enabled());
345        let none: Option<fn(Action) -> Action> = None;
346        assert!(!enabled.on_action_maybe(none).is_enabled());
347    }
348
349    #[test]
350    fn builder_options_clamp() {
351        let content = Content::new();
352        let editor: RichTextEditor<'_, ()> = rich_text_editor(&content)
353            .min_height(-1.0)
354            .max_height(-1.0)
355            .text_size(0.0)
356            .shortcuts(Shortcuts::none());
357        assert_eq!(editor.min_height, 0.0);
358        assert_eq!(editor.max_height, 0.0);
359        assert_eq!(editor.text_size, 1.0);
360        assert_eq!(editor.shortcuts, Shortcuts::none());
361    }
362
363    #[test]
364    fn every_shortcut_maps_to_an_action_except_escape() {
365        for shortcut in <Shortcut as keys::Action>::ALL {
366            assert_eq!(
367                shortcut_action(*shortcut).is_none(),
368                *shortcut == Shortcut::EscapeUnfocus,
369                "{shortcut:?}"
370            );
371        }
372        assert_eq!(
373            shortcut_action(Shortcut::Bold),
374            Some(Action::Format(Format::Toggle(Mark::Bold)))
375        );
376        assert_eq!(shortcut_action(Shortcut::Link), Some(Action::RequestLink));
377    }
378
379    #[test]
380    fn the_keymap_can_be_overridden_and_unbound() {
381        use crate::keys::Chord;
382        let keymap = default_keymap()
383            .unbind_action(&Shortcut::Link)
384            .bind(Chord::character('l').command(), Shortcut::Link);
385        let chord = Chord::character('k').command();
386        assert_eq!(keymap.resolve(chord.key(), chord.modifiers()), None);
387        let chord = Chord::character('l').command();
388        assert_eq!(
389            keymap.resolve(chord.key(), chord.modifiers()),
390            Some(Shortcut::Link)
391        );
392    }
393
394    #[test]
395    fn style_matches_the_input_and_fades_when_disabled() {
396        for theme in [light(), dark()] {
397            let tokens = Tokens::of(&theme);
398            for status in STATES {
399                for invalid in [false, true] {
400                    let style = style(&tokens, status, invalid);
401                    assert_eq!(style.field, input::style(&tokens, status, invalid));
402                }
403            }
404            let active = style(&tokens, text_input::Status::Active, false);
405            let disabled = style(&tokens, text_input::Status::Disabled, false);
406            assert_ne!(active.link, disabled.link);
407            assert_eq!(active.link, tokens.primary);
408        }
409    }
410}