Skip to main content

day_spec/
styled.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Styled text: the document `label().runs(…)` renders and `day-piece-text-editor` edits
5//! (docs/texteditor.md).
6//!
7//! [`StyledText`] is plain text plus two range vectors over it: [`TextRun`]s for character
8//! attributes and [`ParagraphRun`]s for paragraph ones. Text and ranges travel together by
9//! construction, because a range only means something against a particular string.
10//!
11//! Everything an editor's toolbar needs is a pure function here rather than a round trip into the
12//! toolkit: [`StyledText::style_of`] answers "what is the selection's style" (with a mixed state
13//! where the runs disagree), [`StyledText::apply`] changes it, and [`StyledText::reflow`] moves
14//! the ranges over an edit the native editor already made. That is what lets the same logic run
15//! on nine backends and be tested on the headless one.
16
17use crate::props::TextAlign;
18use crate::{Color, Font, FontSpec, FontWeight, Ink, TextRun, runs_are_valid};
19
20// ---------------------------------------------------------------------------
21// Character attributes
22// ---------------------------------------------------------------------------
23
24/// How a [`Decoration`] line is drawn.
25///
26/// A toolkit with no native form of a style draws `Single`, so the text still reads as
27/// decorated (docs/text-runs.md lists who draws what).
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum DecorationStyle {
30    /// One solid line.
31    #[default]
32    Single,
33    /// Two solid lines.
34    Double,
35    /// A dotted line.
36    Dotted,
37    /// The squiggle an app draws its own diagnostics with (a spelling or grammar mark).
38    Wavy,
39}
40
41/// A line under or through a run: [`TextRun::underline`] and [`TextRun::strikethrough`].
42///
43/// One type for both lines because every text system gives them the same two knobs: how the
44/// line is drawn and what color it takes. `color: None` draws the line in the run's text color.
45///
46/// ```ignore
47/// TextRun { underline: Some(Decoration::wavy().color(Color::RED)), ..TextRun::default() }
48/// ```
49#[derive(Clone, Copy, Debug, Default, PartialEq)]
50pub struct Decoration {
51    /// How the line is drawn.
52    pub style: DecorationStyle,
53    /// The line's color; `None` follows the text color.
54    pub color: Option<Ink>,
55}
56
57impl Decoration {
58    /// One solid line in the text color, what a toolbar's underline button turns on.
59    pub const SINGLE: Decoration = Decoration::new(DecorationStyle::Single);
60
61    /// A line of `style` in the text color.
62    #[must_use]
63    pub const fn new(style: DecorationStyle) -> Self {
64        Decoration { style, color: None }
65    }
66    /// Two solid lines.
67    #[must_use]
68    pub const fn double() -> Self {
69        Decoration::new(DecorationStyle::Double)
70    }
71    /// A dotted line.
72    #[must_use]
73    pub const fn dotted() -> Self {
74        Decoration::new(DecorationStyle::Dotted)
75    }
76    /// A wavy line.
77    #[must_use]
78    pub const fn wavy() -> Self {
79        Decoration::new(DecorationStyle::Wavy)
80    }
81    /// This line in `color` instead of the text color.
82    #[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/// A [`TextRun`]'s attributes with no range attached: what a toolbar toggles, what an editor
96/// applies to a selection, and what it styles the next typed character with.
97#[derive(Clone, Debug, Default, PartialEq)]
98pub struct RunStyle {
99    pub font: FontSpec,
100    pub color: Option<Color>,
101    pub background: Option<Color>,
102    /// A line under the text.
103    pub underline: Option<Decoration>,
104    /// A line through the text.
105    pub strikethrough: Option<Decoration>,
106    pub link: Option<String>,
107}
108
109impl RunStyle {
110    /// The style of unstyled text in a document whose base font is `base`.
111    #[must_use]
112    pub fn plain(base: Font) -> Self {
113        RunStyle {
114            font: FontSpec::new(base),
115            ..RunStyle::default()
116        }
117    }
118    /// Bold in the sense a toolbar button means it: semibold or heavier.
119    #[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    /// The toolbar's underline toggle: one solid line when turning it on, none when off.
134    pub fn set_underline(&mut self, on: bool) {
135        self.underline = on.then_some(Decoration::SINGLE);
136    }
137    /// The toolbar's strikethrough toggle.
138    pub fn set_strikethrough(&mut self, on: bool) {
139        self.strikethrough = on.then_some(Decoration::SINGLE);
140    }
141}
142
143// ---------------------------------------------------------------------------
144// Paragraph attributes
145// ---------------------------------------------------------------------------
146
147/// A paragraph's list decoration, if it is a list item.
148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
149pub enum ListStyle {
150    #[default]
151    None,
152    /// A bullet; the glyph is the platform's.
153    Bullet,
154    /// A number, which the app computes. Nothing here renumbers a list, because nothing here
155    /// knows where the list began or whether the paragraph above belongs to it.
156    Ordered(u32),
157}
158
159/// A [`ParagraphRun`]'s attributes with no range attached.
160#[derive(Clone, Copy, Debug, Default, PartialEq)]
161pub struct ParagraphStyle {
162    pub align: TextAlign,
163    /// Leading indent in points, from the reading direction's start edge. A list item's total
164    /// indent is this plus whatever the platform reserves for its marker.
165    pub indent: f64,
166    pub space_before: f64,
167    pub space_after: f64,
168    pub list: ListStyle,
169    /// Nesting depth for a list item (0 = outermost). Ignored when `list` is `None`.
170    pub list_level: u8,
171}
172
173/// One styled paragraph.
174///
175/// A second range vector alongside [`TextRun`] rather than more fields on one, because these
176/// attributes apply to whole paragraphs: folding alignment into a character run would let a
177/// program say "center these three words", which no text system can honor and every one of them
178/// would resolve differently.
179///
180/// `range` is a byte range into the same string the runs address and covers whole paragraphs. A
181/// gap is a paragraph with the document's own defaults.
182#[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// ---------------------------------------------------------------------------
220// The document
221// ---------------------------------------------------------------------------
222
223/// A styled document: plain text, the character runs over it, and the paragraph attributes over
224/// the same offsets.
225#[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    /// Unstyled text.
246    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    /// Parse markdown, the ergonomic way to seed a document
255    /// ([`styled_codec`](crate::styled_codec)).
256    #[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    /// Parse an HTML fragment.
268    #[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    /// Parse the RTF subset Day reads (docs/texteditor.md).
280    #[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    /// Write this document as markdown / HTML / RTF. Each is lossy in the ways
292    /// [`styled_codec`](crate::styled_codec) documents.
293    #[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    /// Text with character runs and no paragraph attributes, which is what a label carries today.
327    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    /// Are both range vectors well formed for the text (ascending, non-overlapping, in bounds,
341    /// on character boundaries)?
342    ///
343    /// # Errors
344    ///
345    /// Returns a message naming the first run or paragraph run that breaks one of those rules.
346    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    /// The whole text as consecutive `(range, style)` segments, unstyled gaps included as `base`.
352    ///
353    /// One view that the query and the mutation below are both written against, so neither has to
354    /// reason about where a run ends and a gap begins.
355    #[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    /// The style in effect across `range`.
376    ///
377    /// Where the segments under it disagree, the differing attribute comes back as its default
378    /// rather than as one of the values. That is what a toolbar renders as its mixed state, and
379    /// it is what makes pressing the button set the whole selection instead of toggling half of
380    /// it.
381    ///
382    /// A collapsed caret takes the style of the segment that ENDS at it, preferring that over the
383    /// one it starts: typing after a bold word continues bold, which is what every editor does.
384    #[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    /// Apply `f` to the style of every segment overlapping `range`, splitting at its boundaries so
406    /// only the selected text changes, then coalescing what came out.
407    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            // Up to three pieces per segment: before the selection, inside it, after it.
415            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    /// The paragraph style in effect across `range`, by the same mixed-state rule as
434    /// [`StyledText::style_of`].
435    #[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    /// Apply `f` to every paragraph the selection touches. Paragraph boundaries are `\n`, so a
453    /// caret anywhere inside a paragraph styles the whole of it, which is what every editor does.
454    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    /// The style recorded for the paragraph spanning `start..end`, or the default.
473    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    /// Move the ranges over a character edit the native editor already made: `removed` bytes at
481    /// `offset` replaced by `inserted` bytes.
482    ///
483    /// This is why a keystroke does not have to ship the whole document back. Ranges before the
484    /// edit are untouched, ranges after it shift, a range containing it grows or shrinks, and a
485    /// range the edit emptied is dropped. That is the rule every attributed-string implementation
486    /// uses, exact, and O(runs) rather than O(document).
487    ///
488    /// `self.text` must already be the new text; this only moves ranges.
489    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 // inside the deleted span: collapse to the edit point
497            }
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        // A run the edit ended inside grows over the insertion, so typing at the end of a bold
506        // word stays bold. Applied after the shift so the comparison is in new coordinates.
507        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    /// Clamp every range into the text and onto character boundaries, dropping what cannot be
523    /// saved. The last defense before a range reaches a backend and panics an `str` slice.
524    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    /// Replace `range` with `text`, moving every other range over the edit. The app-side twin of
545    /// what a keystroke does, for a programmatic insert or delete.
546    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/// Fold `b` into the accumulated selection style: an attribute both agree on survives, one they
558/// differ on resets to its default (the toolbar's mixed state).
559#[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
608/// Does the paragraph `start..end` fall under `sel`? A collapsed caret counts against the
609/// paragraph it sits in, including at its very end.
610fn 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/// Merge adjacent runs whose styles came out equal, and drop runs that say nothing beyond `base`.
618///
619/// Every `apply` produces fragments; without this a document accumulates one run per edit until
620/// the run vector is longer than the text it describes.
621#[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/// The `\n`-delimited paragraphs of `text`, as byte ranges INCLUDING the terminator.
641///
642/// An empty string has no paragraphs. A trailing newline makes an empty final paragraph, the way
643/// an editor shows a blank last line, so `"a\n"` is two paragraphs, not one.
644#[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
661/// Whether these paragraph runs are well formed for `text`: [`runs_are_valid`]'s rules, applied
662/// to the second range vector.
663///
664/// # Errors
665///
666/// Returns a message naming the first paragraph run that overlaps or precedes the one before
667/// it, ends past the text, has an inverted range, or splits a multi-byte character.
668pub 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        // "hello world" with "hello" bold.
713        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        // Half bold, half not: the toolbar shows "not bold", so pressing it bolds everything.
736        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        // Typing at offset 5, right after "hello", continues bold.
743        assert!(doc().style_of(5..5, Font::Body).bold());
744        // And at 11, after the plain tail, it does not.
745        assert!(!doc().style_of(11..11, Font::Body).bold());
746        // At offset 0 there is nothing behind the caret, so it takes the run ahead instead:
747        // typing at the very start of a document that begins bold gives bold, which is what
748        // TextEdit, Word and every web editor do.
749        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        // bold 0..3, bold+italic 3..5, italic 5..8, plain 8..11 (dropped as plain).
757        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        // Type "XX" at offset 8 (inside " world").
783        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        // Type at 2, inside the bold run: it grows.
789        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        // Delete "ello " (1..6): the bold run shrinks to 0..1.
806        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        // Delete the whole bold word: the run goes away rather than becoming empty.
812        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(); // as if the tail were deleted without a reflow
830        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        // An absolute style carries its own size and ignores the platform's.
874        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}