Skip to main content

lexical_ui/table/
table_selection.rs

1//! `LexicalTableSelection.ts`: `TableSelection`, `$isTableSelection`,
2//! `$createTableSelection`, `$createTableSelectionFrom` and
3//! `$visitRecursively`. A table selection is the core's
4//! `Selection::Table`, read and changed through `SelectionRef` as the other
5//! selections are.
6
7use super::table_cell_node::{TableCellHeaderStates, create_table_cell_node, is_table_cell_node};
8use super::table_node::{create_table_node, is_table_node};
9use super::table_row_node::{create_table_row_node, is_table_row_node};
10use super::table_selection_helpers::find_table_node;
11use super::table_utils::{
12    compute_table_cell_rect_boundary, compute_table_map, get_table_cell_node_rect,
13    insert_table_into_grid, map_at,
14};
15use crate::LexicalError;
16use crate::constants::{TEXT_TYPE_TO_FORMAT, lookup};
17use crate::error::invariant;
18use crate::lexical_selection::{Point, PointType, Selection, SelectionRef, get_selection};
19use crate::lexical_utils::get_node_by_key;
20use crate::node::{NodeKey, NodeRef};
21use crate::nodes::paragraph::{ParagraphNode, create_paragraph_node};
22use crate::nodes::text::create_text_node;
23use crate::selection_insert_nodes::find_matching_parent;
24use crate::updates::is_currently_read_only_mode;
25
26/// `TableSelection`'s fields: the table, and the anchor and focus cells as
27/// element points.
28#[derive(Clone, Debug)]
29pub struct TableSelection {
30    pub table_key: NodeKey,
31    pub anchor: Point,
32    pub focus: Point,
33    pub(crate) dirty: bool,
34    /// `_cachedNodes`.
35    pub(crate) cached_nodes: Option<Vec<NodeRef>>,
36}
37
38/// `TableSelectionShape`.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct TableSelectionShape {
41    pub from_x: usize,
42    pub from_y: usize,
43    pub to_x: usize,
44    pub to_y: usize,
45}
46
47impl TableSelection {
48    /// `new TableSelection(tableKey, anchor, focus)`.
49    pub fn new(table_key: impl Into<NodeKey>, anchor: Point, focus: Point) -> Self {
50        Self {
51            table_key: table_key.into(),
52            anchor,
53            focus,
54            dirty: false,
55            cached_nodes: None,
56        }
57    }
58
59    /// `is(selection)`.
60    pub fn is(&self, other: &TableSelection) -> bool {
61        self.table_key == other.table_key
62            && self.anchor == other.anchor
63            && self.focus == other.focus
64    }
65
66    /// `set(tableKey, anchorCellKey, focusCellKey)`.
67    pub fn set(&mut self, table_key: &str, anchor_cell_key: &str, focus_cell_key: &str) {
68        self.dirty = self.dirty
69            || table_key != self.table_key
70            || anchor_cell_key != self.anchor.key
71            || focus_cell_key != self.focus.key;
72        self.table_key = table_key.to_owned();
73        self.anchor.key = anchor_cell_key.to_owned();
74        self.focus.key = focus_cell_key.to_owned();
75        self.cached_nodes = None;
76    }
77
78    /// `isValid()`: element points on nodes that exist, in a table.
79    pub fn is_valid(&self) -> bool {
80        if self.table_key == "root"
81            || self.anchor.key == "root"
82            || self.anchor.point_type != PointType::Element
83            || self.focus.key == "root"
84            || self.focus.point_type != PointType::Element
85        {
86            return false;
87        }
88        get_node_by_key(&self.table_key).is_some()
89            && get_node_by_key(&self.anchor.key).is_some()
90            && get_node_by_key(&self.focus.key).is_some()
91    }
92}
93
94/// `$getCellNodes(tableSelection)`: the anchor and focus cells and their
95/// table.
96struct CellNodes {
97    anchor_cell: NodeRef,
98    anchor_table: NodeRef,
99    focus_cell: NodeRef,
100}
101
102fn get_cell_nodes(selection: &TableSelection) -> Result<CellNodes, LexicalError> {
103    let resolve = |k: &str, point: &Point| -> Result<(NodeRef, NodeRef), LexicalError> {
104        let node = point.get_node()?;
105        let cell_node = find_matching_parent(&node, is_table_cell_node);
106        invariant!(
107            cell_node.is_some(),
108            "Expected TableSelection {k} to be (or a child of) TableCellNode, got key {} of type {}",
109            node.get_key(),
110            node.get_type()
111        );
112        let cell_node = cell_node.expect("checked");
113        let row_node = cell_node.get_parent().filter(is_table_row_node);
114        invariant!(
115            row_node.is_some(),
116            "Expected TableSelection {k} cell parent to be a TableRowNode"
117        );
118        let table_node = row_node
119            .expect("checked")
120            .get_parent()
121            .filter(is_table_node);
122        invariant!(
123            table_node.is_some(),
124            "Expected TableSelection {k} row parent to be a TableNode"
125        );
126        Ok((cell_node, table_node.expect("checked")))
127    };
128    let (anchor_cell, anchor_table) = resolve("anchor", &selection.anchor)?;
129    let (focus_cell, focus_table) = resolve("focus", &selection.focus)?;
130    invariant!(
131        anchor_table == focus_table,
132        "Expected TableSelection anchor and focus to be in the same table"
133    );
134    Ok(CellNodes {
135        anchor_cell,
136        anchor_table,
137        focus_cell,
138    })
139}
140
141/// `$isTableSelection(selection)`.
142pub fn is_table_selection(selection: Option<&SelectionRef>) -> bool {
143    selection.is_some_and(SelectionRef::is_table)
144}
145
146/// `$createTableSelection()`, deprecated upstream: a table selection at
147/// the root, which [`TableSelection::is_valid`] rejects.
148pub fn create_table_selection() -> SelectionRef {
149    SelectionRef::new(Selection::Table(TableSelection::new(
150        "root",
151        Point::new("root", 0, PointType::Element),
152        Point::new("root", 0, PointType::Element),
153    )))
154}
155
156/// `$createTableSelectionFrom(tableNode, anchorCell, focusCell)`: a table
157/// selection from `anchor_cell` to `focus_cell`, a clone of the current one
158/// when it is a table selection. It checks, as JS does in DEV builds, that
159/// the table is attached and holds both cells.
160pub fn create_table_selection_from(
161    table_node: &NodeRef,
162    anchor_cell: &NodeRef,
163    focus_cell: &NodeRef,
164) -> Result<SelectionRef, LexicalError> {
165    let table_node_key = table_node.get_key();
166    invariant!(
167        table_node.is_attached(),
168        "$createTableSelectionFrom: tableNode {table_node_key} is not attached"
169    );
170    invariant!(
171        find_table_node(anchor_cell).as_ref() == Some(table_node),
172        "$createTableSelectionFrom: anchorCell {} is not in table {table_node_key}",
173        anchor_cell.get_key()
174    );
175    invariant!(
176        find_table_node(focus_cell).as_ref() == Some(table_node),
177        "$createTableSelectionFrom: focusCell {} is not in table {table_node_key}",
178        focus_cell.get_key()
179    );
180    let prev_selection = get_selection();
181    let next_selection = match prev_selection.filter(SelectionRef::is_table) {
182        Some(prev) => prev.clone_selection(),
183        None => create_table_selection(),
184    };
185    next_selection
186        .with_table(|t| t.set(table_node_key, anchor_cell.get_key(), focus_cell.get_key()));
187    Ok(next_selection)
188}
189
190/// `$visitRecursively(node, $visit)`: depth first, not into the children of
191/// a node `visit` returns false for.
192pub fn visit_recursively(node: &NodeRef, mut visit: impl FnMut(&NodeRef) -> bool) {
193    let mut stack: Vec<Vec<NodeRef>> = vec![vec![node.clone()]];
194    while let Some(current_array) = stack.last_mut() {
195        match current_array.pop() {
196            None => {
197                stack.pop();
198            }
199            Some(current_node) => {
200                if visit(&current_node) && current_node.is_element() {
201                    stack.push(current_node.get_children());
202                }
203            }
204        }
205    }
206}
207
208/// `TableSelection.getNodes()`: the table, then each row and the cells of
209/// the selected rectangle with their descendants, once each.
210pub(crate) fn get_nodes(selection: &SelectionRef) -> Result<Vec<NodeRef>, LexicalError> {
211    let table = selection.table().expect("a table selection");
212    if !table.is_valid() {
213        return Ok(Vec::new());
214    }
215    if let Some(cached) = table.cached_nodes {
216        return Ok(cached);
217    }
218    let CellNodes {
219        anchor_table: table_node,
220        anchor_cell,
221        focus_cell,
222    } = get_cell_nodes(&table)?;
223    let focus_cell_grid = focus_cell.get_parents().get(1).cloned();
224    if focus_cell_grid.as_ref() != Some(&table_node) {
225        if !table_node.is_parent_of(&focus_cell) {
226            // The focus is on a higher grid level than the anchor.
227            let grid_parent = table_node.get_parent();
228            invariant!(
229                grid_parent.is_some(),
230                "Expected gridParent to have a parent"
231            );
232            let grid_parent = grid_parent.expect("checked");
233            selection.with_table(|t| {
234                t.set(
235                    &table.table_key,
236                    grid_parent.get_key(),
237                    focus_cell.get_key(),
238                )
239            });
240        } else {
241            // The anchor is on a higher grid level than the focus.
242            let focus_cell_parent = focus_cell_grid.and_then(|g| g.get_parent());
243            invariant!(
244                focus_cell_parent.is_some(),
245                "Expected focusCellParent to have a parent"
246            );
247            let focus_cell_parent = focus_cell_parent.expect("checked");
248            selection.with_table(|t| {
249                t.set(
250                    &table.table_key,
251                    focus_cell.get_key(),
252                    focus_cell_parent.get_key(),
253                )
254            });
255        }
256        return get_nodes(selection);
257    }
258    let (map, cell_a_map, cell_b_map) = compute_table_map(&table_node, &anchor_cell, &focus_cell)?;
259    let b = compute_table_cell_rect_boundary(&map, &cell_a_map, &cell_b_map);
260    let mut nodes: Vec<NodeRef> = vec![table_node.clone()];
261    let mut seen: std::collections::HashSet<String> =
262        std::collections::HashSet::from([table_node.get_key().to_owned()]);
263    let mut last_row: Option<NodeRef> = None;
264    for i in b.min_row..=b.max_row {
265        for j in b.min_column..=b.max_column {
266            let cell = map_at(&map, i as i64, j as i64)?.cell.clone();
267            let current_row = cell.get_parent().filter(is_table_row_node);
268            invariant!(
269                current_row.is_some(),
270                "Expected TableCellNode parent to be a TableRowNode"
271            );
272            let current_row = current_row.expect("checked");
273            if last_row.as_ref() != Some(&current_row) {
274                // `nodeMap.set` keeps a key's first place.
275                if seen.insert(current_row.get_key().to_owned()) {
276                    nodes.push(current_row.clone());
277                }
278                last_row = Some(current_row);
279            }
280            if !seen.contains(cell.get_key()) {
281                visit_recursively(&cell, |child| {
282                    if seen.insert(child.get_key().to_owned()) {
283                        nodes.push(child.clone());
284                    }
285                    true
286                });
287            }
288        }
289    }
290    if !is_currently_read_only_mode() {
291        selection.with_table(|t| t.cached_nodes = Some(nodes.clone()));
292    }
293    Ok(nodes)
294}
295
296/// `TableSelection.getTextContent()`: the selected cells' text, a tab
297/// between the cells of a row and a line break after each row.
298pub(crate) fn get_text_content(selection: &SelectionRef) -> Result<String, LexicalError> {
299    let nodes: Vec<NodeRef> = get_nodes(selection)?
300        .into_iter()
301        .filter(is_table_cell_node)
302        .collect();
303    let mut text_content = String::new();
304    for (i, node) in nodes.iter().enumerate() {
305        let row = node.get_parent();
306        let next_row = nodes.get(i + 1).and_then(NodeRef::get_parent);
307        text_content.push_str(&node.get_text_content());
308        text_content.push(if next_row != row { '\n' } else { '\t' });
309    }
310    Ok(text_content)
311}
312
313/// `TableSelection.insertRawText(text)`: the text as tab-separated
314/// values, pasted into the grid at the anchor cell.
315pub(crate) fn insert_raw_text(selection: &SelectionRef, text: &str) -> Result<(), LexicalError> {
316    if text.is_empty() {
317        return Ok(());
318    }
319    let table = selection.table().expect("a table selection");
320    let trimmed = text.strip_suffix('\n').unwrap_or(text);
321    let table_node = create_table_node();
322    for line in trimmed.split('\n') {
323        let row_node = create_table_row_node(None);
324        for cell_text in line.split('\t') {
325            let cell_node = create_table_cell_node(TableCellHeaderStates::NO_STATUS, 1.0, None);
326            let paragraph = create_paragraph_node();
327            if !cell_text.is_empty() {
328                paragraph.append(&[create_text_node(cell_text)])?;
329            }
330            cell_node.append(&[paragraph])?;
331            row_node.append(&[cell_node])?;
332        }
333        table_node.append(&[row_node])?;
334    }
335    let CellNodes { anchor_cell, .. } = get_cell_nodes(&table)?;
336    let range_selection = anchor_cell.select(Some(0), Some(anchor_cell.get_children_size()))?;
337    insert_table_into_grid(&table_node, &range_selection)?;
338    Ok(())
339}
340
341/// `TableSelection.insertNodes(nodes)`: into the focus cell, replacing its
342/// content.
343pub(crate) fn insert_nodes(
344    selection: &SelectionRef,
345    nodes: Vec<NodeRef>,
346) -> Result<(), LexicalError> {
347    let table = selection.table().expect("a table selection");
348    let focus_node = table.focus.get_node()?;
349    invariant!(
350        focus_node.is_element(),
351        "Expected TableSelection focus to be an ElementNode"
352    );
353    let range = focus_node.select(Some(0), Some(focus_node.get_children_size()))?;
354    crate::selection_insert_nodes::normalize_selection(&range)?;
355    range.insert_nodes(nodes)
356}
357
358impl SelectionRef {
359    /// `TableSelection.hasFormat(type)`: whether the first paragraph of any
360    /// selected cell has the format. False for any other selection.
361    pub fn table_has_format(&self, format_type: &str) -> Result<bool, LexicalError> {
362        if !self.is_table() {
363            return Ok(false);
364        }
365        let mut format = 0i32;
366        for cell in get_nodes(self)?.iter().filter(|n| is_table_cell_node(n)) {
367            if let Some(paragraph) = cell
368                .get_first_child()
369                .filter(|p| p.get_latest().is::<ParagraphNode>())
370            {
371                format |= crate::nodes::text::to_int32(paragraph.element_data().get_text_format());
372            }
373        }
374        let flag = lookup(TEXT_TYPE_TO_FORMAT, format_type).unwrap_or(0);
375        Ok(format & flag != 0)
376    }
377
378    /// `TableSelection.getShape()`, deprecated upstream: the rectangle of the
379    /// anchor and focus cells' positions.
380    pub fn get_table_shape(&self) -> Result<Option<TableSelectionShape>, LexicalError> {
381        let Some(table) = self.table() else {
382            return Ok(None);
383        };
384        let CellNodes {
385            anchor_cell,
386            focus_cell,
387            ..
388        } = get_cell_nodes(&table)?;
389        let a = get_table_cell_node_rect(&anchor_cell)?
390            .ok_or_else(|| LexicalError::new("getCellRect: expected to find AnchorNode"))?;
391        let f = get_table_cell_node_rect(&focus_cell)?
392            .ok_or_else(|| LexicalError::new("getCellRect: expected to find focusCellNode"))?;
393        let start_x = a.column_index.min(f.column_index);
394        let stop_x = (a.column_index + a.col_span - 1).max(f.column_index + f.col_span - 1);
395        let start_y = a.row_index.min(f.row_index);
396        let stop_y = (a.row_index + a.row_span - 1).max(f.row_index + f.row_span - 1);
397        Ok(Some(TableSelectionShape {
398            from_x: start_x.min(stop_x),
399            from_y: start_y.min(stop_y),
400            to_x: start_x.max(stop_x),
401            to_y: start_y.max(stop_y),
402        }))
403    }
404}