Skip to main content

teksilo_widgets/
editor_shortcuts.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! The editors' own rebindable commands: bold and the rest of
5//! [`RichTextEditor`](crate::rich_text::RichTextEditor)'s formatting
6//! ([`FormatShortcut`]), comment and duplicate in
7//! [`CodeEditor`](crate::CodeEditor) ([`CodeShortcut`]).
8//!
9//! They work as the standard edit commands do
10//! ([`StandardEdit`](teksilo_core::shortcut::StandardEdit)): a global shortcut
11//! whose id is also the intent name, and an action on each editor that runs
12//! it, so the focused editor answers. Where the standard set is registered in
13//! every tree, these exist only while an editor that runs them does: each
14//! editable instance declares them with
15//! [`register_shortcut_shared`](teksilo_core::build_context::BuildContext::register_shortcut_shared),
16//! and the shortcut goes with the last. A read-only viewer declares none. A
17//! settings UI therefore lists Bold only in an application that has a
18//! rich-text editor, and a user's binding waits in the registry for the next
19//! one.
20//!
21//! An application that binds one of these chords to a global shortcut of its
22//! own shares it with the editor's while an editor exists.
23
24use teksilo_core::event::Key;
25use teksilo_core::shortcut::{KeyStroke, Shortcut};
26use teksilo_i18n::{LocalizedString, tr_widget};
27
28/// The settings-UI category of every [`FormatShortcut`].
29pub const FORMAT_CATEGORY: &str = "format";
30
31/// The settings-UI category of every [`CodeShortcut`].
32pub const CODE_CATEGORY: &str = "code";
33
34/// A formatting command of `RichTextEditor`. Its [`id`](Self::id) is both the
35/// shortcut id and the intent name.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum FormatShortcut {
39    /// `format.bold`, Ctrl+B (⌘B on macOS).
40    Bold,
41    /// `format.italic`, Ctrl+I (⌘I on macOS).
42    Italic,
43    /// `format.underline`, Ctrl+U (⌘U on macOS).
44    Underline,
45    /// `format.insert_paragraph`, Ctrl+Enter (⌘Enter on macOS): a new
46    /// paragraph even inside a table cell, where Enter moves to the cell
47    /// below.
48    InsertParagraph,
49}
50
51impl FormatShortcut {
52    /// Every formatting command, in the order a settings UI lists them.
53    pub const ALL: [FormatShortcut; 4] = [
54        FormatShortcut::Bold,
55        FormatShortcut::Italic,
56        FormatShortcut::Underline,
57        FormatShortcut::InsertParagraph,
58    ];
59
60    /// The shortcut id, which is also the intent name.
61    pub const fn id(self) -> &'static str {
62        match self {
63            FormatShortcut::Bold => "format.bold",
64            FormatShortcut::Italic => "format.italic",
65            FormatShortcut::Underline => "format.underline",
66            FormatShortcut::InsertParagraph => "format.insert_paragraph",
67        }
68    }
69
70    /// The command whose [`id`](Self::id) is `id`.
71    pub fn from_id(id: &str) -> Option<Self> {
72        Self::ALL.into_iter().find(|command| command.id() == id)
73    }
74
75    /// The shortcut an editor declares for this command: its default chord, a
76    /// name in the active language, and the [`FORMAT_CATEGORY`] category.
77    pub fn shortcut(self) -> Shortcut {
78        let (name, key) = match self {
79            FormatShortcut::Bold => (tr_widget!(shortcut_format_bold()), Key::B),
80            FormatShortcut::Italic => (tr_widget!(shortcut_format_italic()), Key::I),
81            FormatShortcut::Underline => (tr_widget!(shortcut_format_underline()), Key::U),
82            FormatShortcut::InsertParagraph => {
83                (tr_widget!(shortcut_format_insert_paragraph()), Key::Enter)
84            }
85        };
86        described(
87            self.id(),
88            name,
89            FORMAT_CATEGORY,
90            tr_widget!(shortcut_category_format()),
91        )
92        .primary(KeyStroke::ctrl(key))
93        .build()
94    }
95}
96
97/// A command of `CodeEditor`. Its [`id`](Self::id) is both the shortcut id and
98/// the intent name.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100#[non_exhaustive]
101pub enum CodeShortcut {
102    /// `code.toggle_comment`, Ctrl+/ (⌘/ on macOS). On a layout that types `/`
103    /// with Shift (AZERTY, German) the chord arrives with Shift held and still
104    /// matches: the registry ignores Shift for a punctuation key.
105    ToggleComment,
106    /// `code.duplicate`, Ctrl+D (⌘D on macOS): the caret's line, or the
107    /// selection, below itself.
108    Duplicate,
109}
110
111impl CodeShortcut {
112    /// Every code command, in the order a settings UI lists them.
113    pub const ALL: [CodeShortcut; 2] = [CodeShortcut::ToggleComment, CodeShortcut::Duplicate];
114
115    /// The shortcut id, which is also the intent name.
116    pub const fn id(self) -> &'static str {
117        match self {
118            CodeShortcut::ToggleComment => "code.toggle_comment",
119            CodeShortcut::Duplicate => "code.duplicate",
120        }
121    }
122
123    /// The command whose [`id`](Self::id) is `id`.
124    pub fn from_id(id: &str) -> Option<Self> {
125        Self::ALL.into_iter().find(|command| command.id() == id)
126    }
127
128    /// The shortcut an editor declares for this command: its default chords, a
129    /// name in the active language, and the [`CODE_CATEGORY`] category.
130    pub fn shortcut(self) -> Shortcut {
131        let category = || tr_widget!(shortcut_category_code());
132        match self {
133            CodeShortcut::ToggleComment => described(
134                self.id(),
135                tr_widget!(shortcut_code_toggle_comment()),
136                CODE_CATEGORY,
137                category(),
138            )
139            .primary(KeyStroke::ctrl(Key::Character('/')))
140            .build(),
141            CodeShortcut::Duplicate => described(
142                self.id(),
143                tr_widget!(shortcut_code_duplicate()),
144                CODE_CATEGORY,
145                category(),
146            )
147            .primary(KeyStroke::ctrl(Key::D))
148            .build(),
149        }
150    }
151}
152
153fn described(
154    id: &'static str,
155    name: LocalizedString,
156    category: &'static str,
157    category_label: LocalizedString,
158) -> teksilo_core::shortcut::ShortcutBuilder {
159    Shortcut::new(id)
160        .name(name)
161        .category(category)
162        .category_label(category_label)
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn ids_round_trip() {
171        for command in FormatShortcut::ALL {
172            assert_eq!(FormatShortcut::from_id(command.id()), Some(command));
173            assert_eq!(command.shortcut().id, command.id());
174        }
175        for command in CodeShortcut::ALL {
176            assert_eq!(CodeShortcut::from_id(command.id()), Some(command));
177            assert_eq!(command.shortcut().id, command.id());
178        }
179        assert_eq!(FormatShortcut::from_id("code.duplicate"), None);
180    }
181
182    #[test]
183    fn toggle_comment_matches_a_layout_that_types_slash_with_shift() {
184        let mut registry = teksilo_core::shortcut::ShortcutRegistry::new();
185        registry.register(CodeShortcut::ToggleComment.shortcut());
186        // French-PC: `/` is Shift+`:`, so the accelerator + `/` arrives with
187        // Shift held and the logical character `/`.
188        let french = KeyStroke::command_shift(Key::Character('/'));
189        assert_eq!(
190            registry.find_by_keystroke(french).map(|s| s.shortcut.id),
191            Some("code.toggle_comment")
192        );
193        // Ctrl+Shift+D is not Ctrl+D.
194        registry.register(CodeShortcut::Duplicate.shortcut());
195        assert!(
196            registry
197                .find_by_keystroke(KeyStroke::command_shift(Key::D))
198                .is_none()
199        );
200    }
201}