Skip to main content

rofd_editor/commands/
text_commands.rs

1use rofd_dom::{AnnotationId, AnnotationKind, AnnotationPayload, Color, FontId, NoteIcon, Rect};
2
3use crate::editor::Editor;
4use crate::payload_util::{set_color, set_width};
5use crate::text_spans::{spans_apply, spans_delete, spans_insert};
6
7/// Normalize line endings to `\n` (`\r\n` and lone `\r`).
8///
9/// Annotation content's model invariant is LF-only (spec 2026-11-09 §1.2.1):
10/// parley treats `\r\n` as TWO newline clusters, which would render a blank
11/// line between them.
12pub fn normalize_newlines(s: &str) -> String {
13    s.replace("\r\n", "\n").replace('\r', "\n")
14}
15
16impl Editor {
17    /// Set the primary color. For a TextBox, `range` scopes the change to the
18    /// selected chars (see [`spans_apply`]); other payload kinds ignore it.
19    pub fn set_annotation_color(
20        &mut self,
21        id: &AnnotationId,
22        range: Option<(usize, usize)>,
23        color: Color,
24    ) {
25        let before = match self.document.annotations.find(id).cloned() {
26            Some(a) => a,
27            None => return,
28        };
29        let mut after = before.clone();
30        if matches!(after.payload, AnnotationPayload::TextBox { .. }) {
31            spans_apply(&mut after.payload, range, &mut |span| {
32                span.color = Some(color)
33            });
34        } else {
35            set_color(&mut after.payload, color);
36        }
37        after.modified = self.current_ts;
38        self.execute_transaction(self.replace_txn(id.clone(), before, after));
39    }
40
41    /// Set the stroke width (Freehand/Shape).
42    pub fn set_annotation_width(&mut self, id: &AnnotationId, width: f64) {
43        let before = match self.document.annotations.find(id).cloned() {
44            Some(a) => a,
45            None => return,
46        };
47        let mut after = before.clone();
48        set_width(&mut after.payload, width);
49        after.modified = self.current_ts;
50        self.execute_transaction(self.replace_txn(id.clone(), before, after));
51    }
52
53    /// Set the font size (millimetres) of a TextBox in ONE transaction.
54    /// `range` scopes the change to the selected chars (see [`spans_apply`]).
55    /// `measure` follows the [`Self::insert_text_measured`] contract and is
56    /// applied inside the same transaction (grow-only callers pass `None`
57    /// when the box does not need to grow).
58    pub fn set_annotation_font_size_measured<F>(
59        &mut self,
60        id: &AnnotationId,
61        range: Option<(usize, usize)>,
62        size_mm: f64,
63        measure: F,
64    ) where
65        F: FnOnce(&AnnotationPayload) -> Option<f64>,
66    {
67        let before = match self.document.annotations.find(id).cloned() {
68            Some(a) => a,
69            None => return,
70        };
71        if !matches!(before.payload, AnnotationPayload::TextBox { .. }) {
72            return;
73        }
74        let mut after = before.clone();
75        spans_apply(&mut after.payload, range, &mut |span| span.size = size_mm);
76        if let Some(height) = measure(&after.payload) {
77            if let AnnotationPayload::TextBox { rect, .. } = &mut after.payload {
78                rect.h = height;
79            }
80        }
81        after.modified = self.current_ts;
82        self.execute_transaction(self.replace_txn(id.clone(), before, after));
83    }
84
85    /// Set the font family of a TextBox (`font = FontId::new(family)`) in ONE
86    /// transaction. `range` scopes the change to the selected chars.
87    pub fn set_annotation_font_family_measured<F>(
88        &mut self,
89        id: &AnnotationId,
90        range: Option<(usize, usize)>,
91        family: &str,
92        measure: F,
93    ) where
94        F: FnOnce(&AnnotationPayload) -> Option<f64>,
95    {
96        let before = match self.document.annotations.find(id).cloned() {
97            Some(a) => a,
98            None => return,
99        };
100        if !matches!(before.payload, AnnotationPayload::TextBox { .. }) {
101            return;
102        }
103        let mut after = before.clone();
104        spans_apply(&mut after.payload, range, &mut |span| {
105            span.font = FontId::new(family)
106        });
107        if let Some(height) = measure(&after.payload) {
108            if let AnnotationPayload::TextBox { rect, .. } = &mut after.payload {
109                rect.h = height;
110            }
111        }
112        after.modified = self.current_ts;
113        self.execute_transaction(self.replace_txn(id.clone(), before, after));
114    }
115
116    /// Insert text into a text annotation (TextBox/Note/Watermark) at char offset.
117    pub fn insert_text(&mut self, id: &AnnotationId, offset: usize, chars: &str) {
118        self.insert_text_measured(id, offset, chars, |_| None);
119    }
120
121    /// Insert text and let `measure` suggest a new annotation height. The
122    /// closure sees the post-edit payload, so the component can shape the exact
123    /// text with its font store; a `Some(h)` is applied in the SAME transaction
124    /// (one undo restores text + height). `measure` must return `Some` only
125    /// when growth is needed.
126    pub fn insert_text_measured<F>(
127        &mut self,
128        id: &AnnotationId,
129        offset: usize,
130        chars: &str,
131        measure: F,
132    ) where
133        F: FnOnce(&AnnotationPayload) -> Option<f64>,
134    {
135        let before = match self.document.annotations.find(id).cloned() {
136            Some(a) => a,
137            None => return,
138        };
139        let mut after = before.clone();
140        let chars = normalize_newlines(chars);
141        if matches!(after.payload, AnnotationPayload::TextBox { .. }) {
142            spans_insert(&mut after.payload, offset, &chars);
143        } else if let Some(content) = text_content_mut(&mut after.payload) {
144            let off = offset.min(content.chars().count());
145            let mut new = content.chars().take(off).collect::<String>();
146            new.push_str(&chars);
147            new.extend(content.chars().skip(off));
148            *content = new;
149        }
150        if let Some(height) = measure(&after.payload) {
151            if let AnnotationPayload::TextBox { rect, .. } = &mut after.payload {
152                rect.h = height;
153            }
154        }
155        after.modified = self.current_ts;
156        self.execute_transaction(self.replace_txn(id.clone(), before, after));
157    }
158
159    /// Replace the char range `[start, end)` with `chars` in ONE transaction.
160    /// Typing / Backspace / Delete / Enter / paste / IME commit over an active
161    /// text selection all route here, so the edit is a single undo step.
162    /// `measure` follows the same contract as [`Self::insert_text_measured`].
163    pub fn replace_text_measured<F>(
164        &mut self,
165        id: &AnnotationId,
166        start: usize,
167        end: usize,
168        chars: &str,
169        measure: F,
170    ) where
171        F: FnOnce(&AnnotationPayload) -> Option<f64>,
172    {
173        let before = match self.document.annotations.find(id).cloned() {
174            Some(a) => a,
175            None => return,
176        };
177        let mut after = before.clone();
178        let chars = normalize_newlines(chars);
179        if matches!(after.payload, AnnotationPayload::TextBox { .. }) {
180            let total = match &after.payload {
181                AnnotationPayload::TextBox { content, .. } => content.chars().count(),
182                _ => 0,
183            };
184            let s = start.min(total);
185            let e = end.min(total).max(s);
186            spans_delete(&mut after.payload, s, e - s);
187            spans_insert(&mut after.payload, s, &chars);
188        } else if let Some(content) = text_content_mut(&mut after.payload) {
189            let total = content.chars().count();
190            let s = start.min(total);
191            let e = end.min(total).max(s);
192            let mut new: String = content.chars().take(s).collect();
193            new.push_str(&chars);
194            new.extend(content.chars().skip(e));
195            *content = new;
196        }
197        if let Some(height) = measure(&after.payload) {
198            if let AnnotationPayload::TextBox { rect, .. } = &mut after.payload {
199                rect.h = height;
200            }
201        }
202        after.modified = self.current_ts;
203        self.execute_transaction(self.replace_txn(id.clone(), before, after));
204    }
205
206    /// Delete `len` chars from a text annotation at char offset.
207    pub fn delete_text(&mut self, id: &AnnotationId, offset: usize, len: usize) {
208        self.delete_text_measured(id, offset, len, |_| None);
209    }
210
211    /// Delete text and let `measure` suggest a new annotation height (same
212    /// contract as [`Self::insert_text_measured`]).
213    pub fn delete_text_measured<F>(
214        &mut self,
215        id: &AnnotationId,
216        offset: usize,
217        len: usize,
218        measure: F,
219    ) where
220        F: FnOnce(&AnnotationPayload) -> Option<f64>,
221    {
222        let before = match self.document.annotations.find(id).cloned() {
223            Some(a) => a,
224            None => return,
225        };
226        let mut after = before.clone();
227        if matches!(after.payload, AnnotationPayload::TextBox { .. }) {
228            let total = match &after.payload {
229                AnnotationPayload::TextBox { content, .. } => content.chars().count(),
230                _ => 0,
231            };
232            let start = offset.min(total);
233            let end = (offset + len).min(total);
234            spans_delete(&mut after.payload, start, end.saturating_sub(start));
235        } else if let Some(content) = text_content_mut(&mut after.payload) {
236            let total = content.chars().count();
237            let start = offset.min(total);
238            let end = (offset + len).min(total);
239            let kept: String = content
240                .chars()
241                .enumerate()
242                .filter(|(i, _)| *i < start || *i >= end)
243                .map(|(_, c)| c)
244                .collect();
245            *content = kept;
246        }
247        if let Some(height) = measure(&after.payload) {
248            if let AnnotationPayload::TextBox { rect, .. } = &mut after.payload {
249                rect.h = height;
250            }
251        }
252        after.modified = self.current_ts;
253        self.execute_transaction(self.replace_txn(id.clone(), before, after));
254    }
255
256    /// Replace the whole text content. The old span styles do not map onto the
257    /// new text, so they are dropped (the box falls back to its flat style).
258    pub fn set_annotation_text(&mut self, id: &AnnotationId, text: &str) {
259        let before = match self.document.annotations.find(id).cloned() {
260            Some(a) => a,
261            None => return,
262        };
263        let mut after = before.clone();
264        if let AnnotationPayload::TextBox { spans, .. } = &mut after.payload {
265            spans.clear();
266        }
267        if let Some(content) = text_content_mut(&mut after.payload) {
268            *content = normalize_newlines(text);
269        }
270        after.modified = self.current_ts;
271        self.execute_transaction(self.replace_txn(id.clone(), before, after));
272    }
273
274    /// Reply to an annotation (creates a Note with reply_to set).
275    pub fn reply_to(&mut self, parent: &AnnotationId, content: &str) -> AnnotationId {
276        // Find the parent's page so the reply lives on the same page.
277        let page = self
278            .document
279            .annotations
280            .find(parent)
281            .map(|a| a.page.clone())
282            .unwrap_or_default();
283        self.create_annotation(
284            AnnotationKind::Note,
285            page,
286            AnnotationPayload::Note {
287                rect: Rect {
288                    x: 0.0,
289                    y: 0.0,
290                    w: 40.0,
291                    h: 20.0,
292                },
293                color: Color::Rgb(255, 200, 0),
294                content: content.into(),
295                icon: NoteIcon::Comment,
296            },
297        );
298        // create_annotation doesn't set reply_to; patch it with a Replace step.
299        // (Slight inefficiency: create + replace = 2 transactions. Acceptable for v1.)
300        let new_id = self.last_created_id();
301        if let Some(new_id) = new_id {
302            // Re-fetch the created annotation to snapshot before/after.
303            if let Some(before) = self.document.annotations.find(&new_id).cloned() {
304                let mut after = before.clone();
305                after.reply_to = Some(parent.clone());
306                after.modified = self.current_ts;
307                self.execute_transaction(self.replace_txn(new_id.clone(), before, after));
308            }
309            return new_id;
310        }
311        // create_annotation always sets selection to Single(id), so last_created_id
312        // is always Some here. This is unreachable in practice.
313        unreachable!("create_annotation should have set selection to the new id")
314    }
315
316    /// The id of the most recently created annotation (create_annotation sets
317    /// selection to Single(id), so this reads from selection).
318    fn last_created_id(&self) -> Option<AnnotationId> {
319        match &self.selection {
320            crate::selection::AnnotationSelection::Single(id) => Some(id.clone()),
321            _ => None,
322        }
323    }
324}
325
326/// Mutable text content for text-bearing payloads (TextBox/Note/Watermark). None for others.
327fn text_content_mut(p: &mut AnnotationPayload) -> Option<&mut String> {
328    match p {
329        AnnotationPayload::Note { content, .. } => Some(content),
330        AnnotationPayload::TextBox { content, .. } => Some(content),
331        AnnotationPayload::Watermark { content, .. } => Some(content),
332        _ => None,
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use crate::editor::Editor;
339    use rofd_dom::{
340        AnnotationId, AnnotationKind, AnnotationPayload, Color, FontId, NoteIcon, PageId, Rect,
341        TextSpan,
342    };
343
344    fn note_editor(content: &str) -> (Editor, AnnotationId) {
345        let mut e = Editor::new();
346        e.set_clock("t".into(), 1);
347        let id = e.create_annotation(
348            AnnotationKind::Note,
349            PageId::new("P0"),
350            AnnotationPayload::Note {
351                rect: Rect {
352                    x: 0.0,
353                    y: 0.0,
354                    w: 10.0,
355                    h: 10.0,
356                },
357                color: Color::Rgb(0, 0, 0),
358                content: content.into(),
359                icon: NoteIcon::Note,
360            },
361        );
362        (e, id)
363    }
364
365    fn span_textbox_editor() -> (Editor, AnnotationId) {
366        let mut e = Editor::new();
367        e.set_clock("t".into(), 1);
368        let id = e.create_annotation(
369            AnnotationKind::TextBox,
370            PageId::new("P0"),
371            AnnotationPayload::TextBox {
372                rect: Rect {
373                    x: 0.0,
374                    y: 0.0,
375                    w: 100.0,
376                    h: 30.0,
377                },
378                content: "abcd".into(),
379                font: FontId::new("F1"),
380                size: 12.0,
381                color: Color::Rgb(0, 0, 0),
382                border: None,
383                spans: vec![
384                    TextSpan {
385                        text: "ab".into(),
386                        font: FontId::new("F1"),
387                        size: 12.0,
388                        color: Some(Color::Rgb(255, 0, 0)),
389                        bold: false,
390                        italic: false,
391                    },
392                    TextSpan {
393                        text: "cd".into(),
394                        font: FontId::new("F1"),
395                        size: 12.0,
396                        color: Some(Color::Rgb(0, 0, 255)),
397                        bold: false,
398                        italic: false,
399                    },
400                ],
401            },
402        );
403        (e, id)
404    }
405
406    fn style_sizes(e: &Editor, id: &AnnotationId) -> Vec<(usize, usize, f64)> {
407        let AnnotationPayload::TextBox { spans, .. } = textbox_payload(e, id) else {
408            panic!("expected TextBox");
409        };
410        let mut out = Vec::new();
411        let mut cursor = 0usize;
412        for span in spans {
413            let len = span.text.chars().count();
414            out.push((cursor, len, span.size));
415            cursor += len;
416        }
417        out
418    }
419
420    #[test]
421    fn set_font_size_on_a_selection_changes_only_that_range() {
422        let (mut e, id) = flat_textbox_editor_with("hello", 20.0);
423        e.set_annotation_font_size_measured(&id, Some((1, 3)), 30.0, |_| None);
424        assert_eq!(
425            style_sizes(&e, &id),
426            vec![(0, 1, 3.5), (1, 2, 30.0), (3, 2, 3.5)]
427        );
428    }
429
430    #[test]
431    fn text_edit_preserves_spans_and_undo_restores_once() {
432        let (mut e, id) = span_textbox_editor();
433        let before = textbox_payload(&e, &id).clone();
434        e.insert_text(&id, 2, "XY");
435        assert_eq!(
436            match textbox_payload(&e, &id) {
437                AnnotationPayload::TextBox { spans, .. } => spans.len(),
438                _ => 0,
439            },
440            2,
441            "insert does not collapse"
442        );
443        assert!(e.undo());
444        assert_eq!(textbox_payload(&e, &id), &before);
445    }
446
447    fn rich_textbox_editor() -> (Editor, AnnotationId) {
448        let mut e = Editor::new();
449        e.set_clock("t".into(), 1);
450        let id = e.create_annotation(
451            AnnotationKind::TextBox,
452            PageId::new("P0"),
453            AnnotationPayload::TextBox {
454                rect: Rect {
455                    x: 10.0,
456                    y: 20.0,
457                    w: 46.0,
458                    h: 10.0,
459                },
460                content: "发的古格".into(),
461                font: FontId::new("118"),
462                size: 4.2333,
463                color: Color::Rgb(0, 0, 0),
464                border: None,
465                spans: vec![
466                    TextSpan {
467                        text: "发的古".into(),
468                        font: FontId::new("118"),
469                        size: 4.2333,
470                        color: None,
471                        bold: false,
472                        italic: false,
473                    },
474                    TextSpan {
475                        text: "格".into(),
476                        font: FontId::new("157"),
477                        size: 4.2333,
478                        color: Some(Color::Rgb(75, 172, 198)),
479                        bold: true,
480                        italic: false,
481                    },
482                ],
483            },
484        );
485        (e, id)
486    }
487
488    fn textbox_payload<'a>(e: &'a Editor, id: &AnnotationId) -> &'a AnnotationPayload {
489        &e.document().annotations.find(id).unwrap().payload
490    }
491
492    fn content_of(e: &Editor, id: &AnnotationId) -> String {
493        let a = e.document().annotations.find(id).unwrap();
494        match &a.payload {
495            AnnotationPayload::Note { content, .. } => content.clone(),
496            _ => panic!("not a text annotation"),
497        }
498    }
499
500    #[test]
501    fn insert_text_at_offset() {
502        let (mut e, id) = note_editor("Hello");
503        e.insert_text(&id, 2, "XX");
504        assert_eq!(content_of(&e, &id), "HeXXllo");
505    }
506
507    #[test]
508    fn text_edit_keeps_span_styles_in_place() {
509        // Rich spans are editable now: inserting inside the last span keeps
510        // both styles and does not change the flat fields.
511        let (mut e, id) = rich_textbox_editor();
512        e.insert_text(&id, 4, "!");
513        match textbox_payload(&e, &id) {
514            AnnotationPayload::TextBox {
515                content,
516                font,
517                size,
518                spans,
519                ..
520            } => {
521                assert_eq!(content, "发的古格!");
522                assert_eq!(spans.len(), 2, "styles survive the edit");
523                assert_eq!(spans[1].text, "格!");
524                assert_eq!(font.0, "118", "flat style unchanged");
525                assert!((size - 4.2333).abs() < 1e-9);
526            }
527            other => panic!("expected TextBox, got {other:?}"),
528        }
529    }
530
531    #[test]
532    fn text_edit_undo_restores_spans() {
533        let (mut e, id) = rich_textbox_editor();
534        let before = textbox_payload(&e, &id).clone();
535        e.delete_text(&id, 0, 1);
536        assert!(
537            matches!(
538                textbox_payload(&e, &id),
539                AnnotationPayload::TextBox { spans, .. } if !spans.is_empty()
540            ),
541            "delete edits the span, it does not clear it"
542        );
543        assert!(e.undo());
544        assert_eq!(textbox_payload(&e, &id), &before, "undo restores spans");
545    }
546
547    #[test]
548    fn flat_textbox_edit_keeps_spans_empty() {
549        let mut e = Editor::new();
550        e.set_clock("t".into(), 1);
551        let id = e.create_annotation(
552            AnnotationKind::TextBox,
553            PageId::new("P0"),
554            AnnotationPayload::TextBox {
555                rect: Rect {
556                    x: 0.0,
557                    y: 0.0,
558                    w: 30.0,
559                    h: 8.0,
560                },
561                content: "hi".into(),
562                font: FontId::new("F1"),
563                size: 3.5,
564                color: Color::Rgb(0, 0, 0),
565                border: None,
566                spans: vec![],
567            },
568        );
569        e.insert_text(&id, 1, "o");
570        assert!(matches!(
571            textbox_payload(&e, &id),
572            AnnotationPayload::TextBox { content, spans, .. }
573                if content == "hoi" && spans.is_empty()
574        ));
575    }
576
577    #[test]
578    fn delete_text_range() {
579        let (mut e, id) = note_editor("Hello");
580        e.delete_text(&id, 1, 2);
581        assert_eq!(content_of(&e, &id), "Hlo");
582    }
583
584    #[test]
585    fn set_text_replaces() {
586        let (mut e, id) = note_editor("Hello");
587        e.set_annotation_text(&id, "World");
588        assert_eq!(content_of(&e, &id), "World");
589    }
590
591    #[test]
592    fn text_edit_undo_restores() {
593        let (mut e, id) = note_editor("Hello");
594        e.insert_text(&id, 5, "!");
595        assert_eq!(content_of(&e, &id), "Hello!");
596        e.undo();
597        assert_eq!(content_of(&e, &id), "Hello");
598    }
599
600    #[test]
601    fn reply_to_creates_note_with_parent() {
602        let (mut e, parent) = note_editor("parent");
603        let child = e.reply_to(&parent, "reply");
604        let c = e.document().annotations.find(&child).unwrap();
605        assert_eq!(c.reply_to, Some(parent.clone()));
606    }
607
608    fn flat_textbox_editor() -> (Editor, AnnotationId) {
609        flat_textbox_editor_with("hi", 10.0)
610    }
611
612    fn flat_textbox_editor_with(content: &str, h: f64) -> (Editor, AnnotationId) {
613        let mut e = Editor::new();
614        e.set_clock("t".into(), 1);
615        let id = e.create_annotation(
616            AnnotationKind::TextBox,
617            PageId::new("P0"),
618            AnnotationPayload::TextBox {
619                rect: Rect {
620                    x: 0.0,
621                    y: 0.0,
622                    w: 30.0,
623                    h,
624                },
625                content: content.into(),
626                font: FontId::new("F1"),
627                size: 3.5,
628                color: Color::Rgb(0, 0, 0),
629                border: None,
630                spans: vec![],
631            },
632        );
633        (e, id)
634    }
635
636    fn textbox_rect(e: &Editor, id: &AnnotationId) -> Rect {
637        match textbox_payload(e, id) {
638            AnnotationPayload::TextBox { rect, .. } => *rect,
639            other => panic!("expected TextBox, got {other:?}"),
640        }
641    }
642
643    fn textbox_content(e: &Editor, id: &AnnotationId) -> String {
644        match textbox_payload(e, id) {
645            AnnotationPayload::TextBox { content, .. } => content.clone(),
646            other => panic!("expected TextBox, got {other:?}"),
647        }
648    }
649
650    #[test]
651    fn insert_text_measured_grows_height_in_same_transaction() {
652        let (mut e, id) = flat_textbox_editor(); // rect h = 10.0, content "hi"
653        e.insert_text_measured(&id, 0, "x", |payload| {
654            assert!(matches!(payload, AnnotationPayload::TextBox { .. }));
655            Some(77.0)
656        });
657        assert_eq!(textbox_rect(&e, &id).h, 77.0);
658        assert_eq!(textbox_content(&e, &id), "xhi");
659        assert!(e.undo());
660        assert_eq!(textbox_rect(&e, &id).h, 10.0, "undo restores height too");
661        assert_eq!(textbox_content(&e, &id), "hi");
662    }
663
664    #[test]
665    fn insert_text_measured_none_keeps_height() {
666        let (mut e, id) = flat_textbox_editor();
667        e.insert_text_measured(&id, 0, "x", |_| None);
668        assert_eq!(textbox_rect(&e, &id).h, 10.0);
669    }
670
671    #[test]
672    fn delete_text_measured_applies_growth() {
673        let (mut e, id) = flat_textbox_editor_with("hello", 10.0);
674        e.delete_text_measured(&id, 0, 1, |_| Some(33.0));
675        assert_eq!(textbox_rect(&e, &id).h, 33.0);
676        assert_eq!(textbox_content(&e, &id), "ello");
677    }
678
679    #[test]
680    fn insert_text_normalizes_crlf() {
681        let (mut e, id) = flat_textbox_editor(); // content "hi"
682        e.insert_text(&id, 0, "a\r\nb\rc");
683        assert_eq!(textbox_content(&e, &id), "a\nb\nchi");
684    }
685
686    #[test]
687    fn set_annotation_text_normalizes_crlf() {
688        let (mut e, id) = flat_textbox_editor();
689        e.set_annotation_text(&id, "a\r\nb");
690        assert_eq!(textbox_content(&e, &id), "a\nb");
691    }
692
693    #[test]
694    fn replace_text_range_is_one_transaction() {
695        let (mut e, id) = flat_textbox_editor_with("hello world", 10.0);
696        // Replace "lo wo" (chars 3..8) with "XY".
697        e.replace_text_measured(&id, 3, 8, "XY", |_| Some(42.0));
698        assert_eq!(textbox_content(&e, &id), "helXYrld");
699        assert_eq!(
700            textbox_rect(&e, &id).h,
701            42.0,
702            "measure applied in-transaction"
703        );
704        assert_eq!(e.history_len(), 2, "create + one replace transaction");
705        assert!(e.undo());
706        assert_eq!(textbox_content(&e, &id), "hello world");
707        assert_eq!(textbox_rect(&e, &id).h, 10.0, "undo restores text + height");
708        assert_eq!(e.history_len(), 1);
709    }
710
711    #[test]
712    fn replace_text_range_clamps_and_handles_empty_insert() {
713        let (mut e, id) = flat_textbox_editor_with("abc", 10.0);
714        // Out-of-range end clamps to the content end; empty text = delete.
715        e.replace_text_measured(&id, 1, 99, "", |_| None);
716        assert_eq!(textbox_content(&e, &id), "a");
717        // Reversed range collapses at `start` (defensive).
718        e.replace_text_measured(&id, 1, 0, "Z", |_| None);
719        assert_eq!(textbox_content(&e, &id), "aZ");
720    }
721
722    #[test]
723    fn rich_textbox_edit_and_growth_are_atomic() {
724        let (mut e, id) = rich_textbox_editor(); // rect h = 10.0, spans non-empty
725        e.insert_text_measured(&id, 4, "x", |payload| {
726            let AnnotationPayload::TextBox {
727                spans, rect, font, ..
728            } = payload
729            else {
730                panic!("expected TextBox");
731            };
732            assert_eq!(spans.len(), 2, "measure sees the span-preserving payload");
733            assert_eq!(font.0, "118", "flat style unchanged");
734            Some(rect.h + 5.0)
735        });
736        match textbox_payload(&e, &id) {
737            AnnotationPayload::TextBox { rect, spans, .. } => {
738                assert_eq!(rect.h, 15.0);
739                assert_eq!(spans.len(), 2);
740            }
741            other => panic!("expected TextBox, got {other:?}"),
742        }
743        assert!(e.undo());
744        assert!(
745            matches!(
746                textbox_payload(&e, &id),
747                AnnotationPayload::TextBox { spans, rect, .. } if !spans.is_empty() && rect.h == 10.0
748            ),
749            "one undo restores spans AND height"
750        );
751    }
752
753    #[test]
754    fn set_font_size_is_one_transaction_and_restores_on_undo() {
755        let (mut e, id) = flat_textbox_editor_with("hello", 20.0);
756        let before = textbox_payload(&e, &id).clone();
757        let history = e.history_len();
758        e.set_annotation_font_size_measured(&id, None, 20.0, |_| Some(80.0));
759        assert_eq!(e.history_len(), history + 1, "one transaction");
760        let AnnotationPayload::TextBox { rect, size, .. } = textbox_payload(&e, &id) else {
761            panic!("expected TextBox");
762        };
763        assert_eq!(*size, 20.0);
764        assert_eq!(rect.h, 80.0, "measure result is applied in the same txn");
765        assert!(e.undo());
766        assert_eq!(textbox_payload(&e, &id), &before);
767    }
768
769    #[test]
770    fn set_font_size_never_shrinks_the_box() {
771        let (mut e, id) = flat_textbox_editor_with("hello", 40.0);
772        e.set_annotation_font_size_measured(&id, None, 6.0, |_| None);
773        let AnnotationPayload::TextBox { rect, size, .. } = textbox_payload(&e, &id) else {
774            panic!("expected TextBox");
775        };
776        assert_eq!(*size, 6.0);
777        assert_eq!(rect.h, 40.0, "grow-only");
778    }
779
780    #[test]
781    fn set_font_family_writes_the_font_id_and_collapses_spans() {
782        let (mut e, id) = rich_textbox_editor();
783        e.set_annotation_font_family_measured(&id, None, "宋体", |_| Some(24.0));
784        let AnnotationPayload::TextBox {
785            font, spans, rect, ..
786        } = textbox_payload(&e, &id)
787        else {
788            panic!("expected TextBox");
789        };
790        assert_eq!(font.0, "宋体");
791        assert!(
792            spans.is_empty(),
793            "rich spans collapse on the first style edit"
794        );
795        assert_eq!(rect.h, 24.0);
796        assert!(e.undo());
797        assert!(
798            matches!(
799                textbox_payload(&e, &id),
800                AnnotationPayload::TextBox { spans, font, .. }
801                    if !spans.is_empty() && font.0 == "118"
802            ),
803            "undo restores the rich appearance"
804        );
805    }
806
807    #[test]
808    fn set_color_collapses_spans_so_the_pick_is_visible() {
809        let (mut e, id) = rich_textbox_editor();
810        let before = textbox_payload(&e, &id).clone();
811        e.set_annotation_color(&id, None, Color::Rgb(0, 0, 255));
812        let AnnotationPayload::TextBox { spans, color, .. } = textbox_payload(&e, &id) else {
813            panic!("expected TextBox");
814        };
815        assert!(spans.is_empty(), "spans collapse so the flat color applies");
816        assert_eq!(*color, Color::Rgb(0, 0, 255));
817        assert!(e.undo());
818        assert_eq!(textbox_payload(&e, &id), &before, "one undo restores spans");
819    }
820
821    #[test]
822    fn unknown_family_still_updates_the_payload() {
823        let (mut e, id) = flat_textbox_editor_with("hi", 20.0);
824        e.set_annotation_font_family_measured(&id, None, "No Such Family", |_| None);
825        let AnnotationPayload::TextBox { font, .. } = textbox_payload(&e, &id) else {
826            panic!("expected TextBox");
827        };
828        assert_eq!(font.0, "No Such Family");
829    }
830}