Skip to main content

editor/
anchor.rs

1//! Positions that outlive the edits under them.
2//!
3//! A comment or a highlight is anchored to a range of text, and that range has
4//! to move when the text around it does. What it *says* — a thread's replies,
5//! a highlight's note, who made either — is the app's, the way a link preview
6//! is. What is here is the range, its wash, and what keeps it over the same
7//! words.
8//!
9//! The anchors live in the editor rather than in the app because
10//! [`crate::History`] restores whole-document snapshots: an undo has no delta to
11//! map an anchor through, so the store has to sit where the history can carry
12//! it back.
13//!
14//! Mapping follows the **left-sticky** rule the marks already follow
15//! (`markdown::Text::insert`): text typed at the end of a range joins it, text
16//! typed at the start does not. Both ends take the same arithmetic, so there is
17//! no bias to pick per end and no second rule to keep in step with the first.
18
19use std::ops::Range;
20
21use markdown::{Annotation, Cursor, Part, Selection, Splice};
22
23/// The app's key for a comment or a highlight. Opaque — nothing here looks
24/// inside one.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub struct AnchorId(pub u64);
27
28/// A range in the document, and which wash it paints.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Anchor {
31    pub id: AnchorId,
32    pub range: Selection,
33    pub state: Annotation,
34}
35
36impl Anchor {
37    pub fn new(id: AnchorId, range: Selection) -> Self {
38        Self {
39            id,
40            range,
41            state: Annotation::default(),
42        }
43    }
44
45    /// Whether the words this pointed at are gone.
46    ///
47    /// Detached rather than dropped: whether that reads as "outdated" or as
48    /// "resolved" is the app's call, and deleting it here would take the choice
49    /// away.
50    pub fn detached(&self) -> bool {
51        self.range.is_collapsed()
52    }
53
54    pub(crate) fn map(&mut self, delta: &Delta) {
55        let (start, end) = self.range.ordered();
56        self.range = match (delta.cursor(start), delta.cursor(end)) {
57            (Some(start), Some(end)) => Selection::new(start.min(end), start.max(end)),
58            (surviving, other) => Selection::at(surviving.or(other).unwrap_or_default()),
59        };
60    }
61}
62
63/// What one step of a mutation did to the positions in a document.
64///
65/// Every path through [`crate::Editor::edit`] hands back a list of these, empty
66/// for an edit that moved nothing — so a block operation added later does not
67/// compile until it says what it did. Silent is the one thing it must not be:
68/// an anchor mapped through the wrong shift points at the wrong words and
69/// nothing complains.
70pub(crate) enum Delta {
71    CellsMoved {
72        block: usize,
73        from: crate::editor::Line,
74        to: usize,
75    },
76    /// Text went in, out, or both.
77    Spliced(Splice),
78    /// A run of blocks left `at`, and arrived at `to` unless it went away.
79    Moved { at: Range<usize>, to: Option<usize> },
80    /// Blocks appeared at `at`, pushing everything from there down.
81    Opened { at: usize, count: usize },
82    /// A row or a column appeared in table `block`, pushing the cells from
83    /// there on.
84    Cells {
85        block: usize,
86        row: Option<usize>,
87        column: Option<usize>,
88    },
89    /// A row or a column left table `block`, taking what was in it and
90    /// pulling the cells after it back.
91    CellsRemoved {
92        block: usize,
93        row: Option<usize>,
94        column: Option<usize>,
95    },
96}
97
98impl Delta {
99    /// Where `at` ends up, and `None` when the block under it went away.
100    pub(crate) fn cursor(&self, at: Cursor) -> Option<Cursor> {
101        match self {
102            Self::CellsMoved { block, from, to } => {
103                let mut at = at;
104                if at.block == *block
105                    && let Part::Cell { row, column } = &mut at.part
106                {
107                    let (index, from) = match from {
108                        crate::editor::Line::Row(from) => (row, *from),
109                        crate::editor::Line::Column(from) => (column, *from),
110                    };
111                    *index = if *index == from {
112                        *to
113                    } else if from < *index && *index <= *to {
114                        *index - 1
115                    } else if *to <= *index && *index < from {
116                        *index + 1
117                    } else {
118                        *index
119                    };
120                }
121                Some(at)
122            }
123            Self::Spliced(splice) => {
124                let (start, end) = splice.removed.ordered();
125                if at < start {
126                    return Some(at);
127                }
128                // Inside what went, the seam is the only place left to be.
129                if at <= end {
130                    return Some(splice.caret);
131                }
132                // Past it in the same text, the seam moved by what replaced it;
133                // further down the document, only the block count moved.
134                if at.block == end.block && at.part == end.part {
135                    return Some(Cursor {
136                        offset: splice.caret.offset + (at.offset - end.offset),
137                        ..splice.caret
138                    });
139                }
140                Some(Cursor {
141                    block: at.block.checked_add_signed(splice.blocks)?,
142                    ..at
143                })
144            }
145            Self::Moved { at: span, to } => {
146                if span.contains(&at.block) {
147                    return Some(Cursor {
148                        block: (*to)? + (at.block - span.start),
149                        ..at
150                    });
151                }
152                // Drained before it was put back, and `to` is already counted
153                // against the hole that left — so this is too.
154                let pulled = if at.block >= span.end {
155                    at.block - span.len()
156                } else {
157                    at.block
158                };
159                let block = match to {
160                    Some(to) if pulled >= *to => pulled + span.len(),
161                    _ => pulled,
162                };
163                Some(Cursor { block, ..at })
164            }
165            Self::Cells { block, row, column } => Some(match at.part {
166                Part::Cell { row: r, column: c } if at.block == *block => {
167                    let past = |line: usize, opened: Option<usize>| {
168                        line + usize::from(opened.is_some_and(|opened| line >= opened))
169                    };
170                    Cursor {
171                        part: Part::Cell {
172                            row: past(r, *row),
173                            column: past(c, *column),
174                        },
175                        ..at
176                    }
177                }
178                _ => at,
179            }),
180            Self::CellsRemoved { block, row, column } => match at.part {
181                Part::Cell { row: r, column: c } if at.block == *block => {
182                    if Some(r) == *row || Some(c) == *column {
183                        return None;
184                    }
185                    let past = |line: usize, removed: Option<usize>| {
186                        line - usize::from(removed.is_some_and(|removed| line > removed))
187                    };
188                    Some(Cursor {
189                        part: Part::Cell {
190                            row: past(r, *row),
191                            column: past(c, *column),
192                        },
193                        ..at
194                    })
195                }
196                _ => Some(at),
197            },
198            Self::Opened { at: opened, count } => Some(Cursor {
199                block: if at.block >= *opened {
200                    at.block + count
201                } else {
202                    at.block
203                },
204                ..at
205            }),
206        }
207    }
208}