1use std::sync::Arc;
5
6use super::document::{
7 BlockKind, Document, Mark, Position, Selection, Size, Style, normalise_link,
8};
9use super::{html, plain, snapshot};
10use crate::editing::{self, History};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Motion {
15 Left,
16 Right,
17 WordLeft,
18 WordRight,
19 BlockStart,
21 BlockEnd,
23 DocumentStart,
24 DocumentEnd,
25 To(Position),
28}
29
30#[derive(Debug, Clone, PartialEq)]
32pub enum Edit {
33 Insert(String),
35 Paste(String),
37 PasteFormatted(Document),
39 Enter,
41 Backspace,
42 Delete,
43 DeleteWordBackward,
44 DeleteWordForward,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum Format {
51 Toggle(Mark),
53 Size(Size),
54 Block(BlockKind),
57 Link(String),
61 Unlink,
63 Clear,
65}
66
67#[derive(Debug, Clone, PartialEq)]
69pub enum Action {
70 Move(Motion),
71 Select(Motion),
73 SelectAll,
74 SelectWord(Position),
75 SelectBlock(Position),
76 Edit(Edit),
77 Format(Format),
78 Undo,
79 Redo,
80 RequestLink,
83}
84
85impl Action {
86 pub fn is_edit(&self) -> bool {
88 matches!(
89 self,
90 Action::Edit(_) | Action::Format(_) | Action::Undo | Action::Redo
91 )
92 }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Default)]
97pub struct Formatting {
98 pub bold: bool,
99 pub italic: bool,
100 pub underline: bool,
101 pub strikethrough: bool,
102 pub size: Option<Size>,
104 pub block: Option<BlockKind>,
106 pub link: Option<Arc<str>>,
108}
109
110impl Formatting {
111 pub fn has(&self, mark: Mark) -> bool {
112 match mark {
113 Mark::Bold => self.bold,
114 Mark::Italic => self.italic,
115 Mark::Underline => self.underline,
116 Mark::Strikethrough => self.strikethrough,
117 }
118 }
119}
120
121#[derive(Debug, Clone)]
128pub struct Content {
129 document: Document,
130 selection: Selection,
131 typing: Option<Style>,
133 history: History,
134 snapshot: String,
136 revision: u64,
137 link_requests: u64,
138}
139
140impl Default for Content {
141 fn default() -> Self {
142 Self::new()
143 }
144}
145
146impl Content {
147 pub fn new() -> Self {
148 Self::with_document(Document::new())
149 }
150
151 pub fn with_text(text: &str) -> Self {
153 Self::with_document(Document::from_text(text))
154 }
155
156 pub fn with_html(html: &str) -> Self {
158 Self::with_document(html::from_html(html))
159 }
160
161 pub fn with_document(document: Document) -> Self {
162 Self {
163 snapshot: snapshot::encode(&document),
164 selection: Selection::caret(document.end()),
165 document,
166 typing: None,
167 history: History::default(),
168 revision: 0,
169 link_requests: 0,
170 }
171 }
172
173 pub fn document(&self) -> &Document {
174 &self.document
175 }
176
177 pub fn selection(&self) -> Selection {
178 self.selection
179 }
180
181 pub fn revision(&self) -> u64 {
184 self.revision
185 }
186
187 pub fn link_requests(&self) -> u64 {
190 self.link_requests
191 }
192
193 pub fn html(&self) -> String {
195 html::to_html(&self.document)
196 }
197
198 pub fn plain_text(&self) -> String {
200 plain::to_plain(&self.document)
201 }
202
203 pub fn text(&self) -> String {
205 self.document.text()
206 }
207
208 pub fn is_empty(&self) -> bool {
209 self.document.is_empty()
210 }
211
212 pub fn has_formatting(&self) -> bool {
215 self.document.has_formatting()
216 }
217
218 pub fn selected(&self) -> Document {
220 self.document
221 .slice(self.selection.start(), self.selection.end())
222 }
223
224 pub fn selected_text(&self) -> String {
226 self.selected().text()
227 }
228
229 pub fn typing_style(&self) -> Style {
231 self.typing
232 .clone()
233 .unwrap_or_else(|| self.document.style_for_insert(self.selection.head))
234 }
235
236 pub fn formatting(&self) -> Formatting {
237 let (start, end) = (self.selection.start(), self.selection.end());
238 let link = self.document.link_at(start).map(|(_, _, url)| url);
239 let block = self.block_kind(start.block, end.block);
240 if self.selection.is_collapsed() {
241 let style = self.typing_style();
242 return Formatting {
243 bold: style.bold,
244 italic: style.italic,
245 underline: style.underline,
246 strikethrough: style.strikethrough,
247 size: Some(style.size),
248 block,
249 link,
250 };
251 }
252 let has = |mark| self.document.all_have(start, end, |style| style.has(mark));
253 Formatting {
254 bold: has(Mark::Bold),
255 italic: has(Mark::Italic),
256 underline: has(Mark::Underline),
257 strikethrough: has(Mark::Strikethrough),
258 size: self.document.size_between(start, end),
259 block,
260 link,
261 }
262 }
263
264 fn block_kind(&self, first: usize, last: usize) -> Option<BlockKind> {
265 let kinds = self.document.blocks().get(first..=last)?;
266 let kind = kinds.first()?.kind();
267 kinds
268 .iter()
269 .all(|block| block.kind() == kind)
270 .then_some(kind)
271 }
272
273 pub fn perform(&mut self, action: Action) {
275 match action {
276 Action::Move(motion) => {
277 let to = self.motion(motion, false);
278 self.select(Selection::caret(to));
279 }
280 Action::Select(motion) => {
281 let to = self.motion(motion, true);
282 self.select(Selection::new(self.selection.anchor, to));
283 }
284 Action::SelectAll => {
285 self.select(Selection::new(self.document.start(), self.document.end()));
286 }
287 Action::SelectWord(at) => {
288 let (start, end) = self.document.word_at(at);
289 self.select(Selection::new(start, end));
290 }
291 Action::SelectBlock(at) => {
292 let at = self.document.clamp(at);
293 let len = self.document.block(at.block).map_or(0, |block| block.len());
294 self.select(Selection::new(
295 Position::new(at.block, 0),
296 Position::new(at.block, len),
297 ));
298 }
299 Action::Edit(edit) => self.edit(edit),
300 Action::Format(format) => self.format(format),
301 Action::Undo => {
302 let restore = self.history.undo(self.snapshot.clone());
303 self.restore(restore);
304 }
305 Action::Redo => {
306 let restore = self.history.redo(self.snapshot.clone());
307 self.restore(restore);
308 }
309 Action::RequestLink => self.link_requests += 1,
310 }
311 }
312
313 fn select(&mut self, selection: Selection) {
314 let selection = Selection::new(
315 self.document.clamp(selection.anchor),
316 self.document.clamp(selection.head),
317 );
318 if selection != self.selection {
319 self.typing = None;
320 self.history.interrupt();
321 }
322 self.selection = selection;
323 }
324
325 fn motion(&self, motion: Motion, extending: bool) -> Position {
326 let head = self.selection.head;
327 let collapsed = self.selection.is_collapsed();
328 match motion {
329 Motion::Left if !extending && !collapsed => self.selection.start(),
330 Motion::Right if !extending && !collapsed => self.selection.end(),
331 Motion::Left => self.document.previous(head),
332 Motion::Right => self.document.next(head),
333 Motion::WordLeft => self.document.word_left(head),
334 Motion::WordRight => self.document.word_right(head),
335 Motion::BlockStart => Position::new(head.block, 0),
336 Motion::BlockEnd => Position::new(
337 head.block,
338 self.document
339 .block(head.block)
340 .map_or(0, |block| block.len()),
341 ),
342 Motion::DocumentStart => self.document.start(),
343 Motion::DocumentEnd => self.document.end(),
344 Motion::To(at) => self.document.clamp(at),
345 }
346 }
347
348 fn change(&mut self, edit: editing::Edit, change: impl FnOnce(&mut Self) -> Option<Selection>) {
351 let replacing = !self.selection.is_collapsed();
352 let snapshot = &self.snapshot;
353 self.history.record(edit, replacing, || snapshot.clone());
354 if let Some(selection) = change(self) {
355 self.snapshot = snapshot::encode(&self.document);
356 self.revision += 1;
357 self.selection = Selection::new(
358 self.document.clamp(selection.anchor),
359 self.document.clamp(selection.head),
360 );
361 }
362 let snapshot = &self.snapshot;
363 self.history.settle(|| snapshot.clone());
364 }
365
366 fn restore(&mut self, restore: Option<editing::Restore>) {
367 let Some(restore) = restore else {
368 return;
369 };
370 let Some((document, caret)) = snapshot::decode(&restore.text, restore.caret) else {
371 return;
372 };
373 self.document = document;
374 self.snapshot = restore.text;
375 self.revision += 1;
376 self.typing = None;
377 self.selection = Selection::caret(caret);
378 let snapshot = &self.snapshot;
379 self.history.settle(|| snapshot.clone());
380 }
381
382 fn edit(&mut self, edit: Edit) {
383 let collapsed = self.selection.is_collapsed();
384 let kind = match &edit {
385 Edit::Insert(text) => editing::Edit::Insert(text.clone()),
386 Edit::Enter => editing::Edit::Insert("\n".into()),
387 Edit::Backspace | Edit::Delete if collapsed => editing::Edit::Delete,
388 _ => editing::Edit::Other,
389 };
390 let typing = self.typing.take();
391 self.change(kind, |content| content.apply(edit, typing))
392 }
393
394 fn apply(&mut self, edit: Edit, typing: Option<Style>) -> Option<Selection> {
395 let (start, end) = (self.selection.start(), self.selection.end());
396 let document = &mut self.document;
397 let caret = match edit {
398 Edit::Insert(text) | Edit::Paste(text) => {
399 let text = text.replace("\r\n", "\n").replace('\r', "\n");
400 if text.is_empty() {
401 return None;
402 }
403 let style = match typing {
404 Some(style) => style,
405 None if start != end => document
406 .block(start.block)
407 .and_then(|block| block.style_after(start.offset))
408 .cloned()
409 .unwrap_or_default(),
410 None => document.style_for_insert(start),
411 };
412 let at = document.delete(start, end);
413 document.insert_text(at, &text, &style)
414 }
415 Edit::PasteFormatted(fragment) => {
416 let at = document.delete(start, end);
417 document.insert(at, &fragment)
418 }
419 Edit::Enter => {
420 let at = document.delete(start, end);
421 let block = document.block(at.block)?;
422 if block.is_empty() && block.kind() != BlockKind::Paragraph {
423 document.set_kind(at.block, at.block, BlockKind::Paragraph);
424 at
425 } else {
426 document.split(at)
427 }
428 }
429 Edit::Backspace | Edit::Delete | Edit::DeleteWordBackward | Edit::DeleteWordForward
430 if start != end =>
431 {
432 document.delete(start, end)
433 }
434 Edit::Backspace => {
435 let kind = document.block(start.block)?.kind();
436 if start.offset == 0 && kind != BlockKind::Paragraph {
437 document.set_kind(start.block, start.block, BlockKind::Paragraph);
438 start
439 } else {
440 let from = document.previous(start);
441 if from == start {
442 return None;
443 }
444 document.delete(from, start)
445 }
446 }
447 Edit::Delete => {
448 let to = document.next(start);
449 if to == start {
450 return None;
451 }
452 document.delete(start, to)
453 }
454 Edit::DeleteWordBackward => {
455 let from = document.word_left(start);
456 if from == start {
457 return None;
458 }
459 document.delete(from, start)
460 }
461 Edit::DeleteWordForward => {
462 let to = document.word_right(start);
463 if to == start {
464 return None;
465 }
466 document.delete(start, to)
467 }
468 };
469 Some(Selection::caret(caret))
470 }
471
472 fn format(&mut self, format: Format) {
473 let (start, end) = (self.selection.start(), self.selection.end());
474 let collapsed = start == end;
475 match format {
476 Format::Toggle(mark) if collapsed => {
477 let mut style = self.typing_style();
478 style.set(mark, !style.has(mark));
479 self.typing = Some(style);
480 }
481 Format::Size(size) if collapsed => {
482 let mut style = self.typing_style();
483 style.size = size;
484 self.typing = Some(style);
485 }
486 Format::Clear if collapsed => {
487 let link = self.typing_style().link;
488 self.typing = Some(Style {
489 link,
490 ..Style::default()
491 });
492 }
493 Format::Toggle(mark) => {
494 let on = !self.document.all_have(start, end, |style| style.has(mark));
495 self.restyle(start, end, move |style| style.set(mark, on));
496 }
497 Format::Size(size) => self.restyle(start, end, move |style| style.size = size),
498 Format::Clear => self.restyle(start, end, |style| *style = Style::default()),
499 Format::Block(kind) => {
500 let all = self.block_kind(start.block, end.block) == Some(kind);
501 let kind = if all { BlockKind::Paragraph } else { kind };
502 let selection = self.selection;
503 self.change(editing::Edit::Other, |content| {
504 content.document.set_kind(start.block, end.block, kind);
505 Some(selection)
506 });
507 }
508 Format::Link(address) => self.link(&address),
509 Format::Unlink => {
510 let range = if collapsed {
511 self.document.link_at(start).map(|(from, to, _)| (from, to))
512 } else {
513 Some((start, end))
514 };
515 if let Some((from, to)) = range {
516 self.restyle(from, to, |style| style.link = None);
517 }
518 }
519 }
520 }
521
522 fn restyle(&mut self, start: Position, end: Position, change: impl Fn(&mut Style)) {
523 let selection = self.selection;
524 self.change(editing::Edit::Other, |content| {
525 let before = content.document.clone();
526 content.document.restyle(start, end, change);
527 (content.document != before).then_some(selection)
528 });
529 }
530
531 fn link(&mut self, address: &str) {
532 let Some(url) = normalise_link(address) else {
533 return;
534 };
535 let (start, end) = (self.selection.start(), self.selection.end());
536 let range = if start != end {
537 Some((start, end))
538 } else {
539 self.document
540 .link_at(start)
541 .map(|(from, to, _)| (from, to))
542 .or_else(|| self.document.word_touching(start))
543 };
544 let link: Arc<str> = url.as_str().into();
545 let Some((from, to)) = range else {
546 let shown = url.strip_prefix("mailto:").unwrap_or(&url).to_owned();
547 let style = self.typing_style();
548 let after_word = start.offset > 0
549 && self
550 .document
551 .block(start.block)
552 .and_then(|block| block.text().get(..start.offset)?.chars().next_back())
553 .is_some_and(|c| !c.is_whitespace());
554 self.change(editing::Edit::Other, |content| {
555 let mut at = start;
556 if after_word {
557 let mut space = style.clone();
558 space.link = None;
559 at = content.document.insert_text(at, " ", &space);
560 }
561 let end = content
562 .document
563 .insert_text(at, &shown, &style.linked(link));
564 Some(Selection::caret(end))
565 });
566 return;
567 };
568 let selection = self.selection;
569 self.change(editing::Edit::Other, |content| {
570 content
571 .document
572 .restyle(from, to, |style| style.link = Some(link.clone()));
573 Some(selection)
574 });
575 }
576}
577
578#[cfg(test)]
579mod tests {
580 use super::*;
581 use crate::forms::rich_text_editor::document::{Block, Run};
582
583 fn at(block: usize, offset: usize) -> Position {
584 Position::new(block, offset)
585 }
586
587 fn typed(content: &mut Content, text: &str) {
588 for c in text.chars() {
589 let edit = if c == '\n' {
590 Edit::Enter
591 } else {
592 Edit::Insert(c.to_string())
593 };
594 content.perform(Action::Edit(edit));
595 }
596 }
597
598 fn select(content: &mut Content, from: Position, to: Position) {
599 content.perform(Action::Move(Motion::To(from)));
600 content.perform(Action::Select(Motion::To(to)));
601 }
602
603 fn runs(content: &Content, block: usize) -> Vec<(String, bool)> {
604 content.document().blocks()[block]
605 .runs()
606 .iter()
607 .map(|run| (run.text.clone(), run.style.bold))
608 .collect()
609 }
610
611 #[test]
612 fn typing_and_moving() {
613 let mut content = Content::new();
614 typed(&mut content, "hello\nworld");
615 assert_eq!(content.text(), "hello\nworld");
616 assert_eq!(content.selection(), Selection::caret(at(1, 5)));
617 content.perform(Action::Move(Motion::WordLeft));
618 content.perform(Action::Move(Motion::Left));
619 assert_eq!(content.selection().head, at(0, 5));
620 content.perform(Action::Select(Motion::BlockStart));
621 assert_eq!(content.selected_text(), "hello");
622 content.perform(Action::Move(Motion::Right));
623 assert_eq!(content.selection(), Selection::caret(at(0, 5)));
624 }
625
626 #[test]
627 fn bold_applies_to_part_of_a_word_and_toggles_off() {
628 let mut content = Content::with_text("hello");
629 select(&mut content, at(0, 1), at(0, 3));
630 content.perform(Action::Format(Format::Toggle(Mark::Bold)));
631 assert_eq!(
632 runs(&content, 0),
633 [
634 ("h".into(), false),
635 ("el".into(), true),
636 ("lo".into(), false)
637 ]
638 );
639 assert!(content.formatting().bold);
640 content.perform(Action::Format(Format::Toggle(Mark::Bold)));
641 assert_eq!(runs(&content, 0), [("hello".into(), false)]);
642 }
643
644 #[test]
645 fn a_mixed_selection_turns_the_mark_on() {
646 let mut content = Content::with_text("abcd");
647 select(&mut content, at(0, 0), at(0, 2));
648 content.perform(Action::Format(Format::Toggle(Mark::Bold)));
649 select(&mut content, at(0, 0), at(0, 4));
650 assert!(!content.formatting().bold);
651 content.perform(Action::Format(Format::Toggle(Mark::Bold)));
652 assert_eq!(runs(&content, 0), [("abcd".into(), true)]);
653 }
654
655 #[test]
656 fn a_mark_at_the_caret_applies_to_what_is_typed_next() {
657 let mut content = Content::with_text("a");
658 content.perform(Action::Format(Format::Toggle(Mark::Bold)));
659 assert!(content.formatting().bold);
660 assert_eq!(content.revision(), 0);
661 typed(&mut content, "bc");
662 content.perform(Action::Format(Format::Toggle(Mark::Bold)));
663 typed(&mut content, "d");
664 assert_eq!(
665 runs(&content, 0),
666 [
667 ("a".into(), false),
668 ("bc".into(), true),
669 ("d".into(), false)
670 ]
671 );
672 content.perform(Action::Format(Format::Size(Size::Huge)));
673 content.perform(Action::Move(Motion::Left));
674 assert_eq!(content.formatting().size, Some(Size::Normal));
675 }
676
677 #[test]
678 fn enter_continues_a_list_and_leaves_it_on_an_empty_item() {
679 let mut content = Content::new();
680 typed(&mut content, "one");
681 content.perform(Action::Format(Format::Block(BlockKind::Bullet)));
682 assert_eq!(content.formatting().block, Some(BlockKind::Bullet));
683 typed(&mut content, "\ntwo\n");
684 let kinds: Vec<_> = content
685 .document()
686 .blocks()
687 .iter()
688 .map(Block::kind)
689 .collect();
690 assert_eq!(kinds, [BlockKind::Bullet; 3]);
691 typed(&mut content, "\n");
692 assert_eq!(content.document().blocks()[2].kind(), BlockKind::Paragraph);
693 assert_eq!(content.document().blocks().len(), 3);
694 }
695
696 #[test]
697 fn backspace_at_the_start_of_an_item_ends_the_list_first() {
698 let mut content = Content::with_text("a\nb");
699 content.perform(Action::SelectAll);
700 content.perform(Action::Format(Format::Block(BlockKind::Numbered)));
701 content.perform(Action::Move(Motion::To(at(1, 0))));
702 content.perform(Action::Edit(Edit::Backspace));
703 assert_eq!(content.document().blocks()[1].kind(), BlockKind::Paragraph);
704 content.perform(Action::Edit(Edit::Backspace));
705 assert_eq!(content.text(), "ab");
706 assert_eq!(content.selection().head, at(0, 1));
707 }
708
709 #[test]
710 fn the_list_toggles_off_when_every_block_has_it() {
711 let mut content = Content::with_text("a\nb");
712 content.perform(Action::SelectAll);
713 content.perform(Action::Format(Format::Block(BlockKind::Bullet)));
714 assert_eq!(content.formatting().block, Some(BlockKind::Bullet));
715 content.perform(Action::Format(Format::Block(BlockKind::Bullet)));
716 assert_eq!(content.formatting().block, Some(BlockKind::Paragraph));
717 }
718
719 #[test]
720 fn undo_restores_text_and_formatting_and_redo_returns() {
721 let mut content = Content::new();
722 typed(&mut content, "one two");
723 content.perform(Action::SelectAll);
724 content.perform(Action::Format(Format::Toggle(Mark::Italic)));
725 assert!(content.formatting().italic);
726 content.perform(Action::Undo);
727 assert!(!content.document().has_formatting());
728 assert_eq!(content.text(), "one two");
729 content.perform(Action::Undo);
730 assert_eq!(content.text(), "one ");
731 assert_eq!(content.selection(), Selection::caret(at(0, 4)));
732 content.perform(Action::Redo);
733 content.perform(Action::Redo);
734 assert_eq!(content.text(), "one two");
735 assert!(content.document().has_formatting());
736 content.perform(Action::Undo);
737 content.perform(Action::Undo);
738 content.perform(Action::Undo);
739 assert!(content.is_empty());
740 }
741
742 #[test]
743 fn deleting_words_and_selections() {
744 let mut content = Content::with_text("one two three");
745 content.perform(Action::Edit(Edit::DeleteWordBackward));
746 assert_eq!(content.text(), "one two ");
747 content.perform(Action::Move(Motion::DocumentStart));
748 content.perform(Action::Edit(Edit::DeleteWordForward));
749 assert_eq!(content.text(), " two ");
750 content.perform(Action::SelectAll);
751 content.perform(Action::Edit(Edit::Delete));
752 assert!(content.is_empty());
753 content.perform(Action::Edit(Edit::Backspace));
754 assert!(content.is_empty());
755 content.perform(Action::Undo);
756 assert_eq!(content.text(), " two ");
757 }
758
759 #[test]
760 fn typing_over_a_selection_takes_its_style() {
761 let mut content = Content::with_document(Document::from_blocks([Block::with_runs(
762 BlockKind::Paragraph,
763 [
764 Run::plain("a "),
765 Run::new("bold", Style::default().with(Mark::Bold)),
766 ],
767 )]));
768 select(&mut content, at(0, 2), at(0, 6));
769 typed(&mut content, "x");
770 assert_eq!(
771 runs(&content, 0),
772 [("a ".into(), false), ("x".into(), true)]
773 );
774 }
775
776 #[test]
777 fn pasting_plain_and_formatted_text() {
778 let mut content = Content::with_text("ab");
779 content.perform(Action::Move(Motion::To(at(0, 1))));
780 content.perform(Action::Edit(Edit::Paste("1\r\n2".into())));
781 assert_eq!(content.text(), "a1\n2b");
782 assert_eq!(content.selection().head, at(1, 1));
783 let fragment = Document::from_blocks([Block::with_runs(
784 BlockKind::Paragraph,
785 [Run::new("B", Style::default().with(Mark::Bold))],
786 )]);
787 content.perform(Action::Edit(Edit::PasteFormatted(fragment)));
788 assert_eq!(
789 runs(&content, 1),
790 [("2".into(), false), ("B".into(), true), ("b".into(), false)]
791 );
792 content.perform(Action::Undo);
793 assert_eq!(content.text(), "a1\n2b");
794 }
795
796 #[test]
797 fn links_apply_to_the_selection_the_word_or_new_text() {
798 let mut content = Content::with_text("see here");
799 content.perform(Action::Move(Motion::To(at(0, 6))));
800 content.perform(Action::Format(Format::Link("example.com".into())));
801 assert_eq!(
802 content.formatting().link.as_deref(),
803 Some("https://example.com")
804 );
805 let (from, to, _) = content.document().link_at(at(0, 6)).unwrap();
806 assert_eq!((from, to), (at(0, 4), at(0, 8)));
807 content.perform(Action::Format(Format::Link("https://other.org".into())));
808 assert_eq!(
809 content.formatting().link.as_deref(),
810 Some("https://other.org")
811 );
812 content.perform(Action::Format(Format::Unlink));
813 assert_eq!(content.formatting().link, None);
814
815 content.perform(Action::Move(Motion::DocumentEnd));
816 typed(&mut content, " ");
817 content.perform(Action::Format(Format::Link("sam@example.com".into())));
818 assert_eq!(content.text(), "see here sam@example.com");
819 typed(&mut content, "!");
820 assert_eq!(
821 content
822 .document()
823 .link_at(at(0, 24))
824 .map(|(_, _, url)| url.to_string()),
825 Some("mailto:sam@example.com".into())
826 );
827 assert_eq!(content.document().style_for_insert(at(0, 25)).link, None);
828
829 content.perform(Action::Format(Format::Link("javascript:alert(1)".into())));
830 assert_eq!(content.text(), "see here sam@example.com!");
831 }
832
833 #[test]
834 fn a_new_link_after_a_word_gets_a_space() {
835 let mut content = Content::with_text("Notes.");
836 content.perform(Action::Format(Format::Link("e.com".into())));
837 assert_eq!(content.text(), "Notes. https://e.com");
838 assert_eq!(content.document().style_for_insert(at(0, 7)).link, None);
839 assert!(content.document().link_at(at(0, 10)).is_some());
840 assert!(content.document().link_at(at(0, 6)).is_none());
841 }
842
843 #[test]
844 fn clear_removes_everything_inline() {
845 let mut content = Content::with_text("text");
846 content.perform(Action::SelectAll);
847 for mark in Mark::ALL {
848 content.perform(Action::Format(Format::Toggle(mark)));
849 }
850 content.perform(Action::Format(Format::Size(Size::Large)));
851 content.perform(Action::Format(Format::Link("e.com".into())));
852 assert!(content.has_formatting());
853 content.perform(Action::Format(Format::Clear));
854 assert!(!content.has_formatting());
855 }
856
857 #[test]
858 fn link_requests_are_counted_without_changing_anything() {
859 let mut content = Content::with_text("x");
860 content.perform(Action::RequestLink);
861 content.perform(Action::RequestLink);
862 assert_eq!(content.link_requests(), 2);
863 assert_eq!(content.revision(), 0);
864 assert!(!Action::RequestLink.is_edit());
865 assert!(Action::Undo.is_edit());
866 }
867
868 #[test]
869 fn selection_actions() {
870 let mut content = Content::with_text("one two\nthree");
871 content.perform(Action::SelectWord(at(0, 5)));
872 assert_eq!(content.selected_text(), "two");
873 content.perform(Action::SelectBlock(at(1, 2)));
874 assert_eq!(content.selected_text(), "three");
875 content.perform(Action::SelectAll);
876 assert_eq!(content.selected_text(), "one two\nthree");
877 content.perform(Action::Move(Motion::Left));
878 assert_eq!(content.selection(), Selection::caret(at(0, 0)));
879 }
880
881 #[test]
882 fn html_and_plain_text_come_from_the_document() {
883 let mut content = Content::with_html("<div>Hi <b>there</b></div><ul><li>item</li></ul>");
884 assert_eq!(content.plain_text(), "Hi *there*\n- item");
885 assert!(content.html().contains("<strong>there</strong>"));
886 content.perform(Action::SelectAll);
887 content.perform(Action::Format(Format::Clear));
888 assert_eq!(content.plain_text(), "Hi there\n- item");
889 }
890}