1use super::generated_json::{
5 export_compact_table_cell_node, export_table_cell_node, update_table_cell_node,
6};
7use crate::LexicalError;
8use crate::json::{Object, Value};
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, enum_value, node_schema, nullable, number_value, optional,
15 schema_getter, schema_setter, string_value, with_accessors, with_field,
16};
17
18#[derive(Clone, Copy, Debug)]
21pub struct TableCellHeaderStates;
22
23impl TableCellHeaderStates {
24 pub const NO_STATUS: i32 = 0;
25 pub const ROW: i32 = 1;
26 pub const COLUMN: i32 = 2;
27 pub const BOTH: i32 = 3;
28}
29
30#[derive(Clone, Debug)]
33pub struct TableCellNode {
34 base: NodeBase,
35 pub(super) element: ElementData,
36 pub(super) col_span: f64,
38 pub(super) row_span: f64,
40 pub(super) header_state: i32,
42 pub(super) width: Option<f64>,
44 pub(super) background_color: Option<String>,
46 pub(super) vertical_align: Option<String>,
49}
50
51impl Default for TableCellNode {
52 fn default() -> Self {
54 TableCellNode {
55 base: NodeBase::default(),
56 element: ElementData::default(),
57 col_span: 1.0,
58 row_span: 1.0,
59 header_state: TableCellHeaderStates::NO_STATUS,
60 width: None,
61 background_color: None,
62 vertical_align: None,
63 }
64 }
65}
66
67impl TableCellNode {
68 pub fn serialized_vertical_align(&self) -> Option<&str> {
71 self.vertical_align
72 .as_deref()
73 .filter(|v| is_valid_vertical_align(Some(v)))
74 }
75
76 pub fn has_header(&self) -> bool {
78 self.header_state != TableCellHeaderStates::NO_STATUS
79 }
80
81 pub fn get_tag(&self) -> &'static str {
83 if self.has_header() { "th" } else { "td" }
84 }
85
86 pub fn col_span(&self) -> f64 {
88 self.col_span
89 }
90
91 pub fn row_span(&self) -> f64 {
93 self.row_span
94 }
95
96 pub fn header_state(&self) -> i32 {
98 self.header_state
99 }
100
101 pub fn width(&self) -> Option<f64> {
103 self.width
104 }
105
106 pub fn background_color(&self) -> Option<&str> {
108 self.background_color.as_deref()
109 }
110
111 pub fn vertical_align(&self) -> Option<&str> {
113 self.vertical_align.as_deref()
114 }
115}
116
117pub(super) fn is_valid_vertical_align(vertical_align: Option<&str>) -> bool {
119 matches!(vertical_align, Some("middle" | "bottom"))
120}
121
122pub fn create_table_cell_node(header_state: i32, col_span: f64, width: Option<f64>) -> NodeRef {
124 crate::lexical_utils::replaced(set_node_key(Box::new(TableCellNode {
125 header_state,
126 col_span,
127 width,
128 ..TableCellNode::default()
129 })))
130}
131
132pub fn create_default_table_cell_node() -> NodeRef {
134 create_table_cell_node(TableCellHeaderStates::NO_STATUS, 1.0, None)
135}
136
137pub fn is_table_cell_node(node: &NodeRef) -> bool {
139 node.get_latest().is::<TableCellNode>()
140}
141
142fn read<R>(node: &NodeRef, f: impl FnOnce(&TableCellNode) -> R) -> Option<R> {
143 node.get_latest().downcast_ref::<TableCellNode>().map(f)
144}
145
146pub(super) fn with_cell(node: &NodeRef, f: impl FnOnce(&mut TableCellNode)) {
148 if is_table_cell_node(node) {
149 with_writable(node.get_key(), |n| {
150 f(n.downcast_mut::<TableCellNode>().expect("a table cell"))
151 });
152 }
153}
154
155impl NodeRef {
156 pub fn get_col_span(&self) -> f64 {
158 read(self, |c| c.col_span).unwrap_or(1.0)
159 }
160
161 pub fn set_col_span(&self, col_span: f64) {
163 with_cell(self, |c| c.col_span = col_span);
164 }
165
166 pub fn get_row_span(&self) -> f64 {
168 read(self, |c| c.row_span).unwrap_or(1.0)
169 }
170
171 pub fn set_row_span(&self, row_span: f64) {
173 with_cell(self, |c| c.row_span = row_span);
174 }
175
176 pub fn get_table_cell_tag(&self) -> Option<&'static str> {
178 read(self, TableCellNode::get_tag)
179 }
180
181 pub fn set_header_styles(&self, header_state: i32, mask: i32) {
184 with_cell(self, |c| {
185 c.header_state = (header_state & mask) | (c.header_state & !mask);
186 });
187 }
188
189 pub fn get_header_styles(&self) -> i32 {
191 read(self, |c| c.header_state).unwrap_or(TableCellHeaderStates::NO_STATUS)
192 }
193
194 pub fn set_cell_width(&self, width: Option<f64>) {
196 with_cell(self, |c| c.width = width);
197 }
198
199 pub fn get_cell_width(&self) -> Option<f64> {
201 read(self, |c| c.width).flatten()
202 }
203
204 pub fn get_background_color(&self) -> Option<String> {
206 read(self, |c| c.background_color.clone()).flatten()
207 }
208
209 pub fn set_background_color(&self, background_color: Option<&str>) {
211 with_cell(self, |c| {
212 c.background_color = background_color.map(str::to_owned)
213 });
214 }
215
216 pub fn get_vertical_align(&self) -> Option<String> {
218 read(self, |c| c.vertical_align.clone()).flatten()
219 }
220
221 pub fn set_vertical_align(&self, vertical_align: Option<&str>) {
224 with_cell(self, |c| {
225 c.vertical_align = vertical_align.filter(|v| !v.is_empty()).map(str::to_owned);
226 });
227 }
228
229 pub fn toggle_header_style(&self, header_state_to_toggle: i32) {
232 with_cell(self, |c| {
233 if (c.header_state & header_state_to_toggle) == header_state_to_toggle {
234 c.header_state &= !header_state_to_toggle;
235 } else {
236 c.header_state |= header_state_to_toggle;
237 }
238 });
239 }
240
241 pub fn has_header_state(&self, header_state: i32) -> bool {
243 (self.get_header_styles() & header_state) == header_state
244 }
245
246 pub fn has_header(&self) -> bool {
248 read(self, TableCellNode::has_header).unwrap_or(false)
249 }
250}
251
252thread_local! {
253 static TABLE_CELL_NODE_SCHEMA: NodeSchema =
254 build_table_cell_node_schema().expect("TableCellNode's schema");
255}
256
257pub fn table_cell_node_schema() -> NodeSchema {
262 TABLE_CELL_NODE_SCHEMA.with(Clone::clone)
263}
264
265fn build_table_cell_node_schema() -> Result<NodeSchema, LexicalError> {
266 let span = || {
267 number_value(
268 1.0,
269 NumberValueOptions {
270 integer: true,
271 min: Some(1.0),
272 ..NumberValueOptions::default()
273 },
274 )
275 };
276 node_schema(vec![
277 (
278 "backgroundColor",
279 with_field(
280 nullable(string_value(""), true)?,
281 |n: &TableCellNode| &n.background_color,
282 |n: &mut TableCellNode| &mut n.background_color,
283 )?,
284 ),
285 (
286 "colSpan",
287 with_field(
288 span()?,
289 |n: &TableCellNode| &n.col_span,
290 |n: &mut TableCellNode| &mut n.col_span,
291 )?,
292 ),
293 (
294 "headerState",
295 with_accessors(
296 number_value(0.0, NumberValueOptions::default())?,
297 Some(schema_getter(|n: &TableCellNode| {
298 f64::from(n.header_state).into()
299 })),
300 Some(schema_setter(|n: &mut TableCellNode, value| {
301 let header_state = crate::nodes::text::to_int32(value.as_f64().unwrap_or(0.0));
302 let mask = TableCellHeaderStates::BOTH;
303 n.header_state = (header_state & mask) | (n.header_state & !mask);
304 })),
305 )?,
306 ),
307 (
308 "rowSpan",
309 with_field(
310 span()?,
311 |n: &TableCellNode| &n.row_span,
312 |n: &mut TableCellNode| &mut n.row_span,
313 )?,
314 ),
315 (
316 "verticalAlign",
317 with_accessors(
318 enum_value(
319 vec![Value::Undefined, "middle".into(), "bottom".into()],
320 None,
321 )?,
322 Some(schema_getter(|n: &TableCellNode| {
323 n.serialized_vertical_align()
324 .map_or(Value::Undefined, Value::from)
325 })),
326 Some(schema_setter(|n: &mut TableCellNode, value| {
327 n.vertical_align = value.as_str().map(str::to_owned);
328 })),
329 )?,
330 ),
331 (
332 "width",
333 with_field(
334 optional(number_value(0.0, NumberValueOptions::default())?, true)?,
335 |n: &TableCellNode| &n.width,
336 |n: &mut TableCellNode| &mut n.width,
337 )?,
338 ),
339 ])
340}
341
342impl LexicalNode for TableCellNode {
343 fn json_schema_chain(&self) -> Vec<NodeSchema> {
344 vec![table_cell_node_schema(), element::element_node_schema()]
345 }
346
347 fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
349 use crate::structure::{NodeChildrenConfig, NodeConfigLink, StaticNodeConfig};
350 vec![NodeConfigLink::new(
351 "tablecell",
352 StaticNodeConfig {
353 children: Some(NodeChildrenConfig::Block),
354 ..StaticNodeConfig::default()
355 },
356 )]
357 }
358
359 fn get_type(&self) -> &'static str {
360 "tablecell"
361 }
362 fn base(&self) -> &NodeBase {
363 &self.base
364 }
365 fn base_mut(&mut self) -> &mut NodeBase {
366 &mut self.base
367 }
368 fn element(&self) -> Option<&ElementData> {
369 Some(&self.element)
370 }
371 fn element_mut(&mut self) -> Option<&mut ElementData> {
372 Some(&mut self.element)
373 }
374
375 fn is_shadow_root(&self) -> bool {
377 true
378 }
379
380 fn collapse_at_start(&self, _: &NodeRef, _: &SelectionRef) -> Result<bool, LexicalError> {
383 Ok(true)
384 }
385
386 fn can_be_empty(&self) -> bool {
388 false
389 }
390
391 fn can_indent(&self) -> bool {
393 false
394 }
395
396 fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
399 let Some(prev) = prev_node.as_any().downcast_ref::<TableCellNode>() else {
400 return true;
401 };
402 prev.header_state != self.header_state
403 || prev.width != self.width
404 || prev.col_span != self.col_span
405 || prev.row_span != self.row_span
406 || prev.background_color != self.background_color
407 || prev.vertical_align != self.vertical_align
408 }
409
410 #[cfg(feature = "html")]
412 fn create_dom(
413 &self,
414 _this: &NodeRef,
415 config: &crate::EditorConfig,
416 _editor: &crate::Editor,
417 ) -> Result<crate::dom::DomNode, LexicalError> {
418 Ok(cell_dom::create_dom(self, &config.theme))
419 }
420
421 #[cfg(feature = "html")]
423 fn export_dom(
424 &self,
425 this: &NodeRef,
426 editor: &crate::Editor,
427 ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
428 cell_dom::export_dom(self, this, editor)
429 }
430
431 #[cfg(feature = "html")]
432 fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
433 use crate::lexical_dom::importer;
434 Some(vec![
435 (
436 "td".to_owned(),
437 importer(0, cell_dom::convert_table_cell_node_element),
438 ),
439 (
440 "th".to_owned(),
441 importer(0, cell_dom::convert_table_cell_node_element),
442 ),
443 ])
444 }
445
446 fn generated_export_json(&self, compact: bool) -> Option<Object> {
448 Some(if compact {
449 export_compact_table_cell_node(self)
450 } else {
451 export_table_cell_node(self)
452 })
453 }
454
455 fn generated_update_from_json(&mut self, json: &Object) -> bool {
457 update_table_cell_node(self, json);
458 true
459 }
460}
461
462#[cfg(feature = "html")]
463pub(super) mod cell_dom {
464 use super::{
465 TableCellHeaderStates, TableCellNode, create_table_cell_node, is_valid_vertical_align,
466 };
467 use crate::LexicalError;
468 use crate::dom::DomNode;
469 use crate::json::{Object, number_to_string};
470 use crate::lexical_dom::{
471 DomConversionOutput, DomExportOutput, add_class_names_to_element, set_direction_from_dom,
472 theme_string,
473 };
474 use crate::node::NodeRef;
475 use crate::nodes::paragraph::create_paragraph_node;
476 use crate::table::constants::{COLUMN_WIDTH, parse_pixel_value};
477 use crate::table::dom_helpers::{cell_index, col_span, row_index, row_span, unsigned_long};
478
479 pub(crate) fn create_dom(cell: &TableCellNode, theme: &Object) -> DomNode {
483 let element = crate::lexical_dom::get_document().create_element(cell.get_tag());
484 if let Some(width) = cell.width.filter(|w| *w != 0.0 && !w.is_nan()) {
485 element
486 .style()
487 .set_property("width", &format!("{}px", number_to_string(width)), "");
488 }
489 if cell.col_span > 1.0 {
490 element.set_attribute("colspan", &unsigned_long(cell.col_span).to_string());
491 }
492 if cell.row_span > 1.0 {
493 element.set_attribute("rowspan", &unsigned_long(cell.row_span).to_string());
494 }
495 if let Some(background_color) = &cell.background_color {
496 element
497 .style()
498 .set_property("background-color", background_color, "");
499 }
500 if is_valid_vertical_align(cell.vertical_align.as_deref()) {
501 element.style().set_property(
502 "vertical-align",
503 cell.vertical_align.as_deref().unwrap_or_default(),
504 "",
505 );
506 }
507 let mut classes: Vec<&str> = Vec::new();
508 if let Some(c) = theme_string(theme, "tableCell") {
509 classes.push(c);
510 }
511 if cell.has_header()
512 && let Some(c) = theme_string(theme, "tableCellHeader")
513 {
514 classes.push(c);
515 }
516 add_class_names_to_element(&element, &classes);
517 element
518 }
519
520 pub(crate) fn export_dom(
525 cell: &TableCellNode,
526 this: &NodeRef,
527 editor: &crate::Editor,
528 ) -> Result<DomExportOutput, LexicalError> {
529 let output = crate::nodes::element::export_dom(cell, this, editor)?;
530 if let Some(element) = output.element.as_ref().filter(|e| e.is_element()) {
531 element.set_attribute("data-temporary-table-cell-lexical-key", this.get_key());
532 let style = element.style();
533 style.set_property("border", "1px solid black", "");
534 if cell.col_span > 1.0 {
535 element.set_attribute("colspan", &unsigned_long(cell.col_span).to_string());
536 }
537 if cell.row_span > 1.0 {
538 element.set_attribute("rowspan", &unsigned_long(cell.row_span).to_string());
539 }
540 let width = cell
541 .width
542 .filter(|w| *w != 0.0 && !w.is_nan())
543 .unwrap_or(COLUMN_WIDTH);
544 style.set_property("width", &format!("{}px", number_to_string(width)), "");
545 style.set_property(
546 "vertical-align",
547 cell.vertical_align
548 .as_deref()
549 .filter(|v| !v.is_empty())
550 .unwrap_or("top"),
551 "",
552 );
553 style.set_property("text-align", "start", "");
554 if cell.background_color.is_none() && cell.has_header() {
555 style.set_property("background-color", "#f2f3f5", "");
556 }
557 }
558 Ok(output)
559 }
560
561 pub(crate) fn convert_table_cell_node_element(
567 dom_node: &DomNode,
568 ) -> Result<Option<DomConversionOutput>, LexicalError> {
569 let node_name = dom_node.node_name().to_ascii_lowercase();
570 let style = dom_node.style();
571 let width = parse_pixel_value(&style.get_property_value("width"));
572 let mut header_state = TableCellHeaderStates::NO_STATUS;
573 if node_name == "th" {
574 match dom_node.get_attribute("scope").as_deref() {
575 Some("col") => header_state = TableCellHeaderStates::COLUMN,
576 Some("row") => header_state = TableCellHeaderStates::ROW,
577 _ => {
578 let parent_row = dom_node.parent_element();
579 let is_in_header_row = parent_row.as_ref().is_some_and(|row| {
580 row.is_element()
581 && row.node_name().eq_ignore_ascii_case("tr")
582 && row.parent_element().is_some_and(|section| {
583 section.is_element()
584 && (section.node_name().eq_ignore_ascii_case("thead")
585 || row_index(row) == 0)
586 })
587 });
588 let is_first_column = cell_index(dom_node) == 0;
589 if is_in_header_row {
590 header_state |= TableCellHeaderStates::ROW;
591 }
592 if is_first_column {
593 header_state |= TableCellHeaderStates::COLUMN;
594 }
595 if header_state == TableCellHeaderStates::NO_STATUS {
596 header_state = TableCellHeaderStates::ROW;
597 }
598 }
599 }
600 }
601 let table_cell_node = create_table_cell_node(header_state, col_span(dom_node), width);
602 let row_span = row_span(dom_node);
603 super::with_cell(&table_cell_node, |c| c.row_span = row_span);
604 let background_color = style.get_property_value("background-color");
605 if !background_color.is_empty() {
606 super::with_cell(&table_cell_node, |c| {
607 c.background_color = Some(background_color.clone());
608 });
609 }
610 let vertical_align = style.get_property_value("vertical-align");
611 if is_valid_vertical_align(Some(&vertical_align)) {
612 super::with_cell(&table_cell_node, |c| {
613 c.vertical_align = Some(vertical_align.clone());
614 });
615 }
616 set_direction_from_dom(&table_cell_node, dom_node);
617
618 let text_decoration = style.get_property_value("text-decoration");
619 let text_decoration: Vec<&str> = text_decoration.split(' ').collect();
620 let font_weight = style.get_property_value("font-weight");
621 let has_bold_font_weight = font_weight == "700" || font_weight == "bold";
622 let has_linethrough_text_decoration = text_decoration.contains(&"line-through");
623 let has_italic_font_style = style.get_property_value("font-style") == "italic";
624 let has_underline_text_decoration = text_decoration.contains(&"underline");
625 let color = style.get_property_value("color");
626 Ok(Some(DomConversionOutput {
627 after: Some(Box::new(move |child_lexical_nodes: Vec<NodeRef>| {
628 let mut result: Vec<NodeRef> = Vec::new();
629 let mut paragraph_node: Option<NodeRef> = None;
630 let remove_single_line_break_node =
631 |paragraph_node: &Option<NodeRef>| -> Result<(), LexicalError> {
632 if let Some(paragraph_node) = paragraph_node {
633 let first_child = paragraph_node.get_first_child();
634 if let Some(first_child) = first_child
635 && first_child
636 .get_latest()
637 .is::<crate::nodes::line_break::LineBreakNode>()
638 && paragraph_node.get_children_size() == 1
639 {
640 first_child.remove(false)?;
641 }
642 }
643 Ok(())
644 };
645 for child in child_lexical_nodes {
646 let is_inline_or_decorator =
647 (child.is_element() || child.is_decorator()) && child.is_inline();
648 if is_inline_or_decorator
649 || child.is_text()
650 || child
651 .get_latest()
652 .is::<crate::nodes::line_break::LineBreakNode>()
653 {
654 if child.is_text() {
655 if has_bold_font_weight {
656 child.toggle_format("bold");
657 }
658 if has_linethrough_text_decoration {
659 child.toggle_format("strikethrough");
660 }
661 if has_italic_font_style {
662 child.toggle_format("italic");
663 }
664 if has_underline_text_decoration {
665 child.toggle_format("underline");
666 }
667 if !color.is_empty() {
668 let existing_style = child.text_data().get_style().to_owned();
669 if !existing_style.contains("color:") {
670 child.set_style(&format!("{existing_style}color: {color};"));
671 }
672 }
673 }
674 match ¶graph_node {
675 Some(paragraph) => {
676 paragraph.append(&[child])?;
677 }
678 None => {
679 let paragraph = create_paragraph_node();
680 paragraph.append(&[child])?;
681 result.push(paragraph.clone());
682 paragraph_node = Some(paragraph);
683 }
684 }
685 } else {
686 result.push(child);
687 remove_single_line_break_node(¶graph_node)?;
688 paragraph_node = None;
689 }
690 }
691 remove_single_line_break_node(¶graph_node)?;
692 if result.is_empty() {
693 result.push(create_paragraph_node());
694 }
695 Ok(result)
696 })),
697 ..DomConversionOutput::node(Some(table_cell_node))
698 }))
699 }
700}