]> BookStack Code Mirror - bookstack/blobdiff - resources/js/wysiwyg/lexical/table/LexicalTableNode.ts
Lexical: Further improvements to table selection and captions
[bookstack] / resources / js / wysiwyg / lexical / table / LexicalTableNode.ts
index 105764be2f0a3b6b30e76495ca006492ca1b8771..460223bc9ce9dc54d4b56d7c64b8e916ad94e24a 100644 (file)
@@ -30,12 +30,13 @@ import {TableDOMCell, TableDOMTable} from './LexicalTableObserver';
 import {getTable} from './LexicalTableSelectionHelpers';
 import {CommonBlockNode, copyCommonBlockProperties, SerializedCommonBlockNode} from "lexical/nodes/CommonBlockNode";
 import {
+  applyCommonPropertyChanges,
   commonPropertiesDifferent, deserializeCommonBlockNode,
   setCommonBlockPropsFromElement,
   updateElementWithCommonBlockProps
 } from "lexical/nodes/common";
 import {el, extractStyleMapFromElement, StyleMap} from "../../utils/dom";
-import {getTableColumnWidths} from "../../utils/tables";
+import {buildColgroupFromTableWidths, getTableColumnWidths} from "../../utils/tables";
 
 export type SerializedTableNode = Spread<{
   colWidths: string[];
@@ -98,15 +99,8 @@ export class TableNode extends CommonBlockNode {
     updateElementWithCommonBlockProps(tableElement, this);
 
     const colWidths = this.getColWidths();
-    if (colWidths.length > 0) {
-      const colgroup = el('colgroup');
-      for (const width of colWidths) {
-        const col = el('col');
-        if (width) {
-          col.style.width = width;
-        }
-        colgroup.append(col);
-      }
+    const colgroup = buildColgroupFromTableWidths(colWidths);
+    if (colgroup) {
       tableElement.append(colgroup);
     }
 
@@ -117,11 +111,29 @@ export class TableNode extends CommonBlockNode {
     return tableElement;
   }
 
-  updateDOM(_prevNode: TableNode): boolean {
-    return commonPropertiesDifferent(_prevNode, this)
-      || this.__colWidths.join(':') !== _prevNode.__colWidths.join(':')
-      || this.__styles.size !== _prevNode.__styles.size
-      || (Array.from(this.__styles.values()).join(':') !== (Array.from(_prevNode.__styles.values()).join(':')));
+  updateDOM(_prevNode: TableNode, dom: HTMLElement): boolean {
+    applyCommonPropertyChanges(_prevNode, this, dom);
+
+    if (this.__colWidths.join(':') !== _prevNode.__colWidths.join(':')) {
+      const existingColGroup = Array.from(dom.children).find(child => child.nodeName === 'COLGROUP');
+      const newColGroup = buildColgroupFromTableWidths(this.__colWidths);
+      if (existingColGroup) {
+        existingColGroup.remove();
+      }
+
+      if (newColGroup) {
+        dom.prepend(newColGroup);
+      }
+    }
+
+    if (Array.from(this.__styles.values()).join(':') !== Array.from(_prevNode.__styles.values()).join(':')) {
+      dom.style.cssText = '';
+      for (const [name, value] of this.__styles.entries()) {
+        dom.style.setProperty(name, value);
+      }
+    }
+
+    return false;
   }
 
   exportDOM(editor: LexicalEditor): DOMExportOutput {