1use crate::props::TextAlign;
18use crate::{Color, Font, FontSpec, FontWeight, Ink, TextRun, runs_are_valid};
19
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum DecorationStyle {
30 #[default]
32 Single,
33 Double,
35 Dotted,
37 Wavy,
39}
40
41#[derive(Clone, Copy, Debug, Default, PartialEq)]
50pub struct Decoration {
51 pub style: DecorationStyle,
53 pub color: Option<Ink>,
55}
56
57impl Decoration {
58 pub const SINGLE: Decoration = Decoration::new(DecorationStyle::Single);
60
61 #[must_use]
63 pub const fn new(style: DecorationStyle) -> Self {
64 Decoration { style, color: None }
65 }
66 #[must_use]
68 pub const fn double() -> Self {
69 Decoration::new(DecorationStyle::Double)
70 }
71 #[must_use]
73 pub const fn dotted() -> Self {
74 Decoration::new(DecorationStyle::Dotted)
75 }
76 #[must_use]
78 pub const fn wavy() -> Self {
79 Decoration::new(DecorationStyle::Wavy)
80 }
81 #[must_use]
83 pub fn color(mut self, color: impl Into<Ink>) -> Self {
84 self.color = Some(color.into());
85 self
86 }
87}
88
89impl From<DecorationStyle> for Decoration {
90 fn from(style: DecorationStyle) -> Self {
91 Decoration::new(style)
92 }
93}
94
95#[derive(Clone, Debug, Default, PartialEq)]
98pub struct RunStyle {
99 pub font: FontSpec,
100 pub color: Option<Color>,
101 pub background: Option<Color>,
102 pub underline: Option<Decoration>,
104 pub strikethrough: Option<Decoration>,
106 pub link: Option<String>,
107}
108
109impl RunStyle {
110 #[must_use]
112 pub fn plain(base: Font) -> Self {
113 RunStyle {
114 font: FontSpec::new(base),
115 ..RunStyle::default()
116 }
117 }
118 #[must_use]
120 pub fn bold(&self) -> bool {
121 self.font.weight.is_some_and(|w| w >= FontWeight::Semibold)
122 }
123 pub fn set_bold(&mut self, on: bool) {
124 self.font.weight = on.then_some(FontWeight::Bold);
125 }
126 #[must_use]
127 pub fn italic(&self) -> bool {
128 self.font.italic
129 }
130 pub fn set_italic(&mut self, on: bool) {
131 self.font.italic = on;
132 }
133 pub fn set_underline(&mut self, on: bool) {
135 self.underline = on.then_some(Decoration::SINGLE);
136 }
137 pub fn set_strikethrough(&mut self, on: bool) {
139 self.strikethrough = on.then_some(Decoration::SINGLE);
140 }
141}
142
143#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
149pub enum ListStyle {
150 #[default]
151 None,
152 Bullet,
154 Ordered(u32),
157}
158
159#[derive(Clone, Copy, Debug, Default, PartialEq)]
161pub struct ParagraphStyle {
162 pub align: TextAlign,
163 pub indent: f64,
166 pub space_before: f64,
167 pub space_after: f64,
168 pub list: ListStyle,
169 pub list_level: u8,
171}
172
173#[derive(Clone, Debug, Default, PartialEq)]
183pub struct ParagraphRun {
184 pub range: std::ops::Range<usize>,
185 pub align: TextAlign,
186 pub indent: f64,
187 pub space_before: f64,
188 pub space_after: f64,
189 pub list: ListStyle,
190 pub list_level: u8,
191}
192
193impl ParagraphRun {
194 #[must_use]
195 pub fn new(range: std::ops::Range<usize>, style: ParagraphStyle) -> Self {
196 ParagraphRun {
197 range,
198 align: style.align,
199 indent: style.indent,
200 space_before: style.space_before,
201 space_after: style.space_after,
202 list: style.list,
203 list_level: style.list_level,
204 }
205 }
206 #[must_use]
207 pub fn style(&self) -> ParagraphStyle {
208 ParagraphStyle {
209 align: self.align,
210 indent: self.indent,
211 space_before: self.space_before,
212 space_after: self.space_after,
213 list: self.list,
214 list_level: self.list_level,
215 }
216 }
217}
218
219#[derive(Clone, Debug, Default, PartialEq)]
226pub struct StyledText {
227 pub text: String,
228 pub runs: Vec<TextRun>,
229 pub paragraphs: Vec<ParagraphRun>,
230}
231
232impl From<String> for StyledText {
233 fn from(text: String) -> Self {
234 StyledText::plain(text)
235 }
236}
237
238impl From<&str> for StyledText {
239 fn from(text: &str) -> Self {
240 StyledText::plain(text)
241 }
242}
243
244impl StyledText {
245 pub fn plain(text: impl Into<String>) -> Self {
247 StyledText {
248 text: text.into(),
249 runs: Vec::new(),
250 paragraphs: Vec::new(),
251 }
252 }
253
254 #[must_use]
257 pub fn markdown(md: &str, base: Font) -> Self {
258 crate::styled_codec::markdown_to_styled(
259 md,
260 crate::styled_codec::DocStyle {
261 base,
262 ..Default::default()
263 },
264 )
265 }
266
267 #[must_use]
269 pub fn html(html: &str, base: Font) -> Self {
270 crate::styled_codec::html_to_styled(
271 html,
272 crate::styled_codec::DocStyle {
273 base,
274 ..Default::default()
275 },
276 )
277 }
278
279 #[must_use]
281 pub fn rtf(rtf: &str, base: Font) -> Self {
282 crate::styled_codec::rtf_to_styled(
283 rtf,
284 crate::styled_codec::DocStyle {
285 base,
286 ..Default::default()
287 },
288 )
289 }
290
291 #[must_use]
294 pub fn to_markdown(&self, base: Font) -> String {
295 crate::styled_codec::styled_to_markdown(
296 self,
297 crate::styled_codec::DocStyle {
298 base,
299 ..Default::default()
300 },
301 )
302 }
303
304 #[must_use]
305 pub fn to_html(&self, base: Font) -> String {
306 crate::styled_codec::styled_to_html(
307 self,
308 crate::styled_codec::DocStyle {
309 base,
310 ..Default::default()
311 },
312 )
313 }
314
315 #[must_use]
316 pub fn to_rtf(&self, base: Font) -> String {
317 crate::styled_codec::styled_to_rtf(
318 self,
319 crate::styled_codec::DocStyle {
320 base,
321 ..Default::default()
322 },
323 )
324 }
325
326 pub fn new(text: impl Into<String>, runs: Vec<TextRun>) -> Self {
328 StyledText {
329 text: text.into(),
330 runs,
331 paragraphs: Vec::new(),
332 }
333 }
334
335 #[must_use]
336 pub fn is_empty(&self) -> bool {
337 self.text.is_empty()
338 }
339
340 pub fn validate(&self) -> Result<(), String> {
347 runs_are_valid(&self.text, &self.runs)?;
348 paragraphs_are_valid(&self.text, &self.paragraphs)
349 }
350
351 #[must_use]
356 pub fn segments(&self, base: Font) -> Vec<(std::ops::Range<usize>, RunStyle)> {
357 let plain = RunStyle::plain(base);
358 let mut out = Vec::with_capacity(self.runs.len() * 2 + 1);
359 let mut at = 0usize;
360 for r in &self.runs {
361 if r.range.start > at {
362 out.push((at..r.range.start, plain.clone()));
363 }
364 if !r.range.is_empty() {
365 out.push((r.range.clone(), r.style()));
366 }
367 at = at.max(r.range.end);
368 }
369 if at < self.text.len() {
370 out.push((at..self.text.len(), plain));
371 }
372 out
373 }
374
375 #[must_use]
385 pub fn style_of(&self, range: std::ops::Range<usize>, base: Font) -> RunStyle {
386 let segs = self.segments(base);
387 if range.is_empty() {
388 let at = range.start;
389 return segs
390 .iter()
391 .find(|(r, _)| r.start < at && r.end >= at)
392 .or_else(|| segs.iter().find(|(r, _)| r.contains(&at)))
393 .map_or_else(|| RunStyle::plain(base), |(_, s)| s.clone());
394 }
395 let mut acc: Option<RunStyle> = None;
396 for (r, s) in &segs {
397 if r.end <= range.start || r.start >= range.end {
398 continue;
399 }
400 acc = Some(merge_style(acc, s));
401 }
402 acc.unwrap_or_else(|| RunStyle::plain(base))
403 }
404
405 pub fn apply(&mut self, range: std::ops::Range<usize>, base: Font, f: impl Fn(&mut RunStyle)) {
408 if range.start >= range.end || range.start >= self.text.len() {
409 return;
410 }
411 let range = range.start..range.end.min(self.text.len());
412 let mut out: Vec<TextRun> = Vec::new();
413 for (r, s) in self.segments(base) {
414 for (piece, inside) in [
416 (r.start..r.end.min(range.start), false),
417 (r.start.max(range.start)..r.end.min(range.end), true),
418 (r.start.max(range.end)..r.end, false),
419 ] {
420 if piece.start >= piece.end {
421 continue;
422 }
423 let mut style = s.clone();
424 if inside {
425 f(&mut style);
426 }
427 out.push(TextRun::styled(piece, style));
428 }
429 }
430 self.runs = coalesce_runs(out, base);
431 }
432
433 #[must_use]
436 pub fn paragraph_style_of(&self, range: std::ops::Range<usize>) -> ParagraphStyle {
437 let mut acc: Option<ParagraphStyle> = None;
438 for (start, end) in paragraph_bounds(&self.text) {
439 if !touches(start, end, &range) {
440 continue;
441 }
442 let style = self.paragraph_at(start, end);
443 acc = Some(match acc {
444 None => style,
445 Some(a) if a == style => a,
446 Some(_) => ParagraphStyle::default(),
447 });
448 }
449 acc.unwrap_or_default()
450 }
451
452 pub fn apply_paragraph(
455 &mut self,
456 range: std::ops::Range<usize>,
457 f: impl Fn(&mut ParagraphStyle),
458 ) {
459 let mut out: Vec<ParagraphRun> = Vec::new();
460 for (start, end) in paragraph_bounds(&self.text) {
461 let mut style = self.paragraph_at(start, end);
462 if touches(start, end, &range) {
463 f(&mut style);
464 }
465 if style != ParagraphStyle::default() {
466 out.push(ParagraphRun::new(start..end, style));
467 }
468 }
469 self.paragraphs = out;
470 }
471
472 fn paragraph_at(&self, start: usize, end: usize) -> ParagraphStyle {
474 self.paragraphs
475 .iter()
476 .find(|p| p.range.start <= start && p.range.end >= end.min(p.range.end).max(start + 1))
477 .map_or_default(ParagraphRun::style)
478 }
479
480 pub fn reflow(&mut self, offset: usize, removed: usize, inserted: usize) {
490 let shift = |p: usize| -> usize {
491 if p <= offset {
492 p
493 } else if p >= offset + removed {
494 p - removed + inserted
495 } else {
496 offset }
498 };
499 for r in &mut self.runs {
500 r.range = shift(r.range.start)..shift(r.range.end);
501 }
502 for p in &mut self.paragraphs {
503 p.range = shift(p.range.start)..shift(p.range.end);
504 }
505 if inserted > 0 {
508 for r in &mut self.runs {
509 if r.range.end == offset && r.range.start < offset {
510 r.range.end = offset + inserted;
511 }
512 }
513 for p in &mut self.paragraphs {
514 if p.range.end == offset && p.range.start < offset {
515 p.range.end = offset + inserted;
516 }
517 }
518 }
519 self.clamp();
520 }
521
522 pub fn clamp(&mut self) {
525 let text = std::mem::take(&mut self.text);
526 let fix = |p: usize| -> usize {
527 let mut p = p.min(text.len());
528 while p > 0 && !text.is_char_boundary(p) {
529 p -= 1;
530 }
531 p
532 };
533 for r in &mut self.runs {
534 r.range = fix(r.range.start)..fix(r.range.end);
535 }
536 for p in &mut self.paragraphs {
537 p.range = fix(p.range.start)..fix(p.range.end);
538 }
539 self.text = text;
540 self.runs.retain(|r| r.range.start < r.range.end);
541 self.paragraphs.retain(|p| p.range.start < p.range.end);
542 }
543
544 pub fn splice(&mut self, range: std::ops::Range<usize>, text: &str) {
547 let range = range.start.min(self.text.len())..range.end.min(self.text.len());
548 if !self.text.is_char_boundary(range.start) || !self.text.is_char_boundary(range.end) {
549 return;
550 }
551 let removed = range.end.saturating_sub(range.start);
552 self.text.replace_range(range.clone(), text);
553 self.reflow(range.start, removed, text.len());
554 }
555}
556
557#[expect(
560 clippy::float_cmp,
561 reason = "a merged run keeps a scale only when both runs store the identical value"
562)]
563fn merge_style(acc: Option<RunStyle>, b: &RunStyle) -> RunStyle {
564 let Some(a) = acc else { return b.clone() };
565 RunStyle {
566 font: FontSpec {
567 style: if a.font.style == b.font.style {
568 a.font.style
569 } else {
570 Font::Body
571 },
572 weight: if a.font.weight == b.font.weight {
573 a.font.weight
574 } else {
575 None
576 },
577 italic: a.font.italic && b.font.italic,
578 tabular: a.font.tabular && b.font.tabular,
579 monospace: a.font.monospace && b.font.monospace,
580 small_caps: a.font.small_caps && b.font.small_caps,
581 oldstyle_figures: a.font.oldstyle_figures && b.font.oldstyle_figures,
582 scale: if a.font.scale == b.font.scale {
583 a.font.scale
584 } else {
585 1.0
586 },
587 },
588 color: if a.color == b.color { a.color } else { None },
589 background: if a.background == b.background {
590 a.background
591 } else {
592 None
593 },
594 underline: if a.underline == b.underline {
595 a.underline
596 } else {
597 None
598 },
599 strikethrough: if a.strikethrough == b.strikethrough {
600 a.strikethrough
601 } else {
602 None
603 },
604 link: if a.link == b.link { a.link } else { None },
605 }
606}
607
608fn touches(start: usize, end: usize, sel: &std::ops::Range<usize>) -> bool {
611 if sel.start == sel.end {
612 return sel.start >= start && sel.start <= end;
613 }
614 start < sel.end && end > sel.start
615}
616
617#[must_use]
622pub fn coalesce_runs(runs: Vec<TextRun>, base: Font) -> Vec<TextRun> {
623 let plain = RunStyle::plain(base);
624 let mut out: Vec<TextRun> = Vec::with_capacity(runs.len());
625 for r in runs {
626 if r.range.is_empty() {
627 continue;
628 }
629 match out.last_mut() {
630 Some(prev) if prev.range.end == r.range.start && prev.style() == r.style() => {
631 prev.range.end = r.range.end;
632 }
633 _ => out.push(r),
634 }
635 }
636 out.retain(|r| r.style() != plain);
637 out
638}
639
640#[must_use]
645pub fn paragraph_bounds(text: &str) -> Vec<(usize, usize)> {
646 if text.is_empty() {
647 return Vec::new();
648 }
649 let mut out = Vec::new();
650 let mut start = 0usize;
651 for (i, b) in text.bytes().enumerate() {
652 if b == b'\n' {
653 out.push((start, i + 1));
654 start = i + 1;
655 }
656 }
657 out.push((start, text.len()));
658 out
659}
660
661pub fn paragraphs_are_valid(text: &str, paragraphs: &[ParagraphRun]) -> Result<(), String> {
669 let mut prev_end = 0usize;
670 for (i, p) in paragraphs.iter().enumerate() {
671 if p.range.start < prev_end {
672 return Err(format!(
673 "paragraph {i} starts at {} but the previous ends at {prev_end} — paragraph runs \
674 must be ascending and non-overlapping",
675 p.range.start
676 ));
677 }
678 if p.range.end > text.len() {
679 return Err(format!(
680 "paragraph {i} ends at {} but the text is {} bytes",
681 p.range.end,
682 text.len()
683 ));
684 }
685 if p.range.start > p.range.end {
686 return Err(format!("paragraph {i} has an inverted range {:?}", p.range));
687 }
688 if !text.is_char_boundary(p.range.start) || !text.is_char_boundary(p.range.end) {
689 return Err(format!(
690 "paragraph {i}'s range {:?} splits a multi-byte character",
691 p.range
692 ));
693 }
694 prev_end = p.range.end;
695 }
696 Ok(())
697}
698
699#[cfg(test)]
700mod tests {
701 use super::*;
702
703 fn bold_run(range: std::ops::Range<usize>) -> TextRun {
704 TextRun::styled(range, {
705 let mut s = RunStyle::plain(Font::Body);
706 s.set_bold(true);
707 s
708 })
709 }
710
711 fn doc() -> StyledText {
712 StyledText::new("hello world", vec![bold_run(0..5)])
714 }
715
716 #[test]
717 fn segments_cover_the_whole_text_including_gaps() {
718 let segs = doc().segments(Font::Body);
719 assert_eq!(
720 segs.iter().map(|(r, _)| r.clone()).collect::<Vec<_>>(),
721 vec![0..5, 5..11]
722 );
723 assert!(segs[0].1.bold());
724 assert!(!segs[1].1.bold());
725 }
726
727 #[test]
728 fn style_of_a_uniform_selection_is_that_style() {
729 assert!(doc().style_of(0..5, Font::Body).bold());
730 assert!(!doc().style_of(5..11, Font::Body).bold());
731 }
732
733 #[test]
734 fn style_of_a_mixed_selection_resets_what_differs() {
735 let s = doc().style_of(0..11, Font::Body);
737 assert!(!s.bold(), "a mixed weight comes back as the default");
738 }
739
740 #[test]
741 fn a_caret_takes_the_style_of_the_run_it_ends() {
742 assert!(doc().style_of(5..5, Font::Body).bold());
744 assert!(!doc().style_of(11..11, Font::Body).bold());
746 assert!(doc().style_of(0..0, Font::Body).bold());
750 }
751
752 #[test]
753 fn apply_splits_runs_at_the_selection_boundaries() {
754 let mut d = doc();
755 d.apply(3..8, Font::Body, |s| s.set_italic(true));
756 let got: Vec<_> = d
758 .runs
759 .iter()
760 .map(|r| (r.range.clone(), r.style().bold(), r.style().italic()))
761 .collect();
762 assert_eq!(
763 got,
764 vec![(0..3, true, false), (3..5, true, true), (5..8, false, true),]
765 );
766 }
767
768 #[test]
769 fn apply_coalesces_and_drops_plain() {
770 let mut d = doc();
771 d.apply(0..11, Font::Body, |s| s.set_bold(false));
772 assert!(
773 d.runs.is_empty(),
774 "unbolding everything leaves nothing to say: {:?}",
775 d.runs
776 );
777 }
778
779 #[test]
780 fn reflow_moves_ranges_over_an_insert() {
781 let mut d = doc();
782 d.text = "hello woXXrld".into();
784 d.reflow(8, 0, 2);
785 assert_eq!(d.runs[0].range, 0..5, "a run before the edit is untouched");
786
787 let mut d = doc();
788 d.text = "heXXllo world".into();
790 d.reflow(2, 0, 2);
791 assert_eq!(d.runs[0].range, 0..7);
792 }
793
794 #[test]
795 fn typing_at_the_end_of_a_run_continues_it() {
796 let mut d = doc();
797 d.text = "helloX world".into();
798 d.reflow(5, 0, 1);
799 assert_eq!(d.runs[0].range, 0..6, "the bold run took the new character");
800 }
801
802 #[test]
803 fn reflow_shrinks_and_drops_over_a_delete() {
804 let mut d = doc();
805 d.text = "hworld".into();
807 d.reflow(1, 5, 0);
808 assert_eq!(d.runs[0].range, 0..1);
809
810 let mut d = doc();
811 d.text = " world".into();
813 d.reflow(0, 5, 0);
814 assert!(d.runs.is_empty(), "{:?}", d.runs);
815 }
816
817 #[test]
818 fn splice_edits_text_and_ranges_together() {
819 let mut d = doc();
820 d.splice(5..5, ",");
821 assert_eq!(d.text, "hello, world");
822 assert_eq!(d.runs[0].range, 0..6);
823 assert!(d.validate().is_ok());
824 }
825
826 #[test]
827 fn clamp_pulls_ranges_off_multi_byte_boundaries() {
828 let mut d = StyledText::new("héllo", vec![bold_run(0..2)]);
829 d.text = "h".into(); d.clamp();
831 assert!(d.validate().is_ok());
832 assert!(d.runs.iter().all(|r| r.range.end <= 1));
833 }
834
835 #[test]
836 fn paragraph_bounds_include_the_terminator_and_the_blank_last_line() {
837 assert_eq!(paragraph_bounds(""), Vec::new());
838 assert_eq!(paragraph_bounds("a"), vec![(0, 1)]);
839 assert_eq!(paragraph_bounds("a\n"), vec![(0, 2), (2, 2)]);
840 assert_eq!(paragraph_bounds("a\nbb\nc"), vec![(0, 2), (2, 5), (5, 6)]);
841 }
842
843 #[test]
844 fn apply_paragraph_styles_the_whole_paragraph_a_caret_sits_in() {
845 let mut d = StyledText::plain("one\ntwo\nthree");
846 d.apply_paragraph(5..5, |p| p.align = TextAlign::Center);
847 assert_eq!(d.paragraphs.len(), 1);
848 assert_eq!(d.paragraphs[0].range, 4..8, "the whole second paragraph");
849 assert_eq!(d.paragraphs[0].align, TextAlign::Center);
850 assert_eq!(d.paragraph_style_of(5..5).align, TextAlign::Center);
851 assert_eq!(
852 d.paragraph_style_of(0..13).align,
853 TextAlign::Leading,
854 "a mixed selection reports the default"
855 );
856 assert!(d.validate().is_ok());
857 }
858
859 #[test]
860 fn paragraph_ranges_reflow_with_the_text() {
861 let mut d = StyledText::plain("one\ntwo");
862 d.apply_paragraph(5..5, |p| p.list = ListStyle::Bullet);
863 assert_eq!(d.paragraphs[0].range, 4..7);
864 d.splice(0..0, "XY");
865 assert_eq!(d.paragraphs[0].range, 6..9);
866 assert!(d.validate().is_ok());
867 }
868
869 #[test]
870 fn font_scale_resolves_against_the_platforms_style_size() {
871 let s = FontSpec::new(Font::Body).scaled(1.5);
872 assert_eq!(s.resolved_points(16.0), 24.0);
873 let abs = FontSpec::new(Font::System(14.0));
875 assert_eq!(abs.resolved_points(16.0), 14.0);
876 assert_eq!(abs.scaled(2.0).resolved_points(16.0), 28.0);
877 }
878}