odox-ui 0.4.1

The shared window of the odox OpenDocument editors: style mapping, document rendering, editing and chrome
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! The paragraphs under a flow's root, as the page editor sees them.
//!
//! A paragraph is named by its path of child indices from the root the flow
//! draws, which is the path [`crate::Flow`] reports it under. The editor's
//! edits become `odox-core` edits on the tree, and an edit that begins an undo
//! step is recorded in [`Editing`] once it has succeeded. A format writes
//! automatic styles, which the document's [`Styles`] is told of as they are
//! written. DESIGN.md ยง11.
//
// Author: David M. Anderson
// Built with AI assistance (Claude, Anthropic)

use std::cell::OnceCell;
use std::ops::Range;

use eframe::egui::Id;
use egui_richedit::{Edit, Mark, Model, Position, RichEdit};
use odox_core::edit::{self, is_paragraph};
use odox_core::{Element, Ns, Refused, Styles};

use crate::Editing;
use crate::flow::is_block_container;

/// The editor over a flow's paragraphs.
pub type PageEditor = RichEdit<Vec<usize>>;

/// The id the page editor takes the keyboard under. The shell reads it to
/// know that typing on the page still leaves its shortcuts to it.
pub(crate) fn page_editor_id() -> Id {
    Id::new("odox-page-editor")
}

/// A page editor with nothing selected.
pub fn page_editor() -> PageEditor {
    RichEdit::new(page_editor_id())
}

/// The paragraphs under a root in a content tree, for one frame's editing.
pub struct FlowModel<'a> {
    content: &'a mut Element,
    styles: &'a mut Styles,
    /// Where the flow's root is under the content root.
    root: Vec<usize>,
    editing: &'a mut Editing,
    /// The part of the root the paragraphs are kept to, as a path under it:
    /// on a slide, the one shape being typed into.
    scope: Vec<usize>,
    /// Every editable paragraph in drawing order, found when first asked for
    /// and forgotten when an edit changes it.
    order: OnceCell<Vec<Vec<usize>>>,
}

impl<'a> FlowModel<'a> {
    /// The paragraphs under the element at a path in a content tree, whose
    /// document's styles are `styles`.
    pub fn new(
        content: &'a mut Element,
        styles: &'a mut Styles,
        root: Vec<usize>,
        editing: &'a mut Editing,
    ) -> Self {
        Self {
            content,
            styles,
            root,
            editing,
            scope: Vec::new(),
            order: OnceCell::new(),
        }
    }

    /// Keep to the paragraphs under one element beneath the root, so that
    /// moving and joining never leave it: a slide's label does not run on
    /// into the next shape.
    #[must_use]
    pub fn within(mut self, scope: Vec<usize>) -> Self {
        self.scope = scope;
        self
    }

    fn root(&self) -> Option<&Element> {
        self.content.at(&self.root)
    }

    fn paragraph_mut(&mut self, path: &[usize]) -> Option<&mut Element> {
        self.content
            .at_mut(&self.root)?
            .at_mut(path)
            .filter(|element| is_paragraph(element))
    }

    fn order(&self) -> &[Vec<usize>] {
        self.order.get_or_init(|| {
            let mut out = Vec::new();
            if let Some(root) = self.root() {
                blocks(root, &mut Vec::new(), &mut out);
            }
            out.retain(|path| path.starts_with(&self.scope));
            out
        })
    }

    fn neighbour(&self, paragraph: &[usize], step: isize) -> Option<Vec<usize>> {
        let order = self.order();
        let index = order.iter().position(|p| p == paragraph)?;
        order.get(index.checked_add_signed(step)?).cloned()
    }

    fn replace(
        &mut self,
        from: &Position<Vec<usize>>,
        to: &Position<Vec<usize>>,
        text: &str,
    ) -> Option<()> {
        let root = self.content.at_mut(&self.root)?;
        match edit::replace_range(
            root,
            (&from.paragraph, from.offset),
            (&to.paragraph, to.offset),
            text,
        ) {
            Ok(()) => Some(()),
            Err(Refused::Structure) => self.clear_between(from, to, text),
            Err(_) => None,
        }
    }

    /// A range that crosses a table or a frame, which no join takes apart:
    /// the selected text goes from every paragraph it covers, each paragraph
    /// stays where it is, and the new text goes in at the start. Nothing to
    /// remove and nothing to put in, as Backspace at the start of a cell, is
    /// refused rather than made an edit of nothing.
    fn clear_between(
        &mut self,
        from: &Position<Vec<usize>>,
        to: &Position<Vec<usize>>,
        text: &str,
    ) -> Option<()> {
        let ranges = self.covered(from, to)?;
        if text.is_empty() && ranges.iter().all(|(_, range)| range.is_empty()) {
            return None;
        }
        for (path, range) in ranges.into_iter().rev() {
            let with = if path == from.paragraph { text } else { "" };
            let paragraph = self.paragraph_mut(&path)?;
            edit::replace(paragraph, range, with);
        }
        Some(())
    }

