1 import {SerializedTableNode, TableNode} from "@lexical/table";
2 import {DOMConversion, DOMConversionMap, DOMConversionOutput, LexicalNode, Spread} from "lexical";
3 import {EditorConfig} from "lexical/LexicalEditor";
5 import {el, extractStyleMapFromElement, StyleMap} from "../utils/dom";
6 import {getTableColumnWidths} from "../utils/tables";
8 export type SerializedCustomTableNode = Spread<{
11 styles: Record<string, string>,
12 }, SerializedTableNode>
14 export class CustomTableNode extends TableNode {
16 __colWidths: string[] = [];
17 __styles: StyleMap = new Map;
20 return 'custom-table';
24 const self = this.getWritable();
29 const self = this.getLatest();
33 setColWidths(widths: string[]) {
34 const self = this.getWritable();
35 self.__colWidths = widths;
38 getColWidths(): string[] {
39 const self = this.getLatest();
40 return self.__colWidths;
43 getStyles(): StyleMap {
44 const self = this.getLatest();
45 return new Map(self.__styles);
48 setStyles(styles: StyleMap): void {
49 const self = this.getWritable();
50 self.__styles = new Map(styles);
53 static clone(node: CustomTableNode) {
54 const newNode = new CustomTableNode(node.__key);
55 newNode.__id = node.__id;
56 newNode.__colWidths = node.__colWidths;
57 newNode.__styles = new Map(node.__styles);
61 createDOM(config: EditorConfig): HTMLElement {
62 const dom = super.createDOM(config);
63 const id = this.getId();
65 dom.setAttribute('id', id);
68 const colWidths = this.getColWidths();
69 if (colWidths.length > 0) {
70 const colgroup = el('colgroup');
71 for (const width of colWidths) {
72 const col = el('col');
74 col.style.width = width;
81 for (const [name, value] of this.__styles.entries()) {
82 dom.style.setProperty(name, value);
88 updateDOM(): boolean {
92 exportJSON(): SerializedCustomTableNode {
94 ...super.exportJSON(),
98 colWidths: this.__colWidths,
99 styles: Object.fromEntries(this.__styles),
103 static importJSON(serializedNode: SerializedCustomTableNode): CustomTableNode {
104 const node = $createCustomTableNode();
105 node.setId(serializedNode.id);
106 node.setColWidths(serializedNode.colWidths);
107 node.setStyles(new Map(Object.entries(serializedNode.styles)));
111 static importDOM(): DOMConversionMap|null {
113 table(node: HTMLElement): DOMConversion|null {
115 conversion: (element: HTMLElement): DOMConversionOutput|null => {
116 const node = $createCustomTableNode();
119 node.setId(element.id);
122 const colWidths = getTableColumnWidths(element as HTMLTableElement);
123 node.setColWidths(colWidths);
124 node.setStyles(extractStyleMapFromElement(element));
135 export function $createCustomTableNode(): CustomTableNode {
136 return new CustomTableNode();
139 export function $isCustomTableNode(node: LexicalNode | null | undefined): node is CustomTableNode {
140 return node instanceof CustomTableNode;