Skip to main content

lexical_ui/table/
table_row_node.rs

1//! `LexicalTableRowNode.ts`: `TableRowNode`, `$createTableRowNode` and
2//! `$isTableRowNode`.
3
4use super::generated_json::{
5    export_compact_table_row_node, export_table_row_node, update_table_row_node,
6};
7use crate::LexicalError;
8use crate::json::Object;
9use crate::lexical_selection::SelectionRef;
10use crate::lexical_utils::{set_node_key, with_writable};
11use crate::node::{LexicalNode, NodeBase, NodeRef};
12use crate::nodes::element::{self, ElementData};
13use crate::schema::{
14    NodeSchema, NumberValueOptions, node_schema, number_value, optional, with_field,
15};
16
17/// `TableRowNode`: a row of a [`TableNode`](super::TableNode), holding
18/// [`TableCellNode`](super::TableCellNode)s.
19#[derive(Clone, Debug, Default)]
20pub struct TableRowNode {
21    base: NodeBase,
22    pub(super) element: ElementData,
23    /// `__height`.
24    pub(super) height: Option<f64>,
25}
26
27impl TableRowNode {
28    /// `__height`.
29    pub fn height(&self) -> Option<f64> {
30        self.height
31    }
32}
33
34/// `$createTableRowNode(height)`.
35pub fn create_table_row_node(height: Option<f64>) -> NodeRef {
36    crate::lexical_utils::replaced(set_node_key(Box::new(TableRowNode {
37        height,
38        ..TableRowNode::default()
39    })))
40}
41
42/// `$isTableRowNode(node)`.
43pub fn is_table_row_node(node: &NodeRef) -> bool {
44    node.get_latest().is::<TableRowNode>()
45}
46
47impl NodeRef {
48    /// `TableRowNode.setHeight(height)`; does nothing to any other node.
49    pub fn set_row_height(&self, height: Option<f64>) {
50        if is_table_row_node(self) {
51            with_writable(self.get_key(), |n| {
52                n.downcast_mut::<TableRowNode>()
53                    .expect("a table row")
54                    .height = height;
55            });
56        }
57    }
58
59    /// `TableRowNode.getHeight()`.
60    pub fn get_row_height(&self) -> Option<f64> {
61        self.get_latest()
62            .downcast_ref::<TableRowNode>()
63            .and_then(|r| r.height)
64    }
65}
66
67thread_local! {
68    static TABLE_ROW_NODE_SCHEMA: NodeSchema =
69        build_table_row_node_schema().expect("TableRowNode's schema");
70}
71
72/// `tableRowNodeSchema`: `height`, optional.
73pub fn table_row_node_schema() -> NodeSchema {
74    TABLE_ROW_NODE_SCHEMA.with(Clone::clone)
75}
76
77fn build_table_row_node_schema() -> Result<NodeSchema, LexicalError> {
78    node_schema(vec![(
79        "height",
80        with_field(
81            optional(number_value(0.0, NumberValueOptions::default())?, false)?,
82            |n: &TableRowNode| &n.height,
83            |n: &mut TableRowNode| &mut n.height,
84        )?,
85    )])
86}
87
88impl LexicalNode for TableRowNode {
89    fn json_schema_chain(&self) -> Vec<NodeSchema> {
90        vec![table_row_node_schema(), element::element_node_schema()]
91    }
92
93    fn get_type(&self) -> &'static str {
94        "tablerow"
95    }
96    fn base(&self) -> &NodeBase {
97        &self.base
98    }
99    fn base_mut(&mut self) -> &mut NodeBase {
100        &mut self.base
101    }
102    fn element(&self) -> Option<&ElementData> {
103        Some(&self.element)
104    }
105    fn element_mut(&mut self) -> Option<&mut ElementData> {
106        Some(&mut self.element)
107    }
108
109    /// `TableRowNode.extractWithChild(child, selection, destination)`: a
110    /// copy to HTML takes the row with its cells.
111    fn extract_with_child(
112        &self,
113        _: &NodeRef,
114        _: &NodeRef,
115        _: Option<&SelectionRef>,
116        destination: &str,
117    ) -> Result<bool, LexicalError> {
118        Ok(destination == "html")
119    }
120
121    /// `TableRowNode.isShadowRoot()`.
122    fn is_shadow_root(&self) -> bool {
123        true
124    }
125
126    /// `TableRowNode.canBeEmpty()`.
127    fn can_be_empty(&self) -> bool {
128        false
129    }
130
131    /// `TableRowNode.canIndent()`.
132    fn can_indent(&self) -> bool {
133        false
134    }
135
136    /// `TableRowNode.updateDOM(prevNode)`.
137    fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
138        prev_node
139            .as_any()
140            .downcast_ref::<TableRowNode>()
141            .is_none_or(|prev| prev.height != self.height)
142    }
143
144    /// `TableRowNode.createDOM(config)`: a `<tr>` with the height and the
145    /// theme's `tableRow` class names.
146    #[cfg(feature = "html")]
147    fn create_dom(
148        &self,
149        _this: &NodeRef,
150        config: &crate::EditorConfig,
151        _editor: &crate::Editor,
152    ) -> Result<crate::dom::DomNode, LexicalError> {
153        use crate::lexical_dom::{add_theme_class_names, get_document};
154        let element = get_document().create_element("tr");
155        if let Some(height) = self.height.filter(|h| *h != 0.0 && !h.is_nan()) {
156            element.style().set_property(
157                "height",
158                &format!("{}px", crate::json::number_to_string(height)),
159                "",
160            );
161        }
162        add_theme_class_names(&element, &config.theme, "tableRow");
163        Ok(element)
164    }
165
166    #[cfg(feature = "html")]
167    fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
168        use crate::lexical_dom::importer;
169        Some(vec![(
170            "tr".to_owned(),
171            importer(0, convert_table_row_element),
172        )])
173    }
174
175    /// `exportTableRowNode` and `exportCompactTableRowNode`.
176    fn generated_export_json(&self, compact: bool) -> Option<Object> {
177        Some(if compact {
178            export_compact_table_row_node(self)
179        } else {
180            export_table_row_node(self)
181        })
182    }
183
184    /// `updateTableRowNode`.
185    fn generated_update_from_json(&mut self, json: &Object) -> bool {
186        update_table_row_node(self, json);
187        true
188    }
189}
190
191/// `$convertTableRowElement(domNode)`: a row with the element's pixel
192/// height and direction, keeping only the cells among its descendants.
193#[cfg(feature = "html")]
194fn convert_table_row_element(
195    dom_node: &crate::dom::DomNode,
196) -> Result<Option<crate::lexical_dom::DomConversionOutput>, LexicalError> {
197    use super::constants::parse_pixel_value;
198    use super::table_cell_node::is_table_cell_node;
199    use crate::lexical_dom::{DomConversionOutput, set_direction_from_dom};
200    let height = parse_pixel_value(&dom_node.style().get_property_value("height"));
201    let node = create_table_row_node(height);
202    set_direction_from_dom(&node, dom_node);
203    Ok(Some(DomConversionOutput {
204        after: Some(Box::new(|children: Vec<NodeRef>| {
205            Ok(crate::utils::descendants_matching(
206                &children,
207                is_table_cell_node,
208            ))
209        })),
210        ..DomConversionOutput::node(Some(node))
211    }))
212}