Skip to main content

iced_cube/application/
formatting_toolbar.rs

1//! A toolbar for the [rich text editor](mod@crate::forms::rich_text_editor):
2//! text size, bold, italic, underline, strikethrough, lists, link and clear
3//! formatting, each showing whether it is on at the caret.
4//!
5//! It is its own component so the app can put it anywhere: above the
6//! editor, in a window's toolbar row or below a compose form. The buttons
7//! are a [toolbar](mod@crate::application::toolbar), so whatever does not
8//! fit moves into its More menu on a narrow window, and the text size is a
9//! [dropdown menu](mod@crate::overlay::dropdown_menu).
10//!
11//! The app owns a [`State`]. After every change to the editor's
12//! [`Content`], call [`State::sync`] so the buttons follow the caret. A
13//! press returns an [`Output`]: apply [`Output::Format`] to the content and
14//! give the editor focus back, and focus [`LINK_FIELD`] on
15//! [`Output::EditLink`], when the address field opens.
16//!
17//! ```no_run
18//! use iced::widget::{column, operation};
19//! use iced::{Element, Task};
20//! use iced_cube::formatting_toolbar::{self, Output, formatting_toolbar};
21//! use iced_cube::rich_text_editor::{self, Action, Content, rich_text_editor};
22//!
23//! const BODY: &str = "body";
24//!
25//! #[derive(Debug, Clone)]
26//! enum Message {
27//!     Edit(Action),
28//!     Format(formatting_toolbar::Event),
29//! }
30//!
31//! #[derive(Default)]
32//! struct Compose {
33//!     body: Content,
34//!     formatting: formatting_toolbar::State,
35//! }
36//!
37//! impl Compose {
38//!     fn update(&mut self, message: Message) -> Task<Message> {
39//!         let output = match message {
40//!             Message::Edit(action) => {
41//!                 self.body.perform(action);
42//!                 self.formatting.sync(&self.body)
43//!             }
44//!             Message::Format(event) => self.formatting.update(event, &self.body),
45//!         };
46//!         match output {
47//!             Some(Output::Format(action)) => {
48//!                 self.body.perform(action);
49//!                 self.formatting.sync(&self.body);
50//!                 operation::focus(BODY)
51//!             }
52//!             Some(Output::EditLink) => operation::focus(formatting_toolbar::LINK_FIELD),
53//!             Some(Output::Closed) => operation::focus(BODY),
54//!             Some(Output::Unfocus) => formatting_toolbar::unfocus(),
55//!             None => Task::none(),
56//!         }
57//!     }
58//!
59//!     fn view(&self) -> Element<'_, Message> {
60//!         column![
61//!             formatting_toolbar(&self.formatting).on_event(Message::Format),
62//!             rich_text_editor(&self.body).id(BODY).on_action(Message::Edit),
63//!         ]
64//!         .into()
65//!     }
66//! }
67//! ```
68
69use std::rc::Rc;
70
71use iced::advanced::layout::{self, Layout};
72use iced::advanced::widget::{Operation, Tree, Widget};
73use iced::advanced::{Clipboard, Shell, overlay, renderer};
74use iced::keyboard;
75use iced::widget::{Id, column, container, row};
76use iced::{Alignment, Element, Length, Rectangle, Renderer, Theme, mouse};
77
78use crate::forms::rich_text_editor::{
79    Action, BlockKind, Content, Format, Mark, Shortcut, Size, default_keymap,
80};
81use crate::keys::{self, Keymap};
82use crate::lucide;
83use crate::overlay::dropdown_menu::{self, dropdown_menu};
84use crate::overlay::tooltip::Position;
85use crate::primitives::button::{self, Variant, button};
86use crate::primitives::icon_button::icon_button;
87use crate::primitives::input::{Shortcuts, input};
88use crate::primitives::separator::vertical_separator;
89use crate::theme::{Tokens, space};
90
91use super::toolbar::{self, PADDING, SEPARATOR_HEIGHT, separator, toggle, toolbar};
92
93/// The id of the link address field, to focus it on [`Output::EditLink`].
94pub const LINK_FIELD: &str = "iced-cube-formatting-link";
95/// Width of the text size button, wide enough for the longest size name.
96pub const SIZE_WIDTH: f32 = 96.0;
97
98/// A button in the strip.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100pub enum Tool {
101    Bold,
102    Italic,
103    Underline,
104    Strikethrough,
105    Bullets,
106    Numbers,
107    Link,
108    Clear,
109}
110
111impl Tool {
112    pub const ALL: [Tool; 8] = [
113        Tool::Bold,
114        Tool::Italic,
115        Tool::Underline,
116        Tool::Strikethrough,
117        Tool::Bullets,
118        Tool::Numbers,
119        Tool::Link,
120        Tool::Clear,
121    ];
122
123    pub const fn label(self) -> &'static str {
124        match self {
125            Tool::Bold => "Bold",
126            Tool::Italic => "Italic",
127            Tool::Underline => "Underline",
128            Tool::Strikethrough => "Strikethrough",
129            Tool::Bullets => "Bulleted list",
130            Tool::Numbers => "Numbered list",
131            Tool::Link => "Link",
132            Tool::Clear => "Clear formatting",
133        }
134    }
135
136    /// The editor shortcut that does the same.
137    pub const fn shortcut(self) -> Shortcut {
138        match self {
139            Tool::Bold => Shortcut::Bold,
140            Tool::Italic => Shortcut::Italic,
141            Tool::Underline => Shortcut::Underline,
142            Tool::Strikethrough => Shortcut::Strikethrough,
143            Tool::Bullets => Shortcut::BulletedList,
144            Tool::Numbers => Shortcut::NumberedList,
145            Tool::Link => Shortcut::Link,
146            Tool::Clear => Shortcut::ClearFormatting,
147        }
148    }
149
150    /// The format a press applies. The link opens the address field instead.
151    pub fn format(self) -> Option<Format> {
152        Some(match self {
153            Tool::Bold => Format::Toggle(Mark::Bold),
154            Tool::Italic => Format::Toggle(Mark::Italic),
155            Tool::Underline => Format::Toggle(Mark::Underline),
156            Tool::Strikethrough => Format::Toggle(Mark::Strikethrough),
157            Tool::Bullets => Format::Block(BlockKind::Bullet),
158            Tool::Numbers => Format::Block(BlockKind::Numbered),
159            Tool::Clear => Format::Clear,
160            Tool::Link => return None,
161        })
162    }
163}
164
165fn entries(keymap: &Keymap<Shortcut>) -> Vec<toolbar::Entry<Tool>> {
166    let entry = |tool: Tool| {
167        let glyph = match tool {
168            Tool::Bold => lucide!(Bold),
169            Tool::Italic => lucide!(Italic),
170            Tool::Underline => lucide!(Underline),
171            Tool::Strikethrough => lucide!(Strikethrough),
172            Tool::Bullets => lucide!(List),
173            Tool::Numbers => lucide!(ListOrdered),
174            Tool::Link => lucide!(Link),
175            Tool::Clear => lucide!(RemoveFormatting),
176        };
177        let entry = if tool == Tool::Clear {
178            toolbar::button(tool, glyph, tool.label())
179        } else {
180            toggle(tool, glyph, tool.label(), false)
181        };
182        match keymap.chords(&tool.shortcut()).first() {
183            Some(chord) => entry.shortcut(chord.to_string()),
184            None => entry,
185        }
186    };
187    vec![
188        entry(Tool::Bold),
189        entry(Tool::Italic),
190        entry(Tool::Underline),
191        entry(Tool::Strikethrough),
192        separator(),
193        entry(Tool::Bullets),
194        entry(Tool::Numbers),
195        separator(),
196        entry(Tool::Link),
197        entry(Tool::Clear),
198    ]
199}
200
201fn sizes(selected: Option<Size>) -> dropdown_menu::State<Size> {
202    dropdown_menu::State::new(
203        Size::ALL.map(|size| dropdown_menu::radio_item(size, size.label(), Some(size) == selected)),
204    )
205}
206
207/// Changes to the toolbar.
208#[derive(Debug, Clone, PartialEq)]
209pub enum Event {
210    Toolbar(toolbar::Event<Tool>),
211    Sizes(dropdown_menu::Event<Size>),
212    /// The address in the link field changed.
213    LinkChanged(String),
214    /// Applies the address, or removes the link when it is empty.
215    LinkSubmit,
216    LinkRemove,
217    LinkCancel,
218}
219
220/// What a press asks of the app.
221#[derive(Debug, Clone, PartialEq)]
222pub enum Output {
223    /// Apply this to the content, then give the editor focus back.
224    Format(Action),
225    /// The link field opened: focus [`LINK_FIELD`].
226    EditLink,
227    /// The link field, the size menu or the keyboard focus on the buttons
228    /// closed with nothing to apply: give the editor focus back.
229    Closed,
230    /// The keyboard moved onto the buttons: take focus from the editor so
231    /// the arrow keys reach the toolbar, for example with [`unfocus`].
232    Unfocus,
233}
234
235/// A task that takes focus from whichever widget has it, for
236/// [`Output::Unfocus`].
237pub fn unfocus<T: Send + 'static>() -> iced::Task<T> {
238    iced::advanced::widget::operate(iced::advanced::widget::operation::focusable::unfocus())
239}
240
241/// The buttons, the size menu and the link field.
242#[derive(Debug, Clone, PartialEq)]
243pub struct State {
244    toolbar: toolbar::State<Tool>,
245    sizes: dropdown_menu::State<Size>,
246    size: Option<Size>,
247    /// The address being edited while the link field is open.
248    link: Option<String>,
249    link_invalid: bool,
250    has_link: bool,
251    link_requests: Option<u64>,
252}
253
254impl Default for State {
255    fn default() -> Self {
256        Self::new()
257    }
258}
259
260impl State {
261    /// A toolbar whose tooltips show the editor's
262    /// [default shortcuts](crate::forms::rich_text_editor::default_keymap).
263    pub fn new() -> Self {
264        Self::with_keymap(&default_keymap())
265    }
266
267    /// A toolbar whose tooltips show the chords of `keymap`, for an editor
268    /// given the same keymap.
269    pub fn with_keymap(keymap: &Keymap<Shortcut>) -> Self {
270        Self {
271            toolbar: toolbar::State::new(entries(keymap)),
272            sizes: sizes(Some(Size::Normal)),
273            size: Some(Size::Normal),
274            link: None,
275            link_invalid: false,
276            has_link: false,
277            link_requests: None,
278        }
279    }
280
281    /// Whether a button shows as on.
282    pub fn is_on(&self, tool: Tool) -> bool {
283        self.toolbar.is_on(tool)
284    }
285
286    /// The size at the caret, or `None` when the selection mixes sizes.
287    pub fn size(&self) -> Option<Size> {
288        self.size
289    }
290
291    /// The address in the link field, while it is open.
292    pub fn link(&self) -> Option<&str> {
293        self.link.as_deref()
294    }
295
296    pub fn toolbar(&self) -> &toolbar::State<Tool> {
297        &self.toolbar
298    }
299
300    /// Matches the buttons to the formatting at the caret. Returns
301    /// [`Output::EditLink`] when the editor's link shortcut was pressed
302    /// since the last call, having opened the link field.
303    pub fn sync(&mut self, content: &Content) -> Option<Output> {
304        let formatting = content.formatting();
305        for (tool, on) in [
306            (Tool::Bold, formatting.bold),
307            (Tool::Italic, formatting.italic),
308            (Tool::Underline, formatting.underline),
309            (Tool::Strikethrough, formatting.strikethrough),
310            (Tool::Bullets, formatting.block == Some(BlockKind::Bullet)),
311            (Tool::Numbers, formatting.block == Some(BlockKind::Numbered)),
312            (Tool::Link, formatting.link.is_some()),
313        ] {
314            if self.toolbar.is_on(tool) != on {
315                self.toolbar.set_on(tool, on);
316            }
317        }
318        if self.size != formatting.size {
319            self.size = formatting.size;
320            let open = self.sizes.is_open();
321            self.sizes = sizes(formatting.size);
322            if open {
323                let _ = self.sizes.update(dropdown_menu::Event::Open);
324            }
325        }
326        self.has_link = formatting.link.is_some();
327        let requests = content.link_requests();
328        let seen = self.link_requests.replace(requests);
329        if seen.is_some_and(|seen| seen != requests) {
330            self.open_link(content);
331            return Some(Output::EditLink);
332        }
333        None
334    }
335
336    fn open_link(&mut self, content: &Content) {
337        let current = content.formatting().link;
338        self.has_link = current.is_some();
339        self.link_invalid = false;
340        self.link = Some(current.map(|url| url.to_string()).unwrap_or_default());
341    }
342
343    /// Applies an event. `content` is read for the link at the caret.
344    pub fn update(&mut self, event: Event, content: &Content) -> Option<Output> {
345        let format = |format| Some(Output::Format(Action::Format(format)));
346        match event {
347            Event::Toolbar(event) => {
348                let focused = self.toolbar.is_focused();
349                let output = self.toolbar.update(event);
350                let Some(output) = output else {
351                    return match (focused, self.toolbar.is_focused()) {
352                        (false, true) => Some(Output::Unfocus),
353                        (true, false) => Some(Output::Closed),
354                        _ => None,
355                    };
356                };
357                let tool = match output {
358                    dropdown_menu::Output::Activated(tool)
359                    | dropdown_menu::Output::Toggled(tool, _)
360                    | dropdown_menu::Output::Selected(tool) => tool,
361                };
362                // A press from the keyboard ends its focus on the buttons,
363                // as the editor or link field takes focus next.
364                for _ in 0..2 {
365                    if self.toolbar.is_focused() {
366                        let _ = self.toolbar.update(toolbar::Event::Close);
367                    }
368                }
369                if let Some(change) = tool.format() {
370                    return format(change);
371                }
372                if self.link.is_some() {
373                    self.link = None;
374                    self.sync_link_button();
375                    return Some(Output::Closed);
376                }
377                self.open_link(content);
378                self.sync_link_button();
379                Some(Output::EditLink)
380            }
381            Event::Sizes(event) => {
382                let open = self.sizes.is_open();
383                match self.sizes.update(event) {
384                    Some(
385                        dropdown_menu::Output::Selected(size)
386                        | dropdown_menu::Output::Activated(size)
387                        | dropdown_menu::Output::Toggled(size, _),
388                    ) => format(Format::Size(size)),
389                    None if open && !self.sizes.is_open() => Some(Output::Closed),
390                    None => None,
391                }
392            }
393            Event::LinkChanged(address) => {
394                self.link_invalid = false;
395                if let Some(link) = &mut self.link {
396                    *link = address;
397                }
398                None
399            }
400            Event::LinkSubmit => {
401                let address = self.link.as_deref()?.trim().to_owned();
402                if address.is_empty() {
403                    self.link = None;
404                    return if self.has_link {
405                        format(Format::Unlink)
406                    } else {
407                        Some(Output::Closed)
408                    };
409                }
410                if crate::forms::rich_text_editor::normalise_link(&address).is_none() {
411                    self.link_invalid = true;
412                    return None;
413                }
414                self.link = None;
415                format(Format::Link(address))
416            }
417            Event::LinkRemove => {
418                self.link = None;
419                format(Format::Unlink)
420            }
421            Event::LinkCancel => {
422                self.link = None;
423                Some(Output::Closed)
424            }
425        }
426    }
427
428    /// A press flips a toggle straight away; the link button shows the
429    /// caret's link rather than the press.
430    fn sync_link_button(&mut self) {
431        if self.toolbar.is_on(Tool::Link) != self.has_link {
432            self.toolbar.set_on(Tool::Link, self.has_link);
433        }
434    }
435
436    /// Resolves a key press from [`keys::subscription`] for the strip,
437    /// as [`toolbar::State::key_event`] does.
438    pub fn key_event(&self, keymap: &Keymap<toolbar::Action>, key: &keys::Event) -> Option<Event> {
439        self.toolbar.key_event(keymap, key).map(Event::Toolbar)
440    }
441}
442
443/// A formatting toolbar builder. Convert it into an [`Element`] to render.
444pub struct FormattingToolbar<'a, Message> {
445    state: &'a State,
446    tooltip: Option<Position>,
447    on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
448}
449
450impl<Message> std::fmt::Debug for FormattingToolbar<'_, Message> {
451    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
452        f.debug_struct("FormattingToolbar")
453            .field("state", self.state)
454            .field("tooltip", &self.tooltip)
455            .finish_non_exhaustive()
456    }
457}
458
459/// Renders the size menu, the buttons that fit and, while it is open, the
460/// link field. Without [`on_event`](FormattingToolbar::on_event) every
461/// control renders disabled.
462pub fn formatting_toolbar<'a, Message>(state: &'a State) -> FormattingToolbar<'a, Message> {
463    FormattingToolbar {
464        state,
465        tooltip: Some(Position::Bottom),
466        on_event: None,
467    }
468}
469
470impl<'a, Message> FormattingToolbar<'a, Message> {
471    /// Where the button tooltips appear, or `None` for none. Defaults to
472    /// below, as for the toolbar: at the top of a window there is no room
473    /// above, and a tooltip squeezed over its button would catch the next
474    /// click.
475    pub fn tooltip(mut self, position: Option<Position>) -> Self {
476        self.tooltip = position;
477        self
478    }
479
480    pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
481        self.on_event = Some(Box::new(on_event));
482        self
483    }
484}
485
486impl<'a, Message: Clone + 'a> From<FormattingToolbar<'a, Message>> for Element<'a, Message> {
487    fn from(bar: FormattingToolbar<'a, Message>) -> Self {
488        let FormattingToolbar {
489            state,
490            tooltip,
491            on_event,
492        } = bar;
493        let on_event: Option<Rc<dyn Fn(Event) -> Message + 'a>> = on_event.map(Rc::from);
494        let send = |event: Event| on_event.as_ref().map(|on_event| on_event(event));
495
496        let label = state.size.map_or("Mixed", Size::label);
497        let trigger = button(label)
498            .variant(Variant::Ghost)
499            .size(button::Size::Sm)
500            .trailing_icon(lucide!(ChevronDown))
501            .width(SIZE_WIDTH)
502            .on_press_maybe(send(Event::Sizes(dropdown_menu::Event::Toggle)));
503        let size_menu: Element<'a, Message> = match on_event.clone() {
504            Some(on_event) => dropdown_menu(&state.sizes, trigger)
505                .width(160.0)
506                .on_event(move |event| on_event(Event::Sizes(event)))
507                .into(),
508            None => trigger.into(),
509        };
510
511        let mut strip = toolbar(&state.toolbar).tooltip(tooltip).edge(false);
512        if let Some(on_event) = on_event.clone() {
513            strip = strip.on_event(move |event| on_event(Event::Toolbar(event)));
514        }
515
516        let bar = container(
517            row![
518                container(size_menu).padding(PADDING),
519                container(vertical_separator()).height(SEPARATOR_HEIGHT),
520                strip,
521            ]
522            .align_y(Alignment::Center),
523        )
524        .width(Length::Fill)
525        .style(|theme| toolbar::bar_style(&Tokens::of(theme)));
526
527        let Some(address) = &state.link else {
528            return bar.into();
529        };
530        // Escape closes the field rather than only leaving it.
531        let field = input("Paste or type a link", address)
532            .id(Id::new(LINK_FIELD))
533            .shortcuts(Shortcuts::all().without(Shortcut::EscapeUnfocus))
534            .invalid(state.link_invalid)
535            .on_input_maybe(
536                on_event
537                    .clone()
538                    .map(|on_event| move |text| on_event(Event::LinkChanged(text))),
539            )
540            .on_submit_maybe(send(Event::LinkSubmit));
541        let apply = button("Apply")
542            .size(button::Size::Sm)
543            .on_press_maybe(send(Event::LinkSubmit));
544        let mut controls = row![field, apply]
545            .spacing(space::SM)
546            .align_y(Alignment::Center);
547        if state.has_link {
548            controls = controls.push(
549                button("Remove")
550                    .variant(Variant::Ghost)
551                    .size(button::Size::Sm)
552                    .on_press_maybe(send(Event::LinkRemove)),
553            );
554        }
555        let close = icon_button(lucide!(X))
556            .label("Close")
557            .tooltip(None)
558            .size(button::Size::Sm)
559            .on_press_maybe(send(Event::LinkCancel));
560        controls = controls.push(close);
561        let controls: Element<'a, Message> = container(controls)
562            .padding([space::XS, space::SM])
563            .width(Length::Fill)
564            .style(|theme| toolbar::bar_style(&Tokens::of(theme)))
565            .into();
566        let controls = match send(Event::LinkCancel) {
567            Some(cancel) => Element::new(OnEscape {
568                content: controls,
569                message: cancel,
570            }),
571            None => controls,
572        };
573        column![bar, controls].into()
574    }
575}
576
577/// Sends `message` on an Escape press that the content leaves, so Escape
578/// closes the open link field.
579struct OnEscape<'a, Message> {
580    content: Element<'a, Message>,
581    message: Message,
582}
583
584impl<Message: Clone> Widget<Message, Theme, Renderer> for OnEscape<'_, Message> {
585    fn children(&self) -> Vec<Tree> {
586        vec![Tree::new(&self.content)]
587    }
588
589    fn diff(&self, tree: &mut Tree) {
590        tree.diff_children(std::slice::from_ref(&self.content));
591    }
592
593    fn size(&self) -> iced::Size<Length> {
594        self.content.as_widget().size()
595    }
596
597    fn layout(
598        &mut self,
599        tree: &mut Tree,
600        renderer: &Renderer,
601        limits: &layout::Limits,
602    ) -> layout::Node {
603        self.content
604            .as_widget_mut()
605            .layout(&mut tree.children[0], renderer, limits)
606    }
607
608    fn draw(
609        &self,
610        tree: &Tree,
611        renderer: &mut Renderer,
612        theme: &Theme,
613        style: &renderer::Style,
614        layout: Layout<'_>,
615        cursor: mouse::Cursor,
616        viewport: &Rectangle,
617    ) {
618        self.content.as_widget().draw(
619            &tree.children[0],
620            renderer,
621            theme,
622            style,
623            layout,
624            cursor,
625            viewport,
626        );
627    }
628
629    fn operate(
630        &mut self,
631        tree: &mut Tree,
632        layout: Layout<'_>,
633        renderer: &Renderer,
634        operation: &mut dyn Operation,
635    ) {
636        self.content
637            .as_widget_mut()
638            .operate(&mut tree.children[0], layout, renderer, operation);
639    }
640
641    fn update(
642        &mut self,
643        tree: &mut Tree,
644        event: &iced::Event,
645        layout: Layout<'_>,
646        cursor: mouse::Cursor,
647        renderer: &Renderer,
648        clipboard: &mut dyn Clipboard,
649        shell: &mut Shell<'_, Message>,
650        viewport: &Rectangle,
651    ) {
652        self.content.as_widget_mut().update(
653            &mut tree.children[0],
654            event,
655            layout,
656            cursor,
657            renderer,
658            clipboard,
659            shell,
660            viewport,
661        );
662        if shell.is_event_captured() {
663            return;
664        }
665        if let iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event
666            && *key == keyboard::Key::Named(keyboard::key::Named::Escape)
667            && modifiers.is_empty()
668        {
669            shell.publish(self.message.clone());
670            shell.capture_event();
671        }
672    }
673
674    fn mouse_interaction(
675        &self,
676        tree: &Tree,
677        layout: Layout<'_>,
678        cursor: mouse::Cursor,
679        viewport: &Rectangle,
680        renderer: &Renderer,
681    ) -> mouse::Interaction {
682        self.content.as_widget().mouse_interaction(
683            &tree.children[0],
684            layout,
685            cursor,
686            viewport,
687            renderer,
688        )
689    }
690
691    fn overlay<'b>(
692        &'b mut self,
693        tree: &'b mut Tree,
694        layout: Layout<'b>,
695        renderer: &Renderer,
696        viewport: &Rectangle,
697        translation: iced::Vector,
698    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
699        self.content.as_widget_mut().overlay(
700            &mut tree.children[0],
701            layout,
702            renderer,
703            viewport,
704            translation,
705        )
706    }
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712    use crate::forms::rich_text_editor::{Motion, Position};
713
714    fn press(state: &mut State, content: &Content, tool: Tool) -> Option<Output> {
715        state.update(Event::Toolbar(toolbar::Event::Press(tool)), content)
716    }
717
718    #[test]
719    fn every_tool_but_link_formats() {
720        for tool in Tool::ALL {
721            assert_eq!(tool.format().is_none(), tool == Tool::Link, "{tool:?}");
722        }
723        let mut state = State::new();
724        let content = Content::with_text("text");
725        assert_eq!(
726            press(&mut state, &content, Tool::Bold),
727            Some(Output::Format(Action::Format(Format::Toggle(Mark::Bold))))
728        );
729        assert_eq!(
730            press(&mut state, &content, Tool::Numbers),
731            Some(Output::Format(Action::Format(Format::Block(
732                BlockKind::Numbered
733            ))))
734        );
735    }
736
737    #[test]
738    fn tooltips_show_the_shortcuts() {
739        let state = State::new();
740        let bold = state
741            .toolbar()
742            .item(Tool::Bold)
743            .and_then(|item| item.shortcut.clone());
744        let expected = if cfg!(target_os = "macos") {
745            "Cmd+B"
746        } else {
747            "Ctrl+B"
748        };
749        assert_eq!(bold.as_deref(), Some(expected));
750        let bare = State::with_keymap(&Keymap::new());
751        assert!(
752            bare.toolbar()
753                .item(Tool::Bold)
754                .is_some_and(|item| item.shortcut.is_none())
755        );
756    }
757
758    #[test]
759    fn sync_follows_the_caret() {
760        let mut content = Content::with_text("plain");
761        let mut state = State::new();
762        assert_eq!(state.sync(&content), None);
763        content.perform(Action::SelectAll);
764        for format in [
765            Format::Toggle(Mark::Bold),
766            Format::Toggle(Mark::Underline),
767            Format::Size(Size::Large),
768            Format::Block(BlockKind::Bullet),
769        ] {
770            content.perform(Action::Format(format));
771        }
772        state.sync(&content);
773        assert!(state.is_on(Tool::Bold) && state.is_on(Tool::Underline));
774        assert!(!state.is_on(Tool::Italic) && !state.is_on(Tool::Numbers));
775        assert!(state.is_on(Tool::Bullets));
776        assert_eq!(state.size(), Some(Size::Large));
777        assert!(state.sizes.is_checked(Size::Large));
778        content.perform(Action::Move(Motion::DocumentEnd));
779        content.perform(Action::Edit(crate::forms::rich_text_editor::Edit::Insert(
780            " x".into(),
781        )));
782        content.perform(Action::Select(Motion::DocumentStart));
783        content.perform(Action::Format(Format::Size(Size::Small)));
784        content.perform(Action::Move(Motion::To(Position::new(0, 0))));
785        content.perform(Action::Select(Motion::DocumentEnd));
786        state.sync(&content);
787        assert_eq!(state.size(), Some(Size::Small));
788    }
789
790    #[test]
791    fn sizes_come_from_the_menu() {
792        let mut state = State::new();
793        let content = Content::new();
794        assert_eq!(
795            state.update(
796                Event::Sizes(dropdown_menu::Event::Activate(Size::Huge)),
797                &content
798            ),
799            Some(Output::Format(Action::Format(Format::Size(Size::Huge))))
800        );
801    }
802
803    #[test]
804    fn the_link_field_opens_applies_and_cancels() {
805        let mut content = Content::with_text("see here");
806        let mut state = State::new();
807        state.sync(&content);
808        assert_eq!(
809            press(&mut state, &content, Tool::Link),
810            Some(Output::EditLink)
811        );
812        assert_eq!(state.link(), Some(""));
813        assert!(!state.is_on(Tool::Link));
814        state.update(Event::LinkChanged("javascript:alert(1)".into()), &content);
815        assert_eq!(state.update(Event::LinkSubmit, &content), None);
816        assert!(state.link_invalid);
817        state.update(Event::LinkChanged("example.com".into()), &content);
818        let Some(Output::Format(action)) = state.update(Event::LinkSubmit, &content) else {
819            panic!("a link to apply");
820        };
821        assert_eq!(action, Action::Format(Format::Link("example.com".into())));
822        assert_eq!(state.link(), None);
823        content.perform(action);
824        state.sync(&content);
825        assert!(state.is_on(Tool::Link));
826
827        assert_eq!(
828            press(&mut state, &content, Tool::Link),
829            Some(Output::EditLink)
830        );
831        assert_eq!(state.link(), Some("https://example.com"));
832        assert!(state.is_on(Tool::Link));
833        assert_eq!(
834            state.update(Event::LinkRemove, &content),
835            Some(Output::Format(Action::Format(Format::Unlink)))
836        );
837        press(&mut state, &content, Tool::Link);
838        assert_eq!(
839            state.update(Event::LinkCancel, &content),
840            Some(Output::Closed)
841        );
842        press(&mut state, &content, Tool::Link);
843        state.update(Event::LinkChanged("  ".into()), &content);
844        assert_eq!(
845            state.update(Event::LinkSubmit, &content),
846            Some(Output::Format(Action::Format(Format::Unlink)))
847        );
848    }
849
850    #[test]
851    fn keyboard_focus_on_the_buttons_takes_and_returns_focus() {
852        let mut state = State::new();
853        let content = Content::with_text("x");
854        assert_eq!(
855            state.update(Event::Toolbar(toolbar::Event::Focus), &content),
856            Some(Output::Unfocus)
857        );
858        assert_eq!(
859            state.update(Event::Toolbar(toolbar::Event::Next), &content),
860            None
861        );
862        assert_eq!(
863            state.update(Event::Toolbar(toolbar::Event::Close), &content),
864            Some(Output::Closed)
865        );
866    }
867
868    #[test]
869    fn closing_the_size_menu_returns_focus() {
870        let mut state = State::new();
871        let content = Content::new();
872        assert_eq!(
873            state.update(Event::Sizes(dropdown_menu::Event::Toggle), &content),
874            None
875        );
876        assert_eq!(
877            state.update(Event::Sizes(dropdown_menu::Event::Close), &content),
878            Some(Output::Closed)
879        );
880        assert_eq!(
881            state.update(Event::Sizes(dropdown_menu::Event::Close), &content),
882            None
883        );
884    }
885
886    #[test]
887    fn pressing_link_again_closes_the_field() {
888        let mut state = State::new();
889        let content = Content::with_text("x");
890        assert_eq!(
891            press(&mut state, &content, Tool::Link),
892            Some(Output::EditLink)
893        );
894        assert_eq!(
895            press(&mut state, &content, Tool::Link),
896            Some(Output::Closed)
897        );
898        assert_eq!(state.link(), None);
899        assert!(!state.is_on(Tool::Link));
900    }
901
902    #[test]
903    fn the_link_shortcut_opens_the_field_once() {
904        let mut content = Content::with_text("x");
905        let mut state = State::new();
906        state.sync(&content);
907        content.perform(Action::RequestLink);
908        assert_eq!(state.sync(&content), Some(Output::EditLink));
909        assert_eq!(state.link(), Some(""));
910        assert_eq!(state.sync(&content), None);
911    }
912}