1use super::generated_json::{export_compact_table_node, export_table_node, update_table_node};
12use super::table_cell_node::is_table_cell_node;
13use super::table_row_node::is_table_row_node;
14use crate::json::{Object, Value};
15use crate::lexical_selection::SelectionRef;
16use crate::lexical_utils::{set_node_key, with_writable};
17use crate::node::{LexicalNode, NodeBase, NodeRef};
18use crate::nodes::element::{self, ElementData};
19use crate::schema::{
20 NodeSchema, NumberValueOptions, array_value, boolean_value, node_schema, number_value,
21 optional, schema_getter, schema_setter, with_accessors,
22};
23use crate::{Editor, LexicalError};
24use std::cell::RefCell;
25use std::rc::{Rc, Weak};
26
27#[derive(Clone, Debug, Default)]
29pub struct TableNode {
30 base: NodeBase,
31 pub(super) element: ElementData,
32 pub(super) row_striping: bool,
34 pub(super) frozen_column_count: f64,
36 pub(super) frozen_row_count: f64,
38 pub(super) col_widths: Option<Vec<f64>>,
40}
41
42fn truthy(x: f64) -> Option<f64> {
44 (x != 0.0 && !x.is_nan()).then_some(x)
45}
46
47impl TableNode {
48 pub fn serialized_frozen_column_count(&self) -> Option<f64> {
50 truthy(self.frozen_column_count)
51 }
52
53 pub fn serialized_frozen_row_count(&self) -> Option<f64> {
55 truthy(self.frozen_row_count)
56 }
57
58 pub fn serialized_row_striping(&self) -> Option<bool> {
60 self.row_striping.then_some(true)
61 }
62
63 pub fn col_widths(&self) -> Option<&[f64]> {
65 self.col_widths.as_deref()
66 }
67}
68
69pub fn create_table_node() -> NodeRef {
71 crate::lexical_utils::replaced(set_node_key(Box::<TableNode>::default()))
72}
73
74pub fn is_table_node(node: &NodeRef) -> bool {
76 node.get_latest().is::<TableNode>()
77}
78
79fn read<R>(node: &NodeRef, f: impl FnOnce(&TableNode) -> R) -> Option<R> {
80 node.get_latest().downcast_ref::<TableNode>().map(f)
81}
82
83fn with_table(node: &NodeRef, f: impl FnOnce(&mut TableNode)) {
84 if is_table_node(node) {
85 with_writable(node.get_key(), |n| {
86 f(n.downcast_mut::<TableNode>().expect("a table"))
87 });
88 }
89}
90
91impl NodeRef {
92 pub fn get_col_widths(&self) -> Option<Vec<f64>> {
94 read(self, |t| t.col_widths.clone()).flatten()
95 }
96
97 pub fn set_col_widths(&self, col_widths: Option<Vec<f64>>) {
99 with_table(self, |t| t.col_widths = col_widths);
100 }
101
102 pub fn get_row_striping(&self) -> bool {
104 read(self, |t| t.row_striping).unwrap_or(false)
105 }
106
107 pub fn set_row_striping(&self, row_striping: bool) {
109 with_table(self, |t| t.row_striping = row_striping);
110 }
111
112 pub fn set_frozen_columns(&self, column_count: f64) {
114 with_table(self, |t| t.frozen_column_count = column_count);
115 }
116
117 pub fn get_frozen_columns(&self) -> f64 {
119 read(self, |t| t.frozen_column_count).unwrap_or(0.0)
120 }
121
122 pub fn set_frozen_rows(&self, row_count: f64) {
124 with_table(self, |t| t.frozen_row_count = row_count);
125 }
126
127 pub fn get_frozen_rows(&self) -> f64 {
129 read(self, |t| t.frozen_row_count).unwrap_or(0.0)
130 }
131
132 pub fn get_column_count(&self) -> usize {
134 let Some(first_row) = self.get_first_child().filter(is_table_row_node) else {
135 return 0;
136 };
137 first_row
138 .get_children()
139 .iter()
140 .filter(|cell| is_table_cell_node(cell))
141 .map(|cell| cell.get_col_span())
142 .sum::<f64>() as usize
143 }
144}
145
146thread_local! {
147 static TABLE_NODE_SCHEMA: NodeSchema = build_table_node_schema().expect("TableNode's schema");
148 static SCROLLABLE_EDITORS: RefCell<Vec<Weak<crate::editor::EditorInner>>> =
150 const { RefCell::new(Vec::new()) };
151 static STICKY_EDITORS: RefCell<Vec<Weak<crate::editor::EditorInner>>> =
154 const { RefCell::new(Vec::new()) };
155}
156
157fn set_in(
158 set: &'static std::thread::LocalKey<RefCell<Vec<Weak<crate::editor::EditorInner>>>>,
159 editor: &Editor,
160 active: bool,
161) {
162 set.with(|s| {
163 let mut s = s.borrow_mut();
164 s.retain(|e| e.strong_count() > 0 && !std::ptr::eq(e.as_ptr(), Rc::as_ptr(&editor.0)));
165 if active {
166 s.push(Rc::downgrade(&editor.0));
167 }
168 });
169}
170
171fn has_in(
172 set: &'static std::thread::LocalKey<RefCell<Vec<Weak<crate::editor::EditorInner>>>>,
173 editor: &Editor,
174) -> bool {
175 set.with(|s| {
176 s.borrow()
177 .iter()
178 .any(|e| std::ptr::eq(e.as_ptr(), Rc::as_ptr(&editor.0)))
179 })
180}
181
182pub fn is_scrollable_tables_active(editor: &Editor) -> bool {
185 has_in(&SCROLLABLE_EDITORS, editor)
186}
187
188pub fn set_scrollable_tables_active(editor: &Editor, active: bool) {
190 set_in(&SCROLLABLE_EDITORS, editor, active);
191}
192
193pub fn is_sticky_scrollbar_active(editor: &Editor) -> bool {
196 has_in(&STICKY_EDITORS, editor)
197}
198
199#[cfg(feature = "extension")]
200pub(super) fn set_sticky_scrollbar_active(editor: &Editor, active: bool) {
201 set_in(&STICKY_EDITORS, editor, active);
202}
203
204pub fn table_node_schema() -> NodeSchema {
208 TABLE_NODE_SCHEMA.with(Clone::clone)
209}
210
211fn build_table_node_schema() -> Result<NodeSchema, LexicalError> {
212 let number = || number_value(0.0, NumberValueOptions::default());
213 node_schema(vec![
214 (
215 "colWidths",
216 with_accessors(
217 optional(array_value(number()?)?, false)?,
218 Some(schema_getter(|n: &TableNode| {
219 n.col_widths.as_ref().map_or(Value::Undefined, |w| {
220 Value::Array(w.iter().map(|x| Value::Number(*x)).collect())
221 })
222 })),
223 Some(schema_setter(|n: &mut TableNode, value| {
224 n.col_widths = value
225 .as_array()
226 .map(|w| w.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect());
227 })),
228 )?,
229 ),
230 (
231 "frozenColumnCount",
232 with_accessors(
233 number()?,
234 Some(schema_getter(|n: &TableNode| {
235 n.serialized_frozen_column_count()
236 .map_or(Value::Undefined, Value::from)
237 })),
238 Some(schema_setter(|n: &mut TableNode, value| {
239 n.frozen_column_count = value.as_f64().unwrap_or(0.0);
240 })),
241 )?,
242 ),
243 (
244 "frozenRowCount",
245 with_accessors(
246 number()?,
247 Some(schema_getter(|n: &TableNode| {
248 n.serialized_frozen_row_count()
249 .map_or(Value::Undefined, Value::from)
250 })),
251 Some(schema_setter(|n: &mut TableNode, value| {
252 n.frozen_row_count = value.as_f64().unwrap_or(0.0);
253 })),
254 )?,
255 ),
256 (
257 "rowStriping",
258 with_accessors(
259 boolean_value(false),
260 Some(schema_getter(|n: &TableNode| {
261 n.serialized_row_striping()
262 .map_or(Value::Undefined, Value::from)
263 })),
264 Some(schema_setter(|n: &mut TableNode, value| {
265 n.row_striping = value.as_bool().unwrap_or(false);
266 })),
267 )?,
268 ),
269 ])
270}
271
272impl LexicalNode for TableNode {
273 fn json_schema_chain(&self) -> Vec<NodeSchema> {
274 vec![table_node_schema(), element::element_node_schema()]
275 }
276
277 fn get_type(&self) -> &'static str {
278 "table"
279 }
280 fn base(&self) -> &NodeBase {
281 &self.base
282 }
283 fn base_mut(&mut self) -> &mut NodeBase {
284 &mut self.base
285 }
286 fn element(&self) -> Option<&ElementData> {
287 Some(&self.element)
288 }
289 fn element_mut(&mut self) -> Option<&mut ElementData> {
290 Some(&mut self.element)
291 }
292
293 fn extract_with_child(
295 &self,
296 _: &NodeRef,
297 _: &NodeRef,
298 _: Option<&SelectionRef>,
299 destination: &str,
300 ) -> Result<bool, LexicalError> {
301 Ok(destination == "html")
302 }
303
304 fn can_be_empty(&self) -> bool {
306 false
307 }
308
309 fn is_shadow_root(&self) -> bool {
311 true
312 }
313
314 fn can_indent(&self) -> bool {
316 false
317 }
318
319 #[cfg(feature = "html")]
321 fn create_dom(
322 &self,
323 this: &NodeRef,
324 config: &crate::EditorConfig,
325 editor: &crate::Editor,
326 ) -> Result<crate::dom::DomNode, LexicalError> {
327 Ok(table_dom::create_dom(self, this, &config.theme, editor))
328 }
329
330 #[cfg(feature = "html")]
332 fn export_dom(
333 &self,
334 this: &NodeRef,
335 editor: &crate::Editor,
336 ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
337 table_dom::export_dom(self, this, editor)
338 }
339
340 #[cfg(feature = "html")]
341 fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
342 use crate::lexical_dom::importer;
343 Some(vec![(
344 "table".to_owned(),
345 importer(1, table_dom::convert_table_element),
346 )])
347 }
348
349 fn generated_export_json(&self, compact: bool) -> Option<Object> {
351 Some(if compact {
352 export_compact_table_node(self)
353 } else {
354 export_table_node(self)
355 })
356 }
357
358 fn generated_update_from_json(&mut self, json: &Object) -> bool {
360 update_table_node(self, json);
361 true
362 }
363}
364
365#[cfg(feature = "html")]
366pub(super) mod table_dom {
367 use super::{TableNode, create_table_node, is_scrollable_tables_active};
368 use crate::LexicalError;
369 use crate::dom::DomNode;
370 use crate::json::{Object, Value, number_to_string};
371 use crate::lexical_dom::{
372 DomConversionOutput, DomExportOutput, add_class_names_to_element, get_document,
373 set_direction_from_dom, theme_string,
374 };
375 use crate::node::NodeRef;
376 use crate::set_dom_style::set_dom_style_from_css;
377 use crate::table::constants::parse_pixel_value;
378 use crate::table::table_row_node::is_table_row_node;
379 use std::collections::{HashMap, HashSet};
380
381 fn remove_class_names(element: &DomNode, class_names: &[&str]) {
382 for names in class_names {
383 let tokens: Vec<&str> = names.split_whitespace().collect();
384 if !tokens.is_empty() {
385 element.class_list().remove(&tokens);
386 }
387 }
388 }
389
390 fn first_child_named(node: &DomNode, name: &str) -> Option<DomNode> {
391 node.children()
392 .into_iter()
393 .find(|c| c.local_name().eq_ignore_ascii_case(name))
394 }
395
396 fn children_named(node: &DomNode, name: &str) -> Vec<DomNode> {
397 node.children()
398 .into_iter()
399 .filter(|c| c.local_name().eq_ignore_ascii_case(name))
400 .collect()
401 }
402
403 fn is_table(node: &DomNode) -> bool {
404 node.is_element() && node.local_name() == "table"
405 }
406
407 fn update_colgroup(dom: &DomNode, col_count: usize, col_widths: Option<&[f64]>) {
409 let col_group = first_child_named(dom, "colgroup");
410 let Some(col_widths) = col_widths else {
411 if let Some(col_group) = col_group {
412 col_group.remove();
413 }
414 return;
415 };
416 let col_group = col_group.unwrap_or_else(|| {
417 let col_group = get_document().create_element("colgroup");
418 dom.insert_before(&col_group, dom.first_child().as_ref());
419 col_group
420 });
421 let cols: Vec<DomNode> = (0..col_count)
422 .map(|i| {
423 let col = get_document().create_element("col");
424 if let Some(width) = col_widths.get(i).copied().and_then(super::truthy) {
425 col.style().set_property(
426 "width",
427 &format!("{}px", number_to_string(width)),
428 "",
429 );
430 }
431 col
432 })
433 .collect();
434 col_group.replace_children(&cols);
435 }
436
437 fn align_table_element(dom: &DomNode, theme: &Object, format_type: &str) {
440 let Some(Value::Object(alignment)) = theme.get("tableAlignment") else {
441 return;
442 };
443 let mut remove = Vec::new();
444 let mut add = Vec::new();
445 for format in ["center", "right"] {
446 let Some(classes) = theme_string(alignment, format) else {
447 continue;
448 };
449 if format == format_type {
450 add.push(classes);
451 } else {
452 remove.push(classes);
453 }
454 }
455 remove_class_names(dom, &remove);
456 add_class_names_to_element(dom, &add);
457 }
458
459 fn update_table_element(table: &TableNode, this: &NodeRef, element: &DomNode, theme: &Object) {
461 let style = table.element.get_style();
462 if !style.is_empty() {
463 set_dom_style_from_css(&element.style(), style, "");
464 }
465 if table.row_striping {
466 if let Some(classes) = theme_string(theme, "tableRowStriping") {
467 add_class_names_to_element(element, &[classes]);
468 }
469 element.set_attribute("data-lexical-row-striping", "true");
470 }
471 let column_count = this.get_column_count();
472 if column_count != 0 || table.col_widths.is_some() {
473 update_colgroup(element, column_count, table.col_widths.as_deref());
474 }
475 align_table_element(element, theme, table.element.get_format_type());
476 }
477
478 pub(crate) fn create_dom(
483 table: &TableNode,
484 this: &NodeRef,
485 theme: &Object,
486 editor: &crate::Editor,
487 ) -> DomNode {
488 let table_element = get_document().create_element("table");
489 let style = table.element.get_style();
490 if !style.is_empty() {
491 set_dom_style_from_css(&table_element.style(), style, "");
492 }
493 if table.col_widths.is_some() {
494 table_element.append_child(&get_document().create_element("colgroup"));
495 }
496 if let Some(classes) = theme_string(theme, "table") {
497 add_class_names_to_element(&table_element, &[classes]);
498 }
499 update_table_element(table, this, &table_element, theme);
500 if !is_scrollable_tables_active(editor) {
501 return table_element;
502 }
503 let has_sticky_scrollbar = super::is_sticky_scrollbar_active(editor);
504 let wrapper = get_document().create_element("div");
505 match theme_string(theme, "tableScrollableWrapper") {
506 Some(classes) => add_class_names_to_element(&wrapper, &[classes]),
507 None => {
508 wrapper.style().set_property("overflow-x", "auto", "");
509 }
510 }
511 if has_sticky_scrollbar {
512 wrapper.style().set_property("scrollbar-width", "none", "");
513 }
514 wrapper.append_child(&table_element);
515 let frozen = |count: f64, key: &str, attribute: &str| {
517 if count > 0.0 {
518 if let Some(classes) = theme_string(theme, key) {
519 add_class_names_to_element(&wrapper, &[classes]);
520 }
521 table_element.set_attribute(attribute, "true");
522 }
523 };
524 if table.frozen_column_count != 0.0 {
525 frozen(
526 table.frozen_column_count,
527 "tableFrozenColumn",
528 "data-lexical-frozen-column",
529 );
530 }
531 if table.frozen_row_count != 0.0 {
532 frozen(
533 table.frozen_row_count,
534 "tableFrozenRow",
535 "data-lexical-frozen-row",
536 );
537 }
538 if !has_sticky_scrollbar {
539 return wrapper;
540 }
541 let scrollbar = get_document().create_element("div");
542 match theme_string(theme, "tableStickyScrollbar") {
543 Some(classes) => add_class_names_to_element(&scrollbar, &[classes]),
544 None => {
545 let style = scrollbar.style();
546 style.set_property("position", "sticky", "");
547 style.set_property("bottom", "0", "");
548 style.set_property("overflow-x", "scroll", "");
549 style.set_property("overflow-y", "hidden", "");
550 }
551 }
552 scrollbar.style().set_property("display", "none", "");
553 scrollbar.set_attribute("aria-hidden", "true");
554 scrollbar.set_attribute("tabindex", "-1");
555 let spacer = get_document().create_element("div");
556 spacer.style().set_property("height", "1px", "");
557 spacer.style().set_property("width", "0px", "");
558 scrollbar.append_child(&spacer);
559 let outer = get_document().create_element("div");
560 outer.set_attribute("data-lexical-sticky-scrollbar", "true");
561 outer.append_child(&wrapper);
562 outer.append_child(&scrollbar);
563 outer
564 }
565
566 fn find_table(element: &DomNode) -> Option<DomNode> {
568 if is_table(element) {
569 return Some(element.clone());
570 }
571 element
572 .descendant_elements()
573 .into_iter()
574 .find(|e| e.local_name() == "table")
575 }
576
577 pub(crate) fn export_dom(
582 table: &TableNode,
583 this: &NodeRef,
584 editor: &crate::Editor,
585 ) -> Result<DomExportOutput, LexicalError> {
586 let super_export = crate::nodes::element::export_dom(table, this, editor)?;
587 let element = super_export.element.clone();
588 let exported_element = match &element {
589 Some(e) if e.is_element() && !is_table(e) => find_table(e),
590 other => other.clone(),
591 };
592 if let (Some(element), Some(exported)) = (&element, &exported_element)
593 && element.is_element()
594 && is_table(exported)
595 && exported != element
596 {
597 if let Some(dir) = element.get_attribute("dir").filter(|d| !d.is_empty()) {
598 exported.set_attribute("dir", &dir);
599 }
600 let padding = element.style().get_property_value("padding-inline-start");
601 if !padding.is_empty() {
602 exported
603 .style()
604 .set_property("padding-inline-start", &padding, "");
605 }
606 if let Some(indent) = element.get_attribute("data-lexical-indent") {
607 exported.set_attribute("data-lexical-indent", &indent);
608 }
609 }
610 let super_after = super_export.after;
611 let this = this.clone();
612 let theme = editor.config().theme.clone();
613 let format_type = table.element.get_format_type();
614 Ok(DomExportOutput {
615 element: exported_element,
616 after: Some(Box::new(move |table_element: &DomNode| {
617 let mut table_element = table_element.clone();
618 if let Some(after) = super_after {
619 match after(&table_element)? {
620 Some(e) => table_element = e,
621 None => return Ok(None),
622 }
623 }
624 let Some(table_element) = find_table(&table_element) else {
625 return Ok(None);
626 };
627 align_table_element(&table_element, &theme, format_type);
628
629 let (table_map, _, _) =
631 crate::table::table_utils::compute_table_map_skip_cell_check(
632 &this, None, None,
633 )?;
634 let mut cell_values: HashMap<String, (usize, usize)> = HashMap::new();
635 for map_row in &table_map {
636 for value in map_row.iter().flatten() {
637 let key = value.cell.get_key().to_owned();
638 cell_values
639 .entry(key)
640 .or_insert((value.cell.get_col_span() as usize, value.start_column));
641 }
642 }
643 let mut known_columns: HashSet<usize> = HashSet::new();
645 for row in children_named(&table_element, "tr") {
646 for cell_dom in row.children() {
647 let Some(key) =
648 cell_dom.get_attribute("data-temporary-table-cell-lexical-key")
649 else {
650 continue;
651 };
652 cell_dom.remove_attribute("data-temporary-table-cell-lexical-key");
653 if let Some((col_span, start_column)) = cell_values.remove(&key) {
654 for i in 0..col_span {
655 known_columns.insert(i + start_column);
656 }
657 }
658 }
659 }
660 if let Some(col_group) = first_child_named(&table_element, "colgroup") {
661 let cols: Vec<DomNode> = children_named(&col_group, "col")
662 .into_iter()
663 .enumerate()
664 .filter(|(i, _)| known_columns.contains(i))
665 .map(|(_, col)| col)
666 .collect();
667 col_group.replace_children(&cols);
668 }
669 let rows = children_named(&table_element, "tr");
670 if !rows.is_empty() {
671 let t_body = get_document().create_element("tbody");
672 for row in rows {
673 t_body.append_child(&row);
674 }
675 table_element.append_child(&t_body);
676 }
677 Ok(Some(table_element))
678 })),
679 append: super_export.append,
680 get_child_nodes: super_export.get_child_nodes,
681 })
682 }
683
684 fn is_digits(value: &str) -> bool {
686 !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit())
687 }
688
689 pub(crate) fn convert_table_element(
694 dom_node: &DomNode,
695 ) -> Result<Option<DomConversionOutput>, LexicalError> {
696 let table_node = create_table_node();
697 if dom_node.has_attribute("data-lexical-row-striping") {
698 table_node.set_row_striping(true);
699 }
700 if dom_node.has_attribute("data-lexical-frozen-column") {
701 table_node.set_frozen_columns(1.0);
702 }
703 if dom_node.has_attribute("data-lexical-frozen-row") {
704 table_node.set_frozen_rows(1.0);
705 }
706 if let Some(col_group) = first_child_named(dom_node, "colgroup") {
707 let mut columns = Some(Vec::new());
708 for col in children_named(&col_group, "col") {
709 let width = col.style().get_property_value("width");
710 let width = match parse_pixel_value(&width) {
711 Some(width) => width,
712 None => match col.get_attribute("width").filter(|w| is_digits(w)) {
713 Some(width) => width.parse().unwrap_or(0.0),
714 None => {
715 columns = None;
716 break;
717 }
718 },
719 };
720 if let Some(columns) = columns.as_mut() {
721 columns.push(width);
722 }
723 }
724 if let Some(columns) = columns {
725 table_node.set_col_widths(Some(columns));
726 }
727 }
728 set_direction_from_dom(&table_node, dom_node);
729 Ok(Some(DomConversionOutput {
730 after: Some(Box::new(|children: Vec<NodeRef>| {
731 Ok(crate::utils::descendants_matching(
732 &children,
733 is_table_row_node,
734 ))
735 })),
736 ..DomConversionOutput::node(Some(table_node))
737 }))
738 }
739}