    /// Each paragraph from one position to another in drawing order, with
    /// the range of its text between them.
    fn covered(
        &self,
        from: &Position<Vec<usize>>,
        to: &Position<Vec<usize>>,
    ) -> Option<Vec<(Vec<usize>, Range<usize>)>> {
        let order = self.order();
        let first = order.iter().position(|p| *p == from.paragraph)?;
        let last = order.iter().position(|p| *p == to.paragraph)?;
        let covered: Vec<Vec<usize>> = order.get(first..=last)?.to_vec();
        Some(
            covered
                .into_iter()
                .map(|path| {
                    let len = self.text(&path).map_or(0, |t| t.chars().count());
                    let start = if path == from.paragraph {
                        from.offset
                    } else {
                        0
                    };
                    let end = if path == to.paragraph { to.offset } else { len };
                    (path, start..end.max(start))
                })
                .collect(),
        )
    }

    /// Give the text from one position to another a mark, or take it off,
    /// paragraph by paragraph.
    fn format(
        &mut self,
        from: &Position<Vec<usize>>,
        to: &Position<Vec<usize>>,
        mark: edit::Mark,
        on: bool,
    ) -> Option<()> {
        let automatic =
            |content: &Element| content.child(&Ns::Office, "automatic-styles").is_some();
        for (path, range) in self.covered(from, to)? {
            if range.is_empty() {
                continue;
            }
            let had = automatic(self.content);
            let mut at = self.root.clone();
            at.extend(&path);
            edit::format(self.content, &at, range, mark, on, self.styles).ok()?;
            // Styles written into a document that had nowhere to keep them go
            // before its body, and move the body, and the root, one along.
            if !had
                && automatic(self.content)
                && let Some(first) = self.root.first_mut()
            {
                *first += 1;
            }
        }
        Some(())
    }
}

/// The library's name for a mark.
fn core_mark(mark: Mark) -> edit::Mark {
    match mark {
        Mark::Bold => edit::Mark::Bold,
        Mark::Italic => edit::Mark::Italic,
        Mark::Underline => edit::Mark::Underline,
        Mark::Strike => edit::Mark::Strike,
    }
}

impl Model for FlowModel<'_> {
    type Paragraph = Vec<usize>;

    fn text(&self, paragraph: &Vec<usize>) -> Option<String> {
        self.root()?
            .at(paragraph)
            .filter(|element| is_paragraph(element))
            .map(edit::text)
    }

    fn next(&self, paragraph: &Vec<usize>) -> Option<Vec<usize>> {
        self.neighbour(paragraph, 1)
    }

    fn previous(&self, paragraph: &Vec<usize>) -> Option<Vec<usize>> {
        self.neighbour(paragraph, -1)
    }

    fn first(&self) -> Option<Vec<usize>> {
        self.order().first().cloned()
    }

    fn last(&self) -> Option<Vec<usize>> {
        self.order().last().cloned()
    }

    fn marked(
        &self,
        from: &Position<Vec<usize>>,
        to: &Position<Vec<usize>>,
        mark: Mark,
    ) -> Option<bool> {
        let root = self.root()?;
        let mark = core_mark(mark);
        let ranges: Vec<_> = self
            .covered(from, to)?
            .into_iter()
            .filter(|(_, range)| !range.is_empty())
            .collect();
        if ranges.is_empty() {
            let at = from.offset..from.offset;
            return edit::marked(root.at(&from.paragraph)?, at, mark, self.styles);
        }
        let mut answer = None;
        for (path, range) in ranges {
            let value = edit::marked(root.at(&path)?, range, mark, self.styles)?;
            if answer.is_some_and(|a| a != value) {
                return None;
            }
            answer = Some(value);
        }
        answer
    }

    fn apply(
        &mut self,
        edit: Edit<'_, Vec<usize>>,
        new_step: bool,
    ) -> Option<Position<Vec<usize>>> {
        // An edit to a document that matches its file always begins a step,
        // whatever the editor thinks: typing that runs on past a save is a
        // change the save does not hold, and has to be one a close asks about.
        let new_step = new_step || !self.editing.modified();
        // Taken before trying, because only trying says whether the edit is
        // made. A refusal is decided before anything in the tree changes.
        // Where the edit begins is where an undo of it puts the caret.
        let before = new_step.then(|| self.content.clone());
        let begins = match &edit {
            Edit::Replace { from, .. } | Edit::Format { from, .. } => from.clone(),
            Edit::Split { at } => at.clone(),
        };
        let at = match edit {
            Edit::Replace { from, to, text } => self
                .replace(&from, &to, text)
                .map(|()| Position::new(from.paragraph, from.offset + text.chars().count())),
            Edit::Split { at } => {
                let root = self.content.at_mut(&self.root)?;
                edit::split_at(root, &at.paragraph, at.offset)
                    .ok()
                    .map(|second| Position::new(second, 0))
            }
            Edit::Format { from, to, mark, on } => {
                self.format(&from, &to, core_mark(mark), on).map(|()| to)
            }
        };
        if at.is_some() {
            if let Some(before) = before {
                self.editing.record_snapshot(before, Some(begins));
            }
            self.order = OnceCell::new();
        }
        at
    }
}

