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::{Color, Font, FontSpec, FontWeight, TextRun, runs_are_valid};
18
19// ---------------------------------------------------------------------------
20// Character attributes
21// ---------------------------------------------------------------------------
22
23/// A line under a run.
24///
25/// An enum rather than a `bool` because every toolkit distinguishes at least single from double,
26/// and because a wavy underline is how an app draws its diagnostics (a spelling or grammar
27/// mark of its own making) without fighting the platform's checker for the same pixels.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum Underline {
30    #[default]
31    None,
32    Single,
33    Double,
34    Dotted,
35    /// The squiggle. A backend with no wavy style draws `Single`.
36    Wavy,
37}
38
39impl Underline {
40    #[must_use]
41    pub fn is_on(self) -> bool {
42        self != Underline::None
43    }
44    /// The toolbar's on/off toggle: `Single` when turning it on, `None` when off.
45    #[must_use]
46    pub fn toggled(self) -> Self {
47        if self.is_on() {
48            Underline::None
49        } else {
50            Underline::Single
51        }
52    }
53}
54
55/// A [`TextRun`]'s attributes with no range attached: what a toolbar toggles, what an editor
56/// applies to a selection, and what it styles the next typed character with.
57#[derive(Clone, Debug, Default, PartialEq)]
58pub struct RunStyle {
59    pub font: FontSpec,
60    pub color: Option<Color>,
61    pub background: Option<Color>,
62    pub underline: Underline,
63    pub strikethrough: bool,
64    pub link: Option<String>,
65}
66
67impl RunStyle {
68    /// The style of unstyled text in a document whose base font is `base`.
69    #[must_use]
70    pub fn plain(base: Font) -> Self {
71        RunStyle {
72            font: FontSpec::new(base),
73            ..RunStyle::default()
74        }
75    }
76    /// Bold in the sense a toolbar button means it: semibold or heavier.
77    #[must_use]
78    pub fn bold(&self) -> bool {
79        self.font.weight.is_some_and(|w| w >= FontWeight::Semibold)
80    }
81    pub fn set_bold(&mut self, on: bool) {
82        self.font.weight = on.then_some(FontWeight::Bold);
83    }
84    #[must_use]
85    pub fn italic(&self) -> bool {
86        self.font.italic
87    }
88    pub fn set_italic(&mut self, on: bool) {
89        self.font.italic = on;
90    }
91}
92
93// ---------------------------------------------------------------------------
94// Paragraph attributes
95// ---------------------------------------------------------------------------
96
97/// How a paragraph's lines sit in the width they are given.
98#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
99pub enum ParagraphAlign {
100    /// The reading direction's start edge: left under LTR, right under RTL.
101    #[default]
102    Natural,
103    Center,
104    /// The reading direction's end edge.
105    Trailing,
106    Justified,
107}
108
109/// A paragraph's list decoration, if it is a list item.
110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
111pub enum ListStyle {
112    #[default]
113    None,
114    /// A bullet; the glyph is the platform's.
115    Bullet,
116    /// A number, which the app computes. Nothing here renumbers a list, because nothing here
117    /// knows where the list began or whether the paragraph above belongs to it.
118    Ordered(u32),
119}
120
121/// A [`ParagraphRun`]'s attributes with no range attached.
122#[derive(Clone, Copy, Debug, Default, PartialEq)]
123pub struct ParagraphStyle {
124    pub align: ParagraphAlign,
125    /// Leading indent in points, from the reading direction's start edge. A list item's total
126    /// indent is this plus whatever the platform reserves for its marker.
127    pub indent: f64,
128    pub space_before: f64,
129    pub space_after: f64,
130    pub list: ListStyle,
131    /// Nesting depth for a list item (0 = outermost). Ignored when `list` is `None`.
132    pub list_level: u8,
133}
134
135/// One styled paragraph.
136///
137/// A second range vector alongside [`TextRun`] rather than more fields on one, because these
138/// attributes apply to whole paragraphs: folding alignment into a character run would let a
139/// program say "center these three words", which no text system can honor and every one of them
140/// would resolve differently.
141///
142/// `range` is a byte range into the same string the runs address and covers whole paragraphs. A
143/// gap is a paragraph with the document's own defaults.
144#[derive(Clone, Debug, Default, PartialEq)]
145pub struct ParagraphRun {
146    pub range: std::ops::Range<usize>,
147    pub align: ParagraphAlign,
148    pub indent: f64,
149    pub space_before: f64,
150    pub space_after: f64,
151    pub list: ListStyle,
152    pub list_level: u8,
153}
154
155impl ParagraphRun {
156    #[must_use]
157    pub fn new(range: std::ops::Range<usize>, style: ParagraphStyle) -> Self {
158        ParagraphRun {
159            range,
160            align: style.align,
161            indent: style.indent,
162            space_before: style.space_before,
163            space_after: style.space_after,
164            list: style.list,
165            list_level: style.list_level,
166        }
167    }
168    #[must_use]
169    pub fn style(&self) -> ParagraphStyle {
170        ParagraphStyle {
171            align: self.align,
172            indent: self.indent,
173            space_before: self.space_before,
174            space_after: self.space_after,
175            list: self.list,
176            list_level: self.list_level,
177        }
178    }
179}
180
181// ---------------------------------------------------------------------------
182// The document
183// ---------------------------------------------------------------------------
184
185/// A styled document: plain text, the character runs over it, and the paragraph attributes over
186/// the same offsets.
187#[derive(Clone, Debug, Default, PartialEq)]
188pub struct StyledText {
189    pub text: String,
190    pub runs: Vec<TextRun>,
191    pub paragraphs: Vec<ParagraphRun>,
192}
193
194impl From<String> for StyledText {
195    fn from(text: String) -> Self {
196        StyledText::plain(text)
197    }
198}
199
200impl From<&str> for StyledText {
201    fn from(text: &str) -> Self {
202        StyledText::plain(text)
203    }
204}
205
206impl StyledText {
207    /// Unstyled text.
208    pub fn plain(text: impl Into<String>) -> Self {
209        StyledText {
210            text: text.into(),
211            runs: Vec::new(),
212            paragraphs: Vec::new(),
213        }
214    }
215
216    /// Parse markdown, the ergonomic way to seed a document
217    /// ([`styled_codec`](crate::styled_codec)).
218    #[must_use]
219    pub fn markdown(md: &str, base: Font) -> Self {
220        crate::styled_codec::markdown_to_styled(
221            md,
222            crate::styled_codec::DocStyle {
223                base,
224                ..Default::default()
225            },
226        )
227    }
228
229    /// Parse an HTML fragment.
230    #[must_use]
231    pub fn html(html: &str, base: Font) -> Self {
232        crate::styled_codec::html_to_styled(
233            html,
234            crate::styled_codec::DocStyle {
235                base,
236                ..Default::default()
237            },
238        )
239    }
240
241    /// Parse the RTF subset Day reads (docs/texteditor.md).
242    #[must_use]
243    pub fn rtf(rtf: &str, base: Font) -> Self {
244        crate::styled_codec::rtf_to_styled(
245            rtf,
246            crate::styled_codec::DocStyle {
247                base,
248                ..Default::default()
249            },
250        )
251    }
252
253    /// Write this document as markdown / HTML / RTF. Each is lossy in the ways
254    /// [`styled_codec`](crate::styled_codec) documents.
255    #[must_use]
256    pub fn to_markdown(&self, base: Font) -> String {
257        crate::styled_codec::styled_to_markdown(
258            self,
259            crate::styled_codec::DocStyle {
260                base,
261                ..Default::default()
262            },
263        )
264    }
265
266    #[must_use]
267    pub fn to_html(&self, base: Font) -> String {
268        crate::styled_codec::styled_to_html(
269            self,
270            crate::styled_codec::DocStyle {
271                base,
272                ..Default::default()
273            },
274        )
275    }
276
277    #[must_use]
278    pub fn to_rtf(&self, base: Font) -> String {
279        crate::styled_codec::styled_to_rtf(
280            self,
281            crate::styled_codec::DocStyle {
282                base,
283                ..Default::default()
284            },
285        )
286    }
287
288    /// Text with character runs and no paragraph attributes, which is what a label carries today.
289    pub fn new(text: impl Into<String>, runs: Vec<TextRun>) -> Self {
290        StyledText {
291            text: text.into(),
292            runs,
293            paragraphs: Vec::new(),
294        }
295    }
296
297    #[must_use]
298    pub fn is_empty(&self) -> bool {
299        self.text.is_empty()
300    }
301
302    /// Are both range vectors well formed for the text (ascending, non-overlapping, in bounds,
303    /// on character boundaries)?
304    ///
305    /// # Errors
306    ///
307    /// Returns a message naming the first run or paragraph run that breaks one of those rules.
308    pub fn validate(&self) -> Result<(), String> {
309        runs_are_valid(&self.text, &self.runs)?;
310        paragraphs_are_valid(&self.text, &self.paragraphs)
311    }
312
313    /// The whole text as consecutive `(range, style)` segments, unstyled gaps included as `base`.
314    ///
315    /// One view that the query and the mutation below are both written against, so neither has to
316    /// reason about where a run ends and a gap begins.
317    #[must_use]
318    pub fn segments(&self, base: Font) -> Vec<(std::ops::Range<usize>, RunStyle)> {
319        let plain = RunStyle::plain(base);
320        let mut out = Vec::with_capacity(self.runs.len() * 2 + 1);
321        let mut at = 0usize;
322        for r in &self.runs {
323            if r.range.start > at {
324                out.push((at..r.range.start, plain.clone()));
325            }
326            if !r.range.is_empty() {
327                out.push((r.range.clone(), r.style()));
328            }
329            at = at.max(r.range.end);
330        }
331        if at < self.text.len() {
332            out.push((at..self.text.len(), plain));
333        }
334        out
335    }
336
337    /// The style in effect across `range`.
338    ///
339    /// Where the segments under it disagree, the differing attribute comes back as its default
340    /// rather than as one of the values. That is what a toolbar renders as its mixed state, and
341    /// it is what makes pressing the button set the whole selection instead of toggling half of
342    /// it.
343    ///
344    /// A collapsed caret takes the style of the segment that ENDS at it, preferring that over the
345    /// one it starts: typing after a bold word continues bold, which is what every editor does.
346    #[must_use]
347    pub fn style_of(&self, range: std::ops::Range<usize>, base: Font) -> RunStyle {
348        let segs = self.segments(base);
349        if range.is_empty() {
350            let at = range.start;
351            return segs
352                .iter()
353                .find(|(r, _)| r.start < at && r.end >= at)
354                .or_else(|| segs.iter().find(|(r, _)| r.contains(&at)))
355                .map_or_else(|| RunStyle::plain(base), |(_, s)| s.clone());
356        }
357        let mut acc: Option<RunStyle> = None;
358        for (r, s) in &segs {
359            if r.end <= range.start || r.start >= range.end {
360                continue;
361            }
362            acc = Some(merge_style(acc, s));
363        }
364        acc.unwrap_or_else(|| RunStyle::plain(base))
365    }
366
367    /// Apply `f` to the style of every segment overlapping `range`, splitting at its boundaries so
368    /// only the selected text changes, then coalescing what came out.
369    pub fn apply(&mut self, range: std::ops::Range<usize>, base: Font, f: impl Fn(&mut RunStyle)) {
370        if range.start >= range.end || range.start >= self.text.len() {
371            return;
372        }
373        let range = range.start..range.end.min(self.text.len());
374        let mut out: Vec<TextRun> = Vec::new();
375        for (r, s) in self.segments(base) {
376            // Up to three pieces per segment: before the selection, inside it, after it.
377            for (piece, inside) in [
378                (r.start..r.end.min(range.start), false),
379                (r.start.max(range.start)..r.end.min(range.end), true),
380                (r.start.max(range.end)..r.end, false),
381            ] {
382                if piece.start >= piece.end {
383                    continue;
384                }
385                let mut style = s.clone();
386                if inside {
387                    f(&mut style);
388                }
389                out.push(TextRun::styled(piece, style));
390            }
391        }
392        self.runs = coalesce_runs(out, base);
393    }
394
395    /// The paragraph style in effect across `range`, by the same mixed-state rule as
396    /// [`StyledText::style_of`].
397    #[must_use]
398    pub fn paragraph_style_of(&self, range: std::ops::Range<usize>) -> ParagraphStyle {
399        let mut acc: Option<ParagraphStyle> = None;
400        for (start, end) in paragraph_bounds(&self.text) {
401            if !touches(start, end, &range) {
402                continue;
403            }
404            let style = self.paragraph_at(start, end);
405            acc = Some(match acc {
406                None => style,
407                Some(a) if a == style => a,
408                Some(_) => ParagraphStyle::default(),
409            });
410        }
411        acc.unwrap_or_default()
412    }
413
414    /// Apply `f` to every paragraph the selection touches. Paragraph boundaries are `\n`, so a
415    /// caret anywhere inside a paragraph styles the whole of it, which is what every editor does.
416    pub fn apply_paragraph(
417        &mut self,
418        range: std::ops::Range<usize>,
419        f: impl Fn(&mut ParagraphStyle),
420    ) {
421        let mut out: Vec<ParagraphRun> = Vec::new();
422        for (start, end) in paragraph_bounds(&self.text) {
423            let mut style = self.paragraph_at(start, end);
424            if touches(start, end, &range) {
425                f(&mut style);
426            }
427            if style != ParagraphStyle::default() {
428                out.push(ParagraphRun::new(start..end, style));
429            }
430        }
431        self.paragraphs = out;
432    }
433
434    /// The style recorded for the paragraph spanning `start..end`, or the default.
435    fn paragraph_at(&self, start: usize, end: usize) -> ParagraphStyle {
436        self.paragraphs
437            .iter()
438            .find(|p| p.range.start <= start && p.range.end >= end.min(p.range.end).max(start + 1))
439            .map_or_default(ParagraphRun::style)
440    }
441
442    /// Move the ranges over a character edit the native editor already made: `removed` bytes at
443    /// `offset` replaced by `inserted` bytes.
444    ///
445    /// This is why a keystroke does not have to ship the whole document back. Ranges before the
446    /// edit are untouched, ranges after it shift, a range containing it grows or shrinks, and a
447    /// range the edit emptied is dropped. That is the rule every attributed-string implementation
448    /// uses, exact, and O(runs) rather than O(document).
449    ///
450    /// `self.text` must already be the new text; this only moves ranges.
451    pub fn reflow(&mut self, offset: usize, removed: usize, inserted: usize) {
452        let shift = |p: usize| -> usize {
453            if p <= offset {
454                p
455            } else if p >= offset + removed {
456                p - removed + inserted
457            } else {
458                offset // inside the deleted span: collapse to the edit point
459            }
460        };
461        for r in &mut self.runs {
462            r.range = shift(r.range.start)..shift(r.range.end);
463        }
464        for p in &mut self.paragraphs {
465            p.range = shift(p.range.start)..shift(p.range.end);
466        }
467        // A run the edit ended inside grows over the insertion, so typing at the end of a bold
468        // word stays bold. Applied after the shift so the comparison is in new coordinates.
469        if inserted > 0 {
470            for r in &mut self.runs {
471                if r.range.end == offset && r.range.start < offset {
472                    r.range.end = offset + inserted;
473                }
474            }
475            for p in &mut self.paragraphs {
476                if p.range.end == offset && p.range.start < offset {
477                    p.range.end = offset + inserted;
478                }
479            }
480        }
481        self.clamp();
482    }
483
484    /// Clamp every range into the text and onto character boundaries, dropping what cannot be
485    /// saved. The last defense before a range reaches a backend and panics an `str` slice.
486    pub fn clamp(&mut self) {
487        let text = std::mem::take(&mut self.text);
488        let fix = |p: usize| -> usize {
489            let mut p = p.min(text.len());
490            while p > 0 && !text.is_char_boundary(p) {
491                p -= 1;
492            }
493            p
494        };
495        for r in &mut self.runs {
496            r.range = fix(r.range.start)..fix(r.range.end);
497        }
498        for p in &mut self.paragraphs {
499            p.range = fix(p.range.start)..fix(p.range.end);
500        }
501        self.text = text;
502        self.runs.retain(|r| r.range.start < r.range.end);
503        self.paragraphs.retain(|p| p.range.start < p.range.end);
504    }
505
506    /// Replace `range` with `text`, moving every other range over the edit. The app-side twin of
507    /// what a keystroke does, for a programmatic insert or delete.
508    pub fn splice(&mut self, range: std::ops::Range<usize>, text: &str) {
509        let range = range.start.min(self.text.len())..range.end.min(self.text.len());
510        if !self.text.is_char_boundary(range.start) || !self.text.is_char_boundary(range.end) {
511            return;
512        }
513        let removed = range.end.saturating_sub(range.start);
514        self.text.replace_range(range.clone(), text);
515        self.reflow(range.start, removed, text.len());
516    }
517}
518
519/// Fold `b` into the accumulated selection style: an attribute both agree on survives, one they
520/// differ on resets to its default (the toolbar's mixed state).
521#[expect(
522    clippy::float_cmp,
523    reason = "a merged run keeps a scale only when both runs store the identical value"
524)]
525fn merge_style(acc: Option<RunStyle>, b: &RunStyle) -> RunStyle {
526    let Some(a) = acc else { return b.clone() };
527    RunStyle {
528        font: FontSpec {
529            style: if a.font.style == b.font.style {
530                a.font.style
531            } else {
532                Font::Body
533            },
534            weight: if a.font.weight == b.font.weight {
535                a.font.weight
536            } else {
537                None
538            },
539            italic: a.font.italic && b.font.italic,
540            tabular: a.font.tabular && b.font.tabular,
541            monospace: a.font.monospace && b.font.monospace,
542            scale: if a.font.scale == b.font.scale {
543                a.font.scale
544            } else {
545                1.0
546            },
547        },
548        color: if a.color == b.color { a.color } else { None },
549        background: if a.background == b.background {
550            a.background
551        } else {
552            None
553        },
554        underline: if a.underline == b.underline {
555            a.underline
556        } else {
557            Underline::None
558        },
559        strikethrough: a.strikethrough && b.strikethrough,
560        link: if a.link == b.link { a.link } else { None },
561    }
562}
563
564/// Does the paragraph `start..end` fall under `sel`? A collapsed caret counts against the
565/// paragraph it sits in, including at its very end.
566fn touches(start: usize, end: usize, sel: &std::ops::Range<usize>) -> bool {
567    if sel.start == sel.end {
568        return sel.start >= start && sel.start <= end;
569    }
570    start < sel.end && end > sel.start
571}
572
573/// Merge adjacent runs whose styles came out equal, and drop runs that say nothing beyond `base`.
574///
575/// Every `apply` produces fragments; without this a document accumulates one run per edit until
576/// the run vector is longer than the text it describes.
577#[must_use]
578pub fn coalesce_runs(runs: Vec<TextRun>, base: Font) -> Vec<TextRun> {
579    let plain = RunStyle::plain(base);
580    let mut out: Vec<TextRun> = Vec::with_capacity(runs.len());
581    for r in runs {
582        if r.range.is_empty() {
583            continue;
584        }
585        match out.last_mut() {
586            Some(prev) if prev.range.end == r.range.start && prev.style() == r.style() => {
587                prev.range.end = r.range.end;
588            }
589            _ => out.push(r),
590        }
591    }
592    out.retain(|r| r.style() != plain);
593    out
594}
595
596/// The `\n`-delimited paragraphs of `text`, as byte ranges INCLUDING the terminator.
597///
598/// An empty string has no paragraphs. A trailing newline makes an empty final paragraph, the way
599/// an editor shows a blank last line, so `"a\n"` is two paragraphs, not one.
600#[must_use]
601pub fn paragraph_bounds(text: &str) -> Vec<(usize, usize)> {
602    if text.is_empty() {
603        return Vec::new();
604    }
605    let mut out = Vec::new();
606    let mut start = 0usize;
607    for (i, b) in text.bytes().enumerate() {
608        if b == b'\n' {
609            out.push((start, i + 1));
610            start = i + 1;
611        }
612    }
613    out.push((start, text.len()));
614    out
615}
616
617/// Whether these paragraph runs are well formed for `text`: [`runs_are_valid`]'s rules, applied
618/// to the second range vector.
619///
620/// # Errors
621///
622/// Returns a message naming the first paragraph run that overlaps or precedes the one before
623/// it, ends past the text, has an inverted range, or splits a multi-byte character.
624pub fn paragraphs_are_valid(text: &str, paragraphs: &[ParagraphRun]) -> Result<(), String> {
625    let mut prev_end = 0usize;
626    for (i, p) in paragraphs.iter().enumerate() {
627        if p.range.start < prev_end {
628            return Err(format!(
629                "paragraph {i} starts at {} but the previous ends at {prev_end} — paragraph runs \
630                 must be ascending and non-overlapping",
631                p.range.start
632            ));
633        }
634        if p.range.end > text.len() {
635            return Err(format!(
636                "paragraph {i} ends at {} but the text is {} bytes",
637                p.range.end,
638                text.len()
639            ));
640        }
641        if p.range.start > p.range.end {
642            return Err(format!("paragraph {i} has an inverted range {:?}", p.range));
643        }
644        if !text.is_char_boundary(p.range.start) || !text.is_char_boundary(p.range.end) {
645            return Err(format!(
646                "paragraph {i}'s range {:?} splits a multi-byte character",
647                p.range
648            ));
649        }
650        prev_end = p.range.end;
651    }
652    Ok(())
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658
659    fn bold_run(range: std::ops::Range<usize>) -> TextRun {
660        TextRun::styled(range, {
661            let mut s = RunStyle::plain(Font::Body);
662            s.set_bold(true);
663            s
664        })
665    }
666
667    fn doc() -> StyledText {
668        // "hello world" with "hello" bold.
669        StyledText::new("hello world", vec![bold_run(0..5)])
670    }
671
672    #[test]
673    fn segments_cover_the_whole_text_including_gaps() {
674        let segs = doc().segments(Font::Body);
675        assert_eq!(
676            segs.iter().map(|(r, _)| r.clone()).collect::<Vec<_>>(),
677            vec![0..5, 5..11]
678        );
679        assert!(segs[0].1.bold());
680        assert!(!segs[1].1.bold());
681    }
682
683    #[test]
684    fn style_of_a_uniform_selection_is_that_style() {
685        assert!(doc().style_of(0..5, Font::Body).bold());
686        assert!(!doc().style_of(5..11, Font::Body).bold());
687    }
688
689    #[test]
690    fn style_of_a_mixed_selection_resets_what_differs() {
691        // Half bold, half not: the toolbar shows "not bold", so pressing it bolds everything.
692        let s = doc().style_of(0..11, Font::Body);
693        assert!(!s.bold(), "a mixed weight comes back as the default");
694    }
695
696    #[test]
697    fn a_caret_takes_the_style_of_the_run_it_ends() {
698        // Typing at offset 5, right after "hello", continues bold.
699        assert!(doc().style_of(5..5, Font::Body).bold());
700        // And at 11, after the plain tail, it does not.
701        assert!(!doc().style_of(11..11, Font::Body).bold());
702        // At offset 0 there is nothing behind the caret, so it takes the run ahead instead:
703        // typing at the very start of a document that begins bold gives bold, which is what
704        // TextEdit, Word and every web editor do.
705        assert!(doc().style_of(0..0, Font::Body).bold());
706    }
707
708    #[test]
709    fn apply_splits_runs_at_the_selection_boundaries() {
710        let mut d = doc();
711        d.apply(3..8, Font::Body, |s| s.set_italic(true));
712        // bold 0..3, bold+italic 3..5, italic 5..8, plain 8..11 (dropped as plain).
713        let got: Vec<_> = d
714            .runs
715            .iter()
716            .map(|r| (r.range.clone(), r.style().bold(), r.style().italic()))
717            .collect();
718        assert_eq!(
719            got,
720            vec![(0..3, true, false), (3..5, true, true), (5..8, false, true),]
721        );
722    }
723
724    #[test]
725    fn apply_coalesces_and_drops_plain() {
726        let mut d = doc();
727        d.apply(0..11, Font::Body, |s| s.set_bold(false));
728        assert!(
729            d.runs.is_empty(),
730            "unbolding everything leaves nothing to say: {:?}",
731            d.runs
732        );
733    }
734
735    #[test]
736    fn reflow_moves_ranges_over_an_insert() {
737        let mut d = doc();
738        // Type "XX" at offset 8 (inside " world").
739        d.text = "hello woXXrld".into();
740        d.reflow(8, 0, 2);
741        assert_eq!(d.runs[0].range, 0..5, "a run before the edit is untouched");
742
743        let mut d = doc();
744        // Type at 2, inside the bold run: it grows.
745        d.text = "heXXllo world".into();
746        d.reflow(2, 0, 2);
747        assert_eq!(d.runs[0].range, 0..7);
748    }
749
750    #[test]
751    fn typing_at_the_end_of_a_run_continues_it() {
752        let mut d = doc();
753        d.text = "helloX world".into();
754        d.reflow(5, 0, 1);
755        assert_eq!(d.runs[0].range, 0..6, "the bold run took the new character");
756    }
757
758    #[test]
759    fn reflow_shrinks_and_drops_over_a_delete() {
760        let mut d = doc();
761        // Delete "ello " (1..6): the bold run shrinks to 0..1.
762        d.text = "hworld".into();
763        d.reflow(1, 5, 0);
764        assert_eq!(d.runs[0].range, 0..1);
765
766        let mut d = doc();
767        // Delete the whole bold word: the run goes away rather than becoming empty.
768        d.text = " world".into();
769        d.reflow(0, 5, 0);
770        assert!(d.runs.is_empty(), "{:?}", d.runs);
771    }
772
773    #[test]
774    fn splice_edits_text_and_ranges_together() {
775        let mut d = doc();
776        d.splice(5..5, ",");
777        assert_eq!(d.text, "hello, world");
778        assert_eq!(d.runs[0].range, 0..6);
779        assert!(d.validate().is_ok());
780    }
781
782    #[test]
783    fn clamp_pulls_ranges_off_multi_byte_boundaries() {
784        let mut d = StyledText::new("héllo", vec![bold_run(0..2)]);
785        d.text = "h".into(); // as if the tail were deleted without a reflow
786        d.clamp();
787        assert!(d.validate().is_ok());
788        assert!(d.runs.iter().all(|r| r.range.end <= 1));
789    }
790
791    #[test]
792    fn paragraph_bounds_include_the_terminator_and_the_blank_last_line() {
793        assert_eq!(paragraph_bounds(""), Vec::new());
794        assert_eq!(paragraph_bounds("a"), vec![(0, 1)]);
795        assert_eq!(paragraph_bounds("a\n"), vec![(0, 2), (2, 2)]);
796        assert_eq!(paragraph_bounds("a\nbb\nc"), vec![(0, 2), (2, 5), (5, 6)]);
797    }
798
799    #[test]
800    fn apply_paragraph_styles_the_whole_paragraph_a_caret_sits_in() {
801        let mut d = StyledText::plain("one\ntwo\nthree");
802        d.apply_paragraph(5..5, |p| p.align = ParagraphAlign::Center);
803        assert_eq!(d.paragraphs.len(), 1);
804        assert_eq!(d.paragraphs[0].range, 4..8, "the whole second paragraph");
805        assert_eq!(d.paragraphs[0].align, ParagraphAlign::Center);
806        assert_eq!(d.paragraph_style_of(5..5).align, ParagraphAlign::Center);
807        assert_eq!(
808            d.paragraph_style_of(0..13).align,
809            ParagraphAlign::Natural,
810            "a mixed selection reports the default"
811        );
812        assert!(d.validate().is_ok());
813    }
814
815    #[test]
816    fn paragraph_ranges_reflow_with_the_text() {
817        let mut d = StyledText::plain("one\ntwo");
818        d.apply_paragraph(5..5, |p| p.list = ListStyle::Bullet);
819        assert_eq!(d.paragraphs[0].range, 4..7);
820        d.splice(0..0, "XY");
821        assert_eq!(d.paragraphs[0].range, 6..9);
822        assert!(d.validate().is_ok());
823    }
824
825    #[test]
826    fn font_scale_resolves_against_the_platforms_style_size() {
827        let s = FontSpec::new(Font::Body).scaled(1.5);
828        assert_eq!(s.resolved_points(16.0), 24.0);
829        // An absolute style carries its own size and ignores the platform's.
830        let abs = FontSpec::new(Font::System(14.0));
831        assert_eq!(abs.resolved_points(16.0), 14.0);
832        assert_eq!(abs.scaled(2.0).resolved_points(16.0), 28.0);
833    }
834}