iced_cube/forms/rich_text_editor/
mod.rs1mod 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
82pub const MIN_HEIGHT: f32 = 96.0;
84
85pub fn default_keymap() -> Keymap<Shortcut> {
105 crate::editing::formatting_keymap()
106}
107
108pub 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
128pub 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
148pub 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 pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
171 self.placeholder = Some(placeholder.into());
172 self
173 }
174
175 pub fn id(mut self, id: impl Into<Id>) -> Self {
177 self.id = Some(id.into());
178 self
179 }
180
181 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 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 pub fn invalid(mut self, invalid: bool) -> Self {
201 self.invalid = invalid;
202 self
203 }
204
205 pub fn width(mut self, width: impl Into<Length>) -> Self {
207 self.width = width.into();
208 self
209 }
210
211 pub fn height(mut self, height: impl Into<Length>) -> Self {
215 self.height = height.into();
216 self
217 }
218
219 pub fn min_height(mut self, min_height: f32) -> Self {
221 self.min_height = min_height.max(0.0);
222 self
223 }
224
225 pub fn max_height(mut self, max_height: f32) -> Self {
227 self.max_height = max_height.max(0.0);
228 self
229 }
230
231 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 pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
247 self.shortcuts = shortcuts;
248 self
249 }
250
251 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#[derive(Debug, Clone, Copy, PartialEq)]
287pub struct Appearance {
288 pub field: text_input::Style,
289 pub link: iced::Color,
291 pub quote: iced::Color,
293 pub quote_text: iced::Color,
294 pub caret: iced::Color,
295 pub scrollbar: iced::Color,
296}
297
298pub 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}