/// The paragraphs among a run of blocks, in the order [`crate::Flow`] draws
/// them, and under the same paths.
fn blocks(parent: &Element, path: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
    for (index, element) in parent.elements_indexed() {
        path.push(index);
        block(element, path, out);
        path.pop();
    }
}

fn block(element: &Element, path: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
    if is_paragraph(element) {
        out.push(path.clone());
    } else if element.is(&Ns::Text, "list") {
        for (item_index, item) in element.elements_indexed() {
            if item.is(&Ns::Text, "list-item") || item.is(&Ns::Text, "list-header") {
                path.push(item_index);
                blocks(item, path, out);
                path.pop();
            }
        }
    } else if element.is(&Ns::Table, "table")
        || element.is(&Ns::Table, "table-header-rows")
        || element.is(&Ns::Table, "table-rows")
        || element.is(&Ns::Table, "table-row-group")
    {
        blocks(element, path, out);
    } else if element.is(&Ns::Table, "table-row") {
        for (cell_index, cell) in element.elements_indexed() {
            if cell.is(&Ns::Table, "table-cell") {
                path.push(cell_index);
                blocks(cell, path, out);
                path.pop();
            }
        }
    } else if element.is(&Ns::Draw, "frame") {
        if let Some((box_index, text_box)) = element
            .elements_indexed()
            .find(|(_, e)| e.is(&Ns::Draw, "text-box"))
        {
            path.push(box_index);
            blocks(text_box, path, out);
            path.pop();
        }
    } else if element.name.ns == Ns::Draw {
        // A drawing shape keeps its label as paragraphs of its own, where a
        // frame keeps them in a text box.
        blocks(element, path, out);
    } else if is_block_container(element) {
        blocks(element, path, out);
    }
}

#[cfg(test)]
mod tests {
    use super::FlowModel;
    use crate::Editing;
    use egui_richedit::{Edit, Model, Position};
    use odox_core::{Element, Node, Ns, Styles};

    fn element(prefix: &str, local: &str, ns: Ns, children: Vec<Node>) -> Node {
        let mut e = Element::new(prefix, local, ns);
        e.children = children;
        Node::Element(e)
    }

    fn p(text: &str) -> Node {
        element("text", "p", Ns::Text, vec![Node::Text(text.to_owned())])
    }

    /// `office:text` holding a paragraph, a list of one item, a table of one
    /// cell, and a paragraph, under a content root.
    fn content() -> Element {
        let list = element(
            "text",
            "list",
            Ns::Text,
            vec![element("text", "list-item", Ns::Text, vec![p("item")])],
        );
        let table = element(
            "table",
            "table",
            Ns::Table,
            vec![element(
                "table",
                "table-row",
                Ns::Table,
                vec![element("table", "table-cell", Ns::Table, vec![p("cell")])],
            )],
        );
        let body = element(
            "office",
            "text",
            Ns::Office,
            vec![p("one"), list, table, p("two")],
        );
        let mut root = Element::new("office", "document-content", Ns::Office);
        root.children = vec![element("office", "body", Ns::Office, vec![body])];
        root
    }

    #[test]
    fn paragraphs_follow_one_another_through_lists_and_tables() {
        let mut content = content();
        let mut styles = Styles::collect(Some(&content), None);
        let mut editing = Editing::default();
        let model = FlowModel::new(&mut content, &mut styles, vec![0, 0], &mut editing);
        let mut at = vec![0];
        let mut seen = vec![model.text(&at).expect("the first")];
        while let Some(next) = model.next(&at) {
            seen.push(model.text(&next).expect("a paragraph"));
            assert_eq!(model.previous(&next), Some(at));
            at = next;
        }
        assert_eq!(seen, ["one", "item", "cell", "two"]);
    }

