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        #[cfg(feature = "icedwright")]
527        let bar = icedwright_probe::semantic(bar)
528            .role(icedwright_probe::role::Toolbar)
529            .name("Formatting")
530            .component("iced_cube::formatting_toolbar");
531
532        let Some(address) = &state.link else {
533            return bar.into();
534        };
535        // Escape closes the field rather than only leaving it.
536        let field = input("Paste or type a link", address)
537            .id(Id::new(LINK_FIELD))
538            .shortcuts(Shortcuts::all().without(Shortcut::EscapeUnfocus))
539            .invalid(state.link_invalid)
540            .on_input_maybe(
541                on_event
542                    .clone()
543                    .map(|on_event| move |text| on_event(Event::LinkChanged(text))),
544            )
545            .on_submit_maybe(send(Event::LinkSubmit));
546        let apply = button("Apply")
547            .size(button::Size::Sm)
548            .on_press_maybe(send(Event::LinkSubmit));
549        let mut controls = row![field, apply]
550            .spacing(space::SM)
551            .align_y(Alignment::Center);
552        if state.has_link {
553            controls = controls.push(
554                button("Remove")
555                    .variant(Variant::Ghost)
556                    .size(button::Size::Sm)
557                    .on_press_maybe(send(Event::LinkRemove)),
558            );
559        }
560        let close = icon_button(lucide!(X))
561            .label("Close")
562            .tooltip(None)
563            .size(button::Size::Sm)
564            .on_press_maybe(send(Event::LinkCancel));
565        controls = controls.push(close);
566        let controls: Element<'a, Message> = container(controls)
567            .padding([space::XS, space::SM])
568            .width(Length::Fill)
569            .style(|theme| toolbar::bar_style(&Tokens::of(theme)))
570            .into();
571        let controls = match send(Event::LinkCancel) {
572            Some(cancel) => Element::new(OnEscape {
573                content: controls,
574                message: cancel,
575            }),
576            None => controls,
577        };
578        column![bar, controls].into()
579    }
580}
581
582/// Sends `message` on an Escape press that the content leaves, so Escape
583/// closes the open link field.
584struct OnEscape<'a, Message> {
585    content: Element<'a, Message>,
586    message: Message,
587}
588
589impl<Message: Clone> Widget<Message, Theme, Renderer> for OnEscape<'_, Message> {
590    fn children(&self) -> Vec<Tree> {
591        vec![Tree::new(&self.content)]
592    }
593
594    fn diff(&self, tree: &mut Tree) {
595        tree.diff_children(std::slice::from_ref(&self.content));
596    }
597
598    fn size(&self) -> iced::Size<Length> {
599        self.content.as_widget().size()
600    }
601
602    fn layout(
603        &mut self,
604        tree: &mut Tree,
605        renderer: &Renderer,
606        limits: &layout::Limits,
607    ) -> layout::Node {
608        self.content
609            .as_widget_mut()
610            .layout(&mut tree.children[0], renderer, limits)
611    }
612
613    fn draw(
614        &self,
615        tree: &Tree,
616        renderer: &mut Renderer,
617        theme: &Theme,
618        style: &renderer::Style,
619        layout: Layout<'_>,
620        cursor: mouse::Cursor,
621        viewport: &Rectangle,
622    ) {
623        self.content.as_widget().draw(
624            &tree.children[0],
625            renderer,
626            theme,
627            style,
628            layout,
629            cursor,
630            viewport,
631        );
632    }
633
634    fn operate(
635        &mut self,
636        tree: &mut Tree,
637        layout: Layout<'_>,
638        renderer: &Renderer,
639        operation: &mut dyn Operation,
640    ) {
641        self.content
642            .as_widget_mut()
643            .operate(&mut tree.children[0], layout, renderer, operation);
644    }
645
646    fn update(
647        &mut self,
648        tree: &mut Tree,
649        event: &iced::Event,
650        layout: Layout<'_>,
651        cursor: mouse::Cursor,
652        renderer: &Renderer,
653        clipboard: &mut dyn Clipboard,
654        shell: &mut Shell<'_, Message>,
655        viewport: &Rectangle,
656    ) {
657        self.content.as_widget_mut().update(
658            &mut tree.children[0],
659            event,
660            layout,
661            cursor,
662            renderer,
663            clipboard,
664            shell,
665            viewport,
666        );
667        if shell.is_event_captured() {
668            return;
669        }
670        if let iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event
671            && *key == keyboard::Key::Named(keyboard::key::Named::Escape)
672            && modifiers.is_empty()
673        {
674            shell.publish(self.message.clone());
675            shell.capture_event();
676        }
677    }
678
679    fn mouse_interaction(
680        &self,
681        tree: &Tree,
682        layout: Layout<'_>,
683        cursor: mouse::Cursor,
684        viewport: &Rectangle,
685        renderer: &Renderer,
686    ) -> mouse::Interaction {
687        self.content.as_widget().mouse_interaction(
688            &tree.children[0],
689            layout,
690            cursor,
691            viewport,
692            renderer,
693        )
694    }
695
696    fn overlay<'b>(
697        &'b mut self,
698        tree: &'b mut Tree,
699        layout: Layout<'b>,
700        renderer: &Renderer,
701        viewport: &Rectangle,
702        translation: iced::Vector,
703    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
704        self.content.as_widget_mut().overlay(
705            &mut tree.children[0],
706            layout,
707            renderer,
708            viewport,
709            translation,
710        )
711    }
712}
713
714#[cfg(test)]
715mod tests {
716    use super::*;
717    use crate::forms::rich_text_editor::{Motion, Position};
718
719    fn press(state: &mut State, content: &Content, tool: Tool) -> Option<Output> {
720        state.update(Event::Toolbar(toolbar::Event::Press(tool)), content)
721    }
722
723    #[test]
724    fn every_tool_but_link_formats() {
725        for tool in Tool::ALL {
726            assert_eq!(tool.format().is_none(), tool == Tool::Link, "{tool:?}");
727        }
728        let mut state = State::new();
729        let content = Content::with_text("text");
730        assert_eq!(
731            press(&mut state, &content, Tool::Bold),
732            Some(Output::Format(Action::Format(Format::Toggle(Mark::Bold))))
733        );
734        assert_eq!(
735            press(&mut state, &content, Tool::Numbers),
736            Some(Output::Format(Action::Format(Format::Block(
737                BlockKind::Numbered
738            ))))
739        );
740    }
741
742    #[test]
743    fn tooltips_show_the_shortcuts() {
744        let state = State::new();
745        let bold = state
746            .toolbar()
747            .item(Tool::Bold)
748            .and_then(|item| item.shortcut.clone());
749        let expected = if cfg!(target_os = "macos") {
750            "Cmd+B"
751        } else {
752            "Ctrl+B"
753        };
754        assert_eq!(bold.as_deref(), Some(expected));
755        let bare = State::with_keymap(&Keymap::new());
756        assert!(
757            bare.toolbar()
758                .item(Tool::Bold)
759                .is_some_and(|item| item.shortcut.is_none())
760        );
761    }
762
763    #[test]
764    fn sync_follows_the_caret() {
765        let mut content = Content::with_text("plain");
766        let mut state = State::new();
767        assert_eq!(state.sync(&content), None);
768        content.perform(Action::SelectAll);
769        for format in [
770            Format::Toggle(Mark::Bold),
771            Format::Toggle(Mark::Underline),
772            Format::Size(Size::Large),
773            Format::Block(BlockKind::Bullet),
774        ] {
775            content.perform(Action::Format(format));
776        }
777        state.sync(&content);
778        assert!(state.is_on(Tool::Bold) && state.is_on(Tool::Underline));
779        assert!(!state.is_on(Tool::Italic) && !state.is_on(Tool::Numbers));
780        assert!(state.is_on(Tool::Bullets));
781        assert_eq!(state.size(), Some(Size::Large));
782        assert!(state.sizes.is_checked(Size::Large));
783        content.perform(Action::Move(Motion::DocumentEnd));
784        content.perform(Action::Edit(crate::forms::rich_text_editor::Edit::Insert(
785            " x".into(),
786        )));
787        content.perform(Action::Select(Motion::DocumentStart));
788        content.perform(Action::Format(Format::Size(Size::Small)));
789        content.perform(Action::Move(Motion::To(Position::new(0, 0))));
790        content.perform(Action::Select(Motion::DocumentEnd));
791        state.sync(&content);
792        assert_eq!(state.size(), Some(Size::Small));
793    }
794
795    #[test]
796    fn sizes_come_from_the_menu() {
797        let mut state = State::new();
798        let content = Content::new();
799        assert_eq!(
800            state.update(
801                Event::Sizes(dropdown_menu::Event::Activate(Size::Huge)),
802                &content
803            ),
804            Some(Output::Format(Action::Format(Format::Size(Size::Huge))))
805        );
806    }
807
808    #[test]
809    fn the_link_field_opens_applies_and_cancels() {
810        let mut content = Content::with_text("see here");
811        let mut state = State::new();
812        state.sync(&content);
813        assert_eq!(
814            press(&mut state, &content, Tool::Link),
815            Some(Output::EditLink)
816        );
817        assert_eq!(state.link(), Some(""));
818        assert!(!state.is_on(Tool::Link));
819        state.update(Event::LinkChanged("javascript:alert(1)".into()), &content);
820        assert_eq!(state.update(Event::LinkSubmit, &content), None);
821        assert!(state.link_invalid);
822        state.update(Event::LinkChanged("example.com".into()), &content);
823        let Some(Output::Format(action)) = state.update(Event::LinkSubmit, &content) else {
824            panic!("a link to apply");
825        };
826        assert_eq!(action, Action::Format(Format::Link("example.com".into())));
827        assert_eq!(state.link(), None);
828        content.perform(action);
829        state.sync(&content);
830        assert!(state.is_on(Tool::Link));
831
832        assert_eq!(
833            press(&mut state, &content, Tool::Link),
834            Some(Output::EditLink)
835        );
836        assert_eq!(state.link(), Some("https://example.com"));
837        assert!(state.is_on(Tool::Link));
838        assert_eq!(
839            state.update(Event::LinkRemove, &content),
840            Some(Output::Format(Action::Format(Format::Unlink)))
841        );
842        press(&mut state, &content, Tool::Link);
843        assert_eq!(
844            state.update(Event::LinkCancel, &content),
845            Some(Output::Closed)
846        );
847        press(&mut state, &content, Tool::Link);
848        state.update(Event::LinkChanged("  ".into()), &content);
849        assert_eq!(
850            state.update(Event::LinkSubmit, &content),
851            Some(Output::Format(Action::Format(Format::Unlink)))
852        );
853    }
854
855    #[test]
856    fn keyboard_focus_on_the_buttons_takes_and_returns_focus() {
857        let mut state = State::new();
858        let content = Content::with_text("x");
859        assert_eq!(
860            state.update(Event::Toolbar(toolbar::Event::Focus), &content),
861            Some(Output::Unfocus)
862        );
863        assert_eq!(
864            state.update(Event::Toolbar(toolbar::Event::Next), &content),
865            None
866        );
867        assert_eq!(
868            state.update(Event::Toolbar(toolbar::Event::Close), &content),
869            Some(Output::Closed)
870        );
871    }
872
873    #[test]
874    fn closing_the_size_menu_returns_focus() {
875        let mut state = State::new();
876        let content = Content::new();
877        assert_eq!(
878            state.update(Event::Sizes(dropdown_menu::Event::Toggle), &content),
879            None
880        );
881        assert_eq!(
882            state.update(Event::Sizes(dropdown_menu::Event::Close), &content),
883            Some(Output::Closed)
884        );
885        assert_eq!(
886            state.update(Event::Sizes(dropdown_menu::Event::Close), &content),
887            None
888        );
889    }
890
891    #[test]
892    fn pressing_link_again_closes_the_field() {
893        let mut state = State::new();
894        let content = Content::with_text("x");
895        assert_eq!(
896            press(&mut state, &content, Tool::Link),
897            Some(Output::EditLink)
898        );
899        assert_eq!(
900            press(&mut state, &content, Tool::Link),
901            Some(Output::Closed)
902        );
903        assert_eq!(state.link(), None);
904        assert!(!state.is_on(Tool::Link));
905    }
906
907    #[test]
908    fn the_link_shortcut_opens_the_field_once() {
909        let mut content = Content::with_text("x");
910        let mut state = State::new();
911        state.sync(&content);
912        content.perform(Action::RequestLink);
913        assert_eq!(state.sync(&content), Some(Output::EditLink));
914        assert_eq!(state.link(), Some(""));
915        assert_eq!(state.sync(&content), None);
916    }
917}