    #[test]
    fn a_selection_over_a_whole_table_takes_it_and_joins_the_ends() {
        let mut content = content();
        let mut styles = Styles::collect(Some(&content), None);
        let mut editing = Editing::default();
        editing.reset();
        let mut model = FlowModel::new(&mut content, &mut styles, vec![0, 0], &mut editing);
        // From inside "item" to inside "two", over the table's one cell.
        let at = model.apply(
            Edit::Replace {
                from: Position::new(vec![1, 0, 0], 2),
                to: Position::new(vec![3], 1),
                text: "X",
            },
            true,
        );
        assert_eq!(at, Some(Position::new(vec![1, 0, 0], 3)));
        assert_eq!(model.text(&vec![1, 0, 0]).as_deref(), Some("itXwo"));
        assert_eq!(
            model.next(&vec![1, 0, 0]),
            None,
            "the table and \"two\" are gone"
        );
    }

    #[test]
    fn a_selection_out_of_a_cell_takes_the_text_and_leaves_the_cell() {
        let mut content = content();
        let mut styles = Styles::collect(Some(&content), None);
        let mut editing = Editing::default();
        editing.reset();
        let mut model = FlowModel::new(&mut content, &mut styles, vec![0, 0], &mut editing);
        // From inside "cell" to inside "two".
        let at = model.apply(
            Edit::Replace {
                from: Position::new(vec![2, 0, 0, 0], 2),
                to: Position::new(vec![3], 1),
                text: "",
            },
            true,
        );
        assert_eq!(at, Some(Position::new(vec![2, 0, 0, 0], 2)));
        assert_eq!(model.text(&vec![2, 0, 0, 0]).as_deref(), Some("ce"));
        assert_eq!(model.text(&vec![3]).as_deref(), Some("wo"));
    }

    #[test]
    fn backspace_at_a_list_item_joins_it_to_the_paragraph_before() {
        let mut content = content();
        let mut styles = Styles::collect(Some(&content), None);
        let mut editing = Editing::default();
        editing.reset();
        let mut model = FlowModel::new(&mut content, &mut styles, vec![0, 0], &mut editing);
        let at = model.apply(
            Edit::Replace {
                from: Position::new(vec![0], 3),
                to: Position::new(vec![1, 0, 0], 0),
                text: "",
            },
            true,
        );
        assert_eq!(at, Some(Position::new(vec![0], 3)));
        assert_eq!(model.text(&vec![0]).as_deref(), Some("oneitem"));
        // The list had one item, and went with it.
        assert_eq!(model.text(&vec![1, 0, 0, 0]).as_deref(), Some("cell"));
    }

    #[test]
    fn typing_that_runs_on_past_a_save_is_a_change() {
        let mut content = content();
        let mut styles = Styles::collect(Some(&content), None);
        let mut editing = Editing::default();
        editing.reset();
        let at = |offset| Position::new(vec![0], offset);
        let typed = |offset| Edit::Replace {
            from: at(offset),
            to: at(offset),
            text: "x",
        };
        let mut model = FlowModel::new(&mut content, &mut styles, vec![0, 0], &mut editing);
        model.apply(typed(0), true);
        model.editing.mark_saved();
        // The same run of typing, as far as the editor knows.
        model.apply(typed(1), false);
        assert!(
            editing.modified(),
            "what was typed after the save is unsaved"
        );
    }

    #[test]
    fn an_edit_that_begins_a_step_is_recorded_once_it_succeeds() {
        let mut content = content();
        let mut styles = Styles::collect(Some(&content), None);
        let mut editing = Editing::default();
        editing.reset();
        let mut model = FlowModel::new(&mut content, &mut styles, vec![0, 0], &mut editing);
        let at = model.apply(
            Edit::Split {
                at: Position::new(vec![0], 1),
            },
            true,
        );
        assert_eq!(at, Some(Position::new(vec![1], 0)));
        assert_eq!(model.text(&vec![0]).as_deref(), Some("o"));
        assert_eq!(model.text(&vec![1]).as_deref(), Some("ne"));

        // Backspace at the start of a table's cell: nothing to join and
        // nothing to remove, which is refused and is not a step.
        let refused = model.apply(
            Edit::Replace {
                from: Position::new(vec![2, 0, 0], 4),
                to: Position::new(vec![3, 0, 0, 0], 0),
                text: "",
            },
            true,
        );
        assert_eq!(refused, None);
        assert!(editing.can_undo());
        let mut undone = 0;
        let mut current = content.clone();
        while let Some(previous) = editing.undo(&current, None).map(|(tree, _)| tree) {
            current = previous;
            undone += 1;
        }
        assert_eq!(undone, 1);
    